feat: 节点对齐辅助、分区、附件大小限制
This commit is contained in:
parent
31fefeadb4
commit
4fd36100bc
@ -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<String,Object> successors(@PathVariable long id) { return ok(service.successors(id)); }
|
||||
/** 工作项评论受同一数据权限保护,并原子记录历史。 */
|
||||
@PostMapping("/items/{id}/comments") public Map<String,Object> 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<String,Object> 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<String,Object> 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<String,Object> removeAttachment(@PathVariable long id,@PathVariable long attachmentId) { service.removeAttachment(id,attachmentId); return ok(null); }
|
||||
|
||||
@ -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<String,Object> 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<String,Object> 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()));
|
||||
}
|
||||
/** 人员显式确认沿用旧版交付,复制新对象且不继承审批通过。 */
|
||||
|
||||
@ -195,7 +195,7 @@ public interface IPmService {
|
||||
void comment(long id,CommentInput input);
|
||||
|
||||
/**
|
||||
* 附件存入 MinIO 私有对象,数据库仅保存元数据;限制为 10 MiB,业务回滚时补偿新对象。
|
||||
* 附件存入 MinIO 私有对象,数据库仅保存元数据;限制为 50MB,业务回滚时补偿新对象。
|
||||
*
|
||||
* @param id 路径中的目标对象 ID;服务按当前身份校验维护或查看权限
|
||||
* @param name 附件原始文件名,服务会校验和净化
|
||||
|
||||
@ -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("文件类型格式无效"); }
|
||||
|
||||
@ -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,"文件类型");
|
||||
|
||||
@ -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 时落入文件目录。 */
|
||||
|
||||
@ -16,7 +16,7 @@
|
||||
<el-form-item label="实际交付说明" :required="stage.nodeType === 'DESIGN'"><el-input v-model="note" type="textarea" :rows="3" maxlength="10000" :disabled="busy" placeholder="说明本轮实际交付成果,与阶段目标描述分开" /></el-form-item>
|
||||
<el-button size="small" :disabled="note === (data.note || '') || busy" @click="saveNote">保存说明</el-button>
|
||||
<label class="upload"><el-button size="small" :disabled="busy" tag="span">上传交付附件</el-button><input type="file" :disabled="busy" @change="upload" /></label>
|
||||
<span class="muted">MinIO私有存储,单个文件最多10MiB</span>
|
||||
<span class="muted">MinIO私有存储,单个文件最多{{ ATTACHMENT_MAX_SIZE_LABEL }}</span>
|
||||
</el-form>
|
||||
<StageDeliverySnapshot :snapshot="data.delivery" :project-id="projectId" :iteration-id="iterationId" :show-items="false" :show-note="!data.capabilities.canEditDelivery || stage.nodeType === 'PURCHASE'">
|
||||
<template #file-action="{ file }"><el-button v-if="data.capabilities.canEditDelivery" size="small" link type="danger" :disabled="busy" @click="removeFile(file)">删除</el-button><el-button v-else-if="data.historical && stage.canEditDelivery && stage.currentRevisionId !== data.revisionId" size="small" link type="primary" :disabled="busy" @click="reuseFile(file)">沿用到当前版本</el-button></template>
|
||||
@ -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))
|
||||
}
|
||||
/** 软删确认不会销毁历史对象,取消确认不触发后端操作。 */
|
||||
|
||||
@ -53,7 +53,7 @@
|
||||
<el-alert v-if="!detail.historical" type="info" :closable="false" :title="detail.scheduleConstraints.earliestPlannedStartAt ? `最早合法预计开始:${planningLimitDate(detail.scheduleConstraints.earliestPlannedStartAt, 'start', 'min')}` : '暂无参与排期计算的前置结束时间;缺少前置工作项结束时间会阻止保存后续开始时间。'" />
|
||||
</section>
|
||||
<section><h3>评论</h3><article v-for="comment in detail.comments" :key="comment.id" class="comment"><strong>{{ comment.author }}</strong><p>{{ comment.body }}</p></article><template v-if="canDiscuss"><el-input v-model="commentText" type="textarea" :rows="3" placeholder="添加评论" maxlength="10000" /><el-button size="small" class="comment-submit" :disabled="!commentText.trim() || busy" @click="comment">发送评论</el-button></template></section>
|
||||
<section><div class="section-heading"><h3>附件</h3><label v-if="writable" class="upload-link">上传附件(最多 10 MiB)<input type="file" :disabled="busy" @change="upload" /></label></div><div v-for="file in detail.attachments" :key="file.id" class="attachment"><el-link class="attachment-name" :title="file.name" @click="download(file.id, file.name)">{{ file.name }}</el-link><div class="attachment-actions"><span>{{ (file.size / 1024).toFixed(1) }} KB</span><el-button v-if="writable && detail.canDeleteAttachments" size="small" link type="danger" :disabled="busy || attachmentConfirmationOpen" @click="removeAttachment(file)">删除</el-button></div></div></section>
|
||||
<section><div class="section-heading"><h3>附件</h3><label v-if="writable" class="upload-link">上传附件(最多 {{ ATTACHMENT_MAX_SIZE_LABEL }})<input type="file" :disabled="busy" @change="upload" /></label></div><div v-for="file in detail.attachments" :key="file.id" class="attachment"><el-link class="attachment-name" :title="file.name" @click="download(file.id, file.name)">{{ file.name }}</el-link><div class="attachment-actions"><span>{{ (file.size / 1024).toFixed(1) }} KB</span><el-button v-if="writable && detail.canDeleteAttachments" size="small" link type="danger" :disabled="busy || attachmentConfirmationOpen" @click="removeAttachment(file)">删除</el-button></div></div></section>
|
||||
<section><h3>操作历史</h3><div v-for="entry in detail.history" :key="entry.id" class="history"><strong>{{ actionNames[entry.action] || '工作项更新' }}</strong><span>{{ members.find(m => m.userId === entry.createdBy)?.name || `用户 #${entry.createdBy}` }}</span><p>{{ historyText(entry.detail) }}</p><small class="muted">{{ displayTime(entry.createdAt) }}</small></div></section>
|
||||
</template>
|
||||
</div>
|
||||
@ -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<string, string> = 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 = ''
|
||||
|
||||
@ -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`
|
||||
@ -1,22 +1,39 @@
|
||||
<template>
|
||||
<section class="flow-view">
|
||||
<div class="flow-toolbar">
|
||||
<div class="flow-tools"><el-button size="small" @click="autoLayout" :disabled="busy">自动布局</el-button><el-button size="small" @click="fitAll">适应画布</el-button></div>
|
||||
<div class="flow-tools"><span class="flow-help">点击阶段查看当前及历史工作项;画布位置只保存在当前浏览器</span><el-button v-if="canManage" size="small" @click="stageOpen = true">管理阶段</el-button></div>
|
||||
<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" :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-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>
|
||||
<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>
|
||||
<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>
|
||||
<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" @dragover.prevent @drop.prevent="dropStage">
|
||||
<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" :edges-updatable="false" :nodes-draggable="!busy" :elevate-nodes-on-select="false" @connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragging = true" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport">
|
||||
<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">
|
||||
<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-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>
|
||||
<FlowCanvasGuides :guides="guides" :draft="sectionDraft" :viewport="viewport" />
|
||||
<div v-if="!view.unassigned?.counts?.total && !view.stages.length" class="canvas-empty">{{ canManage ? '从左侧拖入节点,然后连接阶段执行顺序。' : '暂无阶段和工作项。' }}</div>
|
||||
<div class="canvas-legend"><span class="legend-line"></span>未执行 <span class="legend-line green"></span>已完成 <span class="legend-line legacy"></span>历史沿用 <span class="legend-line rework" :style="{ borderColor: FLOW_REWORK_COLOR }"></span>回退记录 · 多条入边须全部满足</div>
|
||||
</div>
|
||||
@ -30,7 +47,7 @@
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { ConnectionLineType, VueFlow, useVueFlow } from '@vue-flow/core'
|
||||
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 { Background } from '@vue-flow/background'
|
||||
@ -46,6 +63,8 @@ import { readFlowPreferences, writeFlowPreferences } from './utils/preferences'
|
||||
import { stageAppearance } from './utils/stageAppearance'
|
||||
import { stageGroupAt } from './utils/stageDrop'
|
||||
import { useCanvasGestureCleanup } from './composables/useCanvasGestureCleanup'
|
||||
import { useCanvasTools } from './composables/useCanvasTools'
|
||||
import type { ArrangeAction } from './utils/canvasGeometry'
|
||||
import { isPaletteNodeType } from '../../shared/constants/stageNodeTypes'
|
||||
import type { FlowNodeData, FlowEdgeData } from './utils/graph'
|
||||
import type { FlowView, Member, Point, Stage, StageNodeType } from '../../types'
|
||||
@ -56,6 +75,8 @@ import { stageDeleteBlockedReason, stageRenameBlockedReason } from '../../featur
|
||||
import FlowStageNode from './components/FlowStageNode.vue'
|
||||
import FlowNodePalette from './components/FlowNodePalette.vue'
|
||||
import FlowReworkEdge from './components/FlowReworkEdge.vue'
|
||||
import FlowSectionNode from './components/FlowSectionNode.vue'
|
||||
import FlowCanvasGuides from './components/FlowCanvasGuides.vue'
|
||||
import { FLOW_REWORK_COLOR } from './constants/theme'
|
||||
import StageReworkDialog from '../../features/stages/components/StageReworkDialog.vue'
|
||||
import StageWorkItemsDrawer from '../../features/stages/components/StageWorkItemsDrawer.vue'
|
||||
@ -64,7 +85,7 @@ const props = defineProps<{ view: FlowView; projectId: number; iterationId?: num
|
||||
const emit = defineEmits<{ open: [id: number]; changed: []; create: [stageId: number | null] }>()
|
||||
const canvas = ref<HTMLElement | null>(null)
|
||||
const flowId = 'project-flow-' + props.projectId + '-' + props.iterationId
|
||||
const { fitView, setViewport, viewport, screenToFlowCoordinate, getNodes, updateNodeInternals, paneDragging } = useVueFlow(flowId)
|
||||
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 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)
|
||||
@ -74,11 +95,15 @@ const createParent = computed(() => props.view.stages.find(stage => stage.id ===
|
||||
const reworkSourceId = ref<number | null>(null), drawerStageId = ref<number | null>(null), drawerTab = ref<'current' | 'history'>('current')
|
||||
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 { sections, guidesEnabled, guides, mode: canvasMode, draft: sectionDraft, interacting: canvasInteracting, selected: selectedNodes, sameScope } = canvasTools
|
||||
// 平移和节点移动期间都暂停静默同步,避免尚未释放的鼠标手势遇到画布重建;坐标仍仅保存到当前浏览器。
|
||||
const isEditing = computed(() => drawerEditing.value || dragging.value || paneDragging.value || busy.value || stageOpen.value || stageNameOpen.value || renamingStage.value !== null || reworkSourceId.value !== null)
|
||||
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)
|
||||
const { finishCanvasGesture } = useCanvasGestureCleanup(
|
||||
computed(() => dragging.value || paneDragging.value),
|
||||
computed(() => !props.active || stageOpen.value || stageNameOpen.value || renamingStage.value !== null || drawerStageId.value !== null || reworkSourceId.value !== null),
|
||||
cancelCanvasSelection,
|
||||
)
|
||||
defineExpose({ isEditing })
|
||||
let loaded = false, movingProgrammatically = false
|
||||
@ -90,6 +115,8 @@ watch(() => props.view, () => {
|
||||
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
|
||||
}
|
||||
// 迁入或迁出阶段组后坐标原点已变化;只清除该节点的旧坐标,避免把根画布绝对位置当成子画布相对位置。
|
||||
@ -106,19 +133,43 @@ watch(() => props.active, async active => { if (active) { await nextTick(); awai
|
||||
/** 按子画布和外框实际尺寸重建阶段摘要,折叠只隐藏内部节点,不改变共享业务图。 */
|
||||
function rebuild() {
|
||||
if (dragging.value) return
|
||||
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 = graph.nodes; edges.value = graph.edges
|
||||
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 persistCanvasLayout() {
|
||||
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()
|
||||
if (groups.length) void nextTick(() => updateNodeInternals(groups))
|
||||
}
|
||||
/** 多选排版的失败原因保留在画布上,不对已选节点进行部分修改。 */
|
||||
function applyArrangement(action: ArrangeAction) { failure.value = canvasTools.arrange(action) }
|
||||
/** 分区由完整根节点的包围框生成;只选择子阶段时提示使用其阶段组。 */
|
||||
function createSelectionSection() { failure.value = canvasTools.sectionFromSelection() }
|
||||
/** 拖动起点记录分区包含的根节点,避免拖动途中将路过的节点吸入分区。 */
|
||||
function dragStarted(event: NodeDragEvent) { dragging.value = true; canvasTools.startDrag(event) }
|
||||
/** 框选使用原生指针捕获;失焦、隐藏或弹窗接管时解除展示状态,避免静默同步一直被暂停。 */
|
||||
function cancelCanvasSelection() {
|
||||
if (!selecting.value) return
|
||||
selecting.value = false; userSelectionActive.value = false; userSelectionRect.value = null
|
||||
nodesSelectionActive.value = getNodes.value.some(node => node.selected)
|
||||
}
|
||||
/** 本地偏好只保存阶段坐标和视口;旧工作项坐标不再写回浏览器。 */
|
||||
function savePreference() { writeFlowPreferences(props.userId, props.projectId, { positions: positions.value, parents: previousParents, collapsedStages: collapsedStages.value, viewport: draftViewport.value }, props.iterationId) }
|
||||
/**
|
||||
* 拖动中只调整受影响的父框和回退路径,保留 Vue Flow 的拖拽锚点及其他阶段位置。
|
||||
* @param event 当前拖动节点集合,支持同时选中多个子阶段
|
||||
* @remarks 尺寸写入 DOM 后刷新父框连接点,避免执行线仍连接旧宽高。
|
||||
*/
|
||||
function nodeDragged(event: NodeDragEvent) {
|
||||
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)
|
||||
updateReworkRoutes(getNodes.value, edges.value)
|
||||
@ -128,7 +179,7 @@ function nodeDragged(event: NodeDragEvent) {
|
||||
* 松开时保存补偿后的父子坐标;重新进入页面可恢复相同外框,不调用业务写接口。
|
||||
* @param event 拖动最终节点集合,用于保存前完成最后一次边界计算
|
||||
*/
|
||||
function dragStopped(event: NodeDragEvent) { nodeDragged(event); positions.value = { ...positions.value, ...Object.fromEntries(getNodes.value.map(node => [node.id, { ...node.position }])) }; dragging.value = false; savePreference(); rebuild() }
|
||||
function dragStopped(event: NodeDragEvent) { nodeDragged(event); canvasTools.finishDrag(); dragging.value = false; persistCanvasLayout() }
|
||||
/** 删除旧手动阶段坐标后按显式阶段图重新布局。 */
|
||||
async function autoLayout() { positions.value = {}; savePreference(); rebuild(); await nextTick(); await fitAll() }
|
||||
/** 缩放和平移只影响当前浏览器的展示偏好。 */
|
||||
@ -151,8 +202,12 @@ async function fitAll() {
|
||||
draftViewport.value = { ...viewport.value }; savePreference()
|
||||
} finally { movingProgrammatically = false }
|
||||
}
|
||||
/** 点击阶段打开当前工作项;按钮事件会停止冒泡以保留历史、创建和回退动作。 */
|
||||
function selectNode(event: NodeMouseEvent) { if (event.node.type === 'stage' || event.node.type === 'group') openDrawer(Number(event.node.id.slice(2)), 'current') }
|
||||
/** 框选模式及修饰键点击只选节点,避免多选时误开抽屉;普通单击仍打开阶段详情。 */
|
||||
function selectNode(event: NodeMouseEvent) {
|
||||
const mouse = event.event as MouseEvent
|
||||
if (canvasMode.value !== 'pan' || mouse.ctrlKey || mouse.metaKey || mouse.shiftKey) return
|
||||
if (event.node.type === 'stage' || event.node.type === 'group') openDrawer(Number(event.node.id.slice(2)), 'current')
|
||||
}
|
||||
/** 当前或历史版本共用同一阶段抽屉,零号虚拟节点只展示未分配当前工作项。 */
|
||||
function openDrawer(stageId: number, tab: 'current' | 'history') { if (stageId !== 0 && !props.view.stages.some(stage => stage.id === stageId)) return; drawerTab.value = stageId === 0 ? 'current' : tab; drawerStageId.value = stageId }
|
||||
/** 工作项详情沿用项目级详情抽屉;先关闭阶段列表,避免两个遮罩层争夺焦点。 */
|
||||
@ -192,7 +247,7 @@ async function removeStage(stageId: number) {
|
||||
finally { busy.value = false }
|
||||
}
|
||||
/** 小地图复用当前版本的状态色,便于缩小时定位回退待重做阶段;主题切换由 CSS 变量即时响应。 */
|
||||
function minimapColor(node: GraphNode<FlowNodeData>) { return stageAppearance(node.data?.stage).accent }
|
||||
function minimapColor(node: GraphNode<FlowNodeData>) { return node.type === 'section' ? 'var(--el-color-primary-light-8)' : stageAppearance(node.data?.stage).accent }
|
||||
/**
|
||||
* 将素材分类和画布落点转为创建草稿,命中子节点或组背景均自动归入同一组。
|
||||
* @param event 浏览器拖放事件,坐标须按当前缩放和平移转换,不能用 DOM 层级推测归属
|
||||
@ -249,4 +304,8 @@ async function edgeClicked(event: { edge: Edge<FlowEdgeData> }) {
|
||||
.flow-canvas :deep([class~="vue-flow__controls-button"]){background:var(--el-bg-color-overlay);color:var(--el-text-color-primary);fill:currentColor;border-bottom-color:var(--el-border-color-light)}
|
||||
.flow-canvas :deep([class~="vue-flow__controls-button"]:hover){background:var(--el-fill-color)}
|
||||
.flow-canvas :deep([class~="vue-flow__minimap"]){background:var(--el-bg-color-overlay);border:1px solid var(--el-border-color-light);box-shadow:var(--el-box-shadow-lighter)}
|
||||
.flow-canvas :deep([class~="vue-flow__node-section"]){padding:0;border:0;background:transparent;pointer-events:none}
|
||||
.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}
|
||||
</style>
|
||||
|
||||
@ -0,0 +1,22 @@
|
||||
<template>
|
||||
<svg class="canvas-guides" aria-hidden="true">
|
||||
<g :transform="`translate(${viewport.x},${viewport.y}) scale(${viewport.zoom})`">
|
||||
<rect v-if="draft" :x="draft.x" :y="draft.y" :width="draft.width" :height="draft.height" class="section-draft" vector-effect="non-scaling-stroke" />
|
||||
<g v-for="(line,index) in guides" :key="index" :class="line.kind">
|
||||
<line :x1="line.x1" :y1="line.y1" :x2="line.x2" :y2="line.y2" vector-effect="non-scaling-stroke" />
|
||||
<template v-if="line.label">
|
||||
<line v-for="end in [1,2] as const" :key="end" :x1="(end===1?line.x1:line.x2)-(line.y1===line.y2?0:4/viewport.zoom)" :x2="(end===1?line.x1:line.x2)+(line.y1===line.y2?0:4/viewport.zoom)" :y1="(end===1?line.y1:line.y2)-(line.y1===line.y2?4/viewport.zoom:0)" :y2="(end===1?line.y1:line.y2)+(line.y1===line.y2?4/viewport.zoom:0)" vector-effect="non-scaling-stroke" />
|
||||
<rect :x="(line.x1+line.x2)/2-(line.label.length*3.5+5)/viewport.zoom" :y="(line.y1+line.y2)/2-8/viewport.zoom" :width="(line.label.length*7+10)/viewport.zoom" :height="16/viewport.zoom" :rx="3/viewport.zoom" class="distance-label" />
|
||||
<text :x="(line.x1+line.x2)/2" :y="(line.y1+line.y2)/2" :font-size="11/viewport.zoom" text-anchor="middle" dominant-baseline="central">{{ line.label }}</text>
|
||||
</template>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import type { CanvasBox, CanvasGuide } from '../utils/canvasGeometry'
|
||||
defineProps<{ guides: CanvasGuide[]; draft: CanvasBox | null; viewport: { x: number; y: number; zoom: number } }>()
|
||||
</script>
|
||||
<style scoped>
|
||||
.canvas-guides{position:absolute;inset:0;width:100%;height:100%;z-index:30;pointer-events:none;overflow:hidden}.alignment line{stroke:var(--el-color-danger);stroke-width:1;stroke-dasharray:4 3}.distance line{stroke:var(--el-color-primary);stroke-width:1}.distance text{fill:var(--el-color-primary)}.distance-label{fill:var(--el-bg-color-overlay);stroke:var(--el-color-primary-light-5);stroke-width:0.5;vector-effect:non-scaling-stroke}.section-draft{fill:var(--el-color-primary-light-9);fill-opacity:0.4;stroke:var(--el-color-primary);stroke-width:1;stroke-dasharray:6 4}
|
||||
</style>
|
||||
@ -0,0 +1,33 @@
|
||||
<template>
|
||||
<div class="canvas-section" :aria-label="`分区:${section.name}`">
|
||||
<header class="section-drag">
|
||||
<el-input v-if="editing" ref="input" v-model="name" size="small" maxlength="100" class="nodrag nopan" aria-label="分区名称" @pointerdown.stop @mousedown.stop @keydown.enter.prevent="submit" @keydown.esc.prevent.stop="cancel" @blur="submit" />
|
||||
<button v-else class="section-name" type="button" :title="section.name + ';双击修改名称'" @dblclick.stop="edit">{{ section.name }}</button>
|
||||
<button type="button" class="nodrag nopan section-action" aria-label="修改分区名称" :disabled="disabled" @pointerdown.stop @mousedown.stop @click.stop="edit"><EditPen /></button>
|
||||
<button type="button" class="nodrag nopan section-action remove" aria-label="删除分区,保留阶段" title="删除分区,保留阶段" :disabled="disabled" @pointerdown.stop @mousedown.stop @click.stop="emit('remove', section.id)"><Delete /></button>
|
||||
<span class="section-grip" title="拖动分区及其内部节点">⠿</span>
|
||||
</header>
|
||||
<button type="button" class="section-resize nodrag nopan" aria-label="调整分区大小" :disabled="disabled" @pointerdown.stop.prevent="emit('resize', section.id, $event)"></button>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref } 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 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) }
|
||||
/** Escape 放弃本次标题草稿,随后到达的 blur 不能再次提交。 */
|
||||
function cancel() { editing.value = 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}
|
||||
.section-drag{height:34px;display:flex;align-items:center;gap:5px;padding:0 10px;box-sizing:border-box;pointer-events:auto;cursor:grab;background:color-mix(in srgb,var(--el-color-primary) 10%,var(--el-bg-color));border-radius:11px 11px 0 0;color:var(--el-text-color-primary)}
|
||||
.section-name{min-width:0;flex:0 1 auto;text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:transparent;color:inherit;font-size:12px;font-weight:600;padding:0;cursor:text}.section-action{width:20px;height:22px;flex:none;display:inline-flex;align-items:center;justify-content:center;border:0;border-radius:3px;background:transparent;color:var(--el-color-primary);cursor:pointer;padding:3px}.section-action svg{width:14px;height:14px}.section-action.remove{color:var(--el-color-danger)}.section-action:hover{background:var(--el-fill-color)}.section-grip{margin-left:auto;color:var(--el-text-color-secondary)}
|
||||
.section-resize{position:absolute;right:0;bottom:0;width:20px;height:20px;pointer-events:auto;border:0;background:linear-gradient(135deg,transparent 55%,var(--el-color-primary) 56%,var(--el-color-primary) 62%,transparent 63%,transparent 72%,var(--el-color-primary) 73%,var(--el-color-primary) 79%,transparent 80%);cursor:nwse-resize}
|
||||
</style>
|
||||
@ -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<boolean>, interrupted: ComputedRef<boolean>) {
|
||||
export function useCanvasGestureCleanup(gestureActive: ComputedRef<boolean>, interrupted: ComputedRef<boolean>, cancelSelection?: () => void) {
|
||||
let pointer = { x: 0, y: 0 }, finishing = false, suppressInterruptedClick = false
|
||||
|
||||
/** 仅记录坐标,不捕获或阻止事件,使鼠标释放仍由 Vue Flow 自己处理。 */
|
||||
@ -28,6 +29,7 @@ export function useCanvasGestureCleanup(gestureActive: ComputedRef<boolean>, 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 })) }
|
||||
|
||||
@ -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<Ref<GraphNode<FlowNodeData>[]>>
|
||||
viewport: Readonly<Ref<Point & { zoom: number }>>
|
||||
enabled: Readonly<Ref<boolean>>
|
||||
toFlow: (point: Point) => Point
|
||||
changed: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理纯展示的分区、框选排版和拖动辅助,不调用业务接口或改变阶段父子关系。
|
||||
* @param options 当前 Vue Flow 实例、坐标转换及本地保存回调;不得传入其他项目画布的节点
|
||||
* @returns 工具状态与事件处理器;浏览器手势监听在结束、失焦、页签隐藏和卸载时释放
|
||||
*/
|
||||
export function useCanvasTools(options: CanvasToolsOptions) {
|
||||
const 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)
|
||||
let pointerCleanup: ((commit: boolean) => void) | null = null
|
||||
let dragActive = false
|
||||
let carried: { id: string; sectionId: string; position: Point; origin: Point }[] = []
|
||||
const carriedChildren = new Map<string, Point>()
|
||||
|
||||
/** 同层排版用相对矩形;辅助线另取绝对坐标,不能混用这两个坐标空间。 */
|
||||
function localBox(node: Node<FlowNodeData>): 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<FlowNodeData>[]) {
|
||||
carried = []; carriedChildren.clear()
|
||||
const moved = new Set(moving.map(node => node.id)), captured = new Set<string>()
|
||||
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<string, Point> = { 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<CanvasBox, 'id'>) {
|
||||
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<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 } }))
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
@ -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<T extends CanvasBox>(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<string, Point> | 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<string, CanvasGuide>()
|
||||
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<string>(), 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
|
||||
}
|
||||
@ -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<string, Point>,
|
||||
}
|
||||
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<string, Point>,
|
||||
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<FlowNodeData>[], edges: Edge<Flow
|
||||
|
||||
/** 将相对子节点转为绝对矩形,用于适应画布和回退通道,避免硬编码阶段组尺寸。 */
|
||||
export function absoluteRectangle(node: Node<FlowNodeData>, nodes: Node<FlowNodeData>[]): 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)
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
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>
|
||||
@ -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 }
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user