Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c832988a2 | |||
| 95e8a57019 | |||
| 6b74629d98 | |||
| 33f5c076f6 | |||
| bcf810998d | |||
| f657052fe9 | |||
| fb737eeb0b | |||
| 6576a45c0a |
@@ -14,6 +14,6 @@ This block is written and re-added by `next dev` — verify at `node_modules/nex
|
|||||||
- 按逻辑完整、可验证的工作单元提交;同一目标可以包含多个 commit。目标或可交付阶段完成并通过适当检查后,主动推送,不必每次提交后立即推送。
|
- 按逻辑完整、可验证的工作单元提交;同一目标可以包含多个 commit。目标或可交付阶段完成并通过适当检查后,主动推送,不必每次提交后立即推送。
|
||||||
- 连续收到需求时,结合当前目标判断是继续同一工作单元,还是拆成独立提交;不要把无关需求混进同一个 commit。尚未验证或未完成的工作如实报告,不把推送成功当作功能验证通过。
|
- 连续收到需求时,结合当前目标判断是继续同一工作单元,还是拆成独立提交;不要把无关需求混进同一个 commit。尚未验证或未完成的工作如实报告,不把推送成功当作功能验证通过。
|
||||||
- 每次提交前审查差异和暂存区,推送前检查远程状态和待推送 commit;只纳入本次负责的改动。保留用户或其他任务的未提交、未跟踪文件,不擅自暂存、丢弃、stash 或提交。
|
- 每次提交前审查差异和暂存区,推送前检查远程状态和待推送 commit;只纳入本次负责的改动。保留用户或其他任务的未提交、未跟踪文件,不擅自暂存、丢弃、stash 或提交。
|
||||||
- 分支和 PR 方式遵循用户当前明确授权。本项目当前阶段已获授权直接推送 main、暂不创建 PR;该阶段结束或用户调整约定后,恢复全局工作分支和 PR 流程。不得把主动管理 Git 理解为强推、重写共享历史、自行合并 PR 或绕过权限的授权。
|
- 分支和 PR 方式遵循用户当前明确授权。本项目已恢复工作分支和 PR 流程:完成并验证后推送工作分支、创建或更新面向 main 的 PR,等待用户手动合并;不直接推送 main,也不自行合并 PR。不得把主动管理 Git 理解为强推、重写共享历史、自行合并 PR 或绕过权限的授权。
|
||||||
- 涉及 gitea.entroia.com 时始终使用专用 codex-bot 身份和隔离 SSH 配置,遵守全局身份约定。
|
- 涉及 gitea.entroia.com 时始终使用专用 codex-bot 身份和隔离 SSH 配置,遵守全局身份约定。
|
||||||
- 每次交付用中文简要说明涉及的文件与修改目的、检查结果、分支、commit 标识及 push 状态;有阻碍及时说明,已获授权的常规操作无需反复询问。
|
- 每次交付用中文简要说明涉及的文件与修改目的、检查结果、分支、commit 标识及 push 状态;有阻碍及时说明,已获授权的常规操作无需反复询问。
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* 旧版画布的节点AI浮层。通过useCanvasAI返回的控制接口管理生成,模型目录由旧画布AI接口读取。
|
||||||
|
* 配置草稿保存在本地state,save回调将配置写回旧节点;本组件不承担新版ledger调度与恢复。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { NodeToolbar, Position } from "@xyflow/react";
|
import { NodeToolbar, Position } from "@xyflow/react";
|
||||||
@@ -8,6 +12,7 @@ import { CANVAS_ACCEPT, managedImageSource } from "@/lib/canvas-v2";
|
|||||||
import type { CanvasNode } from "@/lib/canvas";
|
import type { CanvasNode } from "@/lib/canvas";
|
||||||
import type { CanvasModel, useCanvasAI } from "./use-canvas-ai";
|
import type { CanvasModel, useCanvasAI } from "./use-canvas-ai";
|
||||||
import styles from "./canvas.module.css";
|
import styles from "./canvas.module.css";
|
||||||
|
/** 以boardId+node.id定位run步骤,列表最后一项作为当前任务;NodeToolbar将面板附着在显示节点下方。 */
|
||||||
export function AIPanel({ id, node, workspace, boardId, ai, save }: { id: string; node: CanvasNode; workspace: string; boardId: string; ai: ReturnType<typeof useCanvasAI>; save: (patch: NonNullable<CanvasNode["data"]["ai"]>) => void }) {
|
export function AIPanel({ id, node, workspace, boardId, ai, save }: { id: string; node: CanvasNode; workspace: string; boardId: string; ai: ReturnType<typeof useCanvasAI>; save: (patch: NonNullable<CanvasNode["data"]["ai"]>) => void }) {
|
||||||
const [models, setModels] = useState<CanvasModel[]>([]);
|
const [models, setModels] = useState<CanvasModel[]>([]);
|
||||||
const [model, setModel] = useState(node.data.ai?.modelId || "");
|
const [model, setModel] = useState(node.data.ai?.modelId || "");
|
||||||
@@ -19,7 +24,10 @@ export function AIPanel({ id, node, workspace, boardId, ai, save }: { id: string
|
|||||||
const image = ["image", "plain-image"].includes(node.data.kind);
|
const image = ["image", "plain-image"].includes(node.data.kind);
|
||||||
const relevant = [...ai.runs.values()].filter((run) => run.steps?.some((step) => step.board_id === boardId && step.node_id === node.id));
|
const relevant = [...ai.runs.values()].filter((run) => run.steps?.some((step) => step.board_id === boardId && step.node_id === node.id));
|
||||||
const run = relevant.at(-1), step = run?.steps?.find((step) => step.board_id === boardId && step.node_id === node.id);
|
const run = relevant.at(-1), step = run?.steps?.find((step) => step.board_id === boardId && step.node_id === node.id);
|
||||||
|
// starting防止本地重复启动,之后以步骤queued/running判断生成忙碌;这不是整份画布的同步锁。
|
||||||
const busy = starting || step?.status === "queued" || step?.status === "running";
|
const busy = starting || step?.status === "queued" || step?.status === "running";
|
||||||
|
// 演示/非live路径不请求模型;真实路径按输出模态筛选,并保留仍兼容选择或回退到首个可用模型。
|
||||||
|
// 清理时abort,失败和finally检查signal再更新;成功分支直接采用api返回的结果。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!ai.live) { setLoading(false); return; }
|
if (!ai.live) { setLoading(false); return; }
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
@@ -30,10 +38,16 @@ export function AIPanel({ id, node, workspace, boardId, ai, save }: { id: string
|
|||||||
}).catch((error) => { if (!controller.signal.aborted) setError(errorText(error)); }).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
}).catch((error) => { if (!controller.signal.aborted) setError(errorText(error)); }).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [workspace, boardId, image, ai.live]);
|
}, [workspace, boardId, image, ai.live]);
|
||||||
|
/** 构造当前输入配置,参数固定为空对象;状态切换事件需显式替换刚改变的值,避免读取旧React state。 */
|
||||||
const config = () => ({ enabled: true, modelId: model, prompt, propagate, parameters: {} });
|
const config = () => ({ enabled: true, modelId: model, prompt, propagate, parameters: {} });
|
||||||
|
/** 输入blur时,有模型且live才调用save;仅持久化配置,不启动服务端任务。 */
|
||||||
const persist = () => { if (model && ai.live) save(config()); };
|
const persist = () => { if (model && ai.live) save(config()); };
|
||||||
|
// output取当前步骤资源,文本内容则从最后一个step.output事件取;两者按同一board/node限定。
|
||||||
const output = run?.outputs?.find((item) => item.step_id === step?.step_id)?.output;
|
const output = run?.outputs?.find((item) => item.step_id === step?.step_id)?.output;
|
||||||
const textOutput = run?.events?.filter((event) => event.type === "step.output" && event.node_id === node.id && event.board_id === boardId).at(-1)?.output?.text;
|
const textOutput = run?.events?.filter((event) => event.type === "step.output" && event.node_id === node.id && event.board_id === boardId).at(-1)?.output?.text;
|
||||||
|
// 模型和传播开关变化即时save,正文blur保存;执行由ai.run负责,starting在finally复位。
|
||||||
|
// 上传中、演示或没有可用模型禁止启动;与新版不同,此处未要求prompt非空,也未在busy时禁用textarea。
|
||||||
|
// 冲突时保留结果并给显式apply入口,错误优先显示本面板错误;关闭/取消任务的行为交由父层与ai接口决定。
|
||||||
return <NodeToolbar nodeId={id} isVisible position={Position.Bottom} offset={26} style={{ zIndex: 110 }}><section className={`${styles.aiPanel} nodrag nopan nowheel`} aria-label="元素 AI 工具"
|
return <NodeToolbar nodeId={id} isVisible position={Position.Bottom} offset={26} style={{ zIndex: 110 }}><section className={`${styles.aiPanel} nodrag nopan nowheel`} aria-label="元素 AI 工具"
|
||||||
onPointerDown={(event) => event.stopPropagation()} onClick={(event) => event.stopPropagation()} onDoubleClick={(event) => event.stopPropagation()} onKeyDown={(event) => event.stopPropagation()}>
|
onPointerDown={(event) => event.stopPropagation()} onClick={(event) => event.stopPropagation()} onDoubleClick={(event) => event.stopPropagation()} onKeyDown={(event) => event.stopPropagation()}>
|
||||||
<header><Sparkles size={14} /><strong>{image ? "图像创作" : "文本创作"}</strong><span>{node.data.title}</span></header>
|
<header><Sparkles size={14} /><strong>{image ? "图像创作" : "文本创作"}</strong><span>{node.data.title}</span></header>
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* 旧版画布未同步草稿的选择对话框。通过原生dialog提供模态展示,把恢复、导出或使用服务端版本交给调用方。
|
||||||
|
* 本组件不读取草稿、不写服务端,也不判断本地内容是否能安全覆盖;canRestore由上层计算。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import styles from "./canvas.module.css";
|
import styles from "./canvas.module.css";
|
||||||
|
/** 可恢复时显示恢复按钮,否则提示子图关系变化;导出按钮仅在提供exportDraft回调时出现。 */
|
||||||
export function DraftRecovery({ restore, discard, canRestore = true, exportDraft }: { restore: () => void; discard: () => void; canRestore?: boolean; exportDraft?: () => void }) {
|
export function DraftRecovery({ restore, discard, canRestore = true, exportDraft }: { restore: () => void; discard: () => void; canRestore?: boolean; exportDraft?: () => void }) {
|
||||||
const dialog = useRef<HTMLDialogElement>(null);
|
const dialog = useRef<HTMLDialogElement>(null);
|
||||||
|
// 挂载时showModal启用浏览器模态行为,卸载时close;不额外保存一份open状态。
|
||||||
useEffect(() => { const element = dialog.current; element?.showModal(); return () => element?.close(); }, []);
|
useEffect(() => { const element = dialog.current; element?.showModal(); return () => element?.close(); }, []);
|
||||||
|
// 无document不创建Portal;取消事件阻止默认Escape关闭,要求用户通过明确的版本选择按钮处理。
|
||||||
if (typeof document === "undefined") return null;
|
if (typeof document === "undefined") return null;
|
||||||
return createPortal(<dialog ref={dialog} className={styles.recoveryDialog} aria-labelledby="draft-recovery-title" onCancel={(event) => event.preventDefault()}>
|
return createPortal(<dialog ref={dialog} className={styles.recoveryDialog} aria-labelledby="draft-recovery-title" onCancel={(event) => event.preventDefault()}>
|
||||||
<h2 id="draft-recovery-title">发现未同步的本地草稿</h2><p>{canRestore ? "服务端画布已读取。恢复草稿会以本地内容替换当前服务端版本,请选择要继续编辑的版本。" : "画布的子图关系已更新,这份旧草稿不能直接覆盖。可以先导出草稿,再使用服务端版本继续编辑。"}</p>
|
<h2 id="draft-recovery-title">发现未同步的本地草稿</h2><p>{canRestore ? "服务端画布已读取。恢复草稿会以本地内容替换当前服务端版本,请选择要继续编辑的版本。" : "画布的子图关系已更新,这份旧草稿不能直接覆盖。可以先导出草稿,再使用服务端版本继续编辑。"}</p>
|
||||||
|
|||||||
@@ -1,3 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* 旧版主画布的界面装配与交互控制。useCanvasTree拥有旧快照、writer、历史和子图事务,组件把其投影交给ReactFlow。
|
||||||
|
* 本地state管理工具、模式、菜单与提示,refs保存拖动/连线起点及文件选择上下文;真实上传与演示Data URL分别处理。
|
||||||
|
* 节点/连线组件通过Context调用适配动作,不直接修改投影;子图归属、端口连线和解散优先使用服务端能力与事务。
|
||||||
|
* 迁移门闩暂停旧编辑和创作入口,给迁移协调组件提供检查、保存排空与备份;本文件不自行切换到新版engine。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
import { useImageUploads } from "./use-image-uploads";
|
import { useImageUploads } from "./use-image-uploads";
|
||||||
import {LegacyCanvasMigration} from "./legacy-canvas-migration";
|
import {LegacyCanvasMigration} from "./legacy-canvas-migration";
|
||||||
@@ -41,15 +47,21 @@ import type { NodeTransform } from "@/lib/canvas-geometry";
|
|||||||
import { MaterialNode, NodeEditing } from "./material-node";
|
import { MaterialNode, NodeEditing } from "./material-node";
|
||||||
import styles from "./canvas.module.css";
|
import styles from "./canvas.module.css";
|
||||||
|
|
||||||
|
/** 旧边统一使用可编辑贝塞尔组件,节点按旧type名称分派;类型映射本身不持有元素实例数据。 */
|
||||||
const edgeTypes = { default: CanvasEdge };
|
const edgeTypes = { default: CanvasEdge };
|
||||||
|
/** 图标面板延迟在客户端加载,避免首屏加载目录面板及其交互代码;加载中提供可访问状态。 */
|
||||||
const IconPicker = dynamic(() => import("./icon-picker").then((module) => module.IconPicker), { ssr: false, loading: () => <div role="status" className={styles.iconLoading}>正在加载图标面板…</div> });
|
const IconPicker = dynamic(() => import("./icon-picker").then((module) => module.IconPicker), { ssr: false, loading: () => <div role="status" className={styles.iconLoading}>正在加载图标面板…</div> });
|
||||||
|
/** ReactFlow type到节点展示组件的固定表,须与makeCanvasNode/投影生成的type保持一致。 */
|
||||||
const nodeTypes = { material: MaterialNode, plainText: PlainTextNode, icon: IconNode, frame: FrameNode, plainImage: PlainImageNode };
|
const nodeTypes = { material: MaterialNode, plainText: PlainTextNode, icon: IconNode, frame: FrameNode, plainImage: PlainImageNode };
|
||||||
|
|
||||||
|
/** 每个挂载对应一个board身份,初始快照/草稿只在useState初始化时采用;切画布应由上层key重挂载。 */
|
||||||
function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?: CanvasSnapshot; migration?:LegacyMigrationContext }) {
|
function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?: CanvasSnapshot; migration?:LegacyMigrationContext }) {
|
||||||
const flow = useReactFlow<CanvasNode>();
|
const flow = useReactFlow<CanvasNode>();
|
||||||
const { zoom } = useViewport();
|
const { zoom } = useViewport();
|
||||||
const reduceMotion = useReducedMotion();
|
const reduceMotion = useReducedMotion();
|
||||||
const storageKey = canvasStorageKey(board.workspace_id, board.id);
|
const storageKey = canvasStorageKey(board.workspace_id, board.id);
|
||||||
|
// 服务端快照优先,另有不同本地内容则等待恢复选择;无快照可直接用草稿。
|
||||||
|
// 视口独立读本地键并限制范围,损坏视口不阻断文档;草稿解码失败回退快照/空文档并提示。
|
||||||
const [initial] = useState(() => {
|
const [initial] = useState(() => {
|
||||||
try {
|
try {
|
||||||
const local = readLocalRecovery(localStorage, storageKey, snapshot);
|
const local = readLocalRecovery(localStorage, storageKey, snapshot);
|
||||||
@@ -62,6 +74,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
} catch { return { document: snapshot?.document || emptyCanvas(), recovery: null, error: "无法读取此浏览器的图谱草稿,可通过导入恢复备份。" }; }
|
} catch { return { document: snapshot?.document || emptyCanvas(), recovery: null, error: "无法读取此浏览器的图谱草稿,可通过导入恢复备份。" }; }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 工具与变换模式是界面状态,不放入文档;draggedIds仅驱动成员预览,membershipNotice短暂展示结果。
|
||||||
const [tool, setTool] = useState<"select" | "hand">("select");
|
const [tool, setTool] = useState<"select" | "hand">("select");
|
||||||
const [error, setError] = useState(initial.error);
|
const [error, setError] = useState(initial.error);
|
||||||
const feedback = useContext(FeedbackContext);
|
const feedback = useContext(FeedbackContext);
|
||||||
@@ -72,26 +85,35 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
const [rotating, setRotating] = useState<string | null>(null);
|
const [rotating, setRotating] = useState<string | null>(null);
|
||||||
const [draggedIds, setDraggedIds] = useState<string[]>([]);
|
const [draggedIds, setDraggedIds] = useState<string[]>([]);
|
||||||
const [membershipNotice, setMembershipNotice] = useState("");
|
const [membershipNotice, setMembershipNotice] = useState("");
|
||||||
|
// 防节点拖动与多选拖动回调重复进入;起点按显示ID保存,连线屏幕起点用于区分点击与拉出新分支。
|
||||||
const dragSession = useRef<"idle" | "active" | "finishing">("idle");
|
const dragSession = useRef<"idle" | "active" | "finishing">("idle");
|
||||||
const dragOrigins = useRef(new Map<string, XYPosition>());
|
const dragOrigins = useRef(new Map<string, XYPosition>());
|
||||||
const draggingFrame = useRef(false);
|
const draggingFrame = useRef(false);
|
||||||
const connectionStart = useRef<{ id: string; direction: NodeDirection; point: XYPosition } | null>(null);
|
const connectionStart = useRef<{ id: string; direction: NodeDirection; point: XYPosition } | null>(null);
|
||||||
|
// 图片分支先保留源节点/方向/位置,等文件选择返回;cancel事件要清它,不能沿用上次创建意图。
|
||||||
const pendingImage = useRef<BranchRequest | null>(null);
|
const pendingImage = useRef<BranchRequest | null>(null);
|
||||||
|
/** 稳定关闭回调供Portal菜单与画布事件共用,避免菜单因每次渲染重新安装监听。 */
|
||||||
const closeBranch = useCallback(() => setBranchRequest(null), []);
|
const closeBranch = useCallback(() => setBranchRequest(null), []);
|
||||||
const imageKind = useRef<"image" | "plain-image">("image");
|
const imageKind = useRef<"image" | "plain-image">("image");
|
||||||
const imageInput = useRef<HTMLInputElement>(null);
|
const imageInput = useRef<HTMLInputElement>(null);
|
||||||
const projectInput = useRef<HTMLInputElement>(null);
|
const projectInput = useRef<HTMLInputElement>(null);
|
||||||
const [recovery, setRecovery] = useState(initial.recovery);
|
const [recovery, setRecovery] = useState(initial.recovery);
|
||||||
|
// 根恢复待决时暂停保存;tree负责真实owner文档,UI显示节点来自其树投影。子图恢复按Map首项逐个处理。
|
||||||
const tree = useCanvasTree(board.id, board.workspace_id, initial.document, snapshot, Boolean(recovery), board.parent_board_id, migration);
|
const tree = useCanvasTree(board.id, board.workspace_id, initial.document, snapshot, Boolean(recovery), board.parent_board_id, migration);
|
||||||
const childRecovery = [...tree.recoveries][0];
|
const childRecovery = [...tree.recoveries][0];
|
||||||
|
/** 下载单份内存文档JSON备份,稍后释放Blob URL;不修改草稿选择,也不保证包含所有子图。 */
|
||||||
const downloadDraft = (document: import("@/lib/canvas").CanvasDocument) => { const url = URL.createObjectURL(new Blob([JSON.stringify(document, null, 2)], { type: "application/json" })); const link = window.document.createElement("a"); link.href = url; link.download = "画布本地草稿.json"; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); };
|
const downloadDraft = (document: import("@/lib/canvas").CanvasDocument) => { const url = URL.createObjectURL(new Blob([JSON.stringify(document, null, 2)], { type: "application/json" })); const link = window.document.createElement("a"); link.href = url; link.download = "画布本地草稿.json"; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); };
|
||||||
const sync = tree;
|
const sync = tree;
|
||||||
|
// snapshot存在才执行真实AI;state.present组合根元数据与整树显示节点/边,不能把它当单board持久快照。
|
||||||
const ai = useCanvasAI(board.workspace_id, board.id, !!snapshot, tree);
|
const ai = useCanvasAI(board.workspace_id, board.id, !!snapshot, tree);
|
||||||
const state = { present: { ...tree.rootDocument, nodes: tree.views.nodes, edges: tree.views.edges } };
|
const state = { present: { ...tree.rootDocument, nodes: tree.views.nodes, edges: tree.views.edges } };
|
||||||
const treeRef = useRef(tree); treeRef.current = tree;
|
const treeRef = useRef(tree); treeRef.current = tree;
|
||||||
|
// 上传完成回调通过treeRef定位当前归属,并更新当前文档与历史;job.owner可能已不再是最新owner。
|
||||||
const uploads = useImageUploads(board.workspace_id, (job, asset) => treeRef.current.resolveImageUpload(job.node.id, asset,{width:job.node.width!,height:job.node.height!}));
|
const uploads = useImageUploads(board.workspace_id, (job, asset) => treeRef.current.resolveImageUpload(job.node.id, asset,{width:job.node.width!,height:job.node.height!}));
|
||||||
const imageUploading = demoImageUploading;
|
const imageUploading = demoImageUploading;
|
||||||
|
// 文件导入等待期间的迁移检查标记;这不是通用导入队列,也不提供并发文件事务锁。
|
||||||
const ioActive=useRef(false);
|
const ioActive=useRef(false);
|
||||||
|
// 上传任务与文档都可能变化:按pendingUpload重新找owner,补资源或纯图片默认尺寸,避免移动/撤销后遗漏占位。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const current = treeRef.current;
|
const current = treeRef.current;
|
||||||
for (const job of uploads.jobs) {
|
for (const job of uploads.jobs) {
|
||||||
@@ -102,38 +124,48 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
if (node.data.kind==="plain-image"&&node.width===320&&node.height===240&&(job.node.width!==320||job.node.height!==240)) current.resolveImageUpload(job.node.id,undefined,{width:job.node.width!,height:job.node.height!});
|
if (node.data.kind==="plain-image"&&node.width===320&&node.height===240&&(job.node.width!==320||job.node.height!==240)) current.resolveImageUpload(job.node.id,undefined,{width:job.node.width!,height:job.node.height!});
|
||||||
}
|
}
|
||||||
}, [uploads.jobs,tree.documents]);
|
}, [uploads.jobs,tree.documents]);
|
||||||
|
/** undo/redo走异步树历史接口并显示失败,其余动作走根document reducer;不把服务端事务撤销当普通reducer动作。 */
|
||||||
function dispatch(action: CanvasAction) {
|
function dispatch(action: CanvasAction) {
|
||||||
if (action.type === "undo" || action.type === "redo") { void treeRef.current[action.type]().catch((error) => setError(error.message)); return; }
|
if (action.type === "undo" || action.type === "redo") { void treeRef.current[action.type]().catch((error) => setError(error.message)); return; }
|
||||||
treeRef.current.dispatch(action);
|
treeRef.current.dispatch(action);
|
||||||
}
|
}
|
||||||
|
// 浏览器文件选择取消不触发普通onChange,单独监听cancel清理待建图片分支;卸载拆监听。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const input = imageInput.current;
|
const input = imageInput.current;
|
||||||
|
/** 取消本次选择意图,不删除已经存在的图片节点或中止已启动上传。 */
|
||||||
const cancel = () => { pendingImage.current = null; };
|
const cancel = () => { pendingImage.current = null; };
|
||||||
input?.addEventListener("cancel", cancel);
|
input?.addEventListener("cancel", cancel);
|
||||||
return () => input?.removeEventListener("cancel", cancel);
|
return () => input?.removeEventListener("cancel", cancel);
|
||||||
}, []);
|
}, []);
|
||||||
const { nodes: displayNodes, edges } = state.present;
|
const { nodes: displayNodes, edges } = state.present;
|
||||||
|
// 对成员任务保护节点关闭拖动/删除/连接;tree.update内部仍保护相应数据,界面禁用不是唯一护栏。
|
||||||
const nodes = displayNodes.map((node) => { const ref = tree.views.nodeRefs.get(node.id); const blocked = ref && tree.protectedNodes(ref.boardId).has(ref.id); return blocked ? { ...node, draggable: false, deletable: false, connectable: false } : node; });
|
const nodes = displayNodes.map((node) => { const ref = tree.views.nodeRefs.get(node.id); const blocked = ref && tree.protectedNodes(ref.boardId).has(ref.id); return blocked ? { ...node, draggable: false, deletable: false, connectable: false } : node; });
|
||||||
|
/** 上传任务的本地nodeID映射到当前场景ID;尚无投影时按根/原owner构造兼容显示ID。 */
|
||||||
const uploadDisplayID = (job: typeof uploads.jobs[number]) => [...tree.views.nodeRefs].find(([,ref])=>ref.id===job.node.id)?.[0] || displayID(board.id,job.owner,job.node.id);
|
const uploadDisplayID = (job: typeof uploads.jobs[number]) => [...tree.views.nodeRefs].find(([,ref])=>ref.id===job.node.id)?.[0] || displayID(board.id,job.owner,job.node.id);
|
||||||
|
// 预览URL按显示ID提供;正式图片onLoad再映射回job,上传完成的任务才回收本地URL。
|
||||||
const imagePreviews = { sources: new Map(uploads.jobs.map((job) => [uploadDisplayID(job),job.localURL])), loaded: (id: string) => { const job = uploads.jobs.find((job) => uploadDisplayID(job)===id);if(job) uploads.loaded(job.node.id); } };
|
const imagePreviews = { sources: new Map(uploads.jobs.map((job) => [uploadDisplayID(job),job.localURL])), loaded: (id: string) => { const job = uploads.jobs.find((job) => uploadDisplayID(job)===id);if(job) uploads.loaded(job.node.id); } };
|
||||||
|
|
||||||
|
// 从场景节点派生分区名称、已有frameId计数与本次拖入/拖出候选,只作显示,不在此改变owner。
|
||||||
const frameFeedback = useMemo(() => {
|
const frameFeedback = useMemo(() => {
|
||||||
const names = new Map(nodes.filter((node) => node.data.kind === "frame").map((node) => [node.id, node.data.title]));
|
const names = new Map(nodes.filter((node) => node.data.kind === "frame").map((node) => [node.id, node.data.title]));
|
||||||
const counts = new Map<string, number>();
|
const counts = new Map<string, number>();
|
||||||
for (const node of nodes) if (node.data.frameId) counts.set(node.data.frameId, (counts.get(node.data.frameId) || 0) + 1);
|
for (const node of nodes) if (node.data.frameId) counts.set(node.data.frameId, (counts.get(node.data.frameId) || 0) + 1);
|
||||||
return { names, counts, drops: frameDropFeedback(nodes, draggedIds) };
|
return { names, counts, drops: frameDropFeedback(nodes, draggedIds) };
|
||||||
}, [nodes, draggedIds]);
|
}, [nodes, draggedIds]);
|
||||||
|
// 成员提示四秒后清理;重新提示重置计时器,卸载取消。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!membershipNotice) return;
|
if (!membershipNotice) return;
|
||||||
const timer = setTimeout(() => setMembershipNotice(""), 4000);
|
const timer = setTimeout(() => setMembershipNotice(""), 4000);
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, [membershipNotice]);
|
}, [membershipNotice]);
|
||||||
|
// 全局反馈可用时把本地错误转成稳定ID通知并清本地error;无Provider时保留底部内联提示。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!feedback || !error) return;
|
if (!feedback || !error) return;
|
||||||
const id = `canvas:${board.id}:error`;
|
const id = `canvas:${board.id}:error`;
|
||||||
notify({ id, level: "error", title: error });
|
notify({ id, level: "error", title: error });
|
||||||
setError("");
|
setError("");
|
||||||
}, [feedback, error, board.id]);
|
}, [feedback, error, board.id]);
|
||||||
|
// 成员通知使用board级稳定ID,内容变化替换旧通知,清理时显式dismiss。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!feedback || !membershipNotice) return;
|
if (!feedback || !membershipNotice) return;
|
||||||
const id = `canvas:${board.id}:membership`;
|
const id = `canvas:${board.id}:membership`;
|
||||||
@@ -141,29 +173,40 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
return () => dismissNotification(id);
|
return () => dismissNotification(id);
|
||||||
}, [feedback, membershipNotice, board.id]);
|
}, [feedback, membershipNotice, board.id]);
|
||||||
const duration = reduceMotion ? 0 : 180;
|
const duration = reduceMotion ? 0 : 180;
|
||||||
|
/** 视口派发给根并独立写本地键;存储失败不打断浏览,内容writer自行判断是否需要服务端保存。 */
|
||||||
const rememberViewport = (viewport: import("@xyflow/react").Viewport) => {
|
const rememberViewport = (viewport: import("@xyflow/react").Viewport) => {
|
||||||
treeRef.current.dispatch({ type: "viewport", viewport });
|
treeRef.current.dispatch({ type: "viewport", viewport });
|
||||||
try { localStorage.setItem(storageKey + ":viewport", JSON.stringify(viewport)); } catch { /* View changes do not require server writes. */ }
|
try { localStorage.setItem(storageKey + ":viewport", JSON.stringify(viewport)); } catch { /* View changes do not require server writes. */ }
|
||||||
};
|
};
|
||||||
|
/** 工具栏视口动画完成后保存实际视口;错误转界面提示,不提前记录尚未完成的目标值。 */
|
||||||
const changeView = (operation: () => Promise<boolean>) => {
|
const changeView = (operation: () => Promise<boolean>) => {
|
||||||
void operation().then(() => rememberViewport(flow.getViewport())).catch((error) => setError(error.message));
|
void operation().then(() => rememberViewport(flow.getViewport())).catch((error) => setError(error.message));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// latest保留当前显示几何,拖动结束基于最新节点计算成员反馈,避免只使用开始时的闭包。
|
||||||
const latest = useRef(state.present);
|
const latest = useRef(state.present);
|
||||||
latest.current = state.present;
|
latest.current = state.present;
|
||||||
|
|
||||||
|
/** 显示ID的选择交tree解析owner;稳定回调通过treeRef避免每次文档更新重建编辑上下文。 */
|
||||||
const select = useCallback((id: string) => treeRef.current.select(id), []);
|
const select = useCallback((id: string) => treeRef.current.select(id), []);
|
||||||
|
/** 对目标owner建立checkpoint,把后续连续编辑归到同一撤销起点;缺目标时使用根board。 */
|
||||||
const beginEdit = useCallback((id?: string) => { const current = treeRef.current; const ref = id ? current.views.nodeRefs.get(id) || current.views.edgeRefs.get(id) : undefined; current.dispatch({ type: "checkpoint" }, ref?.boardId || board.id); }, [board.id]);
|
const beginEdit = useCallback((id?: string) => { const current = treeRef.current; const ref = id ? current.views.nodeRefs.get(id) || current.views.edgeRefs.get(id) : undefined; current.dispatch({ type: "checkpoint" }, ref?.boardId || board.id); }, [board.id]);
|
||||||
|
/** 正文动作按投影ID定位原节点,reducer处理文本值与历史。 */
|
||||||
const edit = useCallback((id: string, text: string) => treeRef.current.nodeAction(id, (id) => ({ type: "edit", id, text })), []);
|
const edit = useCallback((id: string, text: string) => treeRef.current.nodeAction(id, (id) => ({ type: "edit", id, text })), []);
|
||||||
|
/** 打开分支类型菜单并退出变换模式,point用于屏幕定位。 */
|
||||||
const branch = useCallback((id: string, direction: NodeDirection, point: XYPosition) => { setBranchRequest({ id, direction, point }); setRotating(null); setResizing(null); }, []);
|
const branch = useCallback((id: string, direction: NodeDirection, point: XYPosition) => { setBranchRequest({ id, direction, point }); setRotating(null); setResizing(null); }, []);
|
||||||
|
/** 将场景位置减owner原点再除scale,宽高也除scale;旋转等其余字段直接交旧transform动作。 */
|
||||||
const transform = useCallback((id: string, transform: NodeTransform) => {
|
const transform = useCallback((id: string, transform: NodeTransform) => {
|
||||||
const ref = treeRef.current.views.nodeRefs.get(id); if (!ref) return;
|
const ref = treeRef.current.views.nodeRefs.get(id); if (!ref) return;
|
||||||
treeRef.current.nodeAction(id, (id) => ({ type: "transform", id, transform: { ...transform,
|
treeRef.current.nodeAction(id, (id) => ({ type: "transform", id, transform: { ...transform,
|
||||||
...(transform.position ? { position: { x: (transform.position.x - ref.origin.x) / ref.scale, y: (transform.position.y - ref.origin.y) / ref.scale } } : {}),
|
...(transform.position ? { position: { x: (transform.position.x - ref.origin.x) / ref.scale, y: (transform.position.y - ref.origin.y) / ref.scale } } : {}),
|
||||||
...(transform.width !== undefined ? { width: transform.width / ref.scale, height: transform.height! / ref.scale } : {}) } }));
|
...(transform.width !== undefined ? { width: transform.width / ref.scale, height: transform.height! / ref.scale } : {}) } }));
|
||||||
}, []);
|
}, []);
|
||||||
|
/** 样式适配只构造旧style动作,具体字段合并由reducer处理。 */
|
||||||
const style = useCallback((id: string, style: TextStyle, fontSize?: number) => treeRef.current.nodeAction(id, (id) => ({ type: "style", id, style, fontSize })), []);
|
const style = useCallback((id: string, style: TextStyle, fontSize?: number) => treeRef.current.nodeAction(id, (id) => ({ type: "style", id, style, fontSize })), []);
|
||||||
|
/** 节点名称通过owner映射更新,避免将显示复合ID当持久ID。 */
|
||||||
const rename = useCallback((id: string, title: string) => treeRef.current.nodeAction(id, (id) => ({ type: "rename-node", id, title })), []);
|
const rename = useCallback((id: string, title: string) => treeRef.current.nodeAction(id, (id) => ({ type: "rename-node", id, title })), []);
|
||||||
|
/** 分区属性以replace提交;折叠切换从已保存expanded/collapsedSize或默认值恢复尺寸,并写node与style。 */
|
||||||
const frame = useCallback((id: string, patch: { title?: string; labelMode?: FrameLabelMode; presentation?: import("@/lib/canvas-v2").FramePresentation }) => {
|
const frame = useCallback((id: string, patch: { title?: string; labelMode?: FrameLabelMode; presentation?: import("@/lib/canvas-v2").FramePresentation }) => {
|
||||||
const current = treeRef.current, ref = current.views.nodeRefs.get(id); if (!ref) return;
|
const current = treeRef.current, ref = current.views.nodeRefs.get(id); if (!ref) return;
|
||||||
const document = current.documents.get(ref.boardId)!;
|
const document = current.documents.get(ref.boardId)!;
|
||||||
@@ -174,7 +217,9 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
return { ...node, ...(size ? { ...size, style: { ...node.style, ...size } } : {}), data: { ...node.data, ...patch } };
|
return { ...node, ...(size ? { ...size, style: { ...node.style, ...size } } : {}), data: { ...node.data, ...patch } };
|
||||||
}) } }, ref.boardId);
|
}) } }, ref.boardId);
|
||||||
}, []);
|
}, []);
|
||||||
|
// 注入节点动作及本地旋转/拉伸模式,两模式互斥;旧版接口没有新版手势token租约。
|
||||||
const editing = useMemo(() => ({ begin: beginEdit, select, edit, branch, transform, style, rename, frame, workspace: board.workspace_id, schema: 2 as const, rotating, resizing, resize: (id: string | null) => { setResizing(id); setRotating(null); }, rotate: (id: string | null) => { setRotating(id); setResizing(null); } }), [beginEdit, select, edit, branch, transform, style, rename, frame, rotating, resizing, board.workspace_id, state.present.schema_version]);
|
const editing = useMemo(() => ({ begin: beginEdit, select, edit, branch, transform, style, rename, frame, workspace: board.workspace_id, schema: 2 as const, rotating, resizing, resize: (id: string | null) => { setResizing(id); setRotating(null); }, rotate: (id: string | null) => { setRotating(id); setResizing(null); } }), [beginEdit, select, edit, branch, transform, style, rename, frame, rotating, resizing, board.workspace_id, state.present.schema_version]);
|
||||||
|
/** 在源owner文档创建节点与连线,at从场景坐标转局部;发布后尝试把视口移向新节点,异常留作提示。 */
|
||||||
function createBranch(request: BranchRequest, kind: "text" | "image" | "script", src?: string) {
|
function createBranch(request: BranchRequest, kind: "text" | "image" | "script", src?: string) {
|
||||||
try {
|
try {
|
||||||
const document = branchCanvasNode(tree.documents.get(tree.views.nodeRefs.get(request.id)!.boardId)!, tree.views.nodeRefs.get(request.id)!.id, request.direction, kind, src, request.at ? { x: (request.at.x - tree.views.nodeRefs.get(request.id)!.origin.x) / tree.views.nodeRefs.get(request.id)!.scale, y: (request.at.y - tree.views.nodeRefs.get(request.id)!.origin.y) / tree.views.nodeRefs.get(request.id)!.scale } : undefined);
|
const document = branchCanvasNode(tree.documents.get(tree.views.nodeRefs.get(request.id)!.boardId)!, tree.views.nodeRefs.get(request.id)!.id, request.direction, kind, src, request.at ? { x: (request.at.x - tree.views.nodeRefs.get(request.id)!.origin.x) / tree.views.nodeRefs.get(request.id)!.scale, y: (request.at.y - tree.views.nodeRefs.get(request.id)!.origin.y) / tree.views.nodeRefs.get(request.id)!.scale } : undefined);
|
||||||
@@ -184,11 +229,13 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
setBranchRequest(null);
|
setBranchRequest(null);
|
||||||
} catch (error) { setError(error instanceof Error ? error.message : "无法创建节点。"); }
|
} catch (error) { setError(error instanceof Error ? error.message : "无法创建节点。"); }
|
||||||
}
|
}
|
||||||
|
/** 图片分支需要文件选择才能创建,先保存request并关菜单;文本/脚本立即创建。 */
|
||||||
function chooseBranch(kind: "text" | "image" | "script") {
|
function chooseBranch(kind: "text" | "image" | "script") {
|
||||||
if (!branchRequest) return;
|
if (!branchRequest) return;
|
||||||
if (kind === "image") { pendingImage.current = branchRequest; imageKind.current = "image"; setBranchRequest(null); imageInput.current?.click(); }
|
if (kind === "image") { pendingImage.current = branchRequest; imageKind.current = "image"; setBranchRequest(null); imageInput.current?.click(); }
|
||||||
else createBranch(branchRequest, kind);
|
else createBranch(branchRequest, kind);
|
||||||
}
|
}
|
||||||
|
/** 无有效目标的连接拖动若移动至少5px并落到空白pane,且源仍选中,则在落点打开分支菜单。 */
|
||||||
const connectionEnd: OnConnectEnd = (event, connection) => {
|
const connectionEnd: OnConnectEnd = (event, connection) => {
|
||||||
const start = connectionStart.current;
|
const start = connectionStart.current;
|
||||||
connectionStart.current = null;
|
connectionStart.current = null;
|
||||||
@@ -201,11 +248,13 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
setBranchRequest({ id: start.id, direction: start.direction, point: { x: point.clientX, y: point.clientY }, at });
|
setBranchRequest({ id: start.id, direction: start.direction, point: { x: point.clientX, y: point.clientY }, at });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 按窗口中心转换为场景点并加六档偏移,减少连续添加完全重叠;不是按编辑器容器中心计算。 */
|
||||||
const center = () => {
|
const center = () => {
|
||||||
const point = flow.screenToFlowPosition({ x: window.innerWidth / 2, y: window.innerHeight / 2 });
|
const point = flow.screenToFlowPosition({ x: window.innerWidth / 2, y: window.innerHeight / 2 });
|
||||||
const offset = (nodes.length % 6) * 18;
|
const offset = (nodes.length % 6) * 18;
|
||||||
return { x: point.x - 130 + offset, y: point.y - 80 + offset };
|
return { x: point.x - 130 + offset, y: point.y - 80 + offset };
|
||||||
};
|
};
|
||||||
|
/** 根节点上限500;真实分区走subgraphs命令创建子画布,其它节点本地加入,演示frame也走本地模型。 */
|
||||||
function addNode(kind: CanvasNode["data"]["kind"], src?: string, size?: { width: number; height: number }, title?: string) {
|
function addNode(kind: CanvasNode["data"]["kind"], src?: string, size?: { width: number; height: number }, title?: string) {
|
||||||
if (tree.rootDocument.nodes.length >= 500) { setError("当前图谱已达到 500 个节点,请新建图谱继续创作。"); return; }
|
if (tree.rootDocument.nodes.length >= 500) { setError("当前图谱已达到 500 个节点,请新建图谱继续创作。"); return; }
|
||||||
const node = makeCanvasNode(kind, center(), src);
|
const node = makeCanvasNode(kind, center(), src);
|
||||||
@@ -218,6 +267,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
dispatch({ type: "nodes", changes: [{ type: "add", item: node }] });
|
dispatch({ type: "nodes", changes: [{ type: "add", item: node }] });
|
||||||
setTool("select");
|
setTool("select");
|
||||||
}
|
}
|
||||||
|
/** 一次replace插入三张预填卡片和两条连线,预留三个节点容量并切回选择工具;不触发AI生成。 */
|
||||||
function addTemplate() {
|
function addTemplate() {
|
||||||
if (tree.rootDocument.nodes.length > 497) { setError("当前图谱没有足够空间插入模板。"); return; }
|
if (tree.rootDocument.nodes.length > 497) { setError("当前图谱没有足够空间插入模板。"); return; }
|
||||||
const position = center();
|
const position = center();
|
||||||
@@ -233,6 +283,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
] } });
|
] } });
|
||||||
setTool("select");
|
setTool("select");
|
||||||
}
|
}
|
||||||
|
/** idle才建立checkpoint与拖动起点;有frame参与则不显示普通拖入预览,防止移动分区误收纳覆盖内容。 */
|
||||||
function beginDrag(node: CanvasNode, dragged: CanvasNode[]) {
|
function beginDrag(node: CanvasNode, dragged: CanvasNode[]) {
|
||||||
if (dragSession.current !== "idle") return; dragSession.current = "active"; tree.setDragging(true);
|
if (dragSession.current !== "idle") return; dragSession.current = "active"; tree.setDragging(true);
|
||||||
beginEdit(node.id); closeBranch(); setRotating(null); setResizing(null);
|
beginEdit(node.id); closeBranch(); setRotating(null); setResizing(null);
|
||||||
@@ -242,6 +293,8 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
setDraggedIds(draggingFrame.current ? [] : [...dragOrigins.current.keys()]);
|
setDraggedIds(draggingFrame.current ? [] : [...dragOrigins.current.keys()]);
|
||||||
setMembershipNotice("");
|
setMembershipNotice("");
|
||||||
}
|
}
|
||||||
|
/** 只结束active拖动,先清拖动/保存暂停标记,再按真实位移计算归属;真实子图与旧frameId归属分路处理。
|
||||||
|
* 异步移动失败保留错误提示,不宣称所有跨分区步骤一起回滚。 */
|
||||||
async function finishDrag(node: CanvasNode, dragged: CanvasNode[]) {
|
async function finishDrag(node: CanvasNode, dragged: CanvasNode[]) {
|
||||||
if (dragSession.current !== "active") return;
|
if (dragSession.current !== "active") return;
|
||||||
const origins = new Map(dragOrigins.current);
|
const origins = new Map(dragOrigins.current);
|
||||||
@@ -252,19 +305,23 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
if (ids.length) {
|
if (ids.length) {
|
||||||
const positions = new Map(items.map((item) => [item.id, item.position]));
|
const positions = new Map(items.map((item) => [item.id, item.position]));
|
||||||
const dropped = latest.current.nodes.map((item) => positions.has(item.id) ? { ...item, position: positions.get(item.id)! } : item);
|
const dropped = latest.current.nodes.map((item) => positions.has(item.id) ? { ...item, position: positions.get(item.id)! } : item);
|
||||||
|
// 先生成“加入/移出”展示文案;实际owner由下面的真实子图路径重新判定,成功后才显示结果通知。
|
||||||
const changed = frameDropFeedback(dropped, ids).filter((item) => item.from !== item.to);
|
const changed = frameDropFeedback(dropped, ids).filter((item) => item.from !== item.to);
|
||||||
const messages = changed.map((item) => item.to ? `已加入「${frameFeedback.names.get(item.to) || "分区"}」` : `已移出「${frameFeedback.names.get(item.from!) || "分区"}」`);
|
const messages = changed.map((item) => item.to ? `已加入「${frameFeedback.names.get(item.to) || "分区"}」` : `已移出「${frameFeedback.names.get(item.from!) || "分区"}」`);
|
||||||
const notice = messages.length ? `${changed.length > 1 ? `${changed.length} 项内容:` : ""}${[...new Set(messages)].join(";")}` : "";
|
const notice = messages.length ? `${changed.length > 1 ? `${changed.length} 项内容:` : ""}${[...new Set(messages)].join(";")}` : "";
|
||||||
if (snapshot && tree.rootDocument.schema_version === 2) {
|
if (snapshot && tree.rootDocument.schema_version === 2) {
|
||||||
try {
|
try {
|
||||||
|
// 按source/target分组,同组节点一起迁移;候选分区按面积升序,优先最小包围分区。
|
||||||
const byOwner = new Map<string, { ids: string[]; target: string }>();
|
const byOwner = new Map<string, { ids: string[]; target: string }>();
|
||||||
const parents = subgraphParents(tree.current.current);
|
const parents = subgraphParents(tree.current.current);
|
||||||
for (const item of items.filter((item) => ids.includes(item.id))) {
|
for (const item of items.filter((item) => ids.includes(item.id))) {
|
||||||
const ref = tree.views.nodeRefs.get(item.id); if (!ref) continue;
|
const ref = tree.views.nodeRefs.get(item.id); if (!ref) continue;
|
||||||
const center = { x: item.position.x + (item.width || 260) / 2, y: item.position.y + (item.height || 200) / 2 };
|
const center = { x: item.position.x + (item.width || 260) / 2, y: item.position.y + (item.height || 200) / 2 };
|
||||||
|
/** 沿子图父链防环检查,不能把分区入口移动进自己的后代,形成结构循环。 */
|
||||||
const inMovingSubtree = (child: string) => { const seen = new Set<string>(); let cursor: string | undefined = child; while (cursor && !seen.has(cursor)) { if (cursor === item.data.subgraph?.boardId) return true; seen.add(cursor); cursor = parents.get(cursor)?.boardId; } return false; };
|
const inMovingSubtree = (child: string) => { const seen = new Set<string>(); let cursor: string | undefined = child; while (cursor && !seen.has(cursor)) { if (cursor === item.data.subgraph?.boardId) return true; seen.add(cursor); cursor = parents.get(cursor)?.boardId; } return false; };
|
||||||
const candidates = dropped.filter((candidate) => candidate.id !== item.id && candidate.data.subgraph && !inMovingSubtree(candidate.data.subgraph.boardId) && center.x >= candidate.position.x && center.y >= candidate.position.y && center.x <= candidate.position.x + (candidate.width || 640) && center.y <= candidate.position.y + (candidate.height || 400)).sort((a, b) => (a.width || 640) * (a.height || 400) - (b.width || 640) * (b.height || 400));
|
const candidates = dropped.filter((candidate) => candidate.id !== item.id && candidate.data.subgraph && !inMovingSubtree(candidate.data.subgraph.boardId) && center.x >= candidate.position.x && center.y >= candidate.position.y && center.x <= candidate.position.x + (candidate.width || 640) && center.y <= candidate.position.y + (candidate.height || 400)).sort((a, b) => (a.width || 640) * (a.height || 400) - (b.width || 640) * (b.height || 400));
|
||||||
const target = candidates[0]?.data.subgraph?.boardId || (ref.boardId === board.id ? board.id : parents.get(ref.boardId)?.boardId) || board.id;
|
const target = candidates[0]?.data.subgraph?.boardId || (ref.boardId === board.id ? board.id : parents.get(ref.boardId)?.boardId) || board.id;
|
||||||
|
// 未上传且满足条件的占位图片先走本地迁移;其它节点需要服务端成员事务。
|
||||||
if (target !== ref.boardId && tree.current.current.get(ref.boardId)?.nodes.find((node)=>node.id===ref.id)?.pendingUpload) {
|
if (target !== ref.boardId && tree.current.current.get(ref.boardId)?.nodes.find((node)=>node.id===ref.id)?.pendingUpload) {
|
||||||
tree.movePendingImage(ref.boardId,target,ref.id);continue;
|
tree.movePendingImage(ref.boardId,target,ref.id);continue;
|
||||||
}
|
}
|
||||||
@@ -272,6 +329,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
const key = ref.boardId + "/" + target, group = byOwner.get(key) || { ids: [], target }; group.ids.push(ref.id); byOwner.set(key, group);
|
const key = ref.boardId + "/" + target, group = byOwner.get(key) || { ids: [], target }; group.ids.push(ref.id); byOwner.set(key, group);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 不同owner组并行提出任务,每组沿父子路径逐跳等待;tree内部队列仍串行发送成员请求。
|
||||||
await Promise.all([...byOwner].map(async ([key, group]) => {
|
await Promise.all([...byOwner].map(async ([key, group]) => {
|
||||||
let source = key.split("/")[0];
|
let source = key.split("/")[0];
|
||||||
for (const hop of subgraphMovePath(tree.current.current, source, group.target)) {
|
for (const hop of subgraphMovePath(tree.current.current, source, group.target)) {
|
||||||
@@ -287,10 +345,12 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/** 先把入口端口解析成实际内部节点;同owner本地加边,跨owner优先服务端connections事务,缺能力时尝试暴露端口适配。 */
|
||||||
async function connect(connection: Connection) {
|
async function connect(connection: Connection) {
|
||||||
const source = tree.views.nodeRefs.get(connection.source), target = tree.views.nodeRefs.get(connection.target);
|
const source = tree.views.nodeRefs.get(connection.source), target = tree.views.nodeRefs.get(connection.target);
|
||||||
if (!source || !target) return;
|
if (!source || !target) return;
|
||||||
try {
|
try {
|
||||||
|
/** 按深度计数0—8解析子图入口,每层必须找到明确port映射;仍未到实际节点或缺端口则拒绝。 */
|
||||||
const resolve = async (ref: typeof source, handle: string | null | undefined): Promise<{ boardId: string; id: string; handle: string }> => {
|
const resolve = async (ref: typeof source, handle: string | null | undefined): Promise<{ boardId: string; id: string; handle: string }> => {
|
||||||
let endpoint = { boardId: ref!.boardId, id: ref!.id, handle: handle || "right" };
|
let endpoint = { boardId: ref!.boardId, id: ref!.id, handle: handle || "right" };
|
||||||
for (let depth = 0; depth <= 8; depth++) {
|
for (let depth = 0; depth <= 8; depth++) {
|
||||||
@@ -303,6 +363,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
throw new Error("subgraph_cycle");
|
throw new Error("subgraph_cycle");
|
||||||
};
|
};
|
||||||
const realSource = await resolve(source, connection.sourceHandle), realTarget = await resolve(target, connection.targetHandle || "left");
|
const realSource = await resolve(source, connection.sourceHandle), realTarget = await resolve(target, connection.targetHandle || "left");
|
||||||
|
// 同一canvas快照可直接加边;跨canvas需要共同上层/边界端口关系,不能把显示端点直接写进任一子快照。
|
||||||
if (realSource.boardId === realTarget.boardId) {
|
if (realSource.boardId === realTarget.boardId) {
|
||||||
const document = tree.current.current.get(realSource.boardId)!;
|
const document = tree.current.current.get(realSource.boardId)!;
|
||||||
tree.dispatch({ type: "replace", document: { ...document, schema_version: 2, edges: addEdge({ id: crypto.randomUUID(), source: realSource.id, target: realTarget.id, sourceHandle: realSource.handle, targetHandle: realTarget.handle }, document.edges) } }, realSource.boardId);
|
tree.dispatch({ type: "replace", document: { ...document, schema_version: 2, edges: addEdge({ id: crypto.randomUUID(), source: realSource.id, target: realTarget.id, sourceHandle: realSource.handle, targetHandle: realTarget.handle }, document.edges) } }, realSource.boardId);
|
||||||
@@ -316,11 +377,13 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 兼容路径由exposedConnection提供可寻址端点与owner,失败提示跨画布连接暂不可用。
|
||||||
const exposed = exposedConnection(tree.current.current, realSource, realTarget);
|
const exposed = exposedConnection(tree.current.current, realSource, realTarget);
|
||||||
const document = tree.current.current.get(exposed.boardId)!;
|
const document = tree.current.current.get(exposed.boardId)!;
|
||||||
tree.dispatch({ type: "replace", document: { ...document, schema_version: 2, edges: addEdge({ ...connection, source: exposed.source.id, target: exposed.target.id, sourceHandle: exposed.source.handle, targetHandle: exposed.target.handle, id: crypto.randomUUID() }, document.edges) } }, exposed.boardId);
|
tree.dispatch({ type: "replace", document: { ...document, schema_version: 2, edges: addEdge({ ...connection, source: exposed.source.id, target: exposed.target.id, sourceHandle: exposed.source.handle, targetHandle: exposed.target.handle, id: crypto.randomUUID() }, document.edges) } }, exposed.boardId);
|
||||||
} catch (error) { setError(error instanceof Error && error.message === "boundary_port_required" ? "跨画布连接暂不可用,请稍后重试。" : errorText(error)); }
|
} catch (error) { setError(error instanceof Error && error.message === "boundary_port_required" ? "跨画布连接暂不可用,请稍后重试。" : errorText(error)); }
|
||||||
}
|
}
|
||||||
|
/** 校验MIME与大小并清文件input;迁移期间拒绝。真实画布通过上传占位,演示以Data URL直接加入。 */
|
||||||
async function readImage(event: ChangeEvent<HTMLInputElement>) {
|
async function readImage(event: ChangeEvent<HTMLInputElement>) {
|
||||||
const file = event.target.files?.[0];
|
const file = event.target.files?.[0];
|
||||||
event.target.value = "";
|
event.target.value = "";
|
||||||
@@ -331,6 +394,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
}
|
}
|
||||||
const request = pendingImage.current; pendingImage.current = null;
|
const request = pendingImage.current; pendingImage.current = null;
|
||||||
const kind = imageKind.current;
|
const kind = imageKind.current;
|
||||||
|
// 真实图片上传先取得本地Blob预览并构造draft,随后把pendingUpload节点及可选分支边发布到owner。
|
||||||
if (snapshot) {
|
if (snapshot) {
|
||||||
try { const job = uploads.start(file, (src) => {
|
try { const job = uploads.start(file, (src) => {
|
||||||
const current = treeRef.current;
|
const current = treeRef.current;
|
||||||
@@ -343,12 +407,14 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
const node=makeCanvasNode(kind,center(),src);if(kind==='plain-image')node.data.title=file.name.slice(0,300);
|
const node=makeCanvasNode(kind,center(),src);if(kind==='plain-image')node.data.title=file.name.slice(0,300);
|
||||||
return {owner:board.id,node};
|
return {owner:board.id,node};
|
||||||
});
|
});
|
||||||
|
// pendingUpload以node.id标记,后续资源完成/跨区移动/历史恢复都按这个身份找到占位。
|
||||||
const current=treeRef.current,doc=current.current.current.get(job.owner)!;
|
const current=treeRef.current,doc=current.current.current.get(job.owner)!;
|
||||||
const node={...job.node,pendingUpload:job.node.id};
|
const node={...job.node,pendingUpload:job.node.id};
|
||||||
current.dispatch({type:"replace",document:{...doc,nodes:[...doc.nodes,node],edges:[...doc.edges,...(job.edge?[job.edge]:[])]}},job.owner);
|
current.dispatch({type:"replace",document:{...doc,nodes:[...doc.nodes,node],edges:[...doc.edges,...(job.edge?[job.edge]:[])]}},job.owner);
|
||||||
setTool("select"); } catch(error) {setError(errorText(error));}
|
setTool("select"); } catch(error) {setError(errorText(error));}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// 演示不上传服务端,FileReader读取全部字节为Data URL;纯图片另解码初始尺寸,finally释放读取中UI状态。
|
||||||
setImageUploading(true);
|
setImageUploading(true);
|
||||||
try {
|
try {
|
||||||
const src = await new Promise<string>((resolve, reject) => {
|
const src = await new Promise<string>((resolve, reject) => {
|
||||||
@@ -370,6 +436,8 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
} catch (error) { pendingImage.current = null; setError(errorText(error)); }
|
} catch (error) { pendingImage.current = null; setError(errorText(error)); }
|
||||||
finally { setImageUploading(false); }
|
finally { setImageUploading(false); }
|
||||||
}
|
}
|
||||||
|
/** 旧版导入最多5MB并全量读取解码,替换当前根快照;任一方含真实子图时拒绝,避免破坏跨board关系。
|
||||||
|
* ioActive用于阻止迁移交接;这条路径不是新版渐进导入,也不会自动重建bundle子图。 */
|
||||||
async function importProject(event: ChangeEvent<HTMLInputElement>) {
|
async function importProject(event: ChangeEvent<HTMLInputElement>) {
|
||||||
const file = event.target.files?.[0];
|
const file = event.target.files?.[0];
|
||||||
event.target.value = "";
|
event.target.value = "";
|
||||||
@@ -387,6 +455,8 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
} catch (error) { setError(error instanceof Error ? error.message : "导入失败。"); }
|
} catch (error) { setError(error instanceof Error ? error.message : "导入失败。"); }
|
||||||
finally{ioActive.current=false;}
|
finally{ioActive.current=false;}
|
||||||
}
|
}
|
||||||
|
/** 有上传占位则先等待用户完成;树导出完整可达文档,多board写bundle,单board写当前视口。
|
||||||
|
* 下载名清理文件名非法字符,Blob URL延迟释放;不额外打包File/Blob,已有演示Data URL仍随src导出。 */
|
||||||
async function exportProject() {
|
async function exportProject() {
|
||||||
let documents: Map<string, import("@/lib/canvas").CanvasDocument>;
|
let documents: Map<string, import("@/lib/canvas").CanvasDocument>;
|
||||||
try { if([...tree.current.current.values()].some((doc)=>doc.nodes.some((node)=>node.pendingUpload))) throw new Error("图片仍在上传,完成后即可导出。"); documents = await tree.exportDocuments(); } catch (error) { setError(error instanceof Error ? error.message : "导出未完成"); return; }
|
try { if([...tree.current.current.values()].some((doc)=>doc.nodes.some((node)=>node.pendingUpload))) throw new Error("图片仍在上传,完成后即可导出。"); documents = await tree.exportDocuments(); } catch (error) { setError(error instanceof Error ? error.message : "导出未完成"); return; }
|
||||||
@@ -399,7 +469,9 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 旧版全局快捷键:跳过输入框、文本编辑、对话框和打开的popover,支持撤销/重做与V/H;卸载移除。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
/** 按DOM目标过滤后处理键;此旧路径没有新版routeCanvasKey的组合输入/认领优先级模型。 */
|
||||||
const keydown = (event: KeyboardEvent) => {
|
const keydown = (event: KeyboardEvent) => {
|
||||||
const target = event.target;
|
const target = event.target;
|
||||||
if (!(target instanceof HTMLElement)) return;
|
if (!(target instanceof HTMLElement)) return;
|
||||||
@@ -417,6 +489,11 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
return () => window.removeEventListener("keydown", keydown);
|
return () => window.removeEventListener("keydown", keydown);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Provider把图片预览、节点动作、分区反馈及活动连线接到renderer;迁移时surface与底部创作栏设inert。
|
||||||
|
// ReactFlow删除由onBeforeDelete拦截真实子图/暴露端口节点,避免默认删除破坏结构;普通元素沿tree变化入口。
|
||||||
|
// 选择工具允许拖动/连接,抓手只平移;Space临时平移、Shift部分框选,滚轮默认平移、修饰键缩放。
|
||||||
|
// 工具栏创建/模板/导入走上述入口,顶部视口操作保存本地viewport;AI只给选中且支持的节点显示。
|
||||||
|
// 恢复弹窗先根再子,逐项核查canRestore;迁移组件检查草稿、文件IO和未完成上传再排空writer。
|
||||||
return (
|
return (
|
||||||
<div className={`${styles.editor} ${tool === "hand" ? styles.handMode : ""}`}>
|
<div className={`${styles.editor} ${tool === "hand" ? styles.handMode : ""}`}>
|
||||||
<ImagePreviews.Provider value={imagePreviews}>
|
<ImagePreviews.Provider value={imagePreviews}>
|
||||||
@@ -427,6 +504,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
<ReactFlow<CanvasNode> nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={edgeTypes}
|
<ReactFlow<CanvasNode> nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={edgeTypes}
|
||||||
onBeforeDelete={async ({ nodes: removing }) => {
|
onBeforeDelete={async ({ nodes: removing }) => {
|
||||||
if (tree.busy || tree.transactionBusy) return false;
|
if (tree.busy || tree.transactionBusy) return false;
|
||||||
|
// 选中分区入口要先dissolve保留内容;内部节点若被父port引用,先移回父board再删,清理边界引用。
|
||||||
const linked = removing.filter((node) => node.data.subgraph);
|
const linked = removing.filter((node) => node.data.subgraph);
|
||||||
const parents = subgraphParents(tree.current.current);
|
const parents = subgraphParents(tree.current.current);
|
||||||
const referenced = removing.filter((node) => {
|
const referenced = removing.filter((node) => {
|
||||||
@@ -436,6 +514,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
});
|
});
|
||||||
if (!linked.length && !referenced.length) return true;
|
if (!linked.length && !referenced.length) return true;
|
||||||
try {
|
try {
|
||||||
|
// 分区逐个事务解散,参与者包含父、子、孙及需要调整引用的祖先;并非一批选择全体原子操作。
|
||||||
for (const node of linked) {
|
for (const node of linked) {
|
||||||
const ref = tree.views.nodeRefs.get(node.id)!;
|
const ref = tree.views.nodeRefs.get(node.id)!;
|
||||||
await tree.ensure(node.data.subgraph!.boardId);
|
await tree.ensure(node.data.subgraph!.boardId);
|
||||||
@@ -445,6 +524,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
if (ancestor && subgraphMoveParticipants(tree.current.current, ref.boardId, node.data.subgraph!.boardId, ref.boardId, child.nodes.map((item) => item.id)).includes(ancestor)) participants.add(ancestor);
|
if (ancestor && subgraphMoveParticipants(tree.current.current, ref.boardId, node.data.subgraph!.boardId, ref.boardId, child.nodes.map((item) => item.id)).includes(ancestor)) participants.add(ancestor);
|
||||||
await tree.command(ref.boardId, `subgraphs/${ref.id}/dissolve`, {}, [...participants]);
|
await tree.command(ref.boardId, `subgraphs/${ref.id}/dissolve`, {}, [...participants]);
|
||||||
}
|
}
|
||||||
|
// 解散后owner可能变化,按原ID重新查唯一归属;找不到唯一目标就跳过,不误删同ID的其它节点。
|
||||||
for (const node of removing.filter((node) => !node.data.subgraph)) {
|
for (const node of removing.filter((node) => !node.data.subgraph)) {
|
||||||
const ref = tree.views.nodeRefs.get(node.id); if (!ref) continue;
|
const ref = tree.views.nodeRefs.get(node.id); if (!ref) continue;
|
||||||
let owner = ref.boardId;
|
let owner = ref.boardId;
|
||||||
@@ -461,6 +541,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
}
|
}
|
||||||
if (linked.length) setMembershipNotice("已解散选框,子画布内容已保留");
|
if (linked.length) setMembershipNotice("已解散选框,子画布内容已保留");
|
||||||
} catch (error) { setError(error instanceof Error ? error.message : "删除未完成"); }
|
} catch (error) { setError(error instanceof Error ? error.message : "删除未完成"); }
|
||||||
|
// 结构分支已自行执行删除/解散,阻止ReactFlow再按旧投影默认删一遍。
|
||||||
return false;
|
return false;
|
||||||
}}
|
}}
|
||||||
onNodesChange={tree.nodesChanged}
|
onNodesChange={tree.nodesChanged}
|
||||||
@@ -486,6 +567,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
defaultEdgeOptions={{ style: { stroke: "#aa968b", strokeWidth: 1.5 } }}>
|
defaultEdgeOptions={{ style: { stroke: "#aa968b", strokeWidth: 1.5 } }}>
|
||||||
<Background variant={BackgroundVariant.Dots} gap={22} size={1} color="#c9bfb5" />
|
<Background variant={BackgroundVariant.Dots} gap={22} size={1} color="#c9bfb5" />
|
||||||
{ai.enabled && nodes.filter((node) => node.selected && ["text", "script", "plain-text", "image", "plain-image"].includes(node.data.kind)).map((node) => {
|
{ai.enabled && nodes.filter((node) => node.selected && ["text", "script", "plain-text", "image", "plain-image"].includes(node.data.kind)).map((node) => {
|
||||||
|
// AIPanel收到owner原始节点,显示ID仅用于NodeToolbar定位;save仍经tree.nodeAction回写owner。
|
||||||
const ref = tree.views.nodeRefs.get(node.id)!;
|
const ref = tree.views.nodeRefs.get(node.id)!;
|
||||||
const owned = tree.documents.get(ref.boardId)?.nodes.find((item) => item.id === ref.id);
|
const owned = tree.documents.get(ref.boardId)?.nodes.find((item) => item.id === ref.id);
|
||||||
return owned && <AIPanel key={node.id} id={node.id} node={owned} workspace={board.workspace_id} boardId={ref.boardId} ai={ai} save={(config) => tree.nodeAction(node.id, (id) => ({ type: "node-data", id, patch: { ai: config } }))} />;
|
return owned && <AIPanel key={node.id} id={node.id} node={owned} workspace={board.workspace_id} boardId={ref.boardId} ai={ai} save={(config) => tree.nodeAction(node.id, (id) => ({ type: "node-data", id, patch: { ai: config } }))} />;
|
||||||
@@ -558,6 +640,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
<button onClick={exportProject}>导出当前内容</button><button onClick={() => window.location.reload()}>重新读取</button>
|
<button onClick={exportProject}>导出当前内容</button><button onClick={() => window.location.reload()}>重新读取</button>
|
||||||
</div>}
|
</div>}
|
||||||
{tree.memberJobs.map((job, index) => job.ids.map((id) => {
|
{tree.memberJobs.map((job, index) => job.ids.map((id) => {
|
||||||
|
// 成员任务提示跟随当前source/target中的场景节点,队首同步、后续等待,失败通过retryMembers继续。
|
||||||
const node = [...tree.views.nodeRefs].find(([, ref]) => ref.id === id && [job.source, job.target].includes(ref.boardId));
|
const node = [...tree.views.nodeRefs].find(([, ref]) => ref.id === id && [job.source, job.target].includes(ref.boardId));
|
||||||
return node && <NodeToolbar key={`${job.source}/${id}`} nodeId={node[0]} isVisible position={Position.Top}>
|
return node && <NodeToolbar key={`${job.source}/${id}`} nodeId={node[0]} isVisible position={Position.Top}>
|
||||||
<div className={`${styles.memberSync} nodrag nopan`} role="status" aria-label="元素同步状态" data-node-id={node[0]}>
|
<div className={`${styles.memberSync} nodrag nopan`} role="status" aria-label="元素同步状态" data-node-id={node[0]}>
|
||||||
@@ -577,6 +660,7 @@ function CanvasEditor({ board, snapshot, migration }: { board: Board; snapshot?:
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 为单个旧编辑器建立独立ReactFlow store;board/snapshot身份切换的重挂载由路由调用方负责。 */
|
||||||
export default function GraphCanvas({ board, snapshot, migration }: { board: Board; snapshot?: CanvasSnapshot; migration?:LegacyMigrationContext }) {
|
export default function GraphCanvas({ board, snapshot, migration }: { board: Board; snapshot?: CanvasSnapshot; migration?:LegacyMigrationContext }) {
|
||||||
return <ReactFlowProvider><CanvasEditor board={board} snapshot={snapshot} migration={migration} /></ReactFlowProvider>;
|
return <ReactFlowProvider><CanvasEditor board={board} snapshot={snapshot} migration={migration} /></ReactFlowProvider>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* 新版元素AI工具面板。配置、生成开始、取消和结果采用均通过engine命令进入既有状态与同步链路。
|
||||||
|
* 任务事实读取runtime.runs/ledger,局部state只保存输入、模型目录和界面错误;关闭面板不等于取消生成。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
@@ -10,7 +14,10 @@ import { errorText } from "@/lib/api";
|
|||||||
import { managedImageSource } from "@/lib/canvas-v2";
|
import { managedImageSource } from "@/lib/canvas-v2";
|
||||||
import styles from "./canvas.module.css";
|
import styles from "./canvas.module.css";
|
||||||
|
|
||||||
|
/** 只接受非数组JSON对象作为配置/输出包络,其它值退为空对象,避免直接按对象读取标量。 */
|
||||||
const object = (value: Json | undefined) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
const object = (value: Json | undefined) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
||||||
|
/** 配置输入从元素当前ai字段初始化;模型输出模态按image/plain-image与其它组件区分。
|
||||||
|
* 元素数据来自父层投影,本组件直接读取engine根用于显示任务,不再创建额外轮询器。 */
|
||||||
export function HeadlessAIPanel({ engine, element, close, viewId }: { engine: ProjectEngine; element: ElementRecord; close(): void; viewId:string }) {
|
export function HeadlessAIPanel({ engine, element, close, viewId }: { engine: ProjectEngine; element: ElementRecord; close(): void; viewId:string }) {
|
||||||
const saved = object(element.data.ai), root = engine.getSnapshot();
|
const saved = object(element.data.ai), root = engine.getSnapshot();
|
||||||
const [models, setModels] = useState<readonly RunModel[]>([]), [loading, setLoading] = useState(true), [error, setError] = useState('');
|
const [models, setModels] = useState<readonly RunModel[]>([]), [loading, setLoading] = useState(true), [error, setError] = useState('');
|
||||||
@@ -18,14 +25,20 @@ export function HeadlessAIPanel({ engine, element, close, viewId }: { engine: Pr
|
|||||||
const [prompt, setPrompt] = useState(typeof saved.prompt === 'string' ? saved.prompt : '');
|
const [prompt, setPrompt] = useState(typeof saved.prompt === 'string' ? saved.prompt : '');
|
||||||
const [propagate, setPropagate] = useState(saved.propagate === true);
|
const [propagate, setPropagate] = useState(saved.propagate === true);
|
||||||
const image = ['image','plain-image'].includes(element.componentId);
|
const image = ['image','plain-image'].includes(element.componentId);
|
||||||
|
// 用runContainsTarget核对目标身份,选择相关任务列表的最后一项;不是按时间戳重新排序。
|
||||||
const relevant = [...root.runtime.runs.values()].filter(run => runContainsTarget(run,element));
|
const relevant = [...root.runtime.runs.values()].filter(run => runContainsTarget(run,element));
|
||||||
const run = relevant.at(-1);
|
const run = relevant.at(-1);
|
||||||
|
// ledger里的run.start可尚未得到服务端run,必须单独显示等待/阻断,不能仅看runs来判定空闲。
|
||||||
const starts = [...root.runtime.ledger.operations.values()].filter(record => record.intent.operationType === 'run.start' && record.intent.run.target.id === element.id && record.intent.run.target.incarnation === element.incarnation);
|
const starts = [...root.runtime.ledger.operations.values()].filter(record => record.intent.operationType === 'run.start' && record.intent.run.target.id === element.id && record.intent.run.target.incarnation === element.incarnation);
|
||||||
const pending=starts.filter(record=>record.phase!=='resolved'), rejectedStart=starts.at(-1)?.resolution==='not-applied'?starts.at(-1):undefined;
|
const pending=starts.filter(record=>record.phase!=='resolved'), rejectedStart=starts.at(-1)?.resolution==='not-applied'?starts.at(-1):undefined;
|
||||||
|
// 同一run未解决的cancel/apply也占忙碌状态;hasMore/pendingPage表示任务事件尚未完整读取。
|
||||||
const actions=[...root.runtime.ledger.operations.values()].filter(record=>(record.intent.operationType==='run.cancel'||record.intent.operationType==='run.apply')&&record.intent.action.runId===run?.id&&record.phase!=='resolved');
|
const actions=[...root.runtime.ledger.operations.values()].filter(record=>(record.intent.operationType==='run.cancel'||record.intent.operationType==='run.apply')&&record.intent.action.runId===run?.id&&record.phase!=='resolved');
|
||||||
const cancelling=actions.some(record=>record.intent.operationType==='run.cancel'),applying=actions.some(record=>record.intent.operationType==='run.apply');
|
const cancelling=actions.some(record=>record.intent.operationType==='run.cancel'),applying=actions.some(record=>record.intent.operationType==='run.apply');
|
||||||
const busy = pending.length > 0 || actions.length > 0 || !!run && (run.hasMore || !!run.pendingPage || ['queued','running'].includes(run.status));
|
const busy = pending.length > 0 || actions.length > 0 || !!run && (run.hasMore || !!run.pendingPage || ['queued','running'].includes(run.status));
|
||||||
|
// 展示当前元素最后一个输出事件;是否可采用还要检查output_id、任务冲突状态及已应用集合。
|
||||||
const outputEvent = run?.outputEvents.filter(event => event.node_id === element.id).at(-1), output = object(outputEvent?.output);
|
const outputEvent = run?.outputEvents.filter(event => event.node_id === element.id).at(-1), output = object(outputEvent?.output);
|
||||||
|
// 按当前ownerCanvasId读取可用模型,保留仍兼容的选择,否则选首个available;目录不可用原因单独提示。
|
||||||
|
// 切作用域/卸载时abort;所有异步结果先检查取消状态,不把旧目录写回新面板。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const controller = new AbortController();setLoading(true);setError('');
|
const controller = new AbortController();setLoading(true);setError('');
|
||||||
engine.models(element.ownerCanvasId,controller.signal).then(catalog => {
|
engine.models(element.ownerCanvasId,controller.signal).then(catalog => {
|
||||||
@@ -36,13 +49,20 @@ export function HeadlessAIPanel({ engine, element, close, viewId }: { engine: Pr
|
|||||||
}).catch(error => { if(!controller.signal.aborted)setError(errorText(error)); }).finally(() => { if(!controller.signal.aborted)setLoading(false); });
|
}).catch(error => { if(!controller.signal.aborted)setError(errorText(error)); }).finally(() => { if(!controller.signal.aborted)setLoading(false); });
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
},[engine,element.ownerCanvasId,image]);
|
},[engine,element.ownerCanvasId,image]);
|
||||||
|
/** 将同步命令的rejected结果显示为错误;返回布尔值供“先保存配置再启动”短路。 */
|
||||||
function check(result: Result) { if(result.status === 'rejected') { setError(errorText(new Error(result.code)));return false; }return true; }
|
function check(result: Result) { if(result.status === 'rejected') { setError(errorText(new Error(result.code)));return false; }return true; }
|
||||||
|
/** 有模型且不忙时提交ai配置;否则不发修改并返回true。该函数只配置,不发起生成。 */
|
||||||
function save() {
|
function save() {
|
||||||
if(!model || busy)return true;
|
if(!model || busy)return true;
|
||||||
return check(engine.editor.dispatch({type:'element.data',target:{id:element.id,incarnation:element.incarnation},patch:{ai:{enabled:true,modelId:model,prompt,propagate,parameters:{}}}},{label:'Configure generation'}));
|
return check(engine.editor.dispatch({type:'element.data',target:{id:element.id,incarnation:element.incarnation},patch:{ai:{enabled:true,modelId:model,prompt,propagate,parameters:{}}}},{label:'Configure generation'}));
|
||||||
}
|
}
|
||||||
|
// 用服务端输出身份判断是否已采用,不凭当前正文/图片内容相同推测结果是否应用。
|
||||||
const appliedOutput=typeof output.output_id==='string'&&run?.appliedOutputIds?.includes(output.output_id);
|
const appliedOutput=typeof output.output_id==='string'&&run?.appliedOutputIds?.includes(output.output_id);
|
||||||
|
// 状态文案先展示未解决取消/采用,再展示拒绝、已采用、等待受理与任务进度,防止把请求排队说成已执行。
|
||||||
const message = cancelling ? '取消请求已保存,等待确认…' : applying ? '正在应用生成结果…' : rejectedStart ? `生成未受理:${rejectedStart.blockers.join('、')}` : appliedOutput ? '此生成结果已应用' : pending.length ? pending.some(record => record.phase === 'blocked') ? '生成受理需要处理' : '正在等待同步并受理生成…' : run?.blocked ? '生成结果已保留,当前编辑需要协调' : run?.error ? '任务跟踪需要处理,可重试' : run?.hasMore ? '正在同步任务状态…' : run ? ({queued:'已受理,等待生成',running:'正在生成…',succeeded:'已更新当前元素',failed:'生成未完成,原内容已保留',conflict:'内容已改变,生成结果已保留',cancelled:'已取消生成',partially_succeeded:'部分步骤已完成'}[run.status]) : '结果将显示在当前元素';
|
const message = cancelling ? '取消请求已保存,等待确认…' : applying ? '正在应用生成结果…' : rejectedStart ? `生成未受理:${rejectedStart.blockers.join('、')}` : appliedOutput ? '此生成结果已应用' : pending.length ? pending.some(record => record.phase === 'blocked') ? '生成受理需要处理' : '正在等待同步并受理生成…' : run?.blocked ? '生成结果已保留,当前编辑需要协调' : run?.error ? '任务跟踪需要处理,可重试' : run?.hasMore ? '正在同步任务状态…' : run ? ({queued:'已受理,等待生成',running:'正在生成…',succeeded:'已更新当前元素',failed:'生成未完成,原内容已保留',conflict:'内容已改变,生成结果已保留',cancelled:'已取消生成',partially_succeeded:'部分步骤已完成'}[run.status]) : '结果将显示在当前元素';
|
||||||
|
// 输入blur保存配置,执行按钮再保存一次且成功后startRun;忙碌时锁定配置和启动,关闭按钮仍可用。
|
||||||
|
// queued/running提供取消请求入口;冲突输出保留展示,只有事件读完且未采用时才允许显式替换。
|
||||||
|
// 跟踪重试调用engine.retry,不新建run.start;pointer/keydown止于面板,避免触发画布手势或快捷键。
|
||||||
return <section data-canvas-ui-view={viewId} className={`${styles.aiPanel} nodrag nopan nowheel`} aria-label="元素 AI 工具" style={{position:'absolute',right:24,bottom:90,zIndex:110,maxWidth:'calc(100% - 48px)',maxHeight:'70%',overflow:'auto'}} onPointerDown={event=>event.stopPropagation()} onKeyDown={event=>event.stopPropagation()}>
|
return <section data-canvas-ui-view={viewId} className={`${styles.aiPanel} nodrag nopan nowheel`} aria-label="元素 AI 工具" style={{position:'absolute',right:24,bottom:90,zIndex:110,maxWidth:'calc(100% - 48px)',maxHeight:'70%',overflow:'auto'}} onPointerDown={event=>event.stopPropagation()} onKeyDown={event=>event.stopPropagation()}>
|
||||||
<header><Sparkles size={14}/><strong>{image ? '图像创作' : '文本创作'}</strong><span>{element.data.title as string}</span><button aria-label="关闭 AI 工具" onClick={close}><X size={14}/></button></header>
|
<header><Sparkles size={14}/><strong>{image ? '图像创作' : '文本创作'}</strong><span>{element.data.title as string}</span><button aria-label="关闭 AI 工具" onClick={close}><X size={14}/></button></header>
|
||||||
<textarea aria-label="AI 指令" placeholder="希望如何处理当前内容?" maxLength={16000} disabled={busy} value={prompt} onChange={event=>setPrompt(event.target.value)} onBlur={save}/>
|
<textarea aria-label="AI 指令" placeholder="希望如何处理当前内容?" maxLength={16000} disabled={busy} value={prompt} onChange={event=>setPrompt(event.target.value)} onBlur={save}/>
|
||||||
|
|||||||
@@ -1,3 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* 新版主画布的React/ReactFlow装配。engine拥有文档、历史和运行事实,sessions拥有每视图选择/工具/手势;组件只保存显示缓存与面板状态。
|
||||||
|
* 文档提交先推进场景索引,再按事件类型立即或逐帧发布;几何预览通过session进入投影,提交才产生文档修改。
|
||||||
|
* 画布适配层负责DOM测量、命中、裁剪、焦点和资源显示,core不读取DOM;渲染组件通过动作上下文调用editor/runtime。
|
||||||
|
* 外层只借用项目engine:挂载attach视图,卸载detach,不关闭工作区持有的项目或持久任务。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ContextType } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ContextType } from "react";
|
||||||
@@ -40,9 +46,13 @@ import { UnsupportedNode, UnsupportedEdge } from "./unsupported-elements";
|
|||||||
import { ImagePreviews } from "./canvas-image";
|
import { ImagePreviews } from "./canvas-image";
|
||||||
import styles from "./canvas.module.css";
|
import styles from "./canvas.module.css";
|
||||||
|
|
||||||
|
/** 把适配层样式等可序列化值规范化成JSON Data,去掉undefined等JSON不保留的属性;不处理循环或任意非JSON对象。 */
|
||||||
const json = (value: unknown): Data => JSON.parse(JSON.stringify(value));
|
const json = (value: unknown): Data => JSON.parse(JSON.stringify(value));
|
||||||
|
/** 已attach视图的内容组件;需要外层ReactFlowProvider与CanvasProvider。root/session是发布快照,current供回调读取最新投影。 */
|
||||||
function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engine: ProjectEngine; board: Board; viewId: Id; renderers:ReactRenderers;fitLoading?:boolean }) {
|
function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engine: ProjectEngine; board: Board; viewId: Id; renderers:ReactRenderers;fitLoading?:boolean }) {
|
||||||
|
// 场景索引按engine+view复用,提交订阅先advance变更,再通知显示,避免每次渲染重建整图索引。
|
||||||
const sceneCache=useMemo(()=>createSceneProjection(),[engine,viewId]);
|
const sceneCache=useMemo(()=>createSceneProjection(),[engine,viewId]);
|
||||||
|
/** 用户字段修改/替换删除及undo/redo立即发布,保证受控输入及时回显;批量创建和后台修改允许合并到下一帧。 */
|
||||||
const subscribe = useCallback((notify: (immediate?:boolean) => void) => {
|
const subscribe = useCallback((notify: (immediate?:boolean) => void) => {
|
||||||
let before=engine.getSnapshot().document;
|
let before=engine.getSnapshot().document;
|
||||||
return engine.editor.subscribe((commit,next)=>{sceneCache.advance(before,next.document,commit.changes);before=next.document;
|
return engine.editor.subscribe((commit,next)=>{sceneCache.advance(before,next.document,commit.changes);before=next.document;
|
||||||
@@ -52,16 +62,20 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
notify(immediate);
|
notify(immediate);
|
||||||
});
|
});
|
||||||
}, [engine,sceneCache]);
|
}, [engine,sceneCache]);
|
||||||
|
// rootFrames只调度呈现通知,不延迟editor真实提交;sessionFrames独立合并手势/选择等视图变化。
|
||||||
const rootFrames=useMemo(()=>createFrameSource({subscribe,getSnapshot:engine.getSnapshot},{request:callback=>requestAnimationFrame(callback),cancel:handle=>cancelAnimationFrame(handle as number)}),[engine,subscribe]);
|
const rootFrames=useMemo(()=>createFrameSource({subscribe,getSnapshot:engine.getSnapshot},{request:callback=>requestAnimationFrame(callback),cancel:handle=>cancelAnimationFrame(handle as number)}),[engine,subscribe]);
|
||||||
const root = useSyncExternalStore(rootFrames.subscribe, rootFrames.getSnapshot, rootFrames.getSnapshot);
|
const root = useSyncExternalStore(rootFrames.subscribe, rootFrames.getSnapshot, rootFrames.getSnapshot);
|
||||||
const sessionFrames=useMemo(()=>createSessionFrameSource(engine.sessions,{request:callback=>requestAnimationFrame(callback),cancel:handle=>cancelAnimationFrame(handle as number)}),[engine]);
|
const sessionFrames=useMemo(()=>createSessionFrameSource(engine.sessions,{request:callback=>requestAnimationFrame(callback),cancel:handle=>cancelAnimationFrame(handle as number)}),[engine]);
|
||||||
const sessions = useSyncExternalStore(sessionFrames.subscribe, sessionFrames.getSnapshot, sessionFrames.getSnapshot);
|
const sessions = useSyncExternalStore(sessionFrames.subscribe, sessionFrames.getSnapshot, sessionFrames.getSnapshot);
|
||||||
|
// 视图被detach后保留最近view供本轮Hook计算,最终返回“画布已关闭”;不以lastView恢复已关闭会话。
|
||||||
const liveView = sessions.views.get(viewId), lastView = useRef(liveView);
|
const liveView = sessions.views.get(viewId), lastView = useRef(liveView);
|
||||||
const loading=root.runtime.loading,needsLoadingFit=useRef(!!loading&&fitLoading);
|
const loading=root.runtime.loading,needsLoadingFit=useRef(!!loading&&fitLoading);
|
||||||
|
|
||||||
if (liveView) lastView.current = liveView;
|
if (liveView) lastView.current = liveView;
|
||||||
const view = liveView ?? lastView.current!, flow = useReactFlow<ProjectionNode>();
|
const view = liveView ?? lastView.current!, flow = useReactFlow<ProjectionNode>();
|
||||||
|
// 完整加载后允许普通创建;加载中要求loading版本支持且当前canvas覆盖完整,最终命令层仍再校验准入。
|
||||||
const canCreate=!loading||loading.version>=4&&engine.editor.getQueries(root.document).coverage.completeCanvasIds.includes(view.canvasId);
|
const canCreate=!loading||loading.version>=4&&engine.editor.getQueries(root.document).coverage.completeCanvasIds.includes(view.canvasId);
|
||||||
|
// 加载预览首次适配只取当前canvas直接节点,避免展开后代把视口拉得过远;有交接视口时不再自动fit。
|
||||||
useEffect(()=>{
|
useEffect(()=>{
|
||||||
if(!needsLoadingFit.current||!flow.viewportInitialized||!root.document.canvases.has(view.canvasId))return;
|
if(!needsLoadingFit.current||!flow.viewportInitialized||!root.document.canvases.has(view.canvasId))return;
|
||||||
// Expanded descendants can extend far beyond their partition entry. Initial
|
// Expanded descendants can extend far beyond their partition entry. Initial
|
||||||
@@ -70,7 +84,9 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
if(!nodes.length)return;
|
if(!nodes.length)return;
|
||||||
needsLoadingFit.current=false;void flow.fitView({nodes,padding:.2,maxZoom:1});
|
needsLoadingFit.current=false;void flow.fitView({nodes,padding:.2,maxZoom:1});
|
||||||
},[engine,flow,root.document,view.canvasId]);
|
},[engine,flow,root.document,view.canvasId]);
|
||||||
|
// 复制准备任务来自runtime状态;copying防本地重复点击,两者共同禁用复制入口。
|
||||||
const preparingCopy = [...(root.runtime.imports?.values() ?? [])].some(job => job.status === 'preparing' && job.source?.targetCanvasId === view.canvasId);
|
const preparingCopy = [...(root.runtime.imports?.values() ?? [])].some(job => job.status === 'preparing' && job.source?.targetCanvasId === view.canvasId);
|
||||||
|
// 焦点与epoch用于保留活动输入和排除迟到blur;切engine/view复位,移除renderer未触发blur时另检查isConnected。
|
||||||
const [focusedEditor, setFocusedEditor] = useState<HTMLElement | null>(null), focusEpoch = useRef(0);
|
const [focusedEditor, setFocusedEditor] = useState<HTMLElement | null>(null), focusEpoch = useRef(0);
|
||||||
useEffect(() => { focusEpoch.current++; setFocusedEditor(null); return () => { focusEpoch.current++; }; }, [engine,viewId]);
|
useEffect(() => { focusEpoch.current++; setFocusedEditor(null); return () => { focusEpoch.current++; }; }, [engine,viewId]);
|
||||||
// Removing an active renderer need not dispatch a native blur. Retire only
|
// Removing an active renderer need not dispatch a native blur. Retire only
|
||||||
@@ -78,19 +94,26 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
useEffect(()=>{if(focusedEditor&&!focusedEditor.isConnected)setFocusedEditor(current=>current===focusedEditor?null:current);});
|
useEffect(()=>{if(focusedEditor&&!focusedEditor.isConnected)setFocusedEditor(current=>current===focusedEditor?null:current);});
|
||||||
const [copying, setCopying] = useState(false);
|
const [copying, setCopying] = useState(false);
|
||||||
const [resourcePicker,setResourcePicker]=useState<{canvasId:Id;position:{x:number;y:number}}|null>(null);
|
const [resourcePicker,setResourcePicker]=useState<{canvasId:Id;position:{x:number;y:number}}|null>(null);
|
||||||
|
// 选择转成id/incarnation后查询深复制可用性;渲染时的可用性仅用于UI,点击时再次捕获实际选择交runtime。
|
||||||
const copyAvailability=useMemo(()=>engine.imports.canDuplicate([...view.selection].map(id=>root.document.elements.get(id)).filter((element):element is ElementRecord=>!!element).map(({id,incarnation})=>({id,incarnation})),{viewCanvasId:view.canvasId}),[engine,root,view.selection,view.canvasId]);
|
const copyAvailability=useMemo(()=>engine.imports.canDuplicate([...view.selection].map(id=>root.document.elements.get(id)).filter((element):element is ElementRecord=>!!element).map(({id,incarnation})=>({id,incarnation})),{viewCanvasId:view.canvasId}),[engine,root,view.selection,view.canvasId]);
|
||||||
const [showAI, setShowAI] = useState(false), [showRecovery, setShowRecovery] = useState(false);
|
const [showAI, setShowAI] = useState(false), [showRecovery, setShowRecovery] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
// resource显示状态带engine/view身份,旧显示器迟到回调不能为当前画布提供错误图片;sources不是文档资源表。
|
||||||
const [displayState, setDisplayState] = useState<{engine:ProjectEngine|null;viewId:Id|null;sources:Map<Id,ResourceViewSource>;failures:number}>({engine:null,viewId:null,sources:new Map(),failures:0});
|
const [displayState, setDisplayState] = useState<{engine:ProjectEngine|null;viewId:Id|null;sources:Map<Id,ResourceViewSource>;failures:number}>({engine:null,viewId:null,sources:new Map(),failures:0});
|
||||||
const resourceView=useRef<ReturnType<typeof createResourceView>|null>(null);
|
const resourceView=useRef<ReturnType<typeof createResourceView>|null>(null);
|
||||||
|
// 拖动保存起始场景坐标、指针ID与会话token,positions只含顶层选中节点,防分区与成员重复位移。
|
||||||
const pointerStart = useRef<{ x: number; y: number;pointerId?:number } | null>(null), drag = useRef<{ token: number;pointerId?:number; start: { x: number; y: number }; positions: Map<Id, { x: number; y: number }> } | null>(null);
|
const pointerStart = useRef<{ x: number; y: number;pointerId?:number } | null>(null), drag = useRef<{ token: number;pointerId?:number; start: { x: number; y: number }; positions: Map<Id, { x: number; y: number }> } | null>(null);
|
||||||
|
// 复用投影对象与测量结果,避免ReactFlow把纯元数据变化误当节点卸载,影响输入及连接点。
|
||||||
const projectionCache = useRef<ReturnType<typeof createProjectionCache> | null>(null);
|
const projectionCache = useRef<ReturnType<typeof createProjectionCache> | null>(null);
|
||||||
projectionCache.current ??= createProjectionCache();
|
projectionCache.current ??= createProjectionCache();
|
||||||
const measurements = useRef(new Map<Id, { width: number; height: number; measured: { width: number; height: number } }>());
|
const measurements = useRef(new Map<Id, { width: number; height: number; measured: { width: number; height: number } }>());
|
||||||
|
// groups按元素生命周期保存一次文本编辑的history分组ID,元素重建后清旧分组,不能跨incarnation合并编辑。
|
||||||
const imageInput = useRef<HTMLInputElement>(null), groups = useRef(new Map<Id,{incarnation:number;groupId:Id}>());
|
const imageInput = useRef<HTMLInputElement>(null), groups = useRef(new Map<Id,{incarnation:number;groupId:Id}>());
|
||||||
useEffect(()=>{for(const [id,group]of groups.current)if(root.document.elements.get(id)?.incarnation!==group.incarnation)groups.current.delete(id);},[root.document]);
|
useEffect(()=>{for(const [id,group]of groups.current)if(root.document.elements.get(id)?.incarnation!==group.incarnation)groups.current.delete(id);},[root.document]);
|
||||||
|
// 加载期使用受限renderer catalog,完整后回到正常定义;sceneCache把文档、会话预览与查询组成显示场景。
|
||||||
const catalog=useMemo(()=>loading?createLoadingRendererCatalog(engine.editor.registry,renderers.catalog):renderers.catalog,[engine,renderers,!!loading]);
|
const catalog=useMemo(()=>loading?createLoadingRendererCatalog(engine.editor.registry,renderers.catalog):renderers.catalog,[engine,renderers,!!loading]);
|
||||||
const scene=sceneCache.project(engine,root.document,view,sessions,engine.editor.registry,catalog,engine.editor.getQueries(root.document));
|
const scene=sceneCache.project(engine,root.document,view,sessions,engine.editor.registry,catalog,engine.editor.getQueries(root.document));
|
||||||
|
// 仅在尺寸一致且投影缓存确认身份/变换允许时复用measured;离开场景的节点清测量条目。
|
||||||
const projection = useMemo(() => {
|
const projection = useMemo(() => {
|
||||||
const result = scene;
|
const result = scene;
|
||||||
// Preserve renderer measurements across metadata/preview updates. Dropping them
|
// Preserve renderer measurements across metadata/preview updates. Dropping them
|
||||||
@@ -100,36 +123,50 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
for (const node of result.nodes) { const cached = measurements.current.get(node.id); if (cached && cached.width === node.width && cached.height === node.height && projectionCache.current!.canRetainMeasurement(engine,root.document,view.canvasId,node)) node.measured = cached.measured; }
|
for (const node of result.nodes) { const cached = measurements.current.get(node.id); if (cached && cached.width === node.width && cached.height === node.height && projectionCache.current!.canRetainMeasurement(engine,root.document,view.canvasId,node)) node.measured = cached.measured; }
|
||||||
return projectionCache.current!.reuse(engine,root.document,view.canvasId,result);
|
return projectionCache.current!.reuse(engine,root.document,view.canvasId,result);
|
||||||
}, [engine, root.document, scene,view.canvasId]);
|
}, [engine, root.document, scene,view.canvasId]);
|
||||||
|
// 每个view独立OverlayIndex,Portal控件通过索引贡献边界与焦点;不会把浮层几何存入项目文档。
|
||||||
const surface=useRef<HTMLDivElement>(null),overlays=useMemo(()=>createOverlayIndex(viewId),[engine,viewId]);
|
const surface=useRef<HTMLDivElement>(null),overlays=useMemo(()=>createOverlayIndex(viewId),[engine,viewId]);
|
||||||
const overlayScope=useMemo(()=>({index:overlays,engine}),[overlays,engine]);
|
const overlayScope=useMemo(()=>({index:overlays,engine}),[overlays,engine]);
|
||||||
const overlaySnapshot=useSyncExternalStore(overlays.subscribe,overlays.getSnapshot,overlays.getSnapshot);
|
const overlaySnapshot=useSyncExternalStore(overlays.subscribe,overlays.getSnapshot,overlays.getSnapshot);
|
||||||
const surfaceBounds=surface.current?.getBoundingClientRect();
|
const surfaceBounds=surface.current?.getBoundingClientRect();
|
||||||
|
|
||||||
|
// 绘制范围索引用于可见性筛选;sceneViewport把ReactFlow平移/缩放反算为场景矩形。
|
||||||
const paintCache=useMemo(()=>createProjectedPaintIndex(),[engine,view.canvasId]);
|
const paintCache=useMemo(()=>createProjectedPaintIndex(),[engine,view.canvasId]);
|
||||||
const paint=useMemo(()=>paintCache.sync(projection,engine.editor.registry),[paintCache,projection,engine]);
|
const paint=useMemo(()=>paintCache.sync(projection,engine.editor.registry),[paintCache,projection,engine]);
|
||||||
const viewport=useViewport(),surfaceWidth=useStore(state=>state.width),surfaceHeight=useStore(state=>state.height);
|
const viewport=useViewport(),surfaceWidth=useStore(state=>state.width),surfaceHeight=useStore(state=>state.height);
|
||||||
const sceneViewport={x:-viewport.x/viewport.zoom,y:-viewport.y/viewport.zoom,width:surfaceWidth/viewport.zoom,height:surfaceHeight/viewport.zoom};
|
const sceneViewport={x:-viewport.x/viewport.zoom,y:-viewport.y/viewport.zoom,width:surfaceWidth/viewport.zoom,height:surfaceHeight/viewport.zoom};
|
||||||
|
// 过滤元素生命周期已变的浮层;缺surface矩形时只按身份保守保留,不凭缺失测量断言不可见。
|
||||||
const visibleOverlays=overlaySnapshot.length?(surfaceBounds?overlays.visible(surfaceBounds,target=>root.document.elements.get(target.id)?.incarnation===target.incarnation):overlaySnapshot.filter(entry=>root.document.elements.get(entry.target.id)?.incarnation===entry.target.incarnation)):[];
|
const visibleOverlays=overlaySnapshot.length?(surfaceBounds?overlays.visible(surfaceBounds,target=>root.document.elements.get(target.id)?.incarnation===target.incarnation):overlaySnapshot.filter(entry=>root.document.elements.get(entry.target.id)?.incarnation===entry.target.incarnation)):[];
|
||||||
|
// 未知绘制范围必须保留,加上矩形查询命中;不能把unknown当成屏幕外。
|
||||||
const paintedNodes=[...paint.unknown,...paint.query(sceneViewport)];
|
const paintedNodes=[...paint.unknown,...paint.query(sceneViewport)];
|
||||||
const nativeNodes=useStore(state=>state.nodes);
|
const nativeNodes=useStore(state=>state.nodes);
|
||||||
const connectionPaintCache=useMemo(()=>createConnectionPaintIndex(),[engine,view.canvasId]);
|
const connectionPaintCache=useMemo(()=>createConnectionPaintIndex(),[engine,view.canvasId]);
|
||||||
|
// 连线范围依赖真实Handle测量:新版/未知连线使用measuredConnector,兼容节点使用旧几何适配。
|
||||||
|
// 订阅nativeNodes让测量更新后重算连线路径范围,不把DOM测量要求下放core。
|
||||||
const connectionPaint=useMemo(()=>connectionPaintCache.sync(projection,engine.editor.registry,{anchor:(node,handle,end,edge)=>{const measured=flow.getInternalNode(node.id);return node.data.__headlessRecord||edge.type==='unsupported'?measuredConnector(measured,handle,end):compatConnector(node,handle,end==='source'?'right':'left');}}),[connectionPaintCache,projection,engine,flow,nativeNodes]);
|
const connectionPaint=useMemo(()=>connectionPaintCache.sync(projection,engine.editor.registry,{anchor:(node,handle,end,edge)=>{const measured=flow.getInternalNode(node.id);return node.data.__headlessRecord||edge.type==='unsupported'?measuredConnector(measured,handle,end):compatConnector(node,handle,end==='source'?'right':'left');}}),[connectionPaintCache,projection,engine,flow,nativeNodes]);
|
||||||
// Exhausted geometry work cannot prove any edge invisible. Retain the edge
|
// Exhausted geometry work cannot prove any edge invisible. Retain the edge
|
||||||
// layer and its endpoints, not unrelated nodes or a synthetic sentinel owner.
|
// layer and its endpoints, not unrelated nodes or a synthetic sentinel owner.
|
||||||
const paintedEdges=connectionPaint.unknown.includes('paint_budget')?projection.edges.map(edge=>edge.id):[...connectionPaint.unknown,...connectionPaint.query(sceneViewport)];
|
const paintedEdges=connectionPaint.unknown.includes('paint_budget')?projection.edges.map(edge=>edge.id):[...connectionPaint.unknown,...connectionPaint.query(sceneViewport)];
|
||||||
|
// 保留调用方renderer表,并显式安装unsupported节点/边占位,未知内容仍可在场景中呈现。
|
||||||
const nodeTypes=useMemo(()=>({...renderers.nodeTypes,unsupported:UnsupportedNode}),[renderers]),edgeTypes=useMemo(()=>({...renderers.edgeTypes,unsupported:UnsupportedEdge}),[renderers]);
|
const nodeTypes=useMemo(()=>({...renderers.nodeTypes,unsupported:UnsupportedNode}),[renderers]),edgeTypes=useMemo(()=>({...renderers.edgeTypes,unsupported:UnsupportedEdge}),[renderers]);
|
||||||
|
// 稳定动作闭包从current/engine读取最新状态,runtime-only发布不必重建全部卡片编辑上下文。
|
||||||
const current = useRef({ root, projection, view, engine, sessions }); current.current = { root, projection, view, engine, sessions };
|
const current = useRef({ root, projection, view, engine, sessions }); current.current = { root, projection, view, engine, sessions };
|
||||||
|
/** 将命令拒绝或能力不可用显示为错误;成功结果无需额外复制进本地state。 */
|
||||||
const report = useCallback((result: Result | { enabled: boolean; code?: string }) => {
|
const report = useCallback((result: Result | { enabled: boolean; code?: string }) => {
|
||||||
if ('status' in result && result.status === 'rejected' || 'enabled' in result && !result.enabled) setError(errorText(new Error(result.code)));
|
if ('status' in result && result.status === 'rejected' || 'enabled' in result && !result.enabled) setError(errorText(new Error(result.code)));
|
||||||
}, []);
|
}, []);
|
||||||
|
/** 发命令前读取当前incarnation,元素缺失即抛错;渲染侧更早的身份检查由useScopedNodeEditing等负责。 */
|
||||||
const target = (id: Id) => { const element = engine.getSnapshot().document.elements.get(id); if (!element) throw new Error('element_missing'); return { id, incarnation: element.incarnation }; };
|
const target = (id: Id) => { const element = engine.getSnapshot().document.elements.get(id); if (!element) throw new Error('element_missing'); return { id, incarnation: element.incarnation }; };
|
||||||
|
/** 统一元素data补丁入口,可携history groupId;schema、能力和事务合法性留editor验证。 */
|
||||||
const data = (id: Id, patch: Data, groupId?: Id) => report(engine.editor.dispatch({ type: 'element.data', target: target(id), patch }, { groupId }));
|
const data = (id: Id, patch: Data, groupId?: Id) => report(engine.editor.dispatch({ type: 'element.data', target: target(id), patch }, { groupId }));
|
||||||
|
/** 把ReactFlow选择变化合到session当前Set,成员完全相同则不重复发布;不把selected写入文档。 */
|
||||||
function selectChanges(changes: readonly { id: Id; selected: boolean }[]) {
|
function selectChanges(changes: readonly { id: Id; selected: boolean }[]) {
|
||||||
const current = engine.sessions.getSnapshot().views.get(viewId)!;
|
const current = engine.sessions.getSnapshot().views.get(viewId)!;
|
||||||
const ids = new Set(current.selection);
|
const ids = new Set(current.selection);
|
||||||
for (const change of changes) if (change.selected) ids.add(change.id); else ids.delete(change.id);
|
for (const change of changes) if (change.selected) ids.add(change.id); else ids.delete(change.id);
|
||||||
if (ids.size !== current.selection.size || [...ids].some(id => !current.selection.has(id))) engine.sessions.select(viewId, [...ids]);
|
if (ids.size !== current.selection.size || [...ids].some(id => !current.selection.has(id))) engine.sessions.select(viewId, [...ids]);
|
||||||
}
|
}
|
||||||
|
/** 空白点击补充core投影命中:12px容差、预览目标及实际Handle/layer适配;只选择confirmed命中。
|
||||||
|
* 命中计算后再次比较document/session快照身份,过期帧不能选中新incarnation;抓手模式点击清选择。 */
|
||||||
function selectAtPane(event: {clientX:number;clientY:number}) {
|
function selectAtPane(event: {clientX:number;clientY:number}) {
|
||||||
const captured=current.current;
|
const captured=current.current;
|
||||||
if(captured.view.tool!=='select'){engine.sessions.select(viewId,[]);return;}
|
if(captured.view.tool!=='select'){engine.sessions.select(viewId,[]);return;}
|
||||||
@@ -149,12 +186,16 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
const hit=result.hits[0];
|
const hit=result.hits[0];
|
||||||
engine.sessions.select(viewId,hit?.certainty==='confirmed'?[hit.target.id]:[]);
|
engine.sessions.select(viewId,hit?.certainty==='confirmed'?[hit.target.id]:[]);
|
||||||
}
|
}
|
||||||
|
/** session.begin成功后捕获gesture token,以guardEditingLease约束后续preview/commit/cancel只作用于该交互。 */
|
||||||
function beginTransform(id: Id) {
|
function beginTransform(id: Id) {
|
||||||
const result = engine.sessions.begin(viewId, [target(id)]); report(result); if (!result.enabled) return false;
|
const result = engine.sessions.begin(viewId, [target(id)]); report(result); if (!result.enabled) return false;
|
||||||
const token = engine.sessions.getSnapshot().gesture!.token;
|
const token = engine.sessions.getSnapshot().gesture!.token;
|
||||||
|
/** 每次租约动作实时核对token,旧pointerup不能结束后来新建的手势。 */
|
||||||
const current = () => engine.sessions.getSnapshot().gesture?.token === token;
|
const current = () => engine.sessions.getSnapshot().gesture?.token === token;
|
||||||
return guardEditingLease(current, { preview: (change: Parameters<typeof transform>[1]) => transform(id, change), commit: () => report(engine.sessions.commit(viewId)), cancel: () => engine.sessions.cancel('pointer_cancel') });
|
return guardEditingLease(current, { preview: (change: Parameters<typeof transform>[1]) => transform(id, change), commit: () => report(engine.sessions.commit(viewId)), cancel: () => engine.sessions.cancel('pointer_cancel') });
|
||||||
}
|
}
|
||||||
|
/** 将显示空间位置/尺寸转成owner局部Geometry:尺寸除scale,以中心toLocal后再求左上角,旋转减去父旋转。
|
||||||
|
* 这里只更新session预览,不直接dispatch文档;后续commit统一形成history与同步修改。 */
|
||||||
function transform(id: Id, change: { position?: { x: number; y: number }; width?: number; height?: number; rotation?: number; fontSize?: number }) {
|
function transform(id: Id, change: { position?: { x: number; y: number }; width?: number; height?: number; rotation?: number; fontSize?: number }) {
|
||||||
const { root, projection } = current.current, element = root.document.elements.get(id);
|
const { root, projection } = current.current, element = root.document.elements.get(id);
|
||||||
if (element?.structure !== 'node') return;
|
if (element?.structure !== 'node') return;
|
||||||
@@ -165,16 +206,21 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
const patch: Partial<Geometry> = { x: center.x - width / 2, y: center.y - height / 2, width, height, ...(change.rotation !== undefined ? { rotation: ((change.rotation - t.rotation) % 360 + 360) % 360 } : {}) };
|
const patch: Partial<Geometry> = { x: center.x - width / 2, y: center.y - height / 2, width, height, ...(change.rotation !== undefined ? { rotation: ((change.rotation - t.rotation) % 360 + 360) % 360 } : {}) };
|
||||||
report(engine.sessions.update(viewId, target(id), patch));
|
report(engine.sessions.update(viewId, target(id), patch));
|
||||||
}
|
}
|
||||||
|
/** 创建内置节点,可加入调用方已有事务;frame同时创建以节点为入口的子canvas,保证结构一起提交。
|
||||||
|
* 默认位置从首个data-headless-canvas的DOM矩形取屏幕中心再转场景坐标,at可显式覆盖。 */
|
||||||
function add(kind: 'text' | 'plain-text' | 'image' | 'frame', ref?: { id: Id; src: string }, tx?: Parameters<Parameters<typeof engine.editor.transaction>[0]>[0], at?: { x: number; y: number }) {
|
function add(kind: 'text' | 'plain-text' | 'image' | 'frame', ref?: { id: Id; src: string }, tx?: Parameters<Parameters<typeof engine.editor.transaction>[0]>[0], at?: { x: number; y: number }) {
|
||||||
const id = crypto.randomUUID(), canvasId = current.current.view.canvasId;
|
const id = crypto.randomUUID(), canvasId = current.current.view.canvasId;
|
||||||
const rect = window.document.querySelector('[data-headless-canvas]')?.getBoundingClientRect();
|
const rect = window.document.querySelector('[data-headless-canvas]')?.getBoundingClientRect();
|
||||||
const position = at ?? flow.screenToFlowPosition({ x: (rect?.left ?? 0) + (rect?.width ?? window.innerWidth) / 2, y: (rect?.top ?? 0) + (rect?.height ?? window.innerHeight) / 2 });
|
const position = at ?? flow.screenToFlowPosition({ x: (rect?.left ?? 0) + (rect?.width ?? window.innerWidth) / 2, y: (rect?.top ?? 0) + (rect?.height ?? window.innerHeight) / 2 });
|
||||||
|
// 各类型使用固定默认尺寸及初始incarnation/dataVersion;资源引用由已stage/adopt的ref注入,不在这里上传。
|
||||||
const size = kind === 'frame' ? { width: 640, height: 400 } : kind === 'plain-text' ? { width: 240, height: 72 } : { width: 260, height: 200 };
|
const size = kind === 'frame' ? { width: 640, height: 400 } : kind === 'plain-text' ? { width: 240, height: 72 } : { width: 260, height: 200 };
|
||||||
const element: ElementRecord = { id, incarnation: 1, structure: 'node', componentId: kind, dataVersion: 1, ownerCanvasId: canvasId, geometry: { ...position, ...size, rotation: 0 }, data: { title: kind === 'frame' ? '未命名分区' : kind === 'image' ? '视觉参考' : '灵感笔记', text: '', ...(ref ? { assetId: ref.id, src: ref.src } : {}) } };
|
const element: ElementRecord = { id, incarnation: 1, structure: 'node', componentId: kind, dataVersion: 1, ownerCanvasId: canvasId, geometry: { ...position, ...size, rotation: 0 }, data: { title: kind === 'frame' ? '未命名分区' : kind === 'image' ? '视觉参考' : '灵感笔记', text: '', ...(ref ? { assetId: ref.id, src: ref.src } : {}) } };
|
||||||
|
/** tx内创建元素及可选canvas关系;无外部tx时包装为一个Add element事务。 */
|
||||||
const create = (transaction: NonNullable<typeof tx>) => { transaction.dispatch({ type: 'element.create', element }); if (kind === 'frame') transaction.dispatch({ type: 'canvas.create', canvas: { id: crypto.randomUUID(), parent: { canvasId, entryElementId: id } } }); };
|
const create = (transaction: NonNullable<typeof tx>) => { transaction.dispatch({ type: 'element.create', element }); if (kind === 'frame') transaction.dispatch({ type: 'canvas.create', canvas: { id: crypto.randomUUID(), parent: { canvasId, entryElementId: id } } }); };
|
||||||
if (tx) create(tx); else report(engine.editor.transaction(create, { label: 'Add element' }));
|
if (tx) create(tx); else report(engine.editor.transaction(create, { label: 'Add element' }));
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
/** 选择工具才可建边;拒绝unsupported端点,将owner设为两端所属canvas的共同上级,端口ID来自连接事件。 */
|
||||||
function connect(connection: Connection) {
|
function connect(connection: Connection) {
|
||||||
if(engine.sessions.getSnapshot().views.get(viewId)?.tool!=='select')return;
|
if(engine.sessions.getSnapshot().views.get(viewId)?.tool!=='select')return;
|
||||||
const document = engine.getSnapshot().document, source = document.elements.get(connection.source), destination = document.elements.get(connection.target);
|
const document = engine.getSnapshot().document, source = document.elements.get(connection.source), destination = document.elements.get(connection.target);
|
||||||
@@ -182,21 +228,30 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
if([source.id,destination.id].some(id=>projectionCache.current!.getNode(id)?.type==='unsupported')){setError('此元素暂不支持创建新连线');return;}
|
if([source.id,destination.id].some(id=>projectionCache.current!.getNode(id)?.type==='unsupported')){setError('此元素暂不支持创建新连线');return;}
|
||||||
report(engine.editor.dispatch({ type: 'element.create', element: { id: crypto.randomUUID(), incarnation: 1, componentId: 'connection', dataVersion: 1, structure: 'connection', ownerCanvasId: commonCanvas(document, source.ownerCanvasId, destination.ownerCanvasId), source: { elementId: source.id, ...(connection.sourceHandle ? { portId: connection.sourceHandle } : {}) }, target: { elementId: destination.id, ...(connection.targetHandle ? { portId: connection.targetHandle } : {}) }, data: {}, path: null } }));
|
report(engine.editor.dispatch({ type: 'element.create', element: { id: crypto.randomUUID(), incarnation: 1, componentId: 'connection', dataVersion: 1, structure: 'connection', ownerCanvasId: commonCanvas(document, source.ownerCanvasId, destination.ownerCanvasId), source: { elementId: source.id, ...(connection.sourceHandle ? { portId: connection.sourceHandle } : {}) }, target: { elementId: destination.id, ...(connection.targetHandle ? { portId: connection.targetHandle } : {}) }, data: {}, path: null } }));
|
||||||
}
|
}
|
||||||
|
// 用节点ID+assetId序列作为显示订阅键,资源分辨率/URL交资源视图决定;组件不把Blob URL写入元素data。
|
||||||
const resourceKey = JSON.stringify(projection.nodes.filter(node => typeof node.data.assetId==='string'&&node.data.assetId).map(node => [node.id, node.data.assetId]));
|
const resourceKey = JSON.stringify(projection.nodes.filter(node => typeof node.data.assetId==='string'&&node.data.assetId).map(node => [node.id, node.data.assetId]));
|
||||||
|
// 每个engine/view建立资源显示器,回调只接受当前实例;清理dispose解除订阅及显示资源占用。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!liveView) return;
|
if (!liveView) return;
|
||||||
const view=createResourceView({resolve:(id,signal)=>engine.displayResource(id,{signal}),onChange:(sources,failures)=>{if(resourceView.current===view)setDisplayState({engine,viewId,sources,failures});},onError:error=>{if(resourceView.current===view)setError(errorText(error));}});
|
const view=createResourceView({resolve:(id,signal)=>engine.displayResource(id,{signal}),onChange:(sources,failures)=>{if(resourceView.current===view)setDisplayState({engine,viewId,sources,failures});},onError:error=>{if(resourceView.current===view)setError(errorText(error));}});
|
||||||
resourceView.current=view;
|
resourceView.current=view;
|
||||||
return ()=>{if(resourceView.current===view)resourceView.current=null;view.dispose();};
|
return ()=>{if(resourceView.current===view)resourceView.current=null;view.dispose();};
|
||||||
}, [engine,viewId,Boolean(liveView)]);
|
}, [engine,viewId,Boolean(liveView)]);
|
||||||
|
// 资源目标集合变化才sync,映射失败在本面板报错,不擅自修改文档中的assetId。
|
||||||
useEffect(()=>{try{resourceView.current?.sync(JSON.parse(resourceKey) as [Id,Id][]);}catch(error){setError(errorText(error));}},[engine,viewId,resourceKey,Boolean(liveView)]);
|
useEffect(()=>{try{resourceView.current?.sync(JSON.parse(resourceKey) as [Id,Id][]);}catch(error){setError(errorText(error));}},[engine,viewId,resourceKey,Boolean(liveView)]);
|
||||||
|
// 再按engine/view及当前assetId过滤结果,节点切换资源时不显示上一个资源的迟到URL。
|
||||||
const sources=useMemo(()=>{if(displayState.engine!==engine||displayState.viewId!==viewId)return new Map<Id,string>();const wanted=new Map(JSON.parse(resourceKey) as [Id,Id][]);return new Map([...displayState.sources].filter(([id,source])=>wanted.get(id)===source.resourceId).map(([id,source])=>[id,source.url]));},[displayState,engine,viewId,resourceKey]);
|
const sources=useMemo(()=>{if(displayState.engine!==engine||displayState.viewId!==viewId)return new Map<Id,string>();const wanted=new Map(JSON.parse(resourceKey) as [Id,Id][]);return new Map([...displayState.sources].filter(([id,source])=>wanted.get(id)===source.resourceId).map(([id,source])=>[id,source.url]));},[displayState,engine,viewId,resourceKey]);
|
||||||
|
/** 一次事务删除当前选择中仍存在的元素;关联结构处理由editor命令实现,不循环修改投影数组。 */
|
||||||
function removeSelected() { report(engine.editor.transaction(tx => { for (const id of current.current.view.selection) if (tx.getDocument().elements.has(id)) tx.dispatch({ type: 'element.remove', target: target(id) }); }, { label: 'Delete selection' })); }
|
function removeSelected() { report(engine.editor.transaction(tx => { for (const id of current.current.view.selection) if (tx.getDocument().elements.has(id)) tx.dispatch({ type: 'element.remove', target: target(id) }); }, { label: 'Delete selection' })); }
|
||||||
|
// 同步显示来自ledger:未resolved算待处理;waiting_digest单独等待不算阻断,无定时重试的错误和conflicts要提示处理。
|
||||||
const pending = [...root.runtime.ledger.operations.values()].filter(operation => operation.phase !== 'resolved');
|
const pending = [...root.runtime.ledger.operations.values()].filter(operation => operation.phase !== 'resolved');
|
||||||
const blocked = pending.some(operation => operation.phase === 'blocked' && operation.blockers.some(reason => reason !== 'waiting_digest')) || [...root.runtime.ledger.requests.values()].some(request => request.phase !== 'resolved' && request.error && request.retryAt === undefined) || root.runtime.conflicts.size > 0;
|
const blocked = pending.some(operation => operation.phase === 'blocked' && operation.blockers.some(reason => reason !== 'waiting_digest')) || [...root.runtime.ledger.requests.values()].some(request => request.phase !== 'resolved' && request.error && request.retryAt === undefined) || root.runtime.conflicts.size > 0;
|
||||||
|
// 全局失焦或Escape仅取消本视图拥有的节点/连接手势;不干扰同engine其它视图的交互。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
/** 核对viewId后取消session并清本地拖动记录;window blur不要求指针事件。 */
|
||||||
const cancel = () => { const state = engine.sessions.getSnapshot(); if (state.gesture?.viewId === viewId || state.connectionGesture?.viewId === viewId) engine.sessions.cancel('view_interrupted'); drag.current = null; };
|
const cancel = () => { const state = engine.sessions.getSnapshot(); if (state.gesture?.viewId === viewId || state.connectionGesture?.viewId === viewId) engine.sessions.cancel('view_interrupted'); drag.current = null; };
|
||||||
// Bubble after the target/React handlers: an input owner can claim Escape first.
|
// Bubble after the target/React handlers: an input owner can claim Escape first.
|
||||||
|
/** 冒泡阶段让输入控件优先认领Escape,再按统一路由决定是否取消手势。 */
|
||||||
const escape = (event: KeyboardEvent) => {
|
const escape = (event: KeyboardEvent) => {
|
||||||
if(event.key!=='Escape')return;
|
if(event.key!=='Escape')return;
|
||||||
const claim=routeCanvasKey({key:event.key,composing:event.isComposing,defaultPrevented:event.defaultPrevented,...canvasKeyContext(event)},{gesture:()=>{const state=engine.sessions.getSnapshot();if(state.gesture?.viewId!==viewId&&state.connectionGesture?.viewId!==viewId)return false;cancel();return true;}});
|
const claim=routeCanvasKey({key:event.key,composing:event.isComposing,defaultPrevented:event.defaultPrevented,...canvasKeyContext(event)},{gesture:()=>{const state=engine.sessions.getSnapshot();if(state.gesture?.viewId!==viewId&&state.connectionGesture?.viewId!==viewId)return false;cancel();return true;}});
|
||||||
@@ -208,10 +263,12 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
const modes = view.modes;
|
const modes = view.modes;
|
||||||
// Retain explicit owners in the native renderer, leaving the full graph in its
|
// Retain explicit owners in the native renderer, leaving the full graph in its
|
||||||
// lookup for edges/queries. No synthetic dragging or altered geometry is used.
|
// lookup for edges/queries. No synthetic dragging or altered geometry is used.
|
||||||
|
// 保留模式目标、可见绘制对象、浮层目标和本视图手势;完整图仍留ReactFlow查询表,不以伪造拖动避裁剪。
|
||||||
const retained=new Set<Id>([...modes.keys(),...paintedNodes,...paintedEdges]);
|
const retained=new Set<Id>([...modes.keys(),...paintedNodes,...paintedEdges]);
|
||||||
for(const entry of visibleOverlays)retained.add(entry.target.id);
|
for(const entry of visibleOverlays)retained.add(entry.target.id);
|
||||||
if(sessions.gesture?.viewId===viewId)for(const target of sessions.gesture.targets)retained.add(target.id);
|
if(sessions.gesture?.viewId===viewId)for(const target of sessions.gesture.targets)retained.add(target.id);
|
||||||
if(sessions.connectionGesture?.viewId===viewId)retained.add(sessions.connectionGesture.target.id);
|
if(sessions.connectionGesture?.viewId===viewId)retained.add(sessions.connectionGesture.target.id);
|
||||||
|
// 活动输入可来自节点、连线、Portal浮层或独立UI;无法证明其归属时保守关闭可见性裁剪。
|
||||||
const activeEditor=focusedEditor?.isConnected?focusedEditor:null;
|
const activeEditor=focusedEditor?.isConnected?focusedEditor:null;
|
||||||
const focusedOverlay=activeEditor?.closest<HTMLElement>('[data-canvas-overlay-target]');
|
const focusedOverlay=activeEditor?.closest<HTMLElement>('[data-canvas-overlay-target]');
|
||||||
const focusedUI=activeEditor?.closest<HTMLElement>('[data-canvas-ui-view]');
|
const focusedUI=activeEditor?.closest<HTMLElement>('[data-canvas-ui-view]');
|
||||||
@@ -221,10 +278,12 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
if(focusedId)retained.add(focusedId);
|
if(focusedId)retained.add(focusedId);
|
||||||
// Retained connections also keep their measured endpoint owners alive.
|
// Retained connections also keep their measured endpoint owners alive.
|
||||||
for(const id of [...retained]){const element=root.document.elements.get(id);if(element?.structure==='connection'){retained.add(element.source.elementId);retained.add(element.target.elementId);}}
|
for(const id of [...retained]){const element=root.document.elements.get(id);if(element?.structure==='connection'){retained.add(element.source.elementId);retained.add(element.target.elementId);}}
|
||||||
|
// 所有保留对象仍须存在于文档,且视口尺寸已知,才启用native onlyRenderVisibleElements。
|
||||||
const scoped=!(activeEditor&&!focusedId&&!independentFocus)&&[...retained].every(id=>root.document.elements.has(id));
|
const scoped=!(activeEditor&&!focusedId&&!independentFocus)&&[...retained].every(id=>root.document.elements.has(id));
|
||||||
const cullVisible=!!surfaceWidth&&!!surfaceHeight&&scoped;
|
const cullVisible=!!surfaceWidth&&!!surfaceHeight&&scoped;
|
||||||
const retainedProjection=useMemo(()=>createRetainedProjection(),[engine,viewId]);
|
const retainedProjection=useMemo(()=>createRetainedProjection(),[engine,viewId]);
|
||||||
const rendered=retainedProjection(projection.nodes,projection.edges,retained);
|
const rendered=retainedProjection(projection.nodes,projection.edges,retained);
|
||||||
|
// 单选时才启用图片适配/AI工具;图片要求已知组件、resize能力和声明的assetId资源字段,不能猜同名业务字段。
|
||||||
const selected = view.selection.size === 1 ? root.document.elements.get([...view.selection][0]) : undefined;
|
const selected = view.selection.size === 1 ? root.document.elements.get([...view.selection][0]) : undefined;
|
||||||
const selectedResource=selected?.structure==='node'&&engine.editor.registry.resolve(selected)==='known'&&engine.editor.registry.supports(selected,'geometry.resize')&&typeof selected.data.assetId==='string'&&engine.editor.registry.components.get(selected.componentId)?.resourceFields?.includes('assetId')?root.runtime.resources.get(selected.data.assetId):undefined;
|
const selectedResource=selected?.structure==='node'&&engine.editor.registry.resolve(selected)==='known'&&engine.editor.registry.supports(selected,'geometry.resize')&&typeof selected.data.assetId==='string'&&engine.editor.registry.components.get(selected.componentId)?.resourceFields?.includes('assetId')?root.runtime.resources.get(selected.data.assetId):undefined;
|
||||||
const canFitImage=!!selectedResource&&(selectedResource.image?.version===1&&selectedResource.image.status==='ready'||!!selectedResource.stored)&&!sessions.gesture;
|
const canFitImage=!!selectedResource&&(selectedResource.image?.version===1&&selectedResource.image.status==='ready'||!!selectedResource.stored)&&!sessions.gesture;
|
||||||
@@ -233,15 +292,19 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
// Actions use current.current / engine snapshots instead of captured document projections.
|
// Actions use current.current / engine snapshots instead of captured document projections.
|
||||||
const rotating = [...modes].find(([, mode]) => mode === 'rotate')?.[0] ?? null;
|
const rotating = [...modes].find(([, mode]) => mode === 'rotate')?.[0] ?? null;
|
||||||
const resizing = [...modes].find(([, mode]) => mode === 'resize')?.[0] ?? null;
|
const resizing = [...modes].find(([, mode]) => mode === 'resize')?.[0] ?? null;
|
||||||
|
// 新版资源URL寿命由resourceView管理,CanvasImage的loaded回调这里无需删除旧版上传任务。
|
||||||
const imagePreviews = useMemo<ContextType<typeof ImagePreviews>>(() => ({sources,loaded:()=>{}}),[sources]);
|
const imagePreviews = useMemo<ContextType<typeof ImagePreviews>>(() => ({sources,loaded:()=>{}}),[sources]);
|
||||||
|
// 给旧节点renderer注入新版动作:begin/end维护文本history分组与editing mode,正文按同incarnation使用groupId。
|
||||||
const nodeEditing = useMemo<ContextType<typeof NodeEditing>>(() => ({ workspace: board.workspace_id, schema: 2,
|
const nodeEditing = useMemo<ContextType<typeof NodeEditing>>(() => ({ workspace: board.workspace_id, schema: 2,
|
||||||
begin: id => { if (id) { groups.current.set(id,{incarnation:target(id).incarnation,groupId:crypto.randomUUID()}); engine.sessions.mode(viewId, id, 'editing'); } },
|
begin: id => { if (id) { groups.current.set(id,{incarnation:target(id).incarnation,groupId:crypto.randomUUID()}); engine.sessions.mode(viewId, id, 'editing'); } },
|
||||||
endEditing: id => { groups.current.delete(id); engine.sessions.mode(viewId, id, null); },
|
endEditing: id => { groups.current.delete(id); engine.sessions.mode(viewId, id, null); },
|
||||||
select: id => engine.sessions.select(viewId, [id]), edit: (id, text) => data(id,{text},groups.current.get(id)?.incarnation===engine.getSnapshot().document.elements.get(id)?.incarnation?groups.current.get(id)?.groupId:undefined), rename: (id, title) => data(id, { title }),
|
select: id => engine.sessions.select(viewId, [id]), edit: (id, text) => data(id,{text},groups.current.get(id)?.incarnation===engine.getSnapshot().document.elements.get(id)?.incarnation?groups.current.get(id)?.groupId:undefined), rename: (id, title) => data(id, { title }),
|
||||||
beginTransform, transform, finishTransform: () => { if (engine.sessions.getSnapshot().gesture?.viewId === viewId) report(engine.sessions.commit(viewId)); }, cancelTransform: () => { if (engine.sessions.getSnapshot().gesture?.viewId === viewId) engine.sessions.cancel('pointer_cancel'); },
|
beginTransform, transform, finishTransform: () => { if (engine.sessions.getSnapshot().gesture?.viewId === viewId) report(engine.sessions.commit(viewId)); }, cancelTransform: () => { if (engine.sessions.getSnapshot().gesture?.viewId === viewId) engine.sessions.cancel('pointer_cancel'); },
|
||||||
|
// 样式和分区补丁走data,模式rotate/resize只在sessions中切换;开启一个前先清同视图该类旧模式。
|
||||||
style: (id, textStyle, fontSize) => data(id, json({ textStyle, ...(fontSize !== undefined ? { fontSize } : {}) })), frame: (id, patch) => data(id, json(patch)),
|
style: (id, textStyle, fontSize) => data(id, json({ textStyle, ...(fontSize !== undefined ? { fontSize } : {}) })), frame: (id, patch) => data(id, json(patch)),
|
||||||
rotating, rotate: id => { for (const [key, mode] of engine.sessions.getSnapshot().views.get(viewId)?.modes ?? []) if (mode === 'rotate') engine.sessions.mode(viewId, key, null); if (id) engine.sessions.mode(viewId, id, 'rotate'); },
|
rotating, rotate: id => { for (const [key, mode] of engine.sessions.getSnapshot().views.get(viewId)?.modes ?? []) if (mode === 'rotate') engine.sessions.mode(viewId, key, null); if (id) engine.sessions.mode(viewId, id, 'rotate'); },
|
||||||
resizing, resize: id => { for (const [key, mode] of engine.sessions.getSnapshot().views.get(viewId)?.modes ?? []) if (mode === 'resize') engine.sessions.mode(viewId, key, null); if (id) engine.sessions.mode(viewId, id, 'resize'); },
|
resizing, resize: id => { for (const [key, mode] of engine.sessions.getSnapshot().views.get(viewId)?.modes ?? []) if (mode === 'resize') engine.sessions.mode(viewId, key, null); if (id) engine.sessions.mode(viewId, id, 'resize'); },
|
||||||
|
// 分支直接在当前canvas按方向偏移创建文本,再同一事务创建连线;与旧版弹类型菜单的行为不同。
|
||||||
branch: (id, direction) => {
|
branch: (id, direction) => {
|
||||||
const node = projectionCache.current!.getNode(id); if (!node) return;
|
const node = projectionCache.current!.getNode(id); if (!node) return;
|
||||||
const dx = direction === 'left' ? -340 : direction === 'right' ? 340 : 0, dy = direction === 'top' ? -280 : direction === 'bottom' ? 280 : 0;
|
const dx = direction === 'left' ? -340 : direction === 'right' ? 340 : 0, dy = direction === 'top' ? -280 : direction === 'bottom' ? 280 : 0;
|
||||||
@@ -249,19 +312,23 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
},
|
},
|
||||||
|
|
||||||
}),[engine,viewId,board.workspace_id,flow,report,rotating,resizing]);
|
}),[engine,viewId,board.workspace_id,flow,report,rotating,resizing]);
|
||||||
|
// 曲线编辑同样捕获connectionGesture token;active暂为空集合,连线renderer在此不从run状态获取执行动画。
|
||||||
const edgeEditing = useMemo<ContextType<typeof EdgeEditing>>(() => ({ active: new Set(), begin: id => {
|
const edgeEditing = useMemo<ContextType<typeof EdgeEditing>>(() => ({ active: new Set(), begin: id => {
|
||||||
if (!id) return; const result = engine.sessions.beginConnection(viewId, target(id)); report(result); if (!result.enabled) return false;
|
if (!id) return; const result = engine.sessions.beginConnection(viewId, target(id)); report(result); if (!result.enabled) return false;
|
||||||
const token = engine.sessions.getSnapshot().connectionGesture!.token, element = engine.getSnapshot().document.elements.get(id)!;
|
const token = engine.sessions.getSnapshot().connectionGesture!.token, element = engine.getSnapshot().document.elements.get(id)!;
|
||||||
const transform = current.current.projection.transforms.get(element.ownerCanvasId)!;
|
const transform = current.current.projection.transforms.get(element.ownerCanvasId)!;
|
||||||
|
/** token护栏绑定该条连接手势,预览路径先从场景空间变回owner局部空间。 */
|
||||||
const ownsGesture = () => engine.sessions.getSnapshot().connectionGesture?.token === token;
|
const ownsGesture = () => engine.sessions.getSnapshot().connectionGesture?.token === token;
|
||||||
return guardEditingLease(ownsGesture, { preview: (path: NonNullable<import('@/lib/canvas-v2').EdgeData['path']>) => report(engine.sessions.updateConnection(viewId, transformPath(path as Json, transform, true))), commit: () => report(engine.sessions.commitConnection(viewId)), cancel: () => engine.sessions.cancel('pointer_cancel') });
|
return guardEditingLease(ownsGesture, { preview: (path: NonNullable<import('@/lib/canvas-v2').EdgeData['path']>) => report(engine.sessions.updateConnection(viewId, transformPath(path as Json, transform, true))), commit: () => report(engine.sessions.commitConnection(viewId)), cancel: () => engine.sessions.cancel('pointer_cancel') });
|
||||||
},
|
},
|
||||||
finish: () => { if (engine.sessions.getSnapshot().connectionGesture?.viewId === viewId) report(engine.sessions.commitConnection(viewId)); }, cancel: () => { if (engine.sessions.getSnapshot().connectionGesture?.viewId === viewId) engine.sessions.cancel('pointer_cancel'); },
|
finish: () => { if (engine.sessions.getSnapshot().connectionGesture?.viewId === viewId) report(engine.sessions.commitConnection(viewId)); }, cancel: () => { if (engine.sessions.getSnapshot().connectionGesture?.viewId === viewId) engine.sessions.cancel('pointer_cancel'); },
|
||||||
|
// 临时path只更新session;正式修改把data和path分开命令,在同一个事务提交,避免把路径写进业务data。
|
||||||
patch: (id, value, transient) => {
|
patch: (id, value, transient) => {
|
||||||
const element = engine.getSnapshot().document.elements.get(id); if (element?.structure !== 'connection') return;
|
const element = engine.getSnapshot().document.elements.get(id); if (element?.structure !== 'connection') return;
|
||||||
const t = current.current.projection.transforms.get(element.ownerCanvasId)!;
|
const t = current.current.projection.transforms.get(element.ownerCanvasId)!;
|
||||||
const path = transformPath((value.path ?? null) as Json, t, true);
|
const path = transformPath((value.path ?? null) as Json, t, true);
|
||||||
const displayedPath = current.current.projection.edges.find(edge => edge.id === id)?.data?.path;
|
const displayedPath = current.current.projection.edges.find(edge => edge.id === id)?.data?.path;
|
||||||
|
// 工具栏可能传回整个显示data;只有显式含path且与显示路径不同才提交connection.path,避免无意重写。
|
||||||
const changedPath = Object.hasOwn(value, 'path') && !equal(value.path, displayedPath);
|
const changedPath = Object.hasOwn(value, 'path') && !equal(value.path, displayedPath);
|
||||||
if (transient) { report(engine.sessions.updateConnection(viewId, path)); return; }
|
if (transient) { report(engine.sessions.updateConnection(viewId, path)); return; }
|
||||||
const { path: ignored, ...rest } = value; void ignored;
|
const { path: ignored, ...rest } = value; void ignored;
|
||||||
@@ -269,8 +336,15 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
},
|
},
|
||||||
|
|
||||||
}),[engine,viewId,report]);
|
}),[engine,viewId,report]);
|
||||||
|
// 自定义renderer的dispatch/transaction也经过editor,并统一report拒绝;选项只传label/groupId。
|
||||||
const rendererCommands=useMemo<CanvasRendererCommands>(()=>({dispatch(command,options){const result=engine.editor.dispatch(command,{label:options?.label,groupId:options?.groupId});report(result);return result;},transaction(callback,options){const result=engine.editor.transaction(callback,{label:options?.label,groupId:options?.groupId});report(result);return result;}}),[engine,report]);
|
const rendererCommands=useMemo<CanvasRendererCommands>(()=>({dispatch(command,options){const result=engine.editor.dispatch(command,{label:options?.label,groupId:options?.groupId});report(result);return result;},transaction(callback,options){const result=engine.editor.transaction(callback,{label:options?.label,groupId:options?.groupId});report(result);return result;}}),[engine,report]);
|
||||||
|
// 本组件Hook全部调用后才判断视图关闭,保留React Hook调用顺序;已detach时不挂载交互surface。
|
||||||
if (!liveView) return <p role="status">画布已关闭</p>;
|
if (!liveView) return <p role="status">画布已关闭</p>;
|
||||||
|
// surface集中处理焦点epoch、拖动起点和键盘路由:blur微任务只清旧epoch,多触点取消当前手势。
|
||||||
|
// 快捷键按输入上下文优先级处理Escape、H/V、撤销重做及删除;只有认领成功才阻止默认行为。
|
||||||
|
// ReactFlow位移变化只转session预览,测量单独缓存;拖动结束依据起始位置补最后位移后commit。
|
||||||
|
// 工具栏撤销/深复制/导出走各自editor/runtime接口,视口缩放只改view;导出完整文档JSON,不含文件字节。
|
||||||
|
// 文件选择调用stageFiles,引用与图片节点在回调事务里一起创建;导入/AI/资源/恢复面板按加载与选择条件挂载。
|
||||||
return <div ref={surface} className={`${styles.editor} ${view.tool === 'pan' ? styles.handMode : ''}`} data-headless-canvas data-model-loading={loading?"true":undefined} tabIndex={-1}
|
return <div ref={surface} className={`${styles.editor} ${view.tool === 'pan' ? styles.handMode : ''}`} data-headless-canvas data-model-loading={loading?"true":undefined} tabIndex={-1}
|
||||||
onFocusCapture={event => { if ((event.target as HTMLElement).closest('input,textarea,[contenteditable="true"],[role="textbox"]')) { focusEpoch.current++; setFocusedEditor(event.target as HTMLElement); } }}
|
onFocusCapture={event => { if ((event.target as HTMLElement).closest('input,textarea,[contenteditable="true"],[role="textbox"]')) { focusEpoch.current++; setFocusedEditor(event.target as HTMLElement); } }}
|
||||||
onBlurCapture={() => { const epoch = ++focusEpoch.current; queueMicrotask(() => { if (focusEpoch.current === epoch) setFocusedEditor(null); }); }}
|
onBlurCapture={() => { const epoch = ++focusEpoch.current; queueMicrotask(() => { if (focusEpoch.current === epoch) setFocusedEditor(null); }); }}
|
||||||
@@ -296,6 +370,7 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
onMoveEnd={(_, viewport) => engine.sessions.viewport(viewId, viewport)}
|
onMoveEnd={(_, viewport) => engine.sessions.viewport(viewId, viewport)}
|
||||||
onNodeDragStart={(event, node, nodes) => {
|
onNodeDragStart={(event, node, nodes) => {
|
||||||
const ids = new Set((nodes.length ? nodes : [node]).map(node => node.id));
|
const ids = new Set((nodes.length ? nodes : [node]).map(node => node.id));
|
||||||
|
// 同时选中分区入口与后代时只对最上层目标启动手势,后代位置由结构投影带动。
|
||||||
const top = [...ids].filter(id => { const element = current.current.root.document.elements.get(id)!; return !ancestors(current.current.root.document, element.ownerCanvasId).some(canvasId => { const parent = current.current.root.document.canvases.get(canvasId)?.parent; return parent && ids.has(parent.entryElementId); }); });
|
const top = [...ids].filter(id => { const element = current.current.root.document.elements.get(id)!; return !ancestors(current.current.root.document, element.ownerCanvasId).some(canvasId => { const parent = current.current.root.document.canvases.get(canvasId)?.parent; return parent && ids.has(parent.entryElementId); }); });
|
||||||
const point = 'clientX' in event ? event : event.changedTouches[0];
|
const point = 'clientX' in event ? event : event.changedTouches[0];
|
||||||
drag.current = { token: 0,pointerId:pointerStart.current?.pointerId, start: pointerStart.current ?? flow.screenToFlowPosition({ x: point.clientX, y: point.clientY }), positions: new Map(top.map(id => [id, projectionCache.current!.getNode(id)!.position])) };
|
drag.current = { token: 0,pointerId:pointerStart.current?.pointerId, start: pointerStart.current ?? flow.screenToFlowPosition({ x: point.clientX, y: point.clientY }), positions: new Map(top.map(id => [id, projectionCache.current!.getNode(id)!.position])) };
|
||||||
@@ -305,6 +380,7 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
onEdgesChange={changes => selectChanges(changes.filter(change => change.type === 'select'))}
|
onEdgesChange={changes => selectChanges(changes.filter(change => change.type === 'select'))}
|
||||||
onNodesChange={changes => { for (const change of changes) if (change.type === 'dimensions' && change.dimensions) { const node = projectionCache.current!.getNode(change.id); if (node) measurements.current.set(change.id, { width: node.width!, height: node.height!, measured: { ...change.dimensions } }); } selectChanges(changes.filter(change => change.type === 'select')); for (const change of changes) if (change.type === 'position' && change.position && engine.sessions.getSnapshot().gesture?.viewId === viewId && drag.current?.token === engine.sessions.getSnapshot().gesture?.token && engine.sessions.getSnapshot().gesture?.targets.some(target => target.id === change.id)) transform(change.id, { position: change.position }); }}
|
onNodesChange={changes => { for (const change of changes) if (change.type === 'dimensions' && change.dimensions) { const node = projectionCache.current!.getNode(change.id); if (node) measurements.current.set(change.id, { width: node.width!, height: node.height!, measured: { ...change.dimensions } }); } selectChanges(changes.filter(change => change.type === 'select')); for (const change of changes) if (change.type === 'position' && change.position && engine.sessions.getSnapshot().gesture?.viewId === viewId && drag.current?.token === engine.sessions.getSnapshot().gesture?.token && engine.sessions.getSnapshot().gesture?.targets.some(target => target.id === change.id)) transform(change.id, { position: change.position }); }}
|
||||||
onNodeDragStop={event => {
|
onNodeDragStop={event => {
|
||||||
|
// 仅结束匹配本视图和token的拖动,迟到dragStop不提交当前其它手势。
|
||||||
const saved = drag.current; drag.current = null; pointerStart.current = null;
|
const saved = drag.current; drag.current = null; pointerStart.current = null;
|
||||||
if (engine.sessions.getSnapshot().gesture?.viewId !== viewId || !saved || engine.sessions.getSnapshot().gesture?.token !== saved.token) return;
|
if (engine.sessions.getSnapshot().gesture?.viewId !== viewId || !saved || engine.sessions.getSnapshot().gesture?.token !== saved.token) return;
|
||||||
const point = 'clientX' in event ? event : event.changedTouches[0], end = flow.screenToFlowPosition({ x: point.clientX, y: point.clientY });
|
const point = 'clientX' in event ? event : event.changedTouches[0], end = flow.screenToFlowPosition({ x: point.clientX, y: point.clientY });
|
||||||
@@ -318,6 +394,7 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
<div data-canvas-ui-view={viewId} className={styles.topRight}><div className={`${toolbar.surface} ${styles.toolbar}`} role="toolbar" aria-label="图谱视图控制">
|
<div data-canvas-ui-view={viewId} className={styles.topRight}><div className={`${toolbar.surface} ${styles.toolbar}`} role="toolbar" aria-label="图谱视图控制">
|
||||||
<IconButton icon={Undo2} label="撤销" disabled={!root.history.undo.length} onClick={() => report(engine.editor.history.undo())} /><IconButton icon={Redo2} label="重做" disabled={!root.history.redo.length} onClick={() => report(engine.editor.history.redo())} />
|
<IconButton icon={Undo2} label="撤销" disabled={!root.history.undo.length} onClick={() => report(engine.editor.history.undo())} /><IconButton icon={Redo2} label="重做" disabled={!root.history.redo.length} onClick={() => report(engine.editor.history.redo())} />
|
||||||
<IconButton icon={Copy} label={copying || preparingCopy ? "正在准备复制" : "深复制选中内容"} disabled={copying || preparingCopy || !copyAvailability.enabled} onClick={() => {
|
<IconButton icon={Copy} label={copying || preparingCopy ? "正在准备复制" : "深复制选中内容"} disabled={copying || preparingCopy || !copyAvailability.enabled} onClick={() => {
|
||||||
|
// 深复制点击时捕获选择身份,异步完成只更新同engine/view的面板;runtime负责进度与已加入内容。
|
||||||
const captured = current.current, selection = [...captured.view.selection].map(id => captured.root.document.elements.get(id)).filter((item): item is ElementRecord => !!item).map(({id, incarnation}) => ({id, incarnation}));
|
const captured = current.current, selection = [...captured.view.selection].map(id => captured.root.document.elements.get(id)).filter((item): item is ElementRecord => !!item).map(({id, incarnation}) => ({id, incarnation}));
|
||||||
setCopying(true); setError("");
|
setCopying(true); setError("");
|
||||||
void engine.imports.duplicate(selection, {viewCanvasId: captured.view.canvasId}).catch(error => { if (current.current.engine === engine && current.current.view.id === viewId) setError(errorText(error)); }).finally(() => { if (current.current.engine === engine && current.current.view.id === viewId) setCopying(false); });
|
void engine.imports.duplicate(selection, {viewCanvasId: captured.view.canvasId}).catch(error => { if (current.current.engine === engine && current.current.view.id === viewId) setError(errorText(error)); }).finally(() => { if (current.current.engine === engine && current.current.view.id === viewId) setCopying(false); });
|
||||||
@@ -339,9 +416,12 @@ function CanvasView({ engine, board, viewId, renderers,fitLoading=true }: { engi
|
|||||||
{error && <div className={styles.error} role="alert">{error} {displayState.engine===engine&&displayState.viewId===viewId&&displayState.failures>0&&<button onClick={()=>{setError('');resourceView.current?.retry();}}>重试图片</button>}<button onClick={() => setError('')}>关闭</button></div>}
|
{error && <div className={styles.error} role="alert">{error} {displayState.engine===engine&&displayState.viewId===viewId&&displayState.failures>0&&<button onClick={()=>{setError('');resourceView.current?.retry();}}>重试图片</button>}<button onClick={() => setError('')}>关闭</button></div>}
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
|
/** 挂载期生成稳定viewId并attach,借用initialViewport只初始化一次;detach只释放视图,不关闭engine。
|
||||||
|
* 交接视口存在时禁用加载初次fit,避免从只读预览切入后可视位置突然跳变。 */
|
||||||
export default function HeadlessGraphCanvas({ engine, board, renderers=defaultCanvasRenderers,initialViewport }: { engine: ProjectEngine; board: Board; renderers?:ReactRenderers;initialViewport?:Viewport }) {
|
export default function HeadlessGraphCanvas({ engine, board, renderers=defaultCanvasRenderers,initialViewport }: { engine: ProjectEngine; board: Board; renderers?:ReactRenderers;initialViewport?:Viewport }) {
|
||||||
const [handoffViewport]=useState(initialViewport);
|
const [handoffViewport]=useState(initialViewport);
|
||||||
const [viewId] = useState(() => crypto.randomUUID()), [attached, setAttached] = useState(false);
|
const [viewId] = useState(() => crypto.randomUUID()), [attached, setAttached] = useState(false);
|
||||||
|
// attach完成后才挂载CanvasView所需Provider;清理时detach视图,CanvasView卸载清理自身订阅。
|
||||||
useEffect(() => { const detach = engine.sessions.attach(viewId, board.id);if(handoffViewport)engine.sessions.viewport(viewId,handoffViewport); setAttached(true); return () => { setAttached(false); detach(); }; }, [engine, viewId, board.id,handoffViewport]);
|
useEffect(() => { const detach = engine.sessions.attach(viewId, board.id);if(handoffViewport)engine.sessions.viewport(viewId,handoffViewport); setAttached(true); return () => { setAttached(false); detach(); }; }, [engine, viewId, board.id,handoffViewport]);
|
||||||
return attached ? <ReactFlowProvider><CanvasProvider engine={engine} viewId={viewId}><CanvasView engine={engine} board={board} viewId={viewId} renderers={renderers} fitLoading={!handoffViewport} /></CanvasProvider></ReactFlowProvider> : <p role="status">正在准备画布…</p>;
|
return attached ? <ReactFlowProvider><CanvasProvider engine={engine} viewId={viewId}><CanvasView engine={engine} board={board} viewId={viewId} renderers={renderers} fitLoading={!handoffViewport} /></CanvasProvider></ReactFlowProvider> : <p role="status">正在准备画布…</p>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* 新版画布的导入/复制任务显示入口。订阅engine已发布状态,选择文件后启动runtime任务,并展示已加入前缀、等待项与失败原因。
|
||||||
|
* 面板不保存独立任务事实;暂停/继续/停止由imports实现,停止后已加入内容仍保留,不能把它当成整批回滚。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useRef, useState, useSyncExternalStore } from "react";
|
import { useCallback, useRef, useState, useSyncExternalStore } from "react";
|
||||||
@@ -7,15 +11,25 @@ import { IconButton } from "@/components/ui/icon-button";
|
|||||||
import { errorText } from "@/lib/api";
|
import { errorText } from "@/lib/api";
|
||||||
import styles from "./canvas.module.css";
|
import styles from "./canvas.module.css";
|
||||||
|
|
||||||
|
/** 将记录级错误码转成可读说明,未识别的码使用通用提示;原始错误仍保存在任务记录中。 */
|
||||||
const reason = (code: string) => ({ import_asset_authorization_failed: "资源访问授权失败,此记录未加入", import_asset_capacity: "本组资源过大,无法一次准备", asset_depot_unavailable: "资源仓库暂不可用", import_resource_authorization_required: "资源需要重新授权,此记录尚未加入", invalid_document_import: "导出文档结构不合法", invalid_json_array: "JSON 记录数组格式错误", incomplete_json_array: "JSON 数组尾部不完整", json_nesting_limit: "JSON 嵌套层数过多", invalid_json: "记录格式错误", invalid_json_value: "记录包含不支持的数据", invalid_utf8: "文件编码不是 UTF-8", record_too_large: "单条记录过大", unresolved_dependency: "引用的记录未加入", invalid_native_import_record: "不是画布记录", import_component_unavailable: "元素类型暂不支持", invalid_geometry: "元素尺寸不合法", invalid_endpoint: "连线端点已不存在", duplicate_import_source_key: "记录标识重复", import_source_read_failed: "暂时无法读取源文件,可重试;已加入内容保留", import_source_verification_failed: "源文件校验失败,可重试;已加入内容保留", invalid_import_read_proof: "源文件读取证据不一致,任务已暂停", import_source_unavailable: "导入源文件不可用", import_source_changed: "源文件内容与保存时不一致,任务已暂停", import_source_integrity_unavailable: "旧任务缺少源内容校验,无法安全继续;已加入内容保留", import_source_integrity_missing: "源校验记录缺失,任务已暂停", import_source_integrity_interpreter_unavailable: "源校验版本暂不支持", import_target_missing: "目标分区已不存在", import_target_changed: "目标分区已改变", import_dependency_changed: "引用对象已删除或恢复为新版本", dependency_capacity: "等待引用过多,请调整文件顺序", copy_external_changed: "原图引用已删除、移动或恢复为新版本", invalid_duplicate_source: "复制源数据不可用", invalid_copy_snapshot: "复制快照不可用", invalid_copy_preparation: "复制准备记录不可用", copy_interpreter_changed: "复制规则已变化,需要重新复制", invalid_import_source: "文件过大或格式不支持" } as Record<string,string>)[code] ?? "这条记录暂时无法加入";
|
const reason = (code: string) => ({ import_asset_authorization_failed: "资源访问授权失败,此记录未加入", import_asset_capacity: "本组资源过大,无法一次准备", asset_depot_unavailable: "资源仓库暂不可用", import_resource_authorization_required: "资源需要重新授权,此记录尚未加入", invalid_document_import: "导出文档结构不合法", invalid_json_array: "JSON 记录数组格式错误", incomplete_json_array: "JSON 数组尾部不完整", json_nesting_limit: "JSON 嵌套层数过多", invalid_json: "记录格式错误", invalid_json_value: "记录包含不支持的数据", invalid_utf8: "文件编码不是 UTF-8", record_too_large: "单条记录过大", unresolved_dependency: "引用的记录未加入", invalid_native_import_record: "不是画布记录", import_component_unavailable: "元素类型暂不支持", invalid_geometry: "元素尺寸不合法", invalid_endpoint: "连线端点已不存在", duplicate_import_source_key: "记录标识重复", import_source_read_failed: "暂时无法读取源文件,可重试;已加入内容保留", import_source_verification_failed: "源文件校验失败,可重试;已加入内容保留", invalid_import_read_proof: "源文件读取证据不一致,任务已暂停", import_source_unavailable: "导入源文件不可用", import_source_changed: "源文件内容与保存时不一致,任务已暂停", import_source_integrity_unavailable: "旧任务缺少源内容校验,无法安全继续;已加入内容保留", import_source_integrity_missing: "源校验记录缺失,任务已暂停", import_source_integrity_interpreter_unavailable: "源校验版本暂不支持", import_target_missing: "目标分区已不存在", import_target_changed: "目标分区已改变", import_dependency_changed: "引用对象已删除或恢复为新版本", dependency_capacity: "等待引用过多,请调整文件顺序", copy_external_changed: "原图引用已删除、移动或恢复为新版本", invalid_duplicate_source: "复制源数据不可用", invalid_copy_snapshot: "复制快照不可用", invalid_copy_preparation: "复制准备记录不可用", copy_interpreter_changed: "复制规则已变化,需要重新复制", invalid_import_source: "文件过大或格式不支持" } as Record<string,string>)[code] ?? "这条记录暂时无法加入";
|
||||||
|
|
||||||
|
/** 只显示目标canvas最近三个任务,倒序展示;任务数量与汇总仅覆盖这个显示窗口,不代表项目全部导入。 */
|
||||||
export function HeadlessImports({ engine, canvasId, viewId }: { engine: ProjectEngine; canvasId: string; viewId:string }) {
|
export function HeadlessImports({ engine, canvasId, viewId }: { engine: ProjectEngine; canvasId: string; viewId:string }) {
|
||||||
|
// React订阅唯一发布根,不在组件里复制任务状态;同一个getSnapshot也作为服务端快照入口。
|
||||||
const subscribe = useCallback((notify: () => void) => engine.editor.subscribe(notify), [engine]);
|
const subscribe = useCallback((notify: () => void) => engine.editor.subscribe(notify), [engine]);
|
||||||
const snapshot = useSyncExternalStore(subscribe, engine.getSnapshot, engine.getSnapshot);
|
const snapshot = useSyncExternalStore(subscribe, engine.getSnapshot, engine.getSnapshot);
|
||||||
const input = useRef<HTMLInputElement>(null), [open, setOpen] = useState(false), [error, setError] = useState("");
|
const input = useRef<HTMLInputElement>(null), [open, setOpen] = useState(false), [error, setError] = useState("");
|
||||||
|
// 每次渲染更新engine/canvas身份,用于异步文件探测和控制回调完成后避免更新另一画布的错误显示。
|
||||||
const scope = useRef({ engine, canvasId }); scope.current = { engine, canvasId };
|
const scope = useRef({ engine, canvasId }); scope.current = { engine, canvasId };
|
||||||
const jobs = [...(snapshot.runtime.imports?.values() ?? [])].filter(job => job.source?.targetCanvasId === canvasId).slice(-3).reverse();
|
const jobs = [...(snapshot.runtime.imports?.values() ?? [])].filter(job => job.source?.targetCanvasId === canvasId).slice(-3).reverse();
|
||||||
|
/** 统一承接runtime控制Promise的成功/失败;这里只更新面板错误,不自行重排或重启任务。 */
|
||||||
const control = (work: Promise<void>) => { void work.then(() => { if (scope.current.engine === engine && scope.current.canvasId === canvasId) setError(""); }).catch(error => { if (scope.current.engine === engine && scope.current.canvasId === canvasId) setError(errorText(error)); }); };
|
const control = (work: Promise<void>) => { void work.then(() => { if (scope.current.engine === engine && scope.current.canvasId === canvasId) setError(""); }).catch(error => { if (scope.current.engine === engine && scope.current.canvasId === canvasId) setError(errorText(error)); }); };
|
||||||
|
// canStart决定文件入口可用性;input每次先清value,允许再次选择同一个文件。
|
||||||
|
// .json读取前64KiB探测首个非空白字符:对象走文档导入,数组走记录数组;其它后缀走NDJSON。
|
||||||
|
// 探测前捕获canvas父关系及入口生命周期,await后重新核对,防止向已被替换/移走的目标启动任务。
|
||||||
|
// integrityVersion=1源校验未完成显示校验中;=2允许内容继续编辑,但提示校验完成后同步。
|
||||||
|
// 任务按钮按runtime状态显示;失败详情最多列前10项,停止提示明确已加入内容继续同步。
|
||||||
return <aside data-canvas-ui-view={viewId} className={styles.importPanel} aria-label="画布导入">
|
return <aside data-canvas-ui-view={viewId} className={styles.importPanel} aria-label="画布导入">
|
||||||
<div className={styles.importActions}><IconButton icon={FolderInput} label="导入画布记录" disabled={!engine.imports.canStart(canvasId).enabled} onClick={() => input.current?.click()} /><span>NDJSON / JSON 记录数组</span></div>
|
<div className={styles.importActions}><IconButton icon={FolderInput} label="导入画布记录" disabled={!engine.imports.canStart(canvasId).enabled} onClick={() => input.current?.click()} /><span>NDJSON / JSON 记录数组</span></div>
|
||||||
<input data-canvas-import ref={input} type="file" accept=".ndjson,.jsonl,.json,application/json,application/x-ndjson" hidden onChange={async event => {
|
<input data-canvas-import ref={input} type="file" accept=".ndjson,.jsonl,.json,application/json,application/x-ndjson" hidden onChange={async event => {
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* 新版画布的同步冲突处理界面。取得engine提供的恢复会话,按操作逐项选择保留/放弃,先预览再应用。
|
||||||
|
* 真正的冻结、回执核对、重放及备份由runtime完成;面板只保存选择与方案展示,不自行覆盖当前文档。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
@@ -7,6 +11,7 @@ import type { RecoverySession } from '@/lib/canvas-runtime/engine';
|
|||||||
import type { ConflictPlan, RecoveryChoice } from '@/lib/canvas-runtime/conflicts';
|
import type { ConflictPlan, RecoveryChoice } from '@/lib/canvas-runtime/conflicts';
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogTitle } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
|
||||||
|
/** 按恢复错误分类说明需要等待、重新选择或更新解释器;未知错误保留通用重试提示。 */
|
||||||
function message(error:unknown){
|
function message(error:unknown){
|
||||||
const code=(error as {code?:string;message?:string})?.code??(error as Error)?.message;
|
const code=(error as {code?:string;message?:string})?.code??(error as Error)?.message;
|
||||||
if(code==='recovery_waiting_for_receipts')return '还有请求正在确认。请关闭此窗口,重试同步后再处理。';
|
if(code==='recovery_waiting_for_receipts')return '还有请求正在确认。请关闭此窗口,重试同步后再处理。';
|
||||||
@@ -30,19 +35,24 @@ function message(error:unknown){
|
|||||||
if(code==='forbidden'||code==='unauthorized'||code==='identity_changed')return '当前账号无法读取或修改此画布,请确认权限后重试。';
|
if(code==='forbidden'||code==='unauthorized'||code==='identity_changed')return '当前账号无法读取或修改此画布,请确认权限后重试。';
|
||||||
return '处理未完成,当前修改仍已保留。请重试,或恢复编辑后稍后处理。';
|
return '处理未完成,当前修改仍已保留。请重试,或恢复编辑后稍后处理。';
|
||||||
}
|
}
|
||||||
|
/** undefined明确显示未设置,字符串直接显示,其它JSON序列化;超过240字符可展开全文。
|
||||||
|
* React文本节点负责转义内容,不将导入内容或服务端值作为HTML执行。 */
|
||||||
function PreviewValue({value}:{value:Json|undefined}){
|
function PreviewValue({value}:{value:Json|undefined}){
|
||||||
if(value===undefined)return <span>未设置</span>;
|
if(value===undefined)return <span>未设置</span>;
|
||||||
const text=typeof value==='string'?value:JSON.stringify(value);
|
const text=typeof value==='string'?value:JSON.stringify(value);
|
||||||
return text.length>240?<details><summary>{text.slice(0,240)}…(展开全文)</summary><pre style={{whiteSpace:'pre-wrap',overflowWrap:'anywhere'}}>{text}</pre></details>:<span>{text}</span>;
|
return text.length>240?<details><summary>{text.slice(0,240)}…(展开全文)</summary><pre style={{whiteSpace:'pre-wrap',overflowWrap:'anywhere'}}>{text}</pre></details>:<span>{text}</span>;
|
||||||
}
|
}
|
||||||
|
/** 仅对常见字段提供具体中文名,其它data字段与结构关系使用类别名,不改变字段寻址规则。 */
|
||||||
const fieldLabel=(field:string)=>({'data.title':'标题','data.text':'正文',geometry:'位置与尺寸',path:'连线路径'}[field]??(field.startsWith('data.')?'内容字段':'元素关系'));
|
const fieldLabel=(field:string)=>({'data.title':'标题','data.text':'正文',geometry:'位置与尺寸',path:'连线路径'}[field]??(field.startsWith('data.')?'内容字段':'元素关系'));
|
||||||
|
|
||||||
|
/** 创建/删除/替换类变更并排显示服务端当前记录与本地after;字段变更由主列表另行渲染。 */
|
||||||
function StructureReview({change,document}:{change:Exclude<Change,{kind:'field'}>;document:Document}){
|
function StructureReview({change,document}:{change:Exclude<Change,{kind:'field'}>;document:Document}){
|
||||||
const current=change.kind==='element'?document.elements.get(change.id):document.canvases.get(change.id),kind=change.kind==='element'?'元素':'分区';
|
const current=change.kind==='element'?document.elements.get(change.id):document.canvases.get(change.id),kind=change.kind==='element'?'元素':'分区';
|
||||||
const title=change.kind==='element'?(change.after?.data.title??change.before?.data.title??change.id):change.id;
|
const title=change.kind==='element'?(change.after?.data.title??change.before?.data.title??change.id):change.id;
|
||||||
return <div style={{fontSize:13,overflowWrap:'anywhere',marginTop:8}}><strong>{change.after===null?'删除':change.before===null?'创建':'调整'}{kind} · {String(title)}</strong>
|
return <div style={{fontSize:13,overflowWrap:'anywhere',marginTop:8}}><strong>{change.after===null?'删除':change.before===null?'创建':'调整'}{kind} · {String(title)}</strong>
|
||||||
<div>服务端:{current?<PreviewValue value={current as unknown as Json}/>:<span>不存在</span>}</div><div>本地请求:{change.after?<PreviewValue value={change.after as unknown as Json}/>:<span>删除此{kind}</span>}</div></div>;
|
<div>服务端:{current?<PreviewValue value={current as unknown as Json}/>:<span>不存在</span>}</div><div>本地请求:{change.after?<PreviewValue value={change.after as unknown as Json}/>:<span>删除此{kind}</span>}</div></div>;
|
||||||
}
|
}
|
||||||
|
/** 展示方案内结构影响:记录创建删除,以及owner/端点/路径字段;统计删除数量便于核对关联范围。 */
|
||||||
function PlanStructureReview({plan}:{plan:ConflictPlan}){
|
function PlanStructureReview({plan}:{plan:ConflictPlan}){
|
||||||
const changes=plan.operationIds.flatMap(id=>plan.operations.get(id)!.changes),structural=changes.filter(change=>change.kind!=='field'||['ownerCanvasId','source','target','path'].includes(change.field));
|
const changes=plan.operationIds.flatMap(id=>plan.operations.get(id)!.changes),structural=changes.filter(change=>change.kind!=='field'||['ownerCanvasId','source','target','path'].includes(change.field));
|
||||||
if(!structural.length)return null;
|
if(!structural.length)return null;
|
||||||
@@ -52,17 +62,29 @@ function PlanStructureReview({plan}:{plan:ConflictPlan}){
|
|||||||
</details>;
|
</details>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** owner保存清理时要取消的会话,session用于显示;records按操作序列展示并排除上传任务。
|
||||||
|
* choices每个operationId一个决定;plan是会话生成的预览,任何选择修改都使旧plan失效。 */
|
||||||
export function HeadlessRecoveryDialog({engine,close,viewId}:{engine:ProjectEngine;close():void;viewId:string}){
|
export function HeadlessRecoveryDialog({engine,close,viewId}:{engine:ProjectEngine;close():void;viewId:string}){
|
||||||
const owner=useRef<RecoverySession|undefined>(undefined),[session,setSession]=useState<RecoverySession>(),[records,setRecords]=useState<readonly OperationIntent[]>([]);
|
const owner=useRef<RecoverySession|undefined>(undefined),[session,setSession]=useState<RecoverySession>(),[records,setRecords]=useState<readonly OperationIntent[]>([]);
|
||||||
|
// busy防重复动作;frozen在开始应用后锁住选择,保存异常时允许原方案重试,明确拒绝才解除冻结。
|
||||||
const [choices,setChoices]=useState(new Map<Id,RecoveryChoice>()),[plan,setPlan]=useState<ConflictPlan>(),[error,setError]=useState(''),[busy,setBusy]=useState(true),[frozen,setFrozen]=useState(false);
|
const [choices,setChoices]=useState(new Map<Id,RecoveryChoice>()),[plan,setPlan]=useState<ConflictPlan>(),[error,setError]=useState(''),[busy,setBusy]=useState(true),[frozen,setFrozen]=useState(false);
|
||||||
|
// 微任务中准备会话,组件已清理时跳过;会话晚到则立即cancel,不再认领为当前面板。
|
||||||
useEffect(()=>{
|
useEffect(()=>{
|
||||||
let live=true;
|
let live=true;
|
||||||
Promise.resolve().then(()=>live?engine.prepareRecovery():undefined).then(async session=>{if(!session)return;if(!live){await session.cancel();return;}owner.current=session;setSession(session);setRecords([...engine.getSnapshot().runtime.ledger.operations.values()].filter(record=>session.pendingOperationIds.includes(record.intent.id)&&record.intent.operationType!=='asset.upload').sort((a,b)=>a.intent.sequence-b.intent.sequence).map(record=>record.intent));}).catch(error=>{if(live)setError(message(error));}).finally(()=>{if(live)setBusy(false);});
|
Promise.resolve().then(()=>live?engine.prepareRecovery():undefined).then(async session=>{if(!session)return;if(!live){await session.cancel();return;}owner.current=session;setSession(session);setRecords([...engine.getSnapshot().runtime.ledger.operations.values()].filter(record=>session.pendingOperationIds.includes(record.intent.id)&&record.intent.operationType!=='asset.upload').sort((a,b)=>a.intent.sequence-b.intent.sequence).map(record=>record.intent));}).catch(error=>{if(live)setError(message(error));}).finally(()=>{if(live)setBusy(false);});
|
||||||
|
// 卸载尝试取消自己取得的会话;失败时engine仍保留持久屏障,后续retry/cancelRecovery继续收尾。
|
||||||
return()=>{live=false;void owner.current?.cancel().catch(()=>{/* Engine retains the failed durable barrier; retry/cancelRecovery can finish it. */});};
|
return()=>{live=false;void owner.current?.cancel().catch(()=>{/* Engine retains the failed durable barrier; retry/cancelRecovery can finish it. */});};
|
||||||
},[engine]);
|
},[engine]);
|
||||||
|
/** 已有session且正在操作时不允许取消;否则等待engine解除恢复屏障,成功才关闭,失败留窗提示。 */
|
||||||
async function cancel(){if(busy&&session)return;setBusy(true);try{await engine.cancelRecovery();close();}catch(error){setError(message(error));}finally{setBusy(false);}}
|
async function cancel(){if(busy&&session)return;setBusy(true);try{await engine.cancelRecovery();close();}catch(error){setError(message(error));}finally{setBusy(false);}}
|
||||||
|
/** 有plan则resolve逐项方案,无待处理操作则apply采用最新根;拒绝结果展示原因,异常保留冻结方案供重试。 */
|
||||||
async function apply(){if(!session||busy)return;setBusy(true);setError('');setFrozen(true);try{const result=plan?await session.resolve(plan):await session.apply();if(result.status==='rejected'){setFrozen(false);setError(message({code:result.code}));return;}close();}catch(error){setError(message(error));}finally{setBusy(false);}}
|
async function apply(){if(!session||busy)return;setBusy(true);setError('');setFrozen(true);try{const result=plan?await session.resolve(plan):await session.apply();if(result.status==='rejected'){setFrozen(false);setError(message({code:result.code}));return;}close();}catch(error){setError(message(error));}finally{setBusy(false);}}
|
||||||
|
// canonical是恢复会话捕获的服务端基准,不直接读working当成服务端值。
|
||||||
const canonical=session?.canonical.document;
|
const canonical=session?.canonical.document;
|
||||||
|
// Dialog关闭统一走cancel,session忙碌时抑制Escape;初次准备期间仍可请求恢复编辑。
|
||||||
|
// 逐项显示服务端、本地与方案值:afterPresent=false明确表示移除字段,不等同undefined值。
|
||||||
|
// 仅document.change/run.apply提供保留选项,生成开始/取消等动作可放弃但不能在此自动重新执行。
|
||||||
|
// 选择齐全才允许plan,存在本地记录则必须先有plan才允许应用;方案汇总同时显示undo/redo数量变化。
|
||||||
return <Dialog open onOpenChange={open=>{if(!open)void cancel();}}><DialogContent data-canvas-ui-view={viewId} aria-label="处理同步修改" style={{zIndex:300,maxHeight:'80vh',overflowY:'auto',background:'var(--background, #fffdf9)',color:'var(--foreground, #302d29)'}} onEscapeKeyDown={event=>{if(busy&&session)event.preventDefault();}}>
|
return <Dialog open onOpenChange={open=>{if(!open)void cancel();}}><DialogContent data-canvas-ui-view={viewId} aria-label="处理同步修改" style={{zIndex:300,maxHeight:'80vh',overflowY:'auto',background:'var(--background, #fffdf9)',color:'var(--foreground, #302d29)'}} onEscapeKeyDown={event=>{if(busy&&session)event.preventDefault();}}>
|
||||||
<DialogTitle>处理同步修改</DialogTitle>
|
<DialogTitle>处理同步修改</DialogTitle>
|
||||||
<DialogDescription>检查期间暂停编辑。逐项选择要保留的修改,预览后再应用;原内容和撤销记录会保留备份。</DialogDescription>
|
<DialogDescription>检查期间暂停编辑。逐项选择要保留的修改,预览后再应用;原内容和撤销记录会保留备份。</DialogDescription>
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* 从同工作区已打开的其它项目中发现可复用图片,授权接纳资源后在目标画布创建新图片元素。
|
||||||
|
* 面板不重新上传原文件;资源接纳与元素创建的事务、持久化和授权由engine.adoptResource负责。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useId, useRef, useState } from "react";
|
import { useEffect, useId, useRef, useState } from "react";
|
||||||
@@ -9,27 +13,37 @@ import type { Id, Point } from "@/lib/canvas-core/types";
|
|||||||
import { fault } from "@/lib/canvas-core/values";
|
import { fault } from "@/lib/canvas-core/values";
|
||||||
import { errorText } from "@/lib/api";
|
import { errorText } from "@/lib/api";
|
||||||
|
|
||||||
|
/** 懒加载候选缩略图,失败后以通用图标代替;failed是该预览组件的局部显示状态,不修改资源记录。 */
|
||||||
function Preview({src}:{src:string}){const [failed,setFailed]=useState(false);return failed?<ImageIcon aria-hidden className="h-8 w-8 opacity-50"/>:<img src={src} alt="" loading="lazy" className="h-full w-full object-contain" onError={()=>setFailed(true)}/>;}
|
function Preview({src}:{src:string}){const [failed,setFailed]=useState(false);return failed?<ImageIcon aria-hidden className="h-8 w-8 opacity-50"/>:<img src={src} alt="" loading="lazy" className="h-full w-full object-contain" onError={()=>setFailed(true)}/>;}
|
||||||
|
/** 列表只保存资源ID和展示标题;插入时重新由engine取得资源元数据,不能信任缩略图即代表可访问。 */
|
||||||
type Candidate = { id: Id; title: string };
|
type Candidate = { id: Id; title: string };
|
||||||
|
/** position是打开面板时捕获的画布坐标,插入图片以此为中心;onAdded让调用方选择新元素。 */
|
||||||
export function HeadlessResourcePicker({engine,workspaceId,canvasId,position,close,onAdded,viewId}:{engine:ProjectEngine;workspaceId:Id;canvasId:Id;position:Point;close():void;onAdded(id:Id):void;viewId:string}) {
|
export function HeadlessResourcePicker({engine,workspaceId,canvasId,position,close,onAdded,viewId}:{engine:ProjectEngine;workspaceId:Id;canvasId:Id;position:Point;close():void;onAdded(id:Id):void;viewId:string}) {
|
||||||
const host=useCanvasRuntimeHost(),[items,setItems]=useState<Candidate[]>([]),[loading,setLoading]=useState(true),[busy,setBusy]=useState<Id>(),[error,setError]=useState("");
|
const host=useCanvasRuntimeHost(),[items,setItems]=useState<Candidate[]>([]),[loading,setLoading]=useState(true),[busy,setBusy]=useState<Id>(),[error,setError]=useState("");
|
||||||
|
// controller取消本次面板操作,requesting同步防重复点击,busy用于禁用按钮和展示当前候选进度。
|
||||||
const lifecycle=useRef<AbortController|null>(null),requesting=useRef(false),descriptionId=useId();
|
const lifecycle=useRef<AbortController|null>(null),requesting=useRef(false),descriptionId=useId();
|
||||||
|
/** 关闭前发取消信号;已经提交的事务不会由这个UI回调自动撤销。 */
|
||||||
const dismiss=()=>{lifecycle.current?.abort();close();};
|
const dismiss=()=>{lifecycle.current?.abort();close();};
|
||||||
|
// 初次挂载捕获目标canvas及父入口记录,异步接纳资源后仍须核对入口身份与生命周期。
|
||||||
const [target]=useState(()=>{const document=engine.getSnapshot().document,canvas=document.canvases.get(canvasId),entry=canvas?.parent?document.elements.get(canvas.parent.entryElementId):undefined;return {canvas,entry};});
|
const [target]=useState(()=>{const document=engine.getSnapshot().document,canvas=document.canvases.get(canvasId),entry=canvas?.parent?document.elements.get(canvas.parent.entryElementId):undefined;return {canvas,entry};});
|
||||||
|
// 记录当前账户代次与工作区,收集已打开/正在打开的其它项目;不扫描服务端全部画布。
|
||||||
useEffect(()=>{
|
useEffect(()=>{
|
||||||
const controller=new AbortController();lifecycle.current=controller;
|
const controller=new AbortController();lifecycle.current=controller;
|
||||||
const identity=host.identity(),workspace=host.getWorkspaces().get(workspaceId);
|
const identity=host.identity(),workspace=host.getWorkspaces().get(workspaceId);
|
||||||
void (async()=>{
|
void (async()=>{
|
||||||
if(!workspace?.isCurrentIdentity()||workspace.accountId!==identity.accountId)throw fault('identity_changed');
|
if(!workspace?.isCurrentIdentity()||workspace.accountId!==identity.accountId)throw fault('identity_changed');
|
||||||
|
// 单个项目打开失败不阻断其它候选,allSettled保留每项结果;排除本项目避免重复从自身取资源。
|
||||||
const results=await Promise.allSettled([...workspace.getProjects()].filter(([id])=>id!==engine.getSnapshot().document.projectId).map(([,project])=>project));
|
const results=await Promise.allSettled([...workspace.getProjects()].filter(([id])=>id!==engine.getSnapshot().document.projectId).map(([,project])=>project));
|
||||||
if(controller.signal.aborted)return;
|
if(controller.signal.aborted)return;
|
||||||
if(!workspace.isCurrentIdentity()||host.identity().authEpoch!==identity.authEpoch)throw fault('identity_changed');
|
if(!workspace.isCurrentIdentity()||host.identity().authEpoch!==identity.authEpoch)throw fault('identity_changed');
|
||||||
|
// 按资源ID去重,排除本项目已有资源;其它项目若有本地未stored资源也跳过,避免复用未可靠保存的文件。
|
||||||
const candidates=new Map<Id,Candidate>(),owned=engine.getSnapshot().runtime.resources;
|
const candidates=new Map<Id,Candidate>(),owned=engine.getSnapshot().runtime.resources;
|
||||||
for(const result of results)if(result.status==='fulfilled'){
|
for(const result of results)if(result.status==='fulfilled'){
|
||||||
const snapshot=result.value.getSnapshot();
|
const snapshot=result.value.getSnapshot();
|
||||||
for(const element of snapshot.document.elements.values()){
|
for(const element of snapshot.document.elements.values()){
|
||||||
const id=element.data.assetId;
|
const id=element.data.assetId;
|
||||||
if(element.structure!=='node'||typeof id!=='string'||!id||owned.has(id)||candidates.has(id)||snapshot.runtime.resources.has(id)&&!snapshot.runtime.resources.get(id)!.stored)continue;
|
if(element.structure!=='node'||typeof id!=='string'||!id||owned.has(id)||candidates.has(id)||snapshot.runtime.resources.has(id)&&!snapshot.runtime.resources.get(id)!.stored)continue;
|
||||||
|
// 只从明确声明assetId资源字段的组件提取,不能把任意同名业务字段当图片资源。
|
||||||
if(!result.value.editor.registry.components.get(element.componentId)?.resourceFields?.includes('assetId'))continue;
|
if(!result.value.editor.registry.components.get(element.componentId)?.resourceFields?.includes('assetId'))continue;
|
||||||
candidates.set(id,{id,title:typeof element.data.title==='string'&&element.data.title.trim()?element.data.title:'未命名图片'});
|
candidates.set(id,{id,title:typeof element.data.title==='string'&&element.data.title.trim()?element.data.title:'未命名图片'});
|
||||||
}
|
}
|
||||||
@@ -38,6 +52,8 @@ export function HeadlessResourcePicker({engine,workspaceId,canvasId,position,clo
|
|||||||
})().catch(error=>{if(!controller.signal.aborted){setLoading(false);setError(errorText(error));}});
|
})().catch(error=>{if(!controller.signal.aborted){setLoading(false);setError(errorText(error));}});
|
||||||
return()=>{controller.abort();if(lifecycle.current===controller)lifecycle.current=null;};
|
return()=>{controller.abort();if(lifecycle.current===controller)lifecycle.current=null;};
|
||||||
},[engine,host,workspaceId]);
|
},[engine,host,workspaceId]);
|
||||||
|
/** 一次只接纳一个候选。生成新元素ID,在adoptResource提供的事务内校验目标并创建图片。
|
||||||
|
* 失败保持面板以便重试;关闭或卸载后不再更新错误/选中状态,取消的实际边界由engine处理。 */
|
||||||
async function insert(item:Candidate){
|
async function insert(item:Candidate){
|
||||||
const signal=lifecycle.current?.signal;if(!signal||signal.aborted||requesting.current)return;
|
const signal=lifecycle.current?.signal;if(!signal||signal.aborted||requesting.current)return;
|
||||||
requesting.current=true;
|
requesting.current=true;
|
||||||
@@ -45,15 +61,19 @@ export function HeadlessResourcePicker({engine,workspaceId,canvasId,position,clo
|
|||||||
try{
|
try{
|
||||||
const id=crypto.randomUUID(),result=await engine.adoptResource(item.id,(resource,tx)=>{
|
const id=crypto.randomUUID(),result=await engine.adoptResource(item.id,(resource,tx)=>{
|
||||||
const document=tx.getDocument(),canvas=document.canvases.get(canvasId),entry=canvas?.parent?document.elements.get(canvas.parent.entryElementId):undefined;
|
const document=tx.getDocument(),canvas=document.canvases.get(canvasId),entry=canvas?.parent?document.elements.get(canvas.parent.entryElementId):undefined;
|
||||||
|
// 父入口ID变化或原入口incarnation变化都拒绝,避免资源授权等待期间目标已经重建。
|
||||||
if(!canvas||canvas.parent?.entryElementId!==target.canvas?.parent?.entryElementId||target.entry&&(entry?.id!==target.entry.id||entry.incarnation!==target.entry.incarnation))throw fault('asset_target_changed');
|
if(!canvas||canvas.parent?.entryElementId!==target.canvas?.parent?.entryElementId||target.entry&&(entry?.id!==target.entry.id||entry.incarnation!==target.entry.incarnation))throw fault('asset_target_changed');
|
||||||
|
// 按原始宽高等比装入260×200边界,再以position为中心计算左上角;小图也可能被放大。
|
||||||
const scale=Math.min(260/resource.asset.width,200/resource.asset.height),width=resource.asset.width*scale,height=resource.asset.height*scale;
|
const scale=Math.min(260/resource.asset.width,200/resource.asset.height),width=resource.asset.width*scale,height=resource.asset.height*scale;
|
||||||
tx.dispatch({type:'element.create',element:{id,incarnation:1,structure:'node',componentId:'image',dataVersion:1,ownerCanvasId:canvasId,geometry:{x:position.x-width/2,y:position.y-height/2,width,height,rotation:0},data:{title:item.title,text:'',assetId:resource.id,src:resource.src}}});
|
tx.dispatch({type:'element.create',element:{id,incarnation:1,structure:'node',componentId:'image',dataVersion:1,ownerCanvasId:canvasId,geometry:{x:position.x-width/2,y:position.y-height/2,width,height,rotation:0},data:{title:item.title,text:'',assetId:resource.id,src:resource.src}}});
|
||||||
},{signal});
|
},{signal});
|
||||||
|
// engine拒绝与异常统一进入错误展示;仅在面板仍活跃时通知onAdded并关闭。
|
||||||
if(result.status==='rejected')throw fault(result.code,result.targets);
|
if(result.status==='rejected')throw fault(result.code,result.targets);
|
||||||
if(!signal.aborted){onAdded(id);close();}
|
if(!signal.aborted){onAdded(id);close();}
|
||||||
}catch(error){if(!signal.aborted)setError(error instanceof Error&&error.message==='not_found'?'无法读取这张图片,请确认仍有原画布的访问权限。':errorText(error));}
|
}catch(error){if(!signal.aborted)setError(error instanceof Error&&error.message==='not_found'?'无法读取这张图片,请确认仍有原画布的访问权限。':errorText(error));}
|
||||||
finally{requesting.current=false;if(!signal.aborted)setBusy(undefined);}
|
finally{requesting.current=false;if(!signal.aborted)setBusy(undefined);}
|
||||||
}
|
}
|
||||||
|
// Dialog关闭入口都走dismiss;缩略图使用工作区资源预览接口,标题截断仅影响显示。
|
||||||
return <Dialog open onOpenChange={open=>{if(!open)dismiss();}}><DialogContent data-canvas-ui-view={viewId} aria-describedby={descriptionId}>
|
return <Dialog open onOpenChange={open=>{if(!open)dismiss();}}><DialogContent data-canvas-ui-view={viewId} aria-describedby={descriptionId}>
|
||||||
<DialogHeader><DialogTitle>从其它画布添加图片</DialogTitle><DialogDescription id={descriptionId}>选择同一工作区已打开画布中的图片,无需再次上传。</DialogDescription></DialogHeader>
|
<DialogHeader><DialogTitle>从其它画布添加图片</DialogTitle><DialogDescription id={descriptionId}>选择同一工作区已打开画布中的图片,无需再次上传。</DialogDescription></DialogHeader>
|
||||||
{loading?<p role="status">正在查找图片…</p>:items.length===0?<p>暂无可复用的图片。先打开有已上传图片的画布,再回到这里。</p>:<div className="grid max-h-80 grid-cols-2 gap-3 overflow-y-auto">{items.map(item=><button key={item.id} type="button" aria-label={`添加图片:${item.title}`} disabled={!!busy} onClick={()=>void insert(item)} className="flex min-w-0 flex-col items-center gap-2 rounded-lg border border-border p-3 text-sm hover:bg-muted disabled:opacity-50">
|
{loading?<p role="status">正在查找图片…</p>:items.length===0?<p>暂无可复用的图片。先打开有已上传图片的画布,再回到这里。</p>:<div className="grid max-h-80 grid-cols-2 gap-3 overflow-y-auto">{items.map(item=><button key={item.id} type="button" aria-label={`添加图片:${item.title}`} disabled={!!busy} onClick={()=>void insert(item)} className="flex min-w-0 flex-col items-center gap-2 rounded-lg border border-border p-3 text-sm hover:bg-muted disabled:opacity-50">
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* 旧画布迁往canonical模型的界面协调层。持有本页旧编辑租约,迁移前停止新编辑并排空旧writer,结果确认后重开新版。
|
||||||
|
* “升级”指数据与协议迁移;本地记录和浏览器锁用于跨页协调,服务端版本校验与幂等仍由迁移服务负责。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
import {useEffect,useRef,useState} from 'react';
|
import {useEffect,useRef,useState} from 'react';
|
||||||
import type {Registry} from '@/lib/canvas-core/types';
|
import type {Registry} from '@/lib/canvas-core/types';
|
||||||
@@ -6,21 +10,33 @@ import {canvasMigrationStorageKey,migrationBlocksCanvas,readCanvasMigration,type
|
|||||||
import {errorText} from '@/lib/api';
|
import {errorText} from '@/lib/api';
|
||||||
import styles from './canvas.module.css';
|
import styles from './canvas.module.css';
|
||||||
|
|
||||||
|
/** 将迁移错误码翻成可操作提示,尤其区分确定拒绝与结果未知;未知结果不能当成没写入而直接开放旧编辑。 */
|
||||||
function message(error:unknown){
|
function message(error:unknown){
|
||||||
const code=error instanceof Error?error.message:String(error);
|
const code=error instanceof Error?error.message:String(error);
|
||||||
return ({migration_busy:'其他旧画布页面仍在编辑或升级,请先完成那里的保存和上传,再关闭页面重试。',migration_lock_unavailable:'此浏览器不支持安全升级,请使用支持 Web Locks 的浏览器。',migration_response_unknown:'升级结果尚未确认,编辑已暂停。可继续查询原请求。',invalid_migration_receipt:'升级回执无法确认,已保留原请求并暂停编辑。请继续查询或联系支持。',migration_pending_uploads:'请先完成或取消图片上传,再升级。',draft_recovery_required:'请先处理本地草稿恢复,再升级。',canvas_busy:'请先完成当前操作与同步,再升级。',migration_waiting_for_runs:'请等待生成任务结束,再重新准备升级。',migration_version_conflict:'画布已发生变化,请重新准备升级。',workspace_migration_pending:'本工作区还有另一画布的升级待确认,请先处理原画布。',invalid_migration_record:'无法读取本地升级进度,已保留记录并暂停编辑。',migration_interpreter_unavailable:'本地升级进度需要其他版本解释,已保留记录并暂停编辑。',migration_not_durable:'无法可靠保存升级进度,请保留页面并重试。'} as Record<string,string>)[code]??errorText(error instanceof Error?error:new Error(code));
|
return ({migration_busy:'其他旧画布页面仍在编辑或升级,请先完成那里的保存和上传,再关闭页面重试。',migration_lock_unavailable:'此浏览器不支持安全升级,请使用支持 Web Locks 的浏览器。',migration_response_unknown:'升级结果尚未确认,编辑已暂停。可继续查询原请求。',invalid_migration_receipt:'升级回执无法确认,已保留原请求并暂停编辑。请继续查询或联系支持。',migration_pending_uploads:'请先完成或取消图片上传,再升级。',draft_recovery_required:'请先处理本地草稿恢复,再升级。',canvas_busy:'请先完成当前操作与同步,再升级。',migration_waiting_for_runs:'请等待生成任务结束,再重新准备升级。',migration_version_conflict:'画布已发生变化,请重新准备升级。',workspace_migration_pending:'本工作区还有另一画布的升级待确认,请先处理原画布。',invalid_migration_record:'无法读取本地升级进度,已保留记录并暂停编辑。',migration_interpreter_unavailable:'本地升级进度需要其他版本解释,已保留记录并暂停编辑。',migration_not_durable:'无法可靠保存升级进度,请保留页面并重试。'} as Record<string,string>)[code]??errorText(error instanceof Error?error:new Error(code));
|
||||||
}
|
}
|
||||||
|
/** hold控制旧编辑入口;prepare排空指定根的保存工作,check检查当前是否允许迁移。
|
||||||
|
* canLeave保护重开页面前的未同步内容,exportDraft提供本页备份,context提供账户与迁移根身份。 */
|
||||||
type Props={context:LegacyMigrationContext;workspaceId:string;canvasId:string;registry:Registry;held:boolean;hold(value:boolean):void;prepare(rootId:string):Promise<void>;check():void;canLeave():boolean;exportDraft():void};
|
type Props={context:LegacyMigrationContext;workspaceId:string;canvasId:string;registry:Registry;held:boolean;hold(value:boolean):void;prepare(rootId:string):Promise<void>;check():void;canLeave():boolean;exportDraft():void};
|
||||||
|
/** 只保存迁移展示状态,实际请求/本地记录由createBrowserCanvasMigration管理。
|
||||||
|
* attempt是同步防重入标记,running只用于渲染,finished表示本页已进入成功或外部变更后的交接阶段。 */
|
||||||
export function LegacyCanvasMigration(props:Props){
|
export function LegacyCanvasMigration(props:Props){
|
||||||
|
// 回调经ref读取最新props,避免每次父组件渲染都重新申请共享旧编辑租约。
|
||||||
const port=useRef(props);port.current=props;
|
const port=useRef(props);port.current=props;
|
||||||
const [job,setJob]=useState<CanvasMigrationJob>(),[error,setError]=useState(''),[checking,setChecking]=useState(true),[running,setRunning]=useState(false),[changedElsewhere,setChangedElsewhere]=useState(false);
|
const [job,setJob]=useState<CanvasMigrationJob>(),[error,setError]=useState(''),[checking,setChecking]=useState(true),[running,setRunning]=useState(false),[changedElsewhere,setChangedElsewhere]=useState(false);
|
||||||
|
// lease是本页共享旧编辑锁;life取消本次挂载工作;previous用来识别其它页面删除待确认记录的变化。
|
||||||
const lease=useRef<{release():Promise<void>}|undefined>(undefined),life=useRef<AbortController|undefined>(undefined),attempt=useRef(false),finished=useRef(false),previous=useRef<CanvasMigrationJob|undefined>(undefined);
|
const lease=useRef<{release():Promise<void>}|undefined>(undefined),life=useRef<AbortController|undefined>(undefined),attempt=useRef(false),finished=useRef(false),previous=useRef<CanvasMigrationJob|undefined>(undefined);
|
||||||
|
// localStorage迁移记录按账户+工作区隔离,canvasId用于判断该任务是否阻断当前画布。
|
||||||
const scope={accountId:props.context.accountId,workspaceId:props.workspaceId},key=canvasMigrationStorageKey(scope);
|
const scope={accountId:props.context.accountId,workspaceId:props.workspaceId},key=canvasMigrationStorageKey(scope);
|
||||||
const refresh=useRef<()=>Promise<void>>(async()=>{});
|
const refresh=useRef<()=>Promise<void>>(async()=>{});
|
||||||
|
// 挂载或作用域变化时检查记录并申请旧编辑租约;身份失效或卸载后不再采用异步结果。
|
||||||
useEffect(()=>{
|
useEffect(()=>{
|
||||||
const controller=new AbortController();life.current=controller;
|
const controller=new AbortController();life.current=controller;
|
||||||
|
/** 同时检查本页取消与账户身份,不能只因旧请求返回就更新当前页面或解锁编辑。 */
|
||||||
const current=()=>!controller.signal.aborted&&port.current.context.isCurrentIdentity();
|
const current=()=>!controller.signal.aborted&&port.current.context.isCurrentIdentity();
|
||||||
|
/** 读取并校验本作用域持久迁移记录;格式/解释版本错误也要走保留记录和暂停路径。 */
|
||||||
const read=()=>readCanvasMigration(localStorage,scope);
|
const read=()=>readCanvasMigration(localStorage,scope);
|
||||||
|
/** 迁移尝试进行中不抢租约;已有pending或finished就保持hold,正常情形取得共享锁后开放旧编辑。 */
|
||||||
async function inspect(){
|
async function inspect(){
|
||||||
if(attempt.current||!current())return;
|
if(attempt.current||!current())return;
|
||||||
setChecking(true);
|
setChecking(true);
|
||||||
@@ -29,9 +45,11 @@ export function LegacyCanvasMigration(props:Props){
|
|||||||
if(migrationBlocksCanvas(next,props.canvasId)||finished.current){
|
if(migrationBlocksCanvas(next,props.canvasId)||finished.current){
|
||||||
port.current.hold(true);const held=lease.current;lease.current=undefined;await held?.release();setError('');return;
|
port.current.hold(true);const held=lease.current;lease.current=undefined;await held?.release();setError('');return;
|
||||||
}
|
}
|
||||||
|
// 已持有共享锁时复用;申请新锁前先暂停编辑,避免没有锁的空档接收修改。
|
||||||
if(lease.current){port.current.hold(false);setError('');return;}
|
if(lease.current){port.current.hold(false);setError('');return;}
|
||||||
port.current.hold(true);
|
port.current.hold(true);
|
||||||
const acquired=await claimLegacyCanvasEditing({scope,canvasId:props.canvasId,signal:controller.signal,isCurrentIdentity:current});
|
const acquired=await claimLegacyCanvasEditing({scope,canvasId:props.canvasId,signal:controller.signal,isCurrentIdentity:current});
|
||||||
|
// 等锁期间页面可能卸载或换账户,拿到过期锁立即释放,不再发布可编辑状态。
|
||||||
if(!current()){await acquired.release();return;}
|
if(!current()){await acquired.release();return;}
|
||||||
lease.current=acquired;port.current.hold(false);setError('');
|
lease.current=acquired;port.current.hold(false);setError('');
|
||||||
}catch(error){
|
}catch(error){
|
||||||
@@ -39,6 +57,7 @@ export function LegacyCanvasMigration(props:Props){
|
|||||||
port.current.hold(true);const held=lease.current;lease.current=undefined;await held?.release();
|
port.current.hold(true);const held=lease.current;lease.current=undefined;await held?.release();
|
||||||
// Without Web Locks this browser cannot upgrade, but existing legacy
|
// Without Web Locks this browser cannot upgrade, but existing legacy
|
||||||
// editing remains supported unless there is an unresolved identity job.
|
// editing remains supported unless there is an unresolved identity job.
|
||||||
|
// 不支持Web Locks仅禁止安全迁移;没有阻断记录时仍允许旧编辑,不能把这类环境错误当数据已迁移。
|
||||||
if(error instanceof Error&&error.message==='migration_lock_unavailable'){
|
if(error instanceof Error&&error.message==='migration_lock_unavailable'){
|
||||||
try{if(!migrationBlocksCanvas(read(),props.canvasId))port.current.hold(false);}catch{}
|
try{if(!migrationBlocksCanvas(read(),props.canvasId))port.current.hold(false);}catch{}
|
||||||
}
|
}
|
||||||
@@ -46,6 +65,8 @@ export function LegacyCanvasMigration(props:Props){
|
|||||||
}finally{if(current())setChecking(false);}
|
}finally{if(current())setChecking(false);}
|
||||||
}
|
}
|
||||||
refresh.current=inspect;void inspect();
|
refresh.current=inspect;void inspect();
|
||||||
|
/** 其它页改变同一记录时重新检查;本页迁移中忽略事件,由当前尝试负责收尾。
|
||||||
|
* 待确认记录消失只说明外部变化,本页不能丢掉内存内容,先冻结并提示导出/重新打开。 */
|
||||||
const storage=(event:StorageEvent)=>{
|
const storage=(event:StorageEvent)=>{
|
||||||
if(event.key!==key&&event.key!==null||!current()||attempt.current)return;
|
if(event.key!==key&&event.key!==null||!current()||attempt.current)return;
|
||||||
// Never discard another view's in-memory content because a record vanished.
|
// Never discard another view's in-memory content because a record vanished.
|
||||||
@@ -56,10 +77,13 @@ export function LegacyCanvasMigration(props:Props){
|
|||||||
void inspect();
|
void inspect();
|
||||||
};
|
};
|
||||||
window.addEventListener('storage',storage);
|
window.addEventListener('storage',storage);
|
||||||
|
// 卸载取消检查、拆storage监听并释放本页共享锁,不删除尚待确认的迁移记录。
|
||||||
return()=>{controller.abort();window.removeEventListener('storage',storage);const held=lease.current;lease.current=undefined;void held?.release();};
|
return()=>{controller.abort();window.removeEventListener('storage',storage);const held=lease.current;lease.current=undefined;void held?.release();};
|
||||||
// The port ref follows renders without re-acquiring a shared editing lease.
|
// The port ref follows renders without re-acquiring a shared editing lease.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
},[key,props.canvasId]);
|
},[key,props.canvasId]);
|
||||||
|
/** 新尝试先check并hold,在共享锁仍持有时prepare;释放共享锁后由迁移器申请独占锁。
|
||||||
|
* pending复用原记录resume,其它情况按rootId重新准备,不能把每次点击都变成新的迁移请求。 */
|
||||||
async function upgrade(){
|
async function upgrade(){
|
||||||
const controller=life.current;if(!controller||controller.signal.aborted||attempt.current)return;
|
const controller=life.current;if(!controller||controller.signal.aborted||attempt.current)return;
|
||||||
attempt.current=true;setRunning(true);setError('');
|
attempt.current=true;setRunning(true);setError('');
|
||||||
@@ -67,6 +91,7 @@ export function LegacyCanvasMigration(props:Props){
|
|||||||
let failure='';
|
let failure='';
|
||||||
try{
|
try{
|
||||||
const pending=readCanvasMigration(localStorage,scope);
|
const pending=readCanvasMigration(localStorage,scope);
|
||||||
|
// 工作区已有另一根pending时禁止挤占;同一根结果未知则继续原请求查询,不重复做初始准备。
|
||||||
if(pending?.phase==='pending'&&!migrationBlocksCanvas(pending,props.canvasId))throw new Error('workspace_migration_pending');
|
if(pending?.phase==='pending'&&!migrationBlocksCanvas(pending,props.canvasId))throw new Error('workspace_migration_pending');
|
||||||
if(pending?.phase!=='pending')port.current.check();
|
if(pending?.phase!=='pending')port.current.check();
|
||||||
port.current.hold(true);
|
port.current.hold(true);
|
||||||
@@ -75,14 +100,17 @@ export function LegacyCanvasMigration(props:Props){
|
|||||||
if(pending?.phase!=='pending'&&props.context.rootId){await port.current.prepare(props.context.rootId);if(!current())return;}
|
if(pending?.phase!=='pending'&&props.context.rootId){await port.current.prepare(props.context.rootId);if(!current())return;}
|
||||||
const held=lease.current;lease.current=undefined;await held?.release();if(!current())return;
|
const held=lease.current;lease.current=undefined;await held?.release();if(!current())return;
|
||||||
const migration=createBrowserCanvasMigration({scope,registry:props.registry,signal:controller.signal,isCurrentIdentity:current});
|
const migration=createBrowserCanvasMigration({scope,registry:props.registry,signal:controller.signal,isCurrentIdentity:current});
|
||||||
|
// start独占阶段再次check/prepare/check,覆盖共享锁释放到独占锁取得之间可能出现的旧写入。
|
||||||
const result=pending?.phase==='pending'?await migration.resume():props.context.rootId?await migration.start(props.context.rootId,async()=>{port.current.check();await port.current.prepare(props.context.rootId!);port.current.check();}):undefined;
|
const result=pending?.phase==='pending'?await migration.resume():props.context.rootId?await migration.start(props.context.rootId,async()=>{port.current.check();await port.current.prepare(props.context.rootId!);port.current.check();}):undefined;
|
||||||
if(!current())return;
|
if(!current())return;
|
||||||
|
// 只有确认applied或已迁移才通知外层重开;拒绝/未知保留记录,交finally重新决定是否能恢复旧编辑。
|
||||||
if(result?.status==='applied'||result?.status==='already-migrated'){
|
if(result?.status==='applied'||result?.status==='already-migrated'){
|
||||||
finished.current=true;port.current.context.onApplied();return;
|
finished.current=true;port.current.context.onApplied();return;
|
||||||
}
|
}
|
||||||
if(result&&'error'in result){failure=message(result.error);setError(failure);}
|
if(result&&'error'in result){failure=message(result.error);setError(failure);}
|
||||||
const next=migration.read();previous.current=next;setJob(next);
|
const next=migration.read();previous.current=next;setJob(next);
|
||||||
}catch(error){if(current()){failure=message(error);setError(failure);}}
|
}catch(error){if(current()){failure=message(error);setError(failure);}}
|
||||||
|
// 不论尝试结果都清重入标记;仅当前身份有效才更新UI,并从持久记录重新判断是否仍需hold。
|
||||||
finally{
|
finally{
|
||||||
attempt.current=false;
|
attempt.current=false;
|
||||||
if(current()){
|
if(current()){
|
||||||
@@ -92,8 +120,11 @@ export function LegacyCanvasMigration(props:Props){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// pending表示本页在迁移范围内;other表示工作区另一画布待确认,按钮禁用但不篡改其任务。
|
||||||
const pending=migrationBlocksCanvas(job,props.canvasId),other=job?.phase==='pending'&&!pending;
|
const pending=migrationBlocksCanvas(job,props.canvasId),other=job?.phase==='pending'&&!pending;
|
||||||
if(!props.context.rootId&&!pending&&!error&&!props.held)return null;
|
if(!props.context.rootId&&!pending&&!error&&!props.held)return null;
|
||||||
|
// 入口依次呈现检查中/执行中/外部变更重开/开始或继续迁移;旧撤销记录不迁移,提示写在按钮title。
|
||||||
|
// 本页被hold时提供备份;外部变化后的重开仍须check及canLeave,不能直接丢弃尚未同步的内存内容。
|
||||||
return <div className={styles.migrationPanel} aria-label="画布升级">
|
return <div className={styles.migrationPanel} aria-label="画布升级">
|
||||||
{checking?<span role="status">正在检查画布编辑权限…</span>:<>
|
{checking?<span role="status">正在检查画布编辑权限…</span>:<>
|
||||||
{running?<span role="status">正在保存并升级画布…</span>:changedElsewhere?<button onClick={()=>{try{port.current.check();if(!port.current.canLeave())throw new Error('本页有未同步内容,请先导出备份并手动重新打开画布。');port.current.context.onApplied();}catch(error){setError(message(error));}}}>重新打开画布</button>:props.context.rootId||pending?<button disabled={other} title="保存内容并使用新版编辑器;旧撤销记录不会带入" onClick={()=>void upgrade()}>{pending?'继续查询升级':job?.phase==='rejected'?'重新准备升级':'升级画布'}</button>:props.held?<button onClick={()=>void refresh.current()}>重新检查</button>:null}
|
{running?<span role="status">正在保存并升级画布…</span>:changedElsewhere?<button onClick={()=>{try{port.current.check();if(!port.current.canLeave())throw new Error('本页有未同步内容,请先导出备份并手动重新打开画布。');port.current.context.onApplied();}catch(error){setError(message(error));}}}>重新打开画布</button>:props.context.rootId||pending?<button disabled={other} title="保存内容并使用新版编辑器;旧撤销记录不会带入" onClick={()=>void upgrade()}>{pending?'继续查询升级':job?.phase==='rejected'?'重新准备升级':'升级画布'}</button>:props.held?<button onClick={()=>void refresh.current()}>重新检查</button>:null}
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* 模型读取前缀的只读预览。直接把已校验document投影给ReactFlow,允许浏览视口,不创建可写engine或临时history/ledger。
|
||||||
|
* 这个组件不负责持久化前缀;后续可编辑partial engine的建立与交接由路由及runtime处理。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {useEffect,useMemo,useRef} from 'react';
|
import {useEffect,useMemo,useRef} from 'react';
|
||||||
@@ -11,26 +15,36 @@ import {CanvasRendererCommandsContext,type CanvasRendererCommands} from '@/lib/c
|
|||||||
import {UnsupportedNode,UnsupportedEdge} from './unsupported-elements';
|
import {UnsupportedNode,UnsupportedEdge} from './unsupported-elements';
|
||||||
import styles from './canvas.module.css';
|
import styles from './canvas.module.css';
|
||||||
|
|
||||||
|
/** 已知类型缺少专用preview renderer时展示准备占位;保留已投影连线需要的Handle,禁止新连接。 */
|
||||||
function PreparingNode({data}:NodeProps){return <div style={{width:'100%',height:'100%',padding:14,border:'1px solid #ded7ce',borderRadius:8,background:'#fffdfa'}} aria-label="正在准备元素"><span>{typeof data.title==='string'?data.title:'正在准备元素…'}</span>{(data.__previewHandles as {id?:string;type:'source'|'target'}[]??[]).map((handle,index)=><Handle key={index} type={handle.type} id={handle.id} position={handle.type==='source'?Position.Right:Position.Left} isConnectable={false}/>)}</div>;}
|
function PreparingNode({data}:NodeProps){return <div style={{width:'100%',height:'100%',padding:14,border:'1px solid #ded7ce',borderRadius:8,background:'#fffdfa'}} aria-label="正在准备元素"><span>{typeof data.title==='string'?data.title:'正在准备元素…'}</span>{(data.__previewHandles as {id?:string;type:'source'|'target'}[]??[]).map((handle,index)=><Handle key={index} type={handle.type} id={handle.id} position={handle.type==='source'?Position.Right:Position.Left} isConnectable={false}/>)}</div>;}
|
||||||
|
/** 所有预览命令统一拒绝为model_loading,避免复用的renderer意外修改数据。 */
|
||||||
const reject=()=>({status:'rejected' as const,code:'model_loading',targets:[]});
|
const reject=()=>({status:'rejected' as const,code:'model_loading',targets:[]});
|
||||||
|
/** 冻结命令接口仅提供拒绝结果;inert与ReactFlow只读设置之外,命令层再提供一道限制。 */
|
||||||
const commands:CanvasRendererCommands=Object.freeze({dispatch:reject,transaction:reject});
|
const commands:CanvasRendererCommands=Object.freeze({dispatch:reject,transaction:reject});
|
||||||
|
/** 首次存在节点且视口初始化后fitView一次,限制最大缩放为1,并把结果交给外层用于视图交接。 */
|
||||||
function InitialPreviewViewport({onViewport,nodeCount}:{onViewport(viewport:Viewport):void;nodeCount:number}){
|
function InitialPreviewViewport({onViewport,nodeCount}:{onViewport(viewport:Viewport):void;nodeCount:number}){
|
||||||
|
// fitted是本组件挂载期标记;清理只禁止迟到通知,不取消已经发起的fitView,也不重置fitted。
|
||||||
const flow=useReactFlow(),fitted=useRef(false),notify=useRef(onViewport);notify.current=onViewport;
|
const flow=useReactFlow(),fitted=useRef(false),notify=useRef(onViewport);notify.current=onViewport;
|
||||||
useEffect(()=>{if(!flow.viewportInitialized||fitted.current||!nodeCount)return;fitted.current=true;let active=true;void flow.fitView({padding:.2,maxZoom:1}).then(()=>{if(active)notify.current(flow.getViewport());});return()=>{active=false;};},[flow,nodeCount]);
|
useEffect(()=>{if(!flow.viewportInitialized||fitted.current||!nodeCount)return;fitted.current=true;let active=true;void flow.fitView({padding:.2,maxZoom:1}).then(()=>{if(active)notify.current(flow.getViewport());});return()=>{active=false;};},[flow,nodeCount]);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
/** Render the validated read prefix directly. No temporary editor, ACK, ledger or
|
/** Render the validated read prefix directly. No temporary editor, ACK, ledger or
|
||||||
* writable engine is constructed, and no partial model enters durable storage. */
|
* writable engine is constructed, and no partial model enters durable storage. */
|
||||||
|
/** renderer catalog限制加载期可用渲染路径;无法解释引用关系时沿用opaque占位,不能猜测缺失内容。 */
|
||||||
export default function LoadingGraphCanvas({preview,canvasId,registry,renderers,workspaceId,onViewport}: {preview:ModelPreview;canvasId:string;workspaceId:string;registry:Registry;renderers:ReactRenderers;onViewport(viewport:Viewport):void}){
|
export default function LoadingGraphCanvas({preview,canvasId,registry,renderers,workspaceId,onViewport}: {preview:ModelPreview;canvasId:string;workspaceId:string;registry:Registry;renderers:ReactRenderers;onViewport(viewport:Viewport):void}){
|
||||||
// Without a declared reference schema, use the existing opaque placeholder
|
// Without a declared reference schema, use the existing opaque placeholder
|
||||||
// until the complete document is available to the installed renderer.
|
// until the complete document is available to the installed renderer.
|
||||||
const catalog=useMemo(()=>createLoadingRendererCatalog(registry,renderers.catalog),[registry,renderers]);
|
const catalog=useMemo(()=>createLoadingRendererCatalog(registry,renderers.catalog),[registry,renderers]);
|
||||||
|
// 对已收到文档做只读投影;从现有边补齐各节点Handle描述,不推断尚未读取到的连线。
|
||||||
const projection=useMemo(()=>{
|
const projection=useMemo(()=>{
|
||||||
const value=projectCanvas(preview.document,canvasId,registry,new Set(),()=>undefined,undefined,catalog);
|
const value=projectCanvas(preview.document,canvasId,registry,new Set(),()=>undefined,undefined,catalog);
|
||||||
const handles=new Map<string,{id?:string;type:'source'|'target'}[]>();for(const edge of value.edges)for(const type of ['source','target'] as const){const id=edge[type],rows=handles.get(id)??[];rows.push({type,id:edge[type==='source'?'sourceHandle':'targetHandle']??undefined});handles.set(id,rows);}
|
const handles=new Map<string,{id?:string;type:'source'|'target'}[]>();for(const edge of value.edges)for(const type of ['source','target'] as const){const id=edge[type],rows=handles.get(id)??[];rows.push({type,id:edge[type==='source'?'sourceHandle':'targetHandle']??undefined});handles.set(id,rows);}
|
||||||
|
// 节点禁用拖动/选择/焦点/连接及指针,边禁用选择/焦点;已知组件声明assetId资源字段才设置预览URL。
|
||||||
return{nodes:value.nodes.map(node=>({...node,draggable:false,selectable:false,focusable:false,connectable:false,style:{...node.style,pointerEvents:'none' as const},data:{...node.data,__previewHandles:handles.get(node.id)??[],...(registry.resolve(preview.document.elements.get(node.id)!)==='known'&&typeof node.data.assetId==='string'&®istry.components.get(preview.document.elements.get(node.id)!.componentId)?.resourceFields?.includes('assetId')?{src:`/api/foundry/workspaces/${encodeURIComponent(workspaceId)}/assets/${encodeURIComponent(node.data.assetId)}?variant=preview`}:{})}})),edges:value.edges.map(edge=>({...edge,selectable:false,focusable:false}))};
|
return{nodes:value.nodes.map(node=>({...node,draggable:false,selectable:false,focusable:false,connectable:false,style:{...node.style,pointerEvents:'none' as const},data:{...node.data,__previewHandles:handles.get(node.id)??[],...(registry.resolve(preview.document.elements.get(node.id)!)==='known'&&typeof node.data.assetId==='string'&®istry.components.get(preview.document.elements.get(node.id)!.componentId)?.resourceFields?.includes('assetId')?{src:`/api/foundry/workspaces/${encodeURIComponent(workspaceId)}/assets/${encodeURIComponent(node.data.assetId)}?variant=preview`}:{})}})),edges:value.edges.map(edge=>({...edge,selectable:false,focusable:false}))};
|
||||||
},[preview.document,canvasId,workspaceId,registry,catalog]);
|
},[preview.document,canvasId,workspaceId,registry,catalog]);
|
||||||
|
// 普通rendererId优先使用专用preview,否则节点PreparingNode、边UnsupportedEdge;节点再套inert隔离内部控件。
|
||||||
const nodeTypes=useMemo<NodeTypes>(()=>{const result:NodeTypes={};for(const [id,Renderer]of Object.entries({...Object.fromEntries(Object.keys(renderers.nodeTypes).map(id=>[id,renderers.previewNodeTypes[id]??PreparingNode])),unsupported:UnsupportedNode}))result[id]=props=><div inert style={{width:'100%',height:'100%'}}><Renderer {...props}/></div>;return result;},[renderers]),edgeTypes=useMemo(()=>({...Object.fromEntries(Object.keys(renderers.edgeTypes).map(id=>[id,renderers.previewEdgeTypes[id]??UnsupportedEdge])),unsupported:UnsupportedEdge}),[renderers]);
|
const nodeTypes=useMemo<NodeTypes>(()=>{const result:NodeTypes={};for(const [id,Renderer]of Object.entries({...Object.fromEntries(Object.keys(renderers.nodeTypes).map(id=>[id,renderers.previewNodeTypes[id]??PreparingNode])),unsupported:UnsupportedNode}))result[id]=props=><div inert style={{width:'100%',height:'100%'}}><Renderer {...props}/></div>;return result;},[renderers]),edgeTypes=useMemo(()=>({...Object.fromEntries(Object.keys(renderers.edgeTypes).map(id=>[id,renderers.previewEdgeTypes[id]??UnsupportedEdge])),unsupported:UnsupportedEdge}),[renderers]);
|
||||||
|
// 仍允许拖动或滚动平移,关闭滚轮缩放和Delete删除;onMoveEnd记录视口,进度只显示读取数量。
|
||||||
return <div className={styles.editor} data-canvas-loading-preview aria-label="正在加载的画布,只读预览">
|
return <div className={styles.editor} data-canvas-loading-preview aria-label="正在加载的画布,只读预览">
|
||||||
<CanvasRendererCommandsContext.Provider value={commands}>
|
<CanvasRendererCommandsContext.Provider value={commands}>
|
||||||
<ReactFlow nodes={projection.nodes} edges={projection.edges} nodeTypes={nodeTypes} edgeTypes={edgeTypes} nodesDraggable={false} nodesConnectable={false} elementsSelectable={false} nodesFocusable={false} edgesFocusable={false} panOnDrag panOnScroll zoomOnScroll={false} minZoom={.1} maxZoom={4} deleteKeyCode={null} onMoveEnd={(_,viewport)=>onViewport(viewport)}>
|
<ReactFlow nodes={projection.nodes} edges={projection.edges} nodeTypes={nodeTypes} edgeTypes={edgeTypes} nodesDraggable={false} nodesConnectable={false} elementsSelectable={false} nodesFocusable={false} edgesFocusable={false} panOnDrag panOnScroll zoomOnScroll={false} minZoom={.1} maxZoom={4} deleteKeyCode={null} onMoveEnd={(_,viewport)=>onViewport(viewport)}>
|
||||||
|
|||||||
@@ -1,15 +1,25 @@
|
|||||||
|
/**
|
||||||
|
* ReactFlow适配层的保留标记缓存。为需要保留的节点/边复制一份带__endoleapRetain的投影记录,原对象不变。
|
||||||
|
* 标记供应用固定版本的编译扩展使用,不是模型属性,也不应进入history、存储或业务renderer数据。
|
||||||
|
*/
|
||||||
/** Adapter-only flags consumed by the app's pinned React Flow compiler extension.
|
/** Adapter-only flags consumed by the app's pinned React Flow compiler extension.
|
||||||
* They never enter the document, history, persistence or renderer business data. */
|
* They never enter the document, history, persistence or renderer business data. */
|
||||||
|
/** 每个投影使用者创建一份缓存:WeakMap复用同一原对象的带标记副本,previous复用最近一次整个输出。 */
|
||||||
export function createRetainedProjection(){
|
export function createRetainedProjection(){
|
||||||
|
// 弱引用键避免缓存永久占住已被替换的投影对象;只按对象身份缓存,不监测对象内部原地修改。
|
||||||
const tagged=new WeakMap<object,object>();
|
const tagged=new WeakMap<object,object>();
|
||||||
let previous:{nodes:readonly object[];edges:readonly object[];ids:Set<string>;result:{nodes:object[];edges:object[]}}|undefined;
|
let previous:{nodes:readonly object[];edges:readonly object[];ids:Set<string>;result:{nodes:object[];edges:object[]}}|undefined;
|
||||||
|
/** 输入数组和保留ID集合生成节点/边数组;ids为空时直接返回原数组并清除整批缓存。 */
|
||||||
return <N extends {id:string},E extends {id:string}>(nodes:N[],edges:E[],ids:ReadonlySet<string>):{nodes:N[];edges:E[]}=>{
|
return <N extends {id:string},E extends {id:string}>(nodes:N[],edges:E[],ids:ReadonlySet<string>):{nodes:N[];edges:E[]}=>{
|
||||||
if(!ids.size){previous=undefined;return{nodes,edges};}
|
if(!ids.size){previous=undefined;return{nodes,edges};}
|
||||||
|
// 数组引用及ID成员都相同才复用;快照复制ids,避免调用方之后原地修改Set影响比较基准。
|
||||||
if(previous?.nodes===nodes&&previous.edges===edges&&previous.ids.size===ids.size&&[...ids].every(id=>previous!.ids.has(id)))return previous.result as {nodes:N[];edges:E[]};
|
if(previous?.nodes===nodes&&previous.edges===edges&&previous.ids.size===ids.size&&[...ids].every(id=>previous!.ids.has(id)))return previous.result as {nodes:N[];edges:E[]};
|
||||||
|
/** 未命中的记录保留原引用;命中时浅复制顶层加标记,嵌套数据仍与原投影共享。 */
|
||||||
const retain=<T extends {id:string}>(row:T):T=>{
|
const retain=<T extends {id:string}>(row:T):T=>{
|
||||||
if(!ids.has(row.id))return row;
|
if(!ids.has(row.id))return row;
|
||||||
let value=tagged.get(row);if(!value){value={...row,__endoleapRetain:true};tagged.set(row,value);}return value as T;
|
let value=tagged.get(row);if(!value){value={...row,__endoleapRetain:true};tagged.set(row,value);}return value as T;
|
||||||
};
|
};
|
||||||
|
// 非空集合下会映射两张数组,即使没有命中也生成数组;下一次相同输入再复用该result。
|
||||||
const result={nodes:nodes.map(retain),edges:edges.map(retain)};
|
const result={nodes:nodes.map(retain),edges:edges.map(retain)};
|
||||||
previous={nodes,edges,ids:new Set(ids),result};return result;
|
previous={nodes,edges,ids:new Set(ids),result};return result;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* 旧画布树的AI任务跟踪Hook。发现根及后代画布的活动任务,按事件游标增量读取,协调结果刷新与本地冲突显示。
|
||||||
|
* 此路径使用内存Map/Set和定时轮询,不具备新版runtime ledger的持久请求恢复;卸载会停止本Hook跟踪。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { api } from "@/lib/api";
|
import { api } from "@/lib/api";
|
||||||
import { CANVAS_ACCEPT } from "@/lib/canvas-v2";
|
import { CANVAS_ACCEPT } from "@/lib/canvas-v2";
|
||||||
import { canvasPath } from "@/lib/canvas-sync";
|
import { canvasPath } from "@/lib/canvas-sync";
|
||||||
import type { useCanvasTree } from "./use-canvas-tree";
|
import type { useCanvasTree } from "./use-canvas-tree";
|
||||||
|
/** 服务端模型目录条目:输入/输出模态、可用性与可选参数schema;本Hook只传递模型选择。 */
|
||||||
export type CanvasModel = { id: string; label?: string; display_name?: string; output_modalities: string[]; input_modalities: string[]; available: boolean; unavailable_reason?: string; parameters_schema?: unknown };
|
export type CanvasModel = { id: string; label?: string; display_name?: string; output_modalities: string[]; input_modalities: string[]; available: boolean; unavailable_reason?: string; parameters_schema?: unknown };
|
||||||
|
/** 旧AI接口的任务分页结果;next_seq/has_more跟踪事件页,steps/outputs/events供面板和活动连线显示。 */
|
||||||
export type AIRun = {
|
export type AIRun = {
|
||||||
run_id: string; board_id: string; status: string; next_seq: number; has_more?: boolean; error?: string;
|
run_id: string; board_id: string; status: string; next_seq: number; has_more?: boolean; error?: string;
|
||||||
steps?: { step_id: string; board_id: string; node_id: string; status: string; error?: string }[];
|
steps?: { step_id: string; board_id: string; node_id: string; status: string; error?: string }[];
|
||||||
@@ -12,7 +18,9 @@ export type AIRun = {
|
|||||||
events?: { seq: number; type: string; board_id?: string; node_id?: string; logical_edge_id?: string; canvas_version?: number; output?: { output_id: string; text?: string; src?: string } }[];
|
events?: { seq: number; type: string; board_id?: string; node_id?: string; logical_edge_id?: string; canvas_version?: number; output?: { output_id: string; text?: string; src?: string } }[];
|
||||||
applied_versions?: Record<string, number>;
|
applied_versions?: Record<string, number>;
|
||||||
};
|
};
|
||||||
|
/** 只有queued/running视为执行中;终态任务仍可能因has_more继续拉取剩余事件。 */
|
||||||
const active = (status: string) => status === "queued" || status === "running";
|
const active = (status: string) => status === "queued" || status === "running";
|
||||||
|
/** enabled仅控制画布AI模式显示;live才启用服务请求。tree通过ref保持最新,轮询effect按作用域重建。 */
|
||||||
export function useCanvasAI(workspace: string, root: string, live: boolean, tree: ReturnType<typeof useCanvasTree>) {
|
export function useCanvasAI(workspace: string, root: string, live: boolean, tree: ReturnType<typeof useCanvasTree>) {
|
||||||
const [enabled, setEnabled] = useState(false);
|
const [enabled, setEnabled] = useState(false);
|
||||||
const [runs, setRuns] = useState(new Map<string, AIRun>());
|
const [runs, setRuns] = useState(new Map<string, AIRun>());
|
||||||
@@ -21,16 +29,22 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
|
|||||||
const [activeEdges, setActiveEdges] = useState(new Set<string>());
|
const [activeEdges, setActiveEdges] = useState(new Set<string>());
|
||||||
const reference = useRef(tree); reference.current = tree;
|
const reference = useRef(tree); reference.current = tree;
|
||||||
const wake = useRef<() => void>(() => {});
|
const wake = useRef<() => void>(() => {});
|
||||||
|
// cache是跟踪结果缓存,runs是发布给React的副本;每个run有自己的活动边集合,合并后供连线动画使用。
|
||||||
const cache = useRef(new Map<string, AIRun>());
|
const cache = useRef(new Map<string, AIRun>());
|
||||||
const edgeStates = useRef(new Map<string, Set<string>>());
|
const edgeStates = useRef(new Map<string, Set<string>>());
|
||||||
|
// 每个board只保留最高待刷版本,避免同一批step.applied触发多次重复整画布读取。
|
||||||
const pendingRefresh = useRef(new Map<string, number>());
|
const pendingRefresh = useRef(new Map<string, number>());
|
||||||
|
/** 发布新的Map/Set引用触发React更新;不把可变ref集合原样暴露成受控state。 */
|
||||||
const changed = () => { setRuns(new Map(cache.current)); setActiveEdges(new Set([...edgeStates.current.values()].flatMap((values) => [...values]))); };
|
const changed = () => { setRuns(new Map(cache.current)); setActiveEdges(new Set([...edgeStates.current.values()].flatMap((values) => [...values]))); };
|
||||||
|
// 单个effect内polling防并发轮询,dirty合并UI发布;AbortController统一中止这次作用域的读取。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!live) return;
|
if (!live) return;
|
||||||
let alive = true, timer: ReturnType<typeof setTimeout> | undefined;
|
let alive = true, timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
let polling = false, dirty = false, nextDiscovery = 0;
|
let polling = false, dirty = false, nextDiscovery = 0;
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
|
/** 所有发现/分页GET共享取消信号并协商旧v2响应格式。 */
|
||||||
const request = <T,>(path: string) => api<T>(path, { signal: controller.signal, headers: { Accept: CANVAS_ACCEPT } });
|
const request = <T,>(path: string) => api<T>(path, { signal: controller.signal, headers: { Accept: CANVAS_ACCEPT } });
|
||||||
|
/** 分页发现根和后代活动run,每页50;已跟踪run不覆盖,重复cursor判为协议异常避免无限循环。 */
|
||||||
async function discover() {
|
async function discover() {
|
||||||
let cursor = ""; const seen = new Set<string>();
|
let cursor = ""; const seen = new Set<string>();
|
||||||
do {
|
do {
|
||||||
@@ -39,7 +53,9 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
|
|||||||
cursor = page.next_cursor || ""; if (seen.has(cursor)) throw new Error("invalid_run_cursor"); seen.add(cursor);
|
cursor = page.next_cursor || ""; if (seen.has(cursor)) throw new Error("invalid_run_cursor"); seen.add(cursor);
|
||||||
} while (cursor && alive);
|
} while (cursor && alive);
|
||||||
}
|
}
|
||||||
|
/** 是否仍需较快跟踪,包含终态但事件尚未读完的任务。 */
|
||||||
const hasActive = () => [...cache.current.values()].some((run) => active(run.status) || run.has_more);
|
const hasActive = () => [...cache.current.values()].some((run) => active(run.status) || run.has_more);
|
||||||
|
/** 隐藏页面延后30秒;可见时串行发现、读事件、刷新已应用画布,再按活跃程度安排下一次。 */
|
||||||
async function poll() {
|
async function poll() {
|
||||||
if (!alive || polling) return;
|
if (!alive || polling) return;
|
||||||
if (document.visibilityState === "hidden") { timer = setTimeout(poll, 30000); return; }
|
if (document.visibilityState === "hidden") { timer = setTimeout(poll, 30000); return; }
|
||||||
@@ -49,9 +65,11 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
|
|||||||
for (const [id, previous] of cache.current) {
|
for (const [id, previous] of cache.current) {
|
||||||
if (!active(previous.status) && !previous.has_more) continue;
|
if (!active(previous.status) && !previous.has_more) continue;
|
||||||
let current = previous;
|
let current = previous;
|
||||||
|
// 每页100事件,游标必须安全且不倒退,has_more时必须前进;每run最多保留最近1000条事件。
|
||||||
do {
|
do {
|
||||||
const page = await request<Omit<AIRun, "board_id">>(canvasPath(workspace, previous.board_id) + `/ai/runs/${id}?after_seq=${current.next_seq}&limit=100`);
|
const page = await request<Omit<AIRun, "board_id">>(canvasPath(workspace, previous.board_id) + `/ai/runs/${id}?after_seq=${current.next_seq}&limit=100`);
|
||||||
if (!Number.isSafeInteger(page.next_seq) || page.next_seq < current.next_seq || page.has_more && page.next_seq === current.next_seq) throw new Error("invalid_run_cursor");
|
if (!Number.isSafeInteger(page.next_seq) || page.next_seq < current.next_seq || page.has_more && page.next_seq === current.next_seq) throw new Error("invalid_run_cursor");
|
||||||
|
// edge.active加入动画集合,completed/failed/skipped移除;任务终态清空剩余活动边。
|
||||||
const edges = edgeStates.current.get(id) || new Set<string>();
|
const edges = edgeStates.current.get(id) || new Set<string>();
|
||||||
for (const event of page.events || []) {
|
for (const event of page.events || []) {
|
||||||
if (event.logical_edge_id) { if (event.type === "edge.active") edges.add(event.logical_edge_id); else if (["edge.completed", "edge.failed", "edge.skipped"].includes(event.type)) edges.delete(event.logical_edge_id); }
|
if (event.logical_edge_id) { if (event.type === "edge.active") edges.add(event.logical_edge_id); else if (["edge.completed", "edge.failed", "edge.skipped"].includes(event.type)) edges.delete(event.logical_edge_id); }
|
||||||
@@ -63,6 +81,7 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
|
|||||||
cache.current.set(id, current);
|
cache.current.set(id, current);
|
||||||
} while (current.has_more && alive);
|
} while (current.has_more && alive);
|
||||||
}
|
}
|
||||||
|
// 等树不忙且不在本地事务中才刷新;版本冲突记录到conflicts,不直接用生成快照覆盖本地草稿。
|
||||||
for (const [board, version] of pendingRefresh.current) {
|
for (const [board, version] of pendingRefresh.current) {
|
||||||
if (reference.current.busy || reference.current.transactionBusy) break;
|
if (reference.current.busy || reference.current.transactionBusy) break;
|
||||||
const writer = reference.current.writers.current.get(board);
|
const writer = reference.current.writers.current.get(board);
|
||||||
@@ -79,27 +98,34 @@ export function useCanvasAI(workspace: string, root: string, live: boolean, tree
|
|||||||
polling = false;
|
polling = false;
|
||||||
if (alive) timer = setTimeout(poll, hasActive() || pendingRefresh.current.size ? 1200 : 30000);
|
if (alive) timer = setTimeout(poll, hasActive() || pendingRefresh.current.size ? 1200 : 30000);
|
||||||
}
|
}
|
||||||
|
/** 被唤醒时清计时器并强制下一次重新发现;已有poll运行时由其收尾继续调度。 */
|
||||||
const resume = () => { if (timer) clearTimeout(timer); nextDiscovery = 0; void poll(); };
|
const resume = () => { if (timer) clearTimeout(timer); nextDiscovery = 0; void poll(); };
|
||||||
wake.current = resume;
|
wake.current = resume;
|
||||||
|
/** 页面重新可见时立即唤醒,避免继续等待后台长间隔。 */
|
||||||
const visible = () => { if (document.visibilityState === "visible") resume(); };
|
const visible = () => { if (document.visibilityState === "visible") resume(); };
|
||||||
document.addEventListener("visibilitychange", visible);
|
document.addEventListener("visibilitychange", visible);
|
||||||
void poll();
|
void poll();
|
||||||
|
// effect清理中止GET、定时器和可见性监听,wake退为空实现;此处不清除缓存或自动取消服务端任务。
|
||||||
return () => { alive = false; wake.current = () => {}; controller.abort(); if (timer) clearTimeout(timer); document.removeEventListener("visibilitychange", visible); };
|
return () => { alive = false; wake.current = () => {}; controller.abort(); if (timer) clearTimeout(timer); document.removeEventListener("visibilitychange", visible); };
|
||||||
}, [workspace, root, live]);
|
}, [workspace, root, live]);
|
||||||
|
/** 真实画布经tree.command启动任务,先插queued占位供UI显示,再唤醒跟踪;演示模式明确拒绝。 */
|
||||||
async function run(boardId: string, node: string, model: string, prompt: string, propagate: boolean) {
|
async function run(boardId: string, node: string, model: string, prompt: string, propagate: boolean) {
|
||||||
if (!live) throw new Error("demo_ai_unavailable");
|
if (!live) throw new Error("demo_ai_unavailable");
|
||||||
const result = await reference.current.command(boardId, "ai/runs", { node_id: node, model_id: model, prompt, parameters: {}, propagate }, undefined, false);
|
const result = await reference.current.command(boardId, "ai/runs", { node_id: node, model_id: model, prompt, parameters: {}, propagate }, undefined, false);
|
||||||
const id = result.run_id as string; cache.current.set(id, { run_id: id, board_id: boardId, status: "queued", next_seq: 0, steps: [{ step_id: "pending", board_id: boardId, node_id: node, status: "queued" }] }); changed(); wake.current();
|
const id = result.run_id as string; cache.current.set(id, { run_id: id, board_id: boardId, status: "queued", next_seq: 0, steps: [{ step_id: "pending", board_id: boardId, node_id: node, status: "queued" }] }); changed(); wake.current();
|
||||||
}
|
}
|
||||||
|
/** 以新幂等键发送取消命令后继续查询终态;暂记queued用于保持轮询,不表示服务端重新执行任务。 */
|
||||||
async function cancel(run: AIRun) {
|
async function cancel(run: AIRun) {
|
||||||
await api(canvasPath(workspace, run.board_id) + `/ai/runs/${run.run_id}/cancel`, { method: "POST", headers: { Accept: CANVAS_ACCEPT, "Idempotency-Key": crypto.randomUUID() }, body: "{}" });
|
await api(canvasPath(workspace, run.board_id) + `/ai/runs/${run.run_id}/cancel`, { method: "POST", headers: { Accept: CANVAS_ACCEPT, "Idempotency-Key": crypto.randomUUID() }, body: "{}" });
|
||||||
const next = cache.current.get(run.run_id); if (next) { next.status = "queued"; } wake.current(); // Poll canonical terminal state, including already applied steps.
|
const next = cache.current.get(run.run_id); if (next) { next.status = "queued"; } wake.current(); // Poll canonical terminal state, including already applied steps.
|
||||||
}
|
}
|
||||||
|
/** 先prepareApply协调目标本地状态,再发显式采用命令;成功后移除冲突提示并继续跟踪服务端最终状态。 */
|
||||||
async function apply(run: AIRun, node: string, output: string, targetBoard: string) {
|
async function apply(run: AIRun, node: string, output: string, targetBoard: string) {
|
||||||
await reference.current.prepareApply(targetBoard, node);
|
await reference.current.prepareApply(targetBoard, node);
|
||||||
await reference.current.command(run.board_id, `ai/runs/${run.run_id}/apply`, { node_id: node, output_id: output }, undefined, false, targetBoard);
|
await reference.current.command(run.board_id, `ai/runs/${run.run_id}/apply`, { node_id: node, output_id: output }, undefined, false, targetBoard);
|
||||||
setConflicts((current) => { const next = new Set(current); next.delete(targetBoard); return next; });
|
setConflicts((current) => { const next = new Set(current); next.delete(targetBoard); return next; });
|
||||||
const previous = cache.current.get(run.run_id); if (previous) { previous.status = "queued"; changed(); } wake.current();
|
const previous = cache.current.get(run.run_id); if (previous) { previous.status = "queued"; changed(); } wake.current();
|
||||||
}
|
}
|
||||||
|
// 对外只暴露显示状态和三个动作;调用者不直接修改cache、分页游标或刷新等待表。
|
||||||
return { enabled, setEnabled, runs, conflicts, activeEdges, error, run, cancel, apply, live };
|
return { enabled, setEnabled, runs, conflicts, activeEdges, error, run, cancel, apply, live };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,26 @@
|
|||||||
|
/**
|
||||||
|
* 旧版单画布的自动保存Hook:短延迟备份本地草稿,较长延迟把最新快照交给CanvasSync。
|
||||||
|
* 它使用旧快照writer,不是新版冻结请求ledger;本地recovery记录也不是可靠保存文件字节的资源仓库。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { api } from "@/lib/api";
|
import { api } from "@/lib/api";
|
||||||
import { canvasFingerprint, canvasPath, CanvasSync, type CanvasSnapshot, type SyncState } from "@/lib/canvas-sync";
|
import { canvasFingerprint, canvasPath, CanvasSync, type CanvasSnapshot, type SyncState } from "@/lib/canvas-sync";
|
||||||
import { decodeCanvas, type CanvasDocument } from "@/lib/canvas";
|
import { decodeCanvas, type CanvasDocument } from "@/lib/canvas";
|
||||||
|
|
||||||
|
/** snapshot存在才建立远端writer,无snapshot仍可本地备份;writer在挂载时初始化一次,调用方应按画布重挂载。
|
||||||
|
* key区分草稿作用域,paused阻断这里的新备份/入队,不在此取消已交给writer的请求。 */
|
||||||
export function useCanvasPersistence(document: CanvasDocument, workspace: string, board: string, key: string, snapshot: CanvasSnapshot | undefined, paused: boolean) {
|
export function useCanvasPersistence(document: CanvasDocument, workspace: string, board: string, key: string, snapshot: CanvasSnapshot | undefined, paused: boolean) {
|
||||||
const [sync, setSync] = useState<SyncState>({ status: "saved", version: snapshot?.version || 1 });
|
const [sync, setSync] = useState<SyncState>({ status: "saved", version: snapshot?.version || 1 });
|
||||||
|
// alive限制writer通知更新已卸载组件;latest和pausedRef让异步回调读取当前文档/暂停值。
|
||||||
const alive = useRef(false);
|
const alive = useRef(false);
|
||||||
const latest = useRef(document); latest.current = document;
|
const latest = useRef(document); latest.current = document;
|
||||||
const pausedRef = useRef(paused); pausedRef.current = paused;
|
const pausedRef = useRef(paused); pausedRef.current = paused;
|
||||||
|
// 同一挂载复用writer;状态变化时刷新sync并补本地备份,不随每次文档渲染新建同步器。
|
||||||
const [writer] = useState(() => snapshot ? new CanvasSync(api, canvasPath(workspace, board), snapshot, (next) => {
|
const [writer] = useState(() => snapshot ? new CanvasSync(api, canvasPath(workspace, board), snapshot, (next) => {
|
||||||
if (alive.current) { setSync(next); backup(); }
|
if (alive.current) { setSync(next); backup(); }
|
||||||
}) : null);
|
}) : null);
|
||||||
|
/** 保存规范化document、writer当前版本及内容指纹dirty;回调路径吞掉存储异常,定时effect路径会展示错误。 */
|
||||||
function backup() {
|
function backup() {
|
||||||
if (pausedRef.current) return;
|
if (pausedRef.current) return;
|
||||||
try {
|
try {
|
||||||
@@ -19,6 +28,7 @@ export function useCanvasPersistence(document: CanvasDocument, workspace: string
|
|||||||
localStorage.setItem(key + ":recovery", JSON.stringify({ document: decodeCanvas(JSON.stringify(current)), baseVersion: writer?.version || 1, dirty: writer ? canvasFingerprint(current) !== writer.saved : false }));
|
localStorage.setItem(key + ":recovery", JSON.stringify({ document: decodeCanvas(JSON.stringify(current)), baseVersion: writer?.version || 1, dirty: writer ? canvasFingerprint(current) !== writer.saved : false }));
|
||||||
} catch { /* Storage failure is surfaced by the effect below. */ }
|
} catch { /* Storage failure is surfaced by the effect below. */ }
|
||||||
}
|
}
|
||||||
|
// 文档变化重置250ms本地/800ms远端计时器,形成防抖;暂停不建立计时器,清理只取消尚未触发的任务。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (paused) return;
|
if (paused) return;
|
||||||
const local = setTimeout(() => {
|
const local = setTimeout(() => {
|
||||||
@@ -28,13 +38,16 @@ export function useCanvasPersistence(document: CanvasDocument, workspace: string
|
|||||||
const remote = writer ? setTimeout(() => void writer.enqueue(latest.current), 800) : null;
|
const remote = writer ? setTimeout(() => void writer.enqueue(latest.current), 800) : null;
|
||||||
return () => { clearTimeout(local); if (remote) clearTimeout(remote); };
|
return () => { clearTimeout(local); if (remote) clearTimeout(remote); };
|
||||||
}, [document, writer, key, paused]);
|
}, [document, writer, key, paused]);
|
||||||
|
// pagehide与卸载只执行同步本地backup,不保证远端请求在离页前完成;卸载后不再接收writer的UI通知。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
alive.current = true;
|
alive.current = true;
|
||||||
|
/** 页面隐藏/离开时尽量保存当前内存文档,暂停状态由backup内部再次检查。 */
|
||||||
const flush = () => backup();
|
const flush = () => backup();
|
||||||
window.addEventListener("pagehide", flush);
|
window.addEventListener("pagehide", flush);
|
||||||
return () => { window.removeEventListener("pagehide", flush); backup(); alive.current = false; };
|
return () => { window.removeEventListener("pagehide", flush); backup(); alive.current = false; };
|
||||||
// Writer and key are stable for this board's mounted editor.
|
// Writer and key are stable for this board's mounted editor.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [writer, key]);
|
}, [writer, key]);
|
||||||
|
// retry先补本地备份再委托writer重试;没有远端writer时返回undefined,不伪造同步成功。
|
||||||
return { ...sync, retry: () => { backup(); return writer?.retry(); } };
|
return { ...sync, retry: () => { backup(); return writer?.retry(); } };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* 旧版画布树的状态与操作协调Hook。documents按boardId保存已加载快照,views把嵌套子画布投影为当前ReactFlow场景。
|
||||||
|
* 每个board有独立CanvasSync writer,本地历史和服务端结构事务共用两个栈,成员迁移另用串行内存队列。
|
||||||
|
* 该实现保留旧快照协议与本地草稿恢复,不等同于新版engine的统一提交根、持久ledger和恢复状态机。
|
||||||
|
* 调用方应按根/工作区身份重挂载;refs提供异步操作读取的最新状态,React state负责发布界面变化。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import type { EdgeChange, NodeChange } from "@xyflow/react";
|
import type { EdgeChange, NodeChange } from "@xyflow/react";
|
||||||
@@ -8,20 +14,34 @@ import { CANVAS_ACCEPT, type EdgeData } from "@/lib/canvas-v2";
|
|||||||
import { subgraphMovePath, subgraphMoveParticipants } from "@/lib/canvas-subgraphs";
|
import { subgraphMovePath, subgraphMoveParticipants } from "@/lib/canvas-subgraphs";
|
||||||
import { mergeCanvasDocuments, projectCanvasTree, transformEdgeData, referenceAfterMoves } from "@/lib/canvas-tree";
|
import { mergeCanvasDocuments, projectCanvasTree, transformEdgeData, referenceAfterMoves } from "@/lib/canvas-tree";
|
||||||
|
|
||||||
|
/** 命令返回的快照额外携带board_id,用于把多画布结果安装回各自writer。 */
|
||||||
type OwnedSnapshot = CanvasSnapshot & { board_id: string };
|
type OwnedSnapshot = CanvasSnapshot & { board_id: string };
|
||||||
|
/** 兼容多个旧命令端点的结果包络,可能返回父/子/多快照、事务身份、归档列表和版本;各使用路径再解码快照。 */
|
||||||
export type CanvasCommandResult = { transaction_id?: string; parent?: OwnedSnapshot; child?: OwnedSnapshot; snapshots?: OwnedSnapshot[]; children?: OwnedSnapshot[]; canvas_version?: number; applied_versions?: Record<string, number>; archived_board_ids?: string[]; undo_receipt?: { expires_at: string }; [key: string]: unknown };
|
export type CanvasCommandResult = { transaction_id?: string; parent?: OwnedSnapshot; child?: OwnedSnapshot; snapshots?: OwnedSnapshot[]; children?: OwnedSnapshot[]; canvas_version?: number; applied_versions?: Record<string, number>; archived_board_ids?: string[]; undo_receipt?: { expires_at: string }; [key: string]: unknown };
|
||||||
|
/** 本地历史保存操作前整份画布,可附关联画布;pendingMove标记尚未上传图片的跨画布移动,便于后来按服务端归属撤销。 */
|
||||||
type LocalHistory = { boardId: string; before: CanvasDocument; related?: Map<string, CanvasDocument>; pendingMove?: { id: string; source: string; target: string } };
|
type LocalHistory = { boardId: string; before: CanvasDocument; related?: Map<string, CanvasDocument>; pendingMove?: { id: string; source: string; target: string } };
|
||||||
|
/** 服务端结构事务历史保存可重放的路径/负载、事务ID和参与画布;撤销请求服务端undo,重做重新执行原命令。 */
|
||||||
type TransactionHistory = { boardId: string; path: string; payload: Record<string, unknown>; id: string; participants: string[] };
|
type TransactionHistory = { boardId: string; path: string; payload: Record<string, unknown>; id: string; participants: string[] };
|
||||||
|
/** 两种历史条目共用undo/redo栈,通过是否有id字段区分;不是每次pointermove都直接创建条目。 */
|
||||||
type Entry = LocalHistory | TransactionHistory;
|
type Entry = LocalHistory | TransactionHistory;
|
||||||
|
/** 成员归属迁移的FIFO任务;run在准备后捕获固定body/key供不确定失败重试,refresh表示确定冲突后需刷新基线。 */
|
||||||
type MemberJob = { source: string; target: string; ids: string[]; parent: string; frame: string; participants: string[]; error?: string; refresh?: boolean; run?: () => Promise<void>; resolve: () => void };
|
type MemberJob = { source: string; target: string; ids: string[]; parent: string; frame: string; participants: string[]; error?: string; refresh?: boolean; run?: () => Promise<void>; resolve: () => void };
|
||||||
|
/** 只为一次reducer运算建立临时空历史,借其past是否变化判断该动作是否应进入本Hook自己的历史栈。 */
|
||||||
const history = (document: CanvasDocument): CanvasHistory => ({ past: [], present: document, future: [] });
|
const history = (document: CanvasDocument): CanvasHistory => ({ past: [], present: document, future: [] });
|
||||||
|
|
||||||
|
/** initial建立根画布,snapshot决定是否连接服务端writer;paused阻止保存/独占事务等准入,migration额外限制旧写入。
|
||||||
|
* parentBoardId用于补读祖先快照;导出、跨分区移动和事务可能按需加载更多画布。 */
|
||||||
export function useCanvasTree(root: string, workspace: string, initial: CanvasDocument, snapshot?: CanvasSnapshot, paused = false, parentBoardId?: string, migration?: {accountId:string;isCurrentIdentity():boolean}) {
|
export function useCanvasTree(root: string, workspace: string, initial: CanvasDocument, snapshot?: CanvasSnapshot, paused = false, parentBoardId?: string, migration?: {accountId:string;isCurrentIdentity():boolean}) {
|
||||||
|
// 有迁移上下文时先关旧编辑入口,等迁移协调组件取得共享租约再开放;flush只有迁移准备阶段临时启用。
|
||||||
const migrationGate=useRef(!!migration);
|
const migrationGate=useRef(!!migration);
|
||||||
const migrationFlush=useRef(false);
|
const migrationFlush=useRef(false);
|
||||||
const [migrationHeld,setMigrationState]=useState(!!migration);
|
const [migrationHeld,setMigrationState]=useState(!!migration);
|
||||||
|
/** 同步检查门闩和账号身份,事件处理无需等待React的migrationHeld重新渲染。 */
|
||||||
const migrationBlocked=()=>migrationGate.current||!!migration&&!migration.isCurrentIdentity();
|
const migrationBlocked=()=>migrationGate.current||!!migration&&!migration.isCurrentIdentity();
|
||||||
|
/** 同时更新同步门闩与界面状态;只更新state会留下同一事件轮次中的旧写入窗口。 */
|
||||||
function setMigrationHeld(value:boolean){migrationGate.current=value;setMigrationState(value);}
|
function setMigrationHeld(value:boolean){migrationGate.current=value;setMigrationState(value);}
|
||||||
|
/** 旧接口请求护栏:await前后检查账号,写请求受迁移门闩限制;迁移排空时只放行canvas PATCH。
|
||||||
|
* X-Expected-Account要求代理校验目标账号,避免切号后旧请求误用新会话。 */
|
||||||
const api:CanvasRequest=async <T,>(path:string,options?:RequestInit)=>{
|
const api:CanvasRequest=async <T,>(path:string,options?:RequestInit)=>{
|
||||||
if(migration&&!migration.isCurrentIdentity())throw new Error('identity_changed');
|
if(migration&&!migration.isCurrentIdentity())throw new Error('identity_changed');
|
||||||
if(migrationBlocked()&&options?.method&&options.method!=='GET'&&!(migrationFlush.current&&options.method==='PATCH'&&path.endsWith('/canvas')))throw new Error('canvas_busy');
|
if(migrationBlocked()&&options?.method&&options.method!=='GET'&&!(migrationFlush.current&&options.method==='PATCH'&&path.endsWith('/canvas')))throw new Error('canvas_busy');
|
||||||
@@ -29,33 +49,42 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
const value=await requestAPI<T>(path,{...options,headers:Object.fromEntries(headers)});
|
const value=await requestAPI<T>(path,{...options,headers:Object.fromEntries(headers)});
|
||||||
if(migration&&!migration.isCurrentIdentity())throw new Error('identity_changed');return value;
|
if(migration&&!migration.isCurrentIdentity())throw new Error('identity_changed');return value;
|
||||||
};
|
};
|
||||||
|
// documents是已加载board的模型表,current立即跟随发布供异步回调读取;status/error是旧writer汇总显示值。
|
||||||
const [documents, setDocuments] = useState(new Map([[root, initial]]));
|
const [documents, setDocuments] = useState(new Map([[root, initial]]));
|
||||||
const current = useRef(documents); current.current = documents;
|
const current = useRef(documents); current.current = documents;
|
||||||
const [status, setStatus] = useState("saved");
|
const [status, setStatus] = useState("saved");
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [memberJobs, setMemberJobs] = useState<MemberJob[]>([]);
|
const [memberJobs, setMemberJobs] = useState<MemberJob[]>([]);
|
||||||
|
// capability缓存查询Promise;members是实际内存队列,memberJobs只是供React显示的数组副本。
|
||||||
const memberCapability = useRef<Promise<boolean> | null>(null);
|
const memberCapability = useRef<Promise<boolean> | null>(null);
|
||||||
const members = useRef<MemberJob[]>([]), memberRunning = useRef(false), dragging = useRef(false);
|
const members = useRef<MemberJob[]>([]), memberRunning = useRef(false), dragging = useRef(false);
|
||||||
|
/** 仅挂载期间发布队列副本;任务对象仍共享引用,修改error等字段后需显式通知。 */
|
||||||
const showMembers = () => { if (mounted.current) setMemberJobs([...members.current]); };
|
const showMembers = () => { if (mounted.current) setMemberJobs([...members.current]); };
|
||||||
|
/** 拖动期间延后自动保存,结束时发布新Map触发防抖重新评估;不在这里执行成员归属变化。 */
|
||||||
function setDragging(value: boolean) { dragging.current = value; if (!value) publish(new Map(current.current)); }
|
function setDragging(value: boolean) { dragging.current = value; if (!value) publish(new Map(current.current)); }
|
||||||
|
/** 成员任务涉及的节点暂不能再被普通动作改动;队列非空时也保护子图入口几何及结构,避免请求基准漂移。 */
|
||||||
function protectedNodes(boardId: string) {
|
function protectedNodes(boardId: string) {
|
||||||
const ids = new Set(members.current.flatMap((job) => [job.source, job.target].includes(boardId) ? job.ids : []));
|
const ids = new Set(members.current.flatMap((job) => [job.source, job.target].includes(boardId) ? job.ids : []));
|
||||||
if (members.current.length) for (const node of current.current.get(boardId)?.nodes || []) if (node.data.subgraph) ids.add(node.id);
|
if (members.current.length) for (const node of current.current.get(boardId)?.nodes || []) if (node.data.subgraph) ids.add(node.id);
|
||||||
return ids;
|
return ids;
|
||||||
}
|
}
|
||||||
const [pendingCommand, setPendingCommand] = useState(false);
|
const [pendingCommand, setPendingCommand] = useState(false);
|
||||||
|
// 不确定命令失败时保留同一execute闭包,pendingCommand驱动UI;locked只管当前独占异步操作。
|
||||||
const retryOperation = useRef<(() => Promise<CanvasCommandResult>) | null>(null);
|
const retryOperation = useRef<(() => Promise<CanvasCommandResult>) | null>(null);
|
||||||
const locked = useRef(false), mounted = useRef(true), pause = useRef(paused); pause.current = paused;
|
const locked = useRef(false), mounted = useRef(true), pause = useRef(paused); pause.current = paused;
|
||||||
|
// writer持每画布ACK基线与保存队列,loading去重子画布读取;二者都不是documents的替代存储。
|
||||||
const writers = useRef(new Map<string, CanvasSync>());
|
const writers = useRef(new Map<string, CanvasSync>());
|
||||||
const loading = useRef(new Set<string>());
|
const loading = useRef(new Set<string>());
|
||||||
const [retryLoad, setRetryLoad] = useState(0);
|
const [retryLoad, setRetryLoad] = useState(0);
|
||||||
const [recoveries, setRecoveries] = useState(new Map<string, CanvasDocument>());
|
const [recoveries, setRecoveries] = useState(new Map<string, CanvasDocument>());
|
||||||
const pendingRecovery = useRef(recoveries); pendingRecovery.current = recoveries;
|
const pendingRecovery = useRef(recoveries); pendingRecovery.current = recoveries;
|
||||||
|
/** 以当前服务端快照筛选有内容差异的本地恢复候选,按board记录,等待用户决定;不证明可安全覆盖模型。 */
|
||||||
function inspectRecovery(boardId: string, value: CanvasSnapshot) {
|
function inspectRecovery(boardId: string, value: CanvasSnapshot) {
|
||||||
const local = readLocalRecovery(localStorage, `endoleap_canvas_v1:${workspace}:${boardId}`, value);
|
const local = readLocalRecovery(localStorage, `endoleap_canvas_v1:${workspace}:${boardId}`, value);
|
||||||
if (local) { const next = new Map(pendingRecovery.current).set(boardId, local); pendingRecovery.current = next; setRecoveries(next); }
|
if (local) { const next = new Map(pendingRecovery.current).set(boardId, local); pendingRecovery.current = next; setRecoveries(next); }
|
||||||
}
|
}
|
||||||
|
/** 可编辑时按选择替换本地文档或采用现状,移除恢复候选和草稿记录;远端写入仍走后续writer。 */
|
||||||
function resolveRecovery(boardId: string, restore: boolean) {
|
function resolveRecovery(boardId: string, restore: boolean) {
|
||||||
if(migrationBlocked())return;
|
if(migrationBlocked())return;
|
||||||
const draft = pendingRecovery.current.get(boardId);
|
const draft = pendingRecovery.current.get(boardId);
|
||||||
@@ -63,12 +92,16 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
const next = new Map(pendingRecovery.current); next.delete(boardId); pendingRecovery.current = next; setRecoveries(next);
|
const next = new Map(pendingRecovery.current); next.delete(boardId); pendingRecovery.current = next; setRecoveries(next);
|
||||||
localStorage.removeItem(`endoleap_canvas_v1:${workspace}:${boardId}:recovery`);
|
localStorage.removeItem(`endoleap_canvas_v1:${workspace}:${boardId}:recovery`);
|
||||||
}
|
}
|
||||||
|
// 两个ref数组作为历史栈,boardAliases记录重做子图创建后新旧boardID对应;tick用于仅栈变化时通知UI。
|
||||||
const undo = useRef<Entry[]>([]), redo = useRef<Entry[]>([]);
|
const undo = useRef<Entry[]>([]), redo = useRef<Entry[]>([]);
|
||||||
const boardAliases = useRef(new Map<string, string>());
|
const boardAliases = useRef(new Map<string, string>());
|
||||||
const [, tick] = useState(0);
|
const [, tick] = useState(0);
|
||||||
|
// 根据根与documents派生投影索引,nodeRefs/edgeRefs把场景ID映射回所属board、本地ID和坐标变换。
|
||||||
const views = useMemo(() => projectCanvasTree(root, documents), [root, documents]);
|
const views = useMemo(() => projectCanvasTree(root, documents), [root, documents]);
|
||||||
const view = useRef(views); view.current = views;
|
const view = useRef(views); view.current = views;
|
||||||
|
/** 先更新同步ref,再在挂载期间发布React state;等待中的操作可立即读取新Map。 */
|
||||||
function publish(next: Map<string, CanvasDocument>) { current.current = next; if (mounted.current) setDocuments(next); }
|
function publish(next: Map<string, CanvasDocument>) { current.current = next; if (mounted.current) setDocuments(next); }
|
||||||
|
/** 将服务端快照作为writer基线:已有writer采用新ACK,否则在真实快照模式建立writer;这里只安装,不发保存。 */
|
||||||
function install(boardId: string, value: CanvasSnapshot) {
|
function install(boardId: string, value: CanvasSnapshot) {
|
||||||
const writer = writers.current.get(boardId);
|
const writer = writers.current.get(boardId);
|
||||||
if (writer) writer.adopt(value);
|
if (writer) writer.adopt(value);
|
||||||
@@ -80,25 +113,33 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
// Initialization never writes a snapshot to the server.
|
// Initialization never writes a snapshot to the server.
|
||||||
if (snapshot && !writers.current.has(root)) install(root, snapshot);
|
if (snapshot && !writers.current.has(root)) install(root, snapshot);
|
||||||
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
|
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
|
||||||
|
/** 普通单画布动作入口:检查门闩,经reducer计算新文档,保留成员迁移保护字段,再按需要记历史并发布。 */
|
||||||
const update = (boardId: string, action: CanvasAction) => {
|
const update = (boardId: string, action: CanvasAction) => {
|
||||||
if (migrationBlocked() || locked.current || retryOperation.current) return;
|
if (migrationBlocked() || locked.current || retryOperation.current) return;
|
||||||
const before = current.current.get(boardId); if (!before) return;
|
const before = current.current.get(boardId); if (!before) return;
|
||||||
const result = canvasReducer(history(before), action);
|
const result = canvasReducer(history(before), action);
|
||||||
const protectedIDs = protectedNodes(boardId);
|
const protectedIDs = protectedNodes(boardId);
|
||||||
|
// 迁移中的普通节点只允许选中变化;未作为移动目标的子图入口保留原几何、subgraph/ports/presentation。
|
||||||
|
// reducer删掉的受保护节点也补回,避免异步成员请求到来时对象已被本地删除。
|
||||||
if (protectedIDs.size) result.present = { ...result.present, nodes: result.present.nodes.map((node) => {
|
if (protectedIDs.size) result.present = { ...result.present, nodes: result.present.nodes.map((node) => {
|
||||||
const prior = before.nodes.find((item) => item.id === node.id);
|
const prior = before.nodes.find((item) => item.id === node.id);
|
||||||
if (!prior || !protectedIDs.has(node.id)) return node;
|
if (!prior || !protectedIDs.has(node.id)) return node;
|
||||||
const moving = members.current.some((job) => [job.source, job.target].includes(boardId) && job.ids.includes(node.id));
|
const moving = members.current.some((job) => [job.source, job.target].includes(boardId) && job.ids.includes(node.id));
|
||||||
return prior.data.subgraph && !moving ? { ...node, position: prior.position, width: prior.width, height: prior.height, data: { ...node.data, subgraph: prior.data.subgraph, ports: prior.data.ports, presentation: prior.data.presentation } } : { ...prior, selected: node.selected };
|
return prior.data.subgraph && !moving ? { ...node, position: prior.position, width: prior.width, height: prior.height, data: { ...node.data, subgraph: prior.data.subgraph, ports: prior.data.ports, presentation: prior.data.presentation } } : { ...prior, selected: node.selected };
|
||||||
}).concat(before.nodes.filter((node) => protectedIDs.has(node.id) && !result.present.nodes.some((item) => item.id === node.id))) };
|
}).concat(before.nodes.filter((node) => protectedIDs.has(node.id) && !result.present.nodes.some((item) => item.id === node.id))) };
|
||||||
|
// reducer产生历史才入undo,普通更新路径最多留40项并清redo;其它事务/刷新路径不一定使用同一截断逻辑。
|
||||||
if (result.past.length) { undo.current.push({ boardId, before }); undo.current = undo.current.slice(-40); redo.current = []; }
|
if (result.past.length) { undo.current.push({ boardId, before }); undo.current = undo.current.slice(-40); redo.current = []; }
|
||||||
publish(new Map(current.current).set(boardId, result.present));
|
publish(new Map(current.current).set(boardId, result.present));
|
||||||
};
|
};
|
||||||
|
/** 默认对根发动作,也允许调用方显式指定已加载board。 */
|
||||||
const dispatch = (action: CanvasAction, boardId = root) => update(boardId, action);
|
const dispatch = (action: CanvasAction, boardId = root) => update(boardId, action);
|
||||||
|
/** 从投影节点ID解析实际owner,再用原始节点ID构造动作,避免把场景复合ID写回快照。 */
|
||||||
const nodeAction = (id: string, action: (id: string) => CanvasAction) => { const ref = view.current.nodeRefs.get(id); if (ref) update(ref.boardId, action(ref.id)); };
|
const nodeAction = (id: string, action: (id: string) => CanvasAction) => { const ref = view.current.nodeRefs.get(id); if (ref) update(ref.boardId, action(ref.id)); };
|
||||||
|
/** 按owner分组ReactFlow节点变化;忽略add/replace,将场景位置和尺寸还原为所属board局部坐标。 */
|
||||||
const nodesChanged = (changes: NodeChange<CanvasNode>[]) => {
|
const nodesChanged = (changes: NodeChange<CanvasNode>[]) => {
|
||||||
if (migrationBlocked() || locked.current || retryOperation.current) return;
|
if (migrationBlocked() || locked.current || retryOperation.current) return;
|
||||||
const groups = new Map<string, NodeChange<CanvasNode>[]>();
|
const groups = new Map<string, NodeChange<CanvasNode>[]>();
|
||||||
|
// 同批父分区也在移动时先计算调整后的原点,避免对子节点重复施加父位移;尺寸再除投影scale。
|
||||||
const moves = new Map(changes.flatMap((change) => change.type === "position" && change.position ? [[change.id, change.position] as const] : []));
|
const moves = new Map(changes.flatMap((change) => change.type === "position" && change.position ? [[change.id, change.position] as const] : []));
|
||||||
for (const change of changes) {
|
for (const change of changes) {
|
||||||
if (change.type === "add" || change.type === "replace") continue;
|
if (change.type === "add" || change.type === "replace") continue;
|
||||||
@@ -106,6 +147,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
const adjusted = referenceAfterMoves(root, current.current, view.current.boards, ref.boardId, moves);
|
const adjusted = referenceAfterMoves(root, current.current, view.current.boards, ref.boardId, moves);
|
||||||
const next = { ...change, id: ref.id };
|
const next = { ...change, id: ref.id };
|
||||||
if (next.type === "position" && next.position) next.position = { x: (next.position.x - adjusted.origin.x) / ref.scale, y: (next.position.y - adjusted.origin.y) / ref.scale };
|
if (next.type === "position" && next.position) next.position = { x: (next.position.x - adjusted.origin.x) / ref.scale, y: (next.position.y - adjusted.origin.y) / ref.scale };
|
||||||
|
// ResizeObserver只更新测量信息;非显式resizing不得把测量宽高当模型尺寸写回。
|
||||||
if (next.type === "dimensions") {
|
if (next.type === "dimensions") {
|
||||||
// ResizeObserver measurements are editor state. Only an explicit resize
|
// ResizeObserver measurements are editor state. Only an explicit resize
|
||||||
// gesture may write node dimensions back to the owning snapshot.
|
// gesture may write node dimensions back to the owning snapshot.
|
||||||
@@ -116,6 +158,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
}
|
}
|
||||||
for (const [boardId, changes] of groups) update(boardId, { type: "nodes", changes });
|
for (const [boardId, changes] of groups) update(boardId, { type: "nodes", changes });
|
||||||
};
|
};
|
||||||
|
/** 按edgeRefs分组选择/删除等变化,忽略add/replace;最终update仍统一检查写入准入。 */
|
||||||
const edgesChanged = (changes: EdgeChange[]) => {
|
const edgesChanged = (changes: EdgeChange[]) => {
|
||||||
const groups = new Map<string, EdgeChange[]>();
|
const groups = new Map<string, EdgeChange[]>();
|
||||||
for (const change of changes) {
|
for (const change of changes) {
|
||||||
@@ -124,13 +167,17 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
}
|
}
|
||||||
for (const [boardId, changes] of groups) update(boardId, { type: "edges", changes });
|
for (const [boardId, changes] of groups) update(boardId, { type: "edges", changes });
|
||||||
};
|
};
|
||||||
|
/** 曲线路径从场景坐标反变换回owner局部空间,再派发edge-data;transient交reducer决定历史语义。 */
|
||||||
const patchEdge = (id: string, data: EdgeData, transient = false) => {
|
const patchEdge = (id: string, data: EdgeData, transient = false) => {
|
||||||
const ref = view.current.edgeRefs.get(id); if (ref) update(ref.boardId, { type: "edge-data", id: ref.id, data: transformEdgeData(data, ref, true)!, transient });
|
const ref = view.current.edgeRefs.get(id); if (ref) update(ref.boardId, { type: "edge-data", id: ref.id, data: transformEdgeData(data, ref, true)!, transient });
|
||||||
};
|
};
|
||||||
|
/** 遍历已加载文档,只有目标owner/localID被选中,其余节点取消选择;不直接操作投影数组。 */
|
||||||
const select = (id: string) => {
|
const select = (id: string) => {
|
||||||
for (const [boardId, document] of current.current) update(boardId, { type: "nodes", changes: document.nodes.map((node) => ({ type: "select", id: node.id, selected: view.current.nodeRefs.get(id)?.boardId === boardId && view.current.nodeRefs.get(id)?.id === node.id })) });
|
for (const [boardId, document] of current.current) update(boardId, { type: "nodes", changes: document.nodes.map((node) => ({ type: "select", id: node.id, selected: view.current.nodeRefs.get(id)?.boardId === boardId && view.current.nodeRefs.get(id)?.id === node.id })) });
|
||||||
};
|
};
|
||||||
|
/** 读取并解码一个board的旧v2快照,可传取消信号;api层仍检查迁移账号身份。 */
|
||||||
const read = async (boardId: string, signal?: AbortSignal) => decodeSnapshot(await api<CanvasSnapshot>(canvasPath(workspace, boardId), { headers: { Accept: CANVAS_ACCEPT }, signal }));
|
const read = async (boardId: string, signal?: AbortSignal) => decodeSnapshot(await api<CanvasSnapshot>(canvasPath(workspace, boardId), { headers: { Accept: CANVAS_ACCEPT }, signal }));
|
||||||
|
/** 查询服务端是否支持成员迁移同时提交坐标;演示为false,成功结果复用,失败清缓存供按需重试。 */
|
||||||
function supportsMemberPositions(): Promise<boolean> {
|
function supportsMemberPositions(): Promise<boolean> {
|
||||||
if (!snapshot) return Promise.resolve(false);
|
if (!snapshot) return Promise.resolve(false);
|
||||||
if (!memberCapability.current) {
|
if (!memberCapability.current) {
|
||||||
@@ -141,9 +188,11 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
}
|
}
|
||||||
return memberCapability.current;
|
return memberCapability.current;
|
||||||
}
|
}
|
||||||
|
// 能力预取失败不视作确定不支持,真正成员操作仍可重新请求。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void supportsMemberPositions().catch(() => { /* A failed prefetch is retried on demand, never cached as unsupported. */ });
|
void supportsMemberPositions().catch(() => { /* A failed prefetch is retried on demand, never cached as unsupported. */ });
|
||||||
}, [root, workspace, !!snapshot]);
|
}, [root, workspace, !!snapshot]);
|
||||||
|
/** 按需加载真实快照或演示本地草稿,装writer并检查恢复候选;recursive递归加载子图,祖先集合防环且限制深度。 */
|
||||||
async function ensure(boardId: string, recursive = false, ancestors = new Set<string>()): Promise<void> {
|
async function ensure(boardId: string, recursive = false, ancestors = new Set<string>()): Promise<void> {
|
||||||
if (ancestors.has(boardId) || ancestors.size > 8) throw new Error("subgraph_cycle");
|
if (ancestors.has(boardId) || ancestors.size > 8) throw new Error("subgraph_cycle");
|
||||||
let document = current.current.get(boardId);
|
let document = current.current.get(boardId);
|
||||||
@@ -153,14 +202,17 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
}
|
}
|
||||||
if (recursive) { const next = new Set(ancestors); next.add(boardId); for (const node of document.nodes) if (node.data.subgraph) await ensure(node.data.subgraph.boardId, true, next); }
|
if (recursive) { const next = new Set(ancestors); next.add(boardId); for (const node of document.nodes) if (node.data.subgraph) await ensure(node.data.subgraph.boardId, true, next); }
|
||||||
}
|
}
|
||||||
|
/** 独占期间完整加载根下可达子图,然后收集导出Map;不会把已加载但不可达的祖先或其它分支混入导出。 */
|
||||||
async function exportDocuments() {
|
async function exportDocuments() {
|
||||||
return exclusive(async () => {
|
return exclusive(async () => {
|
||||||
await ensure(root, true);
|
await ensure(root, true);
|
||||||
const reachable = new Map<string, CanvasDocument>();
|
const reachable = new Map<string, CanvasDocument>();
|
||||||
|
/** 可达集合兼作去重;ensure已验证递归关系,此处只遍历当前已加载文档。 */
|
||||||
const collect = (id: string) => { const document = current.current.get(id)!; reachable.set(id, document); for (const node of document.nodes) if (node.data.subgraph && !reachable.has(node.data.subgraph.boardId)) collect(node.data.subgraph.boardId); };
|
const collect = (id: string) => { const document = current.current.get(id)!; reachable.set(id, document); for (const node of document.nodes) if (node.data.subgraph && !reachable.has(node.data.subgraph.boardId)) collect(node.data.subgraph.boardId); };
|
||||||
collect(root); return reachable;
|
collect(root); return reachable;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// 打开子画布时向上读取元数据与快照,补齐祖先关系;alive阻止离页后的采用,不在本effect中abort请求。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!snapshot || !parentBoardId) return;
|
if (!snapshot || !parentBoardId) return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
@@ -178,6 +230,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
// Root identity is stable until this editor unmounts.
|
// Root identity is stable until this editor unmounts.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [parentBoardId, root, workspace]);
|
}, [parentBoardId, root, workspace]);
|
||||||
|
// 场景可见且未折叠的子图按需异步读取,loading去重;回包时重新确认仍被当前文档引用。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
for (const [boardId, document] of documents) for (const node of document.nodes) {
|
for (const [boardId, document] of documents) for (const node of document.nodes) {
|
||||||
if (!view.current.boards.has(boardId)) continue;
|
if (!view.current.boards.has(boardId)) continue;
|
||||||
@@ -192,6 +245,8 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
// Values and writers are scoped to this mounted root/workspace.
|
// Values and writers are scoped to this mounted root/workspace.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [documents, retryLoad]);
|
}, [documents, retryLoad]);
|
||||||
|
// 文档变化防抖:250ms本地备份、800ms远端保存。恢复待决画布跳过,防止覆盖用户尚未选择的草稿。
|
||||||
|
// 远端另等独占锁、命令重试、成员任务和拖动结束;本地备份不需要等这些普通操作全部结束。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (paused || migrationBlocked()) return;
|
if (paused || migrationBlocked()) return;
|
||||||
const backup = setTimeout(() => {
|
const backup = setTimeout(() => {
|
||||||
@@ -208,7 +263,9 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
}, 800);
|
}, 800);
|
||||||
return () => { clearTimeout(backup); clearTimeout(save); };
|
return () => { clearTimeout(backup); clearTimeout(save); };
|
||||||
}, [documents, paused, workspace, memberJobs, migrationHeld]);
|
}, [documents, paused, workspace, memberJobs, migrationHeld]);
|
||||||
|
// pagehide/卸载尽量做本地同步备份,不等待远端flush;暂停/迁移仍禁止写,存储满时保留已有记录。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
/** 遍历最新内存文档,备份规范化payload与ACK版本/dirty;页面离开时错误不再触发界面更新。 */
|
||||||
const backup = () => {
|
const backup = () => {
|
||||||
if (pause.current || migrationBlocked()) return;
|
if (pause.current || migrationBlocked()) return;
|
||||||
for (const [boardId, document] of current.current) {
|
for (const [boardId, document] of current.current) {
|
||||||
@@ -219,6 +276,8 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
window.addEventListener("pagehide", backup);
|
window.addEventListener("pagehide", backup);
|
||||||
return () => { window.removeEventListener("pagehide", backup); backup(); };
|
return () => { window.removeEventListener("pagehide", backup); backup(); };
|
||||||
}, [workspace]);
|
}, [workspace]);
|
||||||
|
/** 串行排空各writer,任一恢复待决或writer错误就失败;deferMemberPositions保留待移动节点原ACK坐标。
|
||||||
|
* 支持原子坐标的成员接口会在归属事务里提交新位置,避免先把新位置单独写入旧owner。 */
|
||||||
async function flush(deferMemberPositions = false) {
|
async function flush(deferMemberPositions = false) {
|
||||||
for (const [boardId, document] of current.current) {
|
for (const [boardId, document] of current.current) {
|
||||||
if (pendingRecovery.current.has(boardId)) throw new Error("draft_recovery_required");
|
if (pendingRecovery.current.has(boardId)) throw new Error("draft_recovery_required");
|
||||||
@@ -228,6 +287,8 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
await writer.enqueue(saving); await writer.settled(); if (writer.error) throw new Error(writer.error);
|
await writer.enqueue(saving); await writer.settled(); if (writer.error) throw new Error(writer.error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/** 迁移前必须已关门,无事务/成员/拖动/加载,且恢复已处理;加载整棵迁移树并核查上传占位。
|
||||||
|
* 先备份本页,再临时放行PATCH排空旧writer;所有writer确认无待保存内容后把备份标为clean。 */
|
||||||
async function prepareMigration(projectRoot:string){
|
async function prepareMigration(projectRoot:string){
|
||||||
if(!migrationGate.current)throw new Error('migration_gate_required');
|
if(!migrationGate.current)throw new Error('migration_gate_required');
|
||||||
if(locked.current||retryOperation.current||members.current.length||dragging.current||loading.current.size)throw new Error('canvas_busy');
|
if(locked.current||retryOperation.current||members.current.length||dragging.current||loading.current.size)throw new Error('canvas_busy');
|
||||||
@@ -240,12 +301,14 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
for(const[boardId,document]of current.current){
|
for(const[boardId,document]of current.current){
|
||||||
const writer=writers.current.get(boardId);
|
const writer=writers.current.get(boardId);
|
||||||
const local=readLocalRecovery(localStorage,`endoleap_canvas_v1:${workspace}:${boardId}`,writer?{version:writer.version,document:writer.document}:undefined);
|
const local=readLocalRecovery(localStorage,`endoleap_canvas_v1:${workspace}:${boardId}`,writer?{version:writer.version,document:writer.document}:undefined);
|
||||||
|
// 本地另有不同恢复内容时转为用户选择,不能用当前内存直接覆盖它后迁移。
|
||||||
if(local&&canvasFingerprint(local,false)!==canvasFingerprint(document,false)){
|
if(local&&canvasFingerprint(local,false)!==canvasFingerprint(document,false)){
|
||||||
const next=new Map(pendingRecovery.current).set(boardId,local);pendingRecovery.current=next;setRecoveries(next);throw new Error('draft_recovery_required');
|
const next=new Map(pendingRecovery.current).set(boardId,local);pendingRecovery.current=next;setRecoveries(next);throw new Error('draft_recovery_required');
|
||||||
}
|
}
|
||||||
// Preserve the current view even if it closes while PATCH is in flight.
|
// Preserve the current view even if it closes while PATCH is in flight.
|
||||||
localStorage.setItem(`endoleap_canvas_v1:${workspace}:${boardId}:recovery`,JSON.stringify({document:canvasPayload(document),baseVersion:writer?.version||1,dirty:writer?writer.needsSave(document):false}));
|
localStorage.setItem(`endoleap_canvas_v1:${workspace}:${boardId}:recovery`,JSON.stringify({document:canvasPayload(document),baseVersion:writer?.version||1,dirty:writer?writer.needsSave(document):false}));
|
||||||
}
|
}
|
||||||
|
// 只在flush的try/finally窗口放开旧PATCH,其它写命令仍被api护栏拒绝。
|
||||||
migrationFlush.current=true;
|
migrationFlush.current=true;
|
||||||
try{await flush();}finally{migrationFlush.current=false;}
|
try{await flush();}finally{migrationFlush.current=false;}
|
||||||
if(!mounted.current||migration&&!migration.isCurrentIdentity())throw new Error('identity_changed');
|
if(!mounted.current||migration&&!migration.isCurrentIdentity())throw new Error('identity_changed');
|
||||||
@@ -255,15 +318,19 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
localStorage.setItem(`endoleap_canvas_v1:${workspace}:${boardId}:recovery`,JSON.stringify({document:canvasPayload(document),baseVersion:writer?.version||1,dirty:false}));
|
localStorage.setItem(`endoleap_canvas_v1:${workspace}:${boardId}:recovery`,JSON.stringify({document:canvasPayload(document),baseVersion:writer?.version||1,dirty:false}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/** 旧版内存独占执行器,阻断冲突准入并发布busy;异常记error后继续抛出,finally可靠释放锁。
|
||||||
|
* 它不是跨标签页锁,也不提供操作的整批服务端回滚。 */
|
||||||
async function exclusive<T>(operation: () => Promise<T>) {
|
async function exclusive<T>(operation: () => Promise<T>) {
|
||||||
if (migrationBlocked() || locked.current || pause.current || members.current.length) throw new Error("canvas_busy");
|
if (migrationBlocked() || locked.current || pause.current || members.current.length) throw new Error("canvas_busy");
|
||||||
locked.current = true; setBusy(true);
|
locked.current = true; setBusy(true);
|
||||||
try { return await operation(); } catch (error) { setError(error instanceof Error ? error.message : "request_failed"); throw error; }
|
try { return await operation(); } catch (error) { setError(error instanceof Error ? error.message : "request_failed"); throw error; }
|
||||||
finally { locked.current = false; if (mounted.current) setBusy(false); }
|
finally { locked.current = false; if (mounted.current) setBusy(false); }
|
||||||
}
|
}
|
||||||
|
/** 服务端快照更新时恢复本地选中标记,避免结构事务结果抹掉当前视图选择。 */
|
||||||
function keepSelection(document: CanvasDocument, local?: CanvasDocument): CanvasDocument {
|
function keepSelection(document: CanvasDocument, local?: CanvasDocument): CanvasDocument {
|
||||||
return { ...document, nodes: document.nodes.map((node) => ({ ...node, selected: local?.nodes.find((item) => item.id === node.id)?.selected })), edges: document.edges.map((edge) => ({ ...edge, selected: local?.edges.find((item) => item.id === edge.id)?.selected })) };
|
return { ...document, nodes: document.nodes.map((node) => ({ ...node, selected: local?.nodes.find((item) => item.id === node.id)?.selected })), edges: document.edges.map((edge) => ({ ...edge, selected: local?.edges.find((item) => item.id === edge.id)?.selected })) };
|
||||||
}
|
}
|
||||||
|
/** 汇总命令返回的各类快照,按boardID去重,基于旧ACK做三方合并再安装新基线。 */
|
||||||
function accept(result: CanvasCommandResult) {
|
function accept(result: CanvasCommandResult) {
|
||||||
const next = new Map(current.current);
|
const next = new Map(current.current);
|
||||||
const values = [...new Map([...(result.parent ? [result.parent] : []), ...(result.child ? [result.child] : []), ...(result.snapshots || []), ...(result.children || [])].map((value)=>[value.board_id,value])).values()];
|
const values = [...new Map([...(result.parent ? [result.parent] : []), ...(result.child ? [result.child] : []), ...(result.snapshots || []), ...(result.children || [])].map((value)=>[value.board_id,value])).values()];
|
||||||
@@ -272,6 +339,8 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
const merged=local&&base?mergeCanvasDocuments(base,local,decoded.document):decoded.document;
|
const merged=local&&base?mergeCanvasDocuments(base,local,decoded.document):decoded.document;
|
||||||
install(value.board_id,decoded);next.set(value.board_id,keepSelection(merged,local));
|
install(value.board_id,decoded);next.set(value.board_id,keepSelection(merged,local));
|
||||||
}
|
}
|
||||||
|
// 子图归档后,将仍在内存上传的节点及相关边投到父画布,避免服务端快照中没有的占位被丢弃。
|
||||||
|
// 其余已归档文档及writer从当前表移除,不在这里删除上传任务的原文件。
|
||||||
for (const id of result.archived_board_ids || []) {
|
for (const id of result.archived_board_ids || []) {
|
||||||
const local=current.current.get(id);
|
const local=current.current.get(id);
|
||||||
const owner=[...current.current].find(([,doc])=>doc.nodes.some((node)=>node.data.subgraph?.boardId===id));
|
const owner=[...current.current].find(([,doc])=>doc.nodes.some((node)=>node.data.subgraph?.boardId===id));
|
||||||
@@ -286,6 +355,8 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
publish(next);
|
publish(next);
|
||||||
return [...new Set(values.map((value) => value.board_id))];
|
return [...new Set(values.map((value) => value.board_id))];
|
||||||
}
|
}
|
||||||
|
/** 结构/AI等旧命令入口:加载参与writer、flush,再冻结expected_versions、If-Match和幂等key。
|
||||||
|
* execute闭包在不确定失败后复用同一body/key/version;这些恢复信息只在内存,不保证刷新后继续。 */
|
||||||
async function command(boardId: string, path: string, payload: Record<string, unknown>, participants?: string[], record = true, versionBoard = boardId) {
|
async function command(boardId: string, path: string, payload: Record<string, unknown>, participants?: string[], record = true, versionBoard = boardId) {
|
||||||
if (retryOperation.current) throw new Error("canvas_busy");
|
if (retryOperation.current) throw new Error("canvas_busy");
|
||||||
return exclusive(async () => {
|
return exclusive(async () => {
|
||||||
@@ -295,21 +366,25 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
await flush();
|
await flush();
|
||||||
const body = { ...payload, ...(participants ? { expected_versions: Object.fromEntries(participants.map((id) => [id, writers.current.get(id)?.version])) } : {}) };
|
const body = { ...payload, ...(participants ? { expected_versions: Object.fromEntries(participants.map((id) => [id, writers.current.get(id)?.version])) } : {}) };
|
||||||
const key = crypto.randomUUID(), version = writers.current.get(versionBoard)?.version || 1;
|
const key = crypto.randomUUID(), version = writers.current.get(versionBoard)?.version || 1;
|
||||||
|
/** 发送、采用回执、按需补读目标快照,并把有transaction_id的结果记入服务端事务历史。 */
|
||||||
const execute = async (): Promise<CanvasCommandResult> => {
|
const execute = async (): Promise<CanvasCommandResult> => {
|
||||||
try {
|
try {
|
||||||
const result = await api<CanvasCommandResult>(canvasPath(workspace, boardId) + "/" + path, { method: "POST", headers: { Accept: CANVAS_ACCEPT, "If-Match": `"${version}"`, "Idempotency-Key": key }, body: JSON.stringify(body) });
|
const result = await api<CanvasCommandResult>(canvasPath(workspace, boardId) + "/" + path, { method: "POST", headers: { Accept: CANVAS_ACCEPT, "If-Match": `"${version}"`, "Idempotency-Key": key }, body: JSON.stringify(body) });
|
||||||
const changed = accept(result);
|
const changed = accept(result);
|
||||||
|
// 改变子图/事务后通知侧栏刷新目录;没有快照但有版本结果时补读并保留期间的本地编辑。
|
||||||
if (path.startsWith("subgraphs") || path.startsWith("transactions/")) window.dispatchEvent(new window.CustomEvent("endoleap:board-directory-changed", { detail: { workspace } }));
|
if (path.startsWith("subgraphs") || path.startsWith("transactions/")) window.dispatchEvent(new window.CustomEvent("endoleap:board-directory-changed", { detail: { workspace } }));
|
||||||
if (!changed.length && result.canvas_version) {
|
if (!changed.length && result.canvas_version) {
|
||||||
const target=typeof result.board_id === "string"?result.board_id:boardId,remote=await read(target),local=current.current.get(target),base=writers.current.get(target)?.document;
|
const target=typeof result.board_id === "string"?result.board_id:boardId,remote=await read(target),local=current.current.get(target),base=writers.current.get(target)?.document;
|
||||||
const merged=base&&local?mergeCanvasDocuments(base,local,remote.document):remote.document;
|
const merged=base&&local?mergeCanvasDocuments(base,local,remote.document):remote.document;
|
||||||
install(target,remote);publish(new Map(current.current).set(target,keepSelection(merged,local)));
|
install(target,remote);publish(new Map(current.current).set(target,keepSelection(merged,local)));
|
||||||
}
|
}
|
||||||
|
// record=false用于undo/redo等已有历史流程,避免将历史遍历再次当新操作压栈。
|
||||||
if (record && result.transaction_id) { undo.current.push({ boardId, path, payload, id: result.transaction_id, participants: changed }); redo.current = []; tick((v) => v + 1); }
|
if (record && result.transaction_id) { undo.current.push({ boardId, path, payload, id: result.transaction_id, participants: changed }); redo.current = []; tick((v) => v + 1); }
|
||||||
retryOperation.current = null; setPendingCommand(false); setError("");
|
retryOperation.current = null; setPendingCommand(false); setError("");
|
||||||
return result;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const code = error instanceof Error ? error.message : "request_failed";
|
const code = error instanceof Error ? error.message : "request_failed";
|
||||||
|
// 网络/上游/解码等不确定失败保留execute并阻断普通编辑;确定拒绝清重试入口,错误仍交调用方处理。
|
||||||
if (error instanceof TypeError || error instanceof ApiError && error.status >= 500 || ["upstream_timeout", "upstream_unavailable", "request_failed", "Failed to fetch", "internal_error", "invalid_canvas_snapshot"].includes(code)) { retryOperation.current = execute; setPendingCommand(true); }
|
if (error instanceof TypeError || error instanceof ApiError && error.status >= 500 || ["upstream_timeout", "upstream_unavailable", "request_failed", "Failed to fetch", "internal_error", "invalid_canvas_snapshot"].includes(code)) { retryOperation.current = execute; setPendingCommand(true); }
|
||||||
else { retryOperation.current = null; setPendingCommand(false); }
|
else { retryOperation.current = null; setPendingCommand(false); }
|
||||||
throw error;
|
throw error;
|
||||||
@@ -320,12 +395,15 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
}
|
}
|
||||||
// Ownership changes pause autosaves, not unrelated local editing. Server
|
// Ownership changes pause autosaves, not unrelated local editing. Server
|
||||||
// acknowledgements merge against the persisted base, preserving intervening edits.
|
// acknowledgements merge against the persisted base, preserving intervening edits.
|
||||||
|
/** 成员队列只跑队首;归属移动期间暂停autosave,允许不相关本地编辑,结果按捕获ACK合并。
|
||||||
|
* 只有成功才shift并resolve;失败任务留队首供重试,Promise不在失败时假装完成。 */
|
||||||
async function runMembers() {
|
async function runMembers() {
|
||||||
if (migrationBlocked() || memberRunning.current || !members.current.length) return;
|
if (migrationBlocked() || memberRunning.current || !members.current.length) return;
|
||||||
const job = members.current[0]; memberRunning.current = true; job.error = undefined; showMembers();
|
const job = members.current[0]; memberRunning.current = true; job.error = undefined; showMembers();
|
||||||
try {
|
try {
|
||||||
if (!job.run) {
|
if (!job.run) {
|
||||||
for (const id of job.participants) if (!writers.current.has(id)) await ensure(id);
|
for (const id of job.participants) if (!writers.current.has(id)) await ensure(id);
|
||||||
|
// 412等确定冲突后的重新准备:读参与快照,先三方合并本地变化,再更新各writer基线。
|
||||||
if (job.refresh) {
|
if (job.refresh) {
|
||||||
const refreshed = await Promise.all(job.participants.map(async (id) => [id, await read(id)] as const));
|
const refreshed = await Promise.all(job.participants.map(async (id) => [id, await read(id)] as const));
|
||||||
const next = new Map(current.current);
|
const next = new Map(current.current);
|
||||||
@@ -336,6 +414,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
for (const [id, remote] of refreshed) install(id, remote);
|
for (const [id, remote] of refreshed) install(id, remote);
|
||||||
publish(next); job.refresh = false;
|
publish(next); job.refresh = false;
|
||||||
}
|
}
|
||||||
|
// 支持坐标时flush延后待移动节点位置;否则先按旧保存行为排空,再捕获参与文档作为合并基线。
|
||||||
const atomic = await supportsMemberPositions();
|
const atomic = await supportsMemberPositions();
|
||||||
await flush(atomic === true);
|
await flush(atomic === true);
|
||||||
const bases = new Map(job.participants.map((id) => [id, writers.current.get(id)!.document]));
|
const bases = new Map(job.participants.map((id) => [id, writers.current.get(id)!.document]));
|
||||||
@@ -344,17 +423,22 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
const node = source.nodes.find((node) => node.id === id); if (!node) throw new Error("invalid_reference");
|
const node = source.nodes.find((node) => node.id === id); if (!node) throw new Error("invalid_reference");
|
||||||
return [id, node.position];
|
return [id, node.position];
|
||||||
}));
|
}));
|
||||||
|
// 请求内容含参与版本和可选局部坐标;创建job.run后重试不得换body或幂等key,除非确定原请求未应用。
|
||||||
const body = JSON.stringify({ source_board_id: job.source, target_board_id: job.target, node_ids: job.ids, ...(atomic ? { positions } : {}),
|
const body = JSON.stringify({ source_board_id: job.source, target_board_id: job.target, node_ids: job.ids, ...(atomic ? { positions } : {}),
|
||||||
expected_versions: Object.fromEntries(job.participants.map((id) => [id, writers.current.get(id)!.version])) });
|
expected_versions: Object.fromEntries(job.participants.map((id) => [id, writers.current.get(id)!.version])) });
|
||||||
const key = crypto.randomUUID(), historyIndex = undo.current.length;
|
const key = crypto.randomUUID(), historyIndex = undo.current.length;
|
||||||
|
/** 一次准备生成的可重试闭包;要求回执覆盖所有参与画布,不能凭缺失快照移动本地owner。 */
|
||||||
job.run = async () => {
|
job.run = async () => {
|
||||||
const result = await api<CanvasCommandResult>(canvasPath(workspace, job.parent) + `/subgraphs/${job.frame}/members`, {
|
const result = await api<CanvasCommandResult>(canvasPath(workspace, job.parent) + `/subgraphs/${job.frame}/members`, {
|
||||||
method: "POST", headers: { Accept: CANVAS_ACCEPT, "Idempotency-Key": key }, body });
|
method: "POST", headers: { Accept: CANVAS_ACCEPT, "Idempotency-Key": key }, body });
|
||||||
const snapshots = [...(result.parent ? [result.parent] : []), ...(result.snapshots || [])];
|
const snapshots = [...(result.parent ? [result.parent] : []), ...(result.snapshots || [])];
|
||||||
const values = new Map(snapshots.map((value) => [value.board_id, { ...decodeSnapshot(value), board_id: value.board_id }]));
|
const values = new Map(snapshots.map((value) => [value.board_id, { ...decodeSnapshot(value), board_id: value.board_id }]));
|
||||||
if (!job.participants.every((id) => values.has(id))) throw new Error("invalid_canvas_snapshot");
|
if (!job.participants.every((id) => values.has(id))) throw new Error("invalid_canvas_snapshot");
|
||||||
|
/** 移动结果已含新坐标,合并前只把源节点暂存位置还原到基线,避免重复施加坐标变化。 */
|
||||||
const normalize = (id: string, local: CanvasDocument) => id !== job.source ? local : { ...local, nodes: local.nodes.map((node) => job.ids.includes(node.id) ? { ...node, position: bases.get(id)!.nodes.find((item) => item.id === node.id)!.position } : node) };
|
const normalize = (id: string, local: CanvasDocument) => id !== job.source ? local : { ...local, nodes: local.nodes.map((node) => job.ids.includes(node.id) ? { ...node, position: bases.get(id)!.nodes.find((item) => item.id === node.id)!.position } : node) };
|
||||||
|
/** 参与画布基于原ACK+归一化本地内容+返回快照重放,未参与文档原样保留。 */
|
||||||
const rebaseLocal=(id:string,doc:CanvasDocument)=>values.has(id)?mergeCanvasDocuments(bases.get(id)!,normalize(id,doc),values.get(id)!.document):doc;
|
const rebaseLocal=(id:string,doc:CanvasDocument)=>values.has(id)?mergeCanvasDocuments(bases.get(id)!,normalize(id,doc),values.get(id)!.document):doc;
|
||||||
|
// 请求期间新增本地历史也基于新owner结果调整;开始前历史和服务端事务条目保持原语义。
|
||||||
const rebasedHistory = undo.current.map((entry,index)=>index<historyIndex||"id" in entry?entry:{...entry,before:rebaseLocal(entry.boardId,entry.before),...(entry.related?{related:new Map([...entry.related].map(([id,doc])=>[id,rebaseLocal(id,doc)]))}:{})});
|
const rebasedHistory = undo.current.map((entry,index)=>index<historyIndex||"id" in entry?entry:{...entry,before:rebaseLocal(entry.boardId,entry.before),...(entry.related?{related:new Map([...entry.related].map(([id,doc])=>[id,rebaseLocal(id,doc)]))}:{})});
|
||||||
const next = new Map(current.current);
|
const next = new Map(current.current);
|
||||||
for (const [id, value] of values) {
|
for (const [id, value] of values) {
|
||||||
@@ -369,6 +453,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
for (const [id, value] of values) install(id, value);
|
for (const [id, value] of values) install(id, value);
|
||||||
publish(next);
|
publish(next);
|
||||||
undo.current = rebasedHistory;
|
undo.current = rebasedHistory;
|
||||||
|
// 将迁移事务插回开始时的historyIndex,保留请求期间后来编辑的顺序,并清除旧redo。
|
||||||
if (result.transaction_id) { undo.current.splice(historyIndex, 0, { boardId: job.parent, path: `subgraphs/${job.frame}/members`, payload: { source_board_id: job.source, target_board_id: job.target, node_ids: job.ids, positions }, id: result.transaction_id, participants: [...values.keys()] }); redo.current = []; }
|
if (result.transaction_id) { undo.current.splice(historyIndex, 0, { boardId: job.parent, path: `subgraphs/${job.frame}/members`, payload: { source_board_id: job.source, target_board_id: job.target, node_ids: job.ids, positions }, id: result.transaction_id, participants: [...values.keys()] }); redo.current = []; }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -378,6 +463,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
job.error = error instanceof Error ? error.message : "request_failed";
|
job.error = error instanceof Error ? error.message : "request_failed";
|
||||||
// A definite rejection performed zero writes. A retry may prepare fresh
|
// A definite rejection performed zero writes. A retry may prepare fresh
|
||||||
// versions; ambiguous transport failures must retain the exact body/key.
|
// versions; ambiguous transport failures must retain the exact body/key.
|
||||||
|
// 确定拒绝可清冻结闭包重新准备;412还需刷新版本。不确定传输失败继续保留原job.run。
|
||||||
if (error instanceof ApiError && error.status < 500) { job.run = undefined; job.refresh = error.status === 412; }
|
if (error instanceof ApiError && error.status < 500) { job.run = undefined; job.refresh = error.status === 412; }
|
||||||
showMembers();
|
showMembers();
|
||||||
} finally {
|
} finally {
|
||||||
@@ -385,24 +471,31 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
if (members.current.length && !members.current[0].error) void runMembers();
|
if (members.current.length && !members.current[0].error) void runMembers();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/** 检查准入和重叠成员任务后入FIFO队列;返回Promise由成功出队时resolve,错误在memberJobs中供UI重试。 */
|
||||||
function moveMembers(parent: string, frame: string, source: string, target: string, ids: string[], participants: string[]) {
|
function moveMembers(parent: string, frame: string, source: string, target: string, ids: string[], participants: string[]) {
|
||||||
if (migrationBlocked() || locked.current || retryOperation.current || pause.current || members.current.some((job) => job.ids.some((id) => ids.includes(id)) && [job.source, job.target].includes(source))) return Promise.reject(new Error("canvas_busy"));
|
if (migrationBlocked() || locked.current || retryOperation.current || pause.current || members.current.some((job) => job.ids.some((id) => ids.includes(id)) && [job.source, job.target].includes(source))) return Promise.reject(new Error("canvas_busy"));
|
||||||
return new Promise<void>((resolve) => {
|
return new Promise<void>((resolve) => {
|
||||||
members.current.push({ parent, frame, source, target, ids, participants, resolve }); showMembers(); void runMembers();
|
members.current.push({ parent, frame, source, target, ids, participants, resolve }); showMembers(); void runMembers();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
/** 将上传资源/尺寸绑定到所有当前文档及本地历史,避免撤销恢复旧Blob占位。
|
||||||
|
* 无asset时保留pendingUpload;尺寸仅在纯图片仍为320×240默认值时采用,不覆盖用户已调整大小。 */
|
||||||
function resolveImageUpload(id: string, asset?: { url: string; id: string }, size?: {width:number;height:number}) {
|
function resolveImageUpload(id: string, asset?: { url: string; id: string }, size?: {width:number;height:number}) {
|
||||||
if(migrationBlocked())return;
|
if(migrationBlocked())return;
|
||||||
|
/** 只匹配pendingUpload身份,移除或保留占位标记,并按文档schema选择是否写assetId。 */
|
||||||
const resolve = (document: CanvasDocument): CanvasDocument => ({ ...document, nodes: document.nodes.map((node) => {
|
const resolve = (document: CanvasDocument): CanvasDocument => ({ ...document, nodes: document.nodes.map((node) => {
|
||||||
if (node.pendingUpload !== id) return node;
|
if (node.pendingUpload !== id) return node;
|
||||||
const fitted=node.data.kind==="plain-image"&&node.width===320&&node.height===240?size:undefined;
|
const fitted=node.data.kind==="plain-image"&&node.width===320&&node.height===240?size:undefined;
|
||||||
const {pendingUpload,...ready}=node;
|
const {pendingUpload,...ready}=node;
|
||||||
return { ...ready, ...(!asset?{pendingUpload}:{}), ...(fitted?{...fitted,style:{...ready.style,...fitted}}:{}), data: { ...ready.data, ...(asset?{src:asset.url,...(document.schema_version===2?{assetId:asset.id}:{})}:{}) } };
|
return { ...ready, ...(!asset?{pendingUpload}:{}), ...(fitted?{...fitted,style:{...ready.style,...fitted}}:{}), data: { ...ready.data, ...(asset?{src:asset.url,...(document.schema_version===2?{assetId:asset.id}:{})}:{}) } };
|
||||||
}) });
|
}) });
|
||||||
|
/** 仅改本地快照历史(含related),服务端事务条目仍由服务端重放解释。 */
|
||||||
const rebase = (entry: Entry): Entry => "id" in entry ? entry : { ...entry, before: resolve(entry.before), ...(entry.related ? {related:new Map([...entry.related].map(([id,doc])=>[id,resolve(doc)]))} : {}) };
|
const rebase = (entry: Entry): Entry => "id" in entry ? entry : { ...entry, before: resolve(entry.before), ...(entry.related ? {related:new Map([...entry.related].map(([id,doc])=>[id,resolve(doc)]))} : {}) };
|
||||||
undo.current = undo.current.map(rebase); redo.current = redo.current.map(rebase);
|
undo.current = undo.current.map(rebase); redo.current = redo.current.map(rebase);
|
||||||
publish(new Map([...current.current].map(([board,doc])=>[board,resolve(doc)])));
|
publish(new Map([...current.current].map(([board,doc])=>[board,resolve(doc)])));
|
||||||
}
|
}
|
||||||
|
/** 未上传且无关联边的图片可先在内存跨分区移动;校验容量/ID后按两owner原点和scale换算。
|
||||||
|
* 保存双画布before及pendingMove历史,上传完成后若进入服务端,撤销可能需要真实成员事务。 */
|
||||||
function movePendingImage(source: string, target: string, id: string) {
|
function movePendingImage(source: string, target: string, id: string) {
|
||||||
if(migrationBlocked())throw new Error("canvas_busy");
|
if(migrationBlocked())throw new Error("canvas_busy");
|
||||||
const from = current.current.get(source)!, to = current.current.get(target)!;
|
const from = current.current.get(source)!, to = current.current.get(target)!;
|
||||||
@@ -413,6 +506,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
undo.current.push({boardId:source,before:from,related:new Map([[target,to]]),pendingMove:{id,source,target}});redo.current=[];
|
undo.current.push({boardId:source,before:from,related:new Map([[target,to]]),pendingMove:{id,source,target}});redo.current=[];
|
||||||
publish(new Map(current.current).set(source,{...from,nodes:from.nodes.filter((node)=>node.id!==id)}).set(target,{...to,nodes:[...to.nodes,moved]}));
|
publish(new Map(current.current).set(source,{...from,nodes:from.nodes.filter((node)=>node.id!==id)}).set(target,{...to,nodes:[...to.nodes,moved]}));
|
||||||
}
|
}
|
||||||
|
/** 独占等待writer停止后读新快照并三方合并;内容指纹改变才记本地历史,再安装新ACK。 */
|
||||||
async function refresh(boardId: string) {
|
async function refresh(boardId: string) {
|
||||||
return exclusive(async () => {
|
return exclusive(async () => {
|
||||||
const writer = writers.current.get(boardId); if (!writer) return;
|
const writer = writers.current.get(boardId); if (!writer) return;
|
||||||
@@ -423,6 +517,8 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
install(boardId, remote); publish(new Map(current.current).set(boardId, merged));
|
install(boardId, remote); publish(new Map(current.current).set(boardId, merged));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
/** 显式采用生成结果前,针对目标节点把基线text/src/assetId/ai对齐到远端,再合并其它本地编辑。
|
||||||
|
* 合并结果先排空保存,后续apply命令才能在明确版本上覆盖目标;此方法本身不发送生成结果采用请求。 */
|
||||||
async function prepareApply(boardId: string, nodeId: string) {
|
async function prepareApply(boardId: string, nodeId: string) {
|
||||||
await exclusive(async () => {
|
await exclusive(async () => {
|
||||||
const writer = writers.current.get(boardId); if (!writer) throw new Error("invalid_reference");
|
const writer = writers.current.get(boardId); if (!writer) throw new Error("invalid_reference");
|
||||||
@@ -436,12 +532,17 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
setError("");
|
setError("");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
/** 查看栈顶并检查准入,成功后才移动栈项;本地条目替换before,事务条目调用服务端undo或重做。
|
||||||
|
* 重做可能创建新子board,使用alias将后续历史引用转到新身份,避免继续操作已归档旧子图。 */
|
||||||
async function undoAction(isRedo = false) {
|
async function undoAction(isRedo = false) {
|
||||||
const stack = isRedo ? redo.current : undo.current, destination = isRedo ? undo.current : redo.current;
|
const stack = isRedo ? redo.current : undo.current, destination = isRedo ? undo.current : redo.current;
|
||||||
const original = stack.at(-1); if (!original || migrationBlocked() || locked.current || retryOperation.current || members.current.length) return;
|
const original = stack.at(-1); if (!original || migrationBlocked() || locked.current || retryOperation.current || members.current.length) return;
|
||||||
|
/** 沿别名链解析最新boardID并防循环;只用于历史重放,不篡改任意元素ID。 */
|
||||||
const alias = (id: string) => { const seen = new Set<string>(); while (boardAliases.current.has(id) && !seen.has(id)) { seen.add(id); id = boardAliases.current.get(id)!; } return id; };
|
const alias = (id: string) => { const seen = new Set<string>(); while (boardAliases.current.has(id) && !seen.has(id)) { seen.add(id); id = boardAliases.current.get(id)!; } return id; };
|
||||||
|
/** 重做本地快照时更新子图board引用,其它节点内容保留。 */
|
||||||
const remapDocument = (document: CanvasDocument) => ({ ...document, nodes: document.nodes.map((node) => node.data.subgraph ? { ...node, data: { ...node.data, subgraph: { boardId: alias(node.data.subgraph.boardId) } } } : node) });
|
const remapDocument = (document: CanvasDocument) => ({ ...document, nodes: document.nodes.map((node) => node.data.subgraph ? { ...node, data: { ...node.data, subgraph: { boardId: alias(node.data.subgraph.boardId) } } } : node) });
|
||||||
const entry: Entry = isRedo ? "id" in original ? { ...original, boardId: alias(original.boardId), participants: original.participants.map(alias), payload: { ...original.payload, ...(typeof original.payload.source_board_id === "string" ? { source_board_id: alias(original.payload.source_board_id) } : {}), ...(typeof original.payload.target_board_id === "string" ? { target_board_id: alias(original.payload.target_board_id) } : {}), ...Object.fromEntries(["source", "target"].flatMap((key) => { const endpoint = original.payload[key] as { board_id?: string } | undefined; return endpoint?.board_id ? [[key, { ...endpoint, board_id: alias(endpoint.board_id) }]] : []; })) } } : { ...original, boardId: alias(original.boardId), before: remapDocument(original.before), ...(original.related?{related:new Map([...original.related].map(([id,doc])=>[alias(id),remapDocument(doc)]))}:{}) } : original;
|
const entry: Entry = isRedo ? "id" in original ? { ...original, boardId: alias(original.boardId), participants: original.participants.map(alias), payload: { ...original.payload, ...(typeof original.payload.source_board_id === "string" ? { source_board_id: alias(original.payload.source_board_id) } : {}), ...(typeof original.payload.target_board_id === "string" ? { target_board_id: alias(original.payload.target_board_id) } : {}), ...Object.fromEntries(["source", "target"].flatMap((key) => { const endpoint = original.payload[key] as { board_id?: string } | undefined; return endpoint?.board_id ? [[key, { ...endpoint, board_id: alias(endpoint.board_id) }]] : []; })) } } : { ...original, boardId: alias(original.boardId), before: remapDocument(original.before), ...(original.related?{related:new Map([...original.related].map(([id,doc])=>[alias(id),remapDocument(doc)]))}:{}) } : original;
|
||||||
|
// 待上传图片若已存在于writer基线,纯本地快照切换已不够,需按归属路径逐跳请求成员移动后再转栈。
|
||||||
if (!("id" in entry) && entry.pendingMove) {
|
if (!("id" in entry) && entry.pendingMove) {
|
||||||
const move=entry.pendingMove,desired=alias(isRedo?move.target:move.source);
|
const move=entry.pendingMove,desired=alias(isRedo?move.target:move.source);
|
||||||
const owner=[...current.current].find(([,doc])=>doc.nodes.some((node)=>node.id===move.id));
|
const owner=[...current.current].find(([,doc])=>doc.nodes.some((node)=>node.id===move.id));
|
||||||
@@ -452,6 +553,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
stack.pop();destination.push(entry);tick((v)=>v+1);return;
|
stack.pop();destination.push(entry);tick((v)=>v+1);return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 服务端事务撤销调用transactions/{id}/undo;重做执行原命令并保存新的事务ID/参与快照身份。
|
||||||
if ("id" in entry) {
|
if ("id" in entry) {
|
||||||
if (isRedo) {
|
if (isRedo) {
|
||||||
const result = await command(entry.boardId, entry.path, entry.payload, entry.path === "subgraphs" ? undefined : entry.participants, false);
|
const result = await command(entry.boardId, entry.path, entry.payload, entry.path === "subgraphs" ? undefined : entry.participants, false);
|
||||||
@@ -464,6 +566,7 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
await command(entry.boardId, `transactions/${entry.id}/undo`, {}, entry.participants, false);
|
await command(entry.boardId, `transactions/${entry.id}/undo`, {}, entry.participants, false);
|
||||||
stack.pop(); destination.push(entry);
|
stack.pop(); destination.push(entry);
|
||||||
}
|
}
|
||||||
|
// 普通本地历史用当前文档作为反向条目,连同related画布一起发布,保证下一次redo可还原。
|
||||||
} else {
|
} else {
|
||||||
const before = current.current.get(entry.boardId); if (!before) return;
|
const before = current.current.get(entry.boardId); if (!before) return;
|
||||||
const next=new Map(current.current).set(entry.boardId, entry.before), related=new Map<string,CanvasDocument>();
|
const next=new Map(current.current).set(entry.boardId, entry.before), related=new Map<string,CanvasDocument>();
|
||||||
@@ -472,6 +575,9 @@ export function useCanvasTree(root: string, workspace: string, initial: CanvasDo
|
|||||||
}
|
}
|
||||||
tick((v) => v + 1);
|
tick((v) => v + 1);
|
||||||
}
|
}
|
||||||
|
/** 重试普通writer并触发子图读取effect;不在这里自动重发成员任务或未确认command,它们有各自入口。 */
|
||||||
const retry = async () => { setError(""); setRetryLoad((v) => v + 1); for (const writer of writers.current.values()) await writer.retry(); };
|
const retry = async () => { setError(""); setRetryLoad((v) => v + 1); for (const writer of writers.current.values()) await writer.retry(); };
|
||||||
|
// 对外暴露投影、动作、恢复、事务及writer引用,旧版UI依赖此组合接口;busy合并独占、待确认命令与迁移门闩。
|
||||||
|
// transactionBusy/canUndo/canRedo反映成员队列与栈是否有项,最终undoAction仍再次检查实际准入。
|
||||||
return { migrationHeld,setMigrationHeld,prepareMigration,isMigrationHeld:migrationBlocked, documents, current, views, resolveImageUpload, movePendingImage, memberJobs, protectedNodes, setDragging, moveMembers, retryMembers: () => void runMembers(), transactionBusy: !!memberJobs.length, pendingCommand, retryPending: () => retryOperation.current ? exclusive(retryOperation.current) : Promise.resolve(null), prepareApply, recoveries, resolveRecovery, ensure, exportDocuments, dispatch, nodeAction, nodesChanged, edgesChanged, patchEdge, select, flush, command, refresh, read, busy: busy || pendingCommand || migrationHeld, error, status, retry, undo: () => undoAction(), redo: () => undoAction(true), canUndo: !memberJobs.length && !!undo.current.length, canRedo: !memberJobs.length && !!redo.current.length, writers, rootDocument: documents.get(root)!, setError };
|
return { migrationHeld,setMigrationHeld,prepareMigration,isMigrationHeld:migrationBlocked, documents, current, views, resolveImageUpload, movePendingImage, memberJobs, protectedNodes, setDragging, moveMembers, retryMembers: () => void runMembers(), transactionBusy: !!memberJobs.length, pendingCommand, retryPending: () => retryOperation.current ? exclusive(retryOperation.current) : Promise.resolve(null), prepareApply, recoveries, resolveRecovery, ensure, exportDocuments, dispatch, nodeAction, nodesChanged, edgesChanged, patchEdge, select, flush, command, refresh, read, busy: busy || pendingCommand || migrationHeld, error, status, retry, undo: () => undoAction(), redo: () => undoAction(true), canUndo: !memberJobs.length && !!undo.current.length, canRedo: !memberJobs.length && !!redo.current.length, writers, rootDocument: documents.get(root)!, setError };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* 旧编辑器的内存上传任务管理。原文件、Blob预览URL和AbortController随Hook挂载存活,资源上传成功后由commit绑定到本地节点。
|
||||||
|
* 这是可取消的页面内流程,没有持久文件仓库;卸载会中止上传并清理URL,不能承诺跨刷新继续上传。
|
||||||
|
*/
|
||||||
"use client";
|
"use client";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { uploadCanvasImage, type CanvasAsset } from "@/lib/canvas-assets";
|
import { uploadCanvasImage, type CanvasAsset } from "@/lib/canvas-assets";
|
||||||
import type { CanvasDocument, CanvasNode } from "@/lib/canvas";
|
import type { CanvasDocument, CanvasNode } from "@/lib/canvas";
|
||||||
|
/** draft指定节点归属与可选关联边,调用方负责先创建可编辑占位并正确处理提交时归属。 */
|
||||||
export type ImageUploadDraft = { owner: string; node: CanvasNode; edge?: CanvasDocument["edges"][number] };
|
export type ImageUploadDraft = { owner: string; node: CanvasNode; edge?: CanvasDocument["edges"][number] };
|
||||||
|
/** file保存原字节、localURL用于即时预览、key用于同任务重试幂等;ready可等待本地图片尺寸解码。 */
|
||||||
export type ImageUploadJob = ImageUploadDraft & { file: File; localURL: string; key: string; status: "uploading" | "failed" | "uploaded"; error?: string; controller: AbortController; ready?: Promise<void>; asset?: CanvasAsset };
|
export type ImageUploadJob = ImageUploadDraft & { file: File; localURL: string; key: string; status: "uploading" | "failed" | "uploaded"; error?: string; controller: AbortController; ready?: Promise<void>; asset?: CanvasAsset };
|
||||||
|
|
||||||
/** Uploads attach file references to existing editable local nodes; transient URLs never enter autosaves. */
|
/** Uploads attach file references to existing editable local nodes; transient URLs never enter autosaves. */
|
||||||
|
/** commit通过ref读取最新回调;pending按节点ID存任务,jobs数组只作React显示发布。 */
|
||||||
export function useImageUploads(workspace: string, commit: (draft: ImageUploadDraft, asset: CanvasAsset) => void) {
|
export function useImageUploads(workspace: string, commit: (draft: ImageUploadDraft, asset: CanvasAsset) => void) {
|
||||||
const pending = useRef(new Map<string, ImageUploadJob>());
|
const pending = useRef(new Map<string, ImageUploadJob>());
|
||||||
const [jobs, setJobs] = useState<ImageUploadJob[]>([]);
|
const [jobs, setJobs] = useState<ImageUploadJob[]>([]);
|
||||||
const mounted = useRef(true), onCommit = useRef(commit); onCommit.current = commit;
|
const mounted = useRef(true), onCommit = useRef(commit); onCommit.current = commit;
|
||||||
|
/** 挂载期间发布新的任务数组;任务对象仍是同一引用,字段更新后需调用changed触发显示。 */
|
||||||
const changed = () => { if (mounted.current) setJobs([...pending.current.values()]); };
|
const changed = () => { if (mounted.current) setJobs([...pending.current.values()]); };
|
||||||
|
/** 中止任务、释放预览URL并移出Map;并不在这里删除文档节点或服务端资源。 */
|
||||||
function remove(id: string) { const job = pending.current.get(id); if (!job) return; job.controller.abort(); URL.revokeObjectURL(job.localURL); pending.current.delete(id); changed(); }
|
function remove(id: string) { const job = pending.current.get(id); if (!job) return; job.controller.abort(); URL.revokeObjectURL(job.localURL); pending.current.delete(id); changed(); }
|
||||||
|
// 卸载统一abort并回收URL,清Map防止迟到上传结果提交;StrictMode重新挂载effect时复位mounted。
|
||||||
useEffect(() => { mounted.current = true; return () => { mounted.current = false; for (const job of pending.current.values()) { job.controller.abort(); URL.revokeObjectURL(job.localURL); } pending.current.clear(); }; }, []);
|
useEffect(() => { mounted.current = true; return () => { mounted.current = false; for (const job of pending.current.values()) { job.controller.abort(); URL.revokeObjectURL(job.localURL); } pending.current.clear(); }; }, []);
|
||||||
|
/** uploading状态防并发重试;开始新尝试前换controller并清错误,保留原幂等key。
|
||||||
|
* 上传与ready并行,二者都成功后才commit;commit抛错也会进入failed状态,允许再次处理。 */
|
||||||
async function run(job: ImageUploadJob) {
|
async function run(job: ImageUploadJob) {
|
||||||
if (job.status === "uploading") return;
|
if (job.status === "uploading") return;
|
||||||
job.status = "uploading"; job.error = undefined; job.controller = new AbortController(); changed();
|
job.status = "uploading"; job.error = undefined; job.controller = new AbortController(); changed();
|
||||||
try {
|
try {
|
||||||
const [asset] = await Promise.all([uploadCanvasImage(api, workspace, job.file, job.file.name, job.controller.signal, job.key), job.ready || Promise.resolve()]);
|
const [asset] = await Promise.all([uploadCanvasImage(api, workspace, job.file, job.file.name, job.controller.signal, job.key), job.ready || Promise.resolve()]);
|
||||||
|
// 结果返回后核对挂载、Map内仍是同一个job且未取消,旧任务不能写到后来同ID的新任务。
|
||||||
if (!mounted.current || pending.current.get(job.node.id) !== job || job.controller.signal.aborted) return;
|
if (!mounted.current || pending.current.get(job.node.id) !== job || job.controller.signal.aborted) return;
|
||||||
job.asset = asset; onCommit.current(job, asset); job.status = "uploaded"; changed();
|
job.asset = asset; onCommit.current(job, asset); job.status = "uploaded"; changed();
|
||||||
} catch (error) { if (mounted.current && pending.current.get(job.node.id) === job && !job.controller.signal.aborted) { job.status = "failed"; job.error = errorText(error); changed(); } }
|
} catch (error) { if (mounted.current && pending.current.get(job.node.id) === job && !job.controller.signal.aborted) { job.status = "failed"; job.error = errorText(error); changed(); } }
|
||||||
}
|
}
|
||||||
|
/** 先创建Blob URL并让调用方建立草稿,草稿构造失败立即释放URL;任务初始failed以便run统一转uploading。 */
|
||||||
function start(file: File, draft: (localURL: string) => ImageUploadDraft) {
|
function start(file: File, draft: (localURL: string) => ImageUploadDraft) {
|
||||||
const localURL = URL.createObjectURL(file);
|
const localURL = URL.createObjectURL(file);
|
||||||
let value: ImageUploadDraft;
|
let value: ImageUploadDraft;
|
||||||
@@ -30,18 +44,23 @@ export function useImageUploads(workspace: string, commit: (draft: ImageUploadDr
|
|||||||
const job: ImageUploadJob = { ...value, file, localURL, key: crypto.randomUUID(), status: "failed", controller: new AbortController() };
|
const job: ImageUploadJob = { ...value, file, localURL, key: crypto.randomUUID(), status: "failed", controller: new AbortController() };
|
||||||
pending.current.set(job.node.id, job); changed();
|
pending.current.set(job.node.id, job); changed();
|
||||||
// Browser decoding runs locally, concurrently with the original-byte upload.
|
// Browser decoding runs locally, concurrently with the original-byte upload.
|
||||||
|
// 纯图片并行解码自然尺寸,限制初始长宽不超过480(不主动放大),再分别设置至少24px的显示尺寸。
|
||||||
if (job.node.data.kind === "plain-image") {
|
if (job.node.data.kind === "plain-image") {
|
||||||
job.ready = new Promise<void>((resolve,reject) => {
|
job.ready = new Promise<void>((resolve,reject) => {
|
||||||
const image = new window.Image(); image.onload = () => {
|
const image = new window.Image(); image.onload = () => {
|
||||||
if (pending.current.get(job.node.id) !== job) { resolve(); return; }
|
if (pending.current.get(job.node.id) !== job) { resolve(); return; }
|
||||||
|
// 分别钳制到最小24可能改变极端长宽比;这里只初始化节点和style尺寸,不重编码上传文件。
|
||||||
const scale = Math.min(1,480/image.naturalWidth,480/image.naturalHeight);
|
const scale = Math.min(1,480/image.naturalWidth,480/image.naturalHeight);
|
||||||
const size = { width: Math.max(24,Math.round(image.naturalWidth*scale)), height: Math.max(24,Math.round(image.naturalHeight*scale)) };
|
const size = { width: Math.max(24,Math.round(image.naturalWidth*scale)), height: Math.max(24,Math.round(image.naturalHeight*scale)) };
|
||||||
job.node = { ...job.node, ...size, style: { ...job.node.style, ...size } }; changed(); resolve();
|
job.node = { ...job.node, ...size, style: { ...job.node.style, ...size } }; changed(); resolve();
|
||||||
}; image.onerror = () => reject(new Error("无法读取图片尺寸。")); image.src = localURL;
|
}; image.onerror = () => reject(new Error("无法读取图片尺寸。")); image.src = localURL;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// start同步返回任务对象,异步上传由run内部捕获失败,不要求调用方等待才显示占位。
|
||||||
void run(job);
|
void run(job);
|
||||||
return job;
|
return job;
|
||||||
}
|
}
|
||||||
|
// hasPending包含失败但不包含uploaded,active只看uploading;loaded仅在正式图片加载后移除已上传预览。
|
||||||
|
// retry复用job及幂等键;若ready曾拒绝,重试不会在这里重建尺寸解码Promise。
|
||||||
return { jobs, hasPending:()=>[...pending.current.values()].some(job=>job.status!=="uploaded"), active: jobs.some((job) => job.status === "uploading"), start, retry: (id: string) => { const job = pending.current.get(id); if (job) void run(job); }, remove, loaded: (id: string) => { if (pending.current.get(id)?.status === "uploaded") remove(id); } };
|
return { jobs, hasPending:()=>[...pending.current.values()].some(job=>job.status!=="uploaded"), active: jobs.some((job) => job.status === "uploading"), start, retry: (id: string) => { const job = pending.current.get(id); if (job) void run(job); }, remove, loaded: (id: string) => { if (pending.current.get(id)?.status === "uploaded") remove(id); } };
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user