();
+
+ // 1. Architecture group containers (lowest zIndex, assistedLayout: false keeps Basalt's grid)
+ for (const g of scene.groups) {
+ const box: SceneBox = { x: round2(g.box.x + pad), y: round2(g.box.y + pad), w: round2(g.box.w), h: round2(g.box.h) };
+ shapes.push({
+ id: lucidId("group", g.id),
+ type: "roundedRectangleContainer",
+ boundingBox: box,
+ style: {
+ fill: { type: "color", color: transparentFill },
+ stroke: { color: P.structure, width: 1, style: "dashed" },
+ rounding: 24, // 12px radius * 2
+ },
+ magnetize: true,
+ assistedLayout: false,
+ containerTitle: {
+ text: `${escHtml(g.label)}`,
+ },
+ zIndex: 0,
+ });
+ }
+
+ // 2. Data-flow swimLanes container (horizontal lanes whose widths sum to exact boundingBox.h)
+ if (scene.lanes.length > 0) {
+ const top = round2(scene.lanes[0]!.box.y + pad);
+ const left = round2(scene.lanes[0]!.box.x + pad);
+ const width = round2(scene.lanes[0]!.box.w);
+ const laneWidths = scene.lanes.map((l) => round2(l.box.h));
+ const totalH = round2(laneWidths.reduce((a, b) => a + b, 0));
+ shapes.push({
+ id: "swimlanes_0",
+ type: "swimLanes",
+ boundingBox: { x: left, y: top, w: width, h: totalH },
+ style: {
+ fill: { type: "color", color: transparentFill },
+ stroke: { color: P.divider, width: 1, style: "solid" },
+ },
+ vertical: false,
+ titleBar: { height: 0, verticalText: false },
+ lanes: scene.lanes.map((l, idx) => ({
+ title: l.label,
+ width: laneWidths[idx]!,
+ headerFill: P.page,
+ laneFill: transparentFill,
+ })),
+ magnetize: true,
+ zIndex: 0,
+ });
+ }
+
+ // 3. Sequence phase bands
+ for (let bIdx = 0; bIdx < scene.bands.length; bIdx++) {
+ const band = scene.bands[bIdx]!;
+ const midY = round2(band.y + band.h / 2 + pad);
+ lines.push({
+ id: `band_${bIdx}`,
+ lineType: "straight",
+ endpoint1: { type: "positionEndpoint", style: "none", position: { x: round2(pad), y: midY } },
+ endpoint2: { type: "positionEndpoint", style: "none", position: { x: round2(pad + band.w), y: midY } },
+ stroke: { color: P.divider, width: 1, style: "solid" },
+ text: [
+ {
+ text: `${escHtml(band.text)}`,
+ position: 0.5,
+ side: "middle",
+ },
+ ],
+ zIndex: 4,
+ });
+ }
+
+ // 4. Nodes (cards, flowchart shapes, participants, schema tables)
+ for (const n of scene.nodes) {
+ const id = lucidId("node", n.id);
+ const box: SceneBox = { x: round2(n.box.x + pad), y: round2(n.box.y + pad), w: round2(n.box.w), h: round2(n.box.h) };
+ shapeBoxById.set(n.id, box);
+
+ const isFocal = n.focal;
+ const fill = isFocal ? P.focalFill : P.cardFill;
+ const stroke = isFocal
+ ? P.focalBorder
+ : scene.type === "flowchart"
+ ? P.structure
+ : P.cardBorder;
+ const nameColor = isFocal ? P.focalInk : P.textPrimary;
+ const kindColor = isFocal ? P.focalQuiet : P.textTertiary;
+ const detailColor = isFocal ? P.focalQuiet : P.textSecondary;
+
+ if (n.shape === "table") {
+ const rows = n.rows ?? [];
+ const rowCount = 1 + rows.length + (n.more ? 1 : 0);
+ const colCount = 3;
+ const cells: LucidTableCell[] = [];
+ const rowSizes: Array<{ index: number; size: number }> = [{ index: 0, size: n.headerH ?? 37 }];
+ // Header row merged across all 3 columns
+ cells.push({
+ xPosition: 0,
+ yPosition: 0,
+ mergeCellsRight: 2,
+ style: { fill: { type: "color", color: fill } },
+ text: `${escHtml(n.name)}
`,
+ });
+ for (let r = 0; r < rows.length; r++) {
+ const row = rows[r]!;
+ const yPos = r + 1;
+ rowSizes.push({ index: yPos, size: round2(row.h) });
+ const rightWord = row.refTable ? `→ ${row.refTable}` : row.type ?? "";
+ cells.push(
+ {
+ xPosition: 0,
+ yPosition: yPos,
+ style: { fill: { type: "color", color: fill } },
+ text: row.key ? `${escHtml(row.key)}
` : "",
+ },
+ {
+ xPosition: 1,
+ yPosition: yPos,
+ style: { fill: { type: "color", color: fill } },
+ text: `${escHtml(row.name)}
`,
+ },
+ {
+ xPosition: 2,
+ yPosition: yPos,
+ style: { fill: { type: "color", color: fill } },
+ text: rightWord
+ ? `${escHtml(rightWord)}
`
+ : "",
+ },
+ );
+ }
+ if (n.more) {
+ const moreIdx = rows.length + 1;
+ rowSizes.push({ index: moreIdx, size: 24 });
+ cells.push({
+ xPosition: 0,
+ yPosition: moreIdx,
+ mergeCellsRight: 2,
+ style: { fill: { type: "color", color: fill } },
+ text: `${escHtml(`+ ${n.more} more`)}
`,
+ });
+ }
+ const keyColW = 36;
+ const typeColW = Math.max(64, round2(box.w * 0.36));
+ const nameColW = Math.max(60, round2(box.w - keyColW - typeColW));
+
+ shapes.push({
+ id,
+ type: "table",
+ boundingBox: box,
+ style: {
+ fill: { type: "color", color: fill },
+ stroke: { color: stroke, width: 1, style: "solid" },
+ textColor: nameColor,
+ },
+ rowCount,
+ colCount,
+ cells,
+ userSpecifiedRows: rowSizes,
+ userSpecifiedCols: [
+ { index: 0, size: keyColW },
+ { index: 1, size: nameColW },
+ { index: 2, size: typeColW },
+ ],
+ verticalBorder: false,
+ horizontalBorder: true,
+ customData: [
+ { key: "basalt_id", value: n.id },
+ { key: "basalt_col", value: String(n.col) },
+ { key: "basalt_row", value: String(n.row) },
+ ],
+ zIndex: 10,
+ });
+ continue;
+ }
+
+ const align = n.shape === "decision" || n.shape === "terminal" || n.shape === "participant" ? "center" : "left";
+ const linesHtml: string[] = [];
+ if (n.kind) {
+ linesHtml.push(`${escHtml(n.kind)}
`);
+ }
+ linesHtml.push(`${escHtml(n.name)}
`);
+ if (n.detail) {
+ const ff = n.detailMono ? "'Geist Mono', 'Liberation Mono', monospace" : "'Geist', 'Liberation Sans', sans-serif";
+ linesHtml.push(`${escHtml(n.detail)}
`);
+ }
+
+ const shapeType = n.shape === "decision" ? "decision" : n.shape === "terminal" ? "terminator" : "rectangle";
+ const shapeStyle: LucidShape["style"] = {
+ fill: { type: "color", color: fill },
+ stroke: { color: stroke, width: 1, style: "solid" },
+ textColor: nameColor,
+ };
+ if (shapeType === "rectangle") shapeStyle.rounding = 16; // 8px Basalt radius-md * 2
+
+ shapes.push({
+ id,
+ type: shapeType,
+ boundingBox: box,
+ style: shapeStyle,
+ text: linesHtml.join(""),
+ customData: [
+ { key: "basalt_id", value: n.id },
+ { key: "basalt_col", value: String(n.col) },
+ { key: "basalt_row", value: String(n.row) },
+ ],
+ zIndex: 10,
+ });
+
+ if (n.mark) {
+ const fileName = `${n.mark.id.replace(/[^a-zA-Z0-9_-]/g, "_")}_${images.length + 1}.svg`;
+ const useDarkForm = isFocal ? singleTheme === "light" : singleTheme === "dark";
+ images.push({ name: fileName, svg: useDarkForm ? n.mark.svgDark : n.mark.svgLight });
+ shapes.push({
+ id: lucidId("mark", n.id),
+ type: "rectangle",
+ boundingBox: { x: round2(box.x + box.w - 12 - 16), y: round2(box.y + 10), w: 16, h: 16 },
+ style: {
+ fill: { type: "image", ref: fileName, imageScale: "fit" },
+ stroke: { color: transparentFill, width: 0 },
+ },
+ zIndex: 15,
+ });
+ }
+ }
+
+ // 5. Sequence lifelines (straight dashed lines attached to participant headers)
+ for (const lf of scene.lifelines) {
+ const lineId = lucidId("life", lf.participantId);
+ const pBox = shapeBoxById.get(lf.participantId);
+ const lx = pBox ? round2(pBox.x + pBox.w / 2) : round2(lf.x + pad);
+ const y1 = pBox ? round2(pBox.y + pBox.h) : round2(lf.y1 + pad);
+ const y2 = round2(lf.y2 + pad);
+ lifeByParticipant.set(lf.participantId, { lineId, x: lx, y1, y2 });
+ lines.push({
+ id: lineId,
+ lineType: "straight",
+ endpoint1: pBox
+ ? { type: "shapeEndpoint", style: "none", shapeId: lucidId("node", lf.participantId), position: { x: 0.5, y: 1 } }
+ : { type: "positionEndpoint", style: "none", position: { x: lx, y: y1 } },
+ endpoint2: { type: "positionEndpoint", style: "none", position: { x: lx, y: y2 } },
+ stroke: { color: P.structure, width: 1, style: "dashed" },
+ zIndex: 5,
+ });
+ }
+
+ // 6. Connector lines (ONE per Basalt edge, snapped in Lucid's exact px coordinates)
+ for (const e of scene.edges) {
+ let endpoint1: LucidEndpoint;
+ let endpoint2: LucidEndpoint;
+ let startPt: Pt;
+ let endPt: Pt;
+
+ if (e.sequence) {
+ const lf1 = lifeByParticipant.get(e.from);
+ const lf2 = lifeByParticipant.get(e.to);
+ if (!lf1 || !lf2) continue;
+ const pos1 = round6(e.fromPort.y);
+ const pos2 = round6(e.toPort.y);
+ startPt = { x: lf1.x, y: round2(lf1.y1 + pos1 * (lf1.y2 - lf1.y1)) };
+ endPt = { x: lf2.x, y: round2(lf2.y1 + pos2 * (lf2.y2 - lf2.y1)) };
+ endpoint1 = { type: "lineEndpoint", style: "none", lineId: lf1.lineId, position: pos1 };
+ endpoint2 = { type: "lineEndpoint", style: e.openTip ? "openArrow" : "arrow", lineId: lf2.lineId, position: pos2 };
+ } else {
+ const srcBox = shapeBoxById.get(e.from);
+ const dstBox = shapeBoxById.get(e.to);
+ if (!srcBox || !dstBox) continue;
+ const fx = round6(e.fromPort.x);
+ const fy = round6(e.fromPort.y);
+ const tx = round6(e.toPort.x);
+ const ty = round6(e.toPort.y);
+ startPt = { x: round2(srcBox.x + fx * srcBox.w), y: round2(srcBox.y + fy * srcBox.h) };
+ endPt = { x: round2(dstBox.x + tx * dstBox.w), y: round2(dstBox.y + ty * dstBox.h) };
+ endpoint1 = { type: "shapeEndpoint", style: e.fk ? "closedCircle" : "none", shapeId: lucidId("node", e.from), position: { x: fx, y: fy } };
+ endpoint2 = { type: "shapeEndpoint", style: e.openTip ? "openArrow" : "arrow", shapeId: lucidId("node", e.to), position: { x: tx, y: ty } };
+ }
+
+ const rawPts: Pt[] = e.pts.map((p) => ({ x: round2(p.x + pad), y: round2(p.y + pad) }));
+ const snapped = snapRouteToPorts(rawPts, startPt, endPt, e.fromPort.side, e.toPort.side);
+ const innerPts = snapped.slice(1, -1);
+
+ const isMain = e.kind === "main";
+ const isDashed = e.kind === "dashed";
+ const lineObj: LucidLine = {
+ id: `edge_${e.index}`,
+ lineType: innerPts.length > 0 ? "elbow" : "straight",
+ endpoint1,
+ endpoint2,
+ stroke: {
+ color: isMain ? P.edgeMain : P.edgePlain,
+ width: isMain ? 2 : 1,
+ style: isDashed ? "dashed" : "solid",
+ },
+ zIndex: 20,
+ };
+
+ if (innerPts.length > 0) {
+ lineObj.elbowControlPoints = innerPts.map((p) => ({ x: round2(p.x), y: round2(p.y) }));
+ }
+
+ if (e.label) {
+ const texts: LucidLineText[] = [
+ {
+ text: `${escHtml(e.label.text)}`,
+ position: e.label.t,
+ side: e.label.on ? "middle" : "top",
+ },
+ ];
+ if (e.label.note) {
+ texts.push({
+ text: `${escHtml(e.label.note)}`,
+ position: e.label.t,
+ side: "bottom",
+ });
+ }
+ lineObj.text = texts;
+ }
+
+ lines.push(lineObj);
+ }
+
+ return {
+ document: {
+ version: 1,
+ documentSettings: { units: "px" },
+ pages: [
+ {
+ id: lucidId("page", scene.id),
+ title: scene.title || scene.id,
+ settings: {
+ fillColor: P.page,
+ infiniteCanvas: false,
+ autoTiling: true,
+ size: { type: "custom", w: canvasW, h: canvasH },
+ },
+ shapes,
+ lines,
+ },
+ ],
+ },
+ images,
+ };
+}
+
+export function sceneToLucidJson(scene: InteropScene, theme: InteropTheme = "light"): LucidDocument {
+ return buildLucidPayload(scene, theme).document;
+}
+
+export function sceneToLucid(scene: InteropScene, theme: InteropTheme = "light"): Uint8Array {
+ const { document, images } = buildLucidPayload(scene, theme);
+ const entries: ZipEntry[] = [
+ { name: "document.json", data: `${JSON.stringify(document, null, 2)}\n` },
+ ...images.map((img) => ({ name: `images/${img.name}`, data: img.svg })),
+ ];
+ return makeDeterministicZip(entries);
+}
diff --git a/packages/react/src/interop/scene.ts b/packages/react/src/interop/scene.ts
new file mode 100644
index 00000000..1bac54e0
--- /dev/null
+++ b/packages/react/src/interop/scene.ts
@@ -0,0 +1,1548 @@
+// Shared scene builder for @srasyndicate/basalt/diagram-interop (DECISIONS 311, 314).
+// Reads Basalt's model and derived ports through diagram-core's existing exports without editing diagram-core.ts.
+// Produces one normalized InteropScene either headlessly (pure JS + Geist metrics) or from a live figure's Geo.
+// Every connector route is snapped to exact port coordinates so first and last segments are strictly axis-aligned.
+import { buildModel, columnCount, derivedPorts, groupReach } from "../diagram-core";
+import type { DiagramSide, DiagramSpec, GLine, GNode, Geo, MNode, Model, Pt, Rect } from "../diagram-core";
+import type {
+ InteropMarkResolver,
+ InteropOptions,
+ InteropScene,
+ MeasuredBand,
+ MeasuredExtras,
+ MeasuredGroup,
+ MeasuredLane,
+ SceneBand,
+ SceneBox,
+ SceneEdge,
+ SceneGroup,
+ SceneLabel,
+ SceneLane,
+ SceneLifeline,
+ SceneMark,
+ SceneNode,
+ ScenePort,
+ SceneTableRow,
+} from "./types";
+
+// ---- Resolved Basalt theme palette (sRGB hex, matching packages/tokens/tokens/theme.{light,dark}.tokens.json) ----
+
+export interface ThemePalette {
+ page: string;
+ cardFill: string;
+ cardBorder: string;
+ divider: string;
+ focalFill: string;
+ focalBorder: string;
+ focalInk: string;
+ focalQuiet: string;
+ focalRule: string;
+ textPrimary: string;
+ textSecondary: string;
+ textTertiary: string;
+ edgeMain: string;
+ edgePlain: string;
+ structure: string;
+}
+
+export function paletteFor(theme: "light" | "dark"): ThemePalette {
+ if (theme === "dark") {
+ return {
+ page: "#000000",
+ cardFill: "#0a0a0a",
+ cardBorder: "#1f1f1f",
+ divider: "#1f1f1f",
+ focalFill: "#ededed",
+ focalBorder: "#ededed",
+ focalInk: "#000000",
+ focalQuiet: "#595959",
+ focalRule: "#d9d9d9",
+ textPrimary: "#f4f4f4",
+ textSecondary: "#bababa",
+ textTertiary: "#979797",
+ edgeMain: "#f4f4f4",
+ edgePlain: "#bababa",
+ structure: "#616161",
+ };
+ }
+ return {
+ page: "#fafafa",
+ cardFill: "#ffffff",
+ cardBorder: "#e6e6e6",
+ divider: "#e6e6e6",
+ focalFill: "#171717",
+ focalBorder: "#171717",
+ focalInk: "#ffffff",
+ focalQuiet: "#b3b3b3",
+ focalRule: "#262626",
+ textPrimary: "#171717",
+ textSecondary: "#4d4d4d",
+ textTertiary: "#6b6b6b",
+ edgeMain: "#171717",
+ edgePlain: "#4d4d4d",
+ structure: "#8a8a8a",
+ };
+}
+
+// ---- Mark terms allowlist (matches packages/react/marks/manifest.json) ----
+// Official AWS, Azure, Google Cloud and Kubernetes (Apache-2.0) marks explicitly allow use in architecture diagrams.
+// Unofficial edits (the 8 tile-removed AWS icons and third-party community drawings) and marks without diagram-use terms are excluded.
+
+const AWS_UNOFFICIAL_MARKS = [
+ "aws-bedrock",
+ "aws-step-functions",
+ "aws-kinesis",
+ "aws-fargate",
+ "aws-secrets-manager",
+ "aws-cognito",
+ "aws-eks",
+ "aws-kms",
+];
+
+/** Whether a bundled Basalt mark id is permitted for embedding in exported diagrams by its manifest terms. */
+export function isBundledMarkEmbeddable(id: string): boolean {
+ if (!id) return false;
+ if (id === "kubernetes") return true;
+ if (id.startsWith("azure-") || id.startsWith("gcp-")) return true;
+ if (id.startsWith("aws-")) return !AWS_UNOFFICIAL_MARKS.includes(id);
+ return false;
+}
+
+/** Extracts raw `` markup from either raw SVG text or a `data:image/svg+xml,...` URI. */
+export function decodeSvgMarkup(input: string): string | undefined {
+ const s = input.trim();
+ if (!s) return undefined;
+ if (s.startsWith("`
+ );
+}
+
export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light"): string {
const adaptive = theme === "adaptive";
const singleTheme: "light" | "dark" = theme === "dark" ? "dark" : "light";
@@ -376,8 +390,13 @@ export function sceneToDrawio(scene: InteropScene, theme: InteropTheme = "light"
// Embedded service mark (only when marks: "embed" and allowed by manifest terms)
if (n.mark) {
// Focal card uses the opposite theme's mark form because its fill is inverted.
- const useDarkForm = isFocal ? singleTheme === "light" : singleTheme === "dark";
- const svg = useDarkForm ? n.mark.svgDark : n.mark.svgLight;
+ const lightModeSvg = isFocal ? n.mark.svgDark : n.mark.svgLight;
+ const darkModeSvg = isFocal ? n.mark.svgLight : n.mark.svgDark;
+ const svg = adaptive && lightModeSvg !== darkModeSvg
+ ? adaptiveMarkSvg(lightModeSvg, darkModeSvg)
+ : singleTheme === "dark"
+ ? darkModeSvg
+ : lightModeSvg;
const uri = encodeSvgDataUri(svg);
const mx = round2(Math.max(4, worldBox.w - 12 - 16));
const markStyle = cellStyle([
diff --git a/packages/react/src/interop/lucid.ts b/packages/react/src/interop/lucid.ts
index d8cd9d1d..09584554 100644
--- a/packages/react/src/interop/lucid.ts
+++ b/packages/react/src/interop/lucid.ts
@@ -142,7 +142,11 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li
const rowCount = 1 + rows.length + (n.more ? 1 : 0);
const colCount = 3;
const cells: LucidTableCell[] = [];
- const rowSizes: Array<{ index: number; size: number }> = [{ index: 0, size: n.headerH ?? 37 }];
+ // Size header, column, and optional "+ N more" rows from the scene's actual row positions so
+ // userSpecifiedRows sums to exact boundingBox.h and every FK endpoint sits on its row's center.
+ const headerSize = round2(rows.length > 0 ? Math.max(20, rows[0]!.y) : box.h);
+ const rowSizes: Array<{ index: number; size: number }> = [{ index: 0, size: headerSize }];
+ let usedH = headerSize;
// Header row merged across all 3 columns
cells.push({
xPosition: 0,
@@ -154,7 +158,13 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li
for (let r = 0; r < rows.length; r++) {
const row = rows[r]!;
const yPos = r + 1;
- rowSizes.push({ index: yPos, size: round2(row.h) });
+ const size = r < rows.length - 1
+ ? round2(Math.max(16, rows[r + 1]!.y - row.y))
+ : n.more
+ ? round2(Math.max(16, row.h))
+ : round2(Math.max(16, box.h - usedH));
+ rowSizes.push({ index: yPos, size });
+ usedH = round2(usedH + size);
const rightWord = row.refTable ? `→ ${row.refTable}` : row.type ?? "";
cells.push(
{
@@ -181,7 +191,9 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li
}
if (n.more) {
const moreIdx = rows.length + 1;
- rowSizes.push({ index: moreIdx, size: 24 });
+ const moreSize = round2(Math.max(16, box.h - usedH));
+ rowSizes.push({ index: moreIdx, size: moreSize });
+ usedH = round2(usedH + moreSize);
cells.push({
xPosition: 0,
yPosition: moreIdx,
@@ -190,6 +202,12 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li
text: `${escHtml(`+ ${n.more} more`)}
`,
});
}
+ // Absorb any residual rounding delta on the final row so sum(userSpecifiedRows) === box.h strictly.
+ const deltaH = round2(box.h - usedH);
+ if (deltaH !== 0 && rowSizes.length > 0) {
+ const last = rowSizes[rowSizes.length - 1]!;
+ last.size = round2(Math.max(16, last.size + deltaH));
+ }
const keyColW = 36;
const typeColW = Math.max(64, round2(box.w * 0.36));
const nameColW = Math.max(60, round2(box.w - keyColW - typeColW));
@@ -269,6 +287,7 @@ export function buildLucidPayload(scene: InteropScene, theme: InteropTheme = "li
fill: { type: "image", ref: fileName, imageScale: "fit" },
stroke: { color: transparentFill, width: 0 },
},
+ ...(n.mark.attribution ? { customData: [{ key: "attribution", value: n.mark.attribution }] } : {}),
zIndex: 15,
});
}
diff --git a/packages/react/src/interop/scene.ts b/packages/react/src/interop/scene.ts
index 1bac54e0..14f9bf78 100644
--- a/packages/react/src/interop/scene.ts
+++ b/packages/react/src/interop/scene.ts
@@ -84,28 +84,43 @@ export function paletteFor(theme: "light" | "dark"): ThemePalette {
};
}
-// ---- Mark terms allowlist (matches packages/react/marks/manifest.json) ----
-// Official AWS, Azure, Google Cloud and Kubernetes (Apache-2.0) marks explicitly allow use in architecture diagrams.
-// Unofficial edits (the 8 tile-removed AWS icons and third-party community drawings) and marks without diagram-use terms are excluded.
-
-const AWS_UNOFFICIAL_MARKS = [
- "aws-bedrock",
- "aws-step-functions",
- "aws-kinesis",
- "aws-fargate",
- "aws-secrets-manager",
- "aws-cognito",
- "aws-eks",
- "aws-kms",
-];
+// ---- Mark terms allowlist (derived from packages/react/marks/manifest.json at build time) ----
+// Build-time constants injected by packages/react/build.mjs from manifest.json's `unofficial` and `terms.quotes`
+// fields; parsed lazily on first call so loading the module allocates nothing at top level.
+
+declare const __BASALT_EMBEDDABLE_MARKS__: string | undefined;
+declare const __BASALT_MARK_ATTRIBUTIONS__: string | undefined;
+
+let embeddableMarksCache: Set | undefined;
+let markAttributionsCache: Record | undefined;
+
+function getEmbeddableMarks(): Set | null {
+ if (embeddableMarksCache) return embeddableMarksCache;
+ if (typeof __BASALT_EMBEDDABLE_MARKS__ !== "string") return null;
+ embeddableMarksCache = new Set(JSON.parse(__BASALT_EMBEDDABLE_MARKS__) as string[]);
+ return embeddableMarksCache;
+}
+
+function getMarkAttributions(): Record {
+ if (markAttributionsCache) return markAttributionsCache;
+ markAttributionsCache = typeof __BASALT_MARK_ATTRIBUTIONS__ === "string"
+ ? (JSON.parse(__BASALT_MARK_ATTRIBUTIONS__) as Record)
+ : {};
+ return markAttributionsCache;
+}
-/** Whether a bundled Basalt mark id is permitted for embedding in exported diagrams by its manifest terms. */
+/** Whether a bundled Basalt mark id is permitted for embedding in exported diagrams by marks/manifest.json terms. */
export function isBundledMarkEmbeddable(id: string): boolean {
if (!id) return false;
- if (id === "kubernetes") return true;
- if (id.startsWith("azure-") || id.startsWith("gcp-")) return true;
- if (id.startsWith("aws-")) return !AWS_UNOFFICIAL_MARKS.includes(id);
- return false;
+ const set = getEmbeddableMarks();
+ return set ? set.has(id) : false;
+}
+
+/** Returns the manifest licence/trademark attribution string for an embeddable bundled mark, if any. */
+export function bundledMarkAttribution(id: string): string | undefined {
+ if (!id) return undefined;
+ const attrs = getMarkAttributions();
+ return Object.prototype.hasOwnProperty.call(attrs, id) ? attrs[id] : undefined;
}
/** Extracts raw `` markup from either raw SVG text or a `data:image/svg+xml,...` URI. */
@@ -138,11 +153,14 @@ function resolveNodeMark(n: MNode, mode: "omit" | "embed", resolver?: InteropMar
const svgLight = rawLight ? decodeSvgMarkup(rawLight) : undefined;
const svgDark = rawDark ? decodeSvgMarkup(rawDark) : svgLight;
if (!svgLight || !svgDark) return undefined;
- return { id: n.mark.id, svgLight, svgDark };
+ return { id: n.mark.id, svgLight, svgDark, attribution: bundledMarkAttribution(n.mark.id) };
}
if (n.mark.onLight) {
- const svgLight = decodeSvgMarkup(n.mark.onLight);
- const svgDark = n.mark.onDark ? decodeSvgMarkup(n.mark.onDark) : svgLight;
+ const rawLight = decodeSvgMarkup(n.mark.onLight) ?? (resolver ? resolver(n.mark.onLight, "light") : undefined);
+ const svgLight = rawLight ? decodeSvgMarkup(rawLight) : undefined;
+ const darkSrc = n.mark.onDark ?? n.mark.onLight;
+ const rawDark = decodeSvgMarkup(darkSrc) ?? (resolver ? resolver(darkSrc, "dark") : undefined);
+ const svgDark = rawDark ? decodeSvgMarkup(rawDark) : svgLight;
if (!svgLight || !svgDark) return undefined;
return { id: `custom-${n.id}`, svgLight, svgDark };
}
@@ -251,7 +269,8 @@ function insideShape(p: Pt, n: GNode, pad: number): boolean {
if (n.shape === "terminal") {
const rr = Math.min(hw, hh);
const ex = Math.min(Math.max(p.x, l + rr), r - rr);
- return Math.hypot(p.x - ex, p.y - cy) < rr - pad;
+ const dx = p.x - ex, dy = p.y - cy;
+ return Math.sqrt(dx * dx + dy * dy) < rr - pad;
}
return p.x > l + pad && p.x < r - pad && p.y > t + pad && p.y < b - pad;
}
@@ -269,18 +288,20 @@ function boxHitsShape(box: Rect, n: GNode): boolean {
if (hit(box, { l: l + rr, r: r - rr, t, b })) return true;
for (const ex of [l + rr, r - rr]) {
const px = Math.max(box.l, Math.min(ex, box.r)), py = Math.max(box.t, Math.min(cy, box.b));
- if (Math.hypot(px - ex, py - cy) < rr - 0.01) return true;
+ const dx = px - ex, dy = py - cy;
+ if (Math.sqrt(dx * dx + dy * dy) < rr - 0.01) return true;
}
return false;
}
function segmentThrough(a: Pt, b: Pt, n: GNode): boolean {
- const len = Math.hypot(b.x - a.x, b.y - a.y);
+ const dx = b.x - a.x, dy = b.y - a.y;
+ const len = Math.sqrt(dx * dx + dy * dy);
const steps = Math.max(2, Math.ceil(len / 2));
for (let k = 1; k < steps; k++) {
const f = k / steps;
if (f * len < 1.5 || (1 - f) * len < 1.5) continue;
- if (insideShape({ x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f }, n, 1)) return true;
+ if (insideShape({ x: a.x + dx * f, y: a.y + dy * f }, n, 1)) return true;
}
return false;
}
@@ -418,12 +439,14 @@ function labelArcFraction(pts: readonly Pt[], box: SceneBox): number {
let total = 0;
const segLens: number[] = [];
for (let i = 1; i < pts.length; i++) {
- const len = Math.hypot(pts[i]!.x - pts[i - 1]!.x, pts[i]!.y - pts[i - 1]!.y);
+ const dx = pts[i]!.x - pts[i - 1]!.x;
+ const dy = pts[i]!.y - pts[i - 1]!.y;
+ const len = Math.abs(dx) < 1e-9 || Math.abs(dy) < 1e-9 ? Math.abs(dx) + Math.abs(dy) : Math.sqrt(dx * dx + dy * dy);
segLens.push(len);
total += len;
}
if (total <= 1e-6) return 0.5;
- let bestDist = Infinity;
+ let bestDist2 = Infinity;
let bestAlong = total / 2;
let acc = 0;
for (let i = 1; i < pts.length; i++) {
@@ -432,9 +455,10 @@ function labelArcFraction(pts: readonly Pt[], box: SceneBox): number {
const len2 = dx * dx + dy * dy;
const u = len2 > 0 ? Math.max(0, Math.min(1, ((cx - a.x) * dx + (cy - a.y) * dy) / len2)) : 0;
const px = a.x + u * dx, py = a.y + u * dy;
- const d = Math.hypot(cx - px, cy - py);
- if (d < bestDist) {
- bestDist = d;
+ const ex = cx - px, ey = cy - py;
+ const d2 = ex * ex + ey * ey;
+ if (d2 < bestDist2) {
+ bestDist2 = d2;
bestAlong = acc + u * segLens[i - 1]!;
}
acc += segLens[i - 1]!;
@@ -1306,9 +1330,12 @@ export function sceneFromMeasured(
// Lanes
const sceneLanes: SceneLane[] = [];
if (m.type === "data-flow") {
- const extraById = new Map((extras.lanes ?? []).map((l) => [l.id, l]));
+ const extraLanes = extras.lanes ?? [];
+ const extraById = new Map(extraLanes.map((l) => [l.id, l]));
+ const extraByIndex = new Map();
+ extraLanes.forEach((l, k) => extraByIndex.set(l.index ?? k, l));
const rowBounds: Array<[number, number]> = m.lanes.map((lane, idx) => {
- const el = extraById.get(lane.id);
+ const el = extraById.get(lane.id) ?? extraByIndex.get(idx);
if (el) return [el.rect.t, el.rect.b];
const members = sceneNodes.filter((n) => n.laneIndex === idx);
if (members.length) return [Math.min(...members.map((x) => x.box.y)), Math.max(...members.map((x) => x.box.y + x.box.h))];
@@ -1518,7 +1545,7 @@ export function readMeasuredExtras(fig: Element, prefix = "basalt-diagram"): Mea
drawing.querySelectorAll(`.${prefix}-lane`).forEach((el, idx) => {
if (!el.getClientRects().length) return;
const label = el.querySelector(`.${prefix}-lane-name`)?.textContent ?? "";
- lanes.push({ id: `lane-${idx}`, label, rect: rectOf(el) });
+ lanes.push({ id: `lane-${idx}`, index: idx, label, rect: rectOf(el) });
});
const bands: MeasuredBand[] = [];
diff --git a/packages/react/src/interop/types.ts b/packages/react/src/interop/types.ts
index d1a31569..955e2a17 100644
--- a/packages/react/src/interop/types.ts
+++ b/packages/react/src/interop/types.ts
@@ -32,6 +32,8 @@ export interface MeasuredGroup {
export interface MeasuredLane {
id: string;
+ /** 0-based lane index matching the DOM order of `.diagram-lane` elements. */
+ index?: number;
label: string;
rect: Rect;
}
@@ -75,6 +77,8 @@ export interface SceneMark {
svgLight: string;
/** Raw SVG markup for dark ground. */
svgDark: string;
+ /** Licence/trademark attribution from marks/manifest.json, when the mark carries one. */
+ attribution?: string;
}
export interface SceneTableRow {
diff --git a/packages/react/src/interop/vsdx.ts b/packages/react/src/interop/vsdx.ts
index 77f17cdb..8685ece3 100644
--- a/packages/react/src/interop/vsdx.ts
+++ b/packages/react/src/interop/vsdx.ts
@@ -130,19 +130,81 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
});
let nextId = 1;
+ const bgId = singleTheme === "dark" ? nextId++ : 0;
+ const groupSheetId = new Map();
+ for (const g of scene.groups) groupSheetId.set(g.id, nextId++);
+ const laneSheetIds = scene.lanes.map(() => nextId++);
+ const lifeSheetIds = scene.lifelines.map(() => nextId++);
+ const bandSheetIds = scene.bands.map(() => nextId++);
+ const nodeSheetId = new Map();
+ for (const n of scene.nodes) nodeSheetId.set(n.id, nextId++);
+
const shapeXml: string[] = [];
const connectXml: string[] = [];
const placed = new Map();
const mediaFiles: Array<{ rId: string; fileName: string; svg: string }> = [];
+ const attributions: string[] = [];
- // 1. Architecture groups (behind nodes)
+ // 0. Dark-theme locked full-page surface-page background (Visio pages default to white)
+ if (bgId) {
+ shapeXml.push(
+ ` \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | \n` +
+ ` | |
\n` +
+ ` | |
\n` +
+ ` | |
\n` +
+ ` | |
\n` +
+ ` | |
\n` +
+ ` \n` +
+ ` `,
+ );
+ }
+
+ // 1. Architecture groups as real Visio Containers (User.msvStructureType="Container" + Relationships)
for (const g of scene.groups) {
- const id = nextId++;
+ const id = groupSheetId.get(g.id)!;
const wIn = n6(g.box.w / DPI);
const hIn = n6(g.box.h / DPI);
const pinX = toVisioX(g.box.x + g.box.w / 2);
const pinY = toVisioY(g.box.y + g.box.h / 2);
const radIn = n6(12 / DPI);
+ const memberIds = g.members.map((mid) => nodeSheetId.get(mid)).filter((x): x is number => x !== undefined);
+ const relCell = memberIds.length
+ ? ` | \n`
+ : "";
shapeXml.push(
` \n` +
` | \n` +
@@ -163,6 +225,13 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
` | \n` +
` | \n` +
` | \n` +
+ relCell +
+ ` \n` +
+ ` |
\n` +
+ ` |
\n` +
+ ` |
\n` +
+ ` |
\n` +
+ ` \n` +
` \n` +
@@ -187,7 +256,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
// 2. Data-flow lanes (behind step cards)
for (let k = 0; k < scene.lanes.length; k++) {
const lane = scene.lanes[k]!;
- const id = nextId++;
+ const id = laneSheetIds[k]!;
const wIn = n6(lane.box.w / DPI);
const hIn = n6(lane.box.h / DPI);
const pinX = toVisioX(lane.box.x + lane.box.w / 2);
@@ -229,8 +298,9 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
}
// 3. Sequence lifelines & phase bands
- for (const lf of scene.lifelines) {
- const id = nextId++;
+ for (let lfIdx = 0; lfIdx < scene.lifelines.length; lfIdx++) {
+ const lf = scene.lifelines[lfIdx]!;
+ const id = lifeSheetIds[lfIdx]!;
const wIn = n6(2 / DPI);
const hIn = n6(Math.max(1, lf.y2 - lf.y1) / DPI);
const pinX = toVisioX(lf.x);
@@ -268,7 +338,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
for (let bIdx = 0; bIdx < scene.bands.length; bIdx++) {
const band = scene.bands[bIdx]!;
- const id = nextId++;
+ const id = bandSheetIds[bIdx]!;
const wIn = n6(band.w / DPI);
const hIn = n6(band.h / DPI);
const pinX = toVisioX(band.w / 2);
@@ -309,7 +379,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
// 4. Node shapes
for (const n of scene.nodes) {
- const id = nextId++;
+ const id = nodeSheetId.get(n.id)!;
const wIn = n6(n.box.w / DPI);
const hIn = n6(n.box.h / DPI);
const pinX = toVisioX(n.box.x + n.box.w / 2);
@@ -505,6 +575,10 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
const { charRows, textRuns } = buildNodeTextRuns(n, P);
const connRowsXml = renderConnectionRows(conns, wIn, hIn);
const geomXml = buildNodeGeometryXml(n, wIn, hIn);
+ const parentGroupId = n.group ? groupSheetId.get(n.group) : undefined;
+ const memberRelCell = parentGroupId
+ ? ` | \n`
+ : "";
shapeXml.push(
` \n` +
@@ -529,6 +603,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
` | \n` +
` | \n` +
` | \n` +
+ memberRelCell +
` \n` +
`${charRows.join("\n")}\n` +
` \n` +
@@ -542,6 +617,7 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
);
if (n.mark) {
+ if (n.mark.attribution && !attributions.includes(n.mark.attribution)) attributions.push(n.mark.attribution);
const markId = nextId++;
const rId = `rId${mediaFiles.length + 1}`;
const fileName = `mark_${mediaFiles.length + 1}.svg`;
@@ -710,12 +786,16 @@ export function sceneToVsdx(scene: InteropScene, theme: InteropTheme = "light"):
` \n` +
`\n`;
+ const descLine = attributions.length
+ ? ` ${escXml(attributions.join(" "))}\n`
+ : "";
const docXml =
`\n` +
`\n` +
` \n` +
` ${escXml(scene.title || scene.id)}\n` +
` Basalt Diagram Exporter\n` +
+ descLine +
` \n` +
` \n` +
` \n` +
From 7cb998c528b166e65bc5842f683433629698c800 Mon Sep 17 00:00:00 2001
From: bailey <74082460+bmjcoding@users.noreply.github.com>
Date: Mon, 23 Nov 2026 19:32:40 -0600
Subject: [PATCH 05/19] basalt-diagram-export: works through npm's .bin link;
packaged --browser; custom mark files; --out checks
From Opus's code review of the converter (DECISIONS 327).
- B1: the main-module check compares real paths, so the CLI runs when
npm links it as node_modules/.bin/basalt-diagram-export (a symlink).
package-lock.json records the package's bin. verify-packages.mjs puts
the bin in the packed consumer's lock entry (so `npm ci` links it, as
a real install does), runs the CLI through the link, and checks it
wrote .drawio, .vsdx and .lucid, a dark draw.io background and the dark
.vsdx page shape. It also prints an assertion's message now, which the
catch used to swallow.
- --browser from a packed install (and polish 6): the harness serves
only the package's own dist (styles.css, the Geist files,
diagram-core.js, diagram-interop.js) to headless Chromium, so it no
longer needs the repo's HTML skill. Playwright is not a dependency:
without it the CLI exits with "npm install -D playwright && npx
playwright install chromium", which verify-packages checks.
- Polish 9: a custom mark's file path is read relative to the input
file; a missing file, a non-SVG file or a remote URL is a warning on
stderr, not a silent omission.
- Polish 10: --out with a file extension needs one diagram and one
format, and the extension must match the format.
- The skill and diagram.md give the in-repo form of the command
(node packages/react/bin/basalt-diagram-export.mjs after npm run
build). SKILL.md is 12,642 of its 12,650 B.
- Polish 11: f92f416f also reworded steps 1 to 3 of SKILL.md to make
room for the export rule; that commit didn't say so. They were
shortened: step 1's "the classes, attributes and tags that bring it
in" became "its triggers", step 3's "the modules your classes,
attributes and tags use" became "the modules you use", and "only for a
file a tool reads, never a file a person opens" became "tools only,
never for readers".
Co-Authored-By: Gemini Neon
Co-Authored-By: Claude Opus 5.5
---
.agent/skills/basalt-html/SKILL.md | 2 +-
.../skills/basalt-html/parts/usage/diagram.md | 2 +-
package-lock.json | 3 +
packages/react/bin/basalt-diagram-export.mjs | 352 ++++++++++--------
scripts/verify-packages.mjs | 35 +-
tools/html-skill/src/usage/diagram.md | 2 +-
6 files changed, 246 insertions(+), 150 deletions(-)
diff --git a/.agent/skills/basalt-html/SKILL.md b/.agent/skills/basalt-html/SKILL.md
index 5cfeb8cf..2e1f2117 100644
--- a/.agent/skills/basalt-html/SKILL.md
+++ b/.agent/skills/basalt-html/SKILL.md
@@ -104,5 +104,5 @@ Your own CSS goes in a `` +
+ `` +
+ `` +
+ `