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): measure containment from the viewBox origin and the label's own rect

Rererr0be0b07ba21b
diff --git a/archify.zip b/archify.zip
index 12aa7cd9..1bc73555 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjs
index 2a41facc..8757a5c2 100644
--- a/archify/renderers/shared/geometry.mjs
+++ b/archify/renderers/shared/geometry.mjs
@@ -946,9 +946,9 @@ 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) {
+function axisCanvasOverflow(start, size, extent, origin = 0) {
if (!Number.isFinite(extent)) return { start: 0, end: 0 };
- return { start: -start, end: start + size - extent };
+ return { start: origin - start, end: start + size - (origin + extent) };
}
// THE CANVAS CONTAINMENT RATIONALE (referenced from the other call sites).
@@ -969,14 +969,18 @@ function axisCanvasOverflow(start, size, extent) {
// 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 [];
+ // Renderers author origin-zero canvases (meta.viewBox is [width, height] by
+ // schema), but `check` re-measures foreign artifacts whose SVG viewBox may
+ // carry a legal non-zero min-x/min-y; those pass all four numbers.
+ const box = asArray(viewBox);
+ const [originX, originY, canvasWidth, canvasHeight] = box.length === 4 ? box : [0, 0, box[0], box[1]];
+ if (!isFinitePoint(originX, originY, 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 horizontal = axisCanvasOverflow(rect.x, rect.width, canvasWidth, originX);
+ const vertical = axisCanvasOverflow(rect.y, rect.height, canvasHeight, originY);
const overflow = {
left: horizontal.start,
right: horizontal.end,
@@ -991,6 +995,7 @@ export function collectLabelCanvasOverflow({ labels, viewBox, tolerance = 0.5 })
relationIndex: Number.isInteger(label?.relationIndex) ? label.relationIndex : fallbackIndex,
rect,
viewBox: [canvasWidth, canvasHeight],
+ viewBoxOrigin: [originX, originY],
sides,
overflowPx: Object.fromEntries(sides.map((side) => [side, Math.round(overflow[side] * 10) / 10])),
tolerance,
@@ -1524,11 +1529,22 @@ export function suggestLabelObstacleFix(labelRect, lx, ly, obstacle, obstacleKin
const xOffset = labelRect.x - lx;
const yOffset = labelRect.y - ly;
const anchorX = clampAnchorToCanvas(lx, xOffset, labelRect.width, canvasWidth);
+ // The placement anchors are derived from the label's own rect, not from the
+ // obstacle alone: an obstacle-only "above" anchor assumes the 14px
+ // single-line rect and lands a 27px two-line rect (dataflow classification,
+ // lifecycle note) back on the obstacle it must clear. The overlap filter
+ // uses the callers' own detection call, so a surviving hint cannot re-raise
+ // the problem it repairs.
const placements = [
- { name: 'below', y: Math.round(obstacle.y + obstacle.height + 14) },
- { name: 'above', y: Math.round(obstacle.y - 4) },
+ { name: 'below', y: Math.round(obstacle.y + obstacle.height + 4 - yOffset) },
+ { name: 'above', y: Math.round(obstacle.y - 4 - labelRect.height - yOffset) },
].filter(({ y }) => anchorX !== null
- && anchorFitsCanvas(y, yOffset, labelRect.height, canvasHeight));
+ && anchorFitsCanvas(y, yOffset, labelRect.height, canvasHeight)
+ && !rectsOverlap(
+ { x: anchorX + xOffset, y: y + yOffset, width: labelRect.width, height: labelRect.height },
+ obstacle,
+ -2,
+ ));
const lines = [
` label rect: ${formatRect(labelRect)}`,
` ${obstacleKind} "${obstacle.id}" rect: ${formatRect(obstacle)}`,
diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjs
index bb28df11..f890d24f 100644
--- a/archify/scripts/check-render-output.mjs
+++ b/archify/scripts/check-render-output.mjs
@@ -119,7 +119,7 @@ if (svgMatches.length === 1) {
// shared/geometry.mjs.
const labelCanvasOverflow = collectLabelCanvasOverflow({
labels: relationshipLabels,
- viewBox: viewBoxSize(svgAttrs),
+ viewBox: viewBoxRect(svgAttrs),
});
const crossingIsError = qualityProfile === 'showcase';
const corridorIsError = qualityProfile === 'showcase';
@@ -196,8 +196,9 @@ if (svgMatches.length === 1) {
relationship: relationshipRecord(hit.relation),
labelRect: roundedRect(hit.rect),
viewBox: hit.viewBox,
+ viewBoxOrigin: hit.viewBoxOrigin,
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.`,
+ 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]}${hit.viewBoxOrigin.some(Boolean) ? ` at ${hit.viewBoxOrigin[0]},${hit.viewBoxOrigin[1]}` : ''}) — adjust labelAt, labelDx, labelDy, or labelSegment; otherwise enlarge meta.viewBox.`,
})),
...relationshipCrossings.map((hit) => ({
severity: crossingIsError ? 'error' : 'warning',
@@ -640,9 +641,15 @@ function textBox(attrs, text) {
};
}
-function viewBoxSize(svgAttrs) {
+// A foreign artifact may author a legal non-zero viewBox origin, so containment
+// needs all four numbers; sizing checks read the trailing pair.
+function viewBoxRect(svgAttrs) {
const viewBox = String(svgAttrs.viewBox || '').trim().split(/[\s,]+/).map(Number);
- return viewBox.length === 4 ? [viewBox[2], viewBox[3]] : [Number.NaN, Number.NaN];
+ return viewBox.length === 4 ? viewBox : [Number.NaN, Number.NaN, Number.NaN, Number.NaN];
+}
+
+function viewBoxSize(svgAttrs) {
+ return viewBoxRect(svgAttrs).slice(2);
}
function formatRectDetail(rect) {
diff --git a/archify/test/geometry.test.mjs b/archify/test/geometry.test.mjs
index 05ccb590..737bc8c6 100644
--- a/archify/test/geometry.test.mjs
+++ b/archify/test/geometry.test.mjs
@@ -686,7 +686,7 @@ test('suggestLabelObstacleFix states its no-viewBox hint as replacement values',
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)',
+ ' Suggested fix: set labelAt [124, 200] or set labelDy 12 (below); or set labelAt [124, 120] or set labelDy -68 (above)',
].join('\n'));
});
@@ -728,7 +728,7 @@ test('suggestLabelObstacleFix offers no relative fix while labelAt is authored',
label: 'synchronous call',
};
const hint = suggestLabelObstacleFix(labelRect, 660, 360, obstacle, 'component', [720, 400]);
- assert.match(hint, /Suggested fix: set labelAt \[602, 332\] \(above\)$/);
+ assert.match(hint, /Suggested fix: set labelAt \[602, 328\] \(above\)$/);
assert.doesNotMatch(hint, /labelD[xy]/);
});
@@ -807,7 +807,40 @@ test('suggestLabelObstacleFix drops a placement that would only trade the obstac
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\)/);
+ assert.match(hint, /labelAt \[260, 328\].*\(above\)/);
+});
+
+// The obstacle-only above anchor assumed the 14px single-line rect: applied to
+// a 27px two-line rect (dataflow classification, lifecycle note) it left the
+// label 12px inside the obstacle and the validator repeated the same hint.
+test('suggestLabelObstacleFix keeps both two-line forms clear of the obstacle it names', () => {
+ const cases = [
+ { labelRect: { x: 67, y: 139, width: 66, height: 27, label: 'clickstream' },
+ lx: 100, ly: 150,
+ obstacle: { id: 'web', x: 44, y: 128, width: 112, height: 58 },
+ viewBox: [1080, 760] },
+ { labelRect: { x: 360, y: 169, width: 81, height: 27, label: 'needs approval' },
+ lx: 400, ly: 180,
+ obstacle: { id: 'executing', x: 343, y: 126, width: 118, height: 62 },
+ viewBox: [980, 660] },
+ ];
+ for (const { labelRect, lx, ly, obstacle, viewBox } of cases) {
+ const hint = suggestLabelObstacleFix(labelRect, lx, ly, obstacle, 'node', viewBox);
+ const placements = [...hint.matchAll(/set labelAt \[(-?\d+), (-?\d+)\][^;]*\((above|below)\)/g)];
+ assert.equal(placements.length, 2, hint);
+ for (const [, x, y] of placements) {
+ const applied = {
+ x: Number(x) + (labelRect.x - lx),
+ y: Number(y) + (labelRect.y - ly),
+ width: labelRect.width,
+ height: labelRect.height,
+ };
+ assert.ok(
+ !rectsOverlap(applied, obstacle, -2),
+ `${hint}\napplied rect [${applied.x}, ${applied.y}, ${applied.width}, ${applied.height}] lands on "${obstacle.id}"`,
+ );
+ }
+ }
});
test('suggestLabelObstacleFix reports when no in-canvas position clears the obstacle', () => {
diff --git a/archify/test/layout-rules.test.mjs b/archify/test/layout-rules.test.mjs
index 0e4559e8..0e91ec29 100644
--- a/archify/test/layout-rules.test.mjs
+++ b/archify/test/layout-rules.test.mjs
@@ -1169,6 +1169,52 @@ test('lifecycle: showcase rejects a transition label that leaves the canvas', ()
assert.match(stderr, /extends past the right edge by 64\.4px .*viewBox 980x660/);
});
+// 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);
diff --git a/archify/test/render-output-checks.test.mjs b/archify/test/render-output-checks.test.mjs
index 4a3f3447..115e775d 100644
--- a/archify/test/render-output-checks.test.mjs
+++ b/archify/test/render-output-checks.test.mjs
@@ -282,6 +282,51 @@ test('render output check: a contained relationship label reports no overflow',
assert.equal(result.composition.metrics.labelCanvasOverflowIssues, 0);
});
+// A foreign artifact may author a legal non-zero viewBox origin, so containment
+// is measured against [min-x, min-x + width], not [0, width]: measuring from
+// zero passed a label the canvas clips and rejected a contained one.
+test('render output check: label containment respects a positive viewBox origin', () => {
+ const svgFor = (rect) => `
+ <path data-edge-key="0" data-edge-from="a" data-edge-to="b" data-composition-points="110,80;330,80" d="M 110 80 L 330 80" class="a-default" marker-end="url(#arrowhead)"/>
+ <g data-edge-key="0" data-edge-from="a" data-edge-to="b" data-edge-label="ship">
+ <rect x="${rect.x}" y="${rect.y}" width="${rect.width}" height="${rect.height}" rx="3" class="c-mask"/>
+ <text x="${rect.x + rect.width / 2}" y="${rect.y + 10}">ship</text>
+ </g>
+ `;
+
+ const contained = checkHtml('origin-positive-contained', svgFor({ x: 280, y: 48, width: 40, height: 14 }), 'showcase', '100 0 240 160');
+ assert.equal(contained.code, 0, JSON.stringify(contained.result.composition.issues));
+ assert.equal(contained.result.composition.metrics.labelCanvasOverflowIssues, 0);
+
+ const clipped = checkHtml('origin-positive-clipped', svgFor({ x: 80, y: 48, width: 60, height: 14 }), 'showcase', '100 0 240 160');
+ assert.notEqual(clipped.code, 0);
+ const issue = clipped.result.composition.issues.find((item) => item.code === 'composition/label-canvas-containment');
+ assert.deepEqual(issue.overflowPx, { left: 20 });
+ assert.deepEqual(issue.viewBoxOrigin, [100, 0]);
+ assert.match(issue.detail, /extends past the left edge by 20px \(label rect \[80, 48, 60, 14\]; viewBox 240x160 at 100,0\)/);
+});
+
+test('render output check: label containment respects a negative viewBox origin', () => {
+ const svgFor = (rect) => `
+ <path data-edge-key="0" data-edge-from="a" data-edge-to="b" data-composition-points="-40,80;170,80" d="M -40 80 L 170 80" class="a-default" marker-end="url(#arrowhead)"/>
+ <g data-edge-key="0" data-edge-from="a" data-edge-to="b" data-edge-label="ship">
+ <rect x="${rect.x}" y="${rect.y}" width="${rect.width}" height="${rect.height}" rx="3" class="c-mask"/>
+ <text x="${rect.x + rect.width / 2}" y="${rect.y + 10}">ship</text>
+ </g>
+ `;
+
+ const contained = checkHtml('origin-negative-contained', svgFor({ x: -50, y: -30, width: 40, height: 14 }), 'showcase', '-60 -40 240 160');
+ assert.equal(contained.code, 0, JSON.stringify(contained.result.composition.issues));
+ assert.equal(contained.result.composition.metrics.labelCanvasOverflowIssues, 0);
+
+ const clipped = checkHtml('origin-negative-clipped', svgFor({ x: 150, y: 48, width: 60, height: 14 }), 'showcase', '-60 -40 240 160');
+ assert.notEqual(clipped.code, 0);
+ const issue = clipped.result.composition.issues.find((item) => item.code === 'composition/label-canvas-containment');
+ assert.deepEqual(issue.overflowPx, { right: 30 });
+ assert.deepEqual(issue.viewBoxOrigin, [-60, -40]);
+ assert.match(issue.detail, /extends past the right edge by 30px \(label rect \[150, 48, 60, 14\]; viewBox 240x160 at -60,-40\)/);
+});
+
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">