Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix(renderers): integrate label canvas containment on dev

tt-a1ifc437920cb83
diff --cc archify.zip
index e436ded2,340bfac3..62ac63aa
Binary files differ
diff --cc archify/renderers/architecture/render-architecture.mjs
index d92aa9dc,5046f919..38ce299d
--- a/archify/renderers/architecture/render-architecture.mjs
+++ b/archify/renderers/architecture/render-architecture.mjs
@@@ -22,11 -22,20 +22,12 @@@ import
cleanBorderRunProblems,
cleanRouteRhythmProblems,
cleanLabelRouteClearanceProblems,
+ cleanLabelCanvasContainmentProblems,
suggestLabelObstacleFix,
suggestComponentSeparation,
- anchor,
- automaticPortSpread,
- automaticPortRhythmBridge,
- defaultFromSide,
- defaultToSide,
- chosenSide,
- routeHonorsEndpointSides,
- normalizeRoutePoints,
polylinePath,
routePointsValue,
- roundedPath,
+ authoredStraightRouteAttrs,
labelPoint,
componentFill,
componentText,
@@@ -140,7 -149,29 +141,28 @@@ const architectureLegendEntries = resol
new Set([...components.values()].map((component) => component.type)),
);
- function autoViewBoxFor(candidateBoundaries) {
-
+ // One source for connection label geometry: the rect the containment rule
+ // measures is the rect the SVG mask draws, the auto canvas covers, the legend
+ // avoids, and the layout report publishes.
+ function connectionLabelBox(conn) {
+ if (!conn.label) return null;
+ const [lx, ly] = labelPoint(conn, pathFor(conn).points);
+ const width = Math.max(30, textUnits(conn.label) * 4.8 + 10);
+ return { x: lx - width / 2, y: ly - 10, width, height: 14, lx, ly };
+ }
+
+ function connectionLabelRects() {
+ const rects = [];
+ for (const [relationIndex, conn] of asArray(arch.connections).entries()) {
+ if (!components.has(conn.from) || !components.has(conn.to)) continue;
+ const box = connectionLabelBox(conn);
+ if (!box) continue;
+ rects.push({ relation: conn, relationIndex, label: conn.label, ...box });
+ }
+ return rects;
+ }
+
+ function autoViewBoxFor(candidateBoundaries, extraRects = []) {
const maxX = Math.max(
0,
...[...components.values()].map((component) => component.x + component.width),
@@@ -268,6 -301,26 +292,17 @@@ function layoutBoundaryTitles(rawBounda
});
}
+ // ---- Routing state ----------------------------------------------------------
+ // Initialized before the boundary-title work below: connection label rects are
+ // part of the derived canvas, so the title convergence must measure the same
+ // width the diagram actually renders into (a title sized for a narrower canvas
+ // would fall below the desktop-readability floor once labels grow it). Routing
+ // reads only components and connections, never boundaries or the viewBox.
-const OUTWARD_SIDE_VECTOR = {
- left: [-1, 0],
- right: [1, 0],
- top: [0, -1],
- bottom: [0, 1],
-};
-const AUTOMATIC_PORT_CORNER_GUTTER = 16;
-const AUTOMATIC_PORT_ALIGNMENT_DELTA = 16;
-const pathCache = new Map();
-const automaticPorts = automaticPortSpread(arch.connections, components);
++const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections);
+ // The auto canvas has to cover these rects; an authored viewBox is never
+ // resized to fit them — there the containment rule reports the clipping.
+ const connectionLabels = connectionLabelRects();
+
const rawBoundaries = asArray(arch.boundaries).map(boundaryRect).filter(Boolean);
function resolveBoundaryTitles() {
if (!enforcesBoundaryTitleComposition || rawBoundaries.length === 0) {
@@@ -628,9 -682,304 +664,6 @@@ function buildLayoutReport()
};
}
--// ---- Connection routing ------------------------------------------------------
- const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections);
-function routeClearsComponents(conn, points, clearance = 2) {
- const endpointIds = new Set([conn.from, conn.to]);
- for (const component of components.values()) {
- if (endpointIds.has(component.id)) continue;
- for (let index = 0; index < points.length - 1; index += 1) {
- if (segmentIntersectsRect({ start: points[index], end: points[index + 1] }, component, clearance)) {
- return false;
- }
- }
- }
- return true;
-}
-
-function routeClearsEndpointComponents(points, from, to) {
- const lastSegment = points.length - 2;
- for (let index = 0; index <= lastSegment; index += 1) {
- const segment = { start: points[index], end: points[index + 1] };
- if (index > 0 && segmentIntersectsRect(segment, from)) return false;
- if (index < lastSegment && segmentIntersectsRect(segment, to)) return false;
- }
- return true;
-}
-
-function outwardStub(point, side, distance = 24) {
- const [dx, dy] = OUTWARD_SIDE_VECTOR[side] || [0, 0];
- return [point[0] + dx * distance, point[1] + dy * distance];
-}
-
-function collinearBacktrack(a, b, c) {
- const first = [b[0] - a[0], b[1] - a[1]];
- const second = [c[0] - b[0], c[1] - b[1]];
- const cross = first[0] * second[1] - first[1] * second[0];
- const dot = first[0] * second[0] + first[1] * second[1];
- return Math.abs(cross) <= 0.0001 && dot < -0.0001;
-}
-
-function sideAwareBridgeCandidates(start, end, fromSide, toSide) {
- const startStub = outwardStub(start, fromSide);
- const endStub = outwardStub(end, toSide);
- const rawCandidates = [];
- const minimumBridge = 16;
- const verticalSides = new Set(['top', 'bottom']);
- const horizontalSides = new Set(['left', 'right']);
-
- // Port spreading can leave parallel-side anchors only a few pixels apart.
- // Route through a bounded outside channel so we keep both endpoint normals
- // without introducing a tiny, noisy connector between the two stubs.
- if (verticalSides.has(fromSide) && verticalSides.has(toSide)
- && Math.abs(start[0] - end[0]) < minimumBridge) {
- for (const channelX of [
- Math.max(start[0], end[0]) + minimumBridge,
- Math.min(start[0], end[0]) - minimumBridge,
- ]) {
- rawCandidates.push([
- startStub,
- [channelX, startStub[1]],
- [channelX, endStub[1]],
- endStub,
- ]);
- }
- }
- if (horizontalSides.has(fromSide) && horizontalSides.has(toSide)
- && Math.abs(start[1] - end[1]) < minimumBridge) {
- for (const channelY of [
- Math.max(start[1], end[1]) + minimumBridge,
- Math.min(start[1], end[1]) - minimumBridge,
- ]) {
- rawCandidates.push([
- startStub,
- [startStub[0], channelY],
- [endStub[0], channelY],
- endStub,
- ]);
- }
- }
-
- rawCandidates.push(
- [startStub, [endStub[0], startStub[1]], endStub],
- [startStub, [startStub[0], endStub[1]], endStub],
- );
- return rawCandidates.map((candidate) => normalizeRoutePoints([start, ...candidate, end]))
- .filter((points) => points.length >= 2)
- .filter((points) => !collinearBacktrack(points[0], points[1], points[2] || points[1]))
- .filter((points) => !collinearBacktrack(points.at(-3) || points.at(-2), points.at(-2), points.at(-1)))
- .filter((points) => routeHonorsEndpointSides(points, fromSide, toSide))
- .map((points) => points.slice(1, -1));
-}
-
-function portHasCornerClearance(rect, side, point) {
- if (side === 'left' || side === 'right') {
- const inset = Math.min(AUTOMATIC_PORT_CORNER_GUTTER, rect.height / 2);
- return point[1] >= rect.y + inset && point[1] <= rect.y + rect.height - inset;
- }
- if (side === 'top' || side === 'bottom') {
- const inset = Math.min(AUTOMATIC_PORT_CORNER_GUTTER, rect.width / 2);
- return point[0] >= rect.x + inset && point[0] <= rect.x + rect.width - inset;
- }
- return false;
-}
-
-function alignFacingPorts(conn, from, to, start, end, fromSide, toSide, ports) {
- const hasExplicitGeometry = (
- conn.via
- || (conn.route && conn.route !== 'auto')
- || conn.channelX !== undefined
- || conn.channelY !== undefined
- || conn.labelAt
- );
- const horizontallyFacing = (
- (fromSide === 'right' && toSide === 'left')
- || (fromSide === 'left' && toSide === 'right')
- );
- const verticallyFacing = (
- (fromSide === 'bottom' && toSide === 'top')
- || (fromSide === 'top' && toSide === 'bottom')
- );
- if (hasExplicitGeometry || (!horizontallyFacing && !verticallyFacing)) return { start, end };
-
- const fromSpread = Boolean(ports?.from);
- const toSpread = Boolean(ports?.to);
- if (fromSpread && toSpread) return { start, end };
- const hasExplicitSides = (
- (conn.fromSide && conn.fromSide !== 'auto')
- || (conn.toSide && conn.toSide !== 'auto')
- );
- if (!fromSpread && !toSpread && hasExplicitSides) return { start, end };
-
- const alignmentDelta = horizontallyFacing
- ? Math.abs(start[1] - end[1])
- : Math.abs(start[0] - end[0]);
- if (alignmentDelta >= AUTOMATIC_PORT_ALIGNMENT_DELTA) return { start, end };
-
- // Keep the shared endpoint's distinct spread slot and move only the
- // relationship's unshared endpoint onto that axis. With no spread endpoint,
- // retain the existing least-movement choice between the two facing sides.
- // If both endpoints are shared, preserve the outside bridge so no competing
- // port is silently collapsed.
- const alignEndToStart = horizontallyFacing
- ? { start, end: [end[0], start[1]] }
- : { start, end: [start[0], end[1]] };
- const alignStartToEnd = horizontallyFacing
- ? { start: [start[0], end[1]], end }
- : { start: [end[0], start[1]], end };
- const candidates = fromSpread
- ? [alignEndToStart]
- : toSpread
- ? [alignStartToEnd]
- : [alignEndToStart, alignStartToEnd];
- for (const candidate of candidates) {
- const points = [candidate.start, candidate.end];
- if (portHasCornerClearance(from, fromSide, candidate.start)
- && portHasCornerClearance(to, toSide, candidate.end)
- && routeHonorsEndpointSides(points, fromSide, toSide)
- && routeClearsEndpointComponents(points, from, to)
- && routeClearsComponents(conn, points)) {
- return candidate;
- }
- }
- return { start, end };
-}
-
-function routeVia(conn, from, to, start, end, fromSide, toSide) {
- if (conn.via) return conn.via;
- switch (conn.route || 'auto') {
- case 'straight':
- return [];
- case 'orthogonal-h': {
- const midX = (start[0] + end[0]) / 2;
- return [[midX, start[1]], [midX, end[1]]];
- }
- case 'orthogonal-v': {
- const midY = (start[1] + end[1]) / 2;
- return [[start[0], midY], [end[0], midY]];
- }
- case 'auto':
- default: {
- // Direct line unless the anchors are clearly orthogonal-friendly.
- const deltaX = Math.abs(start[0] - end[0]);
- const deltaY = Math.abs(start[1] - end[1]);
- if ((deltaX < 4 || deltaY < 4) && routeHonorsEndpointSides([start, end], fromSide, toSide)) return [];
-
- const rhythmBridge = automaticPortRhythmBridge(start, end, fromSide, toSide, {
- accept: (points) => (
- routeClearsEndpointComponents(points, from, to)
- && routeClearsComponents(conn, points)
- ),
- });
- if (rhythmBridge) return rhythmBridge.slice(1, -1);
-
- // Automatic port spreading can leave otherwise aligned endpoints only a
- // few pixels apart. A midpoint route would split that tiny difference
- // into two unreadable endpoint stubs, so take a bounded outside channel
- // when both anchors sit on parallel component sides.
- const minimumStub = 8;
- const fromVerticalSide = start[1] === from.y || start[1] === from.y + from.height;
- const toVerticalSide = end[1] === to.y || end[1] === to.y + to.height;
- if (fromVerticalSide && toVerticalSide && deltaX < minimumStub * 2) {
- const outsideChannels = [
- Math.max(start[0], end[0]) + minimumStub * 2,
- Math.min(start[0], end[0]) - minimumStub * 2,
- ];
- for (const channelX of outsideChannels) {
- const candidate = [[channelX, start[1]], [channelX, end[1]]];
- const points = [start, ...candidate, end];
- if (routeHonorsEndpointSides(points, fromSide, toSide) && routeClearsComponents(conn, points)) return candidate;
- }
- }
-
- const fromHorizontalSide = start[0] === from.x || start[0] === from.x + from.width;
- const toHorizontalSide = end[0] === to.x || end[0] === to.x + to.width;
- if (fromHorizontalSide && toHorizontalSide && deltaY < minimumStub * 2) {
- const outsideChannels = [
- Math.max(start[1], end[1]) + minimumStub * 2,
- Math.min(start[1], end[1]) - minimumStub * 2,
- ];
- for (const channelY of outsideChannels) {
- const candidate = [[start[0], channelY], [end[0], channelY]];
- const points = [start, ...candidate, end];
- if (routeHonorsEndpointSides(points, fromSide, toSide) && routeClearsComponents(conn, points)) return candidate;
- }
- }
-
- const midX = (start[0] + end[0]) / 2;
- const horizontalFirst = [[midX, start[1]], [midX, end[1]]];
- const midY = (start[1] + end[1]) / 2;
- const verticalFirst = [[start[0], midY], [end[0], midY]];
- const candidates = [horizontalFirst, verticalFirst];
- const sideSafe = candidates.filter((candidate) => (
- routeHonorsEndpointSides([start, ...candidate, end], fromSide, toSide)
- ));
- const sideAware = sideAwareBridgeCandidates(start, end, fromSide, toSide);
- const nearParallelPorts = (
- ((fromSide === 'top' || fromSide === 'bottom')
- && (toSide === 'top' || toSide === 'bottom')
- && deltaX < minimumStub * 2)
- || ((fromSide === 'left' || fromSide === 'right')
- && (toSide === 'left' || toSide === 'right')
- && deltaY < minimumStub * 2)
- );
- const ordered = [
- ...(nearParallelPorts ? sideAware : sideSafe),
- ...(nearParallelPorts ? sideSafe : sideAware),
- ...candidates.filter((candidate) => !sideSafe.includes(candidate)),
- ];
- for (const candidate of ordered) {
- const points = [start, ...candidate, end];
- if (routeClearsEndpointComponents(points, from, to) && routeClearsComponents(conn, points)) return candidate;
- }
-
- // Both bounded doglegs are blocked. Keep the best endpoint-safe route
- // when one exists so the universal Clean Flow gate reports the actual
- // obstacle; otherwise preserve the historical deterministic fallback
- // and let the endpoint-direction gate explain the side mismatch.
- return sideSafe[0] || sideAware[0] || horizontalFirst;
- }
- }
-}
-
-function connectionSides(conn) {
- const from = components.get(conn.from);
- const to = components.get(conn.to);
- return {
- fromSide: chosenSide(conn.fromSide, defaultFromSide(from, to)),
- toSide: chosenSide(conn.toSide, defaultToSide(from, to)),
- };
-}
-
-function connectionEndpointSide(conn, endpoint) {
- const field = endpoint === 'source' ? 'fromSide' : 'toSide';
- if (conn[field] && conn[field] !== 'auto') return conn[field];
- return connectionSides(conn)[field];
-}
-
-function pathFor(conn) {
- if (pathCache.has(conn)) return pathCache.get(conn);
- const from = components.get(conn.from);
- const to = components.get(conn.to);
- const ports = automaticPorts.get(conn);
- const { fromSide, toSide } = connectionSides(conn);
- const baseStart = ports?.from || anchor(from, fromSide);
- const baseEnd = ports?.to || anchor(to, toSide);
- const { start, end } = alignFacingPorts(
- conn,
- from,
- to,
- baseStart,
- baseEnd,
- fromSide,
- toSide,
- ports,
- );
- const points = [start, ...routeVia(conn, from, to, start, end, fromSide, toSide), end];
- const routed = { d: roundedPath(points, 8), points };
- pathCache.set(conn, routed);
- return routed;
-}
--
// ---- Rendering ---------------------------------------------------------------
function renderBoundaryFrame(b, index) {
const cls = b.kind === 'security-group' ? 'c-security-group' : 'c-region';
@@@ -654,12 -1003,11 +687,11 @@@ function renderConnectionPath(conn, ind
}
function renderConnectionLabel(conn, index) {
- if (!conn.label) return '';
- const [lx, ly] = labelPoint(conn, pathFor(conn).points);
- const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);
+ const box = connectionLabelBox(conn);
+ if (!box) return '';
return ` <g data-detail="context" ${focusEdgeAttrs(conn.from, conn.to, conn.label, index, conn.id)}>
- <rect x="${lx - w / 2}" y="${ly - 10}" width="${w}" height="14" rx="3" class="c-mask"/>
- <text x="${lx}" y="${ly}" class="${edgeLabelAccent(conn.variant)}" font-size="8" text-anchor="middle">${esc(conn.label)}</text>
+ <rect x="${box.x}" y="${box.y}" width="${box.width}" height="${box.height}" rx="3" class="c-mask"/>
- <text x="${box.lx}" y="${box.ly}" class="${variantAccent(conn.variant)}" font-size="8" text-anchor="middle">${esc(conn.label)}</text>
++ <text x="${box.lx}" y="${box.ly}" class="${edgeLabelAccent(conn.variant)}" font-size="8" text-anchor="middle">${esc(conn.label)}</text>
</g>`;
}
diff --cc archify/scripts/check-render-output.mjs
index 3ac2d12d,15607cbc..9d10fdb6
--- a/archify/scripts/check-render-output.mjs
+++ b/archify/scripts/check-render-output.mjs
@@@ -2,7 -2,7 +2,7 @@@
import fs from 'node:fs';
import path from 'node:path';
- import { collectAmbiguousCorridors, collectBorderRuns, collectLabelRouteClearance, collectRouteRhythmIssues, minimumLabelRouteClearance, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';
-import { collectAmbiguousCorridors, collectBorderRuns, collectLabelCanvasOverflow, collectLabelRouteClearance, collectRouteRhythmIssues, describeLabelCanvasOverflow, formatRect, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';
++import { collectAmbiguousCorridors, collectBorderRuns, collectLabelCanvasOverflow, collectLabelRouteClearance, collectRouteRhythmIssues, describeLabelCanvasOverflow, formatRect, minimumLabelRouteClearance, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';
import {
DESKTOP_READABILITY_VIEWPORT,
DESKTOP_READER_DIAGRAM_WIDTH,
@@@ -170,7 -154,10 +181,8 @@@ if (svgMatches.length === 1)
ambiguousCorridors: ambiguousCorridors.length,
containerBorderRuns: containerBorderRuns.length,
labelRouteClearanceIssues: labelRouteClearance.length,
+ labelCanvasOverflowIssues: labelCanvasOverflow.length,
- minLabelRouteClearance: labelRouteMeasurements.length
- ? Math.round(Math.min(...labelRouteMeasurements.map((hit) => hit.clearance)) * 10) / 10
- : null,
+ minLabelRouteClearance: minimumLabelRouteClearance(labelRouteMeasurements),
desktopReadabilityIssues: desktopReadabilityIssue ? 1 : 0,
minProjectedNodeTextPx: desktopReadabilityIssue?.projectedFontPx ?? null,
...roundedRouteMetrics(routeMetrics),
diff --cc archify/test/layout-rules.test.mjs
index 433f3975,e4d018ea..2847625a
--- a/archify/test/layout-rules.test.mjs
+++ b/archify/test/layout-rules.test.mjs
@@@ -1073,6 -1068,344 +1074,344 @@@ test('sequence: showcase rejects a mess
assert.match(stderr, /customer authorization context.*dashboard-request/);
});
+ // A label rect that leaves the viewBox is clipped by the SVG canvas, so the
+ // artifact ships truncated text while every post-render check still passes.
+ function offCanvasLabelDocument() {
+ return {
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Off-canvas label', quality_profile: 'showcase', viewBox: [720, 400] },
+ components: [
+ { id: 'left', type: 'frontend', label: 'Left', pos: [60, 160], size: [120, 54] },
+ { id: 'right', type: 'backend', label: 'Right', pos: [420, 160], size: [120, 54] },
+ ],
+ connections: [{
+ id: 'left-to-right',
+ from: 'left',
+ to: 'right',
+ label: 'a very long edge label that runs off the canvas',
+ labelAt: [640, 140],
+ }],
+ };
+ }
+
+ test('architecture: showcase rejects a connection label that leaves the canvas', () => {
+ const { code, stderr } = render('architecture', offCanvasLabelDocument());
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /\[composition\/label-canvas-containment\] showcase architecture label "a very long edge label that runs off the canvas" on connections\[0\] id "left-to-right"/);
+ assert.match(stderr, /extends past the right edge by 37\.8px/);
+ assert.match(stderr, /viewBox 720x400/);
+ assert.match(stderr, /labelAt.*labelDx.*labelDy.*labelSegment/);
+ });
+
+ test('architecture: standard keeps a label that leaves the canvas renderable', () => {
+ const d = offCanvasLabelDocument();
+ d.meta.quality_profile = 'standard';
+ const { code, stderr } = render('architecture', d);
+ assert.equal(code, 0, stderr);
+ });
+
+ // The same pin is a defect on the fixed-v1 canvas and a legitimate layout on
+ // readable-v2; see collectLabelCanvasOverflow in renderers/shared/geometry.mjs.
+ function offCanvasWorkflowLabelDocument(schemaVersion) {
+ return {
+ schema_version: schemaVersion,
+ diagram_type: 'workflow',
+ meta: {
+ title: 'Workflow label off canvas',
+ quality_profile: 'showcase',
+ viewBox: [720, 400],
+ legend: { mode: 'hidden' },
+ },
+ lanes: [{ id: 'main', label: 'Main flow' }],
+ nodes: [
+ { id: 'a', lane: 'main', col: 0, type: 'backend', label: 'A' },
+ { id: 'b', lane: 'main', col: 2, type: 'backend', label: 'B' },
+ ],
+ edges: [{ id: 'a-to-b', from: 'a', to: 'b', label: 'dispatch the planned tool call', labelAt: [700, 240] }],
+ };
+ }
+
+ test('workflow: showcase rejects a v1 edge label that leaves the canvas', () => {
+ const { code, stderr } = render('workflow', offCanvasWorkflowLabelDocument(1));
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /\[composition\/label-canvas-containment\] showcase workflow label "dispatch the planned tool call" on edges\[0\] id "a-to-b"/);
+ assert.match(stderr, /extends past the right edge by 57px \(label rect \[623, 230, 154, 14\]; viewBox 720x400\)/);
+ });
+
+ test('workflow: readable-v2 contains the same pinned label without this rule', () => {
+ const grown = offCanvasWorkflowLabelDocument(2);
+ delete grown.meta.viewBox;
+ const { code, stderr, outPath } = render('workflow', grown);
+ assert.equal(code, 0, stderr);
+ const html = fs.readFileSync(outPath, 'utf8');
+ const [, width] = html.match(/viewBox="0 0 (\d+) (\d+)"/).map(Number);
+ assert.ok(width >= 777, `expected the v2 canvas to contain the label rect, got width ${width}`);
+
+ // An authored v2 viewBox that cannot hold the layout is already rejected by
+ // the compiler's own contract, with its own minimum in the message.
+ const pinned = render('workflow', offCanvasWorkflowLabelDocument(2));
+ assert.notEqual(pinned.code, 0, `expected non-zero exit; stderr:\n${pinned.stderr}`);
+ assert.match(pinned.stderr, /cannot contain the readable-v2 layout; minimum \d+×\d+/);
+ assert.doesNotMatch(pinned.stderr, /label-canvas-containment/);
+ });
+
+ test('dataflow: showcase rejects a flow label that leaves the canvas', () => {
+ const d = load('dataflow');
+ d.flows[0].label = 'clickstream ingest with enrichment';
+ d.flows[0].labelAt = [1070, 400];
+ const { code, stderr } = render('dataflow', d);
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /\[composition\/label-canvas-containment\] showcase dataflow label "clickstream ingest with enrichment" on flows\[0\]/);
- assert.match(stderr, /extends past the right edge by 79\.3px .*viewBox 1080x760/);
++ assert.match(stderr, /extends past the right edge by 79\.3px .*viewBox 1080x520/);
+ });
+
+ test('lifecycle: showcase rejects a transition label that leaves the canvas', () => {
+ const d = load('lifecycle');
+ d.transitions[0].label = 'operator approves the escalation';
+ d.transitions[0].labelAt = [960, 300];
+ const { code, stderr } = render('lifecycle', d);
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /\[composition\/label-canvas-containment\] showcase lifecycle label "operator approves the escalation" on transitions\[0\]/);
- assert.match(stderr, /extends past the right edge by 64\.4px .*viewBox 980x660/);
++ assert.match(stderr, /extends past the right edge by 14\.4px .*viewBox 1030x630/);
+ });
+
+ // The repair side of the same contract: a suggested labelAt, applied verbatim,
+ // must clear the obstacle the message names. Both 27px two-line forms used to
+ // get an "above" hint that landed the rect back on the obstacle, so the
+ // validator answered its own fix with the identical message.
+ function suggestedLabelAts(stderr) {
+ return [...new Set(stderr.match(/set labelAt \[-?\d+, -?\d+\]/g) || [])]
+ .map((match) => match.match(/\[(-?\d+), (-?\d+)\]/).slice(1, 3).map(Number));
+ }
+
+ test('dataflow: obstacle hints for a two-line classification label survive being applied', () => {
+ const d = load('dataflow');
+ d.flows[0].labelAt = [100, 150];
+ const { code, stderr } = render('dataflow', d);
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /Label "clickstream" overlaps node "web"/);
+ const suggestions = suggestedLabelAts(stderr);
+ assert.equal(suggestions.length, 2, stderr);
+ for (const labelAt of suggestions) {
+ const applied = load('dataflow');
+ applied.flows[0].labelAt = labelAt;
+ const result = render('dataflow', applied);
+ assert.equal(result.code, 0, `labelAt [${labelAt}]: ${result.stderr}`);
+ }
+ });
+
+ test('lifecycle: obstacle hints for a two-line note label survive being applied', () => {
+ const withLabel = (labelAt) => {
+ const d = load('lifecycle');
+ d.transitions[0].label = 'needs approval';
+ d.transitions[0].note = 'security gate';
+ d.transitions[0].labelAt = labelAt;
+ return d;
+ };
+ const { code, stderr } = render('lifecycle', withLabel([400, 180]));
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /Label "needs approval" overlaps state "executing"/);
+ const suggestions = suggestedLabelAts(stderr);
+ assert.equal(suggestions.length, 2, stderr);
+ for (const labelAt of suggestions) {
+ const result = render('lifecycle', withLabel(labelAt));
+ // The hint's contract covers the named obstacle and the canvas; a residual
+ // route-clearance issue at the new spot is that rule's own report.
+ assert.doesNotMatch(result.stderr, /overlaps state "executing"/, `labelAt [${labelAt}]: ${result.stderr}`);
+ }
+ });
+
+ test('sequence: showcase rejects a message label that leaves the canvas', () => {
+ const d = load('sequence');
+ d.messages = d.messages.slice(0, 1);
+ d.messages[0].label = 'request the cached dashboard payload for the current reporting window and retry budget';
+ d.segments = [];
+ d.activations = [];
+ const { code, stderr } = render('sequence', d);
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /\[composition\/label-canvas-containment\] showcase sequence label ".*" on messages\[0\]/);
- assert.match(stderr, /extends past the left edge by 113\.6px .*viewBox 820x760/);
++ assert.match(stderr, /extends past the left edge by 39px .*viewBox 1080x560/);
+ assert.match(stderr, /shorten the label, reorder participants, or enlarge meta\.viewBox/);
+ });
+
+ // An auto canvas is derived geometry, so it has to cover the label rects the
+ // containment rule measures. An authored viewBox is the author's decision and
+ // is never resized; there the rule reports the clipping instead.
+ test('architecture: an auto viewBox grows to contain a wide connection label', () => {
+ const d = {
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Auto canvas with a wide label', quality_profile: 'showcase' },
+ components: [
+ { id: 'left', type: 'frontend', label: 'Left', pos: [60, 160], size: [120, 54] },
+ { id: 'right', type: 'backend', label: 'Right', pos: [420, 160], size: [120, 54] },
+ ],
+ connections: [{
+ id: 'left-to-right',
+ from: 'left',
+ to: 'right',
+ label: 'a very long edge label that runs off the canvas',
+ labelAt: [640, 140],
+ }],
+ };
+ const { code, stderr, outPath } = render('architecture', d);
+ assert.equal(code, 0, stderr);
+ const html = fs.readFileSync(outPath, 'utf8');
+ const [, width] = html.match(/viewBox="0 0 (\d+) (\d+)"/).map(Number);
+ const mask = html.match(/<g data-detail="context"[^>]*>\s*<rect x="([\d.-]+)"[^>]*width="([\d.]+)"/);
+ const labelRight = Number(mask[1]) + Number(mask[2]);
+ assert.ok(labelRight <= width, `label right edge ${labelRight} exceeds the ${width}px auto canvas`);
+
+ const authored = structuredClone(d);
+ authored.meta.viewBox = [720, 400];
+ const pinned = render('architecture', authored);
+ assert.notEqual(pinned.code, 0, `expected non-zero exit; stderr:\n${pinned.stderr}`);
+ assert.match(pinned.stderr, /\[composition\/label-canvas-containment\]/);
+ });
+
+ // Boundary-title fonts are resolved against the same width the canvas actually
+ // renders into. When a connection label alone widens the auto canvas past the
+ // desktop reader width, the title font must rise with it — otherwise validate
+ // would pass an artifact the desktop-readability check rejects.
+ test('architecture: label-driven canvas growth keeps boundary titles at the readability floor', () => {
+ const d = {
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Label-grown canvas', quality_profile: 'showcase' },
+ boundaries: [{
+ kind: 'region',
+ label: 'Shared production tenant isolation and compliance perimeter for the primary region',
+ wraps: ['a', 'b', 'c'],
+ }],
+ components: [
+ { id: 'a', type: 'frontend', label: 'A', pos: [60, 160], size: [140, 54] },
+ { id: 'b', type: 'backend', label: 'B', pos: [480, 160], size: [140, 54] },
+ { id: 'c', type: 'backend', label: 'C', pos: [860, 160], size: [140, 54] },
+ { id: 'd', type: 'database', label: 'D', pos: [860, 320], size: [140, 54] },
+ ],
+ connections: [{
+ id: 'c-to-d',
+ from: 'c',
+ to: 'd',
+ label: 'streaming replication of the full transaction journal with retries',
+ labelAt: [1310, 300],
+ }],
+ };
+ const { code, stderr, outPath } = render('architecture', d);
+ assert.equal(code, 0, stderr);
+ const html = fs.readFileSync(outPath, 'utf8');
+ const [, width] = html.match(/viewBox="0 0 (\d+) (\d+)"/).map(Number);
+ assert.ok(width > 1395, `expected the label to grow the canvas past 1395px, got ${width}`);
+ const floor = minimumReadableSourceTextPx(width);
+ const fonts = [...html.matchAll(/data-boundary-label=""[^>]*font-size="([\d.]+)"/g)]
+ .map(([, size]) => Number(size));
+ assert.equal(fonts.length, 1, 'expected exactly one boundary title');
+ assert.ok(
+ fonts[0] + 1e-6 >= floor,
+ `boundary title font ${fonts[0]} is below the ${floor}px floor for the ${width}px canvas`,
+ );
+ });
+
+ // The validator must not answer an off-canvas defect with another off-canvas
+ // coordinate: every suggested labelAt has to keep the whole label rect inside.
+ test('architecture: label obstacle fixes stay inside the viewBox', () => {
+ const d = {
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Label on a component near the edge', quality_profile: 'showcase', viewBox: [720, 400] },
+ components: [
+ { id: 'left', type: 'frontend', label: 'Left', pos: [40, 180], size: [120, 54] },
+ { id: 'right', type: 'backend', label: 'Right', pos: [540, 336], size: [160, 54] },
+ ],
+ connections: [{
+ id: 'left-to-right',
+ from: 'left',
+ to: 'right',
+ label: 'synchronous call with retries and backoff',
+ labelAt: [660, 360],
+ }],
+ };
+ const { code, stderr } = render('architecture', d);
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /overlaps component "right"/);
+ const rect = stderr.match(/label rect: \[(-?\d+), (-?\d+), (\d+), (\d+)\]/);
+ assert.ok(rect, `expected a label rect in stderr:\n${stderr}`);
+ const width = Number(rect[3]);
+ const height = Number(rect[4]);
+ const suggestions = suggestedLabelAts(stderr);
+ assert.ok(suggestions.length > 0, `expected at least one labelAt suggestion:\n${stderr}`);
+ for (const [x, y] of suggestions) {
+ assert.ok(x - width / 2 >= 0 && x + width / 2 <= 720, `labelAt [${x}, ${y}] leaves the 720px canvas width (label width ${width})`);
+ assert.ok(y - 10 >= 0 && y - 10 + height <= 400, `labelAt [${x}, ${y}] leaves the 400px canvas height (label height ${height})`);
+ }
+ });
+
+ // Reading the coordinates is not enough: a hint is only executable if applying
+ // it to the document actually clears both the obstacle and the canvas edge.
+ // The relative form is where that breaks — its delta has to be measured from
+ // the document's own labelDx/labelDy, and it means nothing at all while an
+ // authored labelAt is present, because labelPoint returns labelAt unchanged.
+ function pinnedLabelDocument(labelControls) {
+ return {
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Label pinned to the right edge', quality_profile: 'showcase', viewBox: [720, 400] },
+ components: [
+ { id: 'edge', type: 'cloud', label: 'Edge', pos: [560, 60], size: [140, 54] },
+ { id: 'sink', type: 'database', label: 'Sink', pos: [560, 240], size: [140, 54] },
+ ],
+ connections: [{
+ id: 'edge-to-sink',
+ from: 'edge',
+ to: 'sink',
+ label: 'batched telemetry upload with retry and backoff',
+ ...labelControls,
+ }],
+ };
+ }
+
+ function suggestedLabelFixes(stderr) {
+ const unique = new Map();
+ for (const [hint, x, y] of stderr.matchAll(/set labelAt \[(-?\d+), (-?\d+)\]/g)) {
+ unique.set(hint, { labelAt: [Number(x), Number(y)] });
+ }
+ for (const [hint, dx, dy] of stderr.matchAll(/set labelDx (-?\d+) with labelDy (-?\d+)/g)) {
+ unique.set(hint, { labelDx: Number(dx), labelDy: Number(dy) });
+ }
+ for (const [hint, dy] of stderr.matchAll(/or set (labelDy (-?\d+))/g)) {
+ unique.set(hint, { labelDy: Number(dy) });
+ }
+ return [...unique];
+ }
+
+ for (const [name, labelControls, expectedFixes] of [
+ ['no authored label controls', {}, 4],
+ ['an authored labelDx', { labelDx: 120 }, 4],
+ ['an authored labelAt', { labelAt: [660, 104] }, 2],
+ ]) {
+ test(`architecture: every label obstacle fix renders clean when applied to a document with ${name}`, () => {
+ const source = pinnedLabelDocument(labelControls);
+ const { code, stderr } = render('architecture', source);
+ assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
+ assert.match(stderr, /overlaps component "edge"/);
+ assert.match(stderr, /\[composition\/label-canvas-containment\]/);
+
+ const fixes = suggestedLabelFixes(stderr);
+ assert.equal(fixes.length, expectedFixes, `unexpected suggestion set:\n${stderr}`);
+ // An authored labelAt outranks labelDx/labelDy, so a relative suggestion
+ // there would be a fix that changes nothing.
+ if (Array.isArray(labelControls.labelAt)) assert.doesNotMatch(stderr, /set labelD[xy] /);
+
+ for (const [hint, patch] of fixes) {
+ const repaired = structuredClone(source);
+ Object.assign(repaired.connections[0], patch);
+ const result = render('architecture', repaired);
+ assert.equal(result.code, 0, `applying "${hint}" still fails:\n${result.stderr}`);
+ }
+ });
+ }
+
function autoRoutePassThroughDocument(connection) {
return {
schema_version: 1,
diff --cc docs/gallery.html
index 9698ef5d,66915f92..c7fa62c9
--- a/docs/gallery.html
+++ b/docs/gallery.html
@@@ -930,7 -932,8 +932,8 @@@ receipt 99 checks / 11 artifacts / dete
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
- "minLabelRouteClearance": 15,
+ "minLabelRouteClearance": 8,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
"maxBends": 0,
@@@ -1230,7 -1235,8 +1235,8 @@@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
- "minLabelRouteClearance": 57,
+ "minLabelRouteClearance": 44.3,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
"maxBends": 3,
diff --cc docs/gallery/manifest.json
index 76068d79,d8a6ea3e..5769ce46
--- a/docs/gallery/manifest.json
+++ b/docs/gallery/manifest.json
@@@ -282,7 -284,8 +284,8 @@@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
- "minLabelRouteClearance": 15,
+ "minLabelRouteClearance": 8,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
"maxBends": 0,
@@@ -582,7 -587,8 +587,8 @@@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
- "minLabelRouteClearance": 57,
+ "minLabelRouteClearance": 44.3,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
"maxBends": 3,