From c100721ecf65b8ece15976b812de8f376c42ad6b Mon Sep 17 00:00:00 2001 From: zhanghao <774378400@qq.com> Date: Wed, 28 Oct 2026 13:51:08 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20=E8=BF=AD=E4=BB=A3=E6=93=8D?= =?UTF-8?q?=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ruoyi-project/sql/project_collaboration.sql | 4 +- .../sql/upgrade/024_custom_stage_node.sql | 12 +++++ .../manage/controller/PmStageController.java | 4 ++ .../project/manage/domain/StageNodeType.java | 2 +- .../project/manage/dto/StageNameInput.java | 4 ++ .../manage/service/IPmStageService.java | 3 ++ .../service/impl/PmStageServiceImpl.java | 21 +++++++++ .../src/views/project/manage/README.md | 10 ++++- .../src/views/project/manage/api/stages.ts | 2 + .../components/IterationControls.vue | 24 ++++++---- .../stages/components/StageManager.vue | 19 +------- .../stages/components/StageRenameDialog.vue | 43 ++++++++++++++++++ .../manage/features/stages/utils/actions.ts | 32 ++++++++++++++ .../manage/shared/constants/stageNodeTypes.ts | 1 + .../src/views/project/manage/types/stage.ts | 2 +- .../project/manage/views/flow/WorkFlow.vue | 44 ++++++++++++++++--- .../views/flow/components/FlowStageNode.vue | 10 +++-- 17 files changed, 196 insertions(+), 41 deletions(-) create mode 100644 ruoyi-project/sql/upgrade/024_custom_stage_node.sql create mode 100644 ruoyi-project/src/main/java/com/ruoyi/project/manage/dto/StageNameInput.java create mode 100644 ruoyi-ui-vue3/src/views/project/manage/features/stages/components/StageRenameDialog.vue create mode 100644 ruoyi-ui-vue3/src/views/project/manage/features/stages/utils/actions.ts diff --git a/ruoyi-project/sql/project_collaboration.sql b/ruoyi-project/sql/project_collaboration.sql index 08d1fde..e4c5eb4 100644 --- a/ruoyi-project/sql/project_collaboration.sql +++ b/ruoyi-project/sql/project_collaboration.sql @@ -573,10 +573,10 @@ CREATE TABLE pm_collab_stage_revision_member ( -- 画布分类固定于阶段身份,不随执行版本变化;历史普通阶段使用 STAGE。 ALTER TABLE pm_collab_project_stage - ADD COLUMN node_type VARCHAR(24) NOT NULL DEFAULT 'STAGE' COMMENT '固定节点类型:GROUP阶段组,REQUIREMENT需求,PROPOSAL方案,PURCHASE采购,DESIGN设计,MACHINING加工,ASSEMBLY组装,DEBUGGING调试,DEVELOPMENT研发,TESTING测试,STAGE历史普通阶段', + ADD COLUMN node_type VARCHAR(24) NOT NULL DEFAULT 'STAGE' COMMENT '固定节点类型:GROUP阶段组,REQUIREMENT需求,PROPOSAL方案,PURCHASE采购,DESIGN设计,MACHINING加工,ASSEMBLY组装,DEBUGGING调试,DEVELOPMENT研发,TESTING测试,CUSTOM自定义,STAGE历史普通阶段', ADD CONSTRAINT ck_pm_stage_node_type CHECK ( (node_type='GROUP' AND stage_kind='GROUP') OR - (node_type IN ('STAGE','REQUIREMENT','PROPOSAL','PURCHASE','DESIGN','MACHINING','ASSEMBLY','DEBUGGING','DEVELOPMENT','TESTING') AND stage_kind='WORK') + (node_type IN ('STAGE','REQUIREMENT','PROPOSAL','PURCHASE','DESIGN','MACHINING','ASSEMBLY','DEBUGGING','DEVELOPMENT','TESTING','CUSTOM') AND stage_kind='WORK') ); -- 阶段版本交付、人工完成审批及采购批次引用。 diff --git a/ruoyi-project/sql/upgrade/024_custom_stage_node.sql b/ruoyi-project/sql/upgrade/024_custom_stage_node.sql new file mode 100644 index 0000000..26fa51a --- /dev/null +++ b/ruoyi-project/sql/upgrade/024_custom_stage_node.sql @@ -0,0 +1,12 @@ +-- 项目协作:新增自定义工作阶段分类。023 后执行,可重复执行;不修改历史类型或执行事实。 +SET NAMES utf8mb4; +SET @pm_custom_check_exists=(SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA=DATABASE() AND TABLE_NAME='pm_collab_project_stage' AND CONSTRAINT_NAME='ck_pm_stage_node_type'); +-- 在同一 ALTER 内替换分类约束和补充中文注释,避免存在无类型校验的中间状态。 +SET @pm_custom_ddl=CONCAT('ALTER TABLE pm_collab_project_stage ', + IF(@pm_custom_check_exists>0,'DROP CHECK ck_pm_stage_node_type, ',''), + 'MODIFY COLUMN node_type VARCHAR(24) NOT NULL DEFAULT ''STAGE'' COMMENT ''固定节点类型:GROUP阶段组,REQUIREMENT需求,PROPOSAL方案,PURCHASE采购,DESIGN设计,MACHINING加工,ASSEMBLY组装,DEBUGGING调试,DEVELOPMENT研发,TESTING测试,CUSTOM自定义,STAGE历史普通阶段'', ', + 'ADD CONSTRAINT ck_pm_stage_node_type CHECK ((node_type=''GROUP'' AND stage_kind=''GROUP'') OR (node_type IN (''STAGE'',''REQUIREMENT'',''PROPOSAL'',''PURCHASE'',''DESIGN'',''MACHINING'',''ASSEMBLY'',''DEBUGGING'',''DEVELOPMENT'',''TESTING'',''CUSTOM'') AND stage_kind=''WORK''))'); +PREPARE pm_custom_stmt FROM @pm_custom_ddl; +EXECUTE pm_custom_stmt; +DEALLOCATE PREPARE pm_custom_stmt; diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageController.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageController.java index 104641b..60a88fa 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageController.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageController.java @@ -2,6 +2,7 @@ package com.ruoyi.project.manage.controller; import com.ruoyi.project.manage.dto.StageAssignment; import com.ruoyi.project.manage.dto.StageInput; +import com.ruoyi.project.manage.dto.StageNameInput; import com.ruoyi.project.manage.dto.StageEdgeInput; import com.ruoyi.project.manage.dto.VersionInput; import com.ruoyi.project.manage.exception.PmException; @@ -38,6 +39,9 @@ public class PmStageController { /** 阶段版本与所属迭代状态均在统一项目锁内检查。 */ @PatchMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}") public Map iterationEdit(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) { service.editStage(id,iterationId,stageId,decode(body,StageInput.class)); return ok(null); } + /** 快捷改名严格只接受名称和版本;身份、归属、生命周期与冻结状态仍在服务事务中复查。 */ + @PatchMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}/name") + public Map iterationRename(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) { service.renameStage(id,iterationId,stageId,decode(body,StageNameInput.class)); return ok(null); } /** 仅当前迭代的空阶段可软删除,保留原版本记录。 */ @DeleteMapping("/projects/{id}/iterations/{iterationId}/stages/{stageId}") public Map iterationDelete(@PathVariable long id,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) { service.deleteStage(id,iterationId,stageId,decode(body,VersionInput.class)); return ok(null); } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/domain/StageNodeType.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/domain/StageNodeType.java index 62d1999..4302faf 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/domain/StageNodeType.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/domain/StageNodeType.java @@ -4,7 +4,7 @@ import com.ruoyi.project.manage.exception.PmException; /** 画布节点的固定业务类型;仅 GROUP 承载子阶段,其余类型共用工作阶段的执行规则。 */ public enum StageNodeType { - GROUP, REQUIREMENT, PROPOSAL, PURCHASE, DESIGN, MACHINING, ASSEMBLY, DEBUGGING, DEVELOPMENT, TESTING, STAGE; + GROUP, REQUIREMENT, PROPOSAL, PURCHASE, DESIGN, MACHINING, ASSEMBLY, DEBUGGING, DEVELOPMENT, TESTING, CUSTOM, STAGE; /** 将分类映射为既有结构类型,返回 GROUP 容器或 WORK 工作阶段,不改变执行和排期规则。 */ public String kind() { return this == GROUP ? "GROUP" : "WORK"; } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/dto/StageNameInput.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/dto/StageNameInput.java new file mode 100644 index 0000000..a4ee972 --- /dev/null +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/dto/StageNameInput.java @@ -0,0 +1,4 @@ +package com.ruoyi.project.manage.dto; + +/** 画布快捷改名白名单;不接收类型、负责人、采购范围或排期,防止改名覆盖其他业务信息。 */ +public record StageNameInput(String name, Integer version) { } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/IPmStageService.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/IPmStageService.java index be112ca..ca56f7d 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/IPmStageService.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/IPmStageService.java @@ -3,6 +3,7 @@ package com.ruoyi.project.manage.service; import com.ruoyi.project.manage.exception.PmException; import com.ruoyi.project.manage.dto.StageAssignment; import com.ruoyi.project.manage.dto.StageInput; +import com.ruoyi.project.manage.dto.StageNameInput; import com.ruoyi.project.manage.dto.StageEdgeInput; import com.ruoyi.project.manage.dto.VersionInput; @@ -43,6 +44,8 @@ public interface IPmStageService { *

副作用:按阶段版本修改组织元数据并原子保存历史/outbox。

*/ void editStage(long projectId,long iterationId,long id,StageInput input); + /** 仅按版本更新当前有效阶段名称;沿用经理权限、迭代只读及审批冻结门禁,不覆盖交付和历史快照。 */ + void renameStage(long projectId,long iterationId,long id,StageNameInput input); /** 旧编辑入口缺少迭代边界时拒绝执行。 */ default void editStage(long projectId,long id,StageInput input) { throw requiredIteration(); } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageServiceImpl.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageServiceImpl.java index d38fe25..5f73e4b 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageServiceImpl.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageServiceImpl.java @@ -3,6 +3,7 @@ package com.ruoyi.project.manage.service.impl; import com.ruoyi.project.manage.dto.StageAssignment; import com.ruoyi.project.manage.dto.StageEdgeInput; import com.ruoyi.project.manage.dto.StageInput; +import com.ruoyi.project.manage.dto.StageNameInput; import com.ruoyi.project.manage.dto.VersionInput; import com.ruoyi.project.manage.exception.PmException; import com.ruoyi.project.manage.domain.Graph; @@ -179,6 +180,26 @@ public class PmStageServiceImpl implements IPmStageService { auditService.record(projectId,iterationId,null,"STAGE_EDITED",map("stageId",id,"name",input.name().trim()),access.actor()); } + /** + * 仅更新当前阶段名称,兼容历史未设置负责人的节点;不借快捷入口改动交付或固定类型。 + * @param projectId 阶段所属协作项目,管理权限在项目锁前后复查 + * @param iterationId 明确的可写迭代范围 + * @param id 当前有效阶段标识 + * @param input 名称及预期阶段版本;空名称、过期版本和已冻结版本均拒绝 + * 注意:项目锁覆盖版本检查、名称写入及定义快照/审计;历史执行快照不随改名重写。 + */ + public void renameStage(long projectId,long iterationId,long id,StageNameInput input) { + locked(projectId,iterationId,"admin"); + Map existing=stage(projectId,iterationId,id); + if(input==null||input.name()==null||input.name().isBlank()||input.name().trim().length()>120) throw PmException.bad("阶段名称需为 1—120 个字符"); + version(input.version(),(int)number(existing,"version")); + PmStageRules.requireDeliveryMutable(graphService.load(projectId,iterationId),id); + stageMapper.updateStage(id,(int)number(existing,"version"),map("name",input.name().trim())); + groups.bind(projectId,iterationId); + snapshotDefinition(projectId,iterationId); + auditService.record(projectId,iterationId,null,"STAGE_EDITED",map("stageId",id,"name",input.name().trim()),access.actor()); + } + /** 非空阶段拒绝删除;空阶段的连线先移除,再软删阶段并原子保存历史与事件。 */ public void deleteStage(long projectId,long iterationId,long id,VersionInput input) { locked(projectId,iterationId,"admin"); Map existing=stage(projectId,iterationId,id); version(input.version(),(int)number(existing,"version")); diff --git a/ruoyi-ui-vue3/src/views/project/manage/README.md b/ruoyi-ui-vue3/src/views/project/manage/README.md index 31871eb..b7c263a 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/README.md +++ b/ruoyi-ui-vue3/src/views/project/manage/README.md @@ -57,14 +57,22 @@ manage/ ## 工作项分工与前置条件 - 阶段节点展示已有描述的两行摘要,完整说明在阶段抽屉查看;拖入新阶段时可填写描述。 -- 流程画布左侧节点库提供阶段组、需求、方案、采购、设计、加工、组装、调试、研发和测试,支持搜索与拖放。普通类型拖入组内(包括子节点上方)自动归属,组本身仍只支持根画布;未执行及历史保护规则保持不变。 +- 流程画布左侧节点库提供阶段组、需求、方案、采购、设计、加工、组装、调试、研发、测试和自定义,支持搜索与拖放。普通类型拖入组内(包括子节点上方)自动归属,组本身仍只支持根画布;未执行及历史保护规则保持不变。自定义类型按普通工作阶段要求交付齐备后提审,不支持承载子阶段。 - 节点分类创建后固定,名称、负责人和说明可编辑;只有阶段组承载子阶段,其余分类沿用工作阶段规则。组内快捷创建可在提交前选择工作分类;复制迭代保留来源分类,回退换版沿用同一节点身份。 - 已有数据库上线前执行 `ruoyi-project/sql/upgrade/022_stage_node_types.sql`;脚本可重复执行,已有工作阶段标为普通阶段,已有组标为阶段组,不改动排期、执行版本或工作项。新安装结构已包含分类字段和组合约束。 +- 已完成 023 的数据库执行 `ruoyi-project/sql/upgrade/024_custom_stage_node.sql` 开放自定义类型;该升级只扩展类型约束及中文字段注释,不转换历史节点分类。 +- 项目管理者可通过节点名称后的编辑图标快捷改名,接口只接收名称和阶段版本;审批中或已完成版本仍只读。节点右上角删除图标与阶段管理表共用保护条件,已有执行历史、工作项、子阶段、交付附件或采购批次时禁用并说明原因,后端仍持锁复验后软删除。 - 新建和编辑工作项可从项目成员中多选协作人,负责人仍为单选。协作分工不改变项目角色或访问权限,历史版本保留原分工;回退复制仅继承仍有效的成员,并在预览中说明移除项。 - 新建工作项可选多个同迭代前置工作项,需求、任务、缺陷均可作为依赖两端。所有前置已完成或已关闭才满足条件,取消不满足;编辑依赖仍使用详情中的专用入口。 - 依赖、工作项和协作分工在同一项目锁事务中保存,继续共用实际开始、排期及混合执行图环检测。新建表单排期提示由后端约束预览计算,提交时重新验证。 - 已有数据库先完成 `ruoyi-project/sql/upgrade/016_work_item_collaboration.sql` 增量升级;该文件新增协作人关联表并兼容新旧依赖标识,保留已有工作项与排期。全新环境使用 `ruoyi-project/sql/project_collaboration.sql`。 +## 迭代操作 + +- 项目管理者在迭代工具栏直接编辑、开始、结束或删除当前迭代,更多操作使用点击菜单;普通成员不能管理迭代。归档及终态迭代的编辑入口禁用,可先取消归档或重新打开。 +- 筹备迭代由管理者手动开始并记录实际开始时间;执行中由管理者预览、确认结束并记录实际结束时间,不根据预计日期自动切换状态。待开始或进行中的工作项阻止结束,取消工作项或未审批阶段须逐条确认异常并说明原因后才能带异常结束。 +- 删除仅适用于从未执行且没有任何工作项或执行历史的筹备迭代,后端软删除并保留审计;已执行迭代通过结束、取消、归档保留历史。 + ## 甘特成员筛选 - 甘特排期的成员下拉支持多选当前项目成员;清空表示全部,多选按负责人或协作人任一匹配取并集,同一工作项只显示一次。 diff --git a/ruoyi-ui-vue3/src/views/project/manage/api/stages.ts b/ruoyi-ui-vue3/src/views/project/manage/api/stages.ts index dea16ef..cc8c2a4 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/api/stages.ts +++ b/ruoyi-ui-vue3/src/views/project/manage/api/stages.ts @@ -30,6 +30,8 @@ export const stageApi = { removeStageEdge: (id: number, edgeId: number, version: number, iterationId?: number) => request('delete', iterationPath(id, iterationId, `stage-edges/${edgeId}`), { version }), /** 阶段元数据独立版本更新,不调整任务状态或排期。 */ editStage: (id: number, stageId: number, input: StageInput, iterationId?: number) => request('patch', iterationPath(id, iterationId, `stages/${stageId}`), input), + /** 画布快捷改名只传名称及当前版本,不能借此改动交付数据或固定类型。 */ + renameStage: (id: number, stageId: number, name: string, version: number, iterationId?: number) => request('patch', iterationPath(id, iterationId, `stages/${stageId}/name`), { name, version }), /** 非空阶段由后端拒绝;空阶段软删除保留历史。 */ removeStage: (id: number, stageId: number, version: number, iterationId?: number) => request('delete', iterationPath(id, iterationId, `stages/${stageId}`), { version }), } diff --git a/ruoyi-ui-vue3/src/views/project/manage/features/iterations/components/IterationControls.vue b/ruoyi-ui-vue3/src/views/project/manage/features/iterations/components/IterationControls.vue index 7acfe82..dec3bc4 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/features/iterations/components/IterationControls.vue +++ b/ruoyi-ui-vue3/src/views/project/manage/features/iterations/components/IterationControls.vue @@ -5,15 +5,17 @@ {{ iterationStatusNames[selected.status] }}{{ selected.archivedAt ? ' · 已归档' : '' }} {{ selected.finishResult === 'COMPLETED' ? '正常完成' : '带异常结束' }} 新建迭代 - 迭代操作 @@ -80,6 +80,7 @@ import ItemScheduleDialog from '../../schedules/components/ItemScheduleDialog.vu import PredecessorPicker from './PredecessorPicker.vue' import type { WorkItem, Member, Condition, Lifecycle, StageEdge, Stage, PredecessorOption } from '../../../types' import { typeNames, priorityNames, statusNames, actionNames, itemStatusLabel } from '../../../shared/constants/labels' +import { ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_SIZE_LABEL } from '../../../shared/constants/attachments' const lifecycleLabels: Record = statusNames const props = withDefaults(defineProps<{ projectId?: number; iterationId?: number; canExecute?: boolean; id: number | null; refreshKey: number; items: WorkItem[]; members: Member[]; canWrite: boolean; canManage?: boolean; stages?: Stage[]; stageEdges?: StageEdge[] }>(), { stages: () => [], stageEdges: () => [], canExecute: true }) @@ -207,13 +208,13 @@ async function comment() { const itemId = detail.value.id, body = commentText.value await action(() => api.comment(itemId, body), true, () => { if (commentText.value === body) commentText.value = '' }) } -/** 选择文件时固定所属工作项,大小检查后通过统一动作上传;清空 input 以允许重试同一文件。 */ +/** 选择文件时固定所属工作项,按协作统一的 50MB 上限检查后上传;清空 input 以允许重试同一文件。 */ async function upload(event: Event) { const input = event.target as HTMLInputElement, file = input.files?.[0] if (!file || !detail.value) return const itemId = detail.value.id - if (file.size > 10 * 1024 * 1024) { - ElMessage.error('附件不能超过 10 MiB'); input.value = ''; return + if (file.size > ATTACHMENT_MAX_BYTES) { + ElMessage.error(`附件不能超过 ${ATTACHMENT_MAX_SIZE_LABEL}`); input.value = ''; return } await action(() => api.upload(itemId, file)) input.value = '' diff --git a/ruoyi-ui-vue3/src/views/project/manage/shared/constants/attachments.ts b/ruoyi-ui-vue3/src/views/project/manage/shared/constants/attachments.ts new file mode 100644 index 0000000..f9cea0e --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/shared/constants/attachments.ts @@ -0,0 +1,4 @@ +// 与后端及 Spring multipart 的 50MB 上限一致,按 1024 进位;两个上传入口共用,避免提示与校验不一致。 +const ATTACHMENT_MAX_MB = 50 +export const ATTACHMENT_MAX_BYTES = ATTACHMENT_MAX_MB * 1024 * 1024 +export const ATTACHMENT_MAX_SIZE_LABEL = `${ATTACHMENT_MAX_MB}MB` diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/WorkFlow.vue b/ruoyi-ui-vue3/src/views/project/manage/views/flow/WorkFlow.vue index 5156c2f..2944c12 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/views/flow/WorkFlow.vue +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/WorkFlow.vue @@ -1,22 +1,39 @@ + diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowSectionNode.vue b/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowSectionNode.vue new file mode 100644 index 0000000..714132a --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/components/FlowSectionNode.vue @@ -0,0 +1,33 @@ + + + diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/composables/useCanvasGestureCleanup.ts b/ruoyi-ui-vue3/src/views/project/manage/views/flow/composables/useCanvasGestureCleanup.ts index ac12364..2c1c431 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/views/flow/composables/useCanvasGestureCleanup.ts +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/composables/useCanvasGestureCleanup.ts @@ -4,9 +4,10 @@ import { onBeforeUnmount, onMounted, watch, type ComputedRef } from 'vue' * 在画布鼠标手势被窗口切换或弹窗中断时,释放 Vue Flow 的浏览器拖放拦截。 * @param gestureActive 仅当前画布的节点拖动或画布平移状态,不包含节点库的原生拖放 * @param interrupted 画布隐藏或对话框打开时为 true,停止继续接收当前画布手势 + * @param cancelSelection 可选的框选清理;Vue Flow 的指针框选不会触发 D3 的 mouseup,需要另行复位 * @returns 可在再次操作节点库前调用的清理函数;不改动节点业务数据 */ -export function useCanvasGestureCleanup(gestureActive: ComputedRef, interrupted: ComputedRef) { +export function useCanvasGestureCleanup(gestureActive: ComputedRef, interrupted: ComputedRef, cancelSelection?: () => void) { let pointer = { x: 0, y: 0 }, finishing = false, suppressInterruptedClick = false /** 仅记录坐标,不捕获或阻止事件,使鼠标释放仍由 Vue Flow 自己处理。 */ @@ -28,6 +29,7 @@ export function useCanvasGestureCleanup(gestureActive: ComputedRef, int * 升级 Vue Flow 后,若其已自行处理失焦和隐藏时的手势释放,可重新验证并移除此兼容处理。 */ function finishCanvasGesture() { + cancelSelection?.() if (!gestureActive.value || finishing) return finishing = true; suppressInterruptedClick = true try { window.dispatchEvent(new MouseEvent('mouseup', { view: window, bubbles: true, buttons: 0, clientX: pointer.x, clientY: pointer.y })) } diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/composables/useCanvasTools.ts b/ruoyi-ui-vue3/src/views/project/manage/views/flow/composables/useCanvasTools.ts new file mode 100644 index 0000000..81e92ca --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/composables/useCanvasTools.ts @@ -0,0 +1,244 @@ +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 { 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' + +interface CanvasToolsOptions { + nodes: Readonly[]>> + viewport: Readonly> + enabled: Readonly> + toFlow: (point: Point) => Point + changed: () => void +} + +/** + * 管理纯展示的分区、框选排版和拖动辅助,不调用业务接口或改变阶段父子关系。 + * @param options 当前 Vue Flow 实例、坐标转换及本地保存回调;不得传入其他项目画布的节点 + * @returns 工具状态与事件处理器;浏览器手势监听在结束、失焦、页签隐藏和卸载时释放 + */ +export function useCanvasTools(options: CanvasToolsOptions) { + const sections = ref([]), guidesEnabled = ref(true), guides = ref([]) + const mode = ref<'pan' | 'select' | 'section'>('pan'), draft = ref(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) + let pointerCleanup: ((commit: boolean) => void) | null = null + let dragActive = false + let carried: { id: string; sectionId: string; position: Point; origin: Point }[] = [] + const carriedChildren = new Map() + + /** 同层排版用相对矩形;辅助线另取绝对坐标,不能混用这两个坐标空间。 */ + function localBox(node: Node): CanvasBox { + const rect = absoluteRectangle(node, []) + return { ...rect, id: node.id, parentNode: node.parentNode } + } + + /** 根选区整体与兄弟节点比较,父节点已选中时排除其子节点,避免吸附到自己的内容。 */ + function dragBoxes(event: NodeDragEvent): CanvasBox[] { + return selectionRoots(event.nodes.filter(node => !carriedChildren.has(node.id)).map(node => ({ ...absoluteRectangle(node, options.nodes.value), id: node.id, parentNode: node.parentNode }))) + } + + /** 拖动分区时在起点确定内部根节点,整个手势不重新收集,防止途经节点被意外带走。 */ + function startDrag(event: NodeDragEvent) { + dragActive = true + captureSectionContents(event.nodes) + } + + /** 鼠标和键盘共用起点包含关系;已在本次移动集合中的根节点由调用方移动,不能重复携带。 */ + function captureSectionContents(moving: GraphNode[]) { + carried = []; carriedChildren.clear() + const moved = new Set(moving.map(node => node.id)), captured = new Set() + for (const sectionNode of moving.filter(node => node.type === 'section')) { + const area = { ...absoluteRectangle(sectionNode, options.nodes.value), id: sectionNode.id } + for (const node of options.nodes.value) { + if (node.type === 'section' || moved.has(node.id) || captured.has(node.id) || !containsBox(area, { ...absoluteRectangle(node, options.nodes.value), id: node.id, parentNode: node.parentNode })) continue + carried.push({ id: node.id, sectionId: sectionNode.id, position: { ...node.position }, origin: { ...sectionNode.position } }); captured.add(node.id) + } + } + // 选区包含分区及其组内子阶段时,组会被分区整体携带;子阶段必须保留起点相对坐标,不能再直接位移。 + for (const node of moving) if (node.parentNode && captured.has(node.parentNode)) carriedChildren.set(node.id, { ...node.position }) + } + + /** 每次鼠标移动按当前缩放吸附整个选区,再按分区起点补偿内部节点;松手时须再调用一次。 */ + function drag(event: NodeDragEvent) { + restoreCarriedChildren() + const roots = dragBoxes(event), ids = new Set(roots.map(box => box.id)) + const movingNodes = event.nodes.filter(node => ids.has(node.id)) + guides.value = [] + const carriedIds = new Set(carried.map(item => item.id)) + if (guidesEnabled.value && roots.length && new Set(roots.map(box => box.parentNode || '')).size === 1) { + const x = Math.min(...roots.map(box => box.x)), y = Math.min(...roots.map(box => box.y)) + const area = { id: event.node.id, parentNode: roots[0].parentNode, x, y, width: Math.max(...roots.map(box => box.x + box.width)) - x, height: Math.max(...roots.map(box => box.y + box.height)) - y } + const sectionsOnly = roots.every(box => box.id.startsWith('section:')) + const peers = options.nodes.value.filter(node => !ids.has(node.id) && !ids.has(node.parentNode || '') && !carriedIds.has(node.id) && (node.type === 'section') === sectionsOnly).map(node => ({ ...absoluteRectangle(node, options.nodes.value), id: node.id, parentNode: node.parentNode })) + const result = snapBox(area, peers, 6 / options.viewport.value.zoom) + for (const node of movingNodes) node.position = { x: node.position.x + result.delta.x, y: node.position.y + result.delta.y } + guides.value = result.guides + } + moveSectionContents() + } + + /** 按分区整体位移补偿内部节点,阶段组的子节点由 Vue Flow 自然继承父坐标。 */ + function moveSectionContents() { + for (const item of carried) { + const node = options.nodes.value.find(node => node.id === item.id), section = options.nodes.value.find(node => node.id === item.sectionId) + if (node && section) node.position = { x: item.position.x + section.position.x - item.origin.x, y: item.position.y + section.position.y - item.origin.y } + } + restoreCarriedChildren() + } + + /** Vue Flow 会先应用全部显式选中节点的拖动;将被携带组内的选中子阶段恢复为起点相对坐标。 */ + function restoreCarriedChildren() { + for (const [id, position] of carriedChildren) { + const child = options.nodes.value.find(node => node.id === id) + if (child) child.position = { ...position } + } + } + + /** 分区几何与 Vue Flow 节点分开存储;只记录展示矩形,不持久化节点快照或任何业务能力。 */ + function syncSections() { + sections.value = sections.value.map(section => { + const node = options.nodes.value.find(item => item.id === section.id) + return node ? { ...section, ...absoluteRectangle(node, []), id: section.id } : section + }) + } + + /** 辅助线随手势结束清空;本地分区位置由调用方与阶段坐标在一次保存中写入。 */ + function finishDrag() { syncSections(); carried = []; carriedChildren.clear(); dragActive = false; guides.value = [] } + + /** + * 接管画布方向键微调,避免 Vue Flow 默认移动绕过分区携带、组边界和本地保存。 + * @param event 仅当前画布冒泡的键盘事件;文本输入和按钮自身的键盘操作不移动节点 + * @remarks 方向键每次移动 1 个画布单位,Shift 为 10;精确微调不吸附,父子选中只移动父级。 + */ + function moveWithKeyboard(event: KeyboardEvent) { + const vectors: Record = { ArrowLeft: { x: -1, y: 0 }, ArrowRight: { x: 1, y: 0 }, ArrowUp: { x: 0, y: -1 }, ArrowDown: { x: 0, y: 1 } } + const vector = vectors[event.key], target = event.target as Element + if (!vector || target.closest('input,textarea,select,[contenteditable="true"]')) return + event.stopPropagation() + // 鼠标手势持有起点快照或尺寸闭包时不能用键盘重建画布,否则后续移动会写入已被替换的节点对象。 + if (dragActive || pointerCleanup) { event.preventDefault(); return } + if (target.closest('button') || event.ctrlKey || event.metaKey || event.altKey || !options.enabled.value || mode.value === 'section') return + const selectedIds = new Set(selectionRoots(options.nodes.value.filter(node => node.selected).map(localBox)).map(box => box.id)) + const moving = options.nodes.value.filter(node => selectedIds.has(node.id)) + if (!moving.length) return + event.preventDefault(); captureSectionContents(moving) + const step = event.shiftKey ? 10 : 1 + for (const node of moving) if (!carriedChildren.has(node.id)) node.position = { x: node.position.x + vector.x * step, y: node.position.y + vector.y * step } + moveSectionContents(); finishDrag(); options.changed() + } + + /** 对齐只作用于同一父画布的阶段,均分空间不足时返回可展示的原因,不做部分变更。 */ + function arrange(action: ArrangeAction): string { + if (!options.enabled.value) return '画布正在处理其他操作,请稍后重试。' + const result = arrangeBoxes(selected.value, action) + if (!result) return !sameScope.value ? '请选择同一画布层级的节点进行对齐。' : action.startsWith('distribute-') ? '等间距需要至少三个节点,且首尾之间有足够空间。' : '请至少选择两个节点。' + for (const node of options.nodes.value) if (result[node.id]) node.position = result[node.id] + options.changed() + return '' + } + + /** 创建分区仅保存标题与几何值;不将阶段挂到分区下,因此已有执行边和组约束保持独立。 */ + function addSection(box: Omit) { + if (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 (!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 + const width = Math.max(...selected.value.map(box => box.x + box.width)) - x + 24, height = Math.max(...selected.value.map(box => box.y + box.height)) - y + 24 + if (width > 20000 || height > 20000) return '所选节点跨度过大,请分为多个分区(分区边长最多 20000)。' + addSection({ x, y, width, height }) + 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 + section.name = normalized; options.changed() + } + + /** 删除的是展示分区,内部阶段、连线和历史记录不受影响。 */ + function removeSection(id: string) { + if (!options.enabled.value) return + sections.value = sections.value.filter(section => section.id !== id); options.changed() + } + + /** + * 在空白画布按下后绘制分区,使用屏幕到画布的转换处理缩放和平移。 + * @param event 左键指针事件;阻止兼容鼠标事件,避免 Vue Flow 同时平移或框选 + * @remarks 取消、失焦、隐藏和卸载只清理草稿;小于 20 像素的误触不创建分区。 + */ + function drawSection(event: PointerEvent) { + if (!options.enabled.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() + const start = options.toFlow({ x: event.clientX, y: event.clientY }) + draft.value = { id: 'draft', ...start, width: 0, height: 0 } + /** 反向拖框同样使用最小坐标,分区尺寸始终非负。 */ + const move = (pointer: PointerEvent) => { + const end = options.toFlow({ x: pointer.clientX, y: pointer.clientY }) + draft.value = { id: 'draft', x: Math.min(start.x, end.x), y: Math.min(start.y, end.y), width: Math.min(20000, Math.abs(end.x - start.x)), height: Math.min(20000, Math.abs(end.y - start.y)) } + } + listenPointer(move, commit => { + const box = draft.value; draft.value = null + if (commit && box && box.width >= 20 && box.height >= 20) addSection(box) + }) + } + + /** 右下角调整分区尺寸,按缩放换算并限制在可持久化范围;取消时恢复原尺寸。 */ + function resizeSection(id: string, event: PointerEvent) { + if (!options.enabled.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 }) + resizing.value = true + listenPointer(pointer => { + const end = options.toFlow({ x: pointer.clientX, y: pointer.clientY }) + 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() + }) + } + + /** 单个指针手势独占临时监听;先释放监听再执行保存,避免回调重建画布时仍有旧监听写入。 */ + function listenPointer(move: (event: PointerEvent) => void, finish: (commit: boolean) => void) { + pointerCleanup?.(false) + /** 正常抬起提交;取消和窗口失焦撤销当前草稿。 */ + const up = () => cleanup(true), cancel = () => cleanup(false) + /** 事件清理可重复调用,隐藏与卸载的连续回调不会二次提交。 */ + function cleanup(commit: boolean) { + if (pointerCleanup !== cleanup) return + pointerCleanup = null + window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up) + window.removeEventListener('pointercancel', cancel); window.removeEventListener('blur', cancel) + finish(commit) + } + pointerCleanup = cleanup + window.addEventListener('pointermove', move); window.addEventListener('pointerup', up) + window.addEventListener('pointercancel', cancel); window.addEventListener('blur', cancel) + } + + /** 组装纯展示节点,不提供执行连接点,也不设置业务 parentNode。 */ + function sectionNodes(): Node[] { + 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 } })) + } + + watch(guidesEnabled, () => { guides.value = []; options.changed() }) + watch(options.enabled, enabled => { if (!enabled) { pointerCleanup?.(false); guides.value = [] } }) + /** 浏览器切后台未必触发窗口 blur;隐藏时同样撤销未结束的分区草稿。 */ + function visibilityChanged() { if (document.hidden) pointerCleanup?.(false) } + onMounted(() => document.addEventListener('visibilitychange', visibilityChanged)) + onBeforeUnmount(() => { pointerCleanup?.(false); carried = []; document.removeEventListener('visibilitychange', visibilityChanged) }) + return { sections, guidesEnabled, guides, mode, draft, resizing, selected, sameScope, + interacting: computed(() => !!draft.value || resizing.value), startDrag, drag, finishDrag, moveWithKeyboard, arrange, drawSection, resizeSection, + renameSection, removeSection, sectionFromSelection, sectionNodes } +} diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/canvasGeometry.ts b/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/canvasGeometry.ts new file mode 100644 index 0000000..daa86e2 --- /dev/null +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/canvasGeometry.ts @@ -0,0 +1,133 @@ +import type { Point } from '../../../types' + +export interface CanvasBox extends Point { id: string; width: number; height: number; parentNode?: string } +export interface CanvasSection extends CanvasBox { name: string } +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' + +/** 同时选择父子时只操作最外层,防止阶段组平移后子节点又被重复移动。 */ +export function selectionRoots(boxes: T[]): T[] { + const ids = new Set(boxes.map(box => box.id)) + return boxes.filter(box => !box.parentNode || !ids.has(box.parentNode)) +} + +/** + * 在同一父画布内计算六种对齐或边缘间距均分,不修改阶段归属。 + * @param input 选中节点的本层矩形;对齐以选区包围框为基准,均分固定首尾 + * @param action 工具栏动作;center-x 表示横坐标中心相同,center-y 表示纵坐标中心相同 + * @returns 节点的新本层坐标;跨父级、数量不足或均分空间不足返回 null,避免制造重叠 + */ +export function arrangeBoxes(input: CanvasBox[], action: ArrangeAction): Record | null { + const boxes = selectionRoots(input) + if (boxes.length < 2 || new Set(boxes.map(box => box.parentNode || '')).size !== 1) return null + const horizontal = ['left', 'center-x', 'right', 'distribute-x'].includes(action) + const axis = horizontal ? 'x' : 'y', size = horizontal ? 'width' : 'height' + const start = Math.min(...boxes.map(box => box[axis])), end = Math.max(...boxes.map(box => box[axis] + box[size])) + if (action.startsWith('distribute-')) { + if (boxes.length < 3) return null + const sorted = [...boxes].sort((a, b) => a[axis] - b[axis] || a.id.localeCompare(b.id)) + // 排序末节点可能小于中间的大阶段组;以首尾节点本身界定跨度,不能借外包围框把尾节点推远。 + const last = sorted[sorted.length - 1], span = last[axis] + last[size] - sorted[0][axis] + const gap = (span - sorted.reduce((sum, box) => sum + box[size], 0)) / (boxes.length - 1) + if (gap < 0) return null + let offset = start + return Object.fromEntries(sorted.map(box => { const position = { x: box.x, y: box.y, [axis]: offset }; offset += box[size] + gap; return [box.id, position] })) + } + return Object.fromEntries(boxes.map(box => [box.id, { x: box.x, y: box.y, + [axis]: action.startsWith('center-') ? (start + end - box[size]) / 2 : ['right', 'bottom'].includes(action) ? end - box[size] : start }])) +} + +/** 判断整块根节点是否位于分区内部;阶段组按整体矩形计入,组内子阶段不单独归属。 */ +export function containsBox(section: CanvasBox, box: CanvasBox): boolean { + return !box.parentNode && box.x >= section.x && box.y >= section.y && box.x + box.width <= section.x + section.width && box.y + box.height <= section.y + section.height +} + +/** 两矩形在指定轴上的投影相交,只有同排或同列才比较间距,避免远处节点干扰吸附。 */ +function overlaps(a: CanvasBox, b: CanvasBox, axis: 'x' | 'y'): boolean { + const size = axis === 'x' ? 'width' : 'height' + return a[axis] < b[axis] + b[size] && a[axis] + a[size] > b[axis] +} + +/** 生成可缩放的距离标记,数值采用画布坐标像素,与缩放比例无关。 */ +function distanceGuide(a: CanvasBox, b: CanvasBox, axis: 'x' | 'y'): CanvasGuide { + if (axis === 'x') { + const y = Math.max(a.y, b.y) - 12 + return { x1: a.x + a.width, y1: y, x2: b.x, y2: y, kind: 'distance', label: String(Math.round(b.x - a.x - a.width)) } + } + const x = Math.max(a.x, b.x) - 12 + return { x1: x, y1: a.y + a.height, x2: x, y2: b.y, kind: 'distance', label: String(Math.round(b.y - a.y - a.height)) } +} + +/** + * 拖动时计算边缘/中心与等间距吸附,并返回非交互的辅助线。 + * @param moving 当前拖动选区的绝对包围框,多选时作为整体处理 + * @param input 未拖动的同层节点;调用方排除已选父节点的子孙 + * @param threshold 画布坐标阈值,调用方使用 6 / zoom 保持屏幕上吸附距离一致 + * @returns 修正偏移及吸附后的辅助线;每轴只选择最接近目标,不做全图自动布局 + */ +export function snapBox(moving: CanvasBox, input: CanvasBox[], threshold: number): { delta: Point; guides: CanvasGuide[] } { + const peers = input.filter(box => box.id !== moving.id && (box.parentNode || '') === (moving.parentNode || '')) + const delta: Point = { x: 0, y: 0 }, references: CanvasGuide[] = [] + for (const axis of ['x', 'y'] as const) { + const size = axis === 'x' ? 'width' : 'height', other = axis === 'x' ? 'y' : 'x' + let best = threshold + 0.001, correction = 0, reference: CanvasGuide | undefined + // 一轴最多吸附一次;均分候选只用同排/列相邻节点,排序后线性扫描,避免逐帧 O(N²) 配对。 + for (const peer of peers) for (const from of [0, 0.5, 1]) for (const to of [0, 0.5, 1]) { + const value = peer[axis] + peer[size] * to - moving[axis] - moving[size] * from + if (Math.abs(value) < best) { best = Math.abs(value); correction = value; reference = undefined } + } + const row = peers.filter(peer => overlaps(moving, peer, other)).sort((a, b) => a[axis] - b[axis]) + for (let i = 1; i < row.length; i++) { + const a = row[i - 1], b = row[i], gap = b[axis] - a[axis] - a[size] + if (gap < 0) continue + const targets = [a[axis] - gap - moving[size], b[axis] + b[size] + gap] + if (gap >= moving[size]) targets.push((a[axis] + a[size] + b[axis] - moving[size]) / 2) + for (const target of targets) { + const value = target - moving[axis] + if (Math.abs(value) < best) { best = Math.abs(value); correction = value; reference = distanceGuide(a, b, axis) } + } + } + delta[axis] = correction + if (reference) references.push(reference) + } + const snapped = { ...moving, x: moving.x + delta.x, y: moving.y + delta.y }, guides: CanvasGuide[] = [...references] + for (const axis of ['x', 'y'] as const) { + const size = axis === 'x' ? 'width' : 'height', other = axis === 'x' ? 'y' : 'x', otherSize = axis === 'x' ? 'height' : 'width' + for (const peer of peers) for (const from of [0, 0.5, 1]) for (const to of [0, 0.5, 1]) { + const at = snapped[axis] + snapped[size] * from + if (Math.abs(at - peer[axis] - peer[size] * to) > 0.01) continue + const low = Math.min(snapped[other], peer[other]) - 12, high = Math.max(snapped[other] + snapped[otherSize], peer[other] + peer[otherSize]) + 12 + guides.push(axis === 'x' ? { x1: at, x2: at, y1: low, y2: high, kind: 'alignment' } : { y1: at, y2: at, x1: low, x2: high, kind: 'alignment' }) + } + const row = peers.filter(peer => overlaps(snapped, peer, other)) + const before = row.filter(peer => peer[axis] + peer[size] <= snapped[axis]).sort((a, b) => b[axis] + b[size] - a[axis] - a[size])[0] + const after = row.filter(peer => peer[axis] >= snapped[axis] + snapped[size]).sort((a, b) => a[axis] - b[axis])[0] + if (before) guides.push(distanceGuide(before, snapped, axis)) + if (after) guides.push(distanceGuide(snapped, after, axis)) + } + // 同列/同行可能有大量节点;合并共线标记后,SVG 数量只与选区锚点数量相关,避免逐帧堆积 DOM。 + const merged = new Map() + for (const guide of guides) { + const vertical = guide.x1 === guide.x2 + const key = guide.kind === 'alignment' ? (vertical ? 'x:' + guide.x1 : 'y:' + guide.y1) : JSON.stringify(guide) + const previous = merged.get(key) + if (previous && guide.kind === 'alignment') { + if (vertical) { previous.y1 = Math.min(previous.y1, guide.y1); previous.y2 = Math.max(previous.y2, guide.y2) } + else { previous.x1 = Math.min(previous.x1, guide.x1); previous.x2 = Math.max(previous.x2, guide.x2) } + } else merged.set(key, { ...guide }) + } + return { delta, guides: [...merged.values()] } +} + +/** 验证浏览器分区草稿并复制有限几何值,过滤损坏、重复或过大对象;不接受任何阶段父级字段。 */ +export function sanitizeSections(value: unknown): CanvasSection[] { + if (!Array.isArray(value)) return [] + const ids = new Set(), result: CanvasSection[] = [] + for (const entry of value.slice(0, 200)) { + if (!entry || typeof entry !== 'object' || typeof entry.id !== 'string' || !/^section:[\w-]{1,100}$/.test(entry.id) || ids.has(entry.id)) continue + if (typeof entry.name !== 'string' || !entry.name.trim() || !['x', 'y', 'width', 'height'].every(key => typeof entry[key] === 'number' && Number.isFinite(entry[key]))) continue + if (Math.abs(entry.x) > 1e7 || Math.abs(entry.y) > 1e7 || entry.width < 180 || entry.height < 120 || entry.width > 20000 || entry.height > 20000) continue + result.push({ id: entry.id, name: entry.name.trim().slice(0, 100), x: entry.x, y: entry.y, width: entry.width, height: entry.height }); ids.add(entry.id) + } + return result +} diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/graph.ts b/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/graph.ts index 484d670..4e264b8 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/graph.ts +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/graph.ts @@ -2,8 +2,9 @@ import type { Node, Edge } from '@vue-flow/core' import { ConnectionLineType, MarkerType } from '@vue-flow/core' import { FLOW_REWORK_COLOR } from '../constants/theme' import type { FlowView, Point, Stage, WorkItem } from '../../../types' +import type { CanvasSection } from './canvasGeometry' -export interface FlowNodeData { item?: WorkItem; children?: WorkItem[]; stage?: Stage; stageId?: number; title?: string; itemCount?: number; collapsed?: boolean; [key: string]: unknown } +export interface FlowNodeData { section?: CanvasSection; item?: WorkItem; children?: WorkItem[]; stage?: Stage; stageId?: number; title?: string; itemCount?: number; collapsed?: boolean; [key: string]: unknown } export interface FlowEdgeData { kind?: 'execution' | 'rework'; linkId?: number; version?: number; reworkCount?: number; latestReworkAt?: string; laneY?: number; sourceEscapeX?: number; targetEscapeX?: number; [key: string]: unknown } interface Rectangle extends Point { width: number; height: number } export const FLOW_ITEM_WIDTH = 260 @@ -50,7 +51,7 @@ export function buildFlowGraph(view: FlowView, positions: Record, } if (!stages.length || view.unassigned?.counts.total) { const rootRects = stages.filter(stage => !stage.parentStageId).map(stage => rectangles.get(stage.id)!) - const position = freePosition({ x: 30, y: 40 }, FLOW_STAGE_WIDTH, FLOW_STAGE_HEIGHT, rootRects, 48) + const position = positions['s:0'] || freePosition({ x: 30, y: 40 }, FLOW_STAGE_WIDTH, FLOW_STAGE_HEIGHT, rootRects, 48) nodes.push({ id: 's:0', type: 'stage', position, style: { width: FLOW_STAGE_WIDTH + 'px', height: FLOW_STAGE_HEIGHT + 'px' }, data: { stageId: 0, title: '未分配', itemCount: view.unassigned?.counts.total || 0 }, connectable: false, dragHandle: '.stage-drag' }) } const visible = new Set(nodes.map(node => node.id)) @@ -92,7 +93,8 @@ export function buildFlowGraph(view: FlowView, positions: Record, const level = levels.get(stage.id)!, size = rectangles.get(stage.id) || { width: FLOW_STAGE_WIDTH, height: FLOW_STAGE_HEIGHT }, saved = positions['s:' + stage.id] const shift = groupOffsets.get(stage.id) const preferred = saved ? { x: saved.x + (shift?.x || 0), y: saved.y + (shift?.y || 0) } : { x: columns.get(level)!, y: nextY.get(level) || top } - const point = freePosition(preferred, size.width, size.height, occupied, 48), rect = { ...point, width: size.width, height: size.height } + // 自动避让只用于新节点;手动吸附、对齐和均分的坐标必须原样恢复,否则松手后会被二次排版。 + const point = saved ? preferred : freePosition(preferred, size.width, size.height, occupied, 48), rect = { ...point, width: size.width, height: size.height } rectangles.set(stage.id, rect); occupied.push(rect); nextY.set(level, point.y + size.height + 56) } } @@ -152,12 +154,12 @@ export function updateReworkRoutes(nodes: Node[], edges: Edge, nodes: Node[]): Rectangle { - const parent = nodes.find(candidate => candidate.id === node.parentNode), origin = parent ? absoluteRectangle(parent, nodes) : { x: 0, y: 0 } + const parent = node.parentNode ? nodes.find(candidate => candidate.id === node.parentNode) : undefined, origin = parent ? absoluteRectangle(parent, nodes) : { x: 0, y: 0 } const style = typeof node.style === 'object' ? node.style : {} return { x: origin.x + node.position.x, y: origin.y + node.position.y, width: Number.parseFloat(String(style?.width || FLOW_STAGE_WIDTH)), height: Number.parseFloat(String(style?.height || FLOW_STAGE_HEIGHT)) } } -/** 在当前作用域内按实际矩形向下避让,兼容浏览器中相互覆盖的旧坐标。 */ +/** 仅对未保存坐标的新节点在当前作用域内向下避让,避免覆盖已有的手动排列。 */ function freePosition(candidate: Point, width: number, height: number, occupied: Rectangle[], gap: number): Point { const point = { ...candidate }; let conflicts: Rectangle[] do { conflicts = occupied.filter(rect => point.x < rect.x + rect.width + gap && point.x + width + gap > rect.x && point.y < rect.y + rect.height + gap && point.y + height + gap > rect.y); if (conflicts.length) point.y = Math.max(...conflicts.map(rect => rect.y + rect.height + gap)) } while (conflicts.length) diff --git a/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/preferences.ts b/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/preferences.ts index f140687..9206902 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/preferences.ts +++ b/ruoyi-ui-vue3/src/views/project/manage/views/flow/utils/preferences.ts @@ -1,6 +1,9 @@ import type { Point } from '../../../types' +import { sanitizeSections, type CanvasSection } from './canvasGeometry' export interface FlowPreferences { + sections?: CanvasSection[] + guidesEnabled?: boolean parents?: Record collapsedStages: number[] positions: Record @@ -13,7 +16,7 @@ const VERSION = 2 /** 按登录用户、项目和迭代分隔浏览器偏好,避免同设备或同项目串用画布状态。 */ function key(userId: number | string, projectId: number, iterationId?: number): string { return `pm-flow-view:${userId}:${projectId}${iterationId ? `:${iterationId}` : ""}` } -/** 仅恢复当前格式的展示坐标;本地内容不参与阶段、工作项或权限判断。 */ +/** 兼容旧格式坐标并校验新增分区和辅助开关;本地内容不参与阶段、工作项或权限判断。 */ export function readFlowPreferences(userId: number | string, projectId: number, iterationId?: number): FlowPreferences | null { try { const raw = localStorage.getItem(key(userId, projectId, iterationId)) @@ -26,7 +29,7 @@ export function readFlowPreferences(userId: number | string, projectId: number, 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 } + return { collapsedStages, positions, viewport, parents, sections: sanitizeSections(source.sections), guidesEnabled: source.guidesEnabled !== false } } catch { return null } }