"use client"; import { useCallback, useEffect, useMemo, useReducer, useRef, useState, type ChangeEvent } from "react"; 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, 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 { 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 edgeTypes = { default: CanvasEdge }; const nodeTypes = { material: MaterialNode, plainText: PlainTextNode, icon: IconNode, frame: FrameNode, plainImage: PlainImageNode }; function CanvasEditor({ board, snapshot }: { board: Board; snapshot?: CanvasSnapshot }) { const flow = useReactFlow(); const { zoom } = useViewport(); const reduceMotion = useReducedMotion(); const storageKey = canvasStorageKey(board.workspace_id, board.id); const [initial] = useState(() => { try { 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"); const [error, setError] = useState(initial.error); const [branchRequest, setBranchRequest] = useState(null); const [iconPicker, setIconPicker] = useState(false); const [rotating, setRotating] = useState(null); const dragOrigins = useRef(new Map()); const draggingFrame = useRef(false); const connectionStart = useRef<{ id: string; direction: NodeDirection; point: XYPosition } | null>(null); const pendingImage = useRef(null); const closeBranch = useCallback(() => setBranchRequest(null), []); const imageKind = useRef<"image" | "plain-image">("image"); const imageInput = useRef(null); const projectInput = useRef(null); 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; }; input?.addEventListener("cancel", cancel); return () => input?.removeEventListener("cancel", cancel); }, []); const { nodes, edges } = state.present; const duration = reduceMotion ? 0 : 180; const latest = useRef(state.present); latest.current = state.present; 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) => { setBranchRequest({ id, direction, point }); setRotating(null); }, []); 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 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); dispatch({ type: "replace", document }); const child = document.nodes.at(-1)!; void flow.setCenter(child.position.x + 130, child.position.y + 100, { zoom: flow.getZoom(), duration }); setBranchRequest(null); } catch (error) { setError(error instanceof Error ? error.message : "无法创建节点。"); } } function chooseBranch(kind: "text" | "image" | "script") { if (!branchRequest) return; if (kind === "image") { pendingImage.current = branchRequest; imageKind.current = "image"; setBranchRequest(null); imageInput.current?.click(); } else createBranch(branchRequest, kind); } const connectionEnd: OnConnectEnd = (event, connection) => { const start = connectionStart.current; connectionStart.current = null; if (!start || connection.isValid) return; const point = "changedTouches" in event ? event.changedTouches[0] : event; if (!point || Math.hypot(point.clientX - start.point.x, point.clientY - start.point.y) < 5) return; if (!document.elementFromPoint(point.clientX, point.clientY)?.closest(".react-flow__pane")) return; if (!flow.getNode(start.id)?.selected) return; const at = flow.screenToFlowPosition({ x: point.clientX, y: point.clientY }); setBranchRequest({ id: start.id, direction: start.direction, point: { x: point.clientX, y: point.clientY }, at }); }; const center = () => { const point = flow.screenToFlowPosition({ x: window.innerWidth / 2, y: window.innerHeight / 2 }); 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, size?: { width: number; height: number }, title?: string) { if (nodes.length >= 500) { setError("当前图谱已达到 500 个节点,请新建图谱继续创作。"); return; } 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() { if (nodes.length > 497) { setError("当前图谱没有足够空间插入模板。"); return; } const position = center(); const brief = makeCanvasNode("text", { x: position.x - 300, y: position.y }); brief.data = { ...brief.data, title: "创意简报", text: "你想表达什么?\n\n记录主题、受众和一个关键想法。" }; const idea = makeCanvasNode("text", { x: position.x + 20, y: position.y - 100 }); idea.data = { ...idea.data, title: "视觉参考", text: "收集颜色、光线和画面氛围。" }; const script = makeCanvasNode("script", { x: position.x + 340, y: position.y }); script.data.text = "从第一个镜头开始,写下你的故事。"; dispatch({ type: "replace", document: { ...state.present, nodes: [...nodes, brief, idea, script], edges: [...edges, { id: crypto.randomUUID(), source: brief.id, target: idea.id, type: "default" }, { id: crypto.randomUUID(), source: idea.id, target: script.id }, ] } }); 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) } }); } async function readImage(event: ChangeEvent) { const file = event.target.files?.[0]; event.target.value = ""; if (!file) { pendingImage.current = null; return; } 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((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(new Error("无法读取图片。")); reader.readAsDataURL(file); }); 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) { const file = event.target.files?.[0]; event.target.value = ""; if (!file) return; try { if (file.size > 5_000_000) throw new Error("请选择小于 5 MB 的图谱文件。"); const document = decodeCanvas(await file.text()); dispatch({ type: "replace", document }); void flow.setViewport(document.viewport); setError(""); } catch (error) { setError(error instanceof Error ? error.message : "导入失败。"); } } function exportProject() { const content = JSON.stringify({ ...state.present, viewport: flow.getViewport() }, null, 2); const url = URL.createObjectURL(new Blob([content], { type: "application/json" })); const link = document.createElement("a"); link.href = url; link.download = `${board.title.replace(/[\\/:*?"<>|]/g, "_") || "未命名图谱"}.json`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); } useEffect(() => { const keydown = (event: KeyboardEvent) => { const target = event.target; if (!(target instanceof HTMLElement)) return; if (target.closest("input, textarea, [contenteditable=true], [role=dialog], [popover]:popover-open")) return; if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "z") { event.preventDefault(); dispatch({ type: event.shiftKey ? "redo" : "undo" }); } else if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "y") { event.preventDefault(); dispatch({ type: "redo" }); } else if (!event.metaKey && !event.ctrlKey && !event.altKey) { if (event.key.toLowerCase() === "v") setTool("select"); if (event.key.toLowerCase() === "h") setTool("hand"); } }; window.addEventListener("keydown", keydown); return () => window.removeEventListener("keydown", keydown); }, []); return (
nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={edgeTypes} onNodesChange={(changes) => dispatch({ type: "nodes", changes })} onEdgesChange={(changes) => dispatch({ type: "edges", changes })} 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} onPaneClick={() => { closeBranch(); setRotating(null); }} onNodeClick={(_, node) => { if (node.id !== rotating) setRotating(null); }} onMoveStart={closeBranch} onMoveEnd={(_, viewport) => dispatch({ type: "viewport", viewport })} 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 defaultEdgeOptions={{ style: { stroke: "#aa968b", strokeWidth: 1.5 } }}>
dispatch({ type: "undo" })} /> dispatch({ type: "redo" })} />
setTool("select")} /> setTool("hand")} />
自由创作,从移动画布开始

拖动空白处平移,拖动节点移动位置。

触控板滚动平移;按 Ctrl / ⌘ 滚动或双指捏合缩放。

V 选择 · H 抓手 · 按住空格临时平移 · Shift 框选

拖动右下角调整大小;在样式栏开启旋转,拖动元素旋转,点击外部退出。Shift 吸附 15°。

纯文本可独立调整宽高,文字随宽度换行,字号在样式栏设置;不显示卡片连接点或四向加号。

拖动四边中心点创建贝塞尔连线;选中后点击连接点选择新节点类型。Delete 删除所选内容。

添加框选区后拖入内容加入;拖出退出。移动分区只带动已有成员,不收纳被覆盖的内容。选中分区可改名并选择名称显示模式。

⌘ / Ctrl + Z 撤销,Shift + ⌘ / Ctrl + Z 重做。

可通过右上角导出 JSON 备份。

setIconPicker(false)} choose={(name, label) => { if (nodes.length >= 500) { setError("当前图谱已达到 500 个节点。"); return; } const node = makeCanvasNode("icon", center()); node.data = { ...node.data, icon: name, title: label }; dispatch({ type: "replace", document: { ...state.present, nodes: [...nodes.map((item) => ({ ...item, selected: false })), { ...node, selected: true }] } }); setTool("select"); }} /> {recovery && { dispatch({ type: "replace", document: recovery }); setRecovery(null); }} discard={() => setRecovery(null)} />} {snapshot && sync.status === "error" &&
{sync.error === "local_backup_failed" ? "本地备份失败,请导出 JSON 备份。" : sync.error === "version_conflict" ? "画布已在其他地方修改,自动保存已停止,请导出当前内容或重新读取服务端版本。" : errorText(new Error(sync.error))} {sync.error !== "version_conflict" && }
} {error && }
); } export default function GraphCanvas({ board, snapshot }: { board: Board; snapshot?: CanvasSnapshot }) { return ; }