diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmController.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmController.java index ad80354..4718698 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmController.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmController.java @@ -11,6 +11,7 @@ import com.ruoyi.project.manage.dto.TransitionInput; import com.ruoyi.project.manage.dto.VersionInput; import com.ruoyi.project.manage.exception.PmException; import com.ruoyi.project.manage.service.IPmService; +import com.ruoyi.project.manage.service.support.PmAttachmentStorage; import com.ruoyi.project.manage.dto.ItemQuery; import static com.ruoyi.project.manage.util.PmValues.*; @@ -101,8 +102,8 @@ public class PmController { @GetMapping("/items/{id}/successors") public Map successors(@PathVariable long id) { return ok(service.successors(id)); } /** 工作项评论受同一数据权限保护,并原子记录历史。 */ @PostMapping("/items/{id}/comments") public Map comment(@PathVariable long id,@RequestBody JsonNode body) { service.comment(id,decode(body,CommentInput.class)); return ok(null); } - /** 文件写入 MinIO 私有对象,数据库仅保存元数据;不产生公开上传 URL。 */ - @PostMapping("/items/{id}/attachments") public Map attach(@PathVariable long id,@RequestParam("file") MultipartFile file) throws java.io.IOException { if(file.getSize()>10*1024*1024) throw PmException.bad("附件不能超过 10 MiB"); return ok(service.attach(id,file.getOriginalFilename(),file.getContentType(),file.getBytes())); } + /** 在读取字节前按统一的 50MB 上限校验,文件存入 MinIO 私有对象,不产生公开上传 URL。 */ + @PostMapping("/items/{id}/attachments") public Map attach(@PathVariable long id,@RequestParam("file") MultipartFile file) throws java.io.IOException { if(file.getSize()>PmAttachmentStorage.MAX_BYTES) throw PmException.bad("附件不能超过 "+PmAttachmentStorage.MAX_SIZE_LABEL); return ok(service.attach(id,file.getOriginalFilename(),file.getContentType(),file.getBytes())); } /** 绑定工作项与附件 ID,负责人/创建者权限及软删除事务由服务统一处理,不开放存储对象删除入口。 */ @DeleteMapping("/items/{id}/attachments/{attachmentId}") public Map removeAttachment(@PathVariable long id,@PathVariable long attachmentId) { service.removeAttachment(id,attachmentId); return ok(null); } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageCompletionController.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageCompletionController.java index cbb30e0..9886849 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageCompletionController.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/controller/PmStageCompletionController.java @@ -5,6 +5,7 @@ import com.ruoyi.project.manage.dto.StageCompletionInput; import com.ruoyi.project.manage.dto.StagePurchaseInput; import com.ruoyi.project.manage.exception.PmException; import com.ruoyi.project.manage.service.IPmStageCompletionService; +import com.ruoyi.project.manage.service.support.PmAttachmentStorage; import java.nio.charset.StandardCharsets; import java.util.Map; import org.springframework.http.*; @@ -52,10 +53,10 @@ public class PmStageCompletionController { /** 确认本轮采购范围,不修改源采购批次及验收事实。 */ @PutMapping("/stages/{stageId}/purchase-batches") public Map batches(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@RequestBody JsonNode body) {service.batches(projectId,iterationId,stageId,decode(body,StagePurchaseInput.class));return ok(null);} - /** 文件大小在读取字节之前校验;服务再次检查当前轮次、身份及实际内容长度。 */ + /** 读取字节前按统一的 50MB 上限校验;服务再次检查当前轮次、身份及实际内容长度。 */ @PostMapping("/stages/{stageId}/revisions/{revisionId}/attachments") public Map upload(@PathVariable long projectId,@PathVariable long iterationId,@PathVariable long stageId,@PathVariable long revisionId,@RequestParam("file") MultipartFile file) throws java.io.IOException { - if(file.getSize()>10*1024*1024)throw PmException.bad("附件不能超过10MiB"); + if(file.getSize()>PmAttachmentStorage.MAX_BYTES)throw PmException.bad("附件不能超过"+PmAttachmentStorage.MAX_SIZE_LABEL); return ok(service.attach(projectId,iterationId,stageId,revisionId,file.getOriginalFilename(),file.getContentType(),file.getBytes())); } /** 人员显式确认沿用旧版交付,复制新对象且不继承审批通过。 */ diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/IPmService.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/IPmService.java index 561360a..ed19333 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/IPmService.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/IPmService.java @@ -195,7 +195,7 @@ public interface IPmService { void comment(long id,CommentInput input); /** - * 附件存入 MinIO 私有对象,数据库仅保存元数据;限制为 10 MiB,业务回滚时补偿新对象。 + * 附件存入 MinIO 私有对象,数据库仅保存元数据;限制为 50MB,业务回滚时补偿新对象。 * * @param id 路径中的目标对象 ID;服务按当前身份校验维护或查看权限 * @param name 附件原始文件名,服务会校验和净化 diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmServiceImpl.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmServiceImpl.java index b20200a..a7c3384 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmServiceImpl.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmServiceImpl.java @@ -428,7 +428,7 @@ public class PmServiceImpl implements IPmService { } /** - * 工作项写鉴权后保存私有 MinIO 对象及数据库元信息,限制为 10 MiB,不写本地目录或新二进制字段。 + * 工作项写鉴权后保存私有 MinIO 对象及数据库元信息,限制为 50MB,不写本地目录或新二进制字段。 * @param id 当前可写工作项,历史版本不能追加附件 * @param name 原文件名,仅保留文件名部分,不作为对象路径使用 * @param mediaType 浏览器提交的媒体类型,需满足 HTTP 媒体类型格式 @@ -437,7 +437,7 @@ public class PmServiceImpl implements IPmService { */ public long attach(long id,String name,String mediaType,byte[] content) { long projectId=projectOf(id),iterationId=iterationOf(id); locked(projectId,iterationId,"write"); writableItem(graphService.load(projectId,iterationId),id); - if(content==null||content.length==0||content.length>com.ruoyi.project.manage.service.support.PmAttachmentStorage.MAX_BYTES) throw PmException.bad("附件需为 1 字节至 10 MiB"); + if(content==null||content.length==0||content.length>com.ruoyi.project.manage.service.support.PmAttachmentStorage.MAX_BYTES) throw PmException.bad("附件需为 1 字节至 "+com.ruoyi.project.manage.service.support.PmAttachmentStorage.MAX_SIZE_LABEL); String safeName=required(name==null?"附件":name.replace('\\','/').substring(name.replace('\\','/').lastIndexOf('/')+1),255,"附件名称"); String safeType=mediaType==null?"application/octet-stream":required(mediaType,120,"文件类型"); try { org.springframework.http.MediaType.parseMediaType(safeType); } catch(IllegalArgumentException invalid) { throw PmException.bad("文件类型格式无效"); } diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageCompletionServiceImpl.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageCompletionServiceImpl.java index 88ffab5..58cbf21 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageCompletionServiceImpl.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/impl/PmStageCompletionServiceImpl.java @@ -191,10 +191,10 @@ public class PmStageCompletionServiceImpl implements IPmStageCompletionService { record(stage,"STAGE_PURCHASE_SCOPE_CHANGED",map("batchIds",ids,"message","确认本轮采购批次范围"),List.of(),false); } - /** 当前交付维护人上传真实MinIO附件,空文件、超限和不合法媒体类型均拒绝。 */ + /** 当前交付维护人上传真实 MinIO 附件,按统一的 50MB 上限拒绝超限内容,同时校验空文件和媒体类型。 */ public long attach(long projectId,long iterationId,long stageId,long revisionId,String name,String mediaType,byte[] content) { locked(projectId,iterationId,"write");var stage=stage(projectId,iterationId,stageId);maintainer(stage);var revision=currentId(stage,projectId,iterationId,revisionId);mutable(graphs.load(projectId,iterationId),stageId); - if(content==null||content.length==0||content.length>PmAttachmentStorage.MAX_BYTES)throw PmException.bad("附件需为1字节至10MiB"); + if(content==null||content.length==0||content.length>PmAttachmentStorage.MAX_BYTES)throw PmException.bad("附件需为1字节至"+PmAttachmentStorage.MAX_SIZE_LABEL); String path=name==null?"附件":name.replace('\\','/');String safeName=required(path.substring(path.lastIndexOf('/')+1),255,"附件名称"); if(safeName.chars().anyMatch(Character::isISOControl))throw PmException.bad("附件名不能包含控制字符"); String type=mediaType==null?"application/octet-stream":required(mediaType,120,"文件类型"); diff --git a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/support/PmAttachmentStorage.java b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/support/PmAttachmentStorage.java index ca1c472..88bef4a 100644 --- a/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/support/PmAttachmentStorage.java +++ b/ruoyi-project/src/main/java/com/ruoyi/project/manage/service/support/PmAttachmentStorage.java @@ -15,7 +15,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager /** 协作附件只写 MinIO 私有对象;对象键、校验和及下载鉴权由服务端控制,不暴露桶地址。 */ @Component public class PmAttachmentStorage { - public static final int MAX_BYTES=10*1024*1024; + // 上传校验与 MinIO 受限读取共用 50MB 上限,避免上传成功的大附件在下载时被旧上限拒绝。 + public static final int MAX_BYTES=50*1024*1024; + public static final String MAX_SIZE_LABEL=(MAX_BYTES/(1024*1024))+"MB"; private final BusinessFileStorage storage; /** 复用系统存储配置和环境隔离,传入空本地路径,禁止未启用 MinIO 时落入文件目录。 */ diff --git a/ruoyi-ui-vue3/src/views/project/manage/features/stages/components/StageCompletionPanel.vue b/ruoyi-ui-vue3/src/views/project/manage/features/stages/components/StageCompletionPanel.vue index b603047..1de44c4 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/features/stages/components/StageCompletionPanel.vue +++ b/ruoyi-ui-vue3/src/views/project/manage/features/stages/components/StageCompletionPanel.vue @@ -16,7 +16,7 @@ 保存说明 - MinIO私有存储,单个文件最多10MiB + MinIO私有存储,单个文件最多{{ ATTACHMENT_MAX_SIZE_LABEL }} @@ -62,6 +62,7 @@ import { api, errorText, PmApiError } from '../../../api' import { createIdempotencyKey } from '../../../shared/utils/idempotency' import { localTime } from '../../../shared/utils/time' import { approvalStatusNames } from '../../../shared/constants/labels' +import { ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_SIZE_LABEL } from '../../../shared/constants/attachments' import type { Stage, StageApproval, StageApprovalStatus, StageCompletion, StageCompletionCommand, StageDeliveryAttachment, StageDeliverySnapshot as DeliverySnapshot } from '../../../types' import PurchaseBatchPicker from './PurchaseBatchPicker.vue' import StageDeliverySnapshot from './StageDeliverySnapshot.vue' @@ -124,11 +125,11 @@ async function refresh() { if (dirty.value) { try { await ElMessageBox.confirm('刷新将放弃尚未保存的交付说明或采购范围,是否继续?', '刷新阶段交付', { closeOnClickModal: false, type: 'warning' }) } catch { return } } await load(true) } -/** 原生文件输入只交给模块客户端,不能生成公开MinIO地址或本地路径。 */ +/** 按协作统一的 50MB 上限检查文件后交给模块客户端,不生成公开 MinIO 地址或本地路径。 */ function upload(event: Event) { const element = event.target as HTMLInputElement, file = element.files?.[0]; element.value = '' if (!file || !data.value) return - if (!file.size || file.size > 10 * 1024 * 1024) { failure.value = '附件需为1字节至10MiB'; return } + if (!file.size || file.size > ATTACHMENT_MAX_BYTES) { failure.value = `附件需为1字节至${ATTACHMENT_MAX_SIZE_LABEL}`; return } void mutate(() => api.uploadStageAttachment(props.projectId, props.iterationId, props.stage.id, input().revisionId, file)) } /** 软删确认不会销毁历史对象,取消确认不触发后端操作。 */ diff --git a/ruoyi-ui-vue3/src/views/project/manage/features/work-items/components/ItemDetail.vue b/ruoyi-ui-vue3/src/views/project/manage/features/work-items/components/ItemDetail.vue index 94a4d2f..1070459 100644 --- a/ruoyi-ui-vue3/src/views/project/manage/features/work-items/components/ItemDetail.vue +++ b/ruoyi-ui-vue3/src/views/project/manage/features/work-items/components/ItemDetail.vue @@ -53,7 +53,7 @@

评论

{{ comment.author }}

{{ comment.body }}

-

附件

{{ file.name }}
{{ (file.size / 1024).toFixed(1) }} KB删除
+

附件

{{ file.name }}
{{ (file.size / 1024).toFixed(1) }} KB删除

操作历史

{{ actionNames[entry.action] || '工作项更新' }}{{ members.find(m => m.userId === entry.createdBy)?.name || `用户 #${entry.createdBy}` }}

{{ historyText(entry.detail) }}

{{ displayTime(entry.createdAt) }}
@@ -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 } }