Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(diagram): add org, timeline, and fishbone layouts

tianma-if466161284d6a
diff --git a/apps/api/src/mcp-tool-service.ts b/apps/api/src/mcp-tool-service.ts
index 099d0400..f0cc4e85 100644
--- a/apps/api/src/mcp-tool-service.ts
+++ b/apps/api/src/mcp-tool-service.ts
@@ -276,10 +276,10 @@ const parseDiagramMemoIr = (args: Record<string, unknown>): DiagramIr => {
if (args.edges !== undefined && (!Array.isArray(args.edges) || args.edges.length > 400)) {
throw new AppError("invalid_params", "edges must be an array with at most 400 items", 400);
}
- if (args.theme !== undefined && !["brand", "sun", "wa", "island", "rose", "mint", "cosmos", "tea", "naive", "macaron", "ocean", "ink", "classic"].includes(String(args.theme))) {
+ if (args.theme !== undefined && !["brand", "sun", "wa", "island", "rose", "mint", "cosmos", "tea", "naive", "macaron", "ocean", "ink", "classic", "paper"].includes(String(args.theme))) {
throw new AppError("invalid_params", "theme is not a supported diagram color scheme", 400);
}
- if (args.structure !== undefined && !["map", "line", "capsule", "box", "circle", "ellipse", "hexagon", "logic", "tree", "brace"].includes(String(args.structure))) {
+ if (args.structure !== undefined && !["map", "line", "capsule", "box", "circle", "ellipse", "hexagon", "logic", "tree", "brace", "org", "timeline", "fishbone"].includes(String(args.structure))) {
throw new AppError("invalid_params", "structure is not a supported mind-map shape", 400);
}
if (args.title !== undefined && (typeof args.title !== "string" || args.title.length > 160)) {
diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.ts
index 848dcc46..3ca3b6c2 100644
--- a/apps/api/src/mcp-tools.ts
+++ b/apps/api/src/mcp-tools.ts
@@ -106,8 +106,8 @@ const MCP_TOOL_DEFINITIONS = [
notebookId: { type: "string", minLength: 1 },
title: { type: "string", maxLength: 160 },
kind: { type: "string", enum: ["mind-map", "flowchart", "architecture"] },
- theme: { type: "string", enum: ["brand", "sun", "wa", "island", "rose", "mint", "cosmos", "tea", "naive", "macaron", "ocean", "ink", "classic"] },
- structure: { type: "string", enum: ["map", "line", "capsule", "box", "circle", "ellipse", "hexagon", "logic", "tree", "brace"] },
+ theme: { type: "string", enum: ["brand", "sun", "wa", "island", "rose", "mint", "cosmos", "tea", "naive", "macaron", "ocean", "ink", "classic", "paper"] },
+ structure: { type: "string", enum: ["map", "line", "capsule", "box", "circle", "ellipse", "hexagon", "logic", "tree", "brace", "org", "timeline", "fishbone"] },
layout: {
type: "object",
additionalProperties: false,
diff --git a/apps/web/src/components/DiagramEditorPane.test.mjs b/apps/web/src/components/DiagramEditorPane.test.mjs
index dc856eb9..df728039 100644
--- a/apps/web/src/components/DiagramEditorPane.test.mjs
+++ b/apps/web/src/components/DiagramEditorPane.test.mjs
@@ -151,24 +151,32 @@ describe("diagram editor canvas surface", () => {
test("uses restrained rounded edges and fits the complete diagram without clipping", () => {
expect(toolbarSource).toContain("DIAGRAM_THEME_GROUPS");
- expect(toolbarSource).toContain("STRUCTURE_GROUPS");
+ expect(toolbarSource).toContain("DIAGRAM_STRUCTURE_GROUPS");
expect(toolbarSource).toContain("diagramThemeSwatches");
expect(toolbarSource).toContain("<StructureThumb");
expect(toolbarSource).toContain('t("diagram.structure")');
expect(toolbarSource).toContain("diagram.structureGroupMap");
+ expect(toolbarSource).toContain("structureGroupLabelKey");
+ expect(toolbarSource).toContain('structure === "org"');
+ expect(toolbarSource).toContain('structure === "timeline"');
+ expect(toolbarSource).toContain('structure === "fishbone"');
expect(toolbarSource).toContain("diagram.themeGroupVivid");
expect(toolbarSource).toContain('<TooltipContent>{t("diagram.theme")}</TooltipContent>');
expect(toolbarSource).not.toContain('value="ocean"');
expect(toolbarSource).not.toContain('value="ink"');
expect(source).toContain("Graph.registerConnector(MIND_MAP_CONNECTOR_NAME, mindMapConnector, true)");
- expect(source).toContain("name: MIND_MAP_CONNECTOR_NAME, args: { sourceWidth: mindEdge?.sourceWidth, targetWidth: mindEdge?.targetWidth }");
+ expect(source).toContain("name: MIND_MAP_CONNECTOR_NAME, args: { sourceWidth: mindEdge?.sourceWidth, targetWidth: mindEdge?.targetWidth, structure }");
expect(source).toContain('{ fill: "none" }');
expect(source).toContain('if (kind !== "mind-map") edge.attr("line/fill", "none")');
expect(source).toContain("FLOWCHART_EDGE_ROUTER");
expect(source).toContain("applyFlowchartEdgePorts(graph)");
expect(source).toContain("flowchartEdgeIsStraight");
- expect(source).toContain('showTheme={document.kind === "mind-map"}');
+ expect(source).toContain('showTheme={document.kind !== "architecture"}');
+ expect(source).toContain('themeCatalog={document.kind === "flowchart" ? "flowchart" : "mind-map"}');
expect(toolbarSource).toContain("showTheme = true");
+ expect(toolbarSource).toContain("themeCatalog = \"mind-map\"");
+ expect(toolbarSource).toContain("FLOWCHART_SELECTABLE_THEMES");
+ expect(toolbarSource).toContain("flowchartThemeSwatches");
expect(source).toContain("maxScale: policy.maxScale");
expect(source).not.toContain("minScale: policy.minScale");
expect(source).toContain("centerDiagramContent(graph)");
diff --git a/apps/web/src/components/DiagramEditorPane.tsx b/apps/web/src/components/DiagramEditorPane.tsx
index 95343f18..a7eea945 100644
--- a/apps/web/src/components/DiagramEditorPane.tsx
+++ b/apps/web/src/components/DiagramEditorPane.tsx
@@ -74,8 +74,10 @@ import {
MIND_MAP_VERTICAL_GAP,
mindMapBranchSides,
mindMapConnector,
+ mindMapEdgeLineAttrs,
mindMapEdgeTerminal,
mindMapEdgeVisual,
+ mindMapSiblingSpan,
mindMapNodePresentation,
mindMapNodeRole,
resolveMindMapNodeStyle,
@@ -545,7 +547,7 @@ const diagramCanvasColor = (
theme: DiagramTheme,
appearance: DiagramAppearance,
) => (kind === "flowchart"
- ? resolveFlowchartSurface(appearance).canvas
+ ? resolveFlowchartSurface(appearance, theme).canvas
: kind === "architecture"
? resolveArchitectureSurface(appearance).canvas
: resolveDiagramPalette(theme, appearance).canvas);
@@ -787,7 +789,7 @@ const nodeEditorState = (
? resolveMindMapNodeStyle(mindNodes, node.id, resolveDiagramPalette(theme, appearance), theme, appearance, node.getSize())
: null;
const flowchartStyle = !mindRole && (data?.shape === "process" || data?.shape === "decision" || data?.shape === "terminator")
- ? flowchartNodeVisual(data.shape, appearance, node.getSize())
+ ? flowchartNodeVisual(data.shape, appearance, node.getSize(), theme)
: null;
const architectureStyle = !mindRole && !flowchartStyle && data?.shape && isArchitectureNodeShape(data.shape)
? architectureNodeVisual(data.shape, appearance, node.getSize(), data.resourceIcon)
@@ -935,7 +937,7 @@ const nodeMetadata = (
const mindStyle = kind === "mind-map"
? resolveMindMapNodeStyle([node], node.id, palette, theme, appearance, size, structure)
: null;
- const flowchartStyle = kind === "flowchart" ? flowchartNodeVisual(node.shape, appearance, size) : null;
+ const flowchartStyle = kind === "flowchart" ? flowchartNodeVisual(node.shape, appearance, size, theme) : null;
const architectureStyle = kind === "architecture"
? architectureNodeVisual(node.shape, appearance, size, node.resourceIcon)
: null;
@@ -943,7 +945,7 @@ const nodeMetadata = (
? mindStyle.visual
: flowchartStyle ?? architectureStyle ?? nodeAttrs(node.shape, theme, appearance, isRootTopic);
const hasPorts = isConnectableDiagram(kind) && node.shape !== "boundary";
- const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
+ const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance, theme) : null;
const architectureSurface = kind === "architecture" ? resolveArchitectureSurface(appearance) : null;
const portPalette = flowchartSurface
? { ...palette, canvas: flowchartSurface.canvas, topicStroke: flowchartSurface.terminator.stroke }
@@ -992,8 +994,9 @@ const diagramEdgeLabel = (
palette: ReturnType<typeof resolveDiagramPalette>,
kind: DiagramDocument["kind"],
appearance: DiagramAppearance = "light",
+ theme?: DiagramTheme,
) => {
- const flowchart = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
+ const flowchart = kind === "flowchart" ? resolveFlowchartSurface(appearance, theme) : null;
const architecture = kind === "architecture" ? resolveArchitectureSurface(appearance) : null;
return {
position: { distance: 0.5, offset: kind === "architecture" ? { x: 0, y: -16 } : 0 },
@@ -1011,41 +1014,39 @@ const edgeMetadata = (
kind: DiagramDocument["kind"],
theme: DiagramTheme,
appearance: DiagramAppearance,
+ structure?: DiagramStructure,
) => {
const palette = resolveDiagramPalette(theme, appearance);
const edgeKind = edge.kind ?? (kind === "architecture" ? "dependency" : undefined);
const mindEdge = kind === "mind-map" ? mindMapEdgeVisual("primary", palette) : null;
- const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
+ const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance, theme) : null;
const architectureEdge = kind === "architecture"
? architectureEdgeVisual(edgeKind, appearance, edge.bidirectional)
: null;
const edgeStroke = architectureEdge?.stroke ?? mindEdge?.stroke ?? flowchartSurface?.edge ?? palette.flowEdge;
+ const mindLine = mindEdge ? mindMapEdgeLineAttrs(structure, edgeStroke) : null;
return {
id: edge.id,
source: { cell: edge.source },
target: { cell: edge.target },
router: kind === "flowchart" ? FLOWCHART_EDGE_ROUTER : undefined,
connector: kind === "mind-map"
- ? { name: MIND_MAP_CONNECTOR_NAME, args: { sourceWidth: mindEdge?.sourceWidth, targetWidth: mindEdge?.targetWidth } }
+ ? { name: MIND_MAP_CONNECTOR_NAME, args: { sourceWidth: mindEdge?.sourceWidth, targetWidth: mindEdge?.targetWidth, structure } }
: { name: "rounded", args: { radius: 10 } },
data: { ...(edgeKind ? { kind: edgeKind } : {}), ...(edge.bidirectional ? { bidirectional: true } : {}) } satisfies EdgeData,
attrs: {
line: {
stroke: edgeStroke,
- strokeWidth: architectureEdge?.strokeWidth ?? (mindEdge ? 0.5 : 1.5),
+ strokeWidth: architectureEdge?.strokeWidth ?? mindLine?.strokeWidth ?? 1.5,
strokeDasharray: architectureEdge?.strokeDasharray,
sourceMarker: architectureEdge
? architectureEdge.sourceMarker
: edge.bidirectional ? { name: "block", width: 8, height: 6 } : null,
targetMarker: kind === "mind-map" ? null : architectureEdge?.targetMarker ?? { name: "block", width: 8, height: 6 },
- ...(mindEdge ? {
- fill: edgeStroke,
- strokeLinejoin: "round",
- strokeLinecap: "round",
- } : { fill: "none" }),
+ ...(mindLine ?? { fill: "none" }),
},
},
- labels: edge.label ? [diagramEdgeLabel(edge.label, palette, kind, appearance)] : undefined,
+ labels: edge.label ? [diagramEdgeLabel(edge.label, palette, kind, appearance, theme)] : undefined,
};
};
@@ -1203,17 +1204,24 @@ const applyMindMapHierarchy = (graph: Graph, theme: DiagramTheme, appearance: Di
const sourceRole = mindMapNodeRole(nodes, source.id);
const targetStyle = resolveMindMapNodeStyle(nodes, target.id, palette, theme, appearance, target, structure);
const visual = mindMapEdgeVisual(sourceRole, palette, targetStyle.tint);
- const sides = mindMapBranchSides(source, target);
+ const sides = mindMapBranchSides(source, target, structure);
const sourceTerminal = mindMapEdgeTerminal(source, sourceRole, sides.source, structure);
const targetTerminal = mindMapEdgeTerminal(target, targetStyle.role, sides.target, structure);
+ const braceSpan = structure === "brace" ? mindMapSiblingSpan(nodes, sourceId) : null;
+ const line = mindMapEdgeLineAttrs(structure, visual.stroke);
edge.setSource({ cell: sourceId, ...sourceTerminal });
edge.setTarget({ cell: targetId, ...targetTerminal });
- edge.setConnector(MIND_MAP_CONNECTOR_NAME, { sourceWidth: visual.sourceWidth, targetWidth: visual.targetWidth });
+ edge.setConnector(MIND_MAP_CONNECTOR_NAME, {
+ sourceWidth: visual.sourceWidth,
+ targetWidth: visual.targetWidth,
+ structure,
+ ...(braceSpan ? { braceTop: braceSpan.top, braceBottom: braceSpan.bottom } : {}),
+ });
edge.attr("line/stroke", visual.stroke);
- edge.attr("line/fill", visual.stroke);
- edge.attr("line/strokeWidth", 0.5);
- edge.attr("line/strokeLinejoin", "round");
- edge.attr("line/strokeLinecap", "round");
+ edge.attr("line/fill", line.fill);
+ edge.attr("line/strokeWidth", line.strokeWidth);
+ edge.attr("line/strokeLinejoin", line.strokeLinejoin);
+ edge.attr("line/strokeLinecap", line.strokeLinecap);
edge.attr("line/targetMarker", null);
edge.attr("line/sourceMarker", null);
}
@@ -1236,7 +1244,7 @@ const applyGraphPalette = (
const data = node.getData<NodeData>();
const shape = data?.shape ?? "process";
refreshNodeLabel(node, data?.label ?? "", structure);
- const flowchartStyle = kind === "flowchart" ? flowchartNodeVisual(shape, appearance, node.getSize()) : null;
+ const flowchartStyle = kind === "flowchart" ? flowchartNodeVisual(shape, appearance, node.getSize(), theme) : null;
const architectureStyle = kind === "architecture"
? architectureNodeVisual(shape, appearance, node.getSize(), data?.resourceIcon)
: null;
@@ -1250,7 +1258,7 @@ const applyGraphPalette = (
node.attr(selector, selectorAttrs as Record<string, string | number | undefined>);
}
}
- const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
+ const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance, theme) : null;
const architectureSurface = kind === "architecture" ? resolveArchitectureSurface(appearance) : null;
for (const port of node.getPorts()) {
if (!port.id) continue;
@@ -1260,7 +1268,7 @@ const applyGraphPalette = (
});
}
}
- const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
+ const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance, theme) : null;
for (const edge of graph.getEdges()) {
const edgeKind = edge.getData<EdgeData>()?.kind;
const architectureEdge = kind === "architecture"
@@ -1275,7 +1283,7 @@ const applyGraphPalette = (
}
if (kind !== "mind-map") edge.attr("line/fill", "none");
if (edge.getLabels().length > 0) {
- edge.setLabels(edge.getLabels().map((label) => diagramEdgeLabel(String(label.attrs?.label?.text ?? ""), palette, kind, appearance)));
+ edge.setLabels(edge.getLabels().map((label) => diagramEdgeLabel(String(label.attrs?.label?.text ?? ""), palette, kind, appearance, theme)));
}
}
if (kind === "mind-map") applyMindMapHierarchy(graph, theme, appearance, structure);
@@ -1638,7 +1646,7 @@ export const DiagramEditorPane = ({
if (parent?.isNode()) parent.addChild(node);
}
}
- graph.addEdges(document.edges.map((edge) => edgeMetadata(edge, document.kind, documentTheme, appearance)));
+ graph.addEdges(document.edges.map((edge) => edgeMetadata(edge, document.kind, documentTheme, appearance, documentStructure)));
if (document.kind === "flowchart") applyFlowchartEdgePorts(graph);
applyGraphPalette(graph, documentTheme, document.kind, appearance, documentStructure);
graph.on("scale", () => setZoomPercent(Math.round(graph.scale().sx * 100)));
@@ -2155,6 +2163,7 @@ export const DiagramEditorPane = ({
document.kind,
themeRef.current,
appearanceRef.current,
+ structureRef.current,
));
}
if (isMindMap) {
@@ -2260,7 +2269,7 @@ export const DiagramEditorPane = ({
return;
}
const palette = resolveDiagramPalette(themeRef.current, appearanceRef.current);
- edge.setLabels([diagramEdgeLabel(label, palette, document?.kind ?? "flowchart", appearanceRef.current)]);
+ edge.setLabels([diagramEdgeLabel(label, palette, document?.kind ?? "flowchart", appearanceRef.current, themeRef.current)]);
};
const createConnectedFlowNode = (shape: DiagramNodeShape) => {
@@ -2848,7 +2857,8 @@ export const DiagramEditorPane = ({
onExport={exportDiagram}
onRedo={() => runHistoryAction("redo")}
onThemeChange={applyTheme}
- showTheme={document.kind === "mind-map"}
+ showTheme={document.kind !== "architecture"}
+ themeCatalog={document.kind === "flowchart" ? "flowchart" : "mind-map"}
onStructureChange={document.kind === "mind-map" ? applyStructure : undefined}
structure={structure}
onUndo={() => runHistoryAction("undo")}
diff --git a/apps/web/src/components/DiagramToolbar.tsx b/apps/web/src/components/DiagramToolbar.tsx
index 3cf41fdd..928d33dd 100644
--- a/apps/web/src/components/DiagramToolbar.tsx
+++ b/apps/web/src/components/DiagramToolbar.tsx
@@ -15,7 +15,18 @@ import {
ZoomOut,
} from "lucide-react";
import { useTranslation } from "react-i18next";
-import { DIAGRAM_SELECTABLE_STRUCTURES, DIAGRAM_THEME_GROUPS, diagramThemeSwatches, resolveDiagramTheme, type DiagramStructure, type DiagramTheme } from "@edgeever/shared";
+import {
+ DIAGRAM_SELECTABLE_STRUCTURES,
+ DIAGRAM_STRUCTURE_GROUPS,
+ DIAGRAM_THEME_GROUPS,
+ FLOWCHART_SELECTABLE_THEMES,
+ diagramThemeSwatches,
+ flowchartThemeSwatches,
+ resolveDiagramTheme,
+ resolveFlowchartTheme,
+ type DiagramStructure,
+ type DiagramTheme,
+} from "@edgeever/shared";
import { Button } from "@/components/ui/button";
import { MemoEditorToolbarDivider, MemoEditorToolbarRow } from "@/components/MemoEditorToolbarChrome";
import {
@@ -28,10 +39,9 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import type { DiagramAppearance } from "@/lib/diagram-theme";
import { cn } from "@/lib/utils";
-const STRUCTURE_GROUPS: Array<{ labelKey: "diagram.structureGroupMap" | "diagram.structureGroupLogic"; items: Array<typeof DIAGRAM_SELECTABLE_STRUCTURES[number]> }> = [
- { labelKey: "diagram.structureGroupMap", items: ["map", "line", "capsule", "box", "circle", "ellipse", "hexagon"] },
- { labelKey: "diagram.structureGroupLogic", items: ["logic", "tree", "brace"] },
-];
+const structureGroupLabelKey = (id: typeof DIAGRAM_STRUCTURE_GROUPS[number]["id"]) => (
+ `diagram.structureGroup${id.charAt(0).toUpperCase()}${id.slice(1)}` as "diagram.structureGroupMap"
+);
const nodePath = (form: typeof DIAGRAM_SELECTABLE_STRUCTURES[number], x: number, y: number, w: number, h: number) => {
if (form === "line" || form === "brace" || form === "map") return null;
@@ -45,9 +55,60 @@ const nodePath = (form: typeof DIAGRAM_SELECTABLE_STRUCTURES[number], x: number,
return <rect x={x} y={y} width={w} height={h} rx={rx} />;
};
+const ThumbFrame = ({ children }: { children: ReactNode }) => (
+ <svg viewBox="0 0 96 56" className="h-12 w-full text-slate-500" fill="currentColor" stroke="currentColor" strokeWidth="1.2">
+ {children}
+ </svg>
+);
+
const StructureThumb = ({ structure }: { structure: typeof DIAGRAM_SELECTABLE_STRUCTURES[number] }) => {
- const oneSided = structure === "logic" || structure === "tree" || structure === "brace";
- const lineOnly = structure === "line" || structure === "brace" || structure === "map";
+ if (structure === "brace") {
+ return (
+ <ThumbFrame>
+ <rect x="6" y="22" width="20" height="12" rx="3" fill="currentColor" opacity="0.35" stroke="none" />
+ <path d="M 32 10 C 40 10 40 10 40 20 C 40 28 48 28 48 28 C 40 28 40 28 40 36 C 40 46 40 46 32 46" fill="none" />
+ <path d="M 48 16 H 86 M 48 28 H 86 M 48 40 H 86" fill="none" />
+ </ThumbFrame>
+ );
+ }
+ if (structure === "org") {
+ return (
+ <ThumbFrame>
+ <rect x="38" y="6" width="20" height="10" rx="2" fill="currentColor" opacity="0.35" stroke="none" />
+ <path d="M 48 16 V 24 H 16 V 28 M 48 24 H 80 V 28 M 48 24 V 28" fill="none" />
+ <g fill="white"><rect x="6" y="28" width="20" height="10" rx="2" /><rect x="38" y="28" width="20" height="10" rx="2" /><rect x="70" y="28" width="20" height="10" rx="2" /></g>
+ </ThumbFrame>
+ );
+ }
+ if (structure === "tree") {
+ return (
+ <ThumbFrame>
+ <rect x="6" y="8" width="20" height="10" rx="2" fill="currentColor" opacity="0.35" stroke="none" />
+ <path d="M 26 13 H 36 V 44 M 36 13 H 52 M 36 28 H 52 M 36 44 H 52" fill="none" />
+ <g fill="white"><rect x="52" y="8" width="22" height="10" rx="2" /><rect x="52" y="23" width="22" height="10" rx="2" /><rect x="52" y="38" width="22" height="10" rx="2" /></g>
+ </ThumbFrame>
+ );
+ }
+ if (structure === "timeline") {
+ return (
+ <ThumbFrame>
+ <rect x="6" y="22" width="16" height="10" rx="2" fill="currentColor" opacity="0.35" stroke="none" />
+ <path d="M 22 27 H 90 M 40 27 V 14 M 62 27 V 40 M 84 27 V 14" fill="none" />
+ <g fill="white"><rect x="30" y="6" width="20" height="8" rx="2" /><rect x="52" y="40" width="20" height="8" rx="2" /><rect x="74" y="6" width="16" height="8" rx="2" /></g>
+ </ThumbFrame>
+ );
+ }
+ if (structure === "fishbone") {
+ return (
+ <ThumbFrame>
+ <rect x="72" y="22" width="18" height="12" rx="3" fill="currentColor" opacity="0.35" stroke="none" />
+ <path d="M 72 28 H 8 M 58 28 L 46 12 M 58 28 L 46 44 M 38 28 L 26 12 M 38 28 L 26 44" fill="none" />
+ <g fill="white"><rect x="36" y="6" width="16" height="8" rx="2" /><rect x="36" y="42" width="16" height="8" rx="2" /><rect x="16" y="6" width="16" height="8" rx="2" /><rect x="16" y="42" width="16" height="8" rx="2" /></g>
+ </ThumbFrame>
+ );
+ }
+ const oneSided = structure === "logic";
+ const lineOnly = structure === "line" || structure === "map";
const root = { x: oneSided ? 8 : 38, y: 20, w: oneSided ? 22 : 20, h: 12 };
const left = [{ x: 6, y: 8 }, { x: 6, y: 32 }];
const right = oneSided
@@ -57,7 +118,7 @@ const StructureThumb = ({ structure }: { structure: typeof DIAGRAM_SELECTABLE_ST
const cx = root.x + root.w / 2;
const cy = root.y + root.h / 2;
return (
- <svg viewBox="0 0 96 56" className="h-12 w-full text-slate-500" fill="currentColor" stroke="currentColor" strokeWidth="1.2">
+ <ThumbFrame>
<rect x={root.x} y={root.y} width={root.w} height={root.h} rx={3} fill="currentColor" opacity="0.35" stroke="none" />
{(oneSided ? right : [...left, ...right]).map((item, index) => (
<g key={index}>
@@ -69,7 +130,7 @@ const StructureThumb = ({ structure }: { structure: typeof DIAGRAM_SELECTABLE_ST
)}
</g>
))}
- </svg>
+ </ThumbFrame>
);
};
@@ -85,6 +146,7 @@ type DiagramToolbarProps = {
onRedo: () => void;
onThemeChange: (theme: DiagramTheme) => void;
showTheme?: boolean;
+ themeCatalog?: "mind-map" | "flowchart";
onStructureChange?: (structure: DiagramStructure) => void;
structure?: DiagramStructure;
onUndo: () => void;
@@ -128,6 +190,7 @@ export const DiagramToolbar = ({
onRedo,
onThemeChange,
showTheme = true,
+ themeCatalog = "mind-map",
onStructureChange,
onUndo,
onRead,
@@ -142,6 +205,8 @@ export const DiagramToolbar = ({
theme,
}: DiagramToolbarProps) => {
const { t } = useTranslation();
+ const resolvedTheme = themeCatalog === "flowchart" ? resolveFlowchartTheme(theme) : resolveDiagramTheme(theme);
+ const themeLabel = t(`diagram.theme${resolvedTheme.charAt(0).toUpperCase()}${resolvedTheme.slice(1)}` as "diagram.themeBrand");
return (
<MemoEditorToolbarRow className="shrink-0 border-b border-slate-200 bg-white" role="toolbar" aria-label={t("diagram.toolbar")}>
{leading ? <>{leading}<MemoEditorToolbarDivider /></> : null}
@@ -179,15 +244,19 @@ export const DiagramToolbar = ({
</TooltipTrigger>
<TooltipContent>{t("diagram.structure")}</TooltipContent>
</Tooltip>
- <DropdownMenuContent align="start" className="w-[22.5rem] p-3">
- {STRUCTURE_GROUPS.map((group) => (
- <div key={group.labelKey} className="mb-3 last:mb-0">
- <div className="mb-1.5 text-xs font-medium text-slate-500">{t(group.labelKey)}</div>
- <div className="grid grid-cols-3 gap-2">
+ <DropdownMenuContent align="start" className="max-h-[min(36rem,70vh)] w-[22.5rem] overflow-y-auto p-3">
+ {DIAGRAM_STRUCTURE_GROUPS.map((group) => (
+ <div key={group.id} className="mb-3 last:mb-0">
+ <div className="mb-1.5 text-xs font-medium text-slate-500">{t(structureGroupLabelKey(group.id))}</div>
+ <div className={group.items.length >= 3 ? "grid grid-cols-3 gap-2" : "flex flex-wrap gap-2"}>
{group.items.map((value) => (
<DropdownMenuItem
key={value}
- className={cn("h-auto flex-col items-stretch gap-1 rounded-lg border p-1.5", structure === value ? "border-slate-900 bg-slate-50" : "border-slate-200")}
+ className={cn(
+ "h-auto flex-col items-stretch gap-1 rounded-lg border p-1.5",
+ group.items.length < 3 ? "w-[calc((100%-1rem)/3)]" : "",
+ structure === value ? "border-slate-900 bg-slate-50" : "border-slate-200",
+ )}
onSelect={() => onStructureChange(value)}
>
<StructureThumb structure={value} />
@@ -206,11 +275,11 @@ export const DiagramToolbar = ({
<DropdownMenuTrigger asChild>
<Button size="sm" variant="ghost" className="gap-1.5 px-2.5" disabled={readOnly} aria-label={t("diagram.theme")}>
<span className="flex h-3.5 overflow-hidden rounded-sm border border-black/10">
- {diagramThemeSwatches(theme).slice(0, 4).map((color) => (
+ {(themeCatalog === "flowchart" ? flowchartThemeSwatches(theme) : diagramThemeSwatches(theme).slice(0, 4)).map((color) => (
<span key={color} className="h-full w-2.5" style={{ background: color }} />
))}
</span>
- {t(`diagram.theme${resolveDiagramTheme(theme).charAt(0).toUpperCase()}${resolveDiagramTheme(theme).slice(1)}` as "diagram.themeBrand")}
+ {themeLabel}
<ChevronDown className="h-3.5 w-3.5 text-slate-400" />
</Button>
</DropdownMenuTrigger>
@@ -218,7 +287,24 @@ export const DiagramToolbar = ({
<TooltipContent>{t("diagram.theme")}</TooltipContent>
</Tooltip>
<DropdownMenuContent align="start" className="w-[18.5rem] p-3">
- {(["vivid", "classic"] as const).map((group) => (
+ {themeCatalog === "flowchart" ? (
+ <div className="grid grid-cols-1 gap-1.5">
+ {FLOWCHART_SELECTABLE_THEMES.map((value) => (
+ <DropdownMenuItem
+ key={value}
+ className={cn("h-auto items-center gap-3 rounded-lg border px-2 py-1.5", resolveFlowchartTheme(theme) === value ? "border-slate-900 bg-slate-50" : "border-transparent")}
+ onSelect={() => onThemeChange(value)}
+ >
+ <span className="flex h-5 flex-1 overflow-hidden rounded-md border border-black/10">
+ {flowchartThemeSwatches(value).map((color) => (
+ <span key={`${value}-${color}`} className="h-full flex-1" style={{ background: color }} />
+ ))}
+ </span>
+ <span className="w-10 shrink-0 text-xs text-slate-600">{t(`diagram.theme${value.charAt(0).toUpperCase()}${value.slice(1)}` as "diagram.themeBrand")}</span>
+ </DropdownMenuItem>
+ ))}
+ </div>
+ ) : (["vivid", "classic"] as const).map((group) => (
<div key={group} className="mb-3 last:mb-0">
<div className="mb-1.5 text-xs font-medium text-slate-500">{t(group === "vivid" ? "diagram.themeGroupVivid" : "diagram.themeGroupClassic")}</div>
<div className="grid grid-cols-1 gap-1.5">
diff --git a/apps/web/src/lib/diagram-layout.test.mjs b/apps/web/src/lib/diagram-layout.test.mjs
index 0415442a..cb650710 100644
--- a/apps/web/src/lib/diagram-layout.test.mjs
+++ b/apps/web/src/lib/diagram-layout.test.mjs
@@ -18,6 +18,34 @@ describe("diagram auto layout", () => {
expect(new Set(document.nodes.map((node) => positions[node.id].y)).size).toBeGreaterThan(1);
});
+ test("lays out org, timeline, fishbone, brace, and hanging tree as distinct map families", () => {
+ const document = createDefaultDiagramDocument("mind-map");
+ const org = computeDiagramLayout({ ...document, structure: "org" });
+ expect(org["topic-1"].y).toBeGreaterThan(org["topic-root"].y + 40);
+ expect(org["topic-2"].y).toBe(org["topic-1"].y);
+ expect(org["topic-1-a"].y).toBeGreaterThan(org["topic-1"].y);
+
+ const timeline = computeDiagramLayout({ ...document, structure: "timeline" });
+ expect(timeline["topic-1"].x).toBeGreaterThan(timeline["topic-root"].x);
+ expect(timeline["topic-2"].x).toBeGreaterThan(timeline["topic-1"].x);
+ expect(timeline["topic-1"].y).toBeLessThan(timeline["topic-root"].y);
+ expect(timeline["topic-2"].y).toBeGreaterThan(timeline["topic-root"].y);
+
+ const fishbone = computeDiagramLayout({ ...document, structure: "fishbone" });
+ expect(fishbone["topic-1"].x).toBeLessThan(fishbone["topic-root"].x);
+ expect(fishbone["topic-1"].y).toBeLessThan(fishbone["topic-root"].y);
+ expect(fishbone["topic-2"].y).toBeGreaterThan(fishbone["topic-root"].y);
+
+ const brace = computeDiagramLayout({ ...document, structure: "brace" });
+ expect(brace["topic-1"].x).toBeGreaterThan(brace["topic-root"].x);
+ expect(brace["topic-1"].x).toBeGreaterThan(computeDiagramLayout(document)["topic-1"].x);
+
+ const tree = computeDiagramLayout({ ...document, structure: "tree" });
+ expect(tree["topic-1"].y).toBe(tree["topic-root"].y);
+ expect(tree["topic-2"].y).toBeGreaterThan(tree["topic-1"].y);
+ expect(tree["topic-1"].x).toBeGreaterThan(tree["topic-root"].x);
+ });
+
test("uses compact topic sizes while allowing longer labels to grow within a cap", () => {
expect(compactMindMapNodeSize("分支主题", false)).toEqual({ width: 96, height: 36 });
expect(compactMindMapNodeSize("核心主题", true)).toEqual({ width: 124, height: 46 });
diff --git a/packages/shared/src/diagram-flowchart-style.test.mjs b/packages/shared/src/diagram-flowchart-style.test.mjs
index 300f919d..63d5d4a4 100644
--- a/packages/shared/src/diagram-flowchart-style.test.mjs
+++ b/packages/shared/src/diagram-flowchart-style.test.mjs
@@ -2,12 +2,14 @@ import { describe, expect, test } from "bun:test";
import { flowchartNodePresentation } from "./diagram-node-presentation.ts";
import {
FLOWCHART_READABLE_MIN_SCALE,
+ FLOWCHART_SELECTABLE_THEMES,
FLOWCHART_SURFACES,
flowchartEdgeIsStraight,
flowchartEdgePorts,
flowchartFitsReadableViewport,
flowchartNodeVisual,
resolveFlowchartSurface,
+ resolveFlowchartTheme,
} from "./diagram-flowchart-style.ts";
const channel = (value) => {
@@ -27,20 +29,24 @@ const contrast = (foreground, background) => {
describe("flowchart semantic paint", () => {
test("keeps process, decision, and terminator visually distinct", () => {
- for (const appearance of ["light", "dark"]) {
- const surface = resolveFlowchartSurface(appearance);
- expect(surface.process.fill).not.toBe(surface.decision.fill);
- expect(surface.process.fill).not.toBe(surface.terminator.fill);
- expect(surface.decision.stroke).not.toBe(surface.process.stroke);
- expect(surface.terminator.fill).not.toBe("#16A06E");
+ for (const theme of ["brand", "ink", "paper"]) {
+ for (const appearance of ["light", "dark"]) {
+ const surface = resolveFlowchartSurface(appearance, theme);
+ expect(surface.process.fill).not.toBe(surface.decision.fill);
+ expect(surface.process.fill).not.toBe(surface.terminator.fill);
+ expect(surface.decision.stroke).not.toBe(surface.process.stroke);
+ expect(surface.terminator.fill).not.toBe("#16A06E");
+ }
}
});
test("keeps node labels readable on their fills", () => {
- for (const appearance of ["light", "dark"]) {
- const surface = FLOWCHART_SURFACES[appearance];
- for (const paint of [surface.process, surface.decision, surface.terminator]) {
- expect(contrast(paint.text, paint.fill)).toBeGreaterThanOrEqual(4.5);
+ for (const theme of ["brand", "ink", "paper"]) {
+ for (const appearance of ["light", "dark"]) {
+ const surface = FLOWCHART_SURFACES[theme][appearance];
+ for (const paint of [surface.process, surface.decision, surface.terminator]) {
+ expect(contrast(paint.text, paint.fill)).toBeGreaterThanOrEqual(4.5);
+ }
}
}
});
@@ -48,9 +54,23 @@ describe("flowchart semantic paint", () => {
test("uses outlined capsules and Inter for terminator labels", () => {
const visual = flowchartNodeVisual("terminator", "light", { width: 116, height: 40 });
expect(visual.body.rx).toBe(20);
- expect(visual.body.fill).toBe(FLOWCHART_SURFACES.light.terminator.fill);
+ expect(visual.body.fill).toBe(FLOWCHART_SURFACES.brand.light.terminator.fill);
expect(visual.label.fontFamily).toContain("Inter");
});
+
+ test("offers three quiet surfaces and maps unknown themes to forest", () => {
+ expect(FLOWCHART_SELECTABLE_THEMES).toEqual(["brand", "ink", "paper"]);
+ expect(resolveFlowchartTheme("mint")).toBe("brand");
+ expect(resolveFlowchartTheme("classic")).toBe("brand");
+ expect(FLOWCHART_SURFACES.brand.light.terminator.stroke).toBe("#16A06E");
+ expect(resolveFlowchartSurface("light", "mint")).toEqual(FLOWCHART_SURFACES.brand.light);
+ expect(resolveFlowchartSurface("light", "ink").terminator.stroke).toBe("#3A4656");
+ expect(resolveFlowchartSurface("light", "paper").canvas).toBe("#F6F1E8");
+ expect(resolveFlowchartSurface("light", "ink").decision.fill)
+ .not.toBe(resolveFlowchartSurface("light", "brand").decision.fill);
+ expect(resolveFlowchartSurface("light", "paper").terminator.stroke)
+ .not.toBe(resolveFlowchartSurface("light", "brand").terminator.stroke);
+ });
});
describe("flowchart node presentation", () => {
diff --git a/packages/shared/src/diagram-flowchart-style.ts b/packages/shared/src/diagram-flowchart-style.ts
index e34bde80..2fc00ab1 100644
--- a/packages/shared/src/diagram-flowchart-style.ts
+++ b/packages/shared/src/diagram-flowchart-style.ts
@@ -1,4 +1,4 @@
-import type { DiagramNodeShape } from "./diagram";
+import type { DiagramNodeShape, DiagramTheme } from "./diagram";
export const FLOWCHART_LABEL_FONT =
'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
@@ -63,6 +63,8 @@ export const flowchartFitsReadableViewport = (
};
export type FlowchartAppearance = "light" | "dark";
+export const FLOWCHART_SELECTABLE_THEMES = ["brand", "ink", "paper"] as const;
+export type FlowchartTheme = (typeof FLOWCHART_SELECTABLE_THEMES)[number];
export type FlowchartShapePaint = {
fill: string;
@@ -78,28 +80,99 @@ export type FlowchartSurface = {
terminator: FlowchartShapePaint;
};
-export const FLOWCHART_SURFACES: Record<FlowchartAppearance, FlowchartSurface> = {
- light: {
- canvas: "#F5F8F6",
- edge: "#4A8A6C",
- process: { fill: "#FFFFFF", stroke: "#6F9B88", text: "#1C3D31" },
- decision: { fill: "#FFF6E5", stroke: "#D4A24A", text: "#7A4A12" },
- terminator: { fill: "#E7F6EF", stroke: "#16A06E", text: "#145C40" },
+const FLOWCHART_THEME_ALIASES: Partial<Record<DiagramTheme, FlowchartTheme>> = {
+ ocean: "brand",
+ ink: "ink",
+ paper: "paper",
+};
+
+export const resolveFlowchartTheme = (theme?: DiagramTheme): FlowchartTheme => {
+ if (theme && (FLOWCHART_SELECTABLE_THEMES as readonly string[]).includes(theme)) return theme as FlowchartTheme;
+ return FLOWCHART_THEME_ALIASES[theme ?? "brand"] ?? "brand";
+};
+
+export const FLOWCHART_SURFACES: Record<FlowchartTheme, Record<FlowchartAppearance, FlowchartSurface>> = {
+ brand: {
+ light: {
+ canvas: "#F5F8F6",
+ edge: "#4A8A6C",
+ process: { fill: "#FFFFFF", stroke: "#6F9B88", text: "#1C3D31" },
+ decision: { fill: "#FFF6E5", stroke: "#D4A24A", text: "#7A4A12" },
+ terminator: { fill: "#E7F6EF", stroke: "#16A06E", text: "#145C40" },
+ },
+ dark: {
+ canvas: "#101311",
+ edge: "#7BB89A",
+ process: { fill: "#1B2420", stroke: "#5B7569", text: "#E8F2ED" },
+ decision: { fill: "#2A2316", stroke: "#E0B35C", text: "#F8E4B8" },
+ terminator: { fill: "#1A3329", stroke: "#4DB58B", text: "#D8F3E6" },
+ },
},
- dark: {
- canvas: "#101311",
- edge: "#7BB89A",
- process: { fill: "#1B2420", stroke: "#5B7569", text: "#E8F2ED" },
- decision: { fill: "#2A2316", stroke: "#E0B35C", text: "#F8E4B8" },
- terminator: { fill: "#1A3329", stroke: "#4DB58B", text: "#D8F3E6" },
+ ink: {
+ light: {
+ canvas: "#F3F5F7",
+ edge: "#5C6774",
+ process: { fill: "#FFFFFF", stroke: "#7D8794", text: "#1C232C" },
+ decision: { fill: "#E8EDF3", stroke: "#6E7C8F", text: "#243044" },
+ terminator: { fill: "#E6EAEF", stroke: "#3A4656", text: "#1A222C" },
+ },
+ dark: {
+ canvas: "#101214",
+ edge: "#9AA3AE",
+ process: { fill: "#1B1E23", stroke: "#6B7380", text: "#E8ECF1" },
+ decision: { fill: "#222830", stroke: "#8B9BB0", text: "#D5DDE8" },
+ terminator: { fill: "#1A2028", stroke: "#A8B4C4", text: "#E8EEF4" },
+ },
+ },
+ paper: {
+ light: {
+ canvas: "#F6F1E8",
+ edge: "#8B7355",
+ process: { fill: "#FFFCF6", stroke: "#C4B396", text: "#3A3126" },
+ decision: { fill: "#F4E4CC", stroke: "#C08A48", text: "#6A3F14" },
+ terminator: { fill: "#F0E4D0", stroke: "#7A5230", text: "#3F2A16" },
+ },
+ dark: {
+ canvas: "#161310",
+ edge: "#C4A882",
+ process: { fill: "#221E19", stroke: "#7A6A56", text: "#F3EBE0" },
+ decision: { fill: "#2C2418", stroke: "#D4A06A", text: "#F6E2C4" },
+ terminator: { fill: "#2A2118", stroke: "#C4A07A", text: "#F0E4D4" },
+ },
},
};
-export const resolveFlowchartSurface = (appearance: FlowchartAppearance = "light") =>
- FLOWCHART_SURFACES[appearance];
+export const resolveFlowchartSurface = (
+ appearance: FlowchartAppearance = "light",
+ theme?: DiagramTheme,
+) => FLOWCHART_SURFACES[resolveFlowchartTheme(theme)][appearance];
+
+export const flowchartThemeSwatches = (theme?: DiagramTheme) => {
+ const surface = resolveFlowchartSurface("light", theme);
+ return [surface.process.fill, surface.decision.fill, surface.terminator.stroke] as const;
+};
+
+export const flowchartMermaidClassName = (shape: DiagramNodeShape) =>
+ shape === "decision" ? "flowDecision" : shape === "terminator" ? "flowTerminator" : "flowProcess";
+
+export const flowchartMermaidClassDefs = (
+ theme?: DiagramTheme,
+ appearance: FlowchartAppearance = "light",
+) => {
+ const surface = resolveFlowchartSurface(appearance, theme);
+ return (["process", "decision", "terminator"] as const).map((role) => {
+ const paint = surface[role];
+ const className = role === "process" ? "flowProcess" : role === "decision" ? "flowDecision" : "flowTerminator";
+ return ` classDef ${className} fill:${paint.fill},stroke:${paint.stroke},color:${paint.text},stroke-width:1.5px`;
+ });
+};
-export const flowchartShapePaint = (shape: DiagramNodeShape, appearance: FlowchartAppearance) => {
- const surface = resolveFlowchartSurface(appearance);
+export const flowchartShapePaint = (
+ shape: DiagramNodeShape,
+ appearance: FlowchartAppearance,
+ theme?: DiagramTheme,
+) => {
+ const surface = resolveFlowchartSurface(appearance, theme);
if (shape === "decision") return surface.decision;
if (shape === "terminator") return surface.terminator;
return surface.process;
@@ -109,8 +182,9 @@ export const flowchartNodeVisual = (
shape: DiagramNodeShape,
appearance: FlowchartAppearance,
size: { width: number; height: number },
+ theme?: DiagramTheme,
) => {
- const paint = flowchartShapePaint(shape, appearance);
+ const paint = flowchartShapePaint(shape, appearance, theme);
const terminator = shape === "terminator";
const decision = shape === "decision";
return {
diff --git a/packages/shared/src/diagram-layout.ts b/packages/shared/src/diagram-layout.ts
index a55eeb52..436731d7 100644
--- a/packages/shared/src/diagram-layout.ts
+++ b/packages/shared/src/diagram-layout.ts
@@ -12,6 +12,7 @@ import {
MIND_MAP_HORIZONTAL_GAP,
MIND_MAP_VERTICAL_GAP,
mindMapIsOneSided,
+ mindMapLayoutFamily,
mindMapNodePresentation,
mindMapNodeRole,
} from "./diagram-mindmap-style";
@@ -95,6 +96,16 @@ export type DiagramIr = {
};
const MIND_MAP_TWO_SIDED_THRESHOLD = 5;
+const BRACE_HORIZONTAL_GAP = 88;
+const TREE_HORIZONTAL_GAP = 64;
+const ORG_RANK_GAP = 56;
+const ORG_NODE_GAP = 36;
+const TIMELINE_COLUMN_GAP = 56;
+const TIMELINE_SPINE_GAP = 40;
+const TIMELINE_NEST_INDENT = 16;
+const FISHBONE_COLUMN_GAP = 28;
+const FISHBONE_SPINE_GAP = 56;
+const FISHBONE_NEST_INDENT = 20;
const FLOWCHART_DETACHED_GAP = 56;
const FLOWCHART_DETACHED_ROW_GAP = 24;
const FLOWCHART_DETACHED_ROW_WIDTH = 960;
@@ -148,15 +159,19 @@ const computeMindMapLayout = (
}
}
+ const childIdsOf = (nodeId: string, ancestors: Set<string>) => (
+ (childrenByParent.get(nodeId) ?? []).filter((childId) => !ancestors.has(childId) && childId !== nodeId)
+ );
+
const subtreeHeights = new Map<string, number>();
- const measureSubtree = (nodeId: string, ancestors: Set<string>): number => {
+ const measureSubtreeHeight = (nodeId: string, ancestors: Set<string>): number => {
const cached = subtreeHeights.get(nodeId);
if (cached !== undefined) return cached;
const node = nodeById.get(nodeId);
if (!node || ancestors.has(nodeId)) return 0;
const nextAncestors = new Set(ancestors).add(nodeId);
- const childHeights = (childrenByParent.get(nodeId) ?? [])
- .map((childId) => measureSubtree(childId, nextAncestors))
+ const childHeights = childIdsOf(nodeId, nextAncestors)
+ .map((childId) => measureSubtreeHeight(childId, nextAncestors))
.filter((height) => height > 0);
const childrenHeight = childHeights.reduce((total, height) => total + height, 0)
+ Math.max(0, childHeights.length - 1) * MIND_MAP_VERTICAL_GAP;
@@ -168,78 +183,262 @@ const computeMindMapLayout = (
const positions: DiagramLayoutPositions = Object.fromEntries(
document.nodes.map((node) => [node.id, { x: node.x, y: node.y }]),
);
- const placeChildren = (
+
+ const placeBranchChildren = (
nodeId: string,
subtreeTop: number,
ancestors: Set<string>,
direction: 1 | -1,
+ horizontalGap: number,
+ align: "center" | "start",
) => {
const node = nodeById.get(nodeId);
if (!node || ancestors.has(nodeId)) return;
const nextAncestors = new Set(ancestors).add(nodeId);
- const childIds = (childrenByParent.get(nodeId) ?? []).filter((childId) => !nextAncestors.has(childId));
- const childHeights = childIds.map((childId) => measureSubtree(childId, nextAncestors));
+ const childIds = childIdsOf(nodeId, nextAncestors);
+ const childHeights = childIds.map((childId) => measureSubtreeHeight(childId, nextAncestors));
const childrenHeight = childHeights.reduce((total, height) => total + height, 0)
+ Math.max(0, childHeights.length - 1) * MIND_MAP_VERTICAL_GAP;
- let cursor = subtreeTop + (measureSubtree(nodeId, ancestors) - childrenHeight) / 2;
+ let cursor = align === "start"
+ ? positions[nodeId].y
+ : subtreeTop + (measureSubtreeHeight(nodeId, ancestors) - childrenHeight) / 2;
for (let index = 0; index < childIds.length; index += 1) {
const childId = childIds[index];
const child = nodeById.get(childId)!;
const childSubtreeHeight = childHeights[index];
positions[childId] = {
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),
+ ? positions[nodeId].x + node.width + horizontalGap
+ : positions[nodeId].x - horizontalGap - child.width,
+ y: Math.round(align === "start" ? cursor : cursor + (childSubtreeHeight - child.height) / 2),
};
- placeChildren(childId, cursor, nextAncestors, direction);
+ placeBranchChildren(childId, cursor, nextAncestors, direction, horizontalGap, align);
cursor += childSubtreeHeight + MIND_MAP_VERTICAL_GAP;
}
};
- const placeRootSide = (rootId: string, childIds: string[], direction: 1 | -1) => {
+ const placeRootSide = (
+ rootId: string,
+ childIds: string[],
+ direction: 1 | -1,
+ horizontalGap: number,
+ align: "center" | "start",
+ ) => {
const root = nodeById.get(rootId);
if (!root || childIds.length === 0) return;
- const childHeights = childIds.map((childId) => measureSubtree(childId, new Set([rootId])));
+ const childHeights = childIds.map((childId) => measureSubtreeHeight(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;
+ let cursor = align === "start"
+ ? root.y
+ : 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),
+ ? root.x + root.width + horizontalGap
+ : root.x - horizontalGap - child.width,
+ y: Math.round(align === "start" ? cursor : cursor + (childSubtreeHeight - child.height) / 2),
};
- placeChildren(child.id, cursor, new Set([rootId]), direction);
+ placeBranchChildren(child.id, cursor, new Set([rootId]), direction, horizontalGap, align);
cursor += childSubtreeHeight + MIND_MAP_VERTICAL_GAP;
}
};
- const roots = document.nodes
- .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 childIds = (childrenByParent.get(root.id) ?? []).filter((childId) => childId !== root.id);
- if (childIds.length < MIND_MAP_TWO_SIDED_THRESHOLD || mindMapIsOneSided(document.structure)) {
- placeRootSide(root.id, childIds, 1);
- continue;
+ const layoutBranchMap = (oneSided: boolean, horizontalGap: number, align: "center" | "start") => {
+ const roots = document.nodes
+ .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 childIds = childIdsOf(root.id, new Set([root.id]));
+ if (oneSided || childIds.length < MIND_MAP_TWO_SIDED_THRESHOLD) {
+ placeRootSide(root.id, childIds, 1, horizontalGap, align);
+ 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 += measureSubtreeHeight(childId, new Set([root.id])) + MIND_MAP_VERTICAL_GAP;
+ }
+ placeRootSide(root.id, sides.left.ids, -1, horizontalGap, align);
+ placeRootSide(root.id, sides.right.ids, 1, horizontalGap, align);
}
- const sides: Record<"left" | "right", { ids: string[]; height: number }> = {
- left: { ids: [], height: 0 },
- right: { ids: [], height: 0 },
+ return positions;
+ };
+
+ const subtreeWidths = new Map<string, number>();
+ const measureSubtreeWidth = (nodeId: string, ancestors: Set<string>): number => {
+ const cached = subtreeWidths.get(nodeId);
+ if (cached !== undefined) return cached;
+ const node = nodeById.get(nodeId);
+ if (!node || ancestors.has(nodeId)) return 0;
+ const nextAncestors = new Set(ancestors).add(nodeId);
+ const childWidths = childIdsOf(nodeId, nextAncestors).map((childId) => measureSubtreeWidth(childId, nextAncestors));
+ const childrenWidth = childWidths.reduce((total, width) => total + width, 0)
+ + Math.max(0, childWidths.length - 1) * ORG_NODE_GAP;
+ const width = Math.max(node.width, childrenWidth);
+ subtreeWidths.set(nodeId, width);
+ return width;
+ };
+
+ const layoutOrgChart = () => {
+ const placeOrgChildren = (nodeId: string, ancestors: Set<string>) => {
+ const node = nodeById.get(nodeId);
+ if (!node) return;
+ const nextAncestors = new Set(ancestors).add(nodeId);
+ const childIds = childIdsOf(nodeId, nextAncestors);
+ if (childIds.length === 0) return;
+ const childWidths = childIds.map((childId) => measureSubtreeWidth(childId, nextAncestors));
+ const totalWidth = childWidths.reduce((total, width) => total + width, 0)
+ + Math.max(0, childWidths.length - 1) * ORG_NODE_GAP;
+ const parent = positions[nodeId];
+ let cursor = parent.x + node.width / 2 - totalWidth / 2;
+ const childY = parent.y + node.height + ORG_RANK_GAP;
+ for (let index = 0; index < childIds.length; index += 1) {
+ const child = nodeById.get(childIds[index])!;
+ positions[child.id] = {
+ x: Math.round(cursor + (childWidths[index] - child.width) / 2),
+ y: Math.round(childY),
+ };
+ placeOrgChildren(child.id, nextAncestors);
+ cursor += childWidths[index] + ORG_NODE_GAP;
+ }
};
- 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;
+ for (const root of document.nodes.filter((node) => !node.parentId || !nodeById.has(node.parentId))) {
+ placeOrgChildren(root.id, new Set([root.id]));
}
- placeRootSide(root.id, sides.left.ids, -1);
- placeRootSide(root.id, sides.right.ids, 1);
- }
- return positions;
+ return positions;
+ };
+
+ const layoutTimeline = () => {
+ const placeAway = (
+ parentId: string,
+ startY: number,
+ direction: 1 | -1,
+ x: number,
+ ancestors: Set<string>,
+ ): number => {
+ const nextAncestors = new Set(ancestors).add(parentId);
+ const childIds = childIdsOf(parentId, nextAncestors);
+ let cursor = startY;
+ let far = startY;
+ for (const childId of childIds) {
+ const child = nodeById.get(childId)!;
+ if (direction === 1) {
+ positions[childId] = { x: Math.round(x), y: Math.round(cursor) };
+ const nestedFar = placeAway(
+ childId,
+ positions[childId].y + child.height + MIND_MAP_VERTICAL_GAP,
+ 1,
+ x + TIMELINE_NEST_INDENT,
+ nextAncestors,
+ );
+ cursor = Math.max(positions[childId].y + child.height, nestedFar) + MIND_MAP_VERTICAL_GAP;
+ far = cursor;
+ } else {
+ positions[childId] = { x: Math.round(x), y: Math.round(cursor - child.height) };
+ const nestedFar = placeAway(
+ childId,
+ positions[childId].y - MIND_MAP_VERTICAL_GAP,
+ -1,
+ x + TIMELINE_NEST_INDENT,
+ nextAncestors,
+ );
+ cursor = Math.min(positions[childId].y, nestedFar) - MIND_MAP_VERTICAL_GAP;
+ far = cursor;
+ }
+ }
+ return far;
+ };
+ for (const root of document.nodes.filter((node) => !node.parentId || !nodeById.has(node.parentId))) {
+ const spineY = root.y + root.height / 2;
+ const childIds = childIdsOf(root.id, new Set([root.id]));
+ let cursorX = root.x + root.width + TIMELINE_COLUMN_GAP;
+ for (let index = 0; index < childIds.length; index += 1) {
+ const child = nodeById.get(childIds[index])!;
+ const above = index % 2 === 0;
+ positions[child.id] = {
+ x: Math.round(cursorX),
+ y: Math.round(above ? spineY - TIMELINE_SPINE_GAP - child.height : spineY + TIMELINE_SPINE_GAP),
+ };
+ if (above) {
+ placeAway(child.id, positions[child.id].y - MIND_MAP_VERTICAL_GAP, -1, cursorX + TIMELINE_NEST_INDENT, new Set([root.id, child.id]));
+ } else {
+ placeAway(child.id, positions[child.id].y + child.height + MIND_MAP_VERTICAL_GAP, 1, cursorX + TIMELINE_NEST_INDENT, new Set([root.id, child.id]));
+ }
+ const nested = childIdsOf(child.id, new Set([root.id, child.id])).length > 0;
+ cursorX += child.width + (nested ? TIMELINE_NEST_INDENT : 0) + TIMELINE_COLUMN_GAP;
+ }
+ }
+ return positions;
+ };
+
+ const layoutFishbone = () => {
+ const placeBoneChildren = (parentId: string, above: boolean, ancestors: Set<string>): number => {
+ const parent = nodeById.get(parentId);
+ if (!parent) return positions[parentId]?.y ?? 0;
+ const nextAncestors = new Set(ancestors).add(parentId);
+ const childIds = childIdsOf(parentId, nextAncestors);
+ let cursor = above
+ ? positions[parentId].y - MIND_MAP_VERTICAL_GAP
+ : positions[parentId].y + parent.height + MIND_MAP_VERTICAL_GAP;
+ let far = above ? positions[parentId].y : positions[parentId].y + parent.height;
+ for (const childId of childIds) {
+ const child = nodeById.get(childId)!;
+ positions[childId] = {
+ x: Math.round(positions[parentId].x - FISHBONE_NEST_INDENT),
+ y: Math.round(above ? cursor - child.height : cursor),
+ };
+ const childFar = placeBoneChildren(childId, above, nextAncestors);
+ if (above) {
+ cursor = childFar - MIND_MAP_VERTICAL_GAP;
+ far = Math.min(far, childFar);
+ } else {
+ cursor = childFar + MIND_MAP_VERTICAL_GAP;
+ far = Math.max(far, childFar);
+ }
+ }
+ return far;
+ };
+ for (const root of document.nodes.filter((node) => !node.parentId || !nodeById.has(node.parentId))) {
+ const spineY = root.y + root.height / 2;
+ const childIds = childIdsOf(root.id, new Set([root.id]));
+ let cursorX = root.x - FISHBONE_COLUMN_GAP;
+ for (let index = 0; index < childIds.length; index += 2) {
+ const aboveNode = nodeById.get(childIds[index])!;
+ const belowNode = childIds[index + 1] ? nodeById.get(childIds[index + 1]) : undefined;
+ const columnWidth = Math.max(aboveNode.width, belowNode?.width ?? 0) + FISHBONE_NEST_INDENT;
+ cursorX -= columnWidth;
+ positions[aboveNode.id] = {
+ x: Math.round(cursorX + (columnWidth - aboveNode.width) / 2),
+ y: Math.round(spineY - FISHBONE_SPINE_GAP - aboveNode.height),
+ };
+ placeBoneChildren(aboveNode.id, true, new Set([root.id, aboveNode.id]));
+ if (belowNode) {
+ positions[belowNode.id] = {
+ x: Math.round(cursorX + (columnWidth - belowNode.width) / 2),
+ y: Math.round(spineY + FISHBONE_SPINE_GAP),
+ };
+ placeBoneChildren(belowNode.id, false, new Set([root.id, belowNode.id]));
+ }
+ cursorX -= FISHBONE_COLUMN_GAP;
+ }
+ }
+ return positions;
+ };
+
+ const family = mindMapLayoutFamily(document.structure);
+ if (family === "org") return layoutOrgChart();
+ if (family === "timeline") return layoutTimeline();
+ if (family === "fishbone") return layoutFishbone();
+ if (family === "brace") return layoutBranchMap(true, BRACE_HORIZONTAL_GAP, "center");
+ if (family === "tree") return layoutBranchMap(true, TREE_HORIZONTAL_GAP, "start");
+ return layoutBranchMap(mindMapIsOneSided(document.structure), MIND_MAP_HORIZONTAL_GAP, "center");
};
const wrapArchitectureGroups = (
diff --git a/packages/shared/src/diagram-mindmap-style.test.mjs b/packages/shared/src/diagram-mindmap-style.test.mjs
index 6da5c5ed..978679bf 100644
--- a/packages/shared/src/diagram-mindmap-style.test.mjs
+++ b/packages/shared/src/diagram-mindmap-style.test.mjs
@@ -4,15 +4,19 @@ import {
mindMapBranchSides,
mindMapBranchTint,
mindMapBranchTintIndex,
+ mindMapConnector,
mindMapConnectorPath,
+ mindMapEdgeLineAttrs,
mindMapEdgeTerminal,
mindMapEdgeVisual,
+ mindMapLayoutFamily,
mindMapNodePresentation,
mindMapNodeRole,
mindMapNodeVisual,
mindMapRootRadius,
mindMapCloudPath,
mindMapTopicForm,
+ mindMapUsesRibbon,
mindMapUsesUnderline,
resolveMindMapNodeStyle,
MIND_MAP_CONNECTOR_NAME,
@@ -128,4 +132,48 @@ describe("mind map presentation", () => {
expect(path).toContain("L 0.00 -2.00");
expect(path).toContain("L 80.00 0.50");
});
+
+ test("uses stroke connectors and distinct anchors for org, tree, brace, timeline, and fishbone", () => {
+ expect(mindMapLayoutFamily("org")).toBe("org");
+ expect(mindMapUsesRibbon("map")).toBe(true);
+ expect(mindMapUsesRibbon("org")).toBe(false);
+ expect(mindMapUsesRibbon("fishbone")).toBe(false);
+ expect(mindMapEdgeLineAttrs("org", "#16A06E").fill).toBe("none");
+ expect(mindMapEdgeLineAttrs("map", "#16A06E").fill).toBe("#16A06E");
+ expect(mindMapBranchSides(
+ { x: 0, y: 0, width: 120, height: 46 },
+ { x: 40, y: 80, width: 96, height: 36 },
+ "org",
+ )).toEqual({ source: "bottom", target: "top" });
+ expect(mindMapConnector(
+ { x: 60, y: 46 },
+ { x: 88, y: 102 },
+ [],
+ { structure: "org" },
+ )).toContain("L 60.00 74.00");
+ expect(mindMapConnector(
+ { x: 20, y: 20 },
+ { x: 80, y: 60 },
+ [],
+ { structure: "tree" },
+ )).toContain("L 42.80 20.00");
+ expect(mindMapConnector(
+ { x: 20, y: 40 },
+ { x: 90, y: 10 },
+ [],
+ { structure: "brace", braceTop: 10, braceBottom: 70 },
+ )).not.toContain(" Z");
+ expect(mindMapConnector(
+ { x: 20, y: 40 },
+ { x: 80, y: 10 },
+ [],
+ { structure: "timeline" },
+ )).toBe("M 20.00 40.00 L 80.00 40.00 L 80.00 10.00");
+ expect(mindMapConnector(
+ { x: 200, y: 40 },
+ { x: 80, y: 10 },
+ [],
+ { structure: "fishbone" },
+ )).toContain("L 80.00 10.00");
+ });
});
diff --git a/packages/shared/src/diagram-mindmap-style.ts b/packages/shared/src/diagram-mindmap-style.ts
index de953d27..72e4f1ee 100644
--- a/packages/shared/src/diagram-mindmap-style.ts
+++ b/packages/shared/src/diagram-mindmap-style.ts
@@ -50,14 +50,39 @@ export type MindMapTopicForm =
| "cloud"
| "underline";
-export const mindMapIsOneSided = (structure?: DiagramStructure) => (
- structure === "logic" || structure === "tree" || structure === "brace"
-);
+export type MindMapLayoutFamily = "map" | "logic" | "brace" | "org" | "tree" | "timeline" | "fishbone";
+export type MindMapSide = "left" | "right" | "top" | "bottom";
+
+export const mindMapLayoutFamily = (structure?: DiagramStructure): MindMapLayoutFamily => {
+ if (structure === "logic") return "logic";
+ if (structure === "brace") return "brace";
+ if (structure === "org") return "org";
+ if (structure === "tree") return "tree";
+ if (structure === "timeline") return "timeline";
+ if (structure === "fishbone") return "fishbone";
+ return "map";
+};
+
+export const mindMapIsOneSided = (structure?: DiagramStructure) => {
+ const family = mindMapLayoutFamily(structure);
+ return family === "logic" || family === "tree" || family === "brace";
+};
+
+export const mindMapUsesRibbon = (structure?: DiagramStructure) => {
+ const family = mindMapLayoutFamily(structure);
+ return family === "map" || family === "logic";
+};
export const mindMapUsesUnderline = (role: MindMapRole, structure?: DiagramStructure) => {
if (role === "root") return false;
if (structure === "line" || structure === "brace") return true;
- if (structure === "map" || structure === "tree" || !structure) return role === "nested";
+ if (
+ structure === "map"
+ || structure === "tree"
+ || structure === "timeline"
+ || structure === "fishbone"
+ || !structure
+ ) return role === "nested";
return false;
};
@@ -67,7 +92,7 @@ export const mindMapTopicForm = (structure?: DiagramStructure, role: MindMapRole
if (structure === "ellipse") return "ellipse";
if (structure === "circle") return "circle";
if (structure === "hexagon") return "hexagon";
- if (structure === "box" || structure === "logic") return "rounded";
+ if (structure === "box" || structure === "logic" || structure === "org") return "rounded";
if (role === "root") return "capsule";
return "rounded";
};
@@ -343,26 +368,67 @@ export const mindMapEdgeVisual = (
return { stroke, sourceWidth: 1.25, targetWidth: 0.9 };
};
-export const mindMapBranchSides = (source: MindMapBox, target: MindMapBox) => {
+export const mindMapBranchSides = (
+ source: MindMapBox,
+ target: MindMapBox,
+ structure?: DiagramStructure,
+): { source: MindMapSide; target: MindMapSide } => {
+ const family = mindMapLayoutFamily(structure);
const sourceCenter = source.x + source.width / 2;
const targetCenter = target.x + target.width / 2;
+ const sourceMid = source.y + source.height / 2;
+ const targetMid = target.y + target.height / 2;
+ if (family === "org") return { source: "bottom", target: "top" };
+ if (family === "fishbone") {
+ if (targetCenter < sourceCenter - 8) return { source: "left", target: "right" };
+ if (targetMid < sourceMid - 8) return { source: "top", target: "bottom" };
+ if (targetMid > sourceMid + 8) return { source: "bottom", target: "top" };
+ return { source: "left", target: "right" };
+ }
+ if (family === "timeline") {
+ if (targetMid < sourceMid - 8) return { source: targetCenter >= sourceCenter ? "right" : "left", target: "bottom" };
+ if (targetMid > sourceMid + 8) return { source: targetCenter >= sourceCenter ? "right" : "left", target: "top" };
+ return targetCenter >= sourceCenter
+ ? { source: "right", target: "left" }
+ : { source: "left", target: "right" };
+ }
return targetCenter >= sourceCenter
- ? { source: "right" as const, target: "left" as const }
- : { source: "left" as const, target: "right" as const };
+ ? { source: "right", target: "left" }
+ : { source: "left", target: "right" };
};
export const mindMapEdgeTerminal = (
box: MindMapBox,
role: MindMapRole,
- side: "left" | "right",
+ side: MindMapSide,
structure?: DiagramStructure,
-) => ({
- anchor: {
- name: side,
- ...(mindMapUsesUnderline(role, structure) ? { args: { dy: box.height / 2 - 2 } } : {}),
- },
- connectionPoint: { name: mindMapUsesUnderline(role, structure) ? "anchor" : "boundary" },
-});
+) => {
+ const underline = mindMapUsesUnderline(role, structure);
+ const dy = underline && (side === "left" || side === "right") ? box.height / 2 - 2 : 0;
+ return {
+ anchor: {
+ name: side,
+ ...(dy ? { args: { dy } } : {}),
+ },
+ connectionPoint: { name: underline ? "anchor" : "boundary" },
+ };
+};
+
+export const mindMapSiblingSpan = (
+ nodes: Array<{ id: string; parentId?: string; y: number; height: number }>,
+ parentId: string,
+) => {
+ const children = nodes.filter((node) => node.parentId === parentId);
+ if (children.length === 0) return null;
+ const centers = children.map((node) => node.y + node.height / 2);
+ return { top: Math.min(...centers), bottom: Math.max(...centers) };
+};
+
+export const mindMapEdgeLineAttrs = (structure: DiagramStructure | undefined, stroke: string) => (
+ mindMapUsesRibbon(structure)
+ ? { fill: stroke, strokeWidth: 0.5, strokeLinejoin: "round" as const, strokeLinecap: "round" as const }
+ : { fill: "none", strokeWidth: 1.7, strokeLinejoin: "round" as const, strokeLinecap: "round" as const }
+);
const cubicPoint = (p0: MindMapPoint, p1: MindMapPoint, p2: MindMapPoint, p3: MindMapPoint, t: number) => {
const u = 1 - t;
@@ -422,14 +488,107 @@ export const mindMapConnectorPath = (
return commands.join(" ");
};
+const strokePoint = (point: MindMapPoint) => `${formatPoint(point.x)} ${formatPoint(point.y)}`;
+
+const strokePolyline = (points: MindMapPoint[]) => (
+ points.map((point, index) => `${index === 0 ? "M" : "L"} ${strokePoint(point)}`).join(" ")
+);
+
+const orthConnectorPath = (sourcePoint: MindMapPoint, targetPoint: MindMapPoint, axis: "x" | "y") => {
+ if (Math.abs(sourcePoint.x - targetPoint.x) < 0.8 || Math.abs(sourcePoint.y - targetPoint.y) < 0.8) {
+ return strokePolyline([sourcePoint, targetPoint]);
+ }
+ const mid = axis === "y"
+ ? { x: sourcePoint.x, y: (sourcePoint.y + targetPoint.y) / 2 }
+ : { x: (sourcePoint.x + targetPoint.x) / 2, y: sourcePoint.y };
+ const joint = axis === "y"
+ ? { x: targetPoint.x, y: mid.y }
+ : { x: mid.x, y: targetPoint.y };
+ return strokePolyline([sourcePoint, mid, joint, targetPoint]);
+};
+
+const hangingTreeConnectorPath = (sourcePoint: MindMapPoint, targetPoint: MindMapPoint) => {
+ const busX = sourcePoint.x + Math.max(10, Math.min(28, Math.abs(targetPoint.x - sourcePoint.x) * 0.38));
+ if (Math.abs(sourcePoint.y - targetPoint.y) < 0.8) return strokePolyline([sourcePoint, targetPoint]);
+ return strokePolyline([
+ sourcePoint,
+ { x: busX, y: sourcePoint.y },
+ { x: busX, y: targetPoint.y },
+ targetPoint,
+ ]);
+};
+
+const braceConnectorPath = (
+ sourcePoint: MindMapPoint,
+ targetPoint: MindMapPoint,
+ braceTop?: number,
+ braceBottom?: number,
+) => {
+ const top = Math.min(braceTop ?? sourcePoint.y, braceBottom ?? sourcePoint.y, sourcePoint.y, targetPoint.y);
+ const bottom = Math.max(braceTop ?? sourcePoint.y, braceBottom ?? sourcePoint.y, sourcePoint.y, targetPoint.y);
+ const span = Math.max(18, bottom - top);
+ const startY = (top + bottom) / 2 - span / 2;
+ const endY = startY + span;
+ const midY = (startY + endY) / 2;
+ const depth = 9;
+ const column = sourcePoint.x + Math.max(18, Math.min(36, Math.abs(targetPoint.x - sourcePoint.x) * 0.42));
+ return [
+ strokePolyline([sourcePoint, { x: column - depth, y: sourcePoint.y }]),
+ `M ${formatPoint(column - depth)} ${formatPoint(startY)}`,
+ `C ${formatPoint(column)} ${formatPoint(startY)} ${formatPoint(column)} ${formatPoint(startY)} ${formatPoint(column)} ${formatPoint((startY + midY) / 2)}`,
+ `C ${formatPoint(column)} ${formatPoint(midY)} ${formatPoint(column + depth)} ${formatPoint(midY)} ${formatPoint(column + depth)} ${formatPoint(midY)}`,
+ `C ${formatPoint(column)} ${formatPoint(midY)} ${formatPoint(column)} ${formatPoint(midY)} ${formatPoint(column)} ${formatPoint((midY + endY) / 2)}`,
+ `C ${formatPoint(column)} ${formatPoint(endY)} ${formatPoint(column)} ${formatPoint(endY)} ${formatPoint(column - depth)} ${formatPoint(endY)}`,
+ strokePolyline([{ x: column, y: targetPoint.y }, targetPoint]),
+ ].join(" ");
+};
+
+const timelineConnectorPath = (sourcePoint: MindMapPoint, targetPoint: MindMapPoint) => {
+ if (Math.abs(sourcePoint.x - targetPoint.x) < 0.8 || Math.abs(sourcePoint.y - targetPoint.y) < 0.8) {
+ return strokePolyline([sourcePoint, targetPoint]);
+ }
+ return strokePolyline([sourcePoint, { x: targetPoint.x, y: sourcePoint.y }, targetPoint]);
+};
+
+const fishboneConnectorPath = (sourcePoint: MindMapPoint, targetPoint: MindMapPoint) => {
+ if (Math.abs(sourcePoint.y - targetPoint.y) < 0.8 || Math.abs(sourcePoint.x - targetPoint.x) < 0.8) {
+ return strokePolyline([sourcePoint, targetPoint]);
+ }
+ const rise = Math.abs(targetPoint.y - sourcePoint.y);
+ const towardHead = sourcePoint.x >= targetPoint.x ? 1 : -1;
+ const joinX = targetPoint.x + towardHead * Math.max(18, rise / Math.sqrt(3));
+ const spineJoin = {
+ x: towardHead > 0 ? Math.min(sourcePoint.x, joinX) : Math.max(sourcePoint.x, joinX),
+ y: sourcePoint.y,
+ };
+ return strokePolyline([sourcePoint, spineJoin, targetPoint]);
+};
+
+export type MindMapConnectorOptions = {
+ sourceWidth?: number;
+ targetWidth?: number;
+ raw?: boolean;
+ structure?: DiagramStructure;
+ braceTop?: number;
+ braceBottom?: number;
+};
+
export const mindMapConnector = (
sourcePoint: MindMapPoint,
targetPoint: MindMapPoint,
_routePoints?: MindMapPoint[],
- options: { sourceWidth?: number; targetWidth?: number; raw?: boolean } = {},
-) => mindMapConnectorPath(
- sourcePoint,
- targetPoint,
- options.sourceWidth,
- options.targetWidth,
-);
+ options: MindMapConnectorOptions = {},
+) => {
+ const family = mindMapLayoutFamily(options.structure);
+ if (family === "org") return orthConnectorPath(sourcePoint, targetPoint, "y");
+ if (family === "tree") return hangingTreeConnectorPath(sourcePoint, targetPoint);
+ if (family === "brace") return braceConnectorPath(sourcePoint, targetPoint, options.braceTop, options.braceBottom);
+ if (family === "timeline") return timelineConnectorPath(sourcePoint, targetPoint);
+ if (family === "fishbone") return fishboneConnectorPath(sourcePoint, targetPoint);
+ return mindMapConnectorPath(
+ sourcePoint,
+ targetPoint,
+ options.sourceWidth,
+ options.targetWidth,
+ );
+};
diff --git a/packages/shared/src/diagram-view.ts b/packages/shared/src/diagram-view.ts
index dc785b06..923cbdb6 100644
--- a/packages/shared/src/diagram-view.ts
+++ b/packages/shared/src/diagram-view.ts
@@ -17,10 +17,12 @@ import { buildDiagramPalette } from "./diagram-palette";
import {
MIND_MAP_CONNECTOR_NAME,
mindMapBranchSides,
+ mindMapEdgeLineAttrs,
mindMapEdgeTerminal,
mindMapEdgeVisual,
mindMapNodePresentation,
mindMapNodeRole,
+ mindMapSiblingSpan,
mindMapTopicMarkup,
resolveMindMapNodeStyle,
} from "./diagram-mindmap-style";
@@ -50,7 +52,7 @@ export const diagramDocumentToX6Cells = (
appearance: DiagramAppearance,
) => {
const palette = resolvePortableDiagramPalette(document.theme ?? "brand", appearance);
- const flowchartSurface = document.kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
+ const flowchartSurface = document.kind === "flowchart" ? resolveFlowchartSurface(appearance, document.theme) : null;
const architectureSurface = document.kind === "architecture" ? resolveArchitectureSurface(appearance) : null;
const nodes = document.nodes.map((node) => {
const mindMapRole = document.kind === "mind-map" ? mindMapNodeRole(document.nodes, node.id) : null;
@@ -64,7 +66,7 @@ export const diagramDocumentToX6Cells = (
: null;
const mindVisual = mindStyle?.visual ?? null;
const flowchartVisual = document.kind === "flowchart"
- ? flowchartNodeVisual(node.shape, appearance, presentation)
+ ? flowchartNodeVisual(node.shape, appearance, presentation, document.theme)
: null;
const architectureVisual = document.kind === "architecture"
? architectureNodeVisual(node.shape, appearance, presentation, node.resourceIcon)
@@ -145,7 +147,7 @@ export const diagramDocumentToX6Cells = (
: undefined;
const mindEdge = mindMapSourceRole ? mindMapEdgeVisual(mindMapSourceRole, palette, branchTint) : null;
const sides = sourceNode && targetNode
- ? mindMapBranchSides(sourceNode, targetNode)
+ ? mindMapBranchSides(sourceNode, targetNode, document.structure)
: { source: "right" as const, target: "left" as const };
const sourceTerminal = sourceNode && mindMapSourceRole
? mindMapEdgeTerminal(sourceNode, mindMapSourceRole, sides.source, document.structure)
@@ -153,6 +155,9 @@ export const diagramDocumentToX6Cells = (
const targetTerminal = targetNode && mindMapTargetRole
? mindMapEdgeTerminal(targetNode, mindMapTargetRole, sides.target, document.structure)
: null;
+ const braceSpan = document.kind === "mind-map" && document.structure === "brace"
+ ? mindMapSiblingSpan(document.nodes, edge.source)
+ : null;
const architectureEdge = document.kind === "architecture"
? architectureEdgeVisual(edgeKind, appearance, edge.bidirectional)
: null;
@@ -180,21 +185,25 @@ export const diagramDocumentToX6Cells = (
? (flowchartStraight ? { name: "normal" } : FLOWCHART_EDGE_ROUTER)
: undefined,
connector: document.kind === "mind-map"
- ? { name: MIND_MAP_CONNECTOR_NAME, args: { sourceWidth: mindEdge?.sourceWidth, targetWidth: mindEdge?.targetWidth } }
+ ? {
+ name: MIND_MAP_CONNECTOR_NAME,
+ args: {
+ sourceWidth: mindEdge?.sourceWidth,
+ targetWidth: mindEdge?.targetWidth,
+ structure: document.structure,
+ ...(braceSpan ? { braceTop: braceSpan.top, braceBottom: braceSpan.bottom } : {}),
+ },
+ }
: { name: "rounded", args: { radius: 10 } },
attrs: { line: {
stroke,
- strokeWidth: architectureEdge?.strokeWidth ?? (mindEdge ? 0.5 : 1.5),
+ strokeWidth: architectureEdge?.strokeWidth ?? (mindEdge ? mindMapEdgeLineAttrs(document.structure, stroke).strokeWidth : 1.5),
strokeDasharray: architectureEdge?.strokeDasharray,
sourceMarker: architectureEdge
? architectureEdge.sourceMarker
: edge.bidirectional ? { name: "block", width: 8, height: 6 } : null,
targetMarker: document.kind === "mind-map" ? null : architectureEdge?.targetMarker ?? { name: "block", width: 8, height: 6 },
- ...(mindEdge ? {
- fill: stroke,
- strokeLinejoin: "round",
- strokeLinecap: "round",
- } : { fill: "none" }),
+ ...(mindEdge ? mindMapEdgeLineAttrs(document.structure, stroke) : { fill: "none" }),
} },
labels: edge.label ? [{ attrs: {
label: {
diff --git a/packages/shared/src/diagram.test.mjs b/packages/shared/src/diagram.test.mjs
index 7e0d367a..2944842c 100644
--- a/packages/shared/src/diagram.test.mjs
+++ b/packages/shared/src/diagram.test.mjs
@@ -12,12 +12,15 @@ describe("diagram document", () => {
expect(parseDiagramDocument(serializeDiagramDocument(document))).toEqual(document);
});
- test("offers ten mind-map shapes and ten selectable color schemes", () => {
- expect(DIAGRAM_SELECTABLE_STRUCTURES).toHaveLength(10);
+ test("offers selectable mind-map layouts and ten color schemes", () => {
+ expect(DIAGRAM_SELECTABLE_STRUCTURES).toEqual([
+ "map", "line", "capsule", "box", "circle", "ellipse", "hexagon",
+ "logic", "tree", "brace", "org", "timeline", "fishbone",
+ ]);
expect(DIAGRAM_SELECTABLE_THEMES).toHaveLength(10);
const document = createDefaultDiagramDocument("mind-map");
document.theme = "mint";
- document.structure = "logic";
+ document.structure = "fishbone";
expect(parseDiagramDocument(serializeDiagramDocument(document))).toEqual(document);
const unknown = structuredClone(document);
unknown.theme = "not-a-theme";
@@ -71,10 +74,30 @@ describe("diagram document", () => {
expect(markdown).toContain("class n1 flowProcess");
expect(markdown).toContain("class n0 flowTerminator");
+ const paper = createDefaultDiagramDocument("flowchart");
+ paper.theme = "paper";
+ expect(diagramDocumentToMermaid(paper)).toContain("classDef flowTerminator fill:#F0E4D0,stroke:#7A5230");
+ const mint = createDefaultDiagramDocument("flowchart");
+ mint.theme = "mint";
+ expect(diagramDocumentToMermaid(mint)).toContain("classDef flowProcess fill:#FFFFFF,stroke:#6F9B88");
+
const doc = markdownToDoc(markdown);
expect(doc.content?.some((node) => node.type === "codeBlock" && node.attrs?.language === "mermaid")).toBe(true);
});
+ test("persists flowchart paper and ink surfaces in the native projection", () => {
+ const document = createDefaultDiagramDocument("flowchart");
+ document.theme = "paper";
+ expect(parseDiagramDocument(serializeDiagramDocument(document))?.theme).toBe("paper");
+ const paper = diagramDocumentToX6Cells(document, "light");
+ expect(paper.canvas).toBe("#F6F1E8");
+ expect(paper.nodes.find((node) => node.id === "flow-start").attrs.body.stroke).toBe("#7A5230");
+ document.theme = "ink";
+ const ink = diagramDocumentToX6Cells(document, "light");
+ expect(ink.canvas).toBe("#F3F5F7");
+ expect(ink.nodes.find((node) => node.id === "flow-start").attrs.body.stroke).toBe("#3A4656");
+ });
+
test("projects native viewers into the same branded X6 palette", () => {
const document = createDefaultDiagramDocument("mind-map");
const light = diagramDocumentToX6Cells(document, "light");
@@ -93,6 +116,11 @@ describe("diagram document", () => {
const boxed = diagramDocumentToX6Cells({ ...document, structure: "box" }, "light");
expect(boxed.nodes.find((node) => node.id === "topic-1-a").attrs.body.fill).not.toBe("transparent");
expect(boxed.nodes.find((node) => node.id === "topic-1-a").attrs.underline.stroke).toBe("none");
+ const org = diagramDocumentToX6Cells({ ...document, structure: "org" }, "light");
+ expect(org.edges[0].source.anchor.name).toBe("bottom");
+ expect(org.edges[0].target.anchor.name).toBe("top");
+ expect(org.edges[0].attrs.line.fill).toBe("none");
+ expect(org.edges[0].connector.args.structure).toBe("org");
const classic = diagramDocumentToX6Cells({ ...document, theme: "classic" }, "light");
expect(classic.nodes.find((node) => node.id === "topic-1").attrs.body.stroke)
diff --git a/packages/shared/src/diagram.ts b/packages/shared/src/diagram.ts
index 039fa9c8..e83a087c 100644
--- a/packages/shared/src/diagram.ts
+++ b/packages/shared/src/diagram.ts
@@ -4,6 +4,7 @@ import {
architectureMermaidClassDefs,
architectureMermaidClassName,
} from "./diagram-architecture-style";
+import { flowchartMermaidClassDefs, flowchartMermaidClassName } from "./diagram-flowchart-style";
export const DIAGRAM_SCHEMA_VERSION = 1 as const;
export const ARCHITECTURE_DIAGRAM_SCHEMA_VERSION = 2 as const;
@@ -29,12 +30,25 @@ export const DIAGRAM_SELECTABLE_THEMES = [
] as const;
export const DIAGRAM_THEMES = [
"brand", "ocean", "ink", "classic", "sky", "sunset", "violet", "rose", "sand", "slate", "aurora", "mono",
- "sun", "wa", "island", "mint", "cosmos", "tea", "naive", "macaron",
+ "sun", "wa", "island", "mint", "cosmos", "tea", "naive", "macaron", "paper",
] as const;
export type DiagramTheme = (typeof DIAGRAM_THEMES)[number];
export const DIAGRAM_SELECTABLE_STRUCTURES = [
- "map", "line", "capsule", "box", "circle", "ellipse", "hexagon", "logic", "tree", "brace",
+ "map", "line", "capsule", "box", "circle", "ellipse", "hexagon",
+ "logic", "tree", "brace", "org", "timeline", "fishbone",
] as const;
+export const DIAGRAM_STRUCTURE_GROUPS = [
+ { id: "map", items: ["map", "line", "capsule", "box", "circle", "ellipse", "hexagon"] },
+ { id: "logic", items: ["logic"] },
+ { id: "brace", items: ["brace"] },
+ { id: "org", items: ["org"] },
+ { id: "tree", items: ["tree"] },
+ { id: "timeline", items: ["timeline"] },
+ { id: "fishbone", items: ["fishbone"] },
+] as const satisfies ReadonlyArray<{
+ id: string;
+ items: ReadonlyArray<typeof DIAGRAM_SELECTABLE_STRUCTURES[number]>;
+}>;
export const DIAGRAM_STRUCTURES = [
...DIAGRAM_SELECTABLE_STRUCTURES, "rect", "diamond", "cloud",
] as const;
@@ -51,6 +65,7 @@ const THEME_ALIASES: Partial<Record<DiagramTheme, typeof DIAGRAM_SELECTABLE_THEM
slate: "cosmos",
aurora: "mint",
mono: "cosmos",
+ paper: "brand",
};
export const resolveDiagramTheme = (theme?: DiagramTheme): typeof DIAGRAM_SELECTABLE_THEMES[number] => {
@@ -324,8 +339,7 @@ export const diagramDocumentToMermaid = (document: DiagramDocument) => {
: `${id}["${label}"]`;
lines.push(` ${declaration}`);
if (document.kind === "flowchart") {
- const className = node.shape === "decision" ? "flowDecision" : node.shape === "terminator" ? "flowTerminator" : "flowProcess";
- lines.push(` class ${id} ${className}`);
+ lines.push(` class ${id} ${flowchartMermaidClassName(node.shape)}`);
}
}
@@ -339,9 +353,7 @@ export const diagramDocumentToMermaid = (document: DiagramDocument) => {
}
if (document.kind === "flowchart") {
- lines.push(" classDef flowProcess fill:#FFFFFF,stroke:#6F9B88,color:#1C3D31,stroke-width:1.5px");
- lines.push(" classDef flowDecision fill:#FFF6E5,stroke:#D4A24A,color:#7A4A12,stroke-width:1.5px");
- lines.push(" classDef flowTerminator fill:#E7F6EF,stroke:#16A06E,color:#145C40,stroke-width:1.5px");
+ lines.push(...flowchartMermaidClassDefs(document.theme));
}
if (document.kind === "mind-map") {
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index c8991445..0978630d 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -366,6 +366,8 @@ export const enUS = {
themeGroupVivid: "Bright",
themeGroupClassic: "Quiet",
themeBrand: "Forest",
+ themeInk: "Ink",
+ themePaper: "Paper",
themeSun: "Gleam",
themeWa: "Tide",
themeIsland: "Clay",
@@ -378,6 +380,11 @@ export const enUS = {
structure: "Shape",
structureGroupMap: "Mind map",
structureGroupLogic: "Logic chart",
+ structureGroupBrace: "Brace map",
+ structureGroupOrg: "Org chart",
+ structureGroupTree: "Tree chart",
+ structureGroupTimeline: "Timeline",
+ structureGroupFishbone: "Fishbone",
structureLogic: "Logic",
structureMap: "Map",
structureLine: "Line",
@@ -388,6 +395,9 @@ export const enUS = {
structureHexagon: "Hexagon",
structureTree: "Tree",
structureBrace: "Brace",
+ structureOrg: "Org",
+ structureTimeline: "Timeline",
+ structureFishbone: "Fishbone",
export: "Export",
exportPng: "Export PNG",
exportSvg: "Export SVG",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 03e91afb..c867ebc5 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -366,6 +366,8 @@ export const zhCN = {
themeGroupVivid: "鲜亮",
themeGroupClassic: "沉静",
themeBrand: "森绿",
+ themeInk: "墨色",
+ themePaper: "纸色",
themeSun: "晴穗",
themeWa: "潮汐",
themeIsland: "陶岸",
@@ -378,6 +380,11 @@ export const zhCN = {
structure: "形状",
structureGroupMap: "思维导图",
structureGroupLogic: "逻辑图",
+ structureGroupBrace: "括号图",
+ structureGroupOrg: "组织结构图",
+ structureGroupTree: "树形图",
+ structureGroupTimeline: "时间轴",
+ structureGroupFishbone: "鱼骨图",
structureLogic: "逻辑图",
structureMap: "脑图",
structureLine: "线条",
@@ -388,6 +395,9 @@ export const zhCN = {
structureHexagon: "六边",
structureTree: "树图",
structureBrace: "括号",
+ structureOrg: "组织图",
+ structureTimeline: "时间轴",
+ structureFishbone: "鱼骨图",
export: "导出",
exportPng: "导出 PNG",
exportSvg: "导出 SVG",