AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: add editable mind map and flowchart notes
tianma-ifd400371841a7
diff --git a/apps/api/src/memo-service.ts b/apps/api/src/memo-service.tsindex e3d3826b..8d86961c 100644--- a/apps/api/src/memo-service.ts+++ b/apps/api/src/memo-service.ts@@ -917,13 +917,15 @@ export const mergeMemosRecord = async (export const createMemoRecord = async (db: DatabaseAdapter,workspaceId: string,- input: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[]; createdAt?: string; updatedAt?: string },+ input: { notebookId: string; title?: string; contentJson?: unknown; contentMarkdown?: string; tags?: string[]; createdAt?: string; updatedAt?: string },actor: { actorType: "user" | "agent"; actorId: string | null },actorLabel: string): Promise<MemoDetail> => {const tags = normalizeTags(input.tags);const contentMarkdown = input.contentMarkdown ?? "";- const contentJson = markdownToDoc(contentMarkdown);+ const contentJson = input.contentJson && typeof input.contentJson === "object"+ ? input.contentJson as TiptapDoc+ : markdownToDoc(contentMarkdown);const contentText = docToText(contentJson);const title = normalizeMemoTitle(input.title);const excerpt = createExcerpt(contentText);diff --git a/apps/web/package.json b/apps/web/package.jsonindex d92ad6f9..09c795b7 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -4,9 +4,11 @@"private": true,"type": "module","dependencies": {+ "@antv/x6": "3.1.8",+ "@codemirror/lang-markdown": "^6.5.2",+ "@dagrejs/dagre": "3.1.1","@edgeever/client": "workspace:*","@floating-ui/react-dom": "^2.1.8",- "@codemirror/lang-markdown": "^6.5.2","@fontsource-variable/noto-sans-sc": "^5.2.8","@tiptap/extension-code-block-lowlight": "3.31.0","@tiptap/pm": "3.31.0",diff --git a/apps/web/src/components/DiagramEditorPane.test.mjs b/apps/web/src/components/DiagramEditorPane.test.mjsnew file mode 100644index 00000000..42ef3408--- /dev/null+++ b/apps/web/src/components/DiagramEditorPane.test.mjs@@ -0,0 +1,27 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";++const source = readFileSync(new URL("./DiagramEditorPane.tsx", import.meta.url), "utf8");++describe("diagram editor keyboard workflow", () => {+ test("supports direct node editing without routing keystrokes through the side panel", () => {+ expect(source).toContain('graph.on("node:dblclick"');+ expect(source).toContain('aria-label={t("diagram.editNode")}');+ expect(source).toContain('event.key === "Escape"');+ });++ test("keeps the standard mind-map sibling and child shortcuts", () => {+ expect(source).toContain('graph.bindKey("enter"');+ expect(source).toContain('insertNodeRef.current("sibling"');+ expect(source).toContain('graph.bindKey("tab"');+ expect(source).toContain('insertNodeRef.current("child"');+ });+});++describe("diagram editor canvas surface", () => {+ test("keeps alignment grids for flowcharts without adding visual noise to mind maps", () => {+ expect(source).toContain('grid: document.kind === "flowchart" ? diagramGrid(documentTheme) : false');+ expect(source).toContain('if (kind === "flowchart") graph.drawGrid(diagramGrid(theme));');+ expect(source).toContain("else graph.clearGrid();");+ });+});diff --git a/apps/web/src/components/DiagramEditorPane.tsx b/apps/web/src/components/DiagramEditorPane.tsxnew file mode 100644index 00000000..8106587c--- /dev/null+++ b/apps/web/src/components/DiagramEditorPane.tsx@@ -0,0 +1,993 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { Export, Graph, History, Keyboard, Selection, type Edge, type Node } from "@antv/x6";+import {+ ArrowLeft,+ Box,+ Circle,+ Diamond,+ Download,+ FileCode2,+ FileImage,+ GitBranch,+ LayoutDashboard,+ Maximize2,+ Redo2,+ Save,+ Trash2,+ Undo2,+ ZoomIn,+ ZoomOut,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import {+ DIAGRAM_SCHEMA_VERSION,+ diagramFallbackMarkdown,+ markdownToDoc,+ parseDiagramDocument,+ serializeDiagramDocument,+ type DiagramDocument,+ type DiagramNodeShape,+ type DiagramTheme,+ type MemoDetail,+ type MemoEditSession,+} from "@edgeever/shared";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { AppConfirmDialog } from "@/components/dialogs/ConfirmDialogs";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { api } from "@/lib/api";+import { compactMindMapNodeSize, computeDiagramLayout } from "@/lib/diagram-layout";+import { isLocalMemoId } from "@/lib/local-mirror";+import { isBrowserOffline } from "@/lib/network-status";+import type { EdgeEverRepository } from "@/lib/repository";+import { cn } from "@/lib/utils";++type DiagramEditorPaneProps = {+ memo: MemoDetail;+ repository: EdgeEverRepository;+ readOnly: boolean;+ onBackToList: () => void;+ onSaved: (memo: MemoDetail) => Promise<void>;+};++type NodeData = { label: string; shape: DiagramNodeShape; parentId?: string };+type MindMapInsertRelation = "child" | "sibling";+type NodeEditorState = {+ nodeId: string;+ originalValue: string;+ value: string;+ shape: DiagramNodeShape;+ left: number;+ top: number;+ width: number;+ height: number;+ fontSize: number;+ color: string;+ background: string;+ borderColor: string;+};++const BRAND_GREEN = "#16A06E";+const createId = (prefix: string) => `${prefix}-${crypto.randomUUID()}`;++const DIAGRAM_THEMES: Record<DiagramTheme, {+ topicFill: string;+ topicText: string;+ nodeFill: string;+ nodeText: string;+ nodeStroke: string;+ topicStroke: string;+ mindMapEdge: string;+ flowEdge: string;+ canvas: string;+ grid: string;+ gridStrong: string;+}> = {+ brand: {+ topicFill: BRAND_GREEN,+ topicText: "#FFFFFF",+ nodeFill: "#F0F8F4",+ nodeText: "#173B2E",+ nodeStroke: "#B8DFD0",+ topicStroke: "#12845B",+ mindMapEdge: "#55B891",+ flowEdge: "#408A6D",+ canvas: "#F8FAF9",+ grid: "#E6EEE9",+ gridStrong: "#CFDDD5",+ },+ ocean: {+ topicFill: "#DEF1E9",+ topicText: "#0F4432",+ nodeFill: "#FFFEFA",+ nodeText: "#26352E",+ nodeStroke: "#D5E3DB",+ topicStroke: BRAND_GREEN,+ mindMapEdge: "#8ACCB2",+ flowEdge: "#6B9281",+ canvas: "#FBFCFA",+ grid: "#EBF0EC",+ gridStrong: "#D9E3DC",+ },+ ink: {+ topicFill: "#16A06E",+ topicText: "#F5FBF8",+ nodeFill: "#19261F",+ nodeText: "#E5EEE9",+ nodeStroke: "#3C594A",+ topicStroke: "#68D6B0",+ mindMapEdge: "#58BA94",+ flowEdge: "#68A78D",+ canvas: "#101512",+ grid: "#202B25",+ gridStrong: "#304038",+ },+};++const diagramGrid = (theme: DiagramTheme) => ({+ visible: true,+ type: "doubleMesh" as const,+ args: [+ { color: DIAGRAM_THEMES[theme].grid, thickness: 1 },+ { color: DIAGRAM_THEMES[theme].gridStrong, thickness: 1, factor: 5 },+ ],+});++const applyDiagramSurface = (graph: Graph, theme: DiagramTheme, kind: DiagramDocument["kind"]) => {+ graph.drawBackground({ color: DIAGRAM_THEMES[theme].canvas });+ if (kind === "flowchart") graph.drawGrid(diagramGrid(theme));+ else graph.clearGrid();+};++const prepareExportSvg = (background: string) => (svg: SVGSVGElement) => {+ svg.querySelectorAll(".x6-port").forEach((element) => element.remove());+ const viewBox = svg.getAttribute("viewBox")?.split(/\s+/).map(Number);+ if (!viewBox || viewBox.length !== 4 || viewBox.some((value) => !Number.isFinite(value))) return;+ const [x, y, width, height] = viewBox;+ const rect = svg.ownerDocument.createElementNS("http://www.w3.org/2000/svg", "rect");+ rect.setAttribute("x", String(x));+ rect.setAttribute("y", String(y));+ rect.setAttribute("width", String(width));+ rect.setAttribute("height", String(height));+ rect.setAttribute("fill", background);+ svg.insertBefore(rect, svg.firstChild);+};++const createLocalEditSession = (memo: MemoDetail): MemoEditSession => ({+ id: `local-edit:${memo.id}`,+ memoId: memo.id,+ baseRevision: memo.revision,+ baseContentHash: memo.contentHash,+ expiresAt: new Date(Date.now() + 86_400_000).toISOString(),+});++const nodeEditorState = (graph: Graph, node: Node, theme: DiagramTheme): NodeEditorState => {+ const data = node.getData<NodeData>();+ const bbox = node.getBBox();+ const topLeft = graph.localToGraph({ x: bbox.x, y: bbox.y });+ const bottomRight = graph.localToGraph({ x: bbox.x + bbox.width, y: bbox.y + bbox.height });+ const isRootTopic = data?.shape === "topic" && !data.parentId;+ const attrs = nodeAttrs(data?.shape ?? "process", theme, isRootTopic);+ return {+ nodeId: node.id,+ originalValue: data?.label ?? "",+ value: data?.label ?? "",+ shape: data?.shape ?? "process",+ left: topLeft.x,+ top: topLeft.y,+ width: bottomRight.x - topLeft.x,+ height: bottomRight.y - topLeft.y,+ fontSize: 14 * graph.scale().sx,+ color: String(attrs.label.fill),+ background: String(attrs.body.fill),+ borderColor: String(attrs.body.stroke),+ };+};++const nodeAttrs = (shape: DiagramNodeShape, theme: DiagramTheme, isRootTopic = false) => {+ const palette = DIAGRAM_THEMES[theme];+ const isTerminator = shape === "terminator";+ const isAccent = isRootTopic || isTerminator;+ return {+ body: {+ fill: isAccent ? palette.topicFill : palette.nodeFill,+ stroke: isAccent ? palette.topicStroke : palette.nodeStroke,+ strokeWidth: isAccent ? 1.5 : 1,+ rx: isTerminator ? 24 : 11,+ ry: isTerminator ? 24 : 11,+ ...(shape === "decision" ? { refPoints: "0,10 10,0 20,10 10,20" } : {}),+ },+ label: { fill: isAccent ? palette.topicText : palette.nodeText, fontSize: 14, fontWeight: isAccent ? 650 : 500 },+ };+};++const nodeMetadata = (node: DiagramDocument["nodes"][number], theme: DiagramTheme) => {+ const isDecision = node.shape === "decision";+ const isRootTopic = node.shape === "topic" && !node.parentId;+ const visualAttrs = nodeAttrs(node.shape, theme, isRootTopic);+ const palette = DIAGRAM_THEMES[theme];+ const size = node.shape === "topic"+ ? compactMindMapNodeSize(node.label, isRootTopic)+ : { width: node.width, height: node.height };+ return {+ id: node.id,+ shape: isDecision ? "polygon" : "rect",+ x: node.x,+ y: node.y,+ width: size.width,+ height: size.height,+ data: { label: node.label, shape: node.shape, ...(node.parentId ? { parentId: node.parentId } : {}) } satisfies NodeData,+ attrs: {+ body: visualAttrs.body,+ label: { ...visualAttrs.label, text: node.label },+ },+ ports: {+ groups: {+ top: { position: "top", attrs: { circle: { r: 4, magnet: true, stroke: palette.topicStroke, fill: palette.canvas, strokeWidth: 1.5 } } },+ right: { position: "right", attrs: { circle: { r: 4, magnet: true, stroke: palette.topicStroke, fill: palette.canvas, strokeWidth: 1.5 } } },+ bottom: { position: "bottom", attrs: { circle: { r: 4, magnet: true, stroke: palette.topicStroke, fill: palette.canvas, strokeWidth: 1.5 } } },+ left: { position: "left", attrs: { circle: { r: 4, magnet: true, stroke: palette.topicStroke, fill: palette.canvas, strokeWidth: 1.5 } } },+ },+ items: ["top", "right", "bottom", "left"].map((group) => ({ id: group, group })),+ },+ };+};++const edgeMetadata = (edge: DiagramDocument["edges"][number], kind: DiagramDocument["kind"], theme: DiagramTheme) => ({+ id: edge.id,+ source: { cell: edge.source },+ target: { cell: edge.target },+ router: kind === "flowchart" ? { name: "manhattan", args: { padding: 20 } } : undefined,+ connector: { name: kind === "mind-map" ? "smooth" : "rounded", args: { radius: 10 } },+ attrs: {+ line: {+ stroke: kind === "mind-map" ? DIAGRAM_THEMES[theme].mindMapEdge : DIAGRAM_THEMES[theme].flowEdge,+ strokeWidth: kind === "mind-map" ? 2 : 1.5,+ targetMarker: kind === "mind-map" ? null : { name: "block", width: 8, height: 6 },+ },+ },+ labels: edge.label ? [{ attrs: {+ label: { text: edge.label, fill: DIAGRAM_THEMES[theme].nodeText, fontSize: 12 },+ body: { fill: DIAGRAM_THEMES[theme].canvas, stroke: DIAGRAM_THEMES[theme].nodeStroke, strokeWidth: 1, rx: 5, ry: 5 },+ } }] : undefined,+});++const graphToDocument = (graph: Graph, kind: DiagramDocument["kind"], theme: DiagramTheme): DiagramDocument => ({+ schemaVersion: DIAGRAM_SCHEMA_VERSION,+ kind,+ theme,+ nodes: graph.getNodes().map((node) => {+ const data = node.getData<NodeData>();+ const position = node.getPosition();+ const size = node.getSize();+ return {+ id: node.id,+ label: data?.label ?? String(node.attr("label/text") ?? ""),+ x: Math.round(position.x),+ y: Math.round(position.y),+ width: Math.round(size.width),+ height: Math.round(size.height),+ shape: data?.shape ?? "process",+ ...(data?.parentId && graph.getCellById(data.parentId)?.isNode() ? { parentId: data.parentId } : {}),+ };+ }),+ edges: graph.getEdges().flatMap((edge) => {+ const source = edge.getSourceCellId();+ const target = edge.getTargetCellId();+ if (!source || !target) return [];+ const label = edge.getLabels()[0]?.attrs?.label?.text;+ return [{ id: edge.id, source, target, ...(typeof label === "string" && label ? { label } : {}) }];+ }),+});++const removeGraphSelection = (graph: Graph) => {+ const selected = graph.getSelectedCells();+ if (selected.length === 0) return false;+ graph.startBatch("remove");+ for (const cell of selected) {+ if (cell.isNode()) graph.removeConnectedEdges(cell);+ }+ graph.removeCells(selected);+ graph.stopBatch("remove");+ return true;+};++const diagramEditorSnapshot = (title: string, document: DiagramDocument) => JSON.stringify({+ title,+ document: {+ ...document,+ theme: document.theme ?? "brand",+ nodes: document.nodes.map((node) => node.shape === "topic"+ ? { ...node, ...compactMindMapNodeSize(node.label, !node.parentId) }+ : node),+ },+});++const fitDiagramContent = (graph: Graph, document: DiagramDocument, container: HTMLElement | null, padding = 32) => {+ graph.zoomToFit({ padding, maxScale: 1 });+ if (document.kind !== "mind-map" || !container) return;+ const root = graph.getNodes().find((node) => !node.getData<NodeData>()?.parentId);+ if (!root) return;+ const rootLeft = graph.localToGraph(root.getBBox().topLeft).x;+ const desiredLeft = Math.max(36, Math.min(96, container.clientWidth * 0.08));+ const translation = graph.translate();+ graph.translate(translation.tx + desiredLeft - rootLeft, translation.ty);+};++const detectGraphTheme = (graph: Graph): DiagramTheme | null => {+ const node = graph.getNodes()[0];+ if (!node) return null;+ const shape = node.getData<NodeData>()?.shape ?? "process";+ const stroke = node.attr("body/stroke");+ return (Object.keys(DIAGRAM_THEMES) as DiagramTheme[]).find((candidate) => {+ const palette = DIAGRAM_THEMES[candidate];+ return stroke === (shape === "topic" ? palette.topicStroke : palette.nodeStroke);+ }) ?? null;+};++export const DiagramEditorPane = ({ memo, repository, readOnly, onBackToList, onSaved }: DiagramEditorPaneProps) => {+ const { t } = useTranslation();+ const containerRef = useRef<HTMLDivElement | null>(null);+ const graphRef = useRef<Graph | null>(null);+ const insertNodeRef = useRef<(relation: MindMapInsertRelation, baseNodeId?: string) => void>(() => undefined);+ const memoRef = useRef(memo);+ const editSessionRef = useRef<MemoEditSession | null>(null);+ const saveRef = useRef<() => void>(() => undefined);+ const document = parseDiagramDocument(memo.contentMarkdown);+ const documentTheme = document?.theme ?? "brand";+ const [title, setTitle] = useState(memo.title ?? "");+ const [theme, setTheme] = useState<DiagramTheme>(documentTheme);+ const titleRef = useRef(title);+ const themeRef = useRef<DiagramTheme>(documentTheme);+ const savedSnapshotRef = useRef(document ? diagramEditorSnapshot(memo.title ?? "", document) : "");+ const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);+ const [selectedNodeLabel, setSelectedNodeLabel] = useState("");+ const [hasSelection, setHasSelection] = useState(false);+ const [dirty, setDirty] = useState(false);+ const [saving, setSaving] = useState(false);+ const [editSessionReady, setEditSessionReady] = useState(false);+ const [saveError, setSaveError] = useState<string | null>(null);+ const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);+ const [historyState, setHistoryState] = useState({ undo: false, redo: false });+ const [nodeEditor, setNodeEditor] = useState<NodeEditorState | null>(null);+ const nodeEditorRef = useRef<NodeEditorState | null>(null);++ const beginNodeEdit = useCallback((node: Node) => {+ const graph = graphRef.current;+ if (!graph || readOnly) return;+ const nextEditor = nodeEditorState(graph, node, themeRef.current);+ nodeEditorRef.current = nextEditor;+ setNodeEditor(nextEditor);+ }, [readOnly]);++ const finishNodeEdit = useCallback((cancel = false) => {+ const graph = graphRef.current;+ const current = nodeEditorRef.current;+ nodeEditorRef.current = null;+ setNodeEditor(null);+ if (!graph || !current) return null;+ const cell = graph.getCellById(current.nodeId);+ if (!cell?.isNode()) return null;+ if (!cancel) {+ const label = current.value.trim() || current.originalValue;+ if (label !== current.originalValue) {+ graph.startBatch("edit-label");+ cell.setData({ ...cell.getData<NodeData>(), label });+ cell.attr("label/text", label);+ graph.stopBatch("edit-label");+ setSelectedNodeLabel(label);+ }+ }+ containerRef.current?.focus({ preventScroll: true });+ return cell;+ }, []);++ useEffect(() => {+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(false);+ nodeEditorRef.current = null;+ setNodeEditor(null);+ setTheme(documentTheme);+ themeRef.current = documentTheme;+ }, [documentTheme, memo.id]);++ useEffect(() => {+ memoRef.current = memo;+ setTitle(memo.title ?? "");+ titleRef.current = memo.title ?? "";+ savedSnapshotRef.current = document ? diagramEditorSnapshot(memo.title ?? "", document) : "";+ setDirty(false);+ setSaveError(null);+ editSessionRef.current = null;+ setEditSessionReady(false);+ if (readOnly || isLocalMemoId(memo.id) || isBrowserOffline() || window.edgeeverDesktop?.isAvailable) {+ editSessionRef.current = createLocalEditSession(memo);+ setEditSessionReady(true);+ return;+ }+ let cancelled = false;+ void api.createMemoEditSession(memo.id).then(({ editSession }) => {+ if (!cancelled) {+ editSessionRef.current = editSession;+ setEditSessionReady(true);+ }+ }).catch(() => {+ if (!cancelled) setSaveError(t("diagram.editSessionError"));+ });+ return () => { cancelled = true; };+ }, [memo.id, memo.contentHash, memo.revision, readOnly, t]);++ useEffect(() => {+ if (!containerRef.current || !document) return;+ let graph!: Graph;+ graph = new Graph({+ container: containerRef.current,+ autoResize: true,+ async: true,+ background: { color: DIAGRAM_THEMES[documentTheme].canvas },+ grid: document.kind === "flowchart" ? diagramGrid(documentTheme) : false,+ panning: { enabled: true, eventTypes: ["leftMouseDown", "mouseWheel"] },+ mousewheel: { enabled: true, modifiers: ["ctrl", "meta"], minScale: 0.3, maxScale: 2.5 },+ interacting: !readOnly,+ connecting: {+ allowBlank: false,+ allowLoop: false,+ allowNode: true,+ allowEdge: false,+ snap: true,+ router: document.kind === "flowchart" ? "manhattan" : "normal",+ connector: document.kind === "mind-map" ? "smooth" : "rounded",+ createEdge: (): Edge => graph.createEdge(edgeMetadata({ id: createId("edge"), source: "", target: "" }, document.kind, documentTheme)),+ },+ });+ graph.use(new History({ enabled: !readOnly }));+ graph.use(new Export());+ graph.use(new Keyboard({+ enabled: !readOnly,+ global: false,+ guard: (event) => {+ const target = event.target;+ return !(target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)));+ },+ }));+ graph.use(new Selection({ enabled: true, multiple: true, rubberband: true, movable: !readOnly, showNodeSelectionBox: true, showEdgeSelectionBox: true }));+ graph.addNodes(document.nodes.map((node) => nodeMetadata(node, documentTheme)));+ graph.addEdges(document.edges.map((edge) => edgeMetadata(edge, document.kind, documentTheme)));+ graph.cleanHistory();+ if (document.kind === "mind-map") fitDiagramContent(graph, document, containerRef.current);+ else graph.centerContent();++ const updateHistory = () => setHistoryState({ undo: graph.canUndo(), redo: graph.canRedo() });+ const markDirty = () => {+ if (!readOnly) {+ const currentDocument = graphToDocument(graph, document.kind, themeRef.current);+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(titleRef.current, currentDocument));+ }+ updateHistory();+ };+ const clearSelectionAfterHistory = () => {+ const nextTheme = detectGraphTheme(graph) ?? themeRef.current;+ themeRef.current = nextTheme;+ setTheme(nextTheme);+ applyDiagramSurface(graph, nextTheme, document.kind);+ graph.cleanSelection();+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(false);+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, nextTheme),+ ));+ };+ graph.on("model:updated", markDirty);+ graph.on("history:change", updateHistory);+ graph.on("history:undo", clearSelectionAfterHistory);+ graph.on("history:redo", clearSelectionAfterHistory);+ graph.on("node:click", ({ node }: { node: Node }) => {+ const data = node.getData<NodeData>();+ containerRef.current?.focus({ preventScroll: true });+ setSelectedNodeId(node.id);+ setSelectedNodeLabel(data?.label ?? "");+ setHasSelection(true);+ });+ graph.on("node:dblclick", ({ node }: { node: Node }) => beginNodeEdit(node));+ graph.on("edge:click", () => {+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(true);+ });+ graph.on("blank:click", () => {+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(false);+ });+ graph.bindKey(["backspace", "delete"], (event) => {+ event.preventDefault();+ if (!removeGraphSelection(graph)) return;+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(false);+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, themeRef.current),+ ));+ setHistoryState({ undo: graph.canUndo(), redo: graph.canRedo() });+ });+ graph.bindKey("enter", (event) => {+ event.preventDefault();+ const selected = graph.getSelectedCells().find((cell) => cell.isNode());+ if (document.kind === "mind-map") {+ insertNodeRef.current("sibling", selected?.id);+ } else if (selected?.isNode()) {+ beginNodeEdit(selected);+ }+ });+ if (document.kind === "mind-map") {+ graph.bindKey("tab", (event) => {+ event.preventDefault();+ const selected = graph.getSelectedCells().find((cell) => cell.isNode());+ insertNodeRef.current("child", selected?.id);+ });+ }+ graph.bindKey(["meta+z", "ctrl+z"], (event) => {+ event.preventDefault();+ graph.undo();+ const nextTheme = detectGraphTheme(graph) ?? themeRef.current;+ themeRef.current = nextTheme;+ setTheme(nextTheme);+ applyDiagramSurface(graph, nextTheme, document.kind);+ graph.cleanSelection();+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(false);+ setHistoryState({ undo: graph.canUndo(), redo: graph.canRedo() });+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, nextTheme),+ ));+ });+ graph.bindKey(["meta+shift+z", "ctrl+shift+z"], (event) => {+ event.preventDefault();+ graph.redo();+ const nextTheme = detectGraphTheme(graph) ?? themeRef.current;+ themeRef.current = nextTheme;+ setTheme(nextTheme);+ applyDiagramSurface(graph, nextTheme, document.kind);+ graph.cleanSelection();+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(false);+ setHistoryState({ undo: graph.canUndo(), redo: graph.canRedo() });+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, nextTheme),+ ));+ });+ graphRef.current = graph;+ return () => {+ nodeEditorRef.current = null;+ graphRef.current = null;+ graph.dispose();+ };+ }, [beginNodeEdit, memo.contentHash, memo.id, readOnly]);++ useEffect(() => {+ if (!dirty) return;+ const warn = (event: BeforeUnloadEvent) => event.preventDefault();+ window.addEventListener("beforeunload", warn);+ return () => window.removeEventListener("beforeunload", warn);+ }, [dirty]);++ useEffect(() => {+ if (readOnly) return;+ const handleSaveShortcut = (event: KeyboardEvent) => {+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "s") {+ event.preventDefault();+ saveRef.current();+ }+ };+ window.addEventListener("keydown", handleSaveShortcut);+ return () => window.removeEventListener("keydown", handleSaveShortcut);+ }, [readOnly]);++ const addNode = useCallback((+ shape: DiagramNodeShape = "process",+ options: { relation?: MindMapInsertRelation; baseNodeId?: string; beginEditing?: boolean } = {},+ ) => {+ const graph = graphRef.current;+ if (!graph || !document || readOnly) return;+ const baseNodeId = options.baseNodeId ?? selectedNodeId;+ const selected = baseNodeId+ ? graph.getCellById(baseNodeId) as Node | undefined+ : document.kind === "mind-map"+ ? graph.getNodes()[0]+ : undefined;+ const selectedPosition = selected?.isNode() ? selected.getPosition() : { x: 120, y: 120 };+ const selectedSize = selected?.isNode() ? selected.getSize() : { width: 140, height: 52 };+ const isMindMap = document.kind === "mind-map";+ const selectedData = selected?.isNode() ? selected.getData<NodeData>() : undefined;+ const requestedSibling = isMindMap && options.relation === "sibling" && Boolean(selectedData?.parentId);+ const parent = requestedSibling+ ? graph.getCellById(selectedData?.parentId ?? "") as Node | undefined+ : selected;+ const siblings = requestedSibling+ ? graph.getNodes().filter((node) => node.getData<NodeData>()?.parentId === selectedData?.parentId)+ : [];+ const childNodes = isMindMap && selected?.isNode()+ ? graph.getNodes().filter((node) => node.getData<NodeData>()?.parentId === selected.id)+ : [];+ const nextPosition = requestedSibling+ ? {+ x: selectedPosition.x,+ y: Math.max(selectedPosition.y, ...siblings.map((node) => node.getPosition().y)) + 52,+ }+ : {+ x: selectedPosition.x + selectedSize.width + (isMindMap ? 72 : 110),+ y: childNodes.length > 0+ ? Math.max(...childNodes.map((node) => node.getPosition().y)) + 52+ : selectedPosition.y,+ };+ const id = createId(isMindMap ? "topic" : "node");+ graph.startBatch("add");+ const node = graph.addNode(nodeMetadata({+ id,+ label: isMindMap ? t("diagram.newTopic") : t("diagram.newStep"),+ x: nextPosition.x,+ y: nextPosition.y,+ width: shape === "decision" ? 132 : 140,+ height: shape === "decision" ? 84 : 52,+ shape: isMindMap ? "topic" : shape,+ ...(isMindMap && parent?.isNode() ? { parentId: parent.id } : {}),+ }, themeRef.current));+ if (isMindMap && parent?.isNode()) {+ graph.addEdge(edgeMetadata({ id: createId("branch"), source: parent.id, target: id }, document.kind, themeRef.current));+ }+ graph.stopBatch("add");+ graph.select(node);+ setSelectedNodeId(id);+ setSelectedNodeLabel(node.getData<NodeData>().label);+ setHasSelection(true);+ setDirty(true);+ setHistoryState({ undo: graph.canUndo(), redo: graph.canRedo() });+ if (options.beginEditing) {+ requestAnimationFrame(() => beginNodeEdit(node));+ }+ }, [beginNodeEdit, document, readOnly, selectedNodeId, t]);++ insertNodeRef.current = (relation, baseNodeId) => {+ addNode("topic", { relation, baseNodeId, beginEditing: true });+ };++ const updateSelectedLabel = (label: string) => {+ setSelectedNodeLabel(label);+ const node = selectedNodeId ? graphRef.current?.getCellById(selectedNodeId) : null;+ if (!node?.isNode() || readOnly) return;+ node.setData({ ...node.getData<NodeData>(), label });+ node.attr("label/text", label);+ };++ const removeSelected = () => {+ const graph = graphRef.current;+ if (!graph || readOnly) return;+ if (!removeGraphSelection(graph)) return;+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(false);+ if (document) {+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, themeRef.current),+ ));+ }+ setHistoryState({ undo: graph.canUndo(), redo: graph.canRedo() });+ };++ const runHistoryAction = (action: "undo" | "redo") => {+ const graph = graphRef.current;+ if (!graph || readOnly) return;+ if (action === "undo") graph.undo();+ else graph.redo();+ const nextTheme = detectGraphTheme(graph) ?? themeRef.current;+ themeRef.current = nextTheme;+ setTheme(nextTheme);+ applyDiagramSurface(graph, nextTheme, document?.kind ?? "flowchart");+ graph.cleanSelection();+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setHasSelection(false);+ setHistoryState({ undo: graph.canUndo(), redo: graph.canRedo() });+ if (document) {+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, nextTheme),+ ));+ }+ };++ const applyAutoLayout = () => {+ const graph = graphRef.current;+ if (!graph || !document || readOnly || graph.getNodes().length === 0) return;+ const positions = computeDiagramLayout(graphToDocument(graph, document.kind, themeRef.current));+ graph.startBatch("layout");+ let changed = false;+ for (const node of graph.getNodes()) {+ const position = positions[node.id];+ if (!position) continue;+ const currentPosition = node.getPosition();+ if (currentPosition.x !== position.x || currentPosition.y !== position.y) {+ changed = true;+ node.position(position.x, position.y);+ }+ }+ graph.stopBatch("layout");+ fitDiagramContent(graph, document, containerRef.current, 40);+ if (changed) {+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, themeRef.current),+ ));+ setHistoryState({ undo: graph.canUndo(), redo: graph.canRedo() });+ }+ };++ const applyTheme = (nextTheme: DiagramTheme) => {+ const graph = graphRef.current;+ if (nextTheme === theme) return;+ themeRef.current = nextTheme;+ setTheme(nextTheme);+ if (!graph || readOnly) return;+ graph.startBatch("update");+ for (const node of graph.getNodes()) {+ const data = node.getData<NodeData>();+ const shape = data?.shape ?? "process";+ const attrs = nodeAttrs(shape, nextTheme, shape === "topic" && !data?.parentId);+ node.attr("body", attrs.body);+ node.attr("label", { ...attrs.label, text: data?.label ?? "" });+ for (const port of node.getPorts()) {+ if (!port.id) continue;+ node.portProp(port.id, "attrs/circle", {+ stroke: DIAGRAM_THEMES[nextTheme].topicStroke,+ fill: DIAGRAM_THEMES[nextTheme].canvas,+ });+ }+ }+ for (const edge of graph.getEdges()) {+ edge.attr("line/stroke", document?.kind === "mind-map"+ ? DIAGRAM_THEMES[nextTheme].mindMapEdge+ : DIAGRAM_THEMES[nextTheme].flowEdge);+ if (edge.getLabels().length > 0) {+ edge.attr("label/fill", DIAGRAM_THEMES[nextTheme].nodeText);+ edge.attr("body/fill", DIAGRAM_THEMES[nextTheme].canvas);+ edge.attr("body/stroke", DIAGRAM_THEMES[nextTheme].nodeStroke);+ }+ }+ applyDiagramSurface(graph, nextTheme, document?.kind ?? "flowchart");+ graph.stopBatch("update");+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document?.kind ?? "flowchart", nextTheme),+ ));+ };++ const exportDiagram = (format: "png" | "svg") => {+ const graph = graphRef.current;+ if (!graph || !document) return;+ const fallbackName = document.kind === "mind-map" ? t("diagram.mindMap") : t("diagram.flowchart");+ const fileName = (title.trim() || fallbackName).replace(/[\\/:*?"<>|]/g, "-").slice(0, 80);+ setSaveError(null);+ try {+ const palette = DIAGRAM_THEMES[themeRef.current];+ const beforeSerialize = prepareExportSvg(palette.canvas);+ if (format === "png") {+ graph.exportPNG(fileName, { backgroundColor: palette.canvas, padding: 32, ratio: 2, copyStyles: false, beforeSerialize });+ } else {+ graph.exportSVG(fileName, { preserveDimensions: true, copyStyles: false, beforeSerialize });+ }+ } catch {+ setSaveError(t("diagram.exportError"));+ }+ };++ const save = async () => {+ const graph = graphRef.current;+ const currentMemo = memoRef.current;+ const editSession = editSessionRef.current;+ if (!graph || !document || !editSession || readOnly || saving) return;+ setSaving(true);+ setSaveError(null);+ try {+ const nextDocument = graphToDocument(graph, document.kind, themeRef.current);+ const markdown = serializeDiagramDocument(nextDocument);+ const nextTitle = titleRef.current;+ const result = await repository.updateMemo(currentMemo, {+ expectedRevision: currentMemo.revision,+ expectedContentHash: currentMemo.contentHash,+ editSessionId: editSession.id,+ title: nextTitle,+ contentJson: markdownToDoc(diagramFallbackMarkdown(nextDocument)),+ contentMarkdown: markdown,+ tags: currentMemo.tags,+ });+ memoRef.current = result.memo;+ savedSnapshotRef.current = diagramEditorSnapshot(nextTitle, nextDocument);+ setDirty(false);+ graph.cleanHistory();+ setHistoryState({ undo: false, redo: false });+ await onSaved(result.memo);+ } catch (error) {+ setSaveError(error instanceof Error ? error.message : t("diagram.saveError"));+ } finally {+ setSaving(false);+ }+ };+ saveRef.current = () => { void save(); };++ if (!document) return null;+ const kindLabel = document.kind === "mind-map" ? t("diagram.mindMap") : t("diagram.flowchart");++ return (+ <TooltipProvider>+ <div className="flex h-full min-h-0 flex-col bg-white">+ <header className="flex min-h-14 shrink-0 items-center gap-2 border-b border-slate-200 px-3 py-2">+ <Tooltip>+ <TooltipTrigger asChild>+ <Button size="icon" variant="ghost" aria-label={t("diagram.back")} onClick={() => dirty ? setConfirmDiscardOpen(true) : onBackToList()}>+ <ArrowLeft className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>{t("diagram.back")}</TooltipContent>+ </Tooltip>+ <div className="hidden rounded-full border border-[var(--brand-green-border)] bg-[var(--brand-green-soft)] px-2.5 py-1 text-xs font-semibold text-[var(--brand-green-text)] sm:block">{kindLabel}</div>+ <input+ className="min-w-0 flex-1 bg-transparent px-2 text-base font-semibold text-slate-950 outline-none placeholder:text-slate-400 disabled:text-slate-600"+ value={title}+ disabled={readOnly}+ maxLength={160}+ placeholder={kindLabel}+ aria-label={t("diagram.title")}+ onChange={(event) => {+ const nextTitle = event.target.value;+ titleRef.current = nextTitle;+ setTitle(nextTitle);+ const graph = graphRef.current;+ if (graph) {+ setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(+ nextTitle,+ graphToDocument(graph, document.kind, themeRef.current),+ ));+ }+ }}+ />+ <span className={cn("hidden text-xs sm:block", saveError ? "text-rose-600" : dirty ? "text-amber-600" : "text-slate-400")}>{saveError ?? (dirty ? t("diagram.unsaved") : t("diagram.saved"))}</span>+ {!readOnly && (+ <Button variant="solid" size="sm" disabled={!dirty || saving || !editSessionReady} onClick={() => void save()}>+ <Save className="h-4 w-4" />+ {saving ? t("diagram.saving") : t("diagram.save")}+ </Button>+ )}+ </header>++ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex shrink-0 flex-wrap items-center gap-1 border-b border-slate-200 bg-white px-3 py-2">+ {!readOnly && (+ document.kind === "mind-map" ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button size="sm" variant="soft" onClick={() => addNode("topic")}><GitBranch className="h-4 w-4" />{t("diagram.addTopic")}</Button>+ </TooltipTrigger>+ <TooltipContent>{t("diagram.mindMapShortcuts")}</TooltipContent>+ </Tooltip>+ ) : (+ <>+ <Button size="sm" variant="soft" onClick={() => addNode("process")}><Box className="h-4 w-4" />{t("diagram.addStep")}</Button>+ <Tooltip><TooltipTrigger asChild><Button size="sm" variant="ghost" aria-label={t("diagram.addDecision")} onClick={() => addNode("decision")}><Diamond className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.addDecision")}</TooltipContent></Tooltip>+ <Tooltip><TooltipTrigger asChild><Button size="sm" variant="ghost" aria-label={t("diagram.addTerminator")} onClick={() => addNode("terminator")}><Circle className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.addTerminator")}</TooltipContent></Tooltip>+ </>+ )+ )}+ <span className="mx-1 h-5 w-px bg-slate-200" />+ <Tooltip><TooltipTrigger asChild><Button size="icon" variant="ghost" aria-label={t("diagram.undo")} disabled={!historyState.undo || readOnly} onClick={() => runHistoryAction("undo")}><Undo2 className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.undo")}</TooltipContent></Tooltip>+ <Tooltip><TooltipTrigger asChild><Button size="icon" variant="ghost" aria-label={t("diagram.redo")} disabled={!historyState.redo || readOnly} onClick={() => runHistoryAction("redo")}><Redo2 className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.redo")}</TooltipContent></Tooltip>+ {!readOnly && <Tooltip><TooltipTrigger asChild><Button size="icon" variant="ghost" aria-label={t("diagram.deleteSelection")} disabled={!hasSelection} onClick={removeSelected}><Trash2 className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.deleteSelection")}</TooltipContent></Tooltip>}+ {!readOnly && <Tooltip><TooltipTrigger asChild><Button size="icon" variant="ghost" aria-label={t("diagram.autoLayout")} onClick={applyAutoLayout}><LayoutDashboard className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.autoLayout")}</TooltipContent></Tooltip>}+ <span className="mx-1 h-5 w-px bg-slate-200" />+ <Tooltip><TooltipTrigger asChild><Button size="icon" variant="ghost" aria-label={t("diagram.zoomOut")} onClick={() => graphRef.current?.zoom(-0.1)}><ZoomOut className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.zoomOut")}</TooltipContent></Tooltip>+ <Tooltip><TooltipTrigger asChild><Button size="icon" variant="ghost" aria-label={t("diagram.zoomIn")} onClick={() => graphRef.current?.zoom(0.1)}><ZoomIn className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.zoomIn")}</TooltipContent></Tooltip>+ <Tooltip><TooltipTrigger asChild><Button size="icon" variant="ghost" aria-label={t("diagram.fit")} onClick={() => { const graph = graphRef.current; if (graph) fitDiagramContent(graph, document, containerRef.current); }}><Maximize2 className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("diagram.fit")}</TooltipContent></Tooltip>+ <Select value={theme} disabled={readOnly} onValueChange={(value) => applyTheme(value as DiagramTheme)}>+ <SelectTrigger className="h-8 w-[8.5rem] gap-2" aria-label={t("diagram.theme")}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="brand" textValue={t("diagram.themeBrand")}><span className="flex items-center gap-2"><span className="h-3 w-3 rounded-full border border-black/10" style={{ background: DIAGRAM_THEMES.brand.topicFill }} />{t("diagram.themeBrand")}</span></SelectItem>+ <SelectItem value="ocean" textValue={t("diagram.themeOcean")}><span className="flex items-center gap-2"><span className="h-3 w-3 rounded-full border border-black/10" style={{ background: DIAGRAM_THEMES.ocean.topicFill }} />{t("diagram.themeOcean")}</span></SelectItem>+ <SelectItem value="ink" textValue={t("diagram.themeInk")}><span className="flex items-center gap-2"><span className="h-3 w-3 rounded-full border border-black/10" style={{ background: DIAGRAM_THEMES.ink.nodeFill }} />{t("diagram.themeInk")}</span></SelectItem>+ </SelectContent>+ </Select>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button size="sm" variant="outline"><Download className="h-4 w-4" />{t("diagram.export")}</Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onSelect={() => exportDiagram("png")}><FileImage className="h-4 w-4" />{t("diagram.exportPng")}</DropdownMenuItem>+ <DropdownMenuItem onSelect={() => exportDiagram("svg")}><FileCode2 className="h-4 w-4" />{t("diagram.exportSvg")}</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ {selectedNodeId && !readOnly && (+ <div className="ml-auto flex min-w-[220px] flex-1 items-center gap-2 sm:max-w-sm">+ <span className="shrink-0 text-xs font-medium text-slate-500">{t("diagram.nodeText")}</span>+ <Input value={selectedNodeLabel} maxLength={120} onChange={(event) => updateSelectedLabel(event.target.value)} />+ </div>+ )}+ </div>+ <div className="relative min-h-0 flex-1">+ <div ref={containerRef} className="edgeever-diagram-canvas absolute inset-0 touch-none outline-none" data-diagram-theme={theme} tabIndex={0} aria-label={t("diagram.canvas", { type: kindLabel })} />+ {nodeEditor ? (+ <input+ autoFocus+ className="absolute z-20 px-3 text-center font-medium outline-none"+ style={{+ left: nodeEditor.left,+ top: nodeEditor.top,+ width: nodeEditor.width,+ height: nodeEditor.height,+ fontSize: nodeEditor.fontSize,+ color: nodeEditor.color,+ background: nodeEditor.background,+ border: `2px solid ${nodeEditor.borderColor}`,+ borderRadius: nodeEditor.shape === "terminator" ? 999 : 11,+ clipPath: nodeEditor.shape === "decision" ? "polygon(50% 0, 100% 50%, 50% 100%, 0 50%)" : undefined,+ }}+ value={nodeEditor.value}+ maxLength={120}+ aria-label={t("diagram.editNode")}+ onFocus={(event) => event.currentTarget.select()}+ onChange={(event) => {+ const nextEditor = { ...nodeEditor, value: event.target.value };+ nodeEditorRef.current = nextEditor;+ setNodeEditor(nextEditor);+ }}+ onBlur={() => { finishNodeEdit(); }}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ event.preventDefault();+ finishNodeEdit(true);+ return;+ }+ if (event.key === "Enter") {+ event.preventDefault();+ const editedNode = finishNodeEdit();+ if (document.kind === "mind-map" && editedNode) {+ requestAnimationFrame(() => insertNodeRef.current("sibling", editedNode.id));+ }+ return;+ }+ if (event.key === "Tab" && document.kind === "mind-map") {+ event.preventDefault();+ const editedNode = finishNodeEdit();+ if (editedNode) requestAnimationFrame(() => insertNodeRef.current("child", editedNode.id));+ }+ }}+ />+ ) : null}+ </div>+ </div>+ {confirmDiscardOpen ? (+ <AppConfirmDialog+ title={t("diagram.discardTitle")}+ description={t("diagram.discardDescription")}+ confirmLabel={t("diagram.discard")}+ tone="danger"+ onCancel={() => setConfirmDiscardOpen(false)}+ onConfirm={onBackToList}+ />+ ) : null}+ </div>+ </TooltipProvider>+ );+};++export default DiagramEditorPane;diff --git a/apps/web/src/components/NotebookPane.tsx b/apps/web/src/components/NotebookPane.tsxindex 53a79ee6..cc51557b 100644--- a/apps/web/src/components/NotebookPane.tsx+++ b/apps/web/src/components/NotebookPane.tsx@@ -23,6 +23,9 @@ import {Download,ExternalLink,RotateCcw,+ FileText,+ Network,+ Workflow,} from "lucide-react";import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";@@ -39,7 +42,7 @@ import {} from "@/components/ui/dropdown-menu";import { NotebookTreeItem } from "./NotebookTreeItem";import { cn } from "@/lib/utils";-import type { Notebook, AuthUser } from "@edgeever/shared";+import type { Notebook, AuthUser, DiagramKind } from "@edgeever/shared";import type { NotebookNode, NotebookDropPosition, NotebookSortMode } from "@/lib/app-helpers";import type { SyncQueueSummary } from "@/lib/sync-queue";import {@@ -392,7 +395,7 @@ export const NotebookPane = ({onOpenTrash: () => void;onEmptyTrash: () => void;onOpenSettings: () => void;- onCreateMemo: () => void;+ onCreateMemo: (kind?: DiagramKind) => void;canCreateMemo: boolean;isCreatingMemo: boolean;syncSummary: SyncQueueSummary;@@ -558,7 +561,7 @@ export const NotebookPane = ({type="button"title={t("notebookPane.newMemo")}aria-label={t("notebookPane.newMemo")}- onClick={onCreateMemo}+ onClick={() => onCreateMemo()}disabled={!canCreateMemo || isCreatingMemo}><span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-emerald-600 text-white shadow-[0_8px_18px_rgb(var(--brand-green-rgb)/0.28)] transition-transform duration-200 group-hover:scale-105">@@ -566,6 +569,34 @@ export const NotebookPane = ({</span><span className="min-w-0 truncate text-sm font-semibold text-slate-950">{t("notebookPane.newMemo")}</span></button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="flex h-14 w-14 shrink-0 items-center justify-center border-l border-slate-200 text-slate-600 transition-colors hover:bg-emerald-50 hover:text-emerald-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-emerald-500 disabled:cursor-not-allowed disabled:opacity-50"+ type="button"+ aria-label={t("diagram.createType")}+ disabled={!canCreateMemo || isCreatingMemo}+ >+ <span className="grid grid-cols-2 gap-0.5" aria-hidden="true">+ {[0, 1, 2, 3].map((item) => <span key={item} className="h-1.5 w-1.5 rounded-[2px] border border-current" />)}+ </span>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={8} className="w-52">+ <DropdownMenuItem onSelect={() => onCreateMemo()}>+ <FileText className="h-4 w-4" />+ {t("diagram.normalNote")}+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onCreateMemo("mind-map")}>+ <Network className="h-4 w-4" />+ {t("diagram.mindMap")}+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onCreateMemo("flowchart")}>+ <Workflow className="h-4 w-4" />+ {t("diagram.flowchart")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></div></div>diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsxindex 9828d1b3..6d8edcaf 100644--- a/apps/web/src/components/WorkspaceApp.tsx+++ b/apps/web/src/components/WorkspaceApp.tsx@@ -15,10 +15,11 @@ import {} from "react";import { useInfiniteQuery, useQuery, useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query";import type { PluginPanelOpenOptions } from "@edgeever/plugin-api";-import { Home, Search, UserRound, Plus, ChevronDown, ChevronRight, RefreshCw, X } from "lucide-react";+import { Home, Search, UserRound, Plus, ChevronDown, ChevronRight, RefreshCw, X, FileText, Network, Workflow } from "lucide-react";import { useTranslation } from "react-i18next";import * as m from "motion/react-m";import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import {Drawer,DrawerContent,@@ -43,7 +44,7 @@ import {} from "@/lib/mobile-editor";import { cn } from "@/lib/utils";import { isBrowserOffline, isBrowserOnline } from "@/lib/network-status";-import { createExcerpt, docToText, getNotebookDescendantIds, resolveMemoContentDoc, type Notebook, type AuthUser, type MemoSummary, type MemoDetail, type MemoTemplate as SavedMemoTemplate } from "@edgeever/shared";+import { createDefaultDiagramDocument, createExcerpt, diagramFallbackMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, parseDiagramDocument, resolveMemoContentDoc, serializeDiagramDocument, type DiagramKind, type Notebook, type AuthUser, type MemoSummary, type MemoDetail, type MemoTemplate as SavedMemoTemplate } from "@edgeever/shared";import { toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";import type {Pane,@@ -148,6 +149,7 @@ const getVerticalScrollContainer = (target: EventTarget | null) => {};const EditorPane = lazy(() => import("./EditorPane").then((module) => ({ default: module.EditorPane })));+const DiagramEditorPane = lazy(() => import("./DiagramEditorPane"));const AssetsPane = lazy(() => import("./AssetsPane").then((module) => ({ default: module.AssetsPane })));const SettingsPane = lazy(() => import("./SettingsPane").then((module) => ({ default: module.SettingsPane })));const PluginMarketplacePane = lazy(() => import("./PluginMarketplacePane").then((module) => ({ default: module.PluginMarketplacePane })));@@ -363,7 +365,7 @@ const MobileBottomNav = ({activeItem: MobileBottomNavItem;canCreateMemo: boolean;isCreating: boolean;- onCreateMemo: () => void;+ onCreateMemo: (kind?: DiagramKind) => void;onHome: () => void;onOpenSettings: () => void;}) => {@@ -377,16 +379,24 @@ const MobileBottomNav = ({><div className="relative grid h-mobile-bottom-nav grid-cols-3 items-center"><MobileBottomNavButton active={activeItem === "home"} icon={<Home className="h-5 w-5" />} label={t("nav.home")} onClick={onHome} />- <button- className="flex h-mobile-touch flex-col items-center justify-center gap-0.5 rounded-md text-xs font-medium text-emerald-700 transition hover:bg-emerald-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500 disabled:cursor-not-allowed disabled:opacity-50"- type="button"- aria-label={createMemoLabel}- disabled={!canCreateMemo || isCreating}- onClick={onCreateMemo}- >- <Plus className="h-5 w-5" />- <span>{t("nav.createMemo")}</span>- </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="flex h-mobile-touch flex-col items-center justify-center gap-0.5 rounded-md text-xs font-medium text-emerald-700 transition hover:bg-emerald-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500 disabled:cursor-not-allowed disabled:opacity-50"+ type="button"+ aria-label={createMemoLabel}+ disabled={!canCreateMemo || isCreating}+ >+ <Plus className="h-5 w-5" />+ <span>{t("nav.createMemo")}</span>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="center" side="top" sideOffset={8} className="w-52">+ <DropdownMenuItem onSelect={() => onCreateMemo()}><FileText className="h-4 w-4" />{t("diagram.normalNote")}</DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onCreateMemo("mind-map")}><Network className="h-4 w-4" />{t("diagram.mindMap")}</DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onCreateMemo("flowchart")}><Workflow className="h-4 w-4" />{t("diagram.flowchart")}</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu><MobileBottomNavButton active={activeItem === "settings"} icon={<UserRound className="h-5 w-5" />} label={t("nav.mine")} onClick={onOpenSettings} /></div></nav>@@ -1667,6 +1677,7 @@ export const WorkspaceApp = ({},onSuccess: (data) => {const targetNotebookId = data.memo.notebookId;+ const isDiagram = Boolean(parseDiagramDocument(data.memo.contentMarkdown));setMemoView("notebook");setSearch("");@@ -1688,11 +1699,11 @@ export const WorkspaceApp = ({navigateWorkspaceHome();setRightView("editor");pendingCreatedMemoIdRef.current = data.memo.id;- setCreatedMemoEditId(data.memo.id);+ setCreatedMemoEditId(isDiagram ? null : data.memo.id);setSelectedMemoId(data.memo.id);setActivePane("editor");- if (!isDesktopViewport()) {+ if (!isDesktopViewport() && !isDiagram) {openStandaloneMobileEditor(data.memo.id);}},@@ -2035,6 +2046,7 @@ export const WorkspaceApp = ({? queryClient.getQueryData<{ memo: MemoDetail }>(memoDetailQueryKey(detailMemoId, memoView))?.memo ?? null: null;const selectedMemo = memoQuery.data?.memo ?? cachedSelectedMemo;+ const selectedDiagram = parseDiagramDocument(selectedMemo?.contentMarkdown);const desktopFocusModeActive = Boolean(isDesktop && desktopFocusMode && rightView === "editor" && selectedMemo && !memoSelectionModeActive);@@ -2103,7 +2115,7 @@ export const WorkspaceApp = ({setNotebookDeleteConfirmation(notebook);};- const handleCreateMemo = () => {+ const handleCreateMemo = (kind?: DiagramKind) => {const targetNotebookId = createMemoNotebookId;if (!targetNotebookId || memoView === "trash") {@@ -2113,10 +2125,12 @@ export const WorkspaceApp = ({setTemplatesOpen(false);setMobileBottomNavActive("home");creatingMemoSelectionRef.current = true;+ const diagram = kind ? createDefaultDiagramDocument(kind) : null;createMemoMutation.mutate({notebookId: targetNotebookId,- title: "",- contentMarkdown: "",+ title: diagram ? (kind === "mind-map" ? t("diagram.mindMap") : t("diagram.flowchart")) : "",+ contentJson: diagram ? markdownToDoc(diagramFallbackMarkdown(diagram)) : undefined,+ contentMarkdown: diagram ? serializeDiagramDocument(diagram) : "",tags: [],});};@@ -3401,6 +3415,26 @@ export const WorkspaceApp = ({setActivePane("memos");}}>+ {selectedMemo && selectedDiagram ? (+ <DiagramEditorPane+ memo={selectedMemo}+ repository={repository}+ readOnly={memoView === "trash" || selectedMemo.isDeleted}+ onBackToList={() => {+ clearPendingCreatedMemo();+ setActivePane("memos");+ }}+ onSaved={async (memo) => {+ await putLocalMemo(localDataScope, memo);+ cacheMemoDetail(queryClient, memo, memoView);+ updateMemoSummaryInLists(queryClient, memoToSummary(memo));+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["memos"], refetchType: "inactive" }),+ queryClient.invalidateQueries({ queryKey: ["notebooks"], refetchType: "inactive" }),+ ]);+ }}+ />+ ) : (<EditorPaneonOpenExecutionCenter={handleOpenExecutionCenter}companionDiscoveryHub={authRequired && Boolean(user) && !demoMode ? (@@ -3506,6 +3540,7 @@ export const WorkspaceApp = ({onMobileDefaultEditConsumed={handleMobileDefaultEditConsumed}onSaveAsTemplate={handleSaveAsTemplate}/>+ )}</EditorPaneErrorBoundary>)}</m.div>diff --git a/apps/web/src/lib/desktop-repository.ts b/apps/web/src/lib/desktop-repository.tsindex 6ab09fa1..a8003c10 100644--- a/apps/web/src/lib/desktop-repository.ts+++ b/apps/web/src/lib/desktop-repository.ts@@ -230,6 +230,7 @@ export const createDesktopRepository = (): EdgeEverRepository => ({const rpcParams: DesktopMemoCreateParams = {...input,contentMarkdown: mapMarkdownResourceUrls(input.contentMarkdown, toApiResourceUrl),+ contentText: input.contentJson ? docToText(input.contentJson) : undefined,};return request("memo.create", rpcParams).then((result) => {window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed"));diff --git a/apps/web/src/lib/diagram-layout.test.mjs b/apps/web/src/lib/diagram-layout.test.mjsnew file mode 100644index 00000000..8d14ab02--- /dev/null+++ b/apps/web/src/lib/diagram-layout.test.mjs@@ -0,0 +1,28 @@+import { describe, expect, test } from "bun:test";+import { createDefaultDiagramDocument } from "@edgeever/shared";+import { compactMindMapNodeSize, computeDiagramLayout } from "./diagram-layout.ts";++describe("diagram auto layout", () => {+ test("places mind-map children to the right of their root", () => {+ const document = createDefaultDiagramDocument("mind-map");+ const positions = computeDiagramLayout(document);+ expect(positions["topic-root"].x).toBeLessThan(positions["topic-1"].x);+ expect(new Set(document.nodes.map((node) => positions[node.id].y)).size).toBeGreaterThan(1);+ });++ test("uses compact topic sizes while allowing longer labels to grow within a cap", () => {+ expect(compactMindMapNodeSize("分支主题", false)).toEqual({ width: 92, height: 36 });+ expect(compactMindMapNodeSize("核心主题", true)).toEqual({ width: 112, height: 42 });+ expect(compactMindMapNodeSize("A much longer topic label", false).width).toBeLessThanOrEqual(156);+ });++ test("orders a connected flow from left to right and keeps detached nodes finite", () => {+ const document = createDefaultDiagramDocument("flowchart");+ document.nodes.push({ id: "detached", label: "Detached", x: 0, y: 0, width: 140, height: 52, shape: "process" });+ const positions = computeDiagramLayout(document);+ expect(positions["flow-start"].x).toBeLessThan(positions["flow-process"].x);+ expect(positions["flow-process"].x).toBeLessThan(positions["flow-end"].x);+ expect(Number.isFinite(positions.detached.x)).toBeTrue();+ expect(Number.isFinite(positions.detached.y)).toBeTrue();+ });+});diff --git a/apps/web/src/lib/diagram-layout.ts b/apps/web/src/lib/diagram-layout.tsnew file mode 100644index 00000000..a5128275--- /dev/null+++ b/apps/web/src/lib/diagram-layout.ts@@ -0,0 +1,43 @@+import { graphlib, layout as runDagreLayout } from "@dagrejs/dagre";+import type { DiagramDocument } from "@edgeever/shared";++export type DiagramLayoutPositions = Record<string, { x: number; y: number }>;++const visualTextUnits = (label: string) => Array.from(label).reduce(+ (total, character) => total + (/[^\u0000-\u00ff]/.test(character) ? 1 : 0.55),+ 0,+);++export const compactMindMapNodeSize = (label: string, isRoot: boolean) => ({+ width: Math.round(Math.min(isRoot ? 168 : 156, Math.max(isRoot ? 112 : 92, visualTextUnits(label) * 13 + 28))),+ height: isRoot ? 42 : 36,+});++export const computeDiagramLayout = (document: DiagramDocument): DiagramLayoutPositions => {+ const layoutGraph = new graphlib.Graph();+ layoutGraph.setGraph({+ rankdir: "LR",+ ranksep: document.kind === "mind-map" ? 72 : 130,+ nodesep: document.kind === "mind-map" ? 24 : 56,+ marginx: 32,+ marginy: 32,+ });+ layoutGraph.setDefaultEdgeLabel(() => ({}));++ for (const node of document.nodes) {+ layoutGraph.setNode(node.id, { width: node.width, height: node.height });+ }+ for (const edge of document.edges) {+ layoutGraph.setEdge(edge.source, edge.target);+ }++ runDagreLayout(layoutGraph);+ return Object.fromEntries(document.nodes.flatMap((node) => {+ const position = layoutGraph.node(node.id) as { x: number; y: number } | undefined;+ if (!position) return [];+ return [[node.id, {+ x: Math.round(position.x - node.width / 2),+ y: Math.round(position.y - node.height / 2),+ }]];+ }));+};diff --git a/apps/web/src/lib/local-db.ts b/apps/web/src/lib/local-db.tsindex 586e6647..682407c0 100644--- a/apps/web/src/lib/local-db.ts+++ b/apps/web/src/lib/local-db.ts@@ -42,6 +42,7 @@ export type MemoCreateSyncPayload = {temporaryId: string;notebookId: string;title: string;+ contentJson?: TiptapDoc;contentMarkdown?: string;tags: string[];createdAt: string;diff --git a/apps/web/src/lib/repository.ts b/apps/web/src/lib/repository.tsindex e0ec68ae..e58c6bf7 100644--- a/apps/web/src/lib/repository.ts+++ b/apps/web/src/lib/repository.ts@@ -76,7 +76,7 @@ export type EdgeEverRepository = {mergeMemos(input: { memoIds: string[]; notebookId?: string; title?: string }): Promise<{ memo: MemoDetail }>;listMemos(params: LocalMemoListParams): Promise<LocalMemoListResponse>;getMemo(memoId: string, includeDeleted?: boolean): Promise<{ memo: MemoDetail }>;- createMemo(input: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[] }): Promise<{ memo: MemoDetail }>;+ createMemo(input: { notebookId: string; title?: string; contentJson?: TiptapDoc; contentMarkdown?: string; tags?: string[] }): Promise<{ memo: MemoDetail }>;updateMemo(memo: MemoDetail, input: Omit<MemoUpdateSyncPayload, "memoId">): Promise<{ memo: MemoDetail; queued: true }>;/*** Drop the local conflicted draft for a note and replace the local copy with@@ -494,6 +494,7 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {temporaryId: memo.id,notebookId: input.notebookId,title: input.title ?? "",+ contentJson: input.contentJson,contentMarkdown: input.contentMarkdown,tags: input.tags ?? [],createdAt: memo.createdAt,diff --git a/apps/web/src/lib/sync-queue.ts b/apps/web/src/lib/sync-queue.tsindex c7513e5e..2ff1081d 100644--- a/apps/web/src/lib/sync-queue.ts+++ b/apps/web/src/lib/sync-queue.ts@@ -645,6 +645,7 @@ const syncQueueItem = async (item: SyncQueueItem): Promise<SyncQueueResult> => {const data = await api.createMemo({notebookId: payload.notebookId,title: payload.title,+ contentJson: payload.contentJson,contentMarkdown: payload.contentMarkdown,tags: payload.tags,createdAt: payload.createdAt,diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.cssindex f3575d85..22036c33 100644--- a/apps/web/src/styles/globals.css+++ b/apps/web/src/styles/globals.css@@ -476,6 +476,41 @@ html[data-edgeever-extension-theme] .edgeever-memo-divider {background: var(--workspace-selection) !important;}+/* X6 ships blue/orange interaction chrome. Keep the engine behavior while+ * making selection and keyboard focus belong to EdgeEver's visual system. */+.edgeever-diagram-canvas:focus-visible {+ box-shadow: inset 0 0 0 2px rgb(var(--brand-green-rgb) / 0.5);+}++.edgeever-diagram-canvas .x6-widget-selection-rubberband {+ border-color: var(--brand-green) !important;+ background-color: var(--brand-green-muted) !important;+}++.edgeever-diagram-canvas .x6-widget-selection-box,+.edgeever-diagram-canvas .x6-widget-selection-inner {+ border-color: var(--brand-green) !important;+ box-shadow: 0 2px 8px rgb(var(--brand-green-rgb) / 0.18) !important;+}++.edgeever-diagram-canvas[data-diagram-theme="ink"] .x6-widget-selection-box,+.edgeever-diagram-canvas[data-diagram-theme="ink"] .x6-widget-selection-inner {+ border-color: #68d6b0 !important;+ box-shadow: 0 2px 10px rgb(104 214 176 / 0.22) !important;+}++@media (hover: hover) and (pointer: fine) {+ .edgeever-diagram-canvas .x6-port-body {+ opacity: 0;+ transition: opacity 120ms ease;+ }++ .edgeever-diagram-canvas .x6-node:hover .x6-port-body,+ .edgeever-diagram-canvas .x6-port-body:hover {+ opacity: 1;+ }+}+/* Curated reading themes should feel like part of the note canvas in dark* mode. Custom themes keep their explicit background as an intentional user* choice, while bundled themes contribute typography and semantic colors. */diff --git a/bun.lock b/bun.lockindex 73256e17..b4c04749 100644--- a/bun.lock+++ b/bun.lock@@ -211,7 +211,9 @@"name": "@edgeever/web","version": "0.1.3","dependencies": {+ "@antv/x6": "3.1.8","@codemirror/lang-markdown": "^6.5.2",+ "@dagrejs/dagre": "3.1.1","@edgeever/client": "workspace:*","@floating-ui/react-dom": "^2.1.8","@fontsource-variable/noto-sans-sc": "^5.2.8",@@ -302,6 +304,8 @@"@antfu/utils": ["@antfu/[email protected]", "", {}, "sha512-Mex9nXf9vR6AhcXmMrlz/HVgYYZpVGJ6YlPgwl7UnaFpnshXs6EK/oa5Gpf3CzENMjkvEx2tQtntGnb7UtSTOQ=="],+ "@antv/x6": ["@antv/[email protected]", "", { "dependencies": { "dom-align": "^1.12.4", "lodash-es": "^4.17.15", "mousetrap": "^1.6.5", "utility-types": "^3.10.0" } }, "sha512-JVGxBRmjnqDr7W7Ql5XWc6FUtFcy+QlFaV31cv0pHIeVIJmyYnB5rHmdzz93CY5lCS/XcNBtOnNIIq6JVgfZ5w=="],+"@apideck/better-ajv-errors": ["@apideck/[email protected]", "", { "dependencies": { "jsonpointer": "^5.0.1", "leven": "^3.1.0" }, "peerDependencies": { "ajv": ">=8" } }, "sha512-TajUJwGWbDwkCx/CZi7tRE8PVB7simCvKJfHUsSdvps+aTM/PDPP4gkLmKnc+x3CE//y9i/nj74GqdL/hwk7Iw=="],"@astrojs/check": ["@astrojs/[email protected]", "", { "dependencies": { "@astrojs/language-server": "^2.8.4", "chokidar": "^3.5.3", "fast-glob": "^3.3.1", "kleur": "^4.1.5", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": "^5.0.0" }, "bin": { "astro-check": "dist/bin.js" } }, "sha512-vliHXM9cu/viGeKiksUM4mXfO816ohWtawTl2ADPgTsd4nUMjFiyAl7xFZhF34yy4hq4qf7jvK1F2PlR3b5I5w=="],@@ -636,6 +640,10 @@"@cspotcode/source-map-support": ["@cspotcode/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],+ "@dagrejs/dagre": ["@dagrejs/[email protected]", "", { "dependencies": { "@dagrejs/graphlib": "4.0.5" } }, "sha512-zroZB1dFOFiGgv4Xcrn1DckB1o4aOikPqD2NDQPV0WM//CXGcS6xiD0rNkqHmw6FEg4tabt4nxPLwgCWT+Vb2A=="],++ "@dagrejs/graphlib": ["@dagrejs/[email protected]", "", {}, "sha512-7xrBTqIts3o+PMUZX97wSc+7TUbW+/rULzGNCTP6yooNVDXbzw4Wutg/H/xOutTB/c/k0YqOAavgPh4/Zk9PFA=="],+"@devicefarmer/adbkit": ["@devicefarmer/[email protected]", "", { "dependencies": { "@devicefarmer/adbkit-logcat": "^2.1.2", "@devicefarmer/adbkit-monkey": "~1.2.1", "bluebird": "~3.7", "commander": "^9.1.0", "debug": "~4.3.1", "node-forge": "^1.3.1", "split": "~1.0.1" }, "bin": { "adbkit": "bin/adbkit" } }, "sha512-7rBLLzWQnBwutH2WZ0EWUkQdihqrnLYCUMaB44hSol9e0/cdIhuNFcqZO0xNheAU6qqHVA8sMiLofkYTgb+lmw=="],"@devicefarmer/adbkit-logcat": ["@devicefarmer/[email protected]", "", {}, "sha512-yeaGFjNBc/6+svbDeul1tNHtNChw6h8pSHAt5D+JsedUrMTN7tla7B15WLDyekxsuS2XlZHRxpuC6m92wiwCNw=="],@@ -2160,6 +2168,8 @@"dnssd-advertise": ["[email protected]", "", {}, "sha512-Ndrrf6BMPalkQPd/zubL+4YghH2J9NspapQ09uDXwYbvOPkP0oaqf5CkcwJ0b50kS2O3ul6yVu+jz+RY62Cejg=="],+ "dom-align": ["[email protected]", "", {}, "sha512-R8LUSEay/68zE5c8/3BDxiTEvgb4xZTF0RKmAHfiEVN3klfIpXfi2/QCoiWPccVQ0J/ZGdz9OjzL4uJEP/MRAw=="],+"dom-serializer": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],"domelementtype": ["[email protected]", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="],@@ -3130,6 +3140,8 @@"motion-utils": ["[email protected]", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="],+ "mousetrap": ["[email protected]", "", {}, "sha512-QNo4kEepaIBwiT8CDhP98umTetp+JNfQYBWvC1pc6/OAibuXtRcxZ58Qz8skvEHYvURne/7R8T5VoOI7rDsEUA=="],+"mrmime": ["[email protected]", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],@@ -3966,6 +3978,8 @@"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],+ "utility-types": ["[email protected]", "", {}, "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw=="],+"utils-merge": ["[email protected]", "", {}, "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="],"uuid": ["[email protected]", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew=="],diff --git a/crates/desktop-sidecar/src/memo.rs b/crates/desktop-sidecar/src/memo.rsindex 324e9903..6479f4bb 100644--- a/crates/desktop-sidecar/src/memo.rs+++ b/crates/desktop-sidecar/src/memo.rs@@ -482,7 +482,11 @@ pub(crate) fn create_memo(database: &Connection, params: &Value) -> Result<Value.cloned().unwrap_or_else(|| markdown_doc(&markdown));let content_json_text = content_json.to_string();- let text = markdown.lines().collect::<Vec<_>>().join(" ");+ let text = params+ .get("contentText")+ .and_then(Value::as_str)+ .map(str::to_owned)+ .unwrap_or_else(|| markdown.lines().collect::<Vec<_>>().join(" "));let id = now_id("memo_local");let hash = content_hash(&markdown, &content_json_text);let tx = database@@ -497,7 +501,8 @@ pub(crate) fn create_memo(database: &Connection, params: &Value) -> Result<Value"memo.create",&id,&json!({- "temporaryId": id, "notebookId": notebook_id, "title": title, "contentMarkdown": markdown,+ "temporaryId": id, "notebookId": notebook_id, "title": title, "contentJson": content_json,+ "contentMarkdown": markdown,"tags": tags, "createdAt": memo.get("createdAt").and_then(Value::as_str).unwrap_or(""),"updatedAt": memo.get("updatedAt").and_then(Value::as_str).unwrap_or("")}),diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex 466a7f37..37c51d72 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -963,6 +963,7 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {createMemo: (payload: {notebookId: string;title?: string;+ contentJson?: TiptapDoc;contentMarkdown?: string;tags?: string[];createdAt?: string;diff --git a/packages/shared/src/desktop-rpc.ts b/packages/shared/src/desktop-rpc.tsindex fdcf83be..ad09206a 100644--- a/packages/shared/src/desktop-rpc.ts+++ b/packages/shared/src/desktop-rpc.ts@@ -67,7 +67,9 @@ export type DesktopMemoListParams = {export type DesktopMemoCreateParams = {notebookId: string;title?: string;+ contentJson?: TiptapDoc;contentMarkdown?: string;+ contentText?: string;tags?: string[];};diff --git a/packages/shared/src/diagram.test.mjs b/packages/shared/src/diagram.test.mjsnew file mode 100644index 00000000..b1c2acc7--- /dev/null+++ b/packages/shared/src/diagram.test.mjs@@ -0,0 +1,32 @@+import { describe, expect, test } from "bun:test";+import { createDefaultDiagramDocument, parseDiagramDocument, serializeDiagramDocument } from "./diagram.ts";++describe("diagram document", () => {+ test("round-trips unicode labels through the Markdown compatibility envelope", () => {+ const document = createDefaultDiagramDocument("mind-map");+ document.nodes[0].label = "产品路线图 🚀";+ document.theme = "ocean";+ expect(parseDiagramDocument(serializeDiagramDocument(document))).toEqual(document);+ });++ test("keeps a readable Markdown fallback", () => {+ const markdown = serializeDiagramDocument(createDefaultDiagramDocument("flowchart"));+ expect(markdown).toContain("# 流程图");+ expect(markdown).toContain("- 处理步骤");+ });++ test("rejects malformed and dangling graph data", () => {+ expect(parseDiagramDocument("ordinary note")).toBeNull();+ const document = createDefaultDiagramDocument("flowchart");+ document.nodes = document.nodes.slice(0, 1);+ expect(parseDiagramDocument(serializeDiagramDocument(document))).toBeNull();++ const mindMap = createDefaultDiagramDocument("mind-map");+ mindMap.nodes[1].parentId = "missing-parent";+ expect(parseDiagramDocument(serializeDiagramDocument(mindMap))).toBeNull();++ const invalidTheme = createDefaultDiagramDocument("mind-map");+ invalidTheme.theme = "neon";+ expect(parseDiagramDocument(serializeDiagramDocument(invalidTheme))).toBeNull();+ });+});diff --git a/packages/shared/src/diagram.ts b/packages/shared/src/diagram.tsnew file mode 100644index 00000000..da8e9e75--- /dev/null+++ b/packages/shared/src/diagram.ts@@ -0,0 +1,162 @@+export const DIAGRAM_SCHEMA_VERSION = 1 as const;++export type DiagramKind = "mind-map" | "flowchart";+export type DiagramNodeShape = "topic" | "process" | "decision" | "terminator";+export type DiagramTheme = "brand" | "ocean" | "ink";++export type DiagramNode = {+ id: string;+ label: string;+ x: number;+ y: number;+ width: number;+ height: number;+ shape: DiagramNodeShape;+ parentId?: string;+};++export type DiagramEdge = {+ id: string;+ source: string;+ target: string;+ label?: string;+};++export type DiagramDocument = {+ schemaVersion: typeof DIAGRAM_SCHEMA_VERSION;+ kind: DiagramKind;+ theme?: DiagramTheme;+ nodes: DiagramNode[];+ edges: DiagramEdge[];+};++const DIAGRAM_MARKER = "edgeever-diagram-v1";+const DIAGRAM_COMMENT = new RegExp(`<!--\\s*${DIAGRAM_MARKER}:([A-Za-z0-9_-]+)\\s*-->`);++const encodeBase64Url = (value: string) => {+ const bytes = new TextEncoder().encode(value);+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");+};++const decodeBase64Url = (value: string) => {+ const base64 = value.replace(/-/g, "+").replace(/_/g, "/");+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");+ const binary = atob(padded);+ return new TextDecoder().decode(Uint8Array.from(binary, (character) => character.charCodeAt(0)));+};++const isFiniteNumber = (value: unknown): value is number =>+ typeof value === "number" && Number.isFinite(value);++const parseNode = (value: unknown): DiagramNode | null => {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const node = value as Record<string, unknown>;+ if (+ typeof node.id !== "string" || !node.id || typeof node.label !== "string"+ || !isFiniteNumber(node.x) || !isFiniteNumber(node.y)+ || !isFiniteNumber(node.width) || !isFiniteNumber(node.height)+ || !["topic", "process", "decision", "terminator"].includes(String(node.shape))+ ) return null;+ return {+ id: node.id,+ label: node.label,+ x: node.x,+ y: node.y,+ width: node.width,+ height: node.height,+ shape: node.shape as DiagramNodeShape,+ ...(typeof node.parentId === "string" && node.parentId ? { parentId: node.parentId } : {}),+ };+};++const parseEdge = (value: unknown): DiagramEdge | null => {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const edge = value as Record<string, unknown>;+ if (typeof edge.id !== "string" || !edge.id || typeof edge.source !== "string" || typeof edge.target !== "string") return null;+ return {+ id: edge.id,+ source: edge.source,+ target: edge.target,+ ...(typeof edge.label === "string" && edge.label ? { label: edge.label } : {}),+ };+};++export const parseDiagramDocument = (markdown: string | null | undefined): DiagramDocument | null => {+ const encoded = markdown?.match(DIAGRAM_COMMENT)?.[1];+ if (!encoded) return null;+ try {+ const value = JSON.parse(decodeBase64Url(encoded)) as Record<string, unknown>;+ if (value.schemaVersion !== DIAGRAM_SCHEMA_VERSION || (value.kind !== "mind-map" && value.kind !== "flowchart")) return null;+ if (+ !Array.isArray(value.nodes)+ || !Array.isArray(value.edges)+ || (value.theme !== undefined && !["brand", "ocean", "ink"].includes(String(value.theme)))+ ) return null;+ const nodes = value.nodes.map(parseNode);+ const edges = value.edges.map(parseEdge);+ if (nodes.some((node) => !node) || edges.some((edge) => !edge)) return null;+ const nodeIds = new Set((nodes as DiagramNode[]).map((node) => node.id));+ if (+ nodeIds.size !== nodes.length+ || (nodes as DiagramNode[]).some((node) => node.parentId && (node.parentId === node.id || !nodeIds.has(node.parentId)))+ || (edges as DiagramEdge[]).some((edge) => !nodeIds.has(edge.source) || !nodeIds.has(edge.target))+ ) return null;+ return {+ schemaVersion: DIAGRAM_SCHEMA_VERSION,+ kind: value.kind,+ ...(value.theme ? { theme: value.theme as DiagramTheme } : {}),+ nodes: nodes as DiagramNode[],+ edges: edges as DiagramEdge[],+ };+ } catch {+ return null;+ }+};++export const diagramFallbackMarkdown = (document: DiagramDocument) => {+ const title = document.kind === "mind-map" ? "思维导图" : "流程图";+ const connectedTargets = new Set(document.edges.map((edge) => edge.target));+ const orderedNodes = [+ ...document.nodes.filter((node) => !connectedTargets.has(node.id)),+ ...document.nodes.filter((node) => connectedTargets.has(node.id)),+ ];+ return [`# ${title}`, "", ...orderedNodes.map((node) => `- ${node.label.replace(/\s+/g, " ").trim() || "未命名节点"}`)].join("\n");+};++export const serializeDiagramDocument = (document: DiagramDocument) =>+ `${diagramFallbackMarkdown(document)}\n\n<!-- ${DIAGRAM_MARKER}:${encodeBase64Url(JSON.stringify(document))} -->`;++export const createDefaultDiagramDocument = (kind: DiagramKind): DiagramDocument => {+ if (kind === "mind-map") {+ return {+ schemaVersion: DIAGRAM_SCHEMA_VERSION,+ kind,+ nodes: [+ { id: "topic-root", label: "核心主题", x: 72, y: 150, width: 112, height: 42, shape: "topic" },+ { id: "topic-1", label: "分支主题", x: 256, y: 88, width: 92, height: 36, shape: "topic", parentId: "topic-root" },+ { id: "topic-2", label: "分支主题", x: 256, y: 153, width: 92, height: 36, shape: "topic", parentId: "topic-root" },+ { id: "topic-3", label: "分支主题", x: 256, y: 218, width: 92, height: 36, shape: "topic", parentId: "topic-root" },+ ],+ edges: [+ { id: "branch-1", source: "topic-root", target: "topic-1" },+ { id: "branch-2", source: "topic-root", target: "topic-2" },+ { id: "branch-3", source: "topic-root", target: "topic-3" },+ ],+ };+ }+ return {+ schemaVersion: DIAGRAM_SCHEMA_VERSION,+ kind,+ nodes: [+ { id: "flow-start", label: "开始", x: 100, y: 180, width: 120, height: 48, shape: "terminator" },+ { id: "flow-process", label: "处理步骤", x: 340, y: 180, width: 140, height: 56, shape: "process" },+ { id: "flow-end", label: "结束", x: 600, y: 180, width: 120, height: 48, shape: "terminator" },+ ],+ edges: [+ { id: "flow-edge-1", source: "flow-start", target: "flow-process" },+ { id: "flow-edge-2", source: "flow-process", target: "flow-end" },+ ],+ };+};diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 81ea2f98..3862e1e8 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -239,6 +239,48 @@ export const enUS = {createDisabled: "You cannot create a note in this view",creating: "Creating",},+ diagram: {+ normalNote: "Regular note",+ mindMap: "Mind map",+ flowchart: "Flowchart",+ createType: "Choose note type",+ back: "Back to note list",+ title: "Diagram title",+ canvas: "{{type}} canvas",+ addTopic: "Add child topic",+ mindMapShortcuts: "Tab adds a child; Enter adds a sibling",+ addStep: "Add step",+ addDecision: "Add decision",+ addTerminator: "Add start or end",+ newTopic: "New topic",+ newStep: "New step",+ nodeText: "Node text",+ editNode: "Edit node text",+ deleteSelection: "Delete selection",+ undo: "Undo",+ redo: "Redo",+ zoomIn: "Zoom in",+ zoomOut: "Zoom out",+ fit: "Fit diagram",+ autoLayout: "Auto-arrange",+ theme: "Diagram theme",+ themeBrand: "EdgeEver",+ themeOcean: "Mint paper",+ themeInk: "Deep forest",+ export: "Export",+ exportPng: "Export PNG",+ exportSvg: "Export SVG",+ exportError: "Could not export the diagram",+ save: "Save",+ saving: "Saving",+ saved: "Saved",+ unsaved: "Unsaved changes",+ saveError: "Could not save the diagram",+ editSessionError: "A safe editing session could not be opened. Try again shortly.",+ discardTitle: "Discard unsaved changes?",+ discardDescription: "Returning to the note list will lose the diagram changes you have not saved.",+ discard: "Discard changes",+ },workspace: {inboxDeleteTitle: "Inbox cannot be deleted",inboxDeleteDescription: "Inbox is the default notebook, so new notes always have a home.",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 1b973343..b23eff6a 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -239,6 +239,48 @@ export const zhCN = {createDisabled: "当前视图不可新建笔记",creating: "正在创建",},+ diagram: {+ normalNote: "普通笔记",+ mindMap: "思维导图",+ flowchart: "流程图",+ createType: "选择笔记类型",+ back: "返回笔记列表",+ title: "图表标题",+ canvas: "{{type}}画布",+ addTopic: "添加子主题",+ mindMapShortcuts: "Tab 添加子主题,Enter 添加同级主题",+ addStep: "添加步骤",+ addDecision: "添加判断节点",+ addTerminator: "添加起止节点",+ newTopic: "新主题",+ newStep: "新步骤",+ nodeText: "节点文字",+ editNode: "编辑节点文字",+ deleteSelection: "删除所选内容",+ undo: "撤销",+ redo: "重做",+ zoomIn: "放大",+ zoomOut: "缩小",+ fit: "适应画布",+ autoLayout: "自动整理布局",+ theme: "图表主题",+ themeBrand: "EdgeEver",+ themeOcean: "薄荷纸",+ themeInk: "深林",+ export: "导出",+ exportPng: "导出 PNG",+ exportSvg: "导出 SVG",+ exportError: "图表导出失败",+ save: "保存",+ saving: "保存中",+ saved: "已保存",+ unsaved: "有未保存的修改",+ saveError: "图表保存失败",+ editSessionError: "暂时无法建立安全编辑会话,请稍后重试。",+ discardTitle: "放弃未保存的修改?",+ discardDescription: "返回笔记列表后,本次尚未保存的图表修改会丢失。",+ discard: "放弃修改",+ },workspace: {inboxDeleteTitle: "等待分类不能删除",inboxDeleteDescription: "等待分类是默认笔记本,用来保证新笔记始终有归属。",diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex b750d14a..a6157ff0 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -29,6 +29,7 @@ export * from "./sharing";export * from "./sync";export * from "./desktop-rpc";export * from "./deployment-metadata";+export * from "./diagram";export * from "./file-attachment";export * from "./note-image-card";export * from "./pdf-attachment";diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.tsindex 80366814..e3d7183c 100644--- a/packages/shared/src/schemas.ts+++ b/packages/shared/src/schemas.ts@@ -28,6 +28,7 @@ export const NotebookUpdateSchema = z.object({export const MemoCreateSchema = z.object({notebookId: z.string().trim().min(1),title: z.string().trim().max(160).optional(),+ contentJson: z.unknown().optional(),contentMarkdown: z.string().optional(),tags: z.array(z.string()).optional(),createdAt: z.string().datetime().optional(),