feat: 节点坐标、分区、对齐结果自动保存;分组关系和连线继续保存在数据库;项目管理者维护布局,其他成员通过静默同步看到更新;框选、缩放、平移和折叠仍是个人状态;已加入并发冲突保护、保存失败重试和离页草稿恢复

This commit is contained in:
zhanghao 2026-11-03 10:47:10 +08:00
parent 23352ada54
commit 33828713aa
25 changed files with 972 additions and 84 deletions

View File

@ -151,6 +151,23 @@ CREATE TABLE `pm_collab_iteration` (
CONSTRAINT `ck_pm_collab_iteration_status` CHECK ((`status` in (_utf8mb4'PLANNED',_utf8mb4'ACTIVE',_utf8mb4'FINISHED',_utf8mb4'CANCELLED')))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='项目协作:项目迭代';
-- 项目协作:迭代共享流程布局
-- 独立布局版本只解决画布并发覆盖,不推进业务执行图版本;复合外键隔离项目和迭代。
CREATE TABLE `pm_collab_flow_layout` (
`project_id` bigint NOT NULL COMMENT '协作扩展ID(非原项目ID),与迭代共同唯一确定共享布局',
`iteration_id` bigint NOT NULL COMMENT '所属迭代ID,复合外键保证与协作项目一致',
`layout_json` longtext NOT NULL COMMENT '共享流程布局JSON对象,仅包含节点位置和分区,不保存业务连线或状态',
`version` int NOT NULL DEFAULT '1' COMMENT '独立布局乐观锁版本,首次保存为1,每次成功保存递增',
`updated_by` bigint NOT NULL COMMENT '最后保存共享布局的系统用户ID',
`updated_at` bigint NOT NULL COMMENT '最后保存时间(UTC时间戳,微秒)',
PRIMARY KEY (`project_id`,`iteration_id`),
KEY `idx_pm_flow_layout_actor` (`updated_by`),
CONSTRAINT `fk_pm_flow_layout_iteration` FOREIGN KEY (`project_id`,`iteration_id`) REFERENCES `pm_collab_iteration` (`project_id`,`id`),
CONSTRAINT `fk_pm_flow_layout_actor` FOREIGN KEY (`updated_by`) REFERENCES `sys_user` (`user_id`),
CONSTRAINT `ck_pm_flow_layout_json` CHECK (JSON_VALID(`layout_json`) AND JSON_TYPE(CAST(`layout_json` AS JSON))='OBJECT'),
CONSTRAINT `ck_pm_flow_layout_version` CHECK (`version`>0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='项目协作:迭代共享流程布局';
-- 项目协作:迭代操作幂等记录
CREATE TABLE `pm_collab_iteration_request` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',

View File

@ -0,0 +1,21 @@
-- target-database: cmvr-project-dev
-- 项目协作:迭代共享流程布局。024 后执行,可重复执行;仅新增布局表,不改动既有表或业务数据。
-- 前置:现有迭代表具有 (project_id,id) 唯一键;连接到已确认的开发目标库后执行。
SET NAMES utf8mb4;
-- 独立布局版本只解决画布并发覆盖,不推进业务执行图版本;复合外键隔离项目和迭代。
CREATE TABLE IF NOT EXISTS `pm_collab_flow_layout` (
`project_id` bigint NOT NULL COMMENT '协作扩展ID(非原项目ID),与迭代共同唯一确定共享布局',
`iteration_id` bigint NOT NULL COMMENT '所属迭代ID,复合外键保证与协作项目一致',
`layout_json` longtext NOT NULL COMMENT '共享流程布局JSON对象,仅包含节点位置和分区,不保存业务连线或状态',
`version` int NOT NULL DEFAULT '1' COMMENT '独立布局乐观锁版本,首次保存为1,每次成功保存递增',
`updated_by` bigint NOT NULL COMMENT '最后保存共享布局的系统用户ID',
`updated_at` bigint NOT NULL COMMENT '最后保存时间(UTC时间戳,微秒)',
PRIMARY KEY (`project_id`,`iteration_id`),
KEY `idx_pm_flow_layout_actor` (`updated_by`),
CONSTRAINT `fk_pm_flow_layout_iteration` FOREIGN KEY (`project_id`,`iteration_id`) REFERENCES `pm_collab_iteration` (`project_id`,`id`),
CONSTRAINT `fk_pm_flow_layout_actor` FOREIGN KEY (`updated_by`) REFERENCES `sys_user` (`user_id`),
CONSTRAINT `ck_pm_flow_layout_json` CHECK (JSON_VALID(`layout_json`) AND JSON_TYPE(CAST(`layout_json` AS JSON))='OBJECT'),
CONSTRAINT `ck_pm_flow_layout_version` CHECK (`version`>0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='项目协作:迭代共享流程布局';

View File

@ -0,0 +1,89 @@
package com.ruoyi.project.manage.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.project.manage.dto.FlowLayoutInput;
import com.ruoyi.project.manage.exception.PmException;
import com.ruoyi.project.manage.service.IPmFlowLayoutService;
import java.util.Map;
import org.springframework.web.bind.annotation.*;
import static com.ruoyi.project.manage.util.PmValues.map;
/** 共享布局 REST 白名单入口,不接收节点状态、执行连线或客户端权限字段。 */
@RestController
@RequestMapping("/project/manage/projects/{projectId}/iterations/{iterationId}/flow-layout")
public class PmFlowLayoutController {
private final IPmFlowLayoutService service;
private final ObjectMapper strict;
/**
* 使用独立严格解码器保留全局 JSON 配置,并拒绝嵌套未知字段及整数截断。
* @param service 执行项目权限、版本及结构校验的布局服务
* @param json 应用 JSON 配置;不修改其全局宽松策略
*/
public PmFlowLayoutController(IPmFlowLayoutService service, ObjectMapper json) {
this.service = service;
this.strict = json.copy().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT);
this.strict.setConfig(this.strict.getDeserializationConfig().without(MapperFeature.ALLOW_COERCION_OF_SCALARS));
}
/**
* 成员读取共享布局;未初始化仍返回版本 0,不产生写入。
* @param projectId 协作项目 ID
* @param iterationId 显式迭代 ID
* @return 模块统一响应中的布局快照
*/
@GetMapping
public Map<String, Object> get(@PathVariable long projectId, @PathVariable long iterationId) {
return ok(service.get(projectId, iterationId));
}
/**
* 完整替换共享展示布局,版本冲突由服务明确拒绝。
* @param projectId 协作项目 ID
* @param iterationId 目标迭代 ID
* @param body 仅允许版本、位置和分区,嵌套对象同样执行白名单校验
* @return 实际保存的新版本布局;校验失败不会返回假成功
*/
@PutMapping
public Map<String, Object> save(@PathVariable long projectId, @PathVariable long iterationId,
@RequestBody JsonNode body) {
return ok(service.save(projectId, iterationId, decode(body)));
}
/**
* 严格解析布局契约,防止普通展示请求夹带业务或权限数据。
* @param body JSON 对象;根字段和位置父级必须显式提供
* @return 通过递归字段白名单的输入;缺失字段和错误类型统一返回 400
* 注意:Jackson 的标量转换开关仍允许数字转字符串,因此分区身份和名称显式检查原始 JSON 类型。
*/
private FlowLayoutInput decode(JsonNode body) {
try {
if (body == null || !body.isObject() || !body.has("version") || !body.has("positions")
|| !body.has("sections")) throw PmException.bad("共享布局字段不完整");
JsonNode positions = body.get("positions");
if (!positions.isObject()) throw PmException.bad("节点位置必须为对象");
for (JsonNode point : positions) {
if (!point.isObject() || !point.has("parentStageId"))
throw PmException.bad("节点位置必须明确父级");
}
JsonNode sections = body.get("sections");
if (!sections.isArray()) throw PmException.bad("分区必须为数组");
for (JsonNode section : sections) {
if (!section.isObject() || !section.path("id").isTextual() || !section.path("name").isTextual())
throw PmException.bad("分区身份和名称必须为字符串");
}
return strict.treeToValue(body, FlowLayoutInput.class);
} catch (Exception invalid) {
throw PmException.bad("共享布局字段或格式无效");
}
}
/** 将布局结果放入现有模块响应包,保留真实布局版本和服务端能力。 */
private static Map<String, Object> ok(Object value) {
return map("code", 200, "msg", "操作成功", "data", value);
}
}

View File

@ -0,0 +1,13 @@
package com.ruoyi.project.manage.dto;
import java.util.List;
import java.util.Map;
/** 共享画布仅接收坐标、分区及独立布局版本,业务节点和权限事实由服务端读取。 */
public record FlowLayoutInput(Integer version, Map<String, Point> positions, List<Section> sections) {
/** 坐标绑定真实父级,避免结构调整后将局部坐标误当作根画布坐标。 */
public record Point(Double x, Double y, Long parentStageId) { }
/** 分区只作为展示矩形存在,不参与业务父子关系、执行连线或阶段规则。 */
public record Section(String id, String name, Double x, Double y, Double width, Double height) { }
}

View File

@ -0,0 +1,43 @@
package com.ruoyi.project.manage.mapper;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/** 布局持久化仅写独立布局表;项目锁、权限和结构校验由服务在同一事务内完成。 */
@Mapper
public interface PmFlowLayoutMapper {
/**
* 读取唯一迭代布局;不隐式创建行,便于版本 0 表达从未保存的默认布局。
* @param projectId 已鉴权的协作项目 ID
* @param iterationId 当前迭代 ID
* @return 数据库行;未保存时为 null
*/
Map<String, Object> selectLayout(@Param("projectId") long projectId, @Param("iterationId") long iterationId);
/**
* 首次保存固定从版本 1 开始,不允许通过重复键更新覆盖已存在的布局。
* @param projectId 已锁定项目
* @param iterationId 已验证的可编辑迭代
* @param layoutJson 仅含受控位置和分区的 JSON
* @param actor 当前认证用户 ID
* @param updatedAt 服务端 UTC 微秒时间
* @return 插入行数;唯一键冲突由服务转换为布局版本冲突
*/
int insertLayout(@Param("projectId") long projectId, @Param("iterationId") long iterationId,
@Param("layoutJson") String layoutJson, @Param("actor") long actor, @Param("updatedAt") long updatedAt);
/**
* 以旧版本为条件更新并递增版本,数据库条件为服务层比较提供最后一道并发保护。
* @param projectId 已锁定项目
* @param iterationId 当前迭代
* @param version 客户端读取的旧布局版本
* @param layoutJson 通过白名单校验的布局 JSON
* @param actor 当前认证用户 ID
* @param updatedAt 服务端 UTC 微秒时间
* @return 更新行数;0 表示不能覆盖当前布局
*/
int updateLayout(@Param("projectId") long projectId, @Param("iterationId") long iterationId,
@Param("version") int version, @Param("layoutJson") String layoutJson,
@Param("actor") long actor, @Param("updatedAt") long updatedAt);
}

View File

@ -0,0 +1,24 @@
package com.ruoyi.project.manage.service;
import com.ruoyi.project.manage.dto.FlowLayoutInput;
import java.util.Map;
/** 共享布局与业务图分别维护版本;所有入口均执行项目成员及迭代边界校验。 */
public interface IPmFlowLayoutService {
/**
* 读取迭代共享布局并过滤删除或已变更父级的旧位置,不初始化数据库行。
* @param projectId 协作项目 ID,不能使用原项目 ID
* @param iterationId 显式迭代 ID
* @return 布局版本、位置、分区、服务端更新信息和当前编辑能力
*/
Map<String, Object> get(long projectId, long iterationId);
/**
* 在项目锁内复验管理资格、生命周期、结构及布局版本后保存完整布局。
* @param projectId 协作项目 ID
* @param iterationId 布局所属的可编辑迭代
* @param input 客户端基于已读取版本编辑的展示数据,不接受业务状态
* @return 实际保存的布局;版本或结构过期时抛出独立的 409 冲突,不覆盖其他管理者的修改
*/
Map<String, Object> save(long projectId, long iterationId, FlowLayoutInput input);
}

View File

@ -18,7 +18,7 @@ public interface IPmStageService {
*
* @param projectId 当前协作内部项目 ID(非原项目 ID);服务内重新检查成员权限
* @param iterationId 明确的迭代边界,不能混合项目内多个执行图
* @return 阶段和执行连线摘要;浏览器展示偏好不进入响应
* @return 阶段、执行连线及独立版本的共享布局摘要;个人视口、折叠等偏好由浏览器维护
*/
Map<String,Object> flowView(long projectId,long iterationId);
/** 旧项目级画布入口拒绝隐式选择迭代,避免混合多个执行图。 */

View File

@ -0,0 +1,263 @@
package com.ruoyi.project.manage.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.project.manage.dto.FlowLayoutInput;
import com.ruoyi.project.manage.dto.FlowLayoutInput.Point;
import com.ruoyi.project.manage.dto.FlowLayoutInput.Section;
import com.ruoyi.project.manage.exception.PmException;
import com.ruoyi.project.manage.mapper.PmFlowLayoutMapper;
import com.ruoyi.project.manage.mapper.PmStageMapper;
import com.ruoyi.project.manage.mapper.PmWorkspaceMapper;
import com.ruoyi.project.manage.security.PmAccess;
import com.ruoyi.project.manage.security.PmIterationAccess;
import com.ruoyi.project.manage.service.IPmFlowLayoutService;
import com.ruoyi.project.manage.util.PmTime;
import java.util.*;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import static com.ruoyi.project.manage.util.PmValues.*;
/** 共享布局使用项目锁维护一致性,但不参与业务图版本、历史或 outbox。 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class PmFlowLayoutServiceImpl implements IPmFlowLayoutService {
private final PmFlowLayoutMapper mapper;
private final PmStageMapper stages;
private final PmWorkspaceMapper workspace;
private final PmAccess access;
private final PmIterationAccess iterations;
private final ObjectMapper json;
/** 数据库 JSON 仅含展示位置和分区,版本及更新身份保存在独立受控列。 */
private record StoredLayout(Map<String, Point> positions, List<Section> sections) { }
/**
* 注入独立布局存储和既有项目门禁,不依赖图服务以避免推进业务版本或循环依赖。
* @param mapper 布局唯一行及条件更新存储
* @param stages 当前迭代真实阶段和父级查询
* @param workspace 项目及原项目共用的稳定锁入口
* @param access 实时成员与管理资格校验
* @param iterations 迭代归属、状态及归档门禁
* @param json 应用 JSON 编解码器
*/
public PmFlowLayoutServiceImpl(PmFlowLayoutMapper mapper, PmStageMapper stages, PmWorkspaceMapper workspace,
PmAccess access, PmIterationAccess iterations, ObjectMapper json) {
this.mapper = mapper;
this.stages = stages;
this.workspace = workspace;
this.access = access;
this.iterations = iterations;
this.json = json;
}
/**
* 在项目锁内读取布局及真实父级,使返回位置与同一结构快照匹配。
* @param projectId 成员可访问的协作项目 ID
* @param iterationId 归属该项目的有效迭代,允许终态及归档只读
* @return 无行时的版本 0 或已保存快照;读取不会创建行或推进任何版本
*/
@Override
public Map<String, Object> get(long projectId, long iterationId) {
Map<String, Object> iteration = locked(projectId, iterationId, "read");
return snapshot(mapper.selectLayout(projectId, iterationId), parents(projectId, iterationId),
canEdit(projectId, iteration));
}
/**
* 串行保存共享布局,项目锁覆盖撤权、生命周期、父级和独立版本的完整复验。
* @param projectId 当前协作项目 ID
* @param iterationId 当前可编辑迭代 ID
* @param input 完整展示布局和读取时的布局版本
* @return 已提交内容的新版本快照;冲突或校验失败时事务不写入任何业务事实
*/
@Override
public Map<String, Object> save(long projectId, long iterationId, FlowLayoutInput input) {
locked(projectId, iterationId, "admin");
StoredLayout layout = validate(input);
Map<String, Object> previous = mapper.selectLayout(projectId, iterationId);
int version = previous == null ? 0 : Math.toIntExact(number(previous, "version"));
if (input.version() != version) throw versionConflict();
Map<Long, Long> currentParents = parents(projectId, iterationId);
for (Map.Entry<String, Point> entry : layout.positions().entrySet()) {
if (!matches(entry.getKey(), entry.getValue(), currentParents))
throw PmException.conflict("FLOW_LAYOUT_STRUCTURE_CHANGED", "阶段结构已变化,请重新加载共享布局");
}
String encoded = encode(layout);
long actor = access.actor(), now = PmTime.now();
// 同一项目的角色、生命周期和结构写入均使用此锁;锁覆盖比较与写入,防止两个版本 0 同时初始化。
// SQL 仍以唯一键和旧版本作最后保护,不允许重复提交过期请求时盲目覆盖已保存布局。
try {
int changed = version == 0
? mapper.insertLayout(projectId, iterationId, encoded, actor, now)
: mapper.updateLayout(projectId, iterationId, version, encoded, actor, now);
if (changed != 1) throw versionConflict();
} catch (DuplicateKeyException conflict) {
throw versionConflict();
}
return snapshot(map("layout_json", encoded, "version", version + 1, "updated_by", actor, "updated_at", now),
currentParents, true);
}
/**
* 按既有源项目→项目图锁顺序读取最新成员及迭代状态,防止等待锁期间撤权后继续写入。
* @param projectId 协作项目边界
* @param iterationId 明确迭代边界
* @param action read 或 admin;管理写入必须同时满足迭代可变状态
* @return 持锁后读取的有效迭代;锁由外层事务提交或回滚时释放
*/
private Map<String, Object> locked(long projectId, long iterationId, String action) {
access.project(projectId, action);
workspace.lockProject(projectId);
access.project(projectId, action);
return iterations.require(projectId, iterationId, action);
}
/**
* 返回与写入相同的管理者及生命周期能力,不把全局管理员当作项目成员。
* @param projectId 已持锁且已通过成员鉴权的项目
* @param iteration 当前迭代数据库行
* @return 有效未归档 PLANNED/ACTIVE 迭代的项目管理者为 true;明确 403 转换为 false
*/
private boolean canEdit(long projectId, Map<String, Object> iteration) {
if (nullable(iteration, "archived_at") != null
|| !Set.of("PLANNED", "ACTIVE").contains(text(iteration, "status"))) return false;
try {
access.project(projectId, "admin");
return true;
} catch (PmException denied) {
if (denied.getHttpStatus() != 403) throw denied;
return false;
}
}
/**
* 一次查询建立当前迭代父级索引,避免每个位置分别查询造成 N+1 数据库访问。
* @param projectId 已鉴权且已持锁的协作项目
* @param iterationId 当前迭代;Mapper 同时限制未软删除阶段
* @return 真实阶段 ID 到可空真实父级 ID 的映射,不包含其他项目或迭代信息
*/
private Map<Long, Long> parents(long projectId, long iterationId) {
Map<Long, Long> result = new HashMap<>();
for (Map<String, Object> stage : stages.selectVisibleStages(projectId, iterationId))
result.put(number(stage, "id"), nullable(stage, "parentStageId"));
return result;
}
/**
* 校验完整布局的纯展示字段并规范分区名称,任何失败都在写入前拒绝。
* @param input 包含显式旧版本、位置和分区的请求
* @return 独立复制且只含白名单字段的布局;不接受无穷坐标、非法身份、超量或重复分区
*/
private static StoredLayout validate(FlowLayoutInput input) {
if (input == null || input.version() == null || input.version() < 0 || input.version() == Integer.MAX_VALUE
|| input.positions() == null || input.positions().size() > 5001
|| input.sections() == null || input.sections().size() > 200)
throw PmException.bad("共享布局版本、位置或分区数量无效");
Map<String, Point> positions = new LinkedHashMap<>();
for (Map.Entry<String, Point> entry : input.positions().entrySet()) {
Point point = entry.getValue();
stageId(entry.getKey());
if (point == null || !coordinate(point.x()) || !coordinate(point.y())
|| point.parentStageId() != null && point.parentStageId() <= 0)
throw PmException.bad("节点坐标或父级格式无效");
positions.put(entry.getKey(), point);
}
Set<String> ids = new HashSet<>();
List<Section> sections = new ArrayList<>();
for (Section section : input.sections()) {
if (section == null || section.id() == null || !section.id().matches("section:[A-Za-z0-9_-]{1,100}")
|| !ids.add(section.id()) || section.name() == null || section.name().strip().isBlank()
|| section.name().strip().length() > 100 || !coordinate(section.x()) || !coordinate(section.y())
|| !bounded(section.width(), 180, 20000) || !bounded(section.height(), 120, 20000))
throw PmException.bad("分区身份、名称、坐标或尺寸无效");
sections.add(new Section(section.id(), section.name().strip(), section.x(), section.y(),
section.width(), section.height()));
}
return new StoredLayout(positions, sections);
}
/**
* 位置键只允许规范十进制阶段 ID,避免相同 ID 的不同文本形式或数值溢出。
* @param key s:0 虚拟未分配节点或 s:正整数阶段标识
* @return 无损转换后的 ID;非法键统一 400,不查询外部项目对象
*/
private static long stageId(String key) {
if (key == null || !key.matches("s:(0|[1-9][0-9]*)")) throw PmException.bad("节点位置标识无效");
try {
return Long.parseLong(key.substring(2));
} catch (NumberFormatException overflow) {
throw PmException.bad("节点位置标识无效");
}
}
/** 判断展示坐标是否为有限范围数值,阻止异常值污染后续画布布局计算。 */
private static boolean coordinate(Double value) {
return bounded(value, -10_000_000, 10_000_000);
}
/** 检查有限数值及闭区间边界,尺寸与坐标共用相同的非有限值保护。 */
private static boolean bounded(Double value, double min, double max) {
return value != null && Double.isFinite(value) && value >= min && value <= max;
}
/**
* 比较位置声明的父级与数据库真实父级,虚拟未分配节点只能属于根画布。
* @param key 已验证格式的位置键
* @param point 保存时明确绑定的父级及坐标
* @param currentParents 当前迭代有效阶段索引
* @return 节点仍有效且父级完全一致为 true;不从请求推断业务层级
*/
private static boolean matches(String key, Point point, Map<Long, Long> currentParents) {
long id = stageId(key);
return id == 0 ? point.parentStageId() == null
: currentParents.containsKey(id) && Objects.equals(currentParents.get(id), point.parentStageId());
}
/**
* 构造成员可见布局,过滤已删除和已重挂父级的旧位置而不修改数据库历史布局。
* @param row 唯一布局数据库行,null 表示从未保存
* @param currentParents 当前持锁读取的真实父级
* @param canEdit 当前管理者和迭代状态共同决定的能力
* @return 布局、独立版本及北京时间更新信息;只含展示白名单字段
*/
private Map<String, Object> snapshot(Map<String, Object> row, Map<Long, Long> currentParents, boolean canEdit) {
StoredLayout layout = row == null ? new StoredLayout(Map.of(), List.of()) : decode(text(row, "layout_json"));
Map<String, Point> positions = new LinkedHashMap<>();
for (Map.Entry<String, Point> entry : layout.positions().entrySet()) {
if (matches(entry.getKey(), entry.getValue(), currentParents)) positions.put(entry.getKey(), entry.getValue());
}
return map("version", row == null ? 0 : Math.toIntExact(number(row, "version")),
"positions", positions, "sections", layout.sections(),
"updatedBy", row == null ? null : nullable(row, "updated_by"),
"updatedAt", row == null ? null : PmTime.format(nullable(row, "updated_at"), "Asia/Shanghai"),
"canEdit", canEdit);
}
/** 将受控布局编码为数据库 JSON,失败时回滚事务而不保存不完整展示数据。 */
private String encode(StoredLayout layout) {
try {
return json.writeValueAsString(layout);
} catch (Exception invalid) {
throw new IllegalStateException("无法保存共享布局", invalid);
}
}
/** 还原本服务写入的布局 JSON;损坏数据明确失败,不能伪装为空布局供客户端覆盖。 */
private StoredLayout decode(String value) {
try {
StoredLayout layout = json.readValue(value, StoredLayout.class);
if (layout == null || layout.positions() == null || layout.sections() == null)
throw new IllegalStateException("共享布局数据不完整");
return layout;
} catch (Exception invalid) {
throw new IllegalStateException("无法读取共享布局", invalid);
}
}
/** 统一独立布局冲突码;客户端必须重新读取,不能以旧请求自动覆盖当前版本。 */
private static PmException versionConflict() {
return PmException.conflict("FLOW_LAYOUT_VERSION_CONFLICT", "共享布局已被更新,请重新加载后再编辑");
}
}

View File

@ -19,6 +19,7 @@ import com.ruoyi.project.manage.rule.PmRules;
import com.ruoyi.project.manage.rule.PmStageRules;
import com.ruoyi.project.manage.service.IPmService;
import com.ruoyi.project.manage.service.IPmStageService;
import com.ruoyi.project.manage.service.IPmFlowLayoutService;
import com.ruoyi.project.manage.service.support.PmAuditService;
import com.ruoyi.project.manage.service.support.PmGraphService;
import com.ruoyi.project.manage.util.PmJson;
@ -30,7 +31,7 @@ import java.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
/** 阶段和显式执行边共享项目图锁;画布位置仍只是浏览器偏好。 */
/** 阶段和显式执行边共享项目图锁;共享画布布局由独立服务和版本维护。 */
@Service
@Transactional(isolation=Isolation.READ_COMMITTED,rollbackFor=Exception.class)
public class PmStageServiceImpl implements IPmStageService {
@ -47,9 +48,11 @@ public class PmStageServiceImpl implements IPmStageService {
private final IPmService business;
private final com.ruoyi.project.manage.service.support.PmGroupVersionService groups;
private final com.ruoyi.project.manage.service.IPmStageCompletionService completion;
private final IPmFlowLayoutService layouts;
/** 注入当前阶段业务需要的 Mapper 和规则,浏览器布局不再依赖数据库 Mapper。 */
public PmStageServiceImpl(PmWorkspaceMapper workspaceMapper,PmWorkItemMapper workItemMapper,PmStageMapper stageMapper,PmRevisionMapper revisionMapper,PmGraphService graphService,PmAuditService auditService,PmJson jsonCodec,PmAccess access,IPmService business,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.support.PmGroupVersionService groups,com.ruoyi.project.manage.service.IPmStageCompletionService completion) {
/** 注入阶段业务规则及独立共享布局读取服务;布局不参与阶段执行版本和审计流程。 */
public PmStageServiceImpl(PmWorkspaceMapper workspaceMapper,PmWorkItemMapper workItemMapper,PmStageMapper stageMapper,PmRevisionMapper revisionMapper,PmGraphService graphService,PmAuditService auditService,PmJson jsonCodec,PmAccess access,IPmService business,PmIterationAccess iterationAccess,com.ruoyi.project.manage.mapper.PmScheduleMapper schedules,com.ruoyi.project.manage.service.support.PmGroupVersionService groups,com.ruoyi.project.manage.service.IPmStageCompletionService completion,IPmFlowLayoutService layouts) {
this.layouts=layouts;
this.completion=completion;
this.groups=groups;
this.schedules=schedules;
@ -70,7 +73,7 @@ public class PmStageServiceImpl implements IPmStageService {
* 回退能力同时考虑既有经理权限和迭代可写性;只读成员仍可看到当前阶段事实。
* @param projectId 协作内部项目 ID(非原项目 ID),先完成成员鉴权再读取摘要
* @param iterationId 阶段和版本所属迭代,不能跨迭代混合判断
* @return 当前迭代阶段与边摘要;完成和采购开始放行独立表达,工作项明细仍由抽屉分页读取
* @return 当前迭代阶段、边及共享布局摘要;布局使用独立版本,工作项明细仍由抽屉分页读取
*/
public Map<String,Object> flowView(long projectId,long iterationId) {
locked(projectId,iterationId,"read");
@ -113,7 +116,7 @@ public class PmStageServiceImpl implements IPmStageService {
}).toList();
List<Map<String,Object>> reworkEdges=schedules.selectReworkEdges(projectId,iterationId);
for(Map<String,Object> edge:reworkEdges) edge.put("latestReworkAt",PmTime.format(nullable(edge,"latestReworkAt"),"Asia/Shanghai"));
return map("reworkEdges",reworkEdges,"iterationId",iterationId,"graphVersion",number(revisionMapper.selectGraphVersion(projectId,iterationId),"graph_version"),"stages",stages,"stageEdges",stageEdges,"unassigned",summary(items,null,graph),"items",List.of(),"dependencies",List.of());
return map("reworkEdges",reworkEdges,"iterationId",iterationId,"graphVersion",number(revisionMapper.selectGraphVersion(projectId,iterationId),"graph_version"),"stages",stages,"stageEdges",stageEdges,"unassigned",summary(items,null,graph),"items",List.of(),"dependencies",List.of(),"layout",layouts.get(projectId,iterationId));
}
/**

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- SQL 由应用数据源执行;布局版本不能与阶段执行图版本混用。 -->
<!--suppress SqlNoDataSourceInspection -->
<mapper namespace="com.ruoyi.project.manage.mapper.PmFlowLayoutMapper">
<select id="selectLayout" resultType="java.util.LinkedHashMap" flushCache="true" useCache="false">
SELECT layout_json,version,updated_by,updated_at
FROM pm_collab_flow_layout WHERE project_id=#{projectId} AND iteration_id=#{iterationId}
</select>
<!-- 项目锁覆盖首次读取和插入;唯一主键仍阻止绕过服务的并发初始化,不使用盲目 upsert。 -->
<insert id="insertLayout">
INSERT INTO pm_collab_flow_layout(project_id,iteration_id,layout_json,version,updated_by,updated_at)
VALUES(#{projectId},#{iterationId},#{layoutJson},1,#{actor},#{updatedAt})
</insert>
<!-- 仅更新独立布局,不修改 graph_version、审批历史或业务通知。 -->
<update id="updateLayout">
UPDATE pm_collab_flow_layout
SET layout_json=#{layoutJson},version=version+1,updated_by=#{actor},updated_at=#{updatedAt}
WHERE project_id=#{projectId} AND iteration_id=#{iterationId} AND version=#{version}
</update>
</mapper>

View File

@ -56,6 +56,8 @@ manage/
## 工作项分工与前置条件
流程画布的共享布局方案、数据边界、接口和验证记录见 [流程共享布局](docs/shared-flow-layout.md)。节点坐标、分区和排版结果按项目、迭代共用,由项目管理者维护;阶段组父子关系、执行连线及回退记录继续由现有业务表保存。框选高亮和辅助线是临时状态,缩放平移、展开折叠和辅助开关属于个人浏览器偏好。
- 阶段节点展示已有描述的两行摘要,完整说明在阶段抽屉查看;拖入新阶段时可填写描述。
- 采购当前执行版本记录实际开始后即放行直接下游,蓝色连线标注“开始即放行”;采购仍须验收及人工确认才算完成。绿色表示真实完成,历史沿用保持琥珀色;多条入边须全部满足,阶段组仍须全部子阶段完成。详情展示服务端完整准入条件(含继承门禁),排期分别标示采购开始至开始、其他执行边结束至开始边界。
- 流程画布左侧节点库提供阶段组、需求、方案、采购、设计、加工、组装、调试、研发、测试和自定义,支持搜索与拖放。普通类型拖入组内(包括子节点上方)自动归属,组本身仍只支持根画布;未执行及历史保护规则保持不变。自定义类型按普通工作阶段要求交付齐备后提审,不支持承载子阶段。

View File

@ -0,0 +1,10 @@
import { request } from './client'
import { iterationPath } from './paths'
import type { FlowLayout, FlowLayoutInput } from '../types'
export const flowLayoutApi = {
/** 读取当前迭代共享坐标与服务端编辑能力,GET 不初始化布局。 */
flowLayout: (projectId: number, iterationId: number) => request<FlowLayout>('get', iterationPath(projectId, iterationId, 'flow-layout')),
/** 按已读取版本提交完整布局,冲突不能自动覆盖。 */
saveFlowLayout: (projectId: number, iterationId: number, input: FlowLayoutInput) => request<FlowLayout>('put', iterationPath(projectId, iterationId, 'flow-layout'), input),
}

View File

@ -7,6 +7,7 @@ import { stageCompletionApi } from './stage-completion'
import { scheduleApi } from './schedules'
import { notificationApi } from './notifications'
import { todoApi } from './todos'
import { flowLayoutApi } from './flow-layout'
// 对上层保留统一入口,具体请求按业务归属维护;客户端、鉴权与错误处理只实现一次。
export const api = {
@ -19,6 +20,7 @@ export const api = {
...scheduleApi,
...notificationApi,
...todoApi,
...flowLayoutApi,
}
export { PmApiError, errorText, isAccessFailure } from './errors'

View File

@ -0,0 +1,59 @@
# 流程共享布局实施规范与计划
目标:按用户已确认方案,将项目协作的节点坐标、分区和排版结果保存为项目、迭代唯一的一份数据库布局,使成员读取相同画布结构及位置。RCS 97,RRS 42;关键权限已确认:项目管理者维护,普通成员只读。
范围:前端仅本模块,后端及安装/升级 SQL 仅 ruoyi-project。不改工作项、阶段执行审批、回退、父子关系或业务连线规则;不新增 websocket、依赖或个人/共享视图选择器。
## 数据及接口契约
- 新表 `pm_collab_flow_layout`,主键 `(project_id, iteration_id)`,复合外键指向现有迭代表;`layout_json`、独立 `version`、`updated_by`、`updated_at` 全部带中文注释。安装 SQL 同步增加,新环境及已有环境分别适用;升级为 025,仅新增此表,不删除旧表或业务数据。
- `GET /project/manage/projects/{id}/iterations/{iterationId}/flow-layout`:无写入;返回 `{version, positions, sections, updatedBy, updatedAt, canEdit}`。未初始化 version=0、positions={}、sections=[]。flow-view 响应新增同契约的 `layout`,供现有十五秒静默同步复用。
- `PUT` 同路径:请求严格为 `{version, positions, sections}`,响应为新布局;未知字段(含权限、节点业务状态和连线)拒绝。`positions` 是 `{ "s:123": {x,y,parentStageId:null或组ID} }`;允许虚拟未分配节点 s:0,且只能为根节点。
- sections 是 `{id,name,x,y,width,height}[]`,不含业务节点父子关系;id 匹配 `section:[A-Za-z0-9_-]{1,100}`,最多200个,名称非空且最长100,矩形宽180..20000、高120..20000;坐标有限数且绝对值不超过1e7。位置条目最多5001个,键必须合法并属于当前迭代有效节点,父级必须与数据库真实父级一致。
- 读沿用项目成员隔离,管理员无数据绕过;写还须项目管理者、有效未归档 PLANNED/ACTIVE 迭代。源项目→项目图锁覆盖权限/生命周期复查、结构验证及布局版本比较和保存,防止撤权、删除、改层级和并发初始化穿透。布局不推进业务 graphVersion,不产生业务成功通知或审批历史。
- 初始版本0条件插入,之后严格比较递增版本;过期请求409 `FLOW_LAYOUT_VERSION_CONFLICT`,不能自动覆盖新布局。结构已变则409 `FLOW_LAYOUT_STRUCTURE_CHANGED`;不暴露其他项目节点信息。读取过滤已删除或父级不再匹配的旧位置,不让过期坐标被错误解释为另一层级。
## 前端行为与边界
- 数据库坐标为唯一共享来源;初始布局使用确定性的完整展开布局计算,避免个人折叠导致默认位置不同。缺少位置的新增节点采用相同规则补位。旧本机节点/分区缓存不自动上报覆盖共享布局,保留旧键以便需要时人工恢复。
- 缩放/平移、展开折叠、辅助开关为本机个人偏好,使用独立新本地键;框选高亮与辅助线为临时内存。只选中节点、缩放或折叠不得触发布局写入。
- 管理者拖动结束、对齐/等距、自动布局及分区增删改/缩放后自动保存,约500ms合并;同一页面只允许一个在途写入,期间的新草稿在成功后用新版本继续串行提交。折叠隐藏节点的位置仍须保留,不可被部分可见画布覆盖。
- 普通成员可框选查看、缩放、平移、折叠、查看详情,但禁用拖动、自动布局、分区编辑、排版及其键盘绕过;服务端再次鉴权。
- 显示加载、待保存、保存中、已保存及失败状态。瞬时失败保留草稿,可重试;版本/结构冲突明确提示,并由用户选择重新加载共享布局,不能将过期草稿自动套用新版本。无失败假成功提示。
- 未保存/保存中或正在交互时不应用旧轮询快照;保存成功后若本地已有新编辑,不用旧响应覆盖草稿。接收其他管理者的新版本时保留个人视口、折叠及选区,不跳动或重开抽屉。离页使请求回调失效,保留必要的未提交草稿提示,不能写入另一个项目/迭代。
- 后端返回的 canEdit 控制共享编辑能力,不能仅依赖前端项目角色;新建阶段后坐标须等最新阶段摘要到达才能保存,避免尚未加载的节点身份被错误拒绝。
## 实施步骤与验收
- [x] 后端 DTO/Controller/Service/Mapper/XML、flow-view 集成、新安装及025升级;临时测试先观察缺失功能失败。
- [x] 前端 layout 类型/API、自动保存与同步 composable、WorkFlow/画布工具权限、个人偏好拆分;临时运行测试先失败后通过。
- [x] 真实数据库验证跨用户一致、源项目成员隔离、布局版本冲突、并发初始化、撤权及结构变更,实际数据库仅执行非破坏的025建表并检查中文注释和外键(使用已配置开发库,禁止连接不明生产目标)。
- [x] 编译、严格类型检查、生产构建、相关运行测试和独立审查;按项目规则清理全部临时测试/配置/日志/测试数据库。记录实际结果,未运行的检查不称通过。
AC-001:两位成员读取同迭代得到相同节点坐标及分区,业务连线保持数据库事实。
AC-002:普通成员无法通过UI、键盘或直接API修改共享布局,个人视口和折叠仍可用。
AC-003:多次快速编辑、网络失败、旧轮询响应和两管理者并发保存不丢失草稿或静默覆盖。
AC-004:父子阶段变更、删除、新增、折叠、回退换版后布局归属仍正确,不改变业务执行约束。
AC-005:升级不删除既有业务数据,中文表字段注释和外键完整;修改范围严格限定。
## 实施与验证记录(2026-11-03)
FR(共享布局、权限边界、个人状态分离、并发保护)、AC-001 至 AC-005 均已按上述契约实现并验证。Scope Drift、Requirement Drift、Assumption Drift:NONE。新增及修改方法的中文注释、并发及兼容逻辑说明已检查。
- 新布局表已在配置中的开发库 `cmvr-project-dev`(MySQL 8.0.36)执行025两次并核验幂等性,原有业务行数保持不变,布局表初始0行。六列及表的中文注释、复合迭代外键、用户外键、主键、索引和 CHECK 均核验通过。未向开发库写入测试业务数据。
- 后端临时 Controller/Service 边界验证36项通过;真实 Spring 事务、MyBatis XML、SecurityContext 和 MySQL 集成85项通过,覆盖并发首次保存/更新、锁后撤权/改父级/删除/终态/源项目删除、严格输入、5001位置/200分区上限,以及无业务版本、历史和 outbox 副作用。严格字符串边界在发现失败后修复并完整重跑。
- 前端专项运行测试2个文件、16项通过,包括真实 WorkFlow 组件渲染及传输 mock;覆盖隐藏子节点、串行新草稿、冲突、个人操作不写入、只读仍可创建工作项、轮询保留个人状态、离页失败和在途请求完成后的草稿恢复。
- Maven 模块及依赖编译成功;Maven 无现有测试源码,`No tests to run` 不计为测试覆盖。模块严格 `vue-tsc`(含未使用变量和参数检查)及前端生产构建通过。
- 全量前端单元测试347/348通过;唯一失败为未修改的 `system/mobileRelease/index.vue` 状态列样式策略检查。全量运行测试340项通过、1项超时,另有 `app-release.spec.js` 引用不存在的 `system/file/AppRelease.vue` 导致套件加载失败。超时所在 `project-workspace.spec.js` 隔离重跑36/36通过。以上模块不属于本次范围,未修改。
- 独立代码审查发现的离页草稿重试入口问题已通过回归测试修复;最终无未解决 P1/P2。临时测试源码、配置、日志及隔离数据库均在验证后清理。
## 使用与运维边界
1. 其他环境在部署新版后端前执行 `ruoyi-project/sql/upgrade/025_shared_flow_layout.sql`;新安装使用同步更新的完整安装脚本。数据库升级不会自动导入任意成员的旧浏览器布局,首次共享保存由管理者完成。
2. 保存采用约500ms防抖;其他成员通过现有十五秒静默同步看到最新布局,不提供实时协同光标。个人折叠或视口不同只影响浏览范围,业务结构、共享坐标与分区相同。
3. 网络失败时可重试;发生版本或结构冲突必须显式重新加载,放弃未保存修改前确认。离页未确认草稿仅留在当前页面会话内存,按用户、项目、迭代隔离,最多20个范围;达到上限会提示最早草稿被移除,关闭浏览器会提示当前未保存修改。
4. 验证包含组件运行和真实数据库服务集成,未执行完整浏览器到 HTTP 服务的端到端自动化;全量安装脚本未在现有开发库执行,只验证新增表与升级DDL等价。

View File

@ -0,0 +1,10 @@
import type { Point } from './common'
/** 阶段坐标携带业务父级,防止层级变更后误用旧的相对坐标。 */
export interface FlowLayoutPosition extends Point { parentStageId: number | null }
export type FlowLayoutPositions = Record<string, FlowLayoutPosition>
/** 展示分区不承载阶段归属、执行状态或连线。 */
export interface FlowLayoutSection extends Point { id: string; name: string; width: number; height: number }
/** 独立布局版本不能复用业务 graphVersion。 */
export interface FlowLayoutInput { version: number; positions: FlowLayoutPositions; sections: FlowLayoutSection[] }
export interface FlowLayout extends FlowLayoutInput { updatedBy: number | null; updatedAt: string | null; canEdit: boolean }

View File

@ -1,6 +1,7 @@
import type { ItemType, Lifecycle } from './common'
import type { Stage, StageSummary, StageReleaseRule } from './stage'
import type { WorkItem } from './work-item'
import type { FlowLayout } from './flow-layout'
export interface FlowFilters {
keyword?: string
@ -31,7 +32,7 @@ export interface StageEdge {
}
export interface FlowView {
layout?: FlowLayout
graphVersion?: number
stages: Stage[]
stageEdges: StageEdge[]

View File

@ -5,6 +5,7 @@ export type * from './work-item'
export type * from './stage'
export type * from './stage-completion'
export type * from './flow'
export type * from './flow-layout'
export type * from './rework'
export type * from './schedule'
export type * from './todo'

View File

@ -2,34 +2,39 @@
<section class="flow-view">
<div class="flow-toolbar">
<div class="flow-tools">
<el-button size="small" @click="autoLayout" :disabled="busy || canvasInteracting">自动布局</el-button><el-button size="small" @click="fitAll">适应画布</el-button>
<el-button size="small" @click="autoLayout" :disabled="!canEditLayout || busy || canvasInteracting">自动布局</el-button><el-button size="small" @click="fitAll">适应画布</el-button>
<el-button size="small" :type="canvasMode === 'select' ? 'primary' : 'default'" :disabled="busy" @click="canvasMode = canvasMode === 'select' ? 'pan' : 'select'">框选</el-button>
<el-button size="small" :type="canvasMode === 'section' ? 'primary' : 'default'" :disabled="busy || sections.length >= 200" @click="canvasMode = canvasMode === 'section' ? 'pan' : 'section'">分区</el-button>
<el-button size="small" :type="canvasMode === 'section' ? 'primary' : 'default'" :disabled="!canEditLayout || busy || sections.length >= 200" @click="canvasMode = canvasMode === 'section' ? 'pan' : 'section'">分区</el-button>
<el-checkbox v-model="guidesEnabled" size="small" :disabled="busy">对齐与间距辅助</el-checkbox>
<el-dropdown size="small" trigger="click" :disabled="busy || selectedNodes.length < 2 || !sameScope" @command="applyArrangement">
<el-button size="small" :disabled="busy || selectedNodes.length < 2 || !sameScope" :title="sameScope ? '以选区边界对齐' : '请选择同一画布层级的节点'">对齐 / 等距 ▾</el-button>
<el-dropdown size="small" trigger="click" :disabled="!canEditLayout || busy || selectedNodes.length < 2 || !sameScope" @command="applyArrangement">
<el-button size="small" :disabled="!canEditLayout || busy || selectedNodes.length < 2 || !sameScope" :title="sameScope ? '以选区边界对齐' : '请选择同一画布层级的节点'">对齐 / 等距 ▾</el-button>
<template #dropdown><el-dropdown-menu>
<el-dropdown-item command="left">左对齐</el-dropdown-item><el-dropdown-item command="center-x">水平居中(中心竖线对齐)</el-dropdown-item><el-dropdown-item command="right">右对齐</el-dropdown-item>
<el-dropdown-item command="top" divided>顶部对齐</el-dropdown-item><el-dropdown-item command="center-y">垂直居中(中心横线对齐)</el-dropdown-item><el-dropdown-item command="bottom">底部对齐</el-dropdown-item>
<el-dropdown-item command="distribute-x" divided :disabled="selectedNodes.length < 3">水平等间距</el-dropdown-item><el-dropdown-item command="distribute-y" :disabled="selectedNodes.length < 3">垂直等间距</el-dropdown-item>
</el-dropdown-menu></template>
</el-dropdown>
<el-button v-if="selectedNodes.length" size="small" :disabled="busy || selectedNodes.some(node => !!node.parentNode) || sections.length >= 200" @click="createSelectionSection">选区设为分区</el-button>
<el-button v-if="selectedNodes.length" size="small" :disabled="!canEditLayout || busy || selectedNodes.some(node => !!node.parentNode) || sections.length >= 200" @click="createSelectionSection">选区设为分区</el-button>
<span v-if="selectedNodes.length" class="flow-help">已选 {{ selectedNodes.length }} 个节点{{ sameScope ? '' : '(不同层级)' }}</span>
</div>
<div class="flow-tools"><span class="flow-help">{{ canvasMode === 'section' ? '在空白处拖框创建分区;拖动分区标题栏可整体移动' : canvasMode === 'select' ? '拖框或点击选择节点;Ctrl / ⌘ 可加选;空格可平移' : '拖动平移;Shift 拖框 / Ctrl 或 ⌘ 点击多选;布局仅存当前浏览器' }}</span><el-button v-if="canManage" size="small" @click="stageOpen = true">管理阶段</el-button></div>
<div class="flow-tools"><span class="flow-help">{{ canvasMode === 'section' ? '在空白处拖框创建分区;拖动分区标题栏可整体移动' : canvasMode === 'select' ? '拖框或点击选择节点;Ctrl / ⌘ 可加选;空格可平移' : '拖动平移;Shift 拖框 / Ctrl 或 ⌘ 点击多选;成员共享节点位置与分区' }}</span><el-button v-if="canManage" size="small" @click="stageOpen = true">管理阶段</el-button></div>
</div>
<div class="flow-layout-status" role="status" aria-live="polite">
<span :class="{ 'layout-error': layoutFailure }">{{ layoutStatus }}</span>
<el-button v-if="layoutFailure && !layoutConflict" link type="primary" :disabled="layoutSaving || layoutLoading" @click="sharedLayout.retry">重试</el-button>
<el-button link type="primary" :disabled="layoutSaving || layoutLoading || canvasInteracting || sectionEditing" @click="reloadSharedLayout">重新加载共享布局</el-button>
</div>
<el-alert v-if="failure" type="error" :title="failure" :closable="false" class="flow-failure" />
<div class="flow-editor" :class="{ inactive: !active }">
<FlowNodePalette :enabled="canManage && !busy && !stageNameOpen" @pointerdown.capture="finishCanvasGesture" />
<div ref="canvas" class="flow-canvas" :class="{ 'drawing-section': canvasMode === 'section' }" @pointerdown.capture="canvasTools.drawSection" @keydown.capture="canvasTools.moveWithKeyboard" @dragover.prevent @drop.prevent="dropStage">
<!-- 保持阶段组、子阶段和连线的固定层级;选中时自动提升父组会使其背景遮住内部连线。 -->
<VueFlow v-if="active" :id="flowId" v-model:nodes="nodes" :edges="edges" :connection-line-type="ConnectionLineType.Bezier" :delete-key-code="null" :min-zoom="0.1" :max-zoom="4" :nodes-connectable="canManage && !busy && canvasMode !== 'section'" :edges-updatable="false" :nodes-draggable="!busy && canvasMode !== 'section'" :selection-key-code="canvasMode === 'select' ? true : 'Shift'" :multi-selection-key-code="['Control', 'Meta']" :selection-mode="SelectionMode.Full" :pan-on-drag="canvasMode === 'pan' ? true : [1, 2]" :node-drag-threshold="3" :elevate-nodes-on-select="false" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragStarted" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport" @selection-start="selecting = true" @selection-end="selecting = false">
<VueFlow v-if="active" :id="flowId" v-model:nodes="nodes" :edges="edges" :connection-line-type="ConnectionLineType.Bezier" :delete-key-code="null" :min-zoom="0.1" :max-zoom="4" :nodes-connectable="canManage && !busy && canvasMode !== 'section'" :edges-updatable="false" :nodes-draggable="canEditLayout && !busy && canvasMode !== 'section'" :selection-key-code="canvasMode === 'select' ? true : 'Shift'" :multi-selection-key-code="['Control', 'Meta']" :selection-mode="SelectionMode.Full" :pan-on-drag="canvasMode === 'pan' ? true : [1, 2]" :node-drag-threshold="3" :elevate-nodes-on-select="false" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragStarted" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport" @selection-start="selecting = true" @selection-end="selecting = false">
<Background :gap="22" :size="1" pattern-color="var(--el-border-color)" />
<MiniMap pannable zoomable :node-color="minimapColor" node-stroke-color="var(--el-color-primary-light-3)" mask-color="var(--el-mask-color-extra-light)" />
<Controls :show-interactive="false" />
<template #edge-rework="edgeProps"><FlowReworkEdge v-bind="edgeProps" /></template>
<template #node-section="{ data }"><FlowSectionNode v-if="data.section" :section="data.section" :disabled="busy" @rename="canvasTools.renameSection" @remove="canvasTools.removeSection" @resize="canvasTools.resizeSection" /></template>
<template #node-section="{ data }"><FlowSectionNode v-if="data.section" :section="data.section" :disabled="!canEditLayout || busy" @editing="sectionEditing = $event" @rename="canvasTools.renameSection" @remove="canvasTools.removeSection" @resize="canvasTools.resizeSection" /></template>
<template #node-stage="{ data }"><FlowStageNode :data="{ ...data, busy }" @view="openDrawer($event, 'current')" @create="createInStage" @rework="openRework" @history="openDrawer($event, 'history')" @rename="renameStage" @remove="removeStage" /></template>
<template #node-group="{ data }"><FlowStageNode :data="{ ...data, busy }" @view="openDrawer($event, 'current')" @create-child="createChildStage" @toggle="toggleGroup" @rework="openRework" @history="openDrawer($event, 'history')" @rename="renameStage" @remove="removeStage" /></template>
</VueFlow>
@ -49,7 +54,7 @@
import { computed, nextTick, ref, watch } from 'vue'
import { ConnectionLineType, SelectionMode, VueFlow, useVueFlow } from '@vue-flow/core'
import type { Node, Edge, NodeMouseEvent, NodeDragEvent, GraphNode, Connection } from '@vue-flow/core'
import { ElMessageBox } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls'
import { MiniMap } from '@vue-flow/minimap'
@ -64,6 +69,8 @@ import { stageAppearance } from './utils/stageAppearance'
import { stageGroupAt } from './utils/stageDrop'
import { useCanvasGestureCleanup } from './composables/useCanvasGestureCleanup'
import { useCanvasTools } from './composables/useCanvasTools'
import { useSharedFlowLayout } from './composables/useSharedFlowLayout'
import { completeLayoutPositions } from './utils/sharedLayout'
import type { ArrangeAction } from './utils/canvasGeometry'
import { isPaletteNodeType } from '../../shared/constants/stageNodeTypes'
import type { FlowNodeData, FlowEdgeData } from './utils/graph'
@ -86,7 +93,7 @@ const emit = defineEmits<{ open: [id: number]; changed: []; create: [stageId: nu
const canvas = ref<HTMLElement | null>(null)
const flowId = 'project-flow-' + props.projectId + '-' + props.iterationId
const { fitView, setViewport, viewport, screenToFlowCoordinate, getNodes, updateNodeInternals, paneDragging, userSelectionActive, userSelectionRect, nodesSelectionActive } = useVueFlow(flowId)
const nodes = ref<Node<FlowNodeData>[]>([]), edges = ref<Edge<FlowEdgeData>[]>([]), positions = ref<Record<string, Point>>({})
const nodes = ref<Node<FlowNodeData>[]>([]), edges = ref<Edge<FlowEdgeData>[]>([])
const busy = ref(false), dragging = ref(false), failure = ref(''), stageOpen = ref(false), stageNameOpen = ref(false), pendingStagePoint = ref<Point | null>(null)
const draftViewport = ref<(Point & { zoom: number }) | null>(null)
const createParentId = ref<number | null>(null), collapsedStages = ref<number[]>([])
@ -96,10 +103,14 @@ const reworkSourceId = ref<number | null>(null), drawerStageId = ref<number | nu
const drawerEditing = ref(false)
const renamingStage = ref<Stage | null>(null)
const selecting = ref(false)
const canvasTools = useCanvasTools({ nodes: getNodes, viewport, enabled: computed(() => props.active && !busy.value && !stageOpen.value && !stageNameOpen.value && !renamingStage.value && drawerStageId.value === null && reworkSourceId.value === null), toFlow: screenToFlowCoordinate, changed: persistCanvasLayout })
const sectionEditing = ref(false), toolInteracting = ref(false)
const sharedLayout = useSharedFlowLayout({ userId: computed(() => props.userId), projectId: computed(() => props.projectId), iterationId: computed(() => props.iterationId), view: computed(() => props.view), active: computed(() => props.active), manager: computed(() => props.canManage), interacting: computed(() => dragging.value || selecting.value || paneDragging.value || toolInteracting.value || sectionEditing.value || busy.value), load: api.flowLayout, save: api.saveFlowLayout, unsaved: message => ElMessage.warning(message) })
const { positions, canEdit: canEditLayout, status: layoutStatus, failure: layoutFailure, conflict: layoutConflict, saving: layoutSaving, loading: layoutLoading } = sharedLayout
const canvasTools = useCanvasTools({ nodes: getNodes, viewport, sections: sharedLayout.sections, editable: canEditLayout, enabled: computed(() => props.active && !busy.value && !stageOpen.value && !stageNameOpen.value && !renamingStage.value && drawerStageId.value === null && reworkSourceId.value === null), toFlow: screenToFlowCoordinate, changed: persistCanvasLayout, personalChanged: savePreference })
const { sections, guidesEnabled, guides, mode: canvasMode, draft: sectionDraft, interacting: canvasInteracting, selected: selectedNodes, sameScope } = canvasTools
// 平移和节点移动期间都暂停静默同步,避免尚未释放的鼠标手势遇到画布重建;坐标仍仅保存到当前浏览器。
const isEditing = computed(() => drawerEditing.value || dragging.value || selecting.value || canvasInteracting.value || paneDragging.value || busy.value || stageOpen.value || stageNameOpen.value || renamingStage.value !== null || reworkSourceId.value !== null)
watch(canvasInteracting, value => { toolInteracting.value = value })
// 未确认的共享草稿与分区标题编辑同样暂停轮询,防止旧快照覆盖正在编辑的对象。
const isEditing = computed(() => sharedLayout.blocksPolling.value || sectionEditing.value || drawerEditing.value || dragging.value || selecting.value || canvasInteracting.value || paneDragging.value || busy.value || stageOpen.value || stageNameOpen.value || renamingStage.value !== null || reworkSourceId.value !== null)
const { finishCanvasGesture } = useCanvasGestureCleanup(
computed(() => dragging.value || paneDragging.value),
computed(() => !props.active || stageOpen.value || stageNameOpen.value || renamingStage.value !== null || drawerStageId.value !== null || reworkSourceId.value !== null),
@ -107,25 +118,26 @@ const { finishCanvasGesture } = useCanvasGestureCleanup(
)
defineExpose({ isEditing })
let loaded = false, movingProgrammatically = false
let previousParents: Record<string, number | null> = {}
let lastGraphSignature = ''
let createdPlacement: { id: number; point: Point; parentStageId: number | null } | null = null
watch(() => props.view, () => {
if (!loaded) {
const preference = readFlowPreferences(props.userId, props.projectId, props.iterationId)
positions.value = Object.fromEntries(Object.entries(preference?.positions || {}).filter(([id]) => id.startsWith('s:') && (preference?.parents?.[id] ?? null) === (props.view.stages.find(stage => 's:' + stage.id === id)?.parentStageId ?? null)))
draftViewport.value = preference?.viewport || null
collapsedStages.value = preference?.collapsedStages || []
sections.value = preference?.sections || []
guidesEnabled.value = preference?.guidesEnabled !== false
loaded = true
}
// 迁入或迁出阶段组后坐标原点已变化;只清除该节点的旧坐标,避免把根画布绝对位置当成子画布相对位置。
const parents = Object.fromEntries(props.view.stages.map(stage => ['s:' + stage.id, stage.parentStageId ?? null]))
for (const [id, parent] of Object.entries(parents)) if (id in previousParents && previousParents[id] !== parent) delete positions.value[id]
previousParents = parents
// 新建接口先返回 ID,业务摘要稍后才刷新;等摘要确认归属后再把落点提交到共享布局。
const stage = createdPlacement && props.view.stages.find(stage => stage.id === createdPlacement?.id)
if (createdPlacement && stage) {
if ((stage.parentStageId ?? null) === createdPlacement.parentStageId) sharedLayout.update({ ['s:' + stage.id]: createdPlacement.point })
createdPlacement = null
}
rebuild()
}, { immediate: true })
watch(() => [props.canCreate, props.canManage], rebuild)
watch([positions, sections, canEditLayout, () => props.canCreate, () => props.canManage], rebuild)
/**
* 待办已在工作区复核审批身份;这里只展开目标父组、定位节点并打开当前版本交付及审批面板。
* 原定位清空或换目标时先关闭旧抽屉,避免新申请失效后仍显示另一阶段;普通快照不会重开抽屉。
@ -151,22 +163,27 @@ watch(() => props.active, async active => { if (active) { await nextTick(); awai
/** 按子画布和外框实际尺寸重建阶段摘要,折叠只隐藏内部节点,不改变共享业务图。 */
function rebuild() {
if (dragging.value) return
const { layout: _layout, ...businessView } = props.view
const signature = JSON.stringify([businessView, positions.value, sections.value, collapsedStages.value, props.canCreate, props.canManage, canEditLayout.value])
if (signature === lastGraphSignature) return
lastGraphSignature = signature
const selected = new Set(getNodes.value.filter(node => node.selected).map(node => node.id))
const graph = buildFlowGraph(props.view, positions.value, collapsedStages.value)
for (const node of graph.nodes) if (node.data) { node.data.canWrite = props.canCreate; node.data.canManage = props.canManage; node.data.deleteBlockedReason = node.data.stage ? stageDeleteBlockedReason(node.data.stage, props.view.stages) : ''; node.connectable = !!node.data.stage && props.canManage }
for (const edge of graph.edges) edge.selectable = props.canManage && edge.data?.kind !== 'rework'
nodes.value = [...canvasTools.sectionNodes(), ...graph.nodes].map(node => ({ ...node, selected: selected.has(node.id) })); edges.value = graph.edges
}
/** 本地偏好保存阶段坐标、分区和辅助开关;均不进入业务接口,旧工作项坐标不再写回。 */
function savePreference() { writeFlowPreferences(props.userId, props.projectId, { positions: positions.value, parents: previousParents, collapsedStages: collapsedStages.value, viewport: draftViewport.value, sections: sections.value, guidesEnabled: guidesEnabled.value }, props.iterationId) }
/** 浏览器只保留个人视口、折叠与辅助开关;坐标和分区由数据库独立保存。 */
function savePreference() { if (loaded) writeFlowPreferences(props.userId, props.projectId, { collapsedStages: collapsedStages.value, viewport: draftViewport.value, guidesEnabled: guidesEnabled.value }, props.iterationId) }
/** 批量排版后先调整组边界及连线,再一次保存补偿后的相对坐标,避免刷新后子节点漂移。 */
function persistCanvasLayout() {
if (!canEditLayout.value) return
const current = getNodes.value
const groups = current.filter(node => node.type === 'group').map(node => node.id)
for (const id of groups) resizeStageGroup(current, id, edges.value)
updateReworkRoutes(current, edges.value)
positions.value = { ...positions.value, ...Object.fromEntries(current.filter(node => node.id.startsWith('s:')).map(node => [node.id, { ...node.position }])) }
savePreference(); rebuild()
sharedLayout.update(Object.fromEntries(current.filter(node => node.id.startsWith('s:')).map(node => [node.id, { ...node.position }])), sections.value)
rebuild()
if (groups.length) void nextTick(() => updateNodeInternals(groups))
}
/** 多选排版的失败原因保留在画布上,不对已选节点进行部分修改。 */
@ -174,7 +191,7 @@ function applyArrangement(action: ArrangeAction) { failure.value = canvasTools.a
/** 分区由完整根节点的包围框生成;只选择子阶段时提示使用其阶段组。 */
function createSelectionSection() { failure.value = canvasTools.sectionFromSelection() }
/** 拖动起点记录分区包含的根节点,避免拖动途中将路过的节点吸入分区。 */
function dragStarted(event: NodeDragEvent) { dragging.value = true; canvasTools.startDrag(event) }
function dragStarted(event: NodeDragEvent) { if (!canEditLayout.value) return; dragging.value = true; canvasTools.startDrag(event) }
/** 框选使用原生指针捕获;失焦、隐藏或弹窗接管时解除展示状态,避免静默同步一直被暂停。 */
function cancelCanvasSelection() {
if (!selecting.value) return
@ -187,6 +204,7 @@ function cancelCanvasSelection() {
* @remarks 尺寸写入 DOM 后刷新父框连接点,避免执行线仍连接旧宽高。
*/
function nodeDragged(event: NodeDragEvent) {
if (!canEditLayout.value) return
canvasTools.drag(event)
const groups = [...new Set(event.nodes.map(node => node.parentNode).filter((id): id is string => !!id))]
for (const id of groups) resizeStageGroup(getNodes.value, id, edges.value)
@ -194,12 +212,19 @@ function nodeDragged(event: NodeDragEvent) {
if (groups.length) void nextTick(() => updateNodeInternals(groups))
}
/**
* 松开时保存补偿后的父子坐标;重新进入页面可恢复相同外框,不调用业务写接口。
* 松开时保存补偿后的父子共享坐标,隐藏子阶段由完整草稿保留。
* @param event 拖动最终节点集合,用于保存前完成最后一次边界计算
*/
function dragStopped(event: NodeDragEvent) { nodeDragged(event); canvasTools.finishDrag(); dragging.value = false; persistCanvasLayout() }
/** 删除旧手动阶段坐标后按显式阶段图重新布局。 */
async function autoLayout() { positions.value = {}; savePreference(); rebuild(); await nextTick(); await fitAll() }
function dragStopped(event: NodeDragEvent) { if (!canEditLayout.value) { dragging.value = false; return }; nodeDragged(event); canvasTools.finishDrag(); dragging.value = false; persistCanvasLayout() }
/** 自动排版始终按完整展开图计算,再恢复个人折叠并保存共享位置。 */
async function autoLayout() { if (!canEditLayout.value || busy.value || canvasInteracting.value) return; sharedLayout.update(completeLayoutPositions(props.view, {})); rebuild(); await nextTick(); await fitAll() }
/** 重载会放弃当前未保存草稿,先明确确认;网络失败继续保留原草稿。 */
async function reloadSharedLayout() {
if (sharedLayout.dirty.value) {
try { await ElMessageBox.confirm('重新加载会放弃当前未保存的布局修改,是否继续?', '重新加载共享布局', { type: 'warning', closeOnClickModal: false }) } catch { return }
}
await sharedLayout.reload()
}
/** 缩放和平移只影响当前浏览器的展示偏好。 */
function viewportMoved() { if (!loaded || movingProgrammatically || !props.active) return; draftViewport.value = { ...viewport.value }; savePreference() }
/** 页签重进恢复浏览器视口,首次进入使用便于阅读的默认比例。 */
@ -287,8 +312,8 @@ function dropStage(event: DragEvent) {
}
/** 组内快捷创建允许先选择工作节点分类;只在创建前选择,不提供阶段组或后续改类型入口。 */
function createChildStage(id: number) { if (!props.view.stages.some(stage => stage.id === id && stage.canCreateChildStage)) return; createParentId.value = id; createNodeType.value = undefined; pendingStagePoint.value = null; stageNameOpen.value = true }
/** 创建后把本地坐标与父级一起记录;新子节点的偏好不能因尚未刷新父级索引而丢失。 */
function stageCreated(id: number) { if (pendingStagePoint.value) positions.value = { ...positions.value, ['s:' + id]: pendingStagePoint.value }; previousParents['s:' + id] = createParentId.value; stageNameOpen.value = false; pendingStagePoint.value = null; if (createParentId.value) collapsedStages.value = collapsedStages.value.filter(value => value !== createParentId.value); savePreference(); emit('changed') }
/** 创建后的落点先等待最新业务摘要确认节点和父级,避免把尚未加载的 ID 发送到严格布局接口。 */
function stageCreated(id: number) { if (pendingStagePoint.value) createdPlacement = { id, point: { ...pendingStagePoint.value }, parentStageId: createParentId.value }; stageNameOpen.value = false; pendingStagePoint.value = null; if (createParentId.value) collapsedStages.value = collapsedStages.value.filter(value => value !== createParentId.value); savePreference(); emit('changed') }
/** 折叠状态按用户、项目、迭代保存在当前浏览器,展开后恢复子节点相对位置。 */
function toggleGroup(id: number) { collapsedStages.value = collapsedStages.value.includes(id) ? collapsedStages.value.filter(value => value !== id) : [...collapsedStages.value, id]; savePreference(); rebuild() }
/** 仅连接当前项目的两个真实阶段;后端在项目锁内复验权限、环和已执行门禁。 */
@ -326,4 +351,5 @@ async function edgeClicked(event: { edge: Edge<FlowEdgeData> }) {
.flow-canvas :deep([class~="vue-flow__node-stage"].selected .phase-group),.flow-canvas :deep([class~="vue-flow__node-group"].selected .phase-group),.flow-canvas :deep([class~="vue-flow__node-section"].selected .canvas-section){outline:2px solid var(--el-color-primary);outline-offset:3px}
.flow-canvas :deep([class~="vue-flow__selection"]),.flow-canvas :deep([class~="vue-flow__nodesselection-rect"]){background:color-mix(in srgb,var(--el-color-primary) 8%,transparent);border:1px solid var(--el-color-primary)}
.drawing-section :deep([class~="vue-flow__pane"]){cursor:crosshair}
.flow-layout-status{display:flex;align-items:center;gap:12px;margin-bottom:8px;font-size:12px;color:var(--el-text-color-secondary)}.layout-error{color:var(--el-color-danger)}
</style>

View File

@ -11,19 +11,22 @@
</div>
</template>
<script setup lang="ts">
import { nextTick, ref } from 'vue'
import { nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { EditPen, Delete } from '@element-plus/icons-vue'
import type { InputInstance } from 'element-plus'
import type { CanvasSection } from '../utils/canvasGeometry'
const props = defineProps<{ section: CanvasSection; disabled: boolean }>()
const emit = defineEmits<{ rename: [id: string, name: string]; remove: [id: string]; resize: [id: string, event: PointerEvent] }>()
const emit = defineEmits<{ rename: [id: string, name: string]; remove: [id: string]; resize: [id: string, event: PointerEvent]; editing: [value: boolean] }>()
const editing = ref(false), name = ref(''), input = ref<InputInstance>()
/** 使用独立草稿编辑分区标题,避免尚未确认的输入污染浏览器偏好。 */
/** 使用独立标题草稿,编辑状态向上暂停轮询,避免后台快照替换输入框。 */
async function edit() { if (props.disabled) return; name.value = props.section.name; editing.value = true; await nextTick(); input.value?.focus(); input.value?.select() }
/** 非空标题在 Enter 或失焦时提交;空值保留原名,不删除分区。 */
function submit() { if (!editing.value) return; editing.value = false; if (name.value.trim()) emit('rename', props.section.id, name.value) }
/** Enter 或失焦只提交仍有编辑能力的非空标题;撤权后的 blur 不能写入旧草稿。 */
function submit() { if (!editing.value) return; editing.value = false; if (!props.disabled && name.value.trim()) emit('rename', props.section.id, name.value) }
/** Escape 放弃本次标题草稿,随后到达的 blur 不能再次提交。 */
function cancel() { editing.value = false }
watch(editing, value => emit('editing', value), { flush: 'sync' })
watch(() => props.disabled, disabled => { if (disabled) cancel() })
onBeforeUnmount(() => { if (editing.value) emit('editing', false) })
</script>
<style scoped>
.canvas-section{height:100%;width:100%;box-sizing:border-box;border:1px dashed var(--el-color-primary-light-3);border-radius:12px;background:color-mix(in srgb,var(--el-color-primary) 5%,transparent);position:relative;pointer-events:none}

View File

@ -1,6 +1,7 @@
import { computed, onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
import type { GraphNode, Node, NodeDragEvent } from '@vue-flow/core'
import type { Point } from '../../../types'
import type { FlowLayoutSection } from '../../../types'
import { createIdempotencyKey } from '../../../shared/utils/idempotency'
import { absoluteRectangle, type FlowNodeData } from '../utils/graph'
import { arrangeBoxes, containsBox, selectionRoots, snapBox, type ArrangeAction, type CanvasBox, type CanvasGuide, type CanvasSection } from '../utils/canvasGeometry'
@ -9,17 +10,20 @@ interface CanvasToolsOptions {
nodes: Readonly<Ref<GraphNode<FlowNodeData>[]>>
viewport: Readonly<Ref<Point & { zoom: number }>>
enabled: Readonly<Ref<boolean>>
editable: Readonly<Ref<boolean>>
sections?: Ref<FlowLayoutSection[]>
toFlow: (point: Point) => Point
changed: () => void
personalChanged: () => void
}
/**
* 管理纯展示的分区、框选排版和拖动辅助,不调用业务接口或改变阶段父子关系。
* @param options 当前 Vue Flow 实例、坐标转换及本地保存回调;不得传入其他项目画布的节点
* @param options 当前 Vue Flow、服务端编辑能力与独立的布局/个人偏好回调;不得串用项目节点
* @returns 工具状态与事件处理器;浏览器手势监听在结束、失焦、页签隐藏和卸载时释放
*/
export function useCanvasTools(options: CanvasToolsOptions) {
const sections = ref<CanvasSection[]>([]), guidesEnabled = ref(true), guides = ref<CanvasGuide[]>([])
const sections = options.sections || ref<CanvasSection[]>([]), guidesEnabled = ref(true), guides = ref<CanvasGuide[]>([])
const mode = ref<'pan' | 'select' | 'section'>('pan'), draft = ref<CanvasBox | null>(null), resizing = ref(false)
const selected = computed(() => selectionRoots(options.nodes.value.filter(node => node.selected && node.type !== 'section').map(localBox)))
const sameScope = computed(() => new Set(selected.value.map(node => node.parentNode || '')).size <= 1)
@ -41,6 +45,7 @@ export function useCanvasTools(options: CanvasToolsOptions) {
/** 拖动分区时在起点确定内部根节点,整个手势不重新收集,防止途经节点被意外带走。 */
function startDrag(event: NodeDragEvent) {
if (!options.enabled.value || !options.editable.value) return
dragActive = true
captureSectionContents(event.nodes)
}
@ -62,6 +67,7 @@ export function useCanvasTools(options: CanvasToolsOptions) {
/** 每次鼠标移动按当前缩放吸附整个选区,再按分区起点补偿内部节点;松手时须再调用一次。 */
function drag(event: NodeDragEvent) {
if (!options.enabled.value || !options.editable.value) return
restoreCarriedChildren()
const roots = dragBoxes(event), ids = new Set(roots.map(box => box.id))
const movingNodes = event.nodes.filter(node => ids.has(node.id))
@ -104,11 +110,11 @@ export function useCanvasTools(options: CanvasToolsOptions) {
})
}
/** 辅助线随手势结束清空;本地分区位置由调用方与阶段坐标在一次保存中写入。 */
function finishDrag() { syncSections(); carried = []; carriedChildren.clear(); dragActive = false; guides.value = [] }
/** 辅助线随手势结束清空;只在仍有编辑能力时把分区几何合并到共享草稿。 */
function finishDrag() { if (options.enabled.value && options.editable.value) syncSections(); carried = []; carriedChildren.clear(); dragActive = false; guides.value = [] }
/**
* 接管画布方向键微调,避免 Vue Flow 默认移动绕过分区携带、组边界和本地保存。
* 接管方向键微调,阻止 Vue Flow 默认移动绕过只读能力、分区携带及共享保存。
* @param event 仅当前画布冒泡的键盘事件;文本输入和按钮自身的键盘操作不移动节点
* @remarks 方向键每次移动 1 个画布单位,Shift 为 10;精确微调不吸附,父子选中只移动父级。
*/
@ -117,6 +123,7 @@ export function useCanvasTools(options: CanvasToolsOptions) {
const vector = vectors[event.key], target = event.target as Element
if (!vector || target.closest('input,textarea,select,[contenteditable="true"]')) return
event.stopPropagation()
if (!options.editable.value) { event.preventDefault(); return }
// 鼠标手势持有起点快照或尺寸闭包时不能用键盘重建画布,否则后续移动会写入已被替换的节点对象。
if (dragActive || pointerCleanup) { event.preventDefault(); return }
if (target.closest('button') || event.ctrlKey || event.metaKey || event.altKey || !options.enabled.value || mode.value === 'section') return
@ -131,6 +138,7 @@ export function useCanvasTools(options: CanvasToolsOptions) {
/** 对齐只作用于同一父画布的阶段,均分空间不足时返回可展示的原因,不做部分变更。 */
function arrange(action: ArrangeAction): string {
if (!options.editable.value) return '当前共享布局只读。'
if (!options.enabled.value) return '画布正在处理其他操作,请稍后重试。'
const result = arrangeBoxes(selected.value, action)
if (!result) return !sameScope.value ? '请选择同一画布层级的节点进行对齐。' : action.startsWith('distribute-') ? '等间距需要至少三个节点,且首尾之间有足够空间。' : '请至少选择两个节点。'
@ -141,13 +149,15 @@ export function useCanvasTools(options: CanvasToolsOptions) {
/** 创建分区仅保存标题与几何值;不将阶段挂到分区下,因此已有执行边和组约束保持独立。 */
function addSection(box: Omit<CanvasBox, 'id'>) {
if (sections.value.length >= 200) return
if (!options.enabled.value || !options.editable.value || sections.value.length >= 200) return
sections.value.push({ ...box, id: 'section:' + createIdempotencyKey(), name: '分区 ' + (sections.value.length + 1), width: Math.max(180, box.width), height: Math.max(120, box.height) })
mode.value = 'pan'; options.changed()
}
/** 以选中根阶段或完整阶段组的边界创建分区;子阶段仍由业务阶段组管理,不能被展示分区拆出。 */
function sectionFromSelection(): string {
if (!options.editable.value) return '当前共享布局只读。'
if (!options.enabled.value) return '画布正在处理其他操作,请稍后重试。'
if (!selected.value.length || selected.value.some(box => box.parentNode)) return '请选择根画布节点;组内子阶段请选中其完整阶段组。'
if (sections.value.length >= 200) return '当前画布最多支持 200 个分区。'
const x = Math.min(...selected.value.map(box => box.x)) - 24, y = Math.min(...selected.value.map(box => box.y)) - 48
@ -157,16 +167,16 @@ export function useCanvasTools(options: CanvasToolsOptions) {
return ''
}
/** 改名仅接受有限长度的非空文本;节点组件提交草稿后才同步到浏览器偏好。 */
/** 改名只接受有限长度的非空文本,服务端只读时不能通过事件绕过入口禁用。 */
function renameSection(id: string, name: string) {
const section = sections.value.find(item => item.id === id), normalized = name.trim().slice(0, 100)
if (!options.enabled.value || !section || !normalized) return
if (!options.enabled.value || !options.editable.value || !section || !normalized) return
section.name = normalized; options.changed()
}
/** 删除的是展示分区,内部阶段、连线和历史记录不受影响。 */
function removeSection(id: string) {
if (!options.enabled.value) return
if (!options.enabled.value || !options.editable.value) return
sections.value = sections.value.filter(section => section.id !== id); options.changed()
}
@ -176,7 +186,7 @@ export function useCanvasTools(options: CanvasToolsOptions) {
* @remarks 取消、失焦、隐藏和卸载只清理草稿;小于 20 像素的误触不创建分区。
*/
function drawSection(event: PointerEvent) {
if (!options.enabled.value || mode.value !== 'section' || event.button !== 0 || sections.value.length >= 200) return
if (!options.enabled.value || !options.editable.value || mode.value !== 'section' || event.button !== 0 || sections.value.length >= 200) return
const target = event.target as Element
if (target.closest('.vue-flow__node, .vue-flow__controls, .vue-flow__minimap')) return
event.preventDefault(); event.stopPropagation()
@ -195,7 +205,7 @@ export function useCanvasTools(options: CanvasToolsOptions) {
/** 右下角调整分区尺寸,按缩放换算并限制在可持久化范围;取消时恢复原尺寸。 */
function resizeSection(id: string, event: PointerEvent) {
if (!options.enabled.value || event.button !== 0) return
if (!options.enabled.value || !options.editable.value || event.button !== 0) return
const node = options.nodes.value.find(item => item.id === id)
if (!node) return
const original = absoluteRectangle(node, []), start = options.toFlow({ x: event.clientX, y: event.clientY })
@ -205,7 +215,8 @@ export function useCanvasTools(options: CanvasToolsOptions) {
node.style = { width: Math.min(20000, Math.max(180, original.width + end.x - start.x)) + 'px', height: Math.min(20000, Math.max(120, original.height + end.y - start.y)) + 'px' }
}, commit => {
if (!commit) node.style = { width: original.width + 'px', height: original.height + 'px' }
resizing.value = false; syncSections(); options.changed()
resizing.value = false
if (commit && options.editable.value && options.enabled.value) { syncSections(); options.changed() }
})
}
@ -229,10 +240,11 @@ export function useCanvasTools(options: CanvasToolsOptions) {
/** 组装纯展示节点,不提供执行连接点,也不设置业务 parentNode。 */
function sectionNodes(): Node<FlowNodeData>[] {
return sections.value.map(section => ({ id: section.id, type: 'section', position: { x: section.x, y: section.y }, style: { width: section.width + 'px', height: section.height + 'px' }, zIndex: -10, connectable: false, deletable: false, dragHandle: '.section-drag', data: { section } }))
return sections.value.map(section => ({ id: section.id, type: 'section', position: { x: section.x, y: section.y }, style: { width: section.width + 'px', height: section.height + 'px' }, zIndex: -10, connectable: false, deletable: false, draggable: options.editable.value, dragHandle: '.section-drag', data: { section } }))
}
watch(guidesEnabled, () => { guides.value = []; options.changed() })
watch(guidesEnabled, () => { guides.value = []; options.personalChanged() })
watch(options.editable, editable => { if (!editable) { pointerCleanup?.(false); mode.value = 'pan'; guides.value = [] } })
watch(options.enabled, enabled => { if (!enabled) { pointerCleanup?.(false); guides.value = [] } })
/** 浏览器切后台未必触发窗口 blur;隐藏时同样撤销未结束的分区草稿。 */
function visibilityChanged() { if (document.hidden) pointerCleanup?.(false) }

View File

@ -0,0 +1,244 @@
import { computed, onActivated, onBeforeUnmount, onDeactivated, shallowReactive, shallowRef, watch, type Ref } from 'vue'
import { errorText } from '../../../api/errors'
import type { FlowLayout, FlowLayoutInput, FlowLayoutPositions, FlowLayoutSection, FlowView, Point } from '../../../types'
import { completeLayoutPositions, copyLayoutSections } from '../utils/sharedLayout'
interface SharedLayoutOptions {
userId: Readonly<Ref<number | string>>
projectId: Readonly<Ref<number>>
iterationId: Readonly<Ref<number | undefined>>
view: Readonly<Ref<FlowView>>
active: Readonly<Ref<boolean>>
manager: Readonly<Ref<boolean>>
interacting: Readonly<Ref<boolean>>
load: (projectId: number, iterationId: number) => Promise<FlowLayout>
save: (projectId: number, iterationId: number, input: FlowLayoutInput) => Promise<FlowLayout>
unsaved?: (message: string) => void
}
interface LayoutContext {
userId: number | string
projectId: number; iterationId?: number; version: number; positions: FlowLayoutPositions; sections: FlowLayoutSection[]
loaded: boolean; loading: boolean; saving: boolean; dirty: boolean; failure: string; conflict: boolean; serverCanEdit: boolean
revision: number; readEpoch: number; timer?: ReturnType<typeof setTimeout>; inFlight?: Promise<void>; baseline: string
}
// 仅保存本会话尚未被服务器确认的草稿;按登录用户隔离,绝不作为共享布局或本地持久化来源。
// 每份快照最多 5001 个阶段,限制保留 20 个范围,防止长期切换项目造成无界内存增长。
const unsavedDrafts = new Map<string, LayoutContext>()
/** 用户、项目和迭代组成恢复边界,其他登录用户不能读取或续发旧用户草稿。 */
function draftKey(context: Pick<LayoutContext, 'userId' | 'projectId' | 'iterationId'>): string {
return JSON.stringify([String(context.userId), context.projectId, context.iterationId])
}
/**
* 管理数据库布局草稿、合并防抖和独立版本的串行提交。
* @param options 固定业务范围、后端能力及传输方法;不接收本地缓存布局
* @returns 响应式草稿、状态与显式重试/重载入口;冲突草稿绝不自动套到新版本
* @remarks 队列捕获原范围,离页只完成已授权草稿,不向后来选中的迭代写入。
*/
export function useSharedFlowLayout(options: SharedLayoutOptions) {
const current = shallowRef(createContext())
const keptInactive = shallowRef(false)
let disposed = false
const positions = computed(() => current.value.positions)
const sections = computed({ get: () => current.value.sections, set: value => { current.value.sections = value } })
const dirty = computed(() => current.value.dirty), saving = computed(() => current.value.saving), loading = computed(() => current.value.loading)
const failure = computed(() => current.value.failure), conflict = computed(() => current.value.conflict)
const canEdit = computed(() => isVisible(current.value) && options.manager.value && current.value.loaded && current.value.serverCanEdit && !loading.value && !conflict.value)
// 撤权后保留未保存提示,但不让只读成员永远阻止工作区重新读取权限和业务摘要。
const blocksPolling = computed(() => loading.value || saving.value || dirty.value && options.manager.value && current.value.serverCanEdit)
const status = computed(() => loading.value ? '正在加载共享布局' : saving.value ? '正在保存共享布局' : failure.value ? failure.value : dirty.value ? '共享布局待保存' : current.value.loaded ? (current.value.serverCanEdit && options.manager.value ? current.value.version ? '共享布局已保存' : '共享布局已加载,修改后自动保存' : '共享布局只读') : '共享布局尚未加载')
/** 为每个项目/迭代创建独立队列,旧请求只能接触原对象。 */
function createContext(): LayoutContext {
const scope = { userId: options.userId.value, projectId: options.projectId.value, iterationId: options.iterationId.value }
const recovered = unsavedDrafts.get(draftKey(scope))
if (recovered) return recovered
return shallowReactive({ ...scope, version: 0, positions: {}, sections: [], loaded: false, loading: false, saving: false, dirty: false, failure: '', conflict: false, serverCanEdit: false, revision: 0, readEpoch: 0, baseline: '' })
}
/** 只登记未确认草稿,保存成功即移除;容量达到上限时明确提示最早草稿将不再可恢复。 */
function remember(context: LayoutContext): void {
const key = draftKey(context)
if (!context.dirty) { unsavedDrafts.delete(key); return }
unsavedDrafts.delete(key); unsavedDrafts.set(key, context)
if (unsavedDrafts.size > 20) {
const oldest = unsavedDrafts.keys().next().value
if (oldest) { unsavedDrafts.delete(oldest); options.unsaved?.('未保存的迭代过多,最早一份会话草稿已移除;请及时保存当前修改。') }
}
}
/** 读取回调仅在原范围仍显示时生效,KeepAlive 隐藏也属于离页。 */
function isVisible(context: LayoutContext): boolean {
return !disposed && current.value === context && options.active.value && !keptInactive.value
}
/** 内容指纹只比较共享字段,选择、视口、折叠及辅助开关均不参与脏状态。 */
function fingerprint(context: Pick<LayoutContext, 'positions' | 'sections'>): string {
return JSON.stringify({ positions: context.positions, sections: copyLayoutSections(context.sections) })
}
/** 清理尚未提交的合并定时器;在途请求仍由原范围队列负责结束。 */
function clearTimer(context: LayoutContext): void {
if (context.timer) clearTimeout(context.timer)
context.timer = undefined
}
/** 应用服务端已确认布局,不修改视口、选区、折叠或工作项抽屉。 */
function apply(context: LayoutContext, snapshot: FlowLayout): void {
context.version = snapshot.version
context.positions = completeLayoutPositions(options.view.value, snapshot.positions)
context.sections = copyLayoutSections(snapshot.sections)
context.serverCanEdit = snapshot.canEdit; context.loaded = true; context.dirty = false; context.failure = ''; context.conflict = false
context.baseline = fingerprint(context)
remember(context)
}
/**
* 接收已有十五秒轮询快照,同版本只复核权限,不重建同内容画布。
* @param snapshot 后端同项目/迭代布局;编辑或交互时保留本地草稿
* @returns 是否接收了新的布局内容
*/
function accept(snapshot: FlowLayout): boolean {
const context = current.value
if (!isVisible(context) || snapshot.version < context.version) return false
context.serverCanEdit = snapshot.canEdit
if (context.dirty || context.saving || context.loading || options.interacting.value || context.conflict) return false
if (context.loaded && snapshot.version === context.version) {
const complete = completeLayoutPositions(options.view.value, context.positions)
if (JSON.stringify(complete) !== JSON.stringify(context.positions)) { context.positions = complete; context.baseline = fingerprint(context) }
return false
}
apply(context, snapshot)
return true
}
/**
* 合并可见节点坐标,隐藏子阶段仍使用完整草稿;只接受最新摘要认识的节点。
* @param changed 本次可见节点位置,父级从已鉴权摘要取得
* @param nextSections 完整分区列表,默认使用当前工具草稿
*/
function update(changed: Record<string, Point>, nextSections = sections.value): void {
if (!canEdit.value) return
const context = current.value, combined = { ...context.positions }
const parents = new Map(options.view.value.stages.map(stage => ['s:' + stage.id, stage.parentStageId ?? null]))
parents.set('s:0', null)
for (const [id, point] of Object.entries(changed)) if (parents.has(id)) combined[id] = { x: point.x, y: point.y, parentStageId: parents.get(id) ?? null }
context.positions = completeLayoutPositions(options.view.value, combined)
context.sections = copyLayoutSections(nextSections)
context.dirty = fingerprint(context) !== context.baseline
context.revision++
context.failure = ''
remember(context)
clearTimer(context)
if (context.dirty) context.timer = setTimeout(() => { void flush(context) }, 500)
}
/**
* 同一范围只保留一个在途 PUT,响应仅推进版本,不覆盖期间产生的新草稿。
* @param context 提交起点捕获的原项目/迭代上下文,切换页面后不读取新范围
* @returns 当前串行队列完成;失败保留草稿,冲突必须显式重载
*/
async function flush(context = current.value): Promise<void> {
clearTimer(context)
if (String(options.userId.value) !== String(context.userId)) return
if (context.inFlight) {
await context.inFlight
if (isVisible(context) && context.dirty && !context.failure) await flush(context)
return
}
if (!context.dirty || context.conflict || !context.serverCanEdit || !context.iterationId) return
context.saving = true
/** 循环只使用捕获的原范围;新草稿在上一写入成功后以返回版本继续提交。 */
const run = async () => {
while (context.dirty && !context.conflict && context.serverCanEdit) {
const revision = context.revision
const input: FlowLayoutInput = { version: context.version, positions: Object.fromEntries(Object.entries(context.positions).map(([id, point]) => [id, { ...point }])), sections: copyLayoutSections(context.sections) }
try {
const snapshot = await options.save(context.projectId, context.iterationId!, input)
context.version = snapshot.version; context.serverCanEdit = snapshot.canEdit
context.baseline = fingerprint(input)
context.dirty = context.revision !== revision && fingerprint(context) !== context.baseline
context.failure = ''
remember(context)
// 卸载后不继续发起后续写入,避免登录会话已变化;同一用户返回原范围后可恢复并重试。
if (disposed || String(options.userId.value) !== String(context.userId)) {
if (context.dirty) context.failure = '离页前仍有共享布局修改未保存,请重试保存或重新加载共享布局。'
break
}
} catch (error) {
const code = typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : ''
context.conflict = ['FLOW_LAYOUT_VERSION_CONFLICT', 'FLOW_LAYOUT_STRUCTURE_CHANGED'].includes(code)
if (['403', 'FORBIDDEN', '401', 'UNAUTHORIZED', '404', 'NOT_FOUND'].includes(code)) context.serverCanEdit = false
context.failure = context.conflict ? '共享布局或阶段结构已变化,请重新加载共享布局后再编辑。' : '共享布局保存失败:' + errorText(error)
remember(context)
if (!isVisible(context)) options.unsaved?.(context.failure + ' 原项目/迭代的草稿尚未保存。')
break
}
}
}
context.inFlight = run()
try { await context.inFlight } finally { context.inFlight = undefined; context.saving = false }
}
/** 短暂失败显式重试原版本;冲突禁止重试旧完整快照,防止覆盖其他管理者。 */
async function retry(): Promise<void> {
if (!isVisible(current.value) || current.value.conflict) return
if (!current.value.loaded) { await reload(); return }
if (!options.manager.value || !current.value.serverCanEdit) return
await flush()
}
/** 显式重载由组件先确认丢弃草稿;读取失败时仍保留原草稿和版本。 */
async function reload(): Promise<void> {
const context = current.value
if (!isVisible(context) || !context.iterationId) return
clearTimer(context)
if (context.inFlight) await context.inFlight
const epoch = ++context.readEpoch
context.loading = true
try {
const snapshot = await options.load(context.projectId, context.iterationId)
if (isVisible(context) && epoch === context.readEpoch) apply(context, snapshot)
} catch (error) {
if (isVisible(context) && epoch === context.readEpoch) context.failure = '共享布局加载失败:' + errorText(error)
} finally { if (current.value === context && epoch === context.readEpoch) context.loading = false }
}
/** 离页立即提交捕获范围的草稿,阻止防抖取消造成静默丢失;不把任何布局存进浏览器。 */
function leave(): void {
const context = current.value
context.readEpoch++; context.loading = false
if (context.dirty) {
remember(context)
if (context.failure || context.conflict || String(options.userId.value) !== String(context.userId)) options.unsaved?.('共享布局尚未保存,草稿保留在当前会话;返回原迭代后可重试或重新加载。')
else { options.unsaved?.('共享布局尚未保存,正在提交原项目/迭代草稿;若失败,请返回流程页处理。'); void flush(context) }
}
}
/** 刷新或关闭浏览器可能中断网络请求,未确认的共享草稿必须提示用户。 */
function beforeUnload(event: BeforeUnloadEvent): void {
if (!current.value.dirty && !current.value.saving) return
void flush(); event.preventDefault(); event.returnValue = ''
}
watch(() => [options.userId.value, options.projectId.value, options.iterationId.value], () => {
leave(); current.value = createContext()
if (options.view.value.layout) accept(options.view.value.layout)
else void reload()
})
watch(options.view, view => {
if (view.layout) accept(view.layout)
else if (!current.value.loaded && !current.value.loading) void reload()
}, { immediate: true })
watch(options.interacting, interacting => { if (!interacting && options.view.value.layout) accept(options.view.value.layout) })
watch(options.manager, manager => { if (!manager) { clearTimer(current.value); current.value.serverCanEdit = false } })
watch(options.active, active => { if (!active) leave(); else if (!current.value.loaded) void reload(); else if (options.view.value.layout) accept(options.view.value.layout) })
onDeactivated(() => { leave(); keptInactive.value = true })
onActivated(() => { keptInactive.value = false; if (!current.value.loaded) void reload(); else if (options.view.value.layout) accept(options.view.value.layout) })
window.addEventListener('beforeunload', beforeUnload)
onBeforeUnmount(() => { leave(); disposed = true; window.removeEventListener('beforeunload', beforeUnload) })
return { positions, sections, canEdit, dirty, saving, loading, failure, conflict, status, blocksPolling, accept, update, retry, reload, flush }
}

View File

@ -1,7 +1,7 @@
import type { Point } from '../../../types'
import type { FlowLayoutSection, Point } from '../../../types'
export interface CanvasBox extends Point { id: string; width: number; height: number; parentNode?: string }
export interface CanvasSection extends CanvasBox { name: string }
export type CanvasSection = FlowLayoutSection
export interface CanvasGuide { x1: number; y1: number; x2: number; y2: number; kind: 'alignment' | 'distance'; label?: string }
export type ArrangeAction = 'left' | 'center-x' | 'right' | 'top' | 'center-y' | 'bottom' | 'distribute-x' | 'distribute-y'

View File

@ -19,10 +19,10 @@ export function workItemHeight(item: WorkItem, childCount = 0): number { const c
/**
* 先布局子画布,再以实际外框布局根画布;同一 Vue Flow 的父子节点使用相对坐标。
* 展开、折叠和拖动均是浏览器展示偏好,不参与同层执行关系或后端状态计算。
* 坐标由数据库共享布局提供,展开折叠属于个人偏好,二者均不改变业务执行规则。
* 连线区分实际完成与开始放行,仅使用服务端当前版本事实,不能由节点 IN_PROGRESS 推断。
* @param view 完整的已鉴权阶段树和同层边,工作项数量来自服务端摘要
* @param positions 浏览器坐标;子节点坐标以父外框左上角为原点
* @param positions 已按真实父级筛选的共享坐标;子节点坐标以父框左上角为原点
* @param collapsed 已折叠的阶段组ID,内部节点及连线不渲染
* @returns 按父级在前顺序生成的节点与执行/回退边
*/

View File

@ -1,39 +1,39 @@
import type { Point } from '../../../types'
import { sanitizeSections, type CanvasSection } from './canvasGeometry'
/** 个人浏览状态与数据库布局分离,坐标和分区不再写入本机。 */
export interface FlowPreferences {
sections?: CanvasSection[]
guidesEnabled?: boolean
parents?: Record<string, number | null>
collapsedStages: number[]
positions: Record<string, Point>
viewport: (Point & { zoom: number }) | null
}
// 两层节点使用相对坐标,旧平铺坐标不能直接解释为子节点位置。
const VERSION = 2
/** 新旧键分开,旧布局保留以便必要时人工恢复,不自动导入数据库。 */
function key(userId: number | string, projectId: number, iterationId?: number, legacy = false): string {
return `${legacy ? 'pm-flow-view' : 'pm-flow-personal'}:${userId}:${projectId}${iterationId ? `:${iterationId}` : ''}`
}
/** 按登录用户、项目和迭代分隔浏览器偏好,避免同设备或同项目串用画布状态。 */
function key(userId: number | string, projectId: number, iterationId?: number): string { return `pm-flow-view:${userId}:${projectId}${iterationId ? `:${iterationId}` : ""}` }
/** 显式投影个人字段,旧缓存坐标、分区及额外字段均不进入新存储。 */
function personalFields(value: unknown): FlowPreferences | null {
if (!value || typeof value !== 'object') return null
const source = value as Partial<FlowPreferences>
if (!Array.isArray(source.collapsedStages)) return null
const collapsedStages = source.collapsedStages.filter(id => Number.isSafeInteger(id) && id >= 0)
const point = source.viewport
const viewport = point && Number.isFinite(point.x) && Number.isFinite(point.y) && Number.isFinite(point.zoom) && point.zoom > 0 ? { x: point.x, y: point.y, zoom: point.zoom } : null
return { collapsedStages, viewport, guidesEnabled: source.guidesEnabled !== false }
}
/** 兼容旧格式坐标并校验新增分区和辅助开关;本地内容不参与阶段、工作项或权限判断。 */
/** 新键不存在时只读取旧视口、折叠与辅助开关;不迁移旧布局。 */
export function readFlowPreferences(userId: number | string, projectId: number, iterationId?: number): FlowPreferences | null {
try {
const raw = localStorage.getItem(key(userId, projectId, iterationId))
if (!raw) return null
const value: unknown = JSON.parse(raw)
if (!value || typeof value !== 'object' || ![1, VERSION].includes(Number((value as { version?: unknown }).version))) return null
const source = value as Partial<FlowPreferences>
if (!Array.isArray(source.collapsedStages) || !source.positions || typeof source.positions !== 'object') return null
const collapsedStages = source.collapsedStages.filter(id => Number.isSafeInteger(id) && id >= 0)
const positions = Object.fromEntries(Object.entries(source.positions).filter(([id, point]) => /^(s|w):\d+$/.test(id) && Number.isFinite(point?.x) && Number.isFinite(point?.y)).map(([id, point]) => [id, { x: point.x, y: point.y }]))
const viewport = source.viewport && Number.isFinite(source.viewport.x) && Number.isFinite(source.viewport.y) && Number.isFinite(source.viewport.zoom) && source.viewport.zoom > 0 ? { x: source.viewport.x, y: source.viewport.y, zoom: source.viewport.zoom } : null
const parents = Object.fromEntries(Object.entries(source.parents || {}).filter(([id, parent]) => /^s:\d+$/.test(id) && (parent === null || Number.isSafeInteger(parent) && parent > 0)))
return { collapsedStages, positions, viewport, parents, sections: sanitizeSections(source.sections), guidesEnabled: source.guidesEnabled !== false }
const raw = localStorage.getItem(key(userId, projectId, iterationId)) ?? localStorage.getItem(key(userId, projectId, iterationId, true))
return raw ? personalFields(JSON.parse(raw)) : null
} catch { return null }
}
/** 只写当前用户的浏览器存储;隐私模式或容量不足时保留内存中的交互结果。 */
/** 只写个人字段;浏览器禁止存储时仍保留当前内存展示,不冒充共享保存成功。 */
export function writeFlowPreferences(userId: number | string, projectId: number, preference: FlowPreferences, iterationId?: number): void {
try { localStorage.setItem(key(userId, projectId, iterationId), JSON.stringify({ version: VERSION, ...preference })) } catch { /* 浏览器禁用存储时仍允许本次会话操作画布。 */ }
const personal = personalFields(preference)
if (!personal) return
try { localStorage.setItem(key(userId, projectId, iterationId), JSON.stringify({ version: 1, ...personal })) } catch { /* 本地偏好不可用不影响数据库布局。 */ }
}

View File

@ -0,0 +1,22 @@
import type { FlowLayoutPositions, FlowLayoutSection, FlowView } from '../../../types'
import { buildFlowGraph } from './graph'
/**
* 按完整展开图补齐缺失位置,并排除已删除或已换父级的旧位置。
* @param view 服务端最新业务阶段摘要,父级以该摘要为准
* @param saved 当前共享坐标;不接受不携带父级的旧浏览器布局
* @returns 全部有效阶段的确定性坐标,个人折叠不会影响默认排版
*/
export function completeLayoutPositions(view: FlowView, saved: FlowLayoutPositions): FlowLayoutPositions {
const parents = new Map(view.stages.map(stage => ['s:' + stage.id, stage.parentStageId ?? null]))
parents.set('s:0', null)
const valid = Object.fromEntries(Object.entries(saved).filter(([id, point]) => parents.has(id) && point.parentStageId === parents.get(id) && Number.isFinite(point.x) && Number.isFinite(point.y)))
const graph = buildFlowGraph(view, valid, [])
// 隐藏子节点仍在完整快照中;不能用部分可见节点覆盖服务器布局。
return Object.fromEntries(graph.nodes.map(node => [node.id, { x: node.position.x, y: node.position.y, parentStageId: parents.get(node.id) ?? null }]))
}
/** 显式投影持久化字段,避免把 Vue Flow 展示属性混入严格接口。 */
export function copyLayoutSections(sections: FlowLayoutSection[]): FlowLayoutSection[] {
return sections.map(({ id, name, x, y, width, height }) => ({ id, name, x, y, width, height }))
}