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
fix(diagram): unify and refine auto layout
tianma-if6653dc73b852
diff --git a/apps/web/src/components/DiagramEditorPane.test.mjs b/apps/web/src/components/DiagramEditorPane.test.mjsindex 32e28c2b..b633e228 100644--- a/apps/web/src/components/DiagramEditorPane.test.mjs+++ b/apps/web/src/components/DiagramEditorPane.test.mjs@@ -77,10 +77,18 @@ describe("diagram editor canvas surface", () => {expect(source).toContain('connector: { name: kind === "mind-map" ? "smooth" : "rounded"');expect(source).toContain('router: "normal"');expect(source).not.toContain('name: "manhattan"');- expect(source).toContain('maxScale: document.kind === "mind-map" ? 1 : 0.84');+ expect(source).toContain("maxScale: policy.maxScale");+ expect(source).toContain("policy.minScale ? { minScale: policy.minScale }");+ expect(source).toContain("getDiagramLayoutViewport(document.kind)");expect(source).toContain("fitDiagramContent(graph, document, containerRef.current);");});+ test("labels auto layout directly instead of relying on an ambiguous icon", () => {+ expect(source).toContain('<WandSparkles className="h-4 w-4" />');+ expect(source).toContain('<span>{t("diagram.autoLayout")}</span>');+ expect(source).not.toContain('<Button size="icon" variant="ghost" aria-label={t("diagram.autoLayout")}');+ });+test("exposes connection handles on flowcharts and architecture components with safe connection rules", () => {expect(source).toContain("const hasPorts = isConnectableDiagram(kind) && node.shape !== \"boundary\"");expect(source).toContain("const FLOW_PORT_HIT_RADIUS = 14");@@ -106,8 +114,10 @@ describe("diagram editor canvas surface", () => {expect(source).not.toContain('onClick={() => addNode("service")}');expect(source).toContain('{ shape: "database", icon: Database');expect(source).toContain('{ shape: "boundary", icon: Box');- expect(source).toContain('t("diagram.architectureConnectHint")');- expect(source).toContain("fitArchitectureBoundaries(graph)");+ expect(source).not.toContain('t("diagram.architectureConnectHint")');+ expect(source).not.toContain('t("diagram.connectHint")');+ expect(source).not.toContain("fitArchitectureBoundaries(graph)");+ expect(source).toContain("computeDiagramLayoutResult");expect(source).toContain("parent.addChild(node)");expect(source).toContain("updateSelectedEdgeLabel");expect(source).toContain('t("diagram.edgeText")');diff --git a/apps/web/src/components/DiagramEditorPane.tsx b/apps/web/src/components/DiagramEditorPane.tsxindex aa4f0b61..95317a3d 100644--- a/apps/web/src/components/DiagramEditorPane.tsx+++ b/apps/web/src/components/DiagramEditorPane.tsx@@ -38,7 +38,6 @@ import {Globe2,HardDrive,History as HistoryIcon,- LayoutDashboard,KeyRound,Layers3,ListTree,@@ -64,6 +63,7 @@ import {SquareFunction,Trash2,Undo2,+ WandSparkles,Webhook,Workflow,Zap,@@ -102,7 +102,15 @@ import { useAppearanceTheme } from "@/components/ThemeProvider";import { api } from "@/lib/api";import { EDITOR_LOCAL_SAVE_DELAY_MS } from "@/lib/app-helpers";import { copyTextToClipboard } from "@/lib/clipboard";-import { compactArchitectureNodeSize, compactFlowchartNodeSize, compactMindMapNodeSize, computeDiagramLayout } from "@/lib/diagram-layout";+import {+ compactArchitectureNodeSize,+ compactFlowchartNodeSize,+ compactMindMapNodeSize,+ computeDiagramLayout,+ computeDiagramLayoutResult,+ getDiagramLayoutViewport,+ type DiagramLayoutViewport,+} from "@/lib/diagram-layout";import { resolveDiagramPalette, type DiagramAppearance } from "@/lib/diagram-theme";import { isLocalMemoId } from "@/lib/local-mirror";import { isBrowserOffline } from "@/lib/network-status";@@ -880,11 +888,17 @@ const fitDiagramContent = (document: DiagramDocument,container: HTMLElement | null,padding = 32,- minScale?: number,+ viewport?: DiagramLayoutViewport,) => {- graph.zoomToFit({ padding, maxScale: document.kind === "mind-map" ? 1 : 0.84, ...(minScale ? { minScale } : {}) });+ const policy = viewport ?? getDiagramLayoutViewport(document.kind);+ graph.zoomToFit({+ padding,+ maxScale: policy.maxScale,+ ...(policy.minScale ? { minScale: policy.minScale } : {}),+ });if (!container) return;- const anchor = document.kind === "mind-map"+ if (policy.anchor === "center") return;+ const anchor = policy.anchor === "root"? graph.getNodes().find((node) => !node.getData<NodeData>()?.parentId): graph.getNodes().reduce<Node | null>((leftmost, node) => (!leftmost || node.getBBox().x < leftmost.getBBox().x ? node : leftmost@@ -896,26 +910,6 @@ const fitDiagramContent = (graph.translate(translation.tx + desiredLeft - contentLeft, translation.ty);};-const fitArchitectureBoundaries = (graph: Graph) => {- const nodes = graph.getNodes();- for (const boundary of nodes.filter((node) => node.getData<NodeData>()?.shape === "boundary")) {- const children = nodes.filter((node) => node.getData<NodeData>()?.parentId === boundary.id);- if (children.length === 0) continue;- const positions = new Map(children.map((node) => [node.id, node.getPosition()]));- const boxes = children.map((node) => node.getBBox());- const left = Math.min(...boxes.map((box) => box.x)) - 36;- const top = Math.min(...boxes.map((box) => box.y)) - 56;- const right = Math.max(...boxes.map((box) => box.x + box.width)) + 36;- const bottom = Math.max(...boxes.map((box) => box.y + box.height)) + 36;- boundary.position(left, top);- boundary.resize(Math.max(260, right - left), Math.max(180, bottom - top));- for (const child of children) {- const position = positions.get(child.id);- if (position) child.position(position.x, position.y);- }- }-};-const applyGraphPalette = (graph: Graph,theme: DiagramTheme,@@ -1802,21 +1796,27 @@ export const DiagramEditorPane = ({const applyAutoLayout = () => {const graph = graphRef.current;if (!graph || !document || readOnly || graph.getNodes().length === 0) return;- const positions = computeDiagramLayout(graphToDocument(graph, document.kind, themeRef.current));+ const layout = computeDiagramLayoutResult(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;+ for (const nodeId of layout.nodeOrder) {+ const node = graph.getCellById(nodeId);+ const geometry = layout.nodes[nodeId];+ if (!node?.isNode()) continue;+ if (!geometry) continue;const currentPosition = node.getPosition();- if (currentPosition.x !== position.x || currentPosition.y !== position.y) {+ const currentSize = node.getSize();+ if (currentPosition.x !== geometry.x || currentPosition.y !== geometry.y) {changed = true;- node.position(position.x, position.y);+ node.position(geometry.x, geometry.y);+ }+ if (currentSize.width !== geometry.width || currentSize.height !== geometry.height) {+ changed = true;+ node.resize(geometry.width, geometry.height);}}- if (document.kind === "architecture") fitArchitectureBoundaries(graph);graph.stopBatch("layout");- fitDiagramContent(graph, document, containerRef.current, 40, document.kind === "architecture" ? 0.64 : undefined);+ fitDiagramContent(graph, document, containerRef.current, 40, layout.viewport);if (changed) {setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(titleRef.current,@@ -2162,36 +2162,40 @@ export const DiagramEditorPane = ({]}/>) : document.kind === "architecture" ? (- <>- <ArchitectureComponentLibrary- onAdd={(item) => addNode(item.shape, {- label: t(item.labelKey),- resourceIcon: architectureResourceIcon(item),- })}- t={t}- />- <span className="hidden items-center gap-1.5 px-2 text-xs text-slate-500 xl:flex"><Link2 className="h-3.5 w-3.5" />{t("diagram.architectureConnectHint")}</span>- </>+ <ArchitectureComponentLibrary+ onAdd={(item) => addNode(item.shape, {+ label: t(item.labelKey),+ resourceIcon: architectureResourceIcon(item),+ })}+ t={t}+ />) : (- <>- <DiagramInsertMenu- icon={Box}- label={t("diagram.addStep")}- items={[- { icon: Box, label: t("diagram.addStep"), onSelect: () => addNode("process") },- { icon: Diamond, label: t("diagram.addDecision"), onSelect: () => addNode("decision") },- { icon: Circle, label: t("diagram.addTerminator"), onSelect: () => addNode("terminator") },- ]}- />- <span className="hidden items-center gap-1.5 px-2 text-xs text-slate-500 xl:flex"><Link2 className="h-3.5 w-3.5" />{t("diagram.connectHint")}</span>- </>+ <DiagramInsertMenu+ icon={Box}+ label={t("diagram.addStep")}+ items={[+ { icon: Box, label: t("diagram.addStep"), onSelect: () => addNode("process") },+ { icon: Diamond, label: t("diagram.addDecision"), onSelect: () => addNode("decision") },+ { icon: Circle, label: t("diagram.addTerminator"), onSelect: () => addNode("terminator") },+ ]}+ />))}<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>}+ {!readOnly && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button size="sm" variant="ghost" className="gap-1.5 px-2.5" aria-label={t("diagram.autoLayout")} onClick={applyAutoLayout}>+ <WandSparkles className="h-4 w-4" />+ <span>{t("diagram.autoLayout")}</span>+ </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>diff --git a/apps/web/src/lib/diagram-layout.test.mjs b/apps/web/src/lib/diagram-layout.test.mjsindex f122bff9..674893c1 100644--- a/apps/web/src/lib/diagram-layout.test.mjs+++ b/apps/web/src/lib/diagram-layout.test.mjs@@ -1,6 +1,14 @@import { describe, expect, test } from "bun:test";import { createDefaultDiagramDocument } from "@edgeever/shared";-import { compileDiagramIr, compactArchitectureNodeSize, compactFlowchartNodeSize, compactMindMapNodeSize, computeDiagramLayout } from "./diagram-layout.ts";+import {+ compileDiagramIr,+ compactArchitectureNodeSize,+ compactFlowchartNodeSize,+ compactMindMapNodeSize,+ computeDiagramLayout,+ computeDiagramLayoutResult,+ getDiagramLayoutViewport,+} from "./diagram-layout.ts";describe("diagram auto layout", () => {test("places mind-map children to the right of their root", () => {@@ -49,14 +57,22 @@ describe("diagram auto layout", () => {expect(positions["topic-new"].y).toBeGreaterThanOrEqual(selectedSubtreeBottom + 16);});- test("orders a connected flow from left to right and keeps detached nodes finite", () => {+ test("orders a connected flow from top to bottom and places detached nodes afterwards", () => {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(positions["flow-start"].y).toBeLessThan(positions["flow-process"].y);+ expect(positions["flow-process"].y).toBeLessThan(positions["flow-end"].y);expect(Number.isFinite(positions.detached.x)).toBeTrue();expect(Number.isFinite(positions.detached.y)).toBeTrue();+ expect(positions.detached.y).toBeGreaterThan(positions["flow-end"].y + 44);+ });++ test("keeps an explicit horizontal flowchart direction", () => {+ const document = createDefaultDiagramDocument("flowchart");+ const positions = computeDiagramLayout(document, { direction: "left-to-right" });+ expect(positions["flow-start"].x).toBeLessThan(positions["flow-process"].x);+ expect(positions["flow-process"].x).toBeLessThan(positions["flow-end"].x);});test("uses compact flowchart nodes with aligned process and terminator centers", () => {@@ -65,6 +81,23 @@ describe("diagram auto layout", () => {expect(compactFlowchartNodeSize("decision")).toEqual({ width: 116, height: 72 });});+ test("balances a large mind map across both sides while keeping descendants with their branch", () => {+ const document = createDefaultDiagramDocument("mind-map");+ document.nodes.push(+ { id: "topic-4", parentId: "topic-root", label: "Branch 4", x: 256, y: 220, width: 92, height: 36, shape: "topic" },+ { id: "topic-5", parentId: "topic-root", label: "Branch 5", x: 256, y: 272, width: 92, height: 36, shape: "topic" },+ { id: "topic-6", parentId: "topic-root", label: "Branch 6", x: 256, y: 324, width: 92, height: 36, shape: "topic" },+ { id: "topic-6-child", parentId: "topic-6", label: "Nested", x: 420, y: 324, width: 92, height: 36, shape: "topic" },+ );+ const positions = computeDiagramLayout(document);+ const root = document.nodes.find((node) => node.id === "topic-root");+ const directChildren = document.nodes.filter((node) => node.parentId === root.id);+ expect(directChildren.some((node) => positions[node.id].x < root.x)).toBeTrue();+ expect(directChildren.some((node) => positions[node.id].x > root.x + root.width)).toBeTrue();+ const branchDirection = positions["topic-6"].x < root.x ? -1 : 1;+ expect(Math.sign(positions["topic-6-child"].x - positions["topic-6"].x)).toBe(branchDirection);+ });+test("lays out architecture components while preserving authored boundary geometry", () => {const document = createDefaultDiagramDocument("architecture");const positions = computeDiagramLayout(document);@@ -119,4 +152,35 @@ describe("diagram auto layout", () => {expect(contentWidth).toBeLessThanOrEqual(1480);expect(new Set(boundaries.map((node) => node.y)).size).toBeGreaterThan(1);});++ test("returns a complete strategy result for every diagram kind", () => {+ for (const kind of ["mind-map", "flowchart", "architecture"]) {+ const document = createDefaultDiagramDocument(kind);+ const result = computeDiagramLayoutResult(document);+ expect(Object.keys(result.nodes).sort()).toEqual(document.nodes.map((node) => node.id).sort());+ expect([...result.nodeOrder].sort()).toEqual(document.nodes.map((node) => node.id).sort());+ for (const geometry of Object.values(result.nodes)) {+ expect(Number.isFinite(geometry.x)).toBeTrue();+ expect(Number.isFinite(geometry.y)).toBeTrue();+ expect(geometry.width).toBeGreaterThan(0);+ expect(geometry.height).toBeGreaterThan(0);+ }+ expect(result.viewport).toEqual(getDiagramLayoutViewport(kind));+ }+ });++ test("finalizes architecture boundary geometry inside the shared layout engine", () => {+ const document = createDefaultDiagramDocument("architecture");+ const result = computeDiagramLayoutResult(document);+ const boundary = result.nodes.system;+ expect(result.nodeOrder.indexOf("system")).toBeLessThan(result.nodeOrder.indexOf("api"));+ for (const childId of ["api", "database"]) {+ const child = result.nodes[childId];+ expect(child.x).toBeGreaterThan(boundary.x);+ expect(child.y).toBeGreaterThan(boundary.y);+ expect(child.x + child.width).toBeLessThan(boundary.x + boundary.width);+ expect(child.y + child.height).toBeLessThan(boundary.y + boundary.height);+ }+ expect(result.viewport.minScale).toBe(0.64);+ });});diff --git a/apps/web/src/lib/diagram-layout.ts b/apps/web/src/lib/diagram-layout.tsindex e1aaeb87..82fd5add 100644--- a/apps/web/src/lib/diagram-layout.ts+++ b/apps/web/src/lib/diagram-layout.ts@@ -4,4 +4,13 @@ export {compactFlowchartNodeSize,compactMindMapNodeSize,computeDiagramLayout,+ computeDiagramLayoutResult,+ getDiagramLayoutViewport,+} from "@edgeever/shared/diagram-layout";+export type {+ DiagramLayoutNodeGeometry,+ DiagramLayoutOptions,+ DiagramLayoutResult,+ DiagramLayoutStrategy,+ DiagramLayoutViewport,} from "@edgeever/shared/diagram-layout";diff --git a/packages/shared/src/diagram-layout.ts b/packages/shared/src/diagram-layout.tsindex 0ba39117..a9cf1f01 100644--- a/packages/shared/src/diagram-layout.ts+++ b/packages/shared/src/diagram-layout.ts@@ -12,6 +12,25 @@ import {export type DiagramLayoutPositions = Record<string, { x: number; y: number }>;+export type DiagramLayoutNodeGeometry = {+ x: number;+ y: number;+ width: number;+ height: number;+};++export type DiagramLayoutViewport = {+ anchor: "root" | "leftmost" | "center";+ maxScale: number;+ minScale?: number;+};++export type DiagramLayoutResult = {+ nodes: Record<string, DiagramLayoutNodeGeometry>;+ nodeOrder: string[];+ viewport: DiagramLayoutViewport;+};+export type DiagramLayoutOptions = {insertedNodeId?: string;insertAfterNodeId?: string;@@ -56,6 +75,10 @@ export type DiagramIr = {const MIND_MAP_HORIZONTAL_GAP = 72;const MIND_MAP_VERTICAL_GAP = 16;+const MIND_MAP_TWO_SIDED_THRESHOLD = 5;+const FLOWCHART_DETACHED_GAP = 72;+const FLOWCHART_DETACHED_ROW_GAP = 24;+const FLOWCHART_DETACHED_ROW_WIDTH = 960;const ARCHITECTURE_LAYOUT_ROW_WIDTH = 1480;const ARCHITECTURE_GROUP_HORIZONTAL_GAP = 72;const ARCHITECTURE_GROUP_VERTICAL_GAP = 88;@@ -144,7 +167,12 @@ const computeMindMapLayout = (const positions: DiagramLayoutPositions = Object.fromEntries(document.nodes.map((node) => [node.id, { x: node.x, y: node.y }]),);- const placeChildren = (nodeId: string, subtreeTop: number, ancestors: Set<string>) => {+ const placeChildren = (+ nodeId: string,+ subtreeTop: number,+ ancestors: Set<string>,+ direction: 1 | -1,+ ) => {const node = nodeById.get(nodeId);if (!node || ancestors.has(nodeId)) return;const nextAncestors = new Set(ancestors).add(nodeId);@@ -158,10 +186,33 @@ const computeMindMapLayout = (const child = nodeById.get(childId)!;const childSubtreeHeight = childHeights[index];positions[childId] = {- x: positions[nodeId].x + node.width + MIND_MAP_HORIZONTAL_GAP,+ x: direction === 1+ ? positions[nodeId].x + node.width + MIND_MAP_HORIZONTAL_GAP+ : positions[nodeId].x - MIND_MAP_HORIZONTAL_GAP - child.width,+ y: Math.round(cursor + (childSubtreeHeight - child.height) / 2),+ };+ placeChildren(childId, cursor, nextAncestors, direction);+ cursor += childSubtreeHeight + MIND_MAP_VERTICAL_GAP;+ }+ };++ const placeRootSide = (rootId: string, childIds: string[], direction: 1 | -1) => {+ const root = nodeById.get(rootId);+ if (!root || childIds.length === 0) return;+ const childHeights = childIds.map((childId) => measureSubtree(childId, new Set([rootId])));+ const sideHeight = childHeights.reduce((total, height) => total + height, 0)+ + Math.max(0, childHeights.length - 1) * MIND_MAP_VERTICAL_GAP;+ let cursor = root.y + root.height / 2 - sideHeight / 2;+ for (let index = 0; index < childIds.length; index += 1) {+ const child = nodeById.get(childIds[index])!;+ const childSubtreeHeight = childHeights[index];+ positions[child.id] = {+ x: direction === 1+ ? root.x + root.width + MIND_MAP_HORIZONTAL_GAP+ : root.x - MIND_MAP_HORIZONTAL_GAP - child.width,y: Math.round(cursor + (childSubtreeHeight - child.height) / 2),};- placeChildren(childId, cursor, nextAncestors);+ placeChildren(child.id, cursor, new Set([rootId]), direction);cursor += childSubtreeHeight + MIND_MAP_VERTICAL_GAP;}};@@ -170,8 +221,22 @@ const computeMindMapLayout = (.filter((node) => !node.parentId || !nodeById.has(node.parentId)).sort((left, right) => left.y - right.y || left.id.localeCompare(right.id));for (const root of roots) {- const subtreeHeight = measureSubtree(root.id, new Set());- placeChildren(root.id, root.y + root.height / 2 - subtreeHeight / 2, new Set());+ const childIds = (childrenByParent.get(root.id) ?? []).filter((childId) => childId !== root.id);+ if (childIds.length < MIND_MAP_TWO_SIDED_THRESHOLD) {+ placeRootSide(root.id, childIds, 1);+ continue;+ }+ const sides: Record<"left" | "right", { ids: string[]; height: number }> = {+ left: { ids: [], height: 0 },+ right: { ids: [], height: 0 },+ };+ for (const childId of childIds) {+ const side = sides.right.height <= sides.left.height ? sides.right : sides.left;+ side.ids.push(childId);+ side.height += measureSubtree(childId, new Set([root.id])) + MIND_MAP_VERTICAL_GAP;+ }+ placeRootSide(root.id, sides.left.ids, -1);+ placeRootSide(root.id, sides.right.ids, 1);}return positions;};@@ -245,22 +310,23 @@ const wrapArchitectureGroups = (return positions;};-export const computeDiagramLayout = (+const computeDagreLayout = (document: DiagramDocument,- options: DiagramLayoutOptions = {},+ options: DiagramLayoutOptions,+ excludeBoundaries: boolean,+ spacing: { rank: number; node: number } = { rank: 96, node: 40 },): DiagramLayoutPositions => {- if (document.kind === "mind-map") return computeMindMapLayout(document, options);const layoutGraph = new graphlib.Graph();layoutGraph.setGraph({rankdir: options.direction === "top-to-bottom" ? "TB" : "LR",- ranksep: 96,- nodesep: 40,+ ranksep: spacing.rank,+ nodesep: spacing.node,marginx: 32,marginy: 32,});layoutGraph.setDefaultEdgeLabel(() => ({}));- const layoutNodes = document.kind === "architecture"+ const layoutNodes = excludeBoundaries? document.nodes.filter((node) => node.shape !== "boundary"): document.nodes;const layoutNodeIds = new Set(layoutNodes.map((node) => node.id));@@ -279,16 +345,70 @@ export const computeDiagramLayout = (y: Math.round(position.y - node.height / 2),}]];}));- return document.kind === "architecture" ? wrapArchitectureGroups(document, positions) : positions;+ return positions;+};++const placeDetachedFlowchartNodes = (+ document: DiagramDocument,+ positions: DiagramLayoutPositions,+) => {+ const nodeIds = new Set(document.nodes.map((node) => node.id));+ const connectedIds = new Set<string>();+ for (const edge of document.edges) {+ if (!nodeIds.has(edge.source) || !nodeIds.has(edge.target)) continue;+ connectedIds.add(edge.source);+ connectedIds.add(edge.target);+ }+ const connected = document.nodes.filter((node) => connectedIds.has(node.id));+ const detached = document.nodes+ .filter((node) => !connectedIds.has(node.id))+ .sort((left, right) => left.y - right.y || left.x - right.x || left.id.localeCompare(right.id));+ if (connected.length === 0 || detached.length === 0) return positions;++ const contentLeft = Math.min(...connected.map((node) => positions[node.id].x));+ const contentBottom = Math.max(...connected.map((node) => positions[node.id].y + node.height));+ let cursorX = contentLeft;+ let cursorY = contentBottom + FLOWCHART_DETACHED_GAP;+ let rowHeight = 0;+ for (const node of detached) {+ if (cursorX > contentLeft && cursorX + node.width > contentLeft + FLOWCHART_DETACHED_ROW_WIDTH) {+ cursorX = contentLeft;+ cursorY += rowHeight + FLOWCHART_DETACHED_ROW_GAP;+ rowHeight = 0;+ }+ positions[node.id] = { x: cursorX, y: cursorY };+ cursorX += node.width + 40;+ rowHeight = Math.max(rowHeight, node.height);+ }+ return positions;};+const computeFlowchartLayout = (document: DiagramDocument, options: DiagramLayoutOptions) => (+ placeDetachedFlowchartNodes(+ document,+ computeDagreLayout(+ document,+ { ...options, direction: options.direction ?? "top-to-bottom" },+ false,+ { rank: 80, node: 48 },+ ),+ )+);++const computeArchitectureLayout = (document: DiagramDocument, options: DiagramLayoutOptions) => (+ wrapArchitectureGroups(+ document,+ computeDagreLayout(document, { ...options, direction: options.direction ?? "left-to-right" }, true),+ )+);+const irNodeShape = (kind: DiagramKind, type: DiagramIrNodeType | undefined): DiagramNodeShape => {if (kind === "mind-map") return "topic";if (kind === "flowchart") return type === "decision" ? "decision" : type === "start" || type === "end" ? "terminator" : "process";return (type ?? "service") as DiagramNodeShape;};-const fitArchitectureBoundaries = (document: DiagramDocument) => {+const finalizeArchitectureLayout = (document: DiagramDocument) => {const nodeById = new Map(document.nodes.map((node) => [node.id, node]));const boundaryDepth = (nodeId: string) => {let depth = 0;@@ -349,6 +469,88 @@ const fitArchitectureBoundaries = (document: DiagramDocument) => {}};+export type DiagramLayoutStrategy = {+ kind: DiagramKind;+ layout: (document: DiagramDocument, options: DiagramLayoutOptions) => DiagramLayoutPositions;+ finalize?: (document: DiagramDocument) => void;+ viewport: DiagramLayoutViewport;+};++const DIAGRAM_LAYOUT_STRATEGIES: Record<DiagramKind, DiagramLayoutStrategy> = {+ "mind-map": {+ kind: "mind-map",+ layout: computeMindMapLayout,+ viewport: { anchor: "root", maxScale: 1 },+ },+ flowchart: {+ kind: "flowchart",+ layout: computeFlowchartLayout,+ viewport: { anchor: "center", maxScale: 0.9 },+ },+ architecture: {+ kind: "architecture",+ layout: computeArchitectureLayout,+ finalize: finalizeArchitectureLayout,+ viewport: { anchor: "leftmost", maxScale: 0.84, minScale: 0.64 },+ },+};++export const getDiagramLayoutViewport = (kind: DiagramKind): DiagramLayoutViewport => ({+ ...DIAGRAM_LAYOUT_STRATEGIES[kind].viewport,+});++export const computeDiagramLayoutResult = (+ document: DiagramDocument,+ options: DiagramLayoutOptions = {},+): DiagramLayoutResult => {+ const strategy = DIAGRAM_LAYOUT_STRATEGIES[document.kind];+ const layoutDocument: DiagramDocument = {+ ...document,+ nodes: document.nodes.map((node) => ({ ...node })),+ edges: document.edges.map((edge) => ({ ...edge })),+ };+ const positions = strategy.layout(layoutDocument, options);+ for (const node of layoutDocument.nodes) {+ const position = positions[node.id];+ if (position && Number.isFinite(position.x) && Number.isFinite(position.y)) {+ node.x = position.x;+ node.y = position.y;+ }+ }+ strategy.finalize?.(layoutDocument);+ const nodeById = new Map(layoutDocument.nodes.map((node) => [node.id, node]));+ const nodeDepth = (nodeId: string) => {+ let depth = 0;+ let current = nodeById.get(nodeId);+ const visited = new Set<string>();+ while (current?.parentId && !visited.has(current.parentId)) {+ visited.add(current.parentId);+ const parent = nodeById.get(current.parentId);+ if (!parent) break;+ depth += 1;+ current = parent;+ }+ return depth;+ };+ return {+ nodes: Object.fromEntries(layoutDocument.nodes.map((node) => [node.id, {+ x: node.x,+ y: node.y,+ width: node.width,+ height: node.height,+ }])),+ nodeOrder: layoutDocument.nodes+ .map((node) => node.id)+ .sort((left, right) => nodeDepth(left) - nodeDepth(right)),+ viewport: getDiagramLayoutViewport(document.kind),+ };+};++export const computeDiagramLayout = (+ document: DiagramDocument,+ options: DiagramLayoutOptions = {},+): DiagramLayoutPositions => DIAGRAM_LAYOUT_STRATEGIES[document.kind].layout(document, options);+export const compileDiagramIr = (ir: DiagramIr): DiagramDocument => {const nodes = ir.nodes.map((node, index) => {const shape = irNodeShape(ir.kind, node.type);@@ -390,13 +592,12 @@ export const compileDiagramIr = (ir: DiagramIr): DiagramDocument => {nodes,edges,};- const positions = computeDiagramLayout(document, {+ const layout = computeDiagramLayoutResult(document, {direction: ir.layout?.direction ?? (ir.kind === "flowchart" ? "top-to-bottom" : "left-to-right"),});for (const node of document.nodes) {- const position = positions[node.id];- if (position) Object.assign(node, position);+ const geometry = layout.nodes[node.id];+ if (geometry) Object.assign(node, geometry);}- if (ir.kind === "architecture") fitArchitectureBoundaries(document);return document;};diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex a5e7a7b6..dbc73fbc 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -326,8 +326,6 @@ export const enUS = {externalApi: "External API",thirdPartyService: "Third-party service",},- architectureConnectHint: "Drag a handle to connect architecture components",- connectHint: "Drag a handle to connect, or drop on canvas to create the next node",newTopic: "New topic",newStep: "New step",newDecision: "Decision",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 431f0f15..afb66446 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -326,8 +326,6 @@ export const zhCN = {externalApi: "外部 API",thirdPartyService: "第三方服务",},- architectureConnectHint: "拖动端点连接架构组件",- connectHint: "拖动端点连线;松开在空白处可创建后续节点",newTopic: "新主题",newStep: "新步骤",newDecision: "判断条件",