feat(workspace): integrate persisted canvas, element editing and session renewal
This commit is contained in:
@@ -5,33 +5,41 @@ import {
|
||||
Background, BackgroundVariant, ConnectionLineType, ConnectionMode, ReactFlow, ReactFlowProvider, SelectionMode,
|
||||
addEdge, useReactFlow, useViewport, type Connection, type OnConnectEnd, type XYPosition,
|
||||
} from "@xyflow/react";
|
||||
import { Download, FileText, Hand, HelpCircle, ImagePlus, Maximize, Minus, MousePointer2, Plus, Redo2, Sparkles, StickyNote, Shapes, Type, Undo2, Upload } from "lucide-react";
|
||||
import { Download, FileText, Hand, HelpCircle, ImagePlus, Maximize, Minus, MousePointer2, Plus, Redo2, Sparkles, StickyNote, Shapes, Frame, Image as ImageIcon, Type, Undo2, Upload } from "lucide-react";
|
||||
import { useReducedMotion } from "motion/react";
|
||||
import toolbar from "@/components/ui/toolbar.module.css";
|
||||
import { IconButton } from "@/components/ui/icon-button";
|
||||
import { branchCanvasNode, canvasReducer, canvasStorageKey, decodeCanvas, emptyCanvas, makeCanvasNode, type CanvasHistory, type CanvasNode, type NodeDirection } from "@/lib/canvas";
|
||||
import { errorText } from "@/lib/api";
|
||||
import { readLocalRecovery, type CanvasSnapshot } from "@/lib/canvas-sync";
|
||||
import { useCanvasPersistence } from "./use-canvas-persistence";
|
||||
import type { Board } from "@/lib/workspace";
|
||||
import { CanvasEdge, CanvasConnectionLine } from "./canvas-edge";
|
||||
import { BranchMenu, type BranchRequest } from "./branch-menu";
|
||||
import { IconNode } from "./icon-node";
|
||||
import { IconPicker } from "./icon-picker";
|
||||
import type { TextStyle } from "@/lib/canvas-elements";
|
||||
import { DraftRecovery } from "./draft-recovery";
|
||||
import { FrameNode } from "./frame-node";
|
||||
import type { FrameLabelMode, TextStyle } from "@/lib/canvas-elements";
|
||||
import { PlainImageNode } from "./plain-image-node";
|
||||
import { PlainTextNode } from "./plain-text-node";
|
||||
import type { NodeTransform } from "@/lib/canvas-geometry";
|
||||
import { MaterialNode, NodeEditing } from "./material-node";
|
||||
import styles from "./canvas.module.css";
|
||||
|
||||
const nodeTypes = { material: MaterialNode, plainText: PlainTextNode, icon: IconNode };
|
||||
const edgeTypes = { default: CanvasEdge };
|
||||
const nodeTypes = { material: MaterialNode, plainText: PlainTextNode, icon: IconNode, frame: FrameNode, plainImage: PlainImageNode };
|
||||
|
||||
function CanvasEditor({ board }: { board: Board }) {
|
||||
function CanvasEditor({ board, snapshot }: { board: Board; snapshot?: CanvasSnapshot }) {
|
||||
const flow = useReactFlow<CanvasNode>();
|
||||
const { zoom } = useViewport();
|
||||
const reduceMotion = useReducedMotion();
|
||||
const storageKey = canvasStorageKey(board.workspace_id, board.id);
|
||||
const [initial] = useState(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem(storageKey);
|
||||
return { document: stored ? decodeCanvas(stored) : emptyCanvas(), error: "" };
|
||||
} catch { return { document: emptyCanvas(), error: "无法读取此浏览器的图谱草稿,可通过导入恢复备份。" }; }
|
||||
const local = readLocalRecovery(localStorage, storageKey, snapshot);
|
||||
return { document: snapshot?.document || local || emptyCanvas(), recovery: snapshot ? local : null, error: "" };
|
||||
} catch { return { document: snapshot?.document || emptyCanvas(), recovery: null, error: "无法读取此浏览器的图谱草稿,可通过导入恢复备份。" }; }
|
||||
});
|
||||
const [state, dispatch] = useReducer(canvasReducer, { past: [], present: initial.document, future: [] } satisfies CanvasHistory);
|
||||
const [tool, setTool] = useState<"select" | "hand">("select");
|
||||
@@ -39,12 +47,16 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
const [branchRequest, setBranchRequest] = useState<BranchRequest | null>(null);
|
||||
const [iconPicker, setIconPicker] = useState(false);
|
||||
const [rotating, setRotating] = useState<string | null>(null);
|
||||
const dragOrigins = useRef(new Map<string, XYPosition>());
|
||||
const draggingFrame = useRef(false);
|
||||
const connectionStart = useRef<{ id: string; direction: NodeDirection; point: XYPosition } | null>(null);
|
||||
const pendingImage = useRef<BranchRequest | null>(null);
|
||||
const closeBranch = useCallback(() => setBranchRequest(null), []);
|
||||
const imageKind = useRef<"image" | "plain-image">("image");
|
||||
const imageInput = useRef<HTMLInputElement>(null);
|
||||
const projectInput = useRef<HTMLInputElement>(null);
|
||||
const firstSave = useRef(true);
|
||||
const [recovery, setRecovery] = useState(initial.recovery);
|
||||
const sync = useCanvasPersistence(state.present, board.workspace_id, board.id, storageKey, snapshot, Boolean(recovery));
|
||||
useEffect(() => {
|
||||
const input = imageInput.current;
|
||||
const cancel = () => { pendingImage.current = null; };
|
||||
@@ -54,28 +66,10 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
const { nodes, edges } = state.present;
|
||||
const duration = reduceMotion ? 0 : 180;
|
||||
|
||||
useEffect(() => {
|
||||
if (firstSave.current) { firstSave.current = false; return; }
|
||||
const timeout = setTimeout(() => {
|
||||
try {
|
||||
localStorage.setItem(storageKey, JSON.stringify(decodeCanvas(JSON.stringify(state.present))));
|
||||
} catch { setError("浏览器存储空间不足或暂不可用,请导出图谱备份。当前内容仍保留在画布中。"); }
|
||||
}, 400);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [state.present, storageKey]);
|
||||
|
||||
// Flush the latest view and nodes when navigating away before the debounce runs.
|
||||
const latest = useRef(state.present);
|
||||
latest.current = state.present;
|
||||
useEffect(() => {
|
||||
const flush = () => {
|
||||
try { localStorage.setItem(storageKey, JSON.stringify(decodeCanvas(JSON.stringify(latest.current)))); }
|
||||
catch { /* The editor already reports storage failures while it is open. */ }
|
||||
};
|
||||
window.addEventListener("pagehide", flush);
|
||||
return () => { window.removeEventListener("pagehide", flush); flush(); };
|
||||
}, [storageKey]);
|
||||
|
||||
const select = useCallback((id: string) => dispatch({ type: "nodes", changes: latest.current.nodes.map((node) => ({ id: node.id, type: "select" as const, selected: node.id === id })) }), []);
|
||||
const beginEdit = useCallback(() => dispatch({ type: "checkpoint" }), []);
|
||||
const edit = useCallback((id: string, text: string) => dispatch({ type: "edit", id, text }), []);
|
||||
const branch = useCallback((id: string, direction: NodeDirection, point: XYPosition) => {
|
||||
@@ -84,7 +78,9 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
}, []);
|
||||
const transform = useCallback((id: string, transform: NodeTransform) => dispatch({ type: "transform", id, transform }), []);
|
||||
const style = useCallback((id: string, style: TextStyle, fontSize?: number) => dispatch({ type: "style", id, style, fontSize }), []);
|
||||
const editing = useMemo(() => ({ begin: beginEdit, edit, branch, transform, style, rotating, rotate: setRotating }), [beginEdit, edit, branch, transform, style, rotating]);
|
||||
const rename = useCallback((id: string, title: string) => dispatch({ type: "rename-node", id, title }), []);
|
||||
const frame = useCallback((id: string, patch: { title?: string; labelMode?: FrameLabelMode }) => dispatch({ type: "frame", id, ...patch }), []);
|
||||
const editing = useMemo(() => ({ begin: beginEdit, select, edit, branch, transform, style, rename, frame, rotating, rotate: setRotating }), [beginEdit, select, edit, branch, transform, style, rename, frame, rotating]);
|
||||
function createBranch(request: BranchRequest, kind: "text" | "image" | "script", src?: string) {
|
||||
try {
|
||||
const document = branchCanvasNode(state.present, request.id, request.direction, kind, src, request.at);
|
||||
@@ -96,7 +92,7 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
}
|
||||
function chooseBranch(kind: "text" | "image" | "script") {
|
||||
if (!branchRequest) return;
|
||||
if (kind === "image") { pendingImage.current = branchRequest; setBranchRequest(null); imageInput.current?.click(); }
|
||||
if (kind === "image") { pendingImage.current = branchRequest; imageKind.current = "image"; setBranchRequest(null); imageInput.current?.click(); }
|
||||
else createBranch(branchRequest, kind);
|
||||
}
|
||||
const connectionEnd: OnConnectEnd = (event, connection) => {
|
||||
@@ -116,9 +112,12 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
const offset = (nodes.length % 6) * 18;
|
||||
return { x: point.x - 130 + offset, y: point.y - 80 + offset };
|
||||
};
|
||||
function addNode(kind: CanvasNode["data"]["kind"], src?: string) {
|
||||
function addNode(kind: CanvasNode["data"]["kind"], src?: string, size?: { width: number; height: number }, title?: string) {
|
||||
if (nodes.length >= 500) { setError("当前图谱已达到 500 个节点,请新建图谱继续创作。"); return; }
|
||||
dispatch({ type: "nodes", changes: [{ type: "add", item: makeCanvasNode(kind, center(), src) }] });
|
||||
const node = makeCanvasNode(kind, center(), src);
|
||||
if (size) { node.width = size.width; node.height = size.height; node.style = { ...node.style, ...size }; }
|
||||
if (title) node.data.title = title.slice(0, 300);
|
||||
dispatch({ type: "nodes", changes: [{ type: "add", item: node }] });
|
||||
setTool("select");
|
||||
}
|
||||
function addTemplate() {
|
||||
@@ -136,6 +135,20 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
] } });
|
||||
setTool("select");
|
||||
}
|
||||
function beginDrag(node: CanvasNode, dragged: CanvasNode[]) {
|
||||
beginEdit(); closeBranch(); setRotating(null);
|
||||
draggingFrame.current = node.data.kind === "frame" || dragged.some((item) => item.data.kind === "frame");
|
||||
const before = new Map(latest.current.nodes.map((item) => [item.id, item.position]));
|
||||
dragOrigins.current = new Map((dragged.length ? dragged : [node]).map((item) => [item.id, before.get(item.id) || item.position]));
|
||||
}
|
||||
function finishDrag(node: CanvasNode, dragged: CanvasNode[]) {
|
||||
if (!draggingFrame.current) {
|
||||
const items = dragged.length ? dragged : [node];
|
||||
const ids = items.filter((item) => { const start = dragOrigins.current.get(item.id); return item.data.kind !== "frame" && start && (start.x !== item.position.x || start.y !== item.position.y); }).map((item) => item.id);
|
||||
if (ids.length) dispatch({ type: "drop", ids });
|
||||
}
|
||||
dragOrigins.current.clear();
|
||||
}
|
||||
function connect(connection: Connection) {
|
||||
dispatch({ type: "replace", document: { ...state.present, edges: addEdge({ ...connection, id: crypto.randomUUID() }, edges) } });
|
||||
}
|
||||
@@ -146,6 +159,8 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type) || file.size > 2_000_000) {
|
||||
pendingImage.current = null; setError("请选择小于 2 MB 的 PNG、JPEG、WebP 或 GIF 图片。"); return;
|
||||
}
|
||||
const request = pendingImage.current; pendingImage.current = null;
|
||||
const kind = imageKind.current;
|
||||
try {
|
||||
const src = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
@@ -153,8 +168,16 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
reader.onerror = () => reject(new Error("无法读取图片。"));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
const request = pendingImage.current; pendingImage.current = null;
|
||||
if (request) createBranch(request, "image", src); else addNode("image", src);
|
||||
let size: { width: number; height: number } | undefined;
|
||||
if (kind === "plain-image" && !request) {
|
||||
size = await new Promise((resolve, reject) => {
|
||||
const image = new window.Image();
|
||||
image.onload = () => { const scale = Math.min(1, 480 / image.naturalWidth, 480 / image.naturalHeight); resolve({ width: Math.max(24, Math.round(image.naturalWidth * scale)), height: Math.max(24, Math.round(image.naturalHeight * scale)) }); };
|
||||
image.onerror = () => reject(new Error("无法读取图片尺寸。"));
|
||||
image.src = src;
|
||||
});
|
||||
}
|
||||
if (request) createBranch(request, "image", src); else addNode(kind, src, size, kind === "plain-image" ? file.name : undefined);
|
||||
} catch { pendingImage.current = null; setError("无法读取图片,请重新选择。"); }
|
||||
}
|
||||
async function importProject(event: ChangeEvent<HTMLInputElement>) {
|
||||
@@ -200,11 +223,14 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
return (
|
||||
<div className={`${styles.editor} ${tool === "hand" ? styles.handMode : ""}`}>
|
||||
<NodeEditing.Provider value={editing}>
|
||||
<ReactFlow<CanvasNode> nodes={nodes} edges={edges} nodeTypes={nodeTypes}
|
||||
<ReactFlow<CanvasNode> nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={edgeTypes}
|
||||
onNodesChange={(changes) => dispatch({ type: "nodes", changes })}
|
||||
onEdgesChange={(changes) => dispatch({ type: "edges", changes })}
|
||||
connectionLineType={ConnectionLineType.Bezier}
|
||||
onNodeDragStart={() => { beginEdit(); closeBranch(); setRotating(null); }} onConnect={connect} connectionMode={ConnectionMode.Loose}
|
||||
connectionLineType={ConnectionLineType.Bezier} connectionLineComponent={CanvasConnectionLine}
|
||||
onNodeDragStart={(_, node, dragged) => beginDrag(node, dragged)}
|
||||
onNodeDragStop={(_, node, dragged) => finishDrag(node, dragged)}
|
||||
onSelectionDragStart={(_, dragged) => { if (dragged[0]) beginDrag(dragged[0], dragged); }}
|
||||
onSelectionDragStop={(_, dragged) => { if (dragged[0]) finishDrag(dragged[0], dragged); }} onConnect={connect} connectionMode={ConnectionMode.Loose}
|
||||
connectOnClick={false} connectionDragThreshold={5}
|
||||
onConnectStart={(event, params) => { closeBranch(); const point = "touches" in event ? event.touches[0] : event; if (params.nodeId && params.handleId && point) connectionStart.current = { id: params.nodeId, direction: params.handleId as NodeDirection, point: { x: point.clientX, y: point.clientY } }; }}
|
||||
onConnectEnd={connectionEnd}
|
||||
@@ -214,6 +240,7 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
defaultViewport={initial.document.viewport} minZoom={0.1} maxZoom={4}
|
||||
panOnDrag panOnScroll zoomOnScroll={false} zoomOnPinch zoomActivationKeyCode={["Meta", "Control"]}
|
||||
nodesDraggable={tool === "select"} nodesConnectable={tool === "select"}
|
||||
elevateNodesOnSelect={false}
|
||||
elementsSelectable={tool === "select"} selectionMode={SelectionMode.Partial}
|
||||
panActivationKeyCode="Space" selectionKeyCode="Shift"
|
||||
deleteKeyCode={["Backspace", "Delete"]} preventScrolling
|
||||
@@ -240,8 +267,10 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
<span className={toolbar.divider} aria-hidden="true" />
|
||||
<IconButton icon={Type} label="添加纯文本" onClick={() => addNode("plain-text")} />
|
||||
<IconButton icon={StickyNote} label="添加文本卡片" onClick={() => addNode("text")} />
|
||||
<IconButton icon={ImagePlus} label="添加图片" onClick={() => { pendingImage.current = null; imageInput.current?.click(); }} />
|
||||
<IconButton icon={ImagePlus} label="添加图片" onClick={() => { pendingImage.current = null; imageKind.current = "image"; imageInput.current?.click(); }} />
|
||||
<IconButton icon={ImageIcon} label="添加纯图片" onClick={() => { pendingImage.current = null; imageKind.current = "plain-image"; imageInput.current?.click(); }} />
|
||||
<IconButton icon={FileText} label="添加脚本" onClick={() => addNode("script")} />
|
||||
<IconButton icon={Frame} label="添加框选区" onClick={() => addNode("frame")} />
|
||||
<IconButton icon={Shapes} label="添加图标" aria-expanded={iconPicker} onClick={() => setIconPicker(!iconPicker)} />
|
||||
<IconButton icon={Sparkles} label="插入创作模板" onClick={addTemplate} />
|
||||
<span className={toolbar.divider} aria-hidden="true" />
|
||||
@@ -257,7 +286,8 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
<p>V 选择 · H 抓手 · 按住空格临时平移 · Shift 框选</p>
|
||||
<p>拖动右下角调整大小;在样式栏开启旋转,拖动元素旋转,点击外部退出。Shift 吸附 15°。</p>
|
||||
<p>纯文本可独立调整宽高,文字随宽度换行,字号在样式栏设置;不显示卡片连接点或四向加号。</p>
|
||||
<p>拖动四边中心点或选中后的加号创建贝塞尔连线;点击加号选择新节点类型。Delete 删除所选内容。</p>
|
||||
<p>拖动四边中心点创建贝塞尔连线;选中后点击连接点选择新节点类型。Delete 删除所选内容。</p>
|
||||
<p>添加框选区后拖入内容加入;拖出退出。移动分区只带动已有成员,不收纳被覆盖的内容。选中分区可改名并选择名称显示模式。</p>
|
||||
<p>⌘ / Ctrl + Z 撤销,Shift + ⌘ / Ctrl + Z 重做。</p>
|
||||
<p>可通过右上角导出 JSON 备份。</p>
|
||||
</div>
|
||||
@@ -269,6 +299,11 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
dispatch({ type: "replace", document: { ...state.present, nodes: [...nodes.map((item) => ({ ...item, selected: false })), { ...node, selected: true }] } });
|
||||
setTool("select");
|
||||
}} />
|
||||
{recovery && <DraftRecovery restore={() => { dispatch({ type: "replace", document: recovery }); setRecovery(null); }} discard={() => setRecovery(null)} />}
|
||||
{snapshot && sync.status === "error" && <div className={styles.syncError} role="alert"><span>{sync.error === "local_backup_failed" ? "本地备份失败,请导出 JSON 备份。" : sync.error === "version_conflict" ? "画布已在其他地方修改,自动保存已停止,请导出当前内容或重新读取服务端版本。" : errorText(new Error(sync.error))}</span>
|
||||
{sync.error !== "version_conflict" && <button onClick={() => void sync.retry()}>重试保存</button>}
|
||||
<button onClick={exportProject}>导出当前内容</button><button onClick={() => window.location.reload()}>重新读取</button>
|
||||
</div>}
|
||||
{error && <button className={styles.error} role="alert" onClick={() => setError("")} title="点击关闭提示">{error}</button>}
|
||||
<input ref={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" onChange={readImage} hidden />
|
||||
<input ref={projectInput} type="file" accept="application/json,.json" onChange={importProject} hidden />
|
||||
@@ -276,6 +311,6 @@ function CanvasEditor({ board }: { board: Board }) {
|
||||
);
|
||||
}
|
||||
|
||||
export default function GraphCanvas({ board }: { board: Board }) {
|
||||
return <ReactFlowProvider><CanvasEditor board={board} /></ReactFlowProvider>;
|
||||
export default function GraphCanvas({ board, snapshot }: { board: Board; snapshot?: CanvasSnapshot }) {
|
||||
return <ReactFlowProvider><CanvasEditor board={board} snapshot={snapshot} /></ReactFlowProvider>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user