Skip to content

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

feat(renderers): keep edge labels inside the canvas

Rererr3d5502c5d1ec
diff --git a/archify.zip b/archify.zip
index 55b3bbea..12aa7cd9 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index 2b8cc7a7..3c7a390b 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -191,6 +191,7 @@ const COMPOSITION_FIXES = {
'composition/ambiguous-corridor': ['adjust route/via or channel coordinates so unrelated relationships do not visually merge'],
'composition/container-border-run': ['route across the frame perpendicularly through a clear opening'],
'composition/label-route-clearance': ['adjust labelAt, labelDx, labelDy, labelSegment, message y, or the other relationship route'],
+ 'composition/label-canvas-containment': ['adjust labelAt, labelDx, labelDy, or labelSegment so the label rect stays inside the viewBox, or enlarge meta.viewBox'],
'composition/desktop-readability': ['reduce the viewBox width, shorten node copy, widen affected nodes, or split the diagram so node context remains at least 6px at a 1440px desktop viewport'],
'composition/micro-segment': ['move the route/channel/via point so every visible segment is at least 8px'],
'composition/short-interior-segment': ['move the route/channel/via point so every interior turn has at least 16px'],
diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.md
index 890d5c6e..740d283b 100644
--- a/archify/references/authoring-contract.md
+++ b/archify/references/authoring-contract.md
@@ -142,6 +142,7 @@ a time.
3. Fix edge-through-node and endpoint-direction errors.
4. Fix crossings, ambiguous corridors, border runs, and route rhythm.
5. Fix label-to-node, label-to-label, then label-to-route clearance.
+6. Fix labels that leave the canvas: move the label with `labelAt`/`labelDx`/`labelDy`/`labelSegment`, or widen `meta.viewBox`. Suggested `labelDx`/`labelDy` values replace the authored field; they are not added to it.
Run `validate` after every edit. Consume `diagnostics[]` by stable `code`, exact `subject`, measured `evidence`, and `supportedFixes`. If the diagnostic gives `labelAt`, use that point instead of estimating another offset.
diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjs
index b21ac8e4..361fe982 100644
--- a/archify/renderers/architecture/render-architecture.mjs
+++ b/archify/renderers/architecture/render-architecture.mjs
@@ -22,6 +22,7 @@ import {
cleanBorderRunProblems,
cleanRouteRhythmProblems,
cleanLabelRouteClearanceProblems,
+ cleanLabelCanvasContainmentProblems,
suggestLabelObstacleFix,
suggestComponentSeparation,
anchor,
@@ -148,16 +149,43 @@ const architectureLegendEntries = resolveLegend(
new Set([...components.values()].map((component) => component.type)),
);
-function autoViewBoxFor(candidateBoundaries) {
+
+// One source for connection label geometry: the auto canvas has to cover the
+// same rects the containment rule measures, and the layout report has to
+// publish them.
+function connectionLabelRects() {
+ const rects = [];
+ for (const [relationIndex, conn] of asArray(arch.connections).entries()) {
+ if (!conn.label || !components.has(conn.from) || !components.has(conn.to)) continue;
+ const [lx, ly] = labelPoint(conn, pathFor(conn).points);
+ const width = Math.max(30, textUnits(conn.label) * 4.8 + 10);
+ rects.push({
+ relation: conn,
+ relationIndex,
+ label: conn.label,
+ x: lx - width / 2,
+ y: ly - 10,
+ width,
+ height: 14,
+ lx,
+ ly,
+ });
+ }
+ return rects;
+}
+
+function autoViewBoxFor(candidateBoundaries, extraRects = []) {
const maxX = Math.max(
0,
...[...components.values()].map((component) => component.x + component.width),
...candidateBoundaries.map((boundary) => boundary.x + boundary.width),
+ ...extraRects.map((rect) => rect.x + rect.width),
);
const maxY = Math.max(
0,
...[...components.values()].map((component) => component.y + component.height),
...candidateBoundaries.map((boundary) => boundary.y + boundary.height),
+ ...extraRects.map((rect) => rect.y + rect.height),
);
let width = Math.ceil(maxX + layout.margin);
let footprint = legendFootprint(architectureLegendEntries, {
@@ -330,7 +358,7 @@ function componentContext(component) {
}
// ---- Auto viewBox: fit all geometry + the measured resolved legend ----------
-const viewBox = arch.meta?.viewBox || autoViewBoxFor(boundaries);
+let viewBox = arch.meta?.viewBox || autoViewBoxFor(boundaries);
const legendY = () => viewBox[1] - 16;
// ---- Validation: mechanical correctness, never layout taste -----------------
@@ -564,17 +592,11 @@ function validateArchitecture() {
}));
// Connection labels must not land on top of components.
- const labelRects = [];
- for (const [connectionIndex, conn] of asArray(arch.connections).entries()) {
- if (!conn.label || !components.has(conn.from) || !components.has(conn.to)) continue;
- const [lx, ly] = labelPoint(conn, pathFor(conn).points);
- const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);
- labelRects.push({ relation: conn, relationIndex: connectionIndex, label: conn.label, x: lx - w / 2, y: ly - 10, width: w, height: 14, lx, ly });
- }
+ const labelRects = connectionLabelRects();
for (const rect of labelRects) {
for (const c of components.values()) {
if (rectsOverlap(rect, c, -2)) {
- problems.push(`Label "${rect.label}" overlaps component "${c.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, c)}`);
+ problems.push(`Label "${rect.label}" overlaps component "${c.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, c, 'component', viewBox)}`);
}
}
if (enforcesBoundaryTitleComposition) {
@@ -595,6 +617,16 @@ function validateArchitecture() {
relationCollection: 'connections',
profile: arch.meta?.quality_profile,
}));
+ // See collectLabelCanvasOverflow in shared/geometry.mjs. An auto canvas now
+ // covers these rects, so this reports authored viewBoxes and the origin side,
+ // which growth cannot reach.
+ problems.push(...cleanLabelCanvasContainmentProblems({
+ labels: labelRects,
+ viewBox,
+ diagramType: 'architecture',
+ relationCollection: 'connections',
+ profile: arch.meta?.quality_profile,
+ }));
if (problems.length) {
throwDiagnosticProblems('Architecture layout validation failed', problems, {
@@ -604,20 +636,14 @@ function validateArchitecture() {
}
function buildLayoutReport() {
- const labels = [];
- for (const conn of asArray(arch.connections)) {
- if (!conn.label || !components.has(conn.from) || !components.has(conn.to)) continue;
- const [lx, ly] = labelPoint(conn, pathFor(conn).points);
- const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);
- labels.push({
- text: conn.label,
- x: Math.round(lx - w / 2),
- y: Math.round(ly - 10),
- width: Math.round(w),
- height: 14,
- labelAt: [Math.round(lx), Math.round(ly)],
- });
- }
+ const labels = connectionLabelRects().map((rect) => ({
+ text: rect.label,
+ x: Math.round(rect.x),
+ y: Math.round(rect.y),
+ width: Math.round(rect.width),
+ height: 14,
+ labelAt: [Math.round(rect.lx), Math.round(rect.ly)],
+ }));
return {
ok: true,
diagram_type: 'architecture',
@@ -1062,6 +1088,13 @@ ${renderLegend()}
</svg>`;
}
+// Connection labels are diagram content, so an auto canvas that stops at the
+// component/boundary bbox clips them. Routing state only exists once the whole
+// module is initialized, so the auto canvas is grown here rather than inside
+// the boundary-title convergence above. An authored viewBox is never resized:
+// there the containment rule reports the clipping instead.
+if (!arch.meta?.viewBox) viewBox = autoViewBoxFor(boundaries, connectionLabelRects());
+
validateArchitecture();
if (layoutJsonMode) {
console.log(JSON.stringify(buildLayoutReport(), null, 2));
diff --git a/archify/renderers/dataflow/render-dataflow.mjs b/archify/renderers/dataflow/render-dataflow.mjs
index 3eda9d4a..76f0bfb1 100644
--- a/archify/renderers/dataflow/render-dataflow.mjs
+++ b/archify/renderers/dataflow/render-dataflow.mjs
@@ -18,6 +18,7 @@ import {
cleanBorderRunProblems,
cleanRouteRhythmProblems,
cleanLabelRouteClearanceProblems,
+ cleanLabelCanvasContainmentProblems,
suggestLabelObstacleFix,
suggestLabelPairFix,
anchor,
@@ -259,7 +260,7 @@ function validateDataflow() {
for (const rect of labelRects) {
for (const node of nodes.values()) {
if (rectsOverlap(rect, node, -2)) {
- problems.push(`Label "${rect.label}" overlaps node "${node.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, node, 'node')}`);
+ problems.push(`Label "${rect.label}" overlaps node "${node.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, node, 'node', viewBox)}`);
}
}
}
@@ -280,6 +281,13 @@ function validateDataflow() {
profile: dataflow.meta?.quality_profile,
routeHint: 'adjust labelAt, labelDx, labelDy, or labelSegment; otherwise adjust the other flow route/via/channelX/channelY'
}));
+ problems.push(...cleanLabelCanvasContainmentProblems({
+ labels: labelRects,
+ viewBox,
+ diagramType: 'dataflow',
+ relationCollection: 'flows',
+ profile: dataflow.meta?.quality_profile,
+ }));
const lastStageX = stageX(asArray(dataflow.stages).length - 1);
if (lastStageX + layout.stageW / 2 > viewBox[0] - 24) {
diff --git a/archify/renderers/lifecycle/render-lifecycle.mjs b/archify/renderers/lifecycle/render-lifecycle.mjs
index eb7922c4..65f6190d 100644
--- a/archify/renderers/lifecycle/render-lifecycle.mjs
+++ b/archify/renderers/lifecycle/render-lifecycle.mjs
@@ -18,6 +18,7 @@ import {
cleanBorderRunProblems,
cleanRouteRhythmProblems,
cleanLabelRouteClearanceProblems,
+ cleanLabelCanvasContainmentProblems,
suggestLabelObstacleFix,
suggestLabelPairFix,
anchor,
@@ -298,7 +299,7 @@ function validateLifecycle() {
for (const rect of labelRects) {
for (const state of states.values()) {
if (rectsOverlap(rect, state, -2)) {
- problems.push(`Label "${rect.label}" overlaps state "${state.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, state, 'state')}`);
+ problems.push(`Label "${rect.label}" overlaps state "${state.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, state, 'state', viewBox)}`);
}
}
}
@@ -318,6 +319,13 @@ function validateLifecycle() {
relationCollection: 'transitions',
profile: lifecycle.meta?.quality_profile,
}));
+ problems.push(...cleanLabelCanvasContainmentProblems({
+ labels: labelRects,
+ viewBox,
+ diagramType: 'lifecycle',
+ relationCollection: 'transitions',
+ profile: lifecycle.meta?.quality_profile,
+ }));
if (problems.length) {
throwDiagnosticProblems('Lifecycle layout validation failed', problems, {
diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjs
index 02d77817..7fc9b351 100644
--- a/archify/renderers/sequence/render-sequence.mjs
+++ b/archify/renderers/sequence/render-sequence.mjs
@@ -4,7 +4,7 @@ import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../share
import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagramWithBrandMarks, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';
import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';
import { resolveLegend, renderLegend as renderResolvedLegend } from '../shared/legend.mjs';
-import { componentFill, arrowClassMap, rectsOverlap, cleanFlowProblems, cleanCrossingProblems, cleanAmbiguousCorridorProblems, cleanBorderRunProblems, cleanRouteRhythmProblems, cleanLabelRouteClearanceProblems, routePointsValue, asArray, isFinitePoint } from '../shared/geometry.mjs';
+import { componentFill, arrowClassMap, rectsOverlap, cleanFlowProblems, cleanCrossingProblems, cleanAmbiguousCorridorProblems, cleanBorderRunProblems, cleanRouteRhythmProblems, cleanLabelRouteClearanceProblems, cleanLabelCanvasContainmentProblems, routePointsValue, asArray, isFinitePoint } from '../shared/geometry.mjs';
import { availableNodeTextWidth, fittedNodeFontSize, minimumNodeTextWidth } from '../shared/text-fit.mjs';
import { brandLabelFitWidth, brandMetadataFor, brandTopRailProblem, renderBrandMark } from '../shared/brand-marks.mjs';
import { translateMessage as i18nText } from '../shared/i18n.mjs';
@@ -262,6 +262,14 @@ function validateSequence() {
profile: sequence.meta?.quality_profile,
routeHint: 'spread the message y values, shorten the label, or reorder participants so the adjacent route stays visible'
}));
+ problems.push(...cleanLabelCanvasContainmentProblems({
+ labels: labelRects,
+ viewBox,
+ diagramType: 'sequence',
+ relationCollection: 'messages',
+ profile: sequence.meta?.quality_profile,
+ routeHint: 'shorten the label, reorder participants, or enlarge meta.viewBox',
+ }));
for (const segment of asArray(sequence.segments)) {
if (segment.to <= segment.from) {
diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjs
index 733129c2..2a41facc 100644
--- a/archify/renderers/shared/geometry.mjs
+++ b/archify/renderers/shared/geometry.mjs
@@ -943,6 +943,102 @@ export function cleanLabelRouteClearanceProblems({
});
}
+// How far [start, start + size) leaves [0, extent), per end of one axis. This
+// is the single definition of "inside the canvas" that both the containment
+// rule and the repair hints measure against; an unknown extent bounds nothing.
+function axisCanvasOverflow(start, size, extent) {
+ if (!Number.isFinite(extent)) return { start: 0, end: 0 };
+ return { start: -start, end: start + size - extent };
+}
+
+// THE CANVAS CONTAINMENT RATIONALE (referenced from the other call sites).
+//
+// The SVG canvas clips whatever leaves the viewBox, so an edge label that
+// overhangs an edge ships as truncated text while every post-render check on
+// the emitted markup still passes: clipped text is still well-formed markup.
+// Renderers with a fixed canvas already bound their nodes, lanes, and legends
+// against it; edge label rects were the exception.
+//
+// Not applied to readable-v2 workflows: that compiler grows its canvas around
+// pinned label rects and rejects an authored viewBox that cannot hold the
+// result, so the only gap growth cannot close is the origin its own rule
+// already guards. Architecture's auto canvas grows the same way, which leaves
+// this rule reporting authored viewBoxes and the origin side.
+//
+// Showcase only: a standard document authored before the rule exists may
+// overhang by a few pixels, and failing it there would break compatibility
+// instead of repairing a diagram.
+export function collectLabelCanvasOverflow({ labels, viewBox, tolerance = 0.5 }) {
+ const [canvasWidth, canvasHeight] = asArray(viewBox);
+ if (!isFinitePoint(canvasWidth, canvasHeight)) return [];
+ const hits = [];
+ for (const [fallbackIndex, label] of asArray(labels).entries()) {
+ const rect = label?.rect || label;
+ if (!rect || !isFinitePoint(rect.x, rect.y, rect.width, rect.height)) continue;
+ const horizontal = axisCanvasOverflow(rect.x, rect.width, canvasWidth);
+ const vertical = axisCanvasOverflow(rect.y, rect.height, canvasHeight);
+ const overflow = {
+ left: horizontal.start,
+ right: horizontal.end,
+ top: vertical.start,
+ bottom: vertical.end,
+ };
+ const sides = Object.keys(overflow).filter((side) => overflow[side] > tolerance);
+ if (!sides.length) continue;
+ hits.push({
+ label,
+ relation: label?.relation,
+ relationIndex: Number.isInteger(label?.relationIndex) ? label.relationIndex : fallbackIndex,
+ rect,
+ viewBox: [canvasWidth, canvasHeight],
+ sides,
+ overflowPx: Object.fromEntries(sides.map((side) => [side, Math.round(overflow[side] * 10) / 10])),
+ tolerance,
+ });
+ }
+ return hits;
+}
+
+export function describeLabelCanvasOverflow(hit) {
+ return hit.sides.map((side) => `${side} edge by ${hit.overflowPx[side]}px`).join(' and ');
+}
+
+export function cleanLabelCanvasContainmentProblems({
+ labels,
+ viewBox,
+ diagramType,
+ relationCollection,
+ profile,
+ profileIsAuthoritative = false,
+ routeHint = 'adjust labelAt, labelDx, labelDy, or labelSegment; otherwise enlarge meta.viewBox',
+ // Label widths are estimated from the text, not measured, so sub-pixel
+ // overhang is rounding noise rather than a visible truncation.
+ tolerance = 0.5,
+}) {
+ if (qualityProfileForGate(profile, profileIsAuthoritative) !== 'showcase') return [];
+ return collectLabelCanvasOverflow({ labels, viewBox, tolerance }).map((hit) => {
+ const relation = hit.relation;
+ const relationId = relation?.id ? ` id "${relation.id}"` : '';
+ const labelText = hit.label?.label || relation?.label || '';
+ const message = `[composition/label-canvas-containment] showcase ${diagramType} label "${labelText}" on ${relationCollection}[${hit.relationIndex}]${relationId} "${relation?.from}" -> "${relation?.to}" extends past the ${describeLabelCanvasOverflow(hit)} (label rect ${formatRect(hit.rect)}; viewBox ${hit.viewBox[0]}x${hit.viewBox[1]}) — ${routeHint}.`;
+ recordDiagnostic({
+ code: 'composition/label-canvas-containment',
+ severity: 'error',
+ message,
+ subject: relationshipSubject(diagramType, relationCollection, hit.relationIndex, relation),
+ evidence: {
+ label: labelText,
+ labelRect: { x: hit.rect.x, y: hit.rect.y, width: hit.rect.width, height: hit.rect.height },
+ viewBox: hit.viewBox,
+ overflowPx: hit.overflowPx,
+ tolerancePx: hit.tolerance,
+ },
+ supportedFixes: [routeHint],
+ });
+ return message;
+ });
+}
+
function qualityProfileForGate(profile, profileIsAuthoritative) {
return profileIsAuthoritative
? profile
@@ -1386,22 +1482,90 @@ export function formatRect(r) {
return `[${Math.round(r.x)}, ${Math.round(r.y)}, ${Math.round(r.width)}, ${Math.round(r.height)}]`;
}
-function formatDelta(n) {
- const v = Math.round(n);
- return v >= 0 ? `+${v}` : String(v);
+function formatValue(n) {
+ return String(Math.round(n));
}
-/** Actionable hint when an edge label rect hits a node/component box (#7). */
-export function suggestLabelObstacleFix(labelRect, lx, ly, obstacle, obstacleKind = 'component') {
- const lxR = Math.round(lx);
- const lyR = Math.round(ly);
- const belowY = Math.round(obstacle.y + obstacle.height + 14);
- const aboveY = Math.round(obstacle.y - 4);
- return [
+// A label anchor is the text origin, so keeping a suggestion on the canvas
+// means moving the whole rect: offset is `rect - anchor` on that axis.
+function anchorFitsCanvas(anchorValue, offset, size, extent) {
+ const overflow = axisCanvasOverflow(anchorValue + offset, size, extent);
+ return overflow.start <= 0 && overflow.end <= 0;
+}
+
+// Suggestions are emitted as integers, so the real-valued bounds are tightened
+// inward with ceil/floor first: every integer between them keeps the whole rect
+// on the canvas, which a bound like 616.7 would not. Returns null when the rect
+// is wider than the canvas and no anchor can contain it.
+function clampAnchorToCanvas(anchorValue, offset, size, extent) {
+ const rounded = Math.round(anchorValue);
+ if (!Number.isFinite(extent)) return rounded;
+ const min = Math.ceil(-offset);
+ const max = Math.floor(extent - size - offset);
+ return max < min ? null : Math.min(Math.max(rounded, min), max);
+}
+
+/**
+ * Actionable hint when an edge label rect hits a node/component box (#7).
+ * Every suggested value is a replacement for the authored field, not an
+ * increment, and has to survive being applied to the document:
+ * - the absolute form is nudged along x so the rect stays on the canvas, and a
+ * vertical placement that cannot fit is dropped rather than clamped, since
+ * clamping it back would push the label onto the obstacle it must clear;
+ * - the relative form is offered only when labelDx/labelDy actually move this
+ * label (labelPoint returns an authored labelAt as-is) and only when the
+ * replacements, computed from the document's own labelDx/labelDy, land the
+ * rect inside the canvas.
+ * The authored values therefore come from `labelRect.relation`, the authored
+ * relationship the renderer already attaches to every label record.
+ */
+export function suggestLabelObstacleFix(labelRect, lx, ly, obstacle, obstacleKind = 'component', viewBox) {
+ const [canvasWidth, canvasHeight] = asArray(viewBox);
+ const xOffset = labelRect.x - lx;
+ const yOffset = labelRect.y - ly;
+ const anchorX = clampAnchorToCanvas(lx, xOffset, labelRect.width, canvasWidth);
+ const placements = [
+ { name: 'below', y: Math.round(obstacle.y + obstacle.height + 14) },
+ { name: 'above', y: Math.round(obstacle.y - 4) },
+ ].filter(({ y }) => anchorX !== null
+ && anchorFitsCanvas(y, yOffset, labelRect.height, canvasHeight));
+ const lines = [
` label rect: ${formatRect(labelRect)}`,
` ${obstacleKind} "${obstacle.id}" rect: ${formatRect(obstacle)}`,
- ` Suggested fix: labelAt [${lxR}, ${belowY}] or labelDy ${formatDelta(belowY - lyR)} (below); or labelAt [${lxR}, ${aboveY}] or labelDy ${formatDelta(aboveY - lyR)} (above)`,
- ].join('\n');
+ ];
+ if (!placements.length) {
+ lines.push(` Suggested fix: no position clears "${obstacle.id}" inside the ${canvasWidth}x${canvasHeight} viewBox — shorten the label, move the ${obstacleKind}, or enlarge meta.viewBox`);
+ return lines.join('\n');
+ }
+ const authored = labelRect.relation || {};
+ const authoredDx = Number.isFinite(authored.labelDx) ? authored.labelDx : 0;
+ const authoredDy = Number.isFinite(authored.labelDy) ? authored.labelDy : 0;
+ const relativeHint = (y) => {
+ if (Array.isArray(authored.labelAt)) return null;
+ // Both replacements are measured from the automatic label point that the
+ // authored offsets are applied to, and against the unrounded anchor: a
+ // rounded base would shift the applied label by up to a pixel.
+ const dx = Math.round(authoredDx + anchorX - lx);
+ const dy = Math.round(authoredDy + y - ly);
+ // labelDx is authored as a number, so an authored fraction must not read as
+ // a needed nudge once the replacement is rounded to an integer.
+ const movesX = Math.abs(dx - authoredDx) >= 0.5;
+ const landsAtX = lx - authoredDx + (movesX ? dx : authoredDx);
+ const landsAtY = ly - authoredDy + dy;
+ if (!anchorFitsCanvas(landsAtX, xOffset, labelRect.width, canvasWidth)) return null;
+ if (!anchorFitsCanvas(landsAtY, yOffset, labelRect.height, canvasHeight)) return null;
+ return movesX
+ ? `set labelDx ${formatValue(dx)} with labelDy ${formatValue(dy)}`
+ : `set labelDy ${formatValue(dy)}`;
+ };
+ const hint = placements
+ .map(({ name, y }) => {
+ const relative = relativeHint(y);
+ return `set labelAt [${anchorX}, ${y}]${relative ? ` or ${relative}` : ''} (${name})`;
+ })
+ .join('; or ');
+ lines.push(` Suggested fix: ${hint}`);
+ return lines.join('\n');
}
/** Hint when two edge labels collide. */
diff --git a/archify/renderers/workflow/workflow-compiler.mjs b/archify/renderers/workflow/workflow-compiler.mjs
index 81ba79a1..f48de41c 100644
--- a/archify/renderers/workflow/workflow-compiler.mjs
+++ b/archify/renderers/workflow/workflow-compiler.mjs
@@ -34,6 +34,7 @@ import {
cleanBorderRunProblems,
cleanRouteRhythmProblems,
cleanLabelRouteClearanceProblems,
+ cleanLabelCanvasContainmentProblems,
collectAmbiguousCorridors,
collectLabelRouteClearance,
collectBorderRuns,
@@ -2451,7 +2452,7 @@ function validateWorkflow() {
for (const rect of labelRects) {
for (const node of nodes.values()) {
if (rectsOverlap(rect, node, -2)) {
- problems.push(`Label "${rect.label}" overlaps node "${node.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, node, 'node')}`);
+ problems.push(`Label "${rect.label}" overlaps node "${node.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, node, 'node', viewBox)}`);
}
}
}
@@ -2480,6 +2481,15 @@ function validateWorkflow() {
if (legendY() + 18 > viewBox[1]) {
problems.push(`Legend exceeds viewBox height ${viewBox[1]} — set meta.viewBox[1] to at least ${legendY() + 18}.`);
}
+ // v1 only; see collectLabelCanvasOverflow in shared/geometry.mjs.
+ problems.push(...cleanLabelCanvasContainmentProblems({
+ labels: labelRects,
+ viewBox,
+ diagramType: 'workflow',
+ relationCollection: 'edges',
+ profile: workflow.meta?.quality_profile,
+ profileIsAuthoritative: true,
+ }));
}
if (problems.length) {
diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjs
index 704b9650..bb28df11 100644
--- a/archify/scripts/check-render-output.mjs
+++ b/archify/scripts/check-render-output.mjs
@@ -2,7 +2,7 @@
import fs from 'node:fs';
import path from 'node:path';
-import { collectAmbiguousCorridors, collectBorderRuns, collectLabelRouteClearance, collectRouteRhythmIssues, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';
+import { collectAmbiguousCorridors, collectBorderRuns, collectLabelCanvasOverflow, collectLabelRouteClearance, collectRouteRhythmIssues, describeLabelCanvasOverflow, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';
import {
DESKTOP_READABILITY_VIEWPORT,
DESKTOP_READER_DIAGRAM_WIDTH,
@@ -42,6 +42,7 @@ let composition = {
containerBorderRuns: 0,
labelRouteClearanceIssues: 0,
minLabelRouteClearance: null,
+ labelCanvasOverflowIssues: 0,
maxBends: 0,
routesOverSuggestedBends: 0,
maxStretch: null,
@@ -113,21 +114,31 @@ if (svgMatches.length === 1) {
routedRelations: arrows.map((arrow) => ({ relation: arrow, relationIndex: arrow.index, points: arrow.routePoints })),
threshold: labelClearanceThreshold,
});
+ // The renderers bound their own label rects, but `check` also re-measures an
+ // artifact it did not produce; see collectLabelCanvasOverflow in
+ // shared/geometry.mjs.
+ const labelCanvasOverflow = collectLabelCanvasOverflow({
+ labels: relationshipLabels,
+ viewBox: viewBoxSize(svgAttrs),
+ });
const crossingIsError = qualityProfile === 'showcase';
const corridorIsError = qualityProfile === 'showcase';
const rhythmIsError = qualityProfile === 'showcase';
const labelClearanceIsError = qualityProfile === 'showcase';
+ const labelContainmentIsError = qualityProfile === 'showcase';
const desktopReadabilityIsError = qualityProfile === 'showcase';
const compositionErrors = (qualityGatesEnforced ? containerBorderRuns.length : 0)
+ (crossingIsError ? relationshipCrossings.length : 0)
+ (corridorIsError ? ambiguousCorridors.length : 0)
+ (labelClearanceIsError ? labelRouteClearance.length : 0)
+ + (labelContainmentIsError ? labelCanvasOverflow.length : 0)
+ (rhythmIsError ? routeRhythmIssues.length : 0)
+ (desktopReadabilityIsError && desktopReadabilityIssue ? 1 : 0);
const compositionWarnings = (qualityGatesEnforced ? 0 : containerBorderRuns.length)
+ (crossingIsError ? 0 : relationshipCrossings.length)
+ (corridorIsError ? 0 : ambiguousCorridors.length)
+ (labelClearanceIsError ? 0 : labelRouteClearance.length)
+ + (labelContainmentIsError ? 0 : labelCanvasOverflow.length)
+ (rhythmIsError ? 0 : routeRhythmIssues.length)
+ (desktopReadabilityIsError || !desktopReadabilityIssue ? 0 : 1);
composition = {
@@ -143,6 +154,7 @@ 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,
@@ -177,6 +189,16 @@ if (svgMatches.length === 1) {
from: hit.start.map((value) => Math.round(value * 10) / 10),
to: hit.end.map((value) => Math.round(value * 10) / 10),
})),
+ ...labelCanvasOverflow.map((hit) => ({
+ severity: labelContainmentIsError ? 'error' : 'warning',
+ code: 'composition/label-canvas-containment',
+ label: hit.label?.label || hit.relation?.label || '',
+ relationship: relationshipRecord(hit.relation),
+ labelRect: roundedRect(hit.rect),
+ viewBox: hit.viewBox,
+ overflowPx: hit.overflowPx,
+ detail: `[composition/label-canvas-containment] ${qualityProfile} label "${hit.label?.label || hit.relation?.label || ''}" on ${relationshipName(hit.relation)} extends past the ${describeLabelCanvasOverflow(hit)} (label rect ${formatRectDetail(hit.rect)}; viewBox ${hit.viewBox[0]}x${hit.viewBox[1]}) — adjust labelAt, labelDx, labelDy, or labelSegment; otherwise enlarge meta.viewBox.`,
+ })),
...relationshipCrossings.map((hit) => ({
severity: crossingIsError ? 'error' : 'warning',
code: 'composition/proper-crossing',
@@ -618,9 +640,17 @@ function textBox(attrs, text) {
};
}
-function collectDesktopReadability(svgAttrs, fragment) {
+function viewBoxSize(svgAttrs) {
const viewBox = String(svgAttrs.viewBox || '').trim().split(/[\s,]+/).map(Number);
- const viewBoxWidth = viewBox.length === 4 ? viewBox[2] : Number.NaN;
+ return viewBox.length === 4 ? [viewBox[2], viewBox[3]] : [Number.NaN, Number.NaN];
+}
+
+function formatRectDetail(rect) {
+ return `[${Math.round(rect.x)}, ${Math.round(rect.y)}, ${Math.round(rect.width)}, ${Math.round(rect.height)}]`;
+}
+
+function collectDesktopReadability(svgAttrs, fragment) {
+ const [viewBoxWidth] = viewBoxSize(svgAttrs);
if (!Number.isFinite(viewBoxWidth) || viewBoxWidth <= 0) return null;
const scale = Math.min(1, DESKTOP_READER_DIAGRAM_WIDTH / viewBoxWidth);
let worst = null;
diff --git a/archify/test/geometry.test.mjs b/archify/test/geometry.test.mjs
index 2b93f8c4..05ccb590 100644
--- a/archify/test/geometry.test.mjs
+++ b/archify/test/geometry.test.mjs
@@ -36,6 +36,7 @@ import {
labelPoint,
suggestLabelObstacleFix,
suggestComponentSeparation,
+ cleanLabelCanvasContainmentProblems,
} from '../renderers/shared/geometry.mjs';
import { textUnits, applyTemplate, renderSemanticSigil } from '../renderers/shared/utils.mjs';
@@ -674,8 +675,206 @@ test('suggestLabelObstacleFix includes rects and labelAt/labelDy hints', () => {
const hint = suggestLabelObstacleFix(labelRect, 124, 188, obstacle);
assert.match(hint, /label rect: \[100, 180, 48, 14\]/);
assert.match(hint, /component "memtool"/);
- assert.match(hint, /Suggested fix: labelAt/);
- assert.match(hint, /labelDy \+\d+/);
+ assert.match(hint, /Suggested fix: set labelAt/);
+ assert.match(hint, /set labelDy \d+/);
+});
+
+// Agents parse this hint, so pin the whole string for the no-viewBox contract.
+test('suggestLabelObstacleFix states its no-viewBox hint as replacement values', () => {
+ const labelRect = { x: 100, y: 180, width: 48, height: 14, label: '写入' };
+ const obstacle = { id: 'memtool', x: 30, y: 130, width: 230, height: 58 };
+ assert.equal(suggestLabelObstacleFix(labelRect, 124, 188, obstacle), [
+ ' label rect: [100, 180, 48, 14]',
+ ' component "memtool" rect: [30, 130, 230, 58]',
+ ' Suggested fix: set labelAt [124, 202] or set labelDy 14 (below); or set labelAt [124, 126] or set labelDy -62 (above)',
+ ].join('\n'));
+});
+
+test('suggestLabelObstacleFix carries an x nudge into the relative form', () => {
+ const labelRect = { x: 512, y: 94, width: 236, height: 14, label: 'batched telemetry upload' };
+ const obstacle = { id: 'edge', x: 560, y: 60, width: 140, height: 54 };
+ const hint = suggestLabelObstacleFix(labelRect, 630, 104, obstacle, 'component', [720, 400]);
+ assert.match(hint, /set labelAt \[602, 128\] or set labelDx -28 with labelDy 24 \(below\)/);
+ assert.doesNotMatch(hint, /or set labelDy /);
+});
+
+// labelDx/labelDy are offsets from the automatic label point, so a suggestion
+// has to be expressed relative to the values the document already carries.
+test('suggestLabelObstacleFix measures its relative fix from the authored labelDx', () => {
+ const obstacle = { id: 'edge', x: 560, y: 60, width: 140, height: 54 };
+ const authoredAnchor = 750; // automatic point 630 plus the authored labelDx
+ const labelRect = {
+ relation: { label: 'batched telemetry upload', labelDx: 120 },
+ x: authoredAnchor - 118,
+ y: 94,
+ width: 236,
+ height: 14,
+ label: 'batched telemetry upload',
+ };
+ const hint = suggestLabelObstacleFix(labelRect, authoredAnchor, 104, obstacle, 'component', [720, 400]);
+ // 120 + 602 - 750 lands the automatic point at the clamped anchor; the
+ // anchor-relative -148 would land it 120px away.
+ assert.match(hint, /set labelAt \[602, 128\] or set labelDx -28 with labelDy 24 \(below\)/);
+});
+
+test('suggestLabelObstacleFix offers no relative fix while labelAt is authored', () => {
+ const obstacle = { id: 'right', x: 540, y: 336, width: 160, height: 54 };
+ const labelRect = {
+ relation: { label: 'synchronous call', labelAt: [660, 360] },
+ x: 542,
+ y: 350,
+ width: 236,
+ height: 14,
+ label: 'synchronous call',
+ };
+ const hint = suggestLabelObstacleFix(labelRect, 660, 360, obstacle, 'component', [720, 400]);
+ assert.match(hint, /Suggested fix: set labelAt \[602, 332\] \(above\)$/);
+ assert.doesNotMatch(hint, /labelD[xy]/);
+});
+
+// The deltas are emitted as integers, so a fractional anchor sitting exactly on
+// a canvas bound cannot be expressed relatively without landing back outside.
+test('suggestLabelObstacleFix drops a relative fix that integer deltas cannot land inside', () => {
+ const obstacle = { id: 'api', x: 520, y: 180, width: 140, height: 54 };
+ const rectFor = (anchorX) => ({
+ relation: { label: 'edge' },
+ x: anchorX - 100,
+ y: 190,
+ width: 200,
+ height: 14,
+ label: 'edge',
+ });
+ assert.doesNotMatch(
+ suggestLabelObstacleFix(rectFor(620.5), 620.5, 200, obstacle, 'component', [720, 400]),
+ /labelD[xy]/,
+ );
+ assert.match(
+ suggestLabelObstacleFix(rectFor(620), 620, 200, obstacle, 'component', [720, 400]),
+ /set labelAt \[620, 248\] or set labelDy 48 \(below\)/,
+ );
+});
+
+// A rounded anchor as the measurement base adds its own residual to the
+// residual of rounding the suggestion, which can drift the applied label past
+// the containment tolerance. Measure from the real anchor instead.
+test('suggestLabelObstacleFix measures its relative fix from a fractional anchor', () => {
+ const anchorY = 200.6;
+ const labelRect = {
+ relation: { label: 'edge', labelDy: 0.3 },
+ x: 240,
+ y: anchorY - 10,
+ width: 120,
+ height: 14,
+ label: 'edge',
+ };
+ const obstacle = { id: 'api', x: 260, y: 180, width: 140, height: 54 };
+ const hint = suggestLabelObstacleFix(labelRect, 300, anchorY, obstacle, 'component', [720, 400]);
+ const suggested = Number(hint.match(/set labelDy (-?\d+) \(below\)/)[1]);
+ const placement = obstacle.y + obstacle.height + 14;
+ const landsAt = anchorY - labelRect.relation.labelDy + suggested;
+ assert.ok(
+ Math.abs(landsAt - placement) <= 0.5,
+ `labelDy ${suggested} lands the label at ${landsAt}, ${Math.abs(landsAt - placement)}px from the ${placement} placement`,
+ );
+});
+
+test('suggestLabelObstacleFix treats a fractional authored labelDx as no horizontal move', () => {
+ const labelRect = {
+ relation: { label: 'edge', labelDx: 40.4 },
+ x: 240,
+ y: 190,
+ width: 120,
+ height: 14,
+ label: 'edge',
+ };
+ const obstacle = { id: 'api', x: 260, y: 180, width: 140, height: 54 };
+ const hint = suggestLabelObstacleFix(labelRect, 300, 200, obstacle, 'component', [720, 400]);
+ assert.match(hint, /set labelAt \[300, 248\] or set labelDy 48 \(below\)/);
+ assert.doesNotMatch(hint, /labelDx/);
+});
+
+test('suggestLabelObstacleFix keeps its labelAt inside a supplied viewBox', () => {
+ const labelRect = { x: 596, y: 190, width: 160, height: 14, label: 'long edge label' };
+ const obstacle = { id: 'api', x: 560, y: 180, width: 140, height: 60 };
+ const hint = suggestLabelObstacleFix(labelRect, 676, 200, obstacle, 'component', [720, 400]);
+ const [, x, y] = hint.match(/labelAt \[(-?\d+), (-?\d+)\]/).map(Number);
+ assert.ok(x - labelRect.width / 2 >= 0 && x + labelRect.width / 2 <= 720, `labelAt x ${x} leaves the canvas`);
+ assert.ok(y - 10 >= 0 && y - 10 + labelRect.height <= 400, `labelAt y ${y} leaves the canvas`);
+});
+
+test('suggestLabelObstacleFix drops a placement that would only trade the obstacle for a clipped edge', () => {
+ const labelRect = { x: 200, y: 356, width: 120, height: 14, label: 'commit' };
+ const obstacle = { id: 'store', x: 180, y: 336, width: 160, height: 54 };
+ const hint = suggestLabelObstacleFix(labelRect, 260, 366, obstacle, 'component', [720, 400]);
+ assert.doesNotMatch(hint, /\(below\)/);
+ assert.match(hint, /labelAt \[260, 332\].*\(above\)/);
+});
+
+test('suggestLabelObstacleFix reports when no in-canvas position clears the obstacle', () => {
+ const labelRect = { x: 40, y: 30, width: 120, height: 14, label: 'commit' };
+ const obstacle = { id: 'store', x: 0, y: 0, width: 720, height: 400 };
+ const hint = suggestLabelObstacleFix(labelRect, 100, 40, obstacle, 'component', [720, 400]);
+ assert.doesNotMatch(hint, /labelAt/);
+ assert.match(hint, /no position clears "store" inside the 720x400 viewBox/);
+});
+
+test('suggestLabelObstacleFix offers no coordinate for a label wider than the canvas', () => {
+ const labelRect = { x: -40, y: 190, width: 800, height: 14, label: 'a label nobody can fit' };
+ const obstacle = { id: 'api', x: 200, y: 180, width: 140, height: 54 };
+ const hint = suggestLabelObstacleFix(labelRect, 360, 200, obstacle, 'component', [720, 400]);
+ assert.doesNotMatch(hint, /labelAt|labelDx|labelDy/);
+ assert.match(hint, /no position clears "api" inside the 720x400 viewBox — shorten the label/);
+});
+
+test('cleanLabelCanvasContainmentProblems names both edges a corner overhang crosses and stays off standard', () => {
+ const labels = [{
+ relation: { id: 'a-to-b', from: 'a', to: 'b', label: 'over the corner' },
+ relationIndex: 0,
+ label: 'over the corner',
+ x: 680,
+ y: 392,
+ width: 60,
+ height: 14,
+ }];
+ const showcase = cleanLabelCanvasContainmentProblems({
+ labels,
+ viewBox: [720, 400],
+ diagramType: 'architecture',
+ relationCollection: 'connections',
+ profile: 'showcase',
+ });
+ assert.equal(showcase.length, 1);
+ assert.match(showcase[0], /extends past the right edge by 20px and bottom edge by 6px/);
+ assert.deepEqual(cleanLabelCanvasContainmentProblems({
+ labels,
+ viewBox: [720, 400],
+ diagramType: 'architecture',
+ relationCollection: 'connections',
+ profile: 'standard',
+ }), []);
+});
+
+// Label widths are estimated, so the rule has to sit above rounding noise and
+// below anything a reader would see as cut off.
+test('cleanLabelCanvasContainmentProblems ignores overhang under the 0.5px tolerance', () => {
+ const overhangingBy = (amount) => cleanLabelCanvasContainmentProblems({
+ labels: [{
+ relation: { id: 'a-to-b', from: 'a', to: 'b' },
+ relationIndex: 0,
+ label: 'edge',
+ x: 620 + amount,
+ y: 100,
+ width: 100,
+ height: 14,
+ }],
+ viewBox: [720, 400],
+ diagramType: 'architecture',
+ relationCollection: 'connections',
+ profile: 'showcase',
+ });
+ assert.deepEqual(overhangingBy(0.4), []);
+ assert.equal(overhangingBy(0.6).length, 1);
+ assert.match(overhangingBy(0.6)[0], /extends past the right edge by 0\.6px/);
});
test('suggestComponentSeparation proposes nudged pos', () => {
diff --git a/archify/test/layout-rules.test.mjs b/archify/test/layout-rules.test.mjs
index b432ddab..0e4559e8 100644
--- a/archify/test/layout-rules.test.mjs
+++ b/archify/test/layout-rules.test.mjs
@@ -1067,6 +1067,255 @@ test('sequence: showcase rejects a message label that hides an adjacent route',
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/);
+});
+
+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/);
+});
+
+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, /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\]/);
+});
+
+// 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 = [...stderr.matchAll(/labelAt \[(-?\d+), (-?\d+)\]/g)].map(([, x, y]) => [Number(x), Number(y)]);
+ 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 --git a/archify/test/render-output-checks.test.mjs b/archify/test/render-output-checks.test.mjs
index 0a7bbd47..4a3f3447 100644
--- a/archify/test/render-output-checks.test.mjs
+++ b/archify/test/render-output-checks.test.mjs
@@ -234,6 +234,54 @@ test('render output check: relationship labels cannot hide another shared-source
}
});
+// `check` also runs against artifacts it did not produce, so a label the SVG
+// canvas clips has to be measurable from the emitted markup alone.
+test('render output check: a relationship label cannot leave the canvas', () => {
+ for (const profile of ['standard', 'showcase']) {
+ const { code, result } = checkHtml(`label-canvas-${profile}`, `
+ <path data-edge-key="0" data-edge-id="approved" data-edge-from="dlq" data-edge-to="replay" data-composition-points="20,60;200,60" d="M 20 60 L 200 60" class="a-default" marker-end="url(#arrowhead)"/>
+ <g data-detail="context" data-edge-key="0" data-edge-id="approved" data-edge-from="dlq" data-edge-to="replay" data-edge-label="approved replay">
+ <rect x="200" y="48" width="60" height="14" rx="3" class="c-mask"/>
+ <text x="230" y="58">approved replay</text>
+ </g>
+ `, profile);
+
+ assert.equal(result.composition.metrics.labelCanvasOverflowIssues, 1);
+ const issue = result.composition.issues.find((item) => item.code === 'composition/label-canvas-containment');
+ assert.equal(issue.label, 'approved replay');
+ assert.deepEqual(issue.labelRect, { x: 200, y: 48, width: 60, height: 14 });
+ assert.deepEqual(issue.viewBox, [240, 160]);
+ assert.deepEqual(issue.overflowPx, { right: 20 });
+ assert.match(issue.detail, /extends past the right edge by 20px/);
+ // The rule owns no named check: it fails the receipt through composition,
+ // exactly like composition/desktop-readability.
+ assert.equal(result.checks.length, 9);
+ assert.ok(result.checks.every((check) => check.ok));
+ if (profile === 'standard') {
+ assert.equal(code, 0);
+ assert.equal(issue.severity, 'warning');
+ assert.deepEqual(result.composition.summary, { errors: 0, warnings: 1 });
+ } else {
+ assert.notEqual(code, 0);
+ assert.equal(issue.severity, 'error');
+ assert.deepEqual(result.composition.summary, { errors: 1, warnings: 0 });
+ assert.equal(result.ok, false);
+ }
+ }
+});
+
+test('render output check: a contained relationship label reports no overflow', () => {
+ const { code, result } = checkHtml('label-canvas-contained', `
+ <path data-edge-key="0" data-edge-id="approved" data-edge-from="dlq" data-edge-to="replay" data-composition-points="20,60;200,60" d="M 20 60 L 200 60" class="a-default" marker-end="url(#arrowhead)"/>
+ <g data-detail="context" data-edge-key="0" data-edge-id="approved" data-edge-from="dlq" data-edge-to="replay" data-edge-label="approved replay">
+ <rect x="170" y="48" width="60" height="14" rx="3" class="c-mask"/>
+ <text x="200" y="58">approved replay</text>
+ </g>
+ `, 'showcase');
+ assert.equal(code, 0);
+ assert.equal(result.composition.metrics.labelCanvasOverflowIssues, 0);
+});
+
test('render output check: repeated endpoint messages keep their own stable owner identity', () => {
const { code, result } = checkHtml('sequence-repeated-endpoints', `
<g data-edge-key="0" data-edge-from="client" data-edge-to="api" data-edge-label="first request">
diff --git a/docs/gallery.html b/docs/gallery.html
index 4d8bd854..66915f92 100644
--- a/docs/gallery.html
+++ b/docs/gallery.html
@@ -730,6 +730,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 29,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -830,6 +831,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 36,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -930,6 +932,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 15,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1030,6 +1033,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 36.3,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1130,6 +1134,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 119,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1230,6 +1235,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 57,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1330,6 +1336,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 22,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1430,6 +1437,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 9,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1530,6 +1538,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": null,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1630,6 +1639,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": null,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1730,6 +1740,7 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 20,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
diff --git a/docs/gallery/manifest.json b/docs/gallery/manifest.json
index 479a1d53..d8a6ea3e 100644
--- a/docs/gallery/manifest.json
+++ b/docs/gallery/manifest.json
@@ -82,6 +82,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 29,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -182,6 +183,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 36,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -282,6 +284,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 15,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -382,6 +385,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 36.3,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -482,6 +486,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 119,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -582,6 +587,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 57,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -682,6 +688,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 22,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -782,6 +789,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 9,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -882,6 +890,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": null,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -982,6 +991,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": null,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,
@@ -1082,6 +1092,7 @@
"ambiguousCorridors": 0,
"containerBorderRuns": 0,
"labelRouteClearanceIssues": 0,
+ "labelCanvasOverflowIssues": 0,
"minLabelRouteClearance": 20,
"desktopReadabilityIssues": 0,
"minProjectedNodeTextPx": null,