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 structure gallery and named color strips

tianma-if87a6e64a6d2a
diff --git a/apps/api/src/mcp-tool-service.ts b/apps/api/src/mcp-tool-service.ts
index d5f1dbce..099d0400 100644
--- a/apps/api/src/mcp-tool-service.ts
+++ b/apps/api/src/mcp-tool-service.ts
@@ -276,11 +276,11 @@ 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", "ocean", "ink", "classic"].includes(String(args.theme))) {
- throw new AppError("invalid_params", "theme must be brand, ocean, ink, or classic", 400);
+ if (args.theme !== undefined && !["brand", "sun", "wa", "island", "rose", "mint", "cosmos", "tea", "naive", "macaron", "ocean", "ink", "classic"].includes(String(args.theme))) {
+ throw new AppError("invalid_params", "theme is not a supported diagram color scheme", 400);
}
- if (args.structure !== undefined && !["map", "box"].includes(String(args.structure))) {
- throw new AppError("invalid_params", "structure must be map or box", 400);
+ if (args.structure !== undefined && !["map", "line", "capsule", "box", "circle", "ellipse", "hexagon", "logic", "tree", "brace"].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)) {
throw new AppError("invalid_params", "title must be a string with at most 160 characters", 400);
diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.ts
index 617e8e29..848dcc46 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", "ocean", "ink", "classic"] },
- structure: { type: "string", enum: ["map", "box"] },
+ 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"] },
layout: {
type: "object",
additionalProperties: false,
diff --git a/apps/web/src/components/DiagramEditorPane.test.mjs b/apps/web/src/components/DiagramEditorPane.test.mjs
index 0e5d74aa..162e4a21 100644
--- a/apps/web/src/components/DiagramEditorPane.test.mjs
+++ b/apps/web/src/components/DiagramEditorPane.test.mjs
@@ -150,11 +150,13 @@ describe("diagram editor canvas surface", () => {
});
test("uses restrained rounded edges and fits the complete diagram without clipping", () => {
- expect(toolbarSource).toContain('value="classic"');
- expect(toolbarSource).toContain('t("diagram.themeClassic")');
+ expect(toolbarSource).toContain("DIAGRAM_THEME_GROUPS");
+ expect(toolbarSource).toContain("STRUCTURE_GROUPS");
+ expect(toolbarSource).toContain("diagramThemeSwatches");
+ expect(toolbarSource).toContain("<StructureThumb");
expect(toolbarSource).toContain('t("diagram.structure")');
- expect(toolbarSource).toContain('t("diagram.structureMap")');
- expect(toolbarSource).toContain('t("diagram.structureBox")');
+ expect(toolbarSource).toContain("diagram.structureGroupMap");
+ 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"');
@@ -162,7 +164,9 @@ describe("diagram editor canvas surface", () => {
expect(source).toContain("name: MIND_MAP_CONNECTOR_NAME, args: { sourceWidth: mindEdge?.sourceWidth, targetWidth: mindEdge?.targetWidth }");
expect(source).toContain('{ fill: "none" }');
expect(source).toContain('if (kind !== "mind-map") edge.attr("line/fill", "none")');
- expect(source).toContain('name: "manhattan"');
+ expect(source).toContain("FLOWCHART_EDGE_ROUTER");
+ expect(source).toContain('showTheme={document.kind !== "flowchart"}');
+ expect(toolbarSource).toContain("showTheme = true");
expect(source).toContain("maxScale: policy.maxScale");
expect(source).not.toContain("minScale: policy.minScale");
expect(source).toContain("graph.centerContent()");
diff --git a/apps/web/src/components/DiagramEditorPane.tsx b/apps/web/src/components/DiagramEditorPane.tsx
index a1e85e12..ab3fed28 100644
--- a/apps/web/src/components/DiagramEditorPane.tsx
+++ b/apps/web/src/components/DiagramEditorPane.tsx
@@ -70,7 +70,7 @@ import {
markdownToDoc,
MIND_MAP_CONNECTOR_NAME,
MIND_MAP_HORIZONTAL_GAP,
- MIND_MAP_TOPIC_MARKUP,
+ mindMapTopicMarkup,
MIND_MAP_VERTICAL_GAP,
mindMapBranchSides,
mindMapConnector,
@@ -78,11 +78,14 @@ import {
mindMapEdgeVisual,
mindMapNodePresentation,
mindMapNodeRole,
- mindMapRootRadius,
resolveMindMapNodeStyle,
parseDiagramDocument,
resolveDiagramStructure,
+ resolveDiagramTheme,
serializeDiagramDocument,
+ FLOWCHART_EDGE_ROUTER,
+ flowchartNodeVisual,
+ resolveFlowchartSurface,
type ArchitectureResourceIcon,
type DiagramDocument,
type DiagramEdgeKind,
@@ -535,12 +538,21 @@ const setOnlyFlowNodePortsActive = (graph: Graph, activeNode?: Node) => {
graph.getNodes().forEach((node) => setFlowNodePortsActive(graph, node, node.id === activeNode?.id));
};
+const diagramCanvasColor = (
+ kind: DiagramDocument["kind"],
+ theme: DiagramTheme,
+ appearance: DiagramAppearance,
+) => (kind === "flowchart"
+ ? resolveFlowchartSurface(appearance).canvas
+ : resolveDiagramPalette(theme, appearance).canvas);
+
const applyDiagramSurface = (
graph: Graph,
theme: DiagramTheme,
appearance: DiagramAppearance,
+ kind?: DiagramDocument["kind"],
) => {
- graph.drawBackground({ color: resolveDiagramPalette(theme, appearance).canvas });
+ graph.drawBackground({ color: diagramCanvasColor(kind ?? "mind-map", theme, appearance) });
graph.clearGrid();
};
@@ -740,9 +752,12 @@ const nodeEditorState = (
const mindStyle = mindRole
? 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())
+ : null;
const attrs = mindStyle
? mindStyle.visual
- : nodeAttrs(data?.shape ?? "process", theme, appearance, isRootTopic);
+ : flowchartStyle ?? nodeAttrs(data?.shape ?? "process", theme, appearance, isRootTopic);
return {
nodeId: node.id,
originalValue: data?.label ?? "",
@@ -982,15 +997,18 @@ const nodeMetadata = (
const mindStyle = kind === "mind-map"
? resolveMindMapNodeStyle([node], node.id, palette, theme, appearance, size, structure)
: null;
- const visualAttrs = mindStyle ? mindStyle.visual : nodeAttrs(node.shape, theme, appearance, isRootTopic);
- if (mindStyle?.role === "root") {
- visualAttrs.body.rx = mindMapRootRadius(size.height);
- visualAttrs.body.ry = visualAttrs.body.rx;
- }
+ const flowchartStyle = kind === "flowchart" ? flowchartNodeVisual(node.shape, appearance, size) : null;
+ const visualAttrs = mindStyle
+ ? mindStyle.visual
+ : flowchartStyle ?? nodeAttrs(node.shape, theme, appearance, isRootTopic);
const hasPorts = isConnectableDiagram(kind) && node.shape !== "boundary";
const architectureVisuals = kind === "architecture" && node.shape !== "boundary"
? architectureNodeVisuals(node.shape, size, appearance, node.resourceIcon)
: null;
+ const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
+ const portPalette = flowchartSurface
+ ? { ...palette, canvas: flowchartSurface.canvas, topicStroke: flowchartSurface.terminator.stroke }
+ : palette;
return {
id: node.id,
shape: isDecision ? "polygon" : "rect",
@@ -1005,38 +1023,46 @@ const nodeMetadata = (
...(node.parentId ? { parentId: node.parentId } : {}),
...(node.resourceIcon ? { resourceIcon: node.resourceIcon } : {}),
} satisfies NodeData,
- ...(architectureVisuals ? { markup: architectureVisuals.markup } : mindStyle ? { markup: MIND_MAP_TOPIC_MARKUP } : {}),
+ ...(architectureVisuals ? { markup: architectureVisuals.markup } : mindStyle ? { markup: mindMapTopicMarkup(structure, mindStyle.role) } : {}),
attrs: {
body: visualAttrs.body,
...(mindStyle ? { underline: mindStyle.visual.underline } : {}),
label: {
...visualAttrs.label,
text: diagramNodePresentation(node, kind).text,
- lineHeight: mindStyle?.visual.label.lineHeight ?? 18,
+ lineHeight: mindStyle?.visual.label.lineHeight ?? flowchartStyle?.label.lineHeight ?? 18,
...(architectureVisuals ? { refX: 54, refY: "50%", textAnchor: "start", textVerticalAnchor: "middle" } : {}),
},
...(architectureVisuals?.attrs ?? {}),
},
...(hasPorts ? { ports: {
groups: {
- top: flowPortGroup("top", palette),
- right: flowPortGroup("right", palette),
- bottom: flowPortGroup("bottom", palette),
- left: flowPortGroup("left", palette),
+ top: flowPortGroup("top", portPalette),
+ right: flowPortGroup("right", portPalette),
+ bottom: flowPortGroup("bottom", portPalette),
+ left: flowPortGroup("left", portPalette),
},
items: ["top", "right", "bottom", "left"].map((group) => ({ id: group, group })),
} } : {}),
};
};
-const diagramEdgeLabel = (text: string, palette: ReturnType<typeof resolveDiagramPalette>, kind: DiagramDocument["kind"]) => ({
- position: { distance: 0.5, offset: kind === "architecture" ? { x: 0, y: -16 } : 0 },
- attrs: {
- label: { text, fill: palette.nodeText, fontSize: 12, lineHeight: 16, textWrap: { width: 140, height: 512 } },
- body: { ref: "label", refWidth: 1, refHeight: 1, refWidth2: 12, refHeight2: 8, refX: -6, refY: -4,
- fill: palette.canvas, stroke: palette.nodeStroke, strokeWidth: 1, rx: 4, ry: 4 },
- },
-});
+const diagramEdgeLabel = (
+ text: string,
+ palette: ReturnType<typeof resolveDiagramPalette>,
+ kind: DiagramDocument["kind"],
+ appearance: DiagramAppearance = "light",
+) => {
+ const flowchart = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
+ return {
+ position: { distance: 0.5, offset: kind === "architecture" ? { x: 0, y: -16 } : 0 },
+ attrs: {
+ label: { text, fill: flowchart?.process.text ?? palette.nodeText, fontSize: 12, lineHeight: 16, textWrap: { width: 140, height: 512 } },
+ body: { ref: "label", refWidth: 1, refHeight: 1, refWidth2: 12, refHeight2: 8, refX: -6, refY: -4,
+ fill: flowchart?.canvas ?? palette.canvas, stroke: flowchart?.process.stroke ?? palette.nodeStroke, strokeWidth: 1, rx: 4, ry: 4 },
+ },
+ };
+};
const edgeMetadata = (
edge: DiagramDocument["edges"][number],
@@ -1047,16 +1073,17 @@ const edgeMetadata = (
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 edgeStroke = edgeKind === "data"
? "#7C3AED"
: edgeKind === "async"
? "#EA580C"
- : mindEdge?.stroke ?? palette.flowEdge;
+ : mindEdge?.stroke ?? flowchartSurface?.edge ?? palette.flowEdge;
return {
id: edge.id,
source: { cell: edge.source },
target: { cell: edge.target },
- router: kind === "flowchart" ? { name: "manhattan", args: { padding: 28, step: 10 } } : undefined,
+ router: kind === "flowchart" ? FLOWCHART_EDGE_ROUTER : undefined,
connector: kind === "mind-map"
? { name: MIND_MAP_CONNECTOR_NAME, args: { sourceWidth: mindEdge?.sourceWidth, targetWidth: mindEdge?.targetWidth } }
: { name: "rounded", args: { radius: 10 } },
@@ -1075,7 +1102,7 @@ const edgeMetadata = (
} : { fill: "none" }),
},
},
- labels: edge.label ? [diagramEdgeLabel(edge.label, palette, kind)] : undefined,
+ labels: edge.label ? [diagramEdgeLabel(edge.label, palette, kind, appearance)] : undefined,
};
};
@@ -1180,16 +1207,8 @@ const applyMindMapHierarchy = (graph: Graph, theme: DiagramTheme, appearance: Di
for (const node of graph.getNodes()) {
const size = node.getSize();
const { role, visual } = resolveMindMapNodeStyle(nodes, node.id, palette, theme, appearance, size, structure);
- if (role === "root") {
- visual.body.rx = mindMapRootRadius(size.height);
- visual.body.ry = visual.body.rx;
- }
- node.setMarkup(MIND_MAP_TOPIC_MARKUP);
- node.attr("body/fill", visual.body.fill);
- node.attr("body/stroke", visual.body.stroke);
- node.attr("body/strokeWidth", visual.body.strokeWidth);
- node.attr("body/rx", visual.body.rx);
- node.attr("body/ry", visual.body.ry);
+ node.setMarkup(mindMapTopicMarkup(structure, role));
+ node.attr("body", visual.body);
node.attr("underline", visual.underline);
node.attr("label/fill", visual.label.fill);
node.attr("label/fontSize", visual.label.fontSize);
@@ -1242,7 +1261,8 @@ const applyGraphPalette = (
for (const node of graph.getNodes()) {
const data = node.getData<NodeData>();
const shape = data?.shape ?? "process";
- const attrs = nodeAttrs(shape, theme, appearance, shape === "topic" && !data?.parentId);
+ const flowchartStyle = kind === "flowchart" ? flowchartNodeVisual(shape, appearance, node.getSize()) : null;
+ const attrs = flowchartStyle ?? nodeAttrs(shape, theme, appearance, shape === "topic" && !data?.parentId);
node.attr("body", attrs.body);
node.attr("label", attrs.label);
refreshNodeLabel(node, data?.label ?? "", structure);
@@ -1252,24 +1272,26 @@ const applyGraphPalette = (
node.attr(selector, selectorAttrs);
}
}
+ const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
for (const port of node.getPorts()) {
if (!port.id) continue;
node.portProp(port.id, "attrs/circle", {
- stroke: palette.topicStroke,
- fill: palette.canvas,
+ stroke: flowchartSurface?.terminator.stroke ?? palette.topicStroke,
+ fill: flowchartSurface?.canvas ?? palette.canvas,
});
}
}
+ const flowchartSurface = kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
for (const edge of graph.getEdges()) {
const edgeKind = edge.getData<EdgeData>()?.kind;
- edge.attr("line/stroke", edgeKind === "data" ? "#7C3AED" : edgeKind === "async" ? "#EA580C" : kind === "mind-map" ? palette.mindMapEdge : palette.flowEdge);
+ edge.attr("line/stroke", edgeKind === "data" ? "#7C3AED" : edgeKind === "async" ? "#EA580C" : kind === "mind-map" ? palette.mindMapEdge : flowchartSurface?.edge ?? palette.flowEdge);
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)));
+ edge.setLabels(edge.getLabels().map((label) => diagramEdgeLabel(String(label.attrs?.label?.text ?? ""), palette, kind, appearance)));
}
}
if (kind === "mind-map") applyMindMapHierarchy(graph, theme, appearance, structure);
- applyDiagramSurface(graph, theme, appearance);
+ applyDiagramSurface(graph, theme, appearance, kind);
} finally {
if (historyEnabled) graph.enableHistory();
scroller?.enableAutoResize();
@@ -1305,7 +1327,7 @@ export const DiagramEditorPane = ({
const editSessionRef = useRef<MemoEditSession | null>(null);
const saveRef = useRef<() => void>(() => undefined);
const document = parseDiagramDocument(memo.contentMarkdown);
- const documentTheme = document?.theme ?? "brand";
+ const documentTheme = resolveDiagramTheme(document?.theme);
const documentStructure = resolveDiagramStructure(document?.structure);
const [title, setTitle] = useState(memo.title ?? "");
const [tagsText, setTagsText] = useState(memo.tags.join(", "));
@@ -1547,7 +1569,7 @@ export const DiagramEditorPane = ({
container: containerRef.current,
autoResize: true,
async: true,
- background: { color: palette.canvas },
+ background: { color: diagramCanvasColor(document.kind, documentTheme, appearance) },
grid: false,
panning: false,
mousewheel: { enabled: true, modifiers: ["ctrl", "meta"], minScale: 0.3, maxScale: 2.5 },
@@ -1561,7 +1583,7 @@ export const DiagramEditorPane = ({
allowMulti: false,
highlight: isConnectableDiagram(document.kind),
snap: { radius: 24 },
- router: document.kind === "flowchart" ? { name: "manhattan", args: { padding: 28, step: 10 } } : "normal",
+ router: document.kind === "flowchart" ? FLOWCHART_EDGE_ROUTER : "normal",
connector: document.kind === "mind-map" ? MIND_MAP_CONNECTOR_NAME : "rounded",
validateConnection: ({ sourceCell, targetCell, sourcePort, targetPort }) => {
if (!isConnectableDiagram(document.kind) || !sourceCell || !sourcePort) return false;
@@ -2247,7 +2269,7 @@ export const DiagramEditorPane = ({
return;
}
const palette = resolveDiagramPalette(themeRef.current, appearanceRef.current);
- edge.setLabels([diagramEdgeLabel(label, palette, document?.kind ?? "flowchart")]);
+ edge.setLabels([diagramEdgeLabel(label, palette, document?.kind ?? "flowchart", appearanceRef.current)]);
};
const createConnectedFlowNode = (shape: DiagramNodeShape) => {
@@ -2409,6 +2431,7 @@ export const DiagramEditorPane = ({
setStructure(nextStructure);
if (!graph || readOnly || document?.kind !== "mind-map") return;
applyGraphPalette(graph, themeRef.current, "mind-map", appearanceRef.current, nextStructure);
+ applyAutoLayout();
setDirty(savedSnapshotRef.current !== diagramEditorSnapshot(
titleRef.current,
graphToDocument(graph, "mind-map", themeRef.current, nextStructure),
@@ -2422,11 +2445,11 @@ export const DiagramEditorPane = ({
const fileName = (title.trim() || fallbackName).replace(/[\\/:*?"<>|]/g, "-").slice(0, 80);
setSaveError(null);
try {
- const palette = resolveDiagramPalette(themeRef.current, appearanceRef.current);
- const beforeSerialize = prepareExportSvg(palette.canvas);
+ const canvas = diagramCanvasColor(document.kind, themeRef.current, appearanceRef.current);
+ const beforeSerialize = prepareExportSvg(canvas);
const viewBox = graph.getCellsBBox(graph.getCells()) ?? undefined;
if (format === "png") {
- graph.exportPNG(fileName, { backgroundColor: palette.canvas, padding: 32, ratio: 2, copyStyles: false, beforeSerialize, viewBox });
+ graph.exportPNG(fileName, { backgroundColor: canvas, padding: 32, ratio: 2, copyStyles: false, beforeSerialize, viewBox });
} else {
graph.exportSVG(fileName, { preserveDimensions: true, copyStyles: false, beforeSerialize, viewBox });
}
@@ -2832,6 +2855,7 @@ export const DiagramEditorPane = ({
onExport={exportDiagram}
onRedo={() => runHistoryAction("redo")}
onThemeChange={applyTheme}
+ showTheme={document.kind !== "flowchart"}
onStructureChange={document.kind === "mind-map" ? applyStructure : undefined}
structure={structure}
onUndo={() => runHistoryAction("undo")}
@@ -2961,7 +2985,7 @@ export const DiagramEditorPane = ({
color: nodeEditor.color,
background: nodeEditor.background,
border: `2px solid ${nodeEditor.borderColor}`,
- borderRadius: nodeEditor.shape === "terminator" ? 999 : 11,
+ borderRadius: nodeEditor.shape === "terminator" ? 999 : 10,
clipPath: nodeEditor.shape === "decision" ? "polygon(50% 0, 100% 50%, 50% 100%, 0 50%)" : undefined,
}}
value={nodeEditor.value}
diff --git a/apps/web/src/components/DiagramToolbar.tsx b/apps/web/src/components/DiagramToolbar.tsx
index b81d6381..3cf41fdd 100644
--- a/apps/web/src/components/DiagramToolbar.tsx
+++ b/apps/web/src/components/DiagramToolbar.tsx
@@ -15,7 +15,7 @@ import {
ZoomOut,
} from "lucide-react";
import { useTranslation } from "react-i18next";
-import type { DiagramStructure, DiagramTheme } from "@edgeever/shared";
+import { DIAGRAM_SELECTABLE_STRUCTURES, DIAGRAM_THEME_GROUPS, diagramThemeSwatches, resolveDiagramTheme, type DiagramStructure, type DiagramTheme } from "@edgeever/shared";
import { Button } from "@/components/ui/button";
import { MemoEditorToolbarDivider, MemoEditorToolbarRow } from "@/components/MemoEditorToolbarChrome";
import {
@@ -24,9 +24,54 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { resolveDiagramPalette, type DiagramAppearance } from "@/lib/diagram-theme";
+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 nodePath = (form: typeof DIAGRAM_SELECTABLE_STRUCTURES[number], x: number, y: number, w: number, h: number) => {
+ if (form === "line" || form === "brace" || form === "map") return null;
+ if (form === "circle" || form === "ellipse") {
+ return <ellipse cx={x + w / 2} cy={y + h / 2} rx={w / 2} ry={h / 2} />;
+ }
+ if (form === "hexagon") {
+ return <polygon points={`${x + 4},${y} ${x + w - 4},${y} ${x + w},${y + h / 2} ${x + w - 4},${y + h} ${x + 4},${y + h} ${x},${y + h / 2}`} />;
+ }
+ const rx = form === "capsule" ? h / 2 : 3;
+ return <rect x={x} y={y} width={w} height={h} rx={rx} />;
+};
+
+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";
+ 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
+ ? [{ x: 42, y: 6 }, { x: 42, y: 22 }, { x: 42, y: 38 }]
+ : [{ x: 68, y: 8 }, { x: 68, y: 32 }];
+ const leaf = { w: 18, h: 10 };
+ 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">
+ <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}>
+ <path d={`M ${oneSided ? root.x + root.w : (item.x < cx ? root.x : root.x + root.w)} ${cy} C ${item.x + (item.x < cx ? leaf.w : 0)},${cy} ${cx},${item.y + leaf.h / 2} ${item.x + (item.x < cx ? leaf.w : 0)},${item.y + leaf.h / 2}`} fill="none" opacity="0.7" />
+ {lineOnly ? (
+ <path d={`M ${item.x} ${item.y + leaf.h} H ${item.x + leaf.w}`} fill="none" />
+ ) : (
+ <g fill="white" stroke="currentColor">{nodePath(structure, item.x, item.y, leaf.w, leaf.h)}</g>
+ )}
+ </g>
+ ))}
+ </svg>
+ );
+};
type DiagramToolbarProps = {
appearance: DiagramAppearance;
@@ -39,6 +84,7 @@ type DiagramToolbarProps = {
onExport: (format: "png" | "svg") => void;
onRedo: () => void;
onThemeChange: (theme: DiagramTheme) => void;
+ showTheme?: boolean;
onStructureChange?: (structure: DiagramStructure) => void;
structure?: DiagramStructure;
onUndo: () => void;
@@ -81,6 +127,7 @@ export const DiagramToolbar = ({
onExport,
onRedo,
onThemeChange,
+ showTheme = true,
onStructureChange,
onUndo,
onRead,
@@ -120,35 +167,81 @@ export const DiagramToolbar = ({
{onRead ? <Tooltip><TooltipTrigger asChild><Button size="sm" variant="ghost" onClick={onRead}><BookOpen className="h-4 w-4" />{t("diagram.readFlow")}</Button></TooltipTrigger><TooltipContent>{t("diagram.readFlowHint")}</TooltipContent></Tooltip> : null}
<MemoEditorToolbarDivider />
{onStructureChange ? (
- <Select value={structure === "box" ? "box" : "map"} disabled={readOnly} onValueChange={(value) => onStructureChange(value as DiagramStructure)}>
+ <DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
- <SelectTrigger className="h-8 w-[8.5rem] gap-2" aria-label={t("diagram.structure")}>
- <SelectValue />
- </SelectTrigger>
+ <DropdownMenuTrigger asChild>
+ <Button size="sm" variant="ghost" className="gap-1.5 px-2.5" disabled={readOnly} aria-label={t("diagram.structure")}>
+ {t(`diagram.structure${(structure && DIAGRAM_SELECTABLE_STRUCTURES.includes(structure as typeof DIAGRAM_SELECTABLE_STRUCTURES[number]) ? structure : "map").charAt(0).toUpperCase()}${(structure && DIAGRAM_SELECTABLE_STRUCTURES.includes(structure as typeof DIAGRAM_SELECTABLE_STRUCTURES[number]) ? structure : "map").slice(1)}` as "diagram.structureMap")}
+ <ChevronDown className="h-3.5 w-3.5 text-slate-400" />
+ </Button>
+ </DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent>{t("diagram.structure")}</TooltipContent>
</Tooltip>
- <SelectContent>
- <SelectItem value="map" textValue={t("diagram.structureMap")}><span className="flex items-center gap-2"><span className="h-3 w-3 border-b-2 border-slate-500" />{t("diagram.structureMap")}</span></SelectItem>
- <SelectItem value="box" textValue={t("diagram.structureBox")}><span className="flex items-center gap-2"><span className="h-3 w-3 rounded-sm border border-slate-400" />{t("diagram.structureBox")}</span></SelectItem>
- </SelectContent>
- </Select>
+ <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">
+ {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")}
+ onSelect={() => onStructureChange(value)}
+ >
+ <StructureThumb structure={value} />
+ </DropdownMenuItem>
+ ))}
+ </div>
+ </div>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ {showTheme ? (
+ <DropdownMenu>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <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) => (
+ <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")}
+ <ChevronDown className="h-3.5 w-3.5 text-slate-400" />
+ </Button>
+ </DropdownMenuTrigger>
+ </TooltipTrigger>
+ <TooltipContent>{t("diagram.theme")}</TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent align="start" className="w-[18.5rem] p-3">
+ {(["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">
+ {DIAGRAM_THEME_GROUPS[group].map((value) => (
+ <DropdownMenuItem
+ key={value}
+ className={cn("h-auto items-center gap-3 rounded-lg border px-2 py-1.5", 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">
+ {diagramThemeSwatches(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>
+ </div>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
) : null}
- <Select value={theme === "classic" ? "classic" : "brand"} disabled={readOnly} onValueChange={(value) => onThemeChange(value as DiagramTheme)}>
- <Tooltip>
- <TooltipTrigger asChild>
- <SelectTrigger className="h-8 w-[8.5rem] gap-2" aria-label={t("diagram.theme")}>
- <SelectValue />
- </SelectTrigger>
- </TooltipTrigger>
- <TooltipContent>{t("diagram.theme")}</TooltipContent>
- </Tooltip>
- <SelectContent>
- <SelectItem value="brand" textValue={t("diagram.themeBrand")}><span className="flex items-center gap-2"><span className="h-3 w-3 rounded-full border border-black/10" style={{ background: resolveDiagramPalette("brand", appearance).topicFill }} />{t("diagram.themeBrand")}</span></SelectItem>
- <SelectItem value="classic" textValue={t("diagram.themeClassic")}><span className="flex items-center gap-2"><span className="h-3 w-3 rounded-full border border-black/10" style={{ background: "conic-gradient(#16A06E, #3B82F6, #8B5CF6, #F59E0B, #EC4899, #16A06E)" }} />{t("diagram.themeClassic")}</span></SelectItem>
- </SelectContent>
- </Select>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm" variant="outline"><Download className="h-4 w-4" />{t("diagram.export")}</Button>
diff --git a/apps/web/src/lib/diagram-editor-snapshot.ts b/apps/web/src/lib/diagram-editor-snapshot.ts
index d6d1c432..204ac070 100644
--- a/apps/web/src/lib/diagram-editor-snapshot.ts
+++ b/apps/web/src/lib/diagram-editor-snapshot.ts
@@ -8,7 +8,7 @@ export const diagramEditorSnapshot = (title: string, document: DiagramDocument)
schemaVersion: document.schemaVersion,
kind: document.kind,
theme: document.theme ?? "brand",
- structure: document.kind === "mind-map" ? (document.structure === "box" ? "box" : "map") : undefined,
+ structure: document.kind === "mind-map" ? document.structure ?? "map" : undefined,
nodes: document.nodes.map((node) => ({
id: node.id, label: node.label, x: node.x, y: node.y, shape: node.shape,
parentId: node.parentId, resourceIcon: node.resourceIcon,
diff --git a/apps/web/src/lib/diagram-layout.test.mjs b/apps/web/src/lib/diagram-layout.test.mjs
index 0f3d7859..3f58824e 100644
--- a/apps/web/src/lib/diagram-layout.test.mjs
+++ b/apps/web/src/lib/diagram-layout.test.mjs
@@ -68,6 +68,32 @@ describe("diagram auto layout", () => {
expect(positions.detached.y).toBeGreaterThan(positions["flow-end"].y + 44);
});
+ test("aligns a sequential flowchart spine even when a loop returns from below", () => {
+ const document = compileDiagramIr({
+ kind: "flowchart",
+ nodes: [
+ { id: "a", type: "start", label: "开始" },
+ { id: "b", type: "process", label: "步骤一" },
+ { id: "c", type: "process", label: "Transformer 前向计算" },
+ { id: "d", type: "end", label: "结束" },
+ { id: "loop", type: "process", label: "回环" },
+ ],
+ edges: [
+ { source: "a", target: "b" },
+ { source: "b", target: "c" },
+ { source: "c", target: "d" },
+ { source: "d", target: "loop" },
+ { source: "loop", target: "b" },
+ ],
+ });
+ const centerX = (id) => {
+ const node = document.nodes.find((item) => item.id === id);
+ return node.x + node.width / 2;
+ };
+ expect(Math.abs(centerX("a") - centerX("b"))).toBeLessThanOrEqual(1);
+ expect(Math.abs(centerX("b") - centerX("c"))).toBeLessThanOrEqual(1);
+ });
+
test("keeps an explicit horizontal flowchart direction", () => {
const document = createDefaultDiagramDocument("flowchart");
const positions = computeDiagramLayout(document, { direction: "left-to-right" });
@@ -76,9 +102,9 @@ describe("diagram auto layout", () => {
});
test("uses compact flowchart nodes with aligned process and terminator centers", () => {
- expect(compactFlowchartNodeSize("process")).toEqual({ width: 124, height: 44 });
- expect(compactFlowchartNodeSize("terminator")).toEqual({ width: 116, height: 44 });
- expect(compactFlowchartNodeSize("decision")).toEqual({ width: 116, height: 72 });
+ expect(compactFlowchartNodeSize("process")).toEqual({ width: 124, height: 42 });
+ expect(compactFlowchartNodeSize("terminator")).toEqual({ width: 116, height: 40 });
+ expect(compactFlowchartNodeSize("decision")).toEqual({ width: 140, height: 72 });
});
test("balances a large mind map across both sides while keeping descendants with their branch", () => {
diff --git a/apps/web/src/lib/diagram-theme.test.mjs b/apps/web/src/lib/diagram-theme.test.mjs
index e8404edd..83cecbc7 100644
--- a/apps/web/src/lib/diagram-theme.test.mjs
+++ b/apps/web/src/lib/diagram-theme.test.mjs
@@ -32,4 +32,12 @@ describe("diagram appearance palettes", () => {
expect(resolveDiagramPalette("ocean", "light")).toEqual(resolveDiagramPalette("brand", "light"));
expect(resolveDiagramPalette("ink", "dark")).toEqual(resolveDiagramPalette("brand", "dark"));
});
+
+ test("keeps the ten selectable color schemes distinct from forest green", () => {
+ expect(Object.keys(DIAGRAM_THEME_PALETTES)).toEqual(expect.arrayContaining([
+ "brand", "mint", "wa", "island", "rose", "sun", "cosmos", "tea", "naive", "macaron",
+ ]));
+ expect(resolveDiagramPalette("mint", "light").topicFill).not.toBe(resolveDiagramPalette("brand", "light").topicFill);
+ expect(resolveDiagramPalette("ocean", "light")).toEqual(resolveDiagramPalette("brand", "light"));
+ });
});
diff --git a/apps/web/src/lib/diagram-theme.ts b/apps/web/src/lib/diagram-theme.ts
index 819064e4..c4e6acd3 100644
--- a/apps/web/src/lib/diagram-theme.ts
+++ b/apps/web/src/lib/diagram-theme.ts
@@ -1,4 +1,4 @@
-import type { DiagramTheme } from "@edgeever/shared";
+import { buildDiagramPalette, DIAGRAM_SELECTABLE_THEMES, resolveDiagramTheme, type DiagramTheme } from "@edgeever/shared";
export type DiagramAppearance = "light" | "dark";
@@ -16,122 +16,18 @@ export type DiagramPalette = {
gridStrong: string;
};
-const BRAND_GREEN = "#16A06E";
+const withGrid = (palette: ReturnType<typeof buildDiagramPalette>, appearance: DiagramAppearance): DiagramPalette => ({
+ ...palette,
+ grid: appearance === "dark" ? "#1D2722" : "#E6EEE9",
+ gridStrong: appearance === "dark" ? "#2B3A33" : "#CFDDD5",
+});
-export const DIAGRAM_THEME_PALETTES: Record<DiagramTheme, Record<DiagramAppearance, DiagramPalette>> = {
- brand: {
- light: {
- topicFill: BRAND_GREEN,
- topicText: "#FFFFFF",
- nodeFill: "#F0F8F4",
- nodeText: "#173B2E",
- nodeStroke: "#B8DFD0",
- topicStroke: "#12845B",
- mindMapEdge: "#55B891",
- flowEdge: "#408A6D",
- canvas: "#F8FAF9",
- grid: "#E6EEE9",
- gridStrong: "#CFDDD5",
- },
- dark: {
- topicFill: BRAND_GREEN,
- topicText: "#F4FFF9",
- nodeFill: "#18211D",
- nodeText: "#E8F2ED",
- nodeStroke: "#3B5248",
- topicStroke: "#58CDA4",
- mindMapEdge: "#4DB58B",
- flowEdge: "#72B99B",
- canvas: "#101311",
- grid: "#1D2722",
- gridStrong: "#2B3A33",
- },
- },
- ocean: {
- light: {
- topicFill: "#DEF1E9",
- topicText: "#0F4432",
- nodeFill: "#FFFEFA",
- nodeText: "#26352E",
- nodeStroke: "#D5E3DB",
- topicStroke: BRAND_GREEN,
- mindMapEdge: "#8ACCB2",
- flowEdge: "#6B9281",
- canvas: "#FBFCFA",
- grid: "#EBF0EC",
- gridStrong: "#D9E3DC",
- },
- dark: {
- topicFill: "#244D3D",
- topicText: "#DFF7ED",
- nodeFill: "#17201C",
- nodeText: "#E6F0EB",
- nodeStroke: "#3B554A",
- topicStroke: "#65C9A4",
- mindMapEdge: "#55B992",
- flowEdge: "#77AD97",
- canvas: "#111713",
- grid: "#202A25",
- gridStrong: "#304039",
- },
- },
- ink: {
- light: {
- topicFill: BRAND_GREEN,
- topicText: "#F5FBF8",
- nodeFill: "#19261F",
- nodeText: "#E5EEE9",
- nodeStroke: "#3C594A",
- topicStroke: "#68D6B0",
- mindMapEdge: "#58BA94",
- flowEdge: "#68A78D",
- canvas: "#101512",
- grid: "#202B25",
- gridStrong: "#304038",
- },
- dark: {
- topicFill: BRAND_GREEN,
- topicText: "#F5FBF8",
- nodeFill: "#151D19",
- nodeText: "#E7F0EB",
- nodeStroke: "#3C594A",
- topicStroke: "#68D6B0",
- mindMapEdge: "#58BA94",
- flowEdge: "#72B296",
- canvas: "#0B0F0D",
- grid: "#19211D",
- gridStrong: "#29362F",
- },
- },
- classic: {
- light: {
- topicFill: BRAND_GREEN,
- topicText: "#FFFFFF",
- nodeFill: "#F7FAF8",
- nodeText: "#173B2E",
- nodeStroke: "#D5E3DB",
- topicStroke: "#12845B",
- mindMapEdge: "#16A06E",
- flowEdge: "#408A6D",
- canvas: "#FBFCFB",
- grid: "#E6EEE9",
- gridStrong: "#CFDDD5",
- },
- dark: {
- topicFill: BRAND_GREEN,
- topicText: "#F4FFF9",
- nodeFill: "#18211D",
- nodeText: "#E8F2ED",
- nodeStroke: "#3B5248",
- topicStroke: "#58CDA4",
- mindMapEdge: "#4DB58B",
- flowEdge: "#72B99B",
- canvas: "#101311",
- grid: "#1D2722",
- gridStrong: "#2B3A33",
- },
- },
-};
+export const DIAGRAM_THEME_PALETTES = Object.fromEntries(
+ DIAGRAM_SELECTABLE_THEMES.map((theme) => [theme, {
+ light: withGrid(buildDiagramPalette(theme, "light"), "light"),
+ dark: withGrid(buildDiagramPalette(theme, "dark"), "dark"),
+ }]),
+) as Record<typeof DIAGRAM_SELECTABLE_THEMES[number], Record<DiagramAppearance, DiagramPalette>>;
export const resolveDiagramPalette = (theme: DiagramTheme, appearance: DiagramAppearance) =>
- DIAGRAM_THEME_PALETTES[theme === "classic" ? "classic" : "brand"][appearance];
+ withGrid(buildDiagramPalette(resolveDiagramTheme(theme), appearance), appearance);
diff --git a/apps/web/src/lib/flowchart-presentation.test.mjs b/apps/web/src/lib/flowchart-presentation.test.mjs
index 13205d8c..679f2dc9 100644
--- a/apps/web/src/lib/flowchart-presentation.test.mjs
+++ b/apps/web/src/lib/flowchart-presentation.test.mjs
@@ -7,7 +7,7 @@ test('long labels fit bounded nodes while keeping every character', () => {
const presentation = flowchartNodePresentation(shape, label);
expect(presentation.text.replaceAll('\n', '')).toBe(label.replaceAll('\n', ''));
expect(presentation.width).toBeLessThanOrEqual(240);
- expect(presentation.height).toBeGreaterThanOrEqual(presentation.text.split('\n').length * 18 + 24);
+ expect(presentation.height).toBeGreaterThanOrEqual(presentation.text.split('\n').length * 18);
}
});
diff --git a/packages/shared/src/diagram-flowchart-style.test.mjs b/packages/shared/src/diagram-flowchart-style.test.mjs
new file mode 100644
index 00000000..cbd84221
--- /dev/null
+++ b/packages/shared/src/diagram-flowchart-style.test.mjs
@@ -0,0 +1,65 @@
+import { describe, expect, test } from "bun:test";
+import { flowchartNodePresentation } from "./diagram-node-presentation.ts";
+import {
+ FLOWCHART_SURFACES,
+ flowchartNodeVisual,
+ resolveFlowchartSurface,
+} from "./diagram-flowchart-style.ts";
+
+const channel = (value) => {
+ const normalized = value / 255;
+ return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
+};
+
+const luminance = (hex) => {
+ const channels = hex.match(/[a-f\d]{2}/gi).map((value) => channel(Number.parseInt(value, 16)));
+ return channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722;
+};
+
+const contrast = (foreground, background) => {
+ const values = [luminance(foreground), luminance(background)].sort((left, right) => right - left);
+ return (values[0] + 0.05) / (values[1] + 0.05);
+};
+
+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");
+ }
+ });
+
+ 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);
+ }
+ }
+ });
+
+ 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.label.fontFamily).toContain("Inter");
+ });
+});
+
+describe("flowchart node presentation", () => {
+ test("keeps short decision questions on one line", () => {
+ const presentation = flowchartNodePresentation("decision", "是结束标记EOS?");
+ expect(presentation.text.split("\n")).toEqual(["是结束标记EOS?"]);
+ expect(presentation.height).toBeLessThanOrEqual(80);
+ });
+
+ test("preserves every character while wrapping long process labels", () => {
+ const label = "Transformer 前向计算\n因果注意力+前馈网络以及更长的说明文字";
+ const presentation = flowchartNodePresentation("process", label);
+ expect(presentation.text.replaceAll("\n", "")).toBe(label.replaceAll("\n", ""));
+ expect(presentation.width).toBeLessThanOrEqual(240);
+ });
+});
diff --git a/packages/shared/src/diagram-flowchart-style.ts b/packages/shared/src/diagram-flowchart-style.ts
new file mode 100644
index 00000000..fc608497
--- /dev/null
+++ b/packages/shared/src/diagram-flowchart-style.ts
@@ -0,0 +1,81 @@
+import type { DiagramNodeShape } from "./diagram";
+
+export const FLOWCHART_LABEL_FONT =
+ 'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
+
+export const FLOWCHART_EDGE_ROUTER = {
+ name: "manhattan" as const,
+ args: { padding: 16, step: 10 },
+};
+
+export const FLOWCHART_LAYOUT_SPACING = { rank: 56, node: 36 };
+
+export type FlowchartAppearance = "light" | "dark";
+
+export type FlowchartShapePaint = {
+ fill: string;
+ stroke: string;
+ text: string;
+};
+
+export type FlowchartSurface = {
+ canvas: string;
+ edge: string;
+ process: FlowchartShapePaint;
+ decision: FlowchartShapePaint;
+ 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" },
+ },
+ 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" },
+ },
+};
+
+export const resolveFlowchartSurface = (appearance: FlowchartAppearance = "light") =>
+ FLOWCHART_SURFACES[appearance];
+
+export const flowchartShapePaint = (shape: DiagramNodeShape, appearance: FlowchartAppearance) => {
+ const surface = resolveFlowchartSurface(appearance);
+ if (shape === "decision") return surface.decision;
+ if (shape === "terminator") return surface.terminator;
+ return surface.process;
+};
+
+export const flowchartNodeVisual = (
+ shape: DiagramNodeShape,
+ appearance: FlowchartAppearance,
+ size: { width: number; height: number },
+) => {
+ const paint = flowchartShapePaint(shape, appearance);
+ const terminator = shape === "terminator";
+ const decision = shape === "decision";
+ return {
+ body: {
+ fill: paint.fill,
+ stroke: paint.stroke,
+ strokeWidth: 1.5,
+ rx: terminator ? Math.round(size.height / 2) : 10,
+ ry: terminator ? Math.round(size.height / 2) : 10,
+ ...(decision ? { refPoints: "0,10 10,0 20,10 10,20" } : {}),
+ },
+ label: {
+ fill: paint.text,
+ fontSize: 13,
+ fontWeight: terminator ? 650 : decision ? 600 : 500,
+ fontFamily: FLOWCHART_LABEL_FONT,
+ lineHeight: 18,
+ },
+ };
+};
diff --git a/packages/shared/src/diagram-layout.ts b/packages/shared/src/diagram-layout.ts
index 4f8d4c98..36bfed2d 100644
--- a/packages/shared/src/diagram-layout.ts
+++ b/packages/shared/src/diagram-layout.ts
@@ -1,8 +1,11 @@
import { compactFlowchartNodeSize, flowchartNodePresentation } from "./diagram-node-presentation";
export { compactFlowchartNodeSize, flowchartNodePresentation } from "./diagram-node-presentation";
+import { FLOWCHART_LAYOUT_SPACING } from "./diagram-flowchart-style";
+export { FLOWCHART_EDGE_ROUTER, FLOWCHART_LAYOUT_SPACING } from "./diagram-flowchart-style";
import {
MIND_MAP_HORIZONTAL_GAP,
MIND_MAP_VERTICAL_GAP,
+ mindMapIsOneSided,
mindMapNodePresentation,
mindMapNodeRole,
} from "./diagram-mindmap-style";
@@ -86,7 +89,7 @@ export type DiagramIr = {
};
const MIND_MAP_TWO_SIDED_THRESHOLD = 5;
-const FLOWCHART_DETACHED_GAP = 72;
+const FLOWCHART_DETACHED_GAP = 56;
const FLOWCHART_DETACHED_ROW_GAP = 24;
const FLOWCHART_DETACHED_ROW_WIDTH = 960;
const ARCHITECTURE_LAYOUT_ROW_WIDTH = 1480;
@@ -214,7 +217,7 @@ const computeMindMapLayout = (
.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) {
+ if (childIds.length < MIND_MAP_TWO_SIDED_THRESHOLD || mindMapIsOneSided(document.structure)) {
placeRootSide(root.id, childIds, 1);
continue;
}
@@ -375,17 +378,73 @@ const placeDetachedFlowchartNodes = (
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 alignFlowchartSpine = (
+ document: DiagramDocument,
+ positions: DiagramLayoutPositions,
+ direction: "left-to-right" | "top-to-bottom",
+) => {
+ const topToBottom = direction !== "left-to-right";
+ const incoming = new Map<string, string[]>();
+ const outgoing = new Map<string, string[]>();
+ for (const node of document.nodes) {
+ incoming.set(node.id, []);
+ outgoing.set(node.id, []);
+ }
+ for (const edge of document.edges) {
+ if (!positions[edge.source] || !positions[edge.target]) continue;
+ outgoing.get(edge.source)?.push(edge.target);
+ incoming.get(edge.target)?.push(edge.source);
+ }
+ const isBackEdge = (source: string, target: string) => {
+ const from = positions[source];
+ const to = positions[target];
+ return topToBottom ? from.y > to.y + 8 : from.x > to.x + 8;
+ };
+ const sizeById = new Map(document.nodes.map((node) => [node.id, node]));
+ const ordered = [...document.nodes].sort((left, right) => {
+ const leftPosition = positions[left.id];
+ const rightPosition = positions[right.id];
+ return topToBottom
+ ? leftPosition.y - rightPosition.y || leftPosition.x - rightPosition.x
+ : leftPosition.x - rightPosition.x || leftPosition.y - rightPosition.y;
+ });
+ const boxesOverlap = (
+ left: { x: number; y: number; width: number; height: number },
+ right: { x: number; y: number; width: number; height: number },
+ ) => left.x < right.x + right.width && left.x + left.width > right.x
+ && left.y < right.y + right.height && left.y + left.height > right.y;
+
+ for (const node of ordered) {
+ const successors = (outgoing.get(node.id) ?? []).filter((target) => !isBackEdge(node.id, target));
+ if (successors.length !== 1) continue;
+ const targetId = successors[0];
+ const predecessors = (incoming.get(targetId) ?? []).filter((source) => !isBackEdge(source, targetId));
+ if (predecessors.length !== 1 || predecessors[0] !== node.id) continue;
+ const source = sizeById.get(node.id);
+ const target = sizeById.get(targetId);
+ if (!source || !target) continue;
+ const from = positions[node.id];
+ const current = positions[targetId];
+ const next = topToBottom
+ ? { x: Math.round(from.x + source.width / 2 - target.width / 2), y: current.y }
+ : { x: current.x, y: Math.round(from.y + source.height / 2 - target.height / 2) };
+ const nextBox = { ...next, width: target.width, height: target.height };
+ const overlaps = document.nodes.some((other) => {
+ if (other.id === node.id || other.id === targetId) return false;
+ const otherPosition = positions[other.id];
+ return boxesOverlap(nextBox, { ...otherPosition, width: other.width, height: other.height });
+ });
+ if (!overlaps) positions[targetId] = next;
+ }
+ return positions;
+};
+
+const computeFlowchartLayout = (document: DiagramDocument, options: DiagramLayoutOptions) => {
+ const direction = options.direction ?? "top-to-bottom";
+ const positions = computeDagreLayout(document, { ...options, direction }, false, FLOWCHART_LAYOUT_SPACING);
+ alignFlowchartSpine(document, positions, direction);
+ return placeDetachedFlowchartNodes(document, positions);
+};
const computeArchitectureLayout = (document: DiagramDocument, options: DiagramLayoutOptions) => (
wrapArchitectureGroups(
diff --git a/packages/shared/src/diagram-mindmap-style.test.mjs b/packages/shared/src/diagram-mindmap-style.test.mjs
index 478bb782..6da5c5ed 100644
--- a/packages/shared/src/diagram-mindmap-style.test.mjs
+++ b/packages/shared/src/diagram-mindmap-style.test.mjs
@@ -11,6 +11,8 @@ import {
mindMapNodeRole,
mindMapNodeVisual,
mindMapRootRadius,
+ mindMapCloudPath,
+ mindMapTopicForm,
mindMapUsesUnderline,
resolveMindMapNodeStyle,
MIND_MAP_CONNECTOR_NAME,
@@ -84,6 +86,13 @@ describe("mind map presentation", () => {
expect(mindMapUsesUnderline("nested", "map")).toBe(true);
expect(mindMapUsesUnderline("nested", "box")).toBe(false);
expect(mindMapUsesUnderline("primary")).toBe(false);
+ expect(mindMapUsesUnderline("primary", "line")).toBe(true);
+ expect(mindMapUsesUnderline("nested", "line")).toBe(true);
+ expect(mindMapUsesUnderline("root", "line")).toBe(false);
+ expect(mindMapTopicForm("hexagon", "primary")).toBe("hexagon");
+ expect(mindMapTopicForm("capsule", "root")).toBe("capsule");
+ expect(mindMapTopicForm("logic", "primary")).toBe("rounded");
+ expect(mindMapCloudPath(96, 36)).toContain("Z");
expect(nested.body.fill).toBe("transparent");
expect(nested.underline.stroke).toBe(palette.mindMapEdge);
expect(nested.underline.d).toContain("H");
@@ -105,9 +114,9 @@ describe("mind map presentation", () => {
const first = mindMapBranchTint(0, "light");
const second = mindMapBranchTint(1, "light");
expect(first.edge).not.toBe(second.edge);
- const styled = resolveMindMapNodeStyle(nodes, "one-a", palette, "classic", "light", { width: 96, height: 32 });
+ const styled = resolveMindMapNodeStyle(nodes, "one-a", palette, "sun", "light", { width: 96, height: 32 });
expect(styled.underline).toBe(true);
- expect(styled.visual.underline.stroke).toBe(first.edge);
+ expect(styled.visual.underline.stroke).toBe(mindMapBranchTint(0, "light", "sun")?.edge);
const brandNested = resolveMindMapNodeStyle(nodes, "one-a", palette, "brand", "light", { width: 96, height: 32 });
expect(brandNested.visual.underline.stroke).toBe(palette.mindMapEdge);
});
diff --git a/packages/shared/src/diagram-mindmap-style.ts b/packages/shared/src/diagram-mindmap-style.ts
index 781d42f7..de953d27 100644
--- a/packages/shared/src/diagram-mindmap-style.ts
+++ b/packages/shared/src/diagram-mindmap-style.ts
@@ -1,4 +1,5 @@
import type { DiagramStructure, DiagramTheme } from "./diagram";
+import { buildDiagramBranchTints, diagramThemeUsesBranchColors } from "./diagram-palette";
import { visualTextUnits } from "./diagram-node-presentation";
export type MindMapRole = "root" | "primary" | "nested";
@@ -38,6 +39,51 @@ export const MIND_MAP_TOPIC_MARKUP = [
{ tagName: "text", selector: "label" },
];
+export type MindMapTopicForm =
+ | "rounded"
+ | "rect"
+ | "capsule"
+ | "ellipse"
+ | "circle"
+ | "diamond"
+ | "hexagon"
+ | "cloud"
+ | "underline";
+
+export const mindMapIsOneSided = (structure?: DiagramStructure) => (
+ structure === "logic" || structure === "tree" || structure === "brace"
+);
+
+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";
+ return false;
+};
+
+export const mindMapTopicForm = (structure?: DiagramStructure, role: MindMapRole = "primary"): MindMapTopicForm => {
+ if (mindMapUsesUnderline(role, structure)) return "underline";
+ if (structure === "capsule") return "capsule";
+ if (structure === "ellipse") return "ellipse";
+ if (structure === "circle") return "circle";
+ if (structure === "hexagon") return "hexagon";
+ if (structure === "box" || structure === "logic") return "rounded";
+ if (role === "root") return "capsule";
+ return "rounded";
+};
+
+export const mindMapTopicMarkup = (structure?: DiagramStructure, role: MindMapRole = "primary") => {
+ const form = mindMapTopicForm(structure, role);
+ const body = form === "ellipse" || form === "circle"
+ ? { tagName: "ellipse", selector: "body" }
+ : form === "diamond" || form === "hexagon"
+ ? { tagName: "polygon", selector: "body" }
+ : form === "cloud"
+ ? { tagName: "path", selector: "body" }
+ : { tagName: "rect", selector: "body" };
+ return [body, { tagName: "path", selector: "underline" }, { tagName: "text", selector: "label" }];
+};
+
export const MIND_MAP_BRANCH_TINTS: Record<MindMapAppearance, MindMapBranchTint[]> = {
light: [
{ fill: "#E7F6EF", stroke: "#0F8A5C", text: "#145C40", edge: "#16A06E" },
@@ -73,11 +119,7 @@ const wrapVisualText = (label: string, capacity: number) => label.split("\n").fl
const formatPoint = (value: number) => (Math.round(value * 100) / 100).toFixed(2);
-export const mindMapUsesBranchColors = (theme?: DiagramTheme) => theme === "classic";
-
-export const mindMapUsesUnderline = (role: MindMapRole, structure?: DiagramStructure) => (
- role === "nested" && structure !== "box"
-);
+export const mindMapUsesBranchColors = (theme?: DiagramTheme) => diagramThemeUsesBranchColors(theme);
export const mindMapNodeRole = (
nodes: MindMapIndexedNode[],
@@ -122,22 +164,24 @@ export const mindMapBranchTintIndex = (
export const mindMapBranchTint = (
index: number | null,
appearance: MindMapAppearance,
+ theme?: DiagramTheme,
): MindMapBranchTint | undefined => {
if (index == null) return undefined;
- const tints = MIND_MAP_BRANCH_TINTS[appearance];
+ const tints = theme ? buildDiagramBranchTints(theme, appearance) : MIND_MAP_BRANCH_TINTS[appearance];
return tints[index % tints.length];
};
export const mindMapNodeSize = (label: string, role: MindMapRole = "primary", structure?: DiagramStructure) => {
const isRoot = role === "root";
const underline = mindMapUsesUnderline(role, structure);
- return {
- width: Math.round(Math.min(
- isRoot ? 180 : 168,
- Math.max(isRoot ? 124 : underline ? 88 : 96, visualTextUnits(label) * 13 + (isRoot ? 36 : underline ? 22 : 28)),
- )),
- height: isRoot ? 46 : underline ? 32 : 36,
- };
+ const form = mindMapTopicForm(structure, role);
+ const padX = isRoot ? 36 : underline ? 22 : form === "diamond" || form === "hexagon" || form === "circle" ? 36 : 28;
+ const width = Math.round(Math.min(
+ isRoot ? 180 : form === "circle" ? 132 : 168,
+ Math.max(isRoot ? 124 : underline ? 88 : form === "circle" ? 108 : 96, visualTextUnits(label) * 13 + padX),
+ ));
+ const height = isRoot ? 46 : underline ? 32 : form === "circle" ? Math.max(40, width - 24) : 36;
+ return { width, height };
};
export const compactMindMapNodeSize = (label: string, isRoot: boolean) => (
@@ -164,6 +208,34 @@ export const mindMapUnderlinePath = (width: number, height: number) => (
`M 1 ${formatPoint(Math.max(2, height - 2))} H ${formatPoint(Math.max(2, width - 1))}`
);
+export const mindMapCloudPath = (width: number, height: number) => {
+ const w = Math.max(width, 12);
+ const h = Math.max(height, 12);
+ return [
+ `M ${formatPoint(w * 0.18)} ${formatPoint(h * 0.62)}`,
+ `Q ${formatPoint(w * 0.06)} ${formatPoint(h * 0.60)} ${formatPoint(w * 0.08)} ${formatPoint(h * 0.44)}`,
+ `Q ${formatPoint(w * 0.02)} ${formatPoint(h * 0.26)} ${formatPoint(w * 0.22)} ${formatPoint(h * 0.24)}`,
+ `Q ${formatPoint(w * 0.30)} ${formatPoint(h * 0.06)} ${formatPoint(w * 0.48)} ${formatPoint(h * 0.14)}`,
+ `Q ${formatPoint(w * 0.60)} ${formatPoint(h * 0.02)} ${formatPoint(w * 0.72)} ${formatPoint(h * 0.16)}`,
+ `Q ${formatPoint(w * 0.96)} ${formatPoint(h * 0.14)} ${formatPoint(w * 0.92)} ${formatPoint(h * 0.40)}`,
+ `Q ${formatPoint(w * 1.02)} ${formatPoint(h * 0.56)} ${formatPoint(w * 0.84)} ${formatPoint(h * 0.64)}`,
+ `Q ${formatPoint(w * 0.80)} ${formatPoint(h * 0.84)} ${formatPoint(w * 0.58)} ${formatPoint(h * 0.78)}`,
+ `Q ${formatPoint(w * 0.42)} ${formatPoint(h * 0.92)} ${formatPoint(w * 0.30)} ${formatPoint(h * 0.76)}`,
+ `Q ${formatPoint(w * 0.12)} ${formatPoint(h * 0.82)} ${formatPoint(w * 0.18)} ${formatPoint(h * 0.62)}`,
+ "Z",
+ ].join(" ");
+};
+
+const mindMapBodyGeometry = (form: MindMapTopicForm, width: number, height: number, rx: number) => {
+ if (form === "ellipse" || form === "circle") {
+ return { refCx: "50%", refCy: "50%", refRx: "50%", refRy: "50%" };
+ }
+ if (form === "diamond") return { refPoints: "5,0 10,5 5,10 0,5" };
+ if (form === "hexagon") return { refPoints: "2.5,0 7.5,0 10,5 7.5,10 2.5,10 0,5" };
+ if (form === "cloud") return { d: mindMapCloudPath(width, height) };
+ return { rx, ry: rx };
+};
+
export const mindMapNodeVisual = (
role: MindMapRole,
palette: MindMapPalette,
@@ -179,28 +251,7 @@ export const mindMapNodeVisual = (
const width = options.width ?? 96;
const height = options.height ?? (role === "root" ? 46 : underline ? 32 : 36);
const tint = options.tint;
- if (role === "root") {
- return {
- body: {
- fill: palette.topicFill,
- stroke: palette.topicStroke,
- strokeWidth: 1.5,
- rx: mindMapRootRadius(height),
- ry: mindMapRootRadius(height),
- },
- label: {
- fill: palette.topicText,
- fontSize: 15,
- fontWeight: 650,
- fontFamily: MIND_MAP_LABEL_FONT,
- lineHeight: 20,
- refY: "50%",
- textAnchor: "middle" as const,
- textVerticalAnchor: "middle" as const,
- },
- underline: { d: "", stroke: "none", fill: "none" },
- };
- }
+ const form = mindMapTopicForm(options.structure, role);
if (underline) {
const color = tint?.edge ?? palette.mindMapEdge;
return {
@@ -213,8 +264,8 @@ export const mindMapNodeVisual = (
},
label: {
fill: tint?.text ?? palette.nodeText,
- fontSize: 13,
- fontWeight: 500,
+ fontSize: role === "primary" ? 14 : 13,
+ fontWeight: role === "primary" ? 650 : 500,
fontFamily: MIND_MAP_LABEL_FONT,
lineHeight: 18,
refX: "50%",
@@ -232,42 +283,25 @@ export const mindMapNodeVisual = (
},
};
}
- if (role === "nested") {
- return {
- body: {
- fill: tint?.fill ?? palette.canvas,
- stroke: tint?.stroke ?? palette.nodeStroke,
- strokeWidth: 1,
- rx: 8,
- ry: 8,
- },
- label: {
- fill: tint?.text ?? palette.nodeText,
- fontSize: 13,
- fontWeight: 500,
- fontFamily: MIND_MAP_LABEL_FONT,
- lineHeight: 18,
- refY: "50%",
- textAnchor: "middle" as const,
- textVerticalAnchor: "middle" as const,
- },
- underline: { d: "", stroke: "none", fill: "none" },
- };
- }
+ const isRoot = role === "root";
+ const radius = form === "capsule" || (isRoot && form === "rounded")
+ ? mindMapRootRadius(height)
+ : form === "rect"
+ ? 2
+ : isRoot ? 12 : role === "nested" ? 8 : 10;
return {
body: {
- fill: tint?.fill ?? palette.nodeFill,
- stroke: tint?.stroke ?? palette.topicStroke,
- strokeWidth: 1.5,
- rx: 10,
- ry: 10,
+ fill: isRoot ? palette.topicFill : tint?.fill ?? (role === "nested" ? palette.canvas : palette.nodeFill),
+ stroke: isRoot ? palette.topicStroke : tint?.stroke ?? (role === "nested" ? palette.nodeStroke : palette.topicStroke),
+ strokeWidth: role === "nested" && !isRoot ? 1 : 1.5,
+ ...mindMapBodyGeometry(form, width, height, radius),
},
label: {
- fill: tint?.text ?? palette.nodeText,
- fontSize: 14,
- fontWeight: 650,
+ fill: isRoot ? palette.topicText : tint?.text ?? palette.nodeText,
+ fontSize: isRoot ? 15 : role === "primary" ? 14 : 13,
+ fontWeight: isRoot || role === "primary" ? 650 : 500,
fontFamily: MIND_MAP_LABEL_FONT,
- lineHeight: 18,
+ lineHeight: isRoot ? 20 : 18,
refY: "50%",
textAnchor: "middle" as const,
textVerticalAnchor: "middle" as const,
@@ -288,7 +322,7 @@ export const resolveMindMapNodeStyle = (
const role = mindMapNodeRole(nodes, nodeId);
const underline = mindMapUsesUnderline(role, structure);
const tint = mindMapUsesBranchColors(theme)
- ? mindMapBranchTint(mindMapBranchTintIndex(nodes, nodeId), appearance)
+ ? mindMapBranchTint(mindMapBranchTintIndex(nodes, nodeId), appearance, theme)
: undefined;
return {
role,
diff --git a/packages/shared/src/diagram-node-presentation.ts b/packages/shared/src/diagram-node-presentation.ts
index e41a11cf..32721c14 100644
--- a/packages/shared/src/diagram-node-presentation.ts
+++ b/packages/shared/src/diagram-node-presentation.ts
@@ -7,29 +7,51 @@ export const visualTextUnits = (label: string) => Array.from(label).reduce(
export const compactFlowchartNodeSize = (shape: DiagramNodeShape) => (
shape === "decision"
- ? { width: 116, height: 72 }
+ ? { width: 140, height: 72 }
: shape === "terminator"
- ? { width: 116, height: 44 }
- : { width: 124, height: 44 }
+ ? { width: 116, height: 40 }
+ : { width: 124, height: 42 }
);
+const FLOWCHART_CHAR_WIDTH = 13;
+const FLOWCHART_LINE_HEIGHT = 18;
+const FLOWCHART_DECISION_TEXT_RATIO = 0.7;
+
+const wrapFlowchartLabel = (label: string, capacity: number) => label.split("\n").flatMap((paragraph) => {
+ const result: string[] = [];
+ let line = "";
+ for (const character of Array.from(paragraph)) {
+ if (line && visualTextUnits(line + character) > capacity) {
+ result.push(line);
+ line = "";
+ }
+ line += character;
+ }
+ result.push(line);
+ return result;
+});
+
// Shared by semantic creation and rendering so layout reserves space for every line.
export const flowchartNodePresentation = (shape: DiagramNodeShape, label: string) => {
const base = compactFlowchartNodeSize(shape);
const decision = shape === "decision";
- const width = Math.max(decision ? 184 : base.width, Math.min(decision ? 220 : 240,
- Math.ceil(Math.max(...label.split("\n").map(visualTextUnits), 0) * 14 + (decision ? 64 : 32))));
- const capacity = (width - (decision ? width / 2 : 32)) / 14;
- const lines = label.split("\n").flatMap((paragraph) => {
- const result: string[] = [];
- let line = "";
- for (const character of Array.from(paragraph)) {
- if (line && visualTextUnits(line + character) > capacity) { result.push(line); line = ""; }
- line += character;
- }
- result.push(line);
- return result;
- });
- return { width, height: Math.max(base.height, lines.length * 18 * (decision ? 2 : 1) + 24), text: lines.join("\n") };
+ const terminator = shape === "terminator";
+ const units = Math.max(...label.split("\n").map(visualTextUnits), 0);
+ const padX = terminator ? 36 : 28;
+ const width = Math.max(
+ base.width,
+ Math.min(
+ 240,
+ Math.ceil(decision ? units * FLOWCHART_CHAR_WIDTH / FLOWCHART_DECISION_TEXT_RATIO + 12 : units * FLOWCHART_CHAR_WIDTH + padX),
+ ),
+ );
+ const capacity = Math.max(4, (decision ? width * FLOWCHART_DECISION_TEXT_RATIO : width - padX) / FLOWCHART_CHAR_WIDTH);
+ const lines = wrapFlowchartLabel(label, capacity);
+ const textHeight = Math.max(lines.length, 1) * FLOWCHART_LINE_HEIGHT;
+ const height = Math.max(
+ base.height,
+ decision ? Math.ceil(textHeight / (1 - FLOWCHART_DECISION_TEXT_RATIO)) : textHeight + (terminator ? 16 : 18),
+ );
+ return { width, height, text: lines.join("\n") };
};
diff --git a/packages/shared/src/diagram-palette.ts b/packages/shared/src/diagram-palette.ts
new file mode 100644
index 00000000..68905926
--- /dev/null
+++ b/packages/shared/src/diagram-palette.ts
@@ -0,0 +1,137 @@
+import type { DiagramTheme } from "./diagram";
+import { resolveDiagramTheme } from "./diagram";
+
+type DiagramAppearance = "light" | "dark";
+
+export type DiagramColorStrip = {
+ id: Exclude<ReturnType<typeof resolveDiagramTheme>, never>;
+ group: "vivid" | "classic";
+ colors: readonly [string, string, string, string, string, string];
+};
+
+export const DIAGRAM_COLOR_STRIPS: Record<
+ "brand" | "mint" | "wa" | "island" | "rose" | "sun" | "cosmos" | "tea" | "macaron" | "naive",
+ DiagramColorStrip
+> = {
+ brand: { id: "brand", group: "classic", colors: ["#E7F6EF", "#9FDBC4", "#16A06E", "#12845B", "#0F5C42", "#173B2E"] },
+ sun: { id: "sun", group: "vivid", colors: ["#F7E27A", "#C6F07A", "#FFFFFF", "#C084FC", "#60A5FA", "#1F2937"] },
+ wa: { id: "wa", group: "vivid", colors: ["#FFFFFF", "#FFB4A2", "#FF8A4C", "#7DD3FC", "#3B82F6", "#1E3A8A"] },
+ island: { id: "island", group: "classic", colors: ["#F3D5C4", "#D4A276", "#B08968", "#A3A882", "#7D8B69", "#4A5D4E"] },
+ rose: { id: "rose", group: "vivid", colors: ["#FDE8EF", "#F8C1D4", "#F48FB1", "#EC407A", "#C2185B", "#7A1040"] },
+ mint: { id: "mint", group: "vivid", colors: ["#FFFFFF", "#A5F3FC", "#5EEAD4", "#2DD4BF", "#0F9B8E", "#115E59"] },
+ cosmos: { id: "cosmos", group: "classic", colors: ["#D6DCE5", "#8BBAD4", "#4D86B0", "#1E4E7A", "#163A5F", "#0B1F33"] },
+ tea: { id: "tea", group: "classic", colors: ["#D8E2C8", "#B4C49A", "#7A9A58", "#4F7A3C", "#2F5D32", "#1A3C24"] },
+ naive: { id: "naive", group: "vivid", colors: ["#F8C8D4", "#E45A7C", "#8BB4F0", "#4F6FCF", "#F5EED8", "#2D2A32"] },
+ macaron: { id: "macaron", group: "vivid", colors: ["#D4B896", "#F5B89A", "#B8D4C8", "#F0EDE4", "#F2E39A", "#4A4A4A"] },
+};
+
+export const DIAGRAM_THEME_GROUPS = {
+ vivid: ["sun", "wa", "rose", "mint", "naive", "macaron"],
+ classic: ["brand", "island", "tea", "cosmos"],
+} as const;
+
+const hexToRgb = (hex: string) => {
+ const value = hex.replace("#", "");
+ return [Number.parseInt(value.slice(0, 2), 16), Number.parseInt(value.slice(2, 4), 16), Number.parseInt(value.slice(4, 6), 16)] as const;
+};
+
+const rgbToHex = (r: number, g: number, b: number) => `#${[r, g, b].map((channel) => Math.round(Math.min(255, Math.max(0, channel))).toString(16).padStart(2, "0")).join("")}`;
+
+const mix = (from: string, to: string, amount: number) => {
+ const start = hexToRgb(from);
+ const end = hexToRgb(to);
+ return rgbToHex(
+ start[0] + (end[0] - start[0]) * amount,
+ start[1] + (end[1] - start[1]) * amount,
+ start[2] + (end[2] - start[2]) * amount,
+ );
+};
+
+const channel = (value: number) => {
+ const normalized = value / 255;
+ return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
+};
+
+const luminance = (hex: string) => {
+ const [r, g, b] = hexToRgb(hex).map(channel);
+ return r * 0.2126 + g * 0.7152 + b * 0.0722;
+};
+
+const readableText = (fill: string) => (luminance(fill) > 0.32 ? "#1C1917" : "#FFFCF8");
+
+export const diagramThemeSwatches = (theme?: DiagramTheme) =>
+ DIAGRAM_COLOR_STRIPS[resolveDiagramTheme(theme)].colors;
+
+export const diagramThemeUsesBranchColors = (theme?: DiagramTheme) => resolveDiagramTheme(theme) !== "brand";
+
+export const buildDiagramBranchTints = (theme: DiagramTheme | undefined, appearance: DiagramAppearance) => {
+ const colors = diagramThemeSwatches(theme);
+ return colors.map((color) => {
+ const fill = appearance === "dark" ? mix(color, "#101418", 0.55) : mix(color, "#FFFFFF", luminance(color) > 0.82 ? 0.08 : 0.72);
+ return {
+ fill,
+ stroke: appearance === "dark" ? mix(color, "#FFFFFF", 0.18) : mix(color, "#1C1917", 0.22),
+ text: readableText(fill),
+ edge: color === "#FFFFFF" ? colors[2] : color,
+ };
+ });
+};
+
+export const buildDiagramPalette = (theme: DiagramTheme | undefined, appearance: DiagramAppearance) => {
+ const resolved = resolveDiagramTheme(theme);
+ const strip = DIAGRAM_COLOR_STRIPS[resolved];
+ const colors = strip.colors;
+ const accent = colors.find((color) => luminance(color) < 0.55 && luminance(color) > 0.08) ?? colors[2];
+ const deepest = colors[colors.length - 1];
+ const lightest = colors[0];
+ if (resolved === "brand") {
+ if (appearance === "dark") {
+ return {
+ topicFill: "#16A06E",
+ topicText: "#F4FFF9",
+ nodeFill: "#18211D",
+ nodeText: "#E8F2ED",
+ nodeStroke: "#3B5248",
+ topicStroke: "#58CDA4",
+ mindMapEdge: "#4DB58B",
+ flowEdge: "#72B99B",
+ canvas: "#101311",
+ };
+ }
+ return {
+ topicFill: "#16A06E",
+ topicText: "#FFFFFF",
+ nodeFill: "#F0F8F4",
+ nodeText: "#173B2E",
+ nodeStroke: "#B8DFD0",
+ topicStroke: "#12845B",
+ mindMapEdge: "#55B891",
+ flowEdge: "#408A6D",
+ canvas: "#F8FAF9",
+ };
+ }
+ if (appearance === "dark") {
+ return {
+ topicFill: mix(deepest, "#0B0D0C", 0.2),
+ topicText: "#F8FAFC",
+ nodeFill: mix(deepest, "#101418", 0.45),
+ nodeText: "#E8EEF2",
+ nodeStroke: mix(accent, "#101418", 0.55),
+ topicStroke: mix(accent, "#FFFFFF", 0.28),
+ mindMapEdge: accent,
+ flowEdge: mix(accent, "#FFFFFF", 0.12),
+ canvas: "#101311",
+ };
+ }
+ return {
+ topicFill: accent,
+ topicText: readableText(accent),
+ nodeFill: mix(lightest, "#FFFFFF", luminance(lightest) > 0.9 ? 0.2 : 0.55),
+ nodeText: mix(deepest, "#1C1917", 0.15),
+ nodeStroke: mix(accent, "#FFFFFF", 0.62),
+ topicStroke: mix(accent, "#1C1917", 0.18),
+ mindMapEdge: accent,
+ flowEdge: mix(accent, "#1C1917", 0.12),
+ canvas: mix(lightest, "#FFFFFF", 0.72),
+ };
+};
diff --git a/packages/shared/src/diagram-view.ts b/packages/shared/src/diagram-view.ts
index 7a2da0e6..b80e266b 100644
--- a/packages/shared/src/diagram-view.ts
+++ b/packages/shared/src/diagram-view.ts
@@ -1,13 +1,20 @@
import { flowchartNodePresentation } from "./diagram-node-presentation";
+import {
+ FLOWCHART_EDGE_ROUTER,
+ FLOWCHART_LABEL_FONT,
+ flowchartNodeVisual,
+ resolveFlowchartSurface,
+} from "./diagram-flowchart-style";
import type { ArchitectureResourceIcon, DiagramDocument, DiagramNodeShape, DiagramTheme } from "./diagram";
+import { buildDiagramPalette } from "./diagram-palette";
import {
MIND_MAP_CONNECTOR_NAME,
- MIND_MAP_TOPIC_MARKUP,
mindMapBranchSides,
mindMapEdgeTerminal,
mindMapEdgeVisual,
mindMapNodePresentation,
mindMapNodeRole,
+ mindMapTopicMarkup,
resolveMindMapNodeStyle,
} from "./diagram-mindmap-style";
@@ -27,29 +34,10 @@ export type DiagramPalette = {
const BRAND_GREEN = "#16A06E";
-const PALETTES: Record<DiagramTheme, Record<DiagramAppearance, DiagramPalette>> = {
- brand: {
- light: { topicFill: BRAND_GREEN, topicText: "#FFFFFF", nodeFill: "#F0F8F4", nodeText: "#173B2E", nodeStroke: "#B8DFD0", topicStroke: "#12845B", mindMapEdge: "#55B891", flowEdge: "#408A6D", canvas: "#F8FAF9" },
- dark: { topicFill: BRAND_GREEN, topicText: "#F4FFF9", nodeFill: "#18211D", nodeText: "#E8F2ED", nodeStroke: "#3B5248", topicStroke: "#58CDA4", mindMapEdge: "#4DB58B", flowEdge: "#72B99B", canvas: "#101311" },
- },
- ocean: {
- light: { topicFill: "#DEF1E9", topicText: "#0F4432", nodeFill: "#FFFEFA", nodeText: "#26352E", nodeStroke: "#D5E3DB", topicStroke: BRAND_GREEN, mindMapEdge: "#8ACCB2", flowEdge: "#6B9281", canvas: "#FBFCFA" },
- dark: { topicFill: "#244D3D", topicText: "#DFF7ED", nodeFill: "#17201C", nodeText: "#E6F0EB", nodeStroke: "#3B554A", topicStroke: "#65C9A4", mindMapEdge: "#55B992", flowEdge: "#77AD97", canvas: "#111713" },
- },
- ink: {
- light: { topicFill: BRAND_GREEN, topicText: "#F5FBF8", nodeFill: "#19261F", nodeText: "#E5EEE9", nodeStroke: "#3C594A", topicStroke: "#68D6B0", mindMapEdge: "#58BA94", flowEdge: "#68A78D", canvas: "#101512" },
- dark: { topicFill: BRAND_GREEN, topicText: "#F5FBF8", nodeFill: "#151D19", nodeText: "#E7F0EB", nodeStroke: "#3C594A", topicStroke: "#68D6B0", mindMapEdge: "#58BA94", flowEdge: "#72B296", canvas: "#0B0F0D" },
- },
- classic: {
- light: { topicFill: BRAND_GREEN, topicText: "#FFFFFF", nodeFill: "#F7FAF8", nodeText: "#173B2E", nodeStroke: "#D5E3DB", topicStroke: "#12845B", mindMapEdge: "#16A06E", flowEdge: "#408A6D", canvas: "#FBFCFB" },
- dark: { topicFill: BRAND_GREEN, topicText: "#F4FFF9", nodeFill: "#18211D", nodeText: "#E8F2ED", nodeStroke: "#3B5248", topicStroke: "#58CDA4", mindMapEdge: "#4DB58B", flowEdge: "#72B99B", canvas: "#101311" },
- },
-};
-
export const resolvePortableDiagramPalette = (
theme: DiagramTheme = "brand",
appearance: DiagramAppearance = "light",
-) => PALETTES[theme === "classic" ? "classic" : "brand"][appearance];
+) => buildDiagramPalette(theme, appearance);
const architectureAccent: Partial<Record<DiagramNodeShape, string>> = {
client: "#0891B2",
@@ -94,6 +82,7 @@ export const diagramDocumentToX6Cells = (
appearance: DiagramAppearance,
) => {
const palette = resolvePortableDiagramPalette(document.theme ?? "brand", appearance);
+ const flowchartSurface = document.kind === "flowchart" ? resolveFlowchartSurface(appearance) : null;
const nodes = document.nodes.map((node) => {
const mindMapRole = document.kind === "mind-map" ? mindMapNodeRole(document.nodes, node.id) : null;
const presentation = document.kind === "flowchart"
@@ -105,6 +94,9 @@ export const diagramDocumentToX6Cells = (
? resolveMindMapNodeStyle(document.nodes, node.id, palette, document.theme, appearance, presentation, document.structure)
: null;
const mindVisual = mindStyle?.visual ?? null;
+ const flowchartVisual = document.kind === "flowchart"
+ ? flowchartNodeVisual(node.shape, appearance, presentation)
+ : null;
const isRootTopic = node.shape === "topic" && !node.parentId;
const isTerminator = node.shape === "terminator";
const isBoundary = node.shape === "boundary";
@@ -112,6 +104,8 @@ export const diagramDocumentToX6Cells = (
const emphasized = isRootTopic || isTerminator;
const fill = mindVisual
? mindVisual.body.fill
+ : flowchartVisual
+ ? flowchartVisual.body.fill
: isBoundary
? "transparent"
: accent
@@ -119,6 +113,8 @@ export const diagramDocumentToX6Cells = (
: emphasized ? palette.topicFill : palette.nodeFill;
const stroke = mindVisual
? mindVisual.body.stroke
+ : flowchartVisual
+ ? flowchartVisual.body.stroke
: isBoundary ? palette.nodeStroke : accent ?? (emphasized ? palette.topicStroke : palette.nodeStroke);
const usesArchitectureIcon = document.kind === "architecture" && !isBoundary;
const iconGlyph = node.resourceIcon
@@ -137,25 +133,27 @@ export const diagramDocumentToX6Cells = (
{ tagName: "rect", selector: "iconFrame" },
{ tagName: "text", selector: "resourceIcon" },
{ tagName: "text", selector: "label" },
- ] } : mindMapRole ? { markup: MIND_MAP_TOPIC_MARKUP } : {}),
+ ] } : mindMapRole ? { markup: mindMapTopicMarkup(document.structure, mindMapRole) } : {}),
attrs: {
body: {
fill,
stroke,
- strokeWidth: mindVisual?.body.strokeWidth ?? (isBoundary || emphasized || accent ? 1.5 : 1),
+ strokeWidth: mindVisual?.body.strokeWidth ?? flowchartVisual?.body.strokeWidth ?? (isBoundary || emphasized || accent ? 1.5 : 1),
strokeDasharray: isBoundary || node.shape === "external" ? "7 5" : undefined,
- rx: mindVisual?.body.rx ?? (isTerminator ? 24 : node.shape === "database" ? 24 : 11),
- ry: mindVisual?.body.ry ?? (isTerminator ? 24 : node.shape === "database" ? 24 : 11),
+ ...(mindVisual?.body ?? flowchartVisual?.body ?? {
+ rx: isTerminator ? 24 : node.shape === "database" ? 24 : 11,
+ ry: isTerminator ? 24 : node.shape === "database" ? 24 : 11,
+ }),
...(node.shape === "decision" ? { refPoints: "0,10 10,0 20,10 10,20" } : {}),
},
label: {
text: presentation.text,
- lineHeight: mindVisual?.label.lineHeight ?? (mindMapRole === "root" ? 20 : 18),
- fill: mindVisual?.label.fill ?? (emphasized ? palette.topicText : palette.nodeText),
- fontSize: mindVisual?.label.fontSize ?? (node.shape === "topic" ? 14 : isBoundary ? 12 : 13),
- fontWeight: mindVisual?.label.fontWeight ?? (emphasized || isBoundary || accent ? 650 : 500),
+ lineHeight: mindVisual?.label.lineHeight ?? flowchartVisual?.label.lineHeight ?? (mindMapRole === "root" ? 20 : 18),
+ fill: mindVisual?.label.fill ?? flowchartVisual?.label.fill ?? (emphasized ? palette.topicText : palette.nodeText),
+ fontSize: mindVisual?.label.fontSize ?? flowchartVisual?.label.fontSize ?? (node.shape === "topic" ? 14 : isBoundary ? 12 : 13),
+ fontWeight: mindVisual?.label.fontWeight ?? flowchartVisual?.label.fontWeight ?? (emphasized || isBoundary || accent ? 650 : 500),
+ fontFamily: mindVisual?.label.fontFamily ?? flowchartVisual?.label.fontFamily ?? FLOWCHART_LABEL_FONT,
...(mindVisual ? {
- fontFamily: mindVisual.label.fontFamily,
refX: mindVisual.label.refX,
refY: mindVisual.label.refY,
textAnchor: mindVisual.label.textAnchor,
@@ -210,7 +208,11 @@ export const diagramDocumentToX6Cells = (
const targetTerminal = targetNode && mindMapTargetRole
? mindMapEdgeTerminal(targetNode, mindMapTargetRole, sides.target, document.structure)
: null;
- const stroke = edgeKind === "data" ? "#7C3AED" : edgeKind === "async" ? "#EA580C" : mindEdge?.stroke ?? palette.flowEdge;
+ const stroke = edgeKind === "data"
+ ? "#7C3AED"
+ : edgeKind === "async"
+ ? "#EA580C"
+ : mindEdge?.stroke ?? flowchartSurface?.edge ?? palette.flowEdge;
return {
id: edge.id,
source: document.kind === "mind-map"
@@ -219,7 +221,7 @@ export const diagramDocumentToX6Cells = (
target: document.kind === "mind-map"
? { cell: edge.target, ...(targetTerminal ?? { anchor: { name: sides.target } }) }
: { cell: edge.target },
- router: document.kind === "flowchart" ? { name: "manhattan", args: { padding: 28, step: 10 } } : undefined,
+ router: document.kind === "flowchart" ? FLOWCHART_EDGE_ROUTER : undefined,
connector: document.kind === "mind-map"
? { name: MIND_MAP_CONNECTOR_NAME, args: { sourceWidth: mindEdge?.sourceWidth, targetWidth: mindEdge?.targetWidth } }
: { name: "rounded", args: { radius: 10 } },
@@ -236,10 +238,22 @@ export const diagramDocumentToX6Cells = (
} : { fill: "none" }),
} },
labels: edge.label ? [{ attrs: {
- label: { text: edge.label, fill: palette.nodeText, fontSize: 12, lineHeight: 16, textWrap: { width: 140, height: 512 } },
- body: { ref: "label", refWidth: 1, refHeight: 1, refWidth2: 12, refHeight2: 8, refX: -6, refY: -4, fill: palette.canvas, stroke: palette.nodeStroke, strokeWidth: 1, rx: 5, ry: 5 },
+ label: {
+ text: edge.label,
+ fill: flowchartSurface?.process.text ?? palette.nodeText,
+ fontSize: 12,
+ lineHeight: 16,
+ fontFamily: FLOWCHART_LABEL_FONT,
+ textWrap: { width: 140, height: 512 },
+ },
+ body: {
+ ref: "label", refWidth: 1, refHeight: 1, refWidth2: 12, refHeight2: 8, refX: -6, refY: -4,
+ fill: flowchartSurface?.canvas ?? palette.canvas,
+ stroke: flowchartSurface?.process.stroke ?? palette.nodeStroke,
+ strokeWidth: 1, rx: 5, ry: 5,
+ },
} }] : undefined,
};
});
- return { canvas: palette.canvas, edges, nodes };
+ return { canvas: flowchartSurface?.canvas ?? palette.canvas, edges, nodes };
};
diff --git a/packages/shared/src/diagram.test.mjs b/packages/shared/src/diagram.test.mjs
index fcc730ab..4517372f 100644
--- a/packages/shared/src/diagram.test.mjs
+++ b/packages/shared/src/diagram.test.mjs
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { createDefaultDiagramDocument, diagramDocumentToMermaid, diagramFallbackMarkdown, hasDiagramDocumentMarker, parseDiagramDocument, serializeDiagramDocument, stripDiagramDocumentMarker } from "./diagram.ts";
+import { createDefaultDiagramDocument, DIAGRAM_SELECTABLE_STRUCTURES, DIAGRAM_SELECTABLE_THEMES, diagramDocumentToMermaid, diagramFallbackMarkdown, hasDiagramDocumentMarker, parseDiagramDocument, serializeDiagramDocument, stripDiagramDocumentMarker } from "./diagram.ts";
import { diagramDocumentToX6Cells } from "./diagram-view.ts";
import { markdownToDoc } from "./content.ts";
@@ -12,6 +12,20 @@ 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);
+ expect(DIAGRAM_SELECTABLE_THEMES).toHaveLength(10);
+ const document = createDefaultDiagramDocument("mind-map");
+ document.theme = "mint";
+ document.structure = "logic";
+ expect(parseDiagramDocument(serializeDiagramDocument(document))).toEqual(document);
+ const unknown = structuredClone(document);
+ unknown.theme = "not-a-theme";
+ const encoded = serializeDiagramDocument(unknown);
+ const parsedUnknown = parseDiagramDocument(encoded.replace("not-a-theme", "not-a-theme"));
+ expect(parsedUnknown?.theme).toBeUndefined();
+ });
+
test("parses the envelope without browser base64 and text codec globals", () => {
const originalAtob = globalThis.atob;
const originalBtoa = globalThis.btoa;
@@ -53,6 +67,9 @@ describe("diagram document", () => {
expect(markdown).toContain("# 流程图");
expect(markdown).toContain("```mermaid\nflowchart TD");
expect(markdown).toContain('n1["处理步骤"]');
+ expect(markdown).toContain("classDef flowProcess fill:#FFFFFF,stroke:#6F9B88");
+ expect(markdown).toContain("class n1 flowProcess");
+ expect(markdown).toContain("class n0 flowTerminator");
const doc = markdownToDoc(markdown);
expect(doc.content?.some((node) => node.type === "codeBlock" && node.attrs?.language === "mermaid")).toBe(true);
@@ -145,7 +162,7 @@ describe("diagram document", () => {
const invalidTheme = createDefaultDiagramDocument("mind-map");
invalidTheme.theme = "neon";
- expect(parseDiagramDocument(serializeDiagramDocument(invalidTheme))).toBeNull();
+ expect(parseDiagramDocument(serializeDiagramDocument(invalidTheme))?.theme).toBeUndefined();
const architecture = createDefaultDiagramDocument("architecture");
architecture.nodes.find((node) => node.id === "api").parentId = "database";
@@ -161,6 +178,9 @@ test('native flowchart projection shares label sizing and obstacle routing witho
expect(projection.nodes[1].height).toBeGreaterThan(document.nodes[1].height);
expect(projection.nodes[1].attrs.label.text.replaceAll('\n', '')).toBe(document.nodes[1].label.replaceAll('\n', ''));
expect(projection.edges[0].router.name).toBe('manhattan');
+ expect(projection.edges[0].router.args.padding).toBe(16);
expect(projection.edges[0].attrs.line.fill).toBe('none');
+ expect(projection.nodes[0].attrs.body.fill).not.toBe('#16A06E');
+ expect(projection.nodes[0].attrs.label.fontFamily).toContain('Inter');
expect(document).toEqual(original);
});
diff --git a/packages/shared/src/diagram.ts b/packages/shared/src/diagram.ts
index 2c7e5fd9..89767424 100644
--- a/packages/shared/src/diagram.ts
+++ b/packages/shared/src/diagram.ts
@@ -19,13 +19,42 @@ export type DiagramNodeShape =
| "external"
| "boundary";
export type DiagramEdgeKind = "dependency" | "request" | "async" | "data";
-export const DIAGRAM_THEMES = ["brand", "ocean", "ink", "classic"] as const;
+export const DIAGRAM_SELECTABLE_THEMES = [
+ "brand", "sun", "wa", "island", "rose", "mint", "cosmos", "tea", "naive", "macaron",
+] 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",
+] as const;
export type DiagramTheme = (typeof DIAGRAM_THEMES)[number];
-export const DIAGRAM_STRUCTURES = ["map", "box"] as const;
+export const DIAGRAM_SELECTABLE_STRUCTURES = [
+ "map", "line", "capsule", "box", "circle", "ellipse", "hexagon", "logic", "tree", "brace",
+] as const;
+export const DIAGRAM_STRUCTURES = [
+ ...DIAGRAM_SELECTABLE_STRUCTURES, "rect", "diamond", "cloud",
+] as const;
export type DiagramStructure = (typeof DIAGRAM_STRUCTURES)[number];
+const THEME_ALIASES: Partial<Record<DiagramTheme, typeof DIAGRAM_SELECTABLE_THEMES[number]>> = {
+ ocean: "brand",
+ ink: "brand",
+ classic: "sun",
+ sky: "cosmos",
+ sunset: "sun",
+ violet: "rose",
+ sand: "island",
+ slate: "cosmos",
+ aurora: "mint",
+ mono: "cosmos",
+};
+
+export const resolveDiagramTheme = (theme?: DiagramTheme): typeof DIAGRAM_SELECTABLE_THEMES[number] => {
+ if (theme && (DIAGRAM_SELECTABLE_THEMES as readonly string[]).includes(theme)) return theme as typeof DIAGRAM_SELECTABLE_THEMES[number];
+ return THEME_ALIASES[theme ?? "brand"] ?? "brand";
+};
+
export const resolveDiagramStructure = (structure?: DiagramStructure): DiagramStructure => (
- structure === "box" ? "box" : "map"
+ structure && (DIAGRAM_SELECTABLE_STRUCTURES as readonly string[]).includes(structure) ? structure : "map"
);
export const ARCHITECTURE_RESOURCE_ICONS = [
@@ -156,12 +185,11 @@ export const parseDiagramDocument = (markdown: string | null | undefined): Diagr
if (isArchitecture
? value.schemaVersion !== ARCHITECTURE_DIAGRAM_SCHEMA_VERSION
: value.schemaVersion !== DIAGRAM_SCHEMA_VERSION) return null;
- if (
- !Array.isArray(value.nodes)
- || !Array.isArray(value.edges)
- || (value.theme !== undefined && !DIAGRAM_THEMES.includes(value.theme as DiagramTheme))
- || (value.structure !== undefined && !DIAGRAM_STRUCTURES.includes(value.structure as DiagramStructure))
- ) return null;
+ if (!Array.isArray(value.nodes) || !Array.isArray(value.edges)) return null;
+ const theme = DIAGRAM_THEMES.includes(value.theme as DiagramTheme) ? value.theme as DiagramTheme : undefined;
+ const structure = DIAGRAM_STRUCTURES.includes(value.structure as DiagramStructure)
+ ? value.structure as DiagramStructure
+ : undefined;
const nodes = value.nodes.map(parseNode);
const edges = value.edges.map(parseEdge);
if (nodes.some((node) => !node) || edges.some((edge) => !edge)) return null;
@@ -182,8 +210,8 @@ export const parseDiagramDocument = (markdown: string | null | undefined): Diagr
return {
schemaVersion: value.schemaVersion as DiagramDocument["schemaVersion"],
kind: value.kind as DiagramKind,
- ...(value.theme ? { theme: value.theme as DiagramTheme } : {}),
- ...(value.kind === "mind-map" && value.structure ? { structure: value.structure as DiagramStructure } : {}),
+ ...(theme ? { theme } : {}),
+ ...(value.kind === "mind-map" && structure ? { structure } : {}),
nodes: nodes as DiagramNode[],
edges: edges as DiagramEdge[],
};
@@ -307,6 +335,10 @@ export const diagramDocumentToMermaid = (document: DiagramDocument) => {
? `${id}("${label}")`
: `${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}`);
+ }
}
for (const edge of document.edges) {
@@ -318,6 +350,12 @@ export const diagramDocumentToMermaid = (document: DiagramDocument) => {
lines.push(` ${source} ${connector}${label} ${target}`);
}
+ 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");
+ }
+
if (document.kind === "mind-map") {
const root = document.nodes.find((node) => node.shape === "topic" && !node.parentId);
const rootId = root ? nodeIds.get(root.id) : undefined;
@@ -381,9 +419,9 @@ export const createDefaultDiagramDocument = (kind: DiagramKind): DiagramDocument
schemaVersion: DIAGRAM_SCHEMA_VERSION,
kind,
nodes: [
- { id: "flow-start", label: "开始", x: 80, y: 180, width: 104, height: 40, shape: "terminator" },
- { id: "flow-process", label: "处理步骤", x: 256, y: 180, width: 112, height: 40, shape: "process" },
- { id: "flow-end", label: "结束", x: 440, y: 180, width: 104, height: 40, shape: "terminator" },
+ { id: "flow-start", label: "开始", x: 86, y: 48, width: 116, height: 40, shape: "terminator" },
+ { id: "flow-process", label: "处理步骤", x: 82, y: 136, width: 124, height: 42, shape: "process" },
+ { id: "flow-end", label: "结束", x: 86, y: 226, width: 116, height: 40, shape: "terminator" },
],
edges: [
{ id: "flow-edge-1", source: "flow-start", target: "flow-process" },
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index ac431364..6630b72d 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -363,11 +363,31 @@ export const enUS = {
autoLayoutTooltip: "Re-arrange all nodes and connections",
toolbar: "Diagram toolbar",
theme: "Color scheme",
- themeBrand: "Forest Green",
- themeClassic: "Spectrum",
- structure: "Structure",
- structureMap: "Mind map",
- structureBox: "Boxes",
+ themeGroupVivid: "Vivid",
+ themeGroupClassic: "Classic",
+ themeBrand: "Forest",
+ themeSun: "Sun",
+ themeWa: "Breeze",
+ themeIsland: "Island",
+ themeRose: "Rose",
+ themeMint: "Mint",
+ themeCosmos: "Cosmos",
+ themeTea: "Tea",
+ themeNaive: "Play",
+ themeMacaron: "Macaron",
+ structure: "Shape",
+ structureGroupMap: "Mind map",
+ structureGroupLogic: "Logic chart",
+ structureLogic: "Logic",
+ structureMap: "Map",
+ structureLine: "Line",
+ structureCapsule: "Capsule",
+ structureBox: "Box",
+ structureCircle: "Circle",
+ structureEllipse: "Ellipse",
+ structureHexagon: "Hexagon",
+ structureTree: "Tree",
+ structureBrace: "Brace",
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 4c344115..4af6b620 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -363,11 +363,31 @@ export const zhCN = {
autoLayoutTooltip: "重新规整所有节点与连线",
toolbar: "图形工具栏",
theme: "配色",
+ themeGroupVivid: "缤纷",
+ themeGroupClassic: "经典",
themeBrand: "森绿",
- themeClassic: "彩枝",
- structure: "结构",
+ themeSun: "阳光",
+ themeWa: "和风",
+ themeIsland: "岛屿",
+ themeRose: "玫瑰",
+ themeMint: "薄荷",
+ themeCosmos: "宇宙",
+ themeTea: "绿茶",
+ themeNaive: "纯真",
+ themeMacaron: "马卡龙",
+ structure: "形状",
+ structureGroupMap: "思维导图",
+ structureGroupLogic: "逻辑图",
+ structureLogic: "逻辑图",
structureMap: "脑图",
+ structureLine: "线条",
+ structureCapsule: "胶囊",
structureBox: "盒子",
+ structureCircle: "圆形",
+ structureEllipse: "椭圆",
+ structureHexagon: "六边",
+ structureTree: "树图",
+ structureBrace: "括号",
export: "导出",
exportPng: "导出 PNG",
exportSvg: "导出 SVG",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 651004cc..81b9450b 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -30,6 +30,8 @@ export * from "./sync";
export * from "./desktop-rpc";
export * from "./deployment-metadata";
export * from "./diagram";
+export * from "./diagram-palette";
+export * from "./diagram-flowchart-style";
export * from "./diagram-mindmap-style";
export * from "./diagram-view";
export * from "./file-attachment";