Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
fix(dataflow): fit fully automatic showcase layouts
tt-a1id1aa37fcda7b
diff --git a/archify/references/authoring-defaults.md b/archify/references/authoring-defaults.mdindex 7ccd576f..94dcd870 100644--- a/archify/references/authoring-defaults.md+++ b/archify/references/authoring-defaults.md@@ -36,6 +36,6 @@ Use one primary authored language from the user's choice or the request/conversaOmit `meta.visual_preset` for classic, `meta.subtitle` for a title-only header, `meta.legend` for truthful auto, and `meta.engineering_profile` for an ordinary system overview. Explicit styles and a subtitle require a user request. Use legend or deployment ownership under the [legend](authoring-contract.md#legend-contract) or [engineering profile](authoring-contract.md#engineering-profile-default) contracts. Branding is optional and explicit when a node names a real product; [Brand marks](brand-marks.md) gives lookup and capture rules for that branch. Never let a badge replace semantic type, label, or relationship facts. Set required `meta.output` to a portable POSIX-relative `.html` path within the working directory; see [Output path contracts](delivery-contract.md#output-path-contracts) for native path exceptions.-For new Workflow use schema v2, preserving v1 for a fixed legacy source; use its [layout contracts](../renderers/workflow/README.md#layout-contracts) when lane or group geometry needs detail. For Sequence omit `meta.column_fit` for spread columns on both automatic and authored canvases; preserve an authored `meta.viewBox`. Set `meta.column_fit: "fixed"` explicitly when historical fixed coordinates are required; use `spread` when a wide viewBox leaves unused horizontal space or meaningful labels need width. Describe a participant's internal action in a note on its surrounding real cross-participant message, preserving its meaning and order; Sequence self-message loops are not supported. For Lifecycle use schema v3: list the happy path in `mainPath` and author every transition, including the main path; the renderer places all other states and routes. Give an exit shared by several consecutive phases the same label so it draws once, and keep transition labels short; a recoverable failure needs a real transition back. Read [Mode placement](authoring-contract.md#mode-placement) when a mode-specific placement or viewport problem needs more detail.+For new Workflow use schema v2, preserving v1 for a fixed legacy source; use its [layout contracts](../renderers/workflow/README.md#layout-contracts) when lane or group geometry needs detail. For Sequence omit `meta.column_fit` for spread columns on both automatic and authored canvases; preserve an authored `meta.viewBox`. Set `meta.column_fit: "fixed"` explicitly when historical fixed coordinates are required; use `spread` when a wide viewBox leaves unused horizontal space or meaningful labels need width. Describe a participant's internal action in a note on its surrounding real cross-participant message, preserving its meaning and order; Sequence self-message loops are not supported. For a fresh Dataflow start with the stage/row grid, automatic canvas and node widths; add dimensions or route controls for supplied geometry or a measured constraint. For Lifecycle use schema v3: list the happy path in `mainPath` and author every transition, including the main path; the renderer places all other states and routes. Give an exit shared by several consecutive phases the same label so it draws once, and keep transition labels short; a recoverable failure needs a real transition back. Read [Mode placement](authoring-contract.md#mode-placement) when a mode-specific placement or viewport problem needs more detail.`finalize` performs the browser gate. Keep the complete drawing comfortably readable on desktop, with zero horizontal overflow. Use meaningful vertical rows and intrinsic-height page scroll when necessary. The 6px projected-text check is a failure floor; at 1440px, aim for ordinary context text around 7.5px or larger. See [Automated browser evidence](delivery-contract.md#automated-browser-evidence) when viewport evidence fails.diff --git a/archify/renderers/architecture/labels.mjs b/archify/renderers/architecture/labels.mjsindex fa819d28..6f0076b1 100644--- a/archify/renderers/architecture/labels.mjs+++ b/archify/renderers/architecture/labels.mjs@@ -1,215 +1,2 @@-import { normalizeRoutePoints, rectsOverlap, segmentRectClearanceWithin } from '../shared/geometry.mjs';-import { createSpatialGrid } from '../shared/spatial-grid.mjs';--// A bounded fallback for an unpinned label whose usual position collides.-// It never routes an edge, moves a node, expands the canvas, or rewrites input.-export function placeAutomaticLabels({- labels, routes, components, titles, viewBox, placementBottom = viewBox[1], fallbackRing = true, keepFallbackNearRoute = false,- gridSweep = false,-}) {- const placed = [...labels];- const obstacles = [...components, ...titles];- const segments = routes.flatMap(({ relationIndex, points }) => {- const normalized = normalizeRoutePoints(points);- return normalized.slice(1).map((end, index) => ({ relationIndex, start: normalized[index], end }));- });- const inside = rect => (- rect.x >= 0 && rect.y >= 0- && rect.x + rect.width <= viewBox[0] && rect.y + rect.height <= viewBox[1]- );- // The mask test asked every segment about every candidate position. Segments- // go into a uniform grid once, and a candidate only asks the cells it covers.- const SEGMENT_CELL = 120;- const segmentGrid = createSpatialGrid(SEGMENT_CELL);- for (const segment of segments) {- const [sx, sy] = segment.start;- const [ex, ey] = segment.end;- segmentGrid.insert({- minX: Math.min(sx, ex), maxX: Math.max(sx, ex),- minY: Math.min(sy, ey), maxY: Math.max(sy, ey),- }, segment);- }- const segmentsNear = (rect, margin) => segmentGrid.query({- minX: rect.x - margin, maxX: rect.x + rect.width + margin,- minY: rect.y - margin, maxY: rect.y + rect.height + margin,- });- const masksRoute = rect => {- for (const segment of segmentsNear(rect, 4)) {- if (segment.relationIndex === rect.relationIndex) continue;- if (segmentRectClearanceWithin(segment, rect, 4) + 0.0001 < 4) return true;- }- return false;- };- const overlapsLabel = (rect, index, gap = 0) => placed.some((other, otherIndex) => (- otherIndex !== index && rectsOverlap(rect, other, gap)- ));- const clear = (rect, index) => (- inside(rect) && rect.y + rect.height <= placementBottom- && !obstacles.some(obstacle => rectsOverlap(rect, obstacle, 2))- && !overlapsLabel(rect, index, 2) && !masksRoute(rect)- );- const rectAt = (label, lx, ly) => ({- ...label, lx, ly, x: lx - label.width / 2, y: ly - 10,- });- // An opted-in grid layout runs parallel lines through shared gaps. Rank- // every position along all of the label's own segments: beside the line- // first, then centred on its own line (the plate interrupts only that- // line), then stepping outward past neighbouring parallels.- const gridCandidates = (label) => {- const fractions = [0.5, 0.25, 0.75, 0.375, 0.625, 0.125, 0.875];- const ranked = [];- // A close parallel of another relationship on one side (a reciprocal- // pair) makes a label on that side read as the neighbour's: prefer the- // far side.- const parallelOnLowSide = (a, b, axis) => {- const across = 1 - axis;- const [low, high] = [Math.min(a[axis], b[axis]), Math.max(a[axis], b[axis])];- let nearest = null;- for (const other of segments) {- if (other.relationIndex === label.relationIndex) continue;- if (Math.abs(other.start[across] - other.end[across]) > 0.0001) continue;- const distance = other.start[across] - a[across];- if (Math.abs(distance) < 0.0001 || Math.abs(distance) > 36) continue;- const overlap = Math.min(high, Math.max(other.start[axis], other.end[axis]))- - Math.max(low, Math.min(other.start[axis], other.end[axis]));- if (overlap <= 0) continue;- if (nearest === null || Math.abs(distance) < Math.abs(nearest)) nearest = distance;- }- return nearest !== null && nearest < 0;- };- for (const { start: a, end: b } of segments.filter(segment => segment.relationIndex === label.relationIndex)) {- if (Math.abs(a[1] - b[1]) < 0.0001 && Math.abs(a[0] - b[0]) >= label.width + 16) {- const [above, below] = parallelOnLowSide(a, b, 0) ? [1, 0] : [0, 1];- for (const fraction of fractions) {- const x = a[0] + (b[0] - a[0]) * fraction;- if (Math.min(Math.abs(x - a[0]), Math.abs(x - b[0])) < label.width / 2 + 6) continue;- ranked.push([above, x, a[1] - 10], [below, x, a[1] + 20], [2, x, a[1] + 3], [3, x, a[1] - 18], [3, x, a[1] + 28]);- }- } else if (Math.abs(a[0] - b[0]) < 0.0001 && Math.abs(a[1] - b[1]) >= label.height + 16) {- const leftFirst = !parallelOnLowSide(a, b, 1);- for (const fraction of fractions) {- const y = a[1] + (b[1] - a[1]) * fraction;- if (Math.min(Math.abs(y - a[1]), Math.abs(y - b[1])) < label.height / 2 + 6) continue;- ranked.push([2, a[0], y + 3]);- [6, 14, 22, 30, 38, 46, 54].forEach((offset, step) => {- const tier = step === 0 ? 0 : step === 1 ? 1 : 2 + step;- const left = [tier + (leftFirst ? 0 : 0.5), a[0] - label.width / 2 - offset, y + 3];- const right = [tier + (leftFirst ? 0.5 : 0), a[0] + label.width / 2 + offset, y + 3];- ranked.push(left, right);- });- }- }- }- return ranked.map((entry, order) => [...entry, order])- .sort((left, right) => left[0] - right[0] || left[3] - right[3])- .map(([, lx, ly]) => [lx, ly]);- };-- for (const [index, label] of placed.entries()) {- const relation = label.relation;- if (['labelAt', 'labelDx', 'labelDy', 'labelSegment'].some(key => relation[key] !== undefined)) continue;- // Match actual defect thresholds before searching; a valid placement is- // not a reason to restyle the diagram. New placements leave extra space.- // The grid ranking already starts from the preferred position, so it- // also re-ranks labels whose default spot is merely valid.- if (!gridSweep && inside(label) && !components.some(component => rectsOverlap(label, component, -2))- && !titles.some(title => rectsOverlap(label, title))- && !overlapsLabel(label, index) && !masksRoute(label)) continue;- if (gridSweep) {- // Callers measure the plate one pixel higher than rectAt; test with a- // pixel of slack so the chosen position also passes their clearance.- const replacement = gridCandidates(label).map(([lx, ly]) => rectAt(label, lx, ly))- .find(rect => clear({ ...rect, x: rect.x - 1, y: rect.y - 1, width: rect.width + 2, height: rect.height + 2 }, index));- if (replacement) {- placed[index] = replacement;- continue;- }- }- for (const segment of segments.filter(segment => segment.relationIndex === label.relationIndex)) {- const [a, b] = [segment.start, segment.end];- let candidates = [];- if (Math.abs(a[1] - b[1]) < 0.0001 && Math.abs(a[0] - b[0]) >= label.width + 16) {- candidates = [0.5, 0.25, 0.75, 0.125, 0.875].flatMap(fraction => {- const x = a[0] + (b[0] - a[0]) * fraction;- if (Math.min(Math.abs(x - a[0]), Math.abs(x - b[0])) < 8) return [];- return [- [x, a[1] - 10],- [x, a[1] + 20],- [x, a[1] - 18],- [x, a[1] + 28],- ];- });- } else if (Math.abs(a[0] - b[0]) < 0.0001 && Math.abs(a[1] - b[1]) >= label.height + 16) {- candidates = [0.5, 0.25, 0.75, 0.125, 0.875].flatMap(fraction => {- const y = a[1] + (b[1] - a[1]) * fraction;- if (Math.min(Math.abs(y - a[1]), Math.abs(y - b[1])) < 8) return [];- return [- [a[0] - label.width / 2 - 6, y + 3],- [a[0] + label.width / 2 + 6, y + 3],- [a[0] - label.width / 2 - 14, y + 3],- [a[0] + label.width / 2 + 14, y + 3],- ];- });- }- const replacement = candidates.map(([lx, ly]) => rectAt(label, lx, ly))- .find(rect => clear(rect, index));- if (replacement) {- placed[index] = replacement;- break;- }- }- if (placed[index] !== label || !fallbackRing) continue;-- // Dense but valid topologies can leave every point directly beside the- // relationship occupied by another route. Search a small deterministic- // ring around the current anchor and the relationship's segment centres.- // A collision-free island above a node is not a readable edge label.- // Architecture opts into keeping the mask within two label heights of- // its own route; shared callers retain their existing policy. If no nearby- // slot fits, retain the collision so validation can request more space.- const ownSegments = segments.filter(segment => segment.relationIndex === label.relationIndex);- const baseAnchors = [- [label.lx, label.ly],- ...ownSegments.map(segment => [- (segment.start[0] + segment.end[0]) / 2,- (segment.start[1] + segment.end[1]) / 2,- ]),- ];- const horizontalStep = label.width / 2 + 12;- const ringOffsets = [- [0, -28], [0, 38],- [-horizontalStep, -28], [horizontalStep, -28],- [-horizontalStep, 38], [horizontalStep, 38],- [-(label.width + 20), -52], [label.width + 20, -52],- [-(label.width + 20), 62], [label.width + 20, 62],- [-(label.width + 20), -76], [label.width + 20, -76],- [-(label.width + 20), 86], [label.width + 20, 86],- ];- const fallback = baseAnchors.flatMap(([baseX, baseY]) => (- ringOffsets.map(([dx, dy]) => rectAt(label, baseX + dx, baseY + dy))- )).find(rect => clear(rect, index) && (!keepFallbackNearRoute || ownSegments.some(segment => (- segmentRectClearanceWithin(segment, rect, label.height * 2) <= label.height * 2- ))));- if (fallback) placed[index] = fallback;- }- return placed;-}--// The rect a single unpinned label would occupy given only its own route and-// the nodes: what the planner reserves before the remaining routes are laid.-// Only a placement beside the route itself is worth reserving; a label that-// would already need the fallback ring is left to the final placement pass.-export function reservedLabelRect({- label, points, routes = [], labels = [], components, viewBox = [Infinity, Infinity], placementBottom = Infinity,-}) {- const [rect] = placeAutomaticLabels({- labels: [{ ...label, relationIndex: -1 }, ...labels.map(other => ({ ...other, relationIndex: -2 }))],- routes: [{ relationIndex: -1, points }, ...routes],- components,- titles: [],- viewBox,- placementBottom,- fallbackRing: false,- });- return components.some(component => rectsOverlap(rect, component, -2)) ? null : rect;-}+// Compatibility exports for existing renderer and test imports.+export { placeAutomaticLabels, reservedLabelRect } from '../shared/automatic-labels.mjs';diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjsindex 0c3e9462..4b67b6d9 100644--- a/archify/renderers/architecture/render-architecture.mjs+++ b/archify/renderers/architecture/render-architecture.mjs@@ -11,7 +11,7 @@ import { minimumReadableSourceTextPx } from '../shared/desktop-readability.mjs';import { translateMessage as i18nText } from '../shared/i18n.mjs';import { gridLayout, resolveComponentPos, validateGridPlacement } from './grid.mjs';import { createRouter } from './routing.mjs';-import { placeAutomaticLabels, reservedLabelRect } from './labels.mjs';+import { placeAutomaticLabels, reservedLabelRect } from '../shared/automatic-labels.mjs';import { cleanRouteDetourProblems } from '../shared/route-quality.mjs';import {asArray,diff --git a/archify/renderers/dataflow/README.md b/archify/renderers/dataflow/README.mdindex 108a4b15..f7604e1a 100644--- a/archify/renderers/dataflow/README.md+++ b/archify/renderers/dataflow/README.md@@ -58,7 +58,7 @@ without a database node keeps it visual-only.| Constant | Value ||----------|-------|-| viewBox | default `[940, 720]`; schema minimum `[360, 360]` |+| viewBox | default `[940, 720]`; fully automatic showcase width covers all stage frames with 24px right padding (five stages need 1068), and height fits content; schema minimum `[360, 360]` || Stages (2–5) | centers at x = 100 + stage×215; stage band 168 wide, header at y 46 || Row tops (`row` 0–4) | y = 128, 242, 356, 470, 584 (plus `yOffset`) || Default node | 112×58 |@@ -70,6 +70,23 @@ without a database node keeps it visual-only.Route presets for flows: `straight`, `vertical-channel`, `bottom-channel`,`top-channel`, explicit `via` points, or the default `auto` (midpoint elbow).+Showcase improvements apply only when `meta.viewBox` and every node's `width`+are omitted. Any authored canvas or node width preserves the established+whole-diagram layout, as does `standard`.++For a fully automatic showcase, node widths can grow within their stage and+canvas budget to keep supporting text readable at desktop projection. Height+follows actual node bounds, routed points and rendered label plates, leaving+24px below content plus the 74px stage/legend reserve. Rows and authored routes+remain authoritative; inactive channel controls do not enlarge the canvas.++Automatic routes use perpendicular bridges for vertical ports and small+port-spread differences. Unpinned labels receive one bounded placement pass,+with at most 36px mask clearance from their own route. Distant free space is+rejected in favor of the original placement and its collision diagnostic.+Explicit `labelAt`, `labelDx`, `labelDy` and `labelSegment` remain authoritative,+including zero offsets. Existing valid labels are retained.+## Design Rules- Use stages for data lifecycle boundaries: source, ingest, process, store,diff --git a/archify/renderers/dataflow/render-dataflow.mjs b/archify/renderers/dataflow/render-dataflow.mjsindex 6203044b..a9cd2f27 100644--- a/archify/renderers/dataflow/render-dataflow.mjs+++ b/archify/renderers/dataflow/render-dataflow.mjs@@ -7,6 +7,8 @@ import { resolveLegend, renderLegend as renderResolvedLegend } from '../shared/limport { availableNodeTextWidth, fittedNodeFontSize, minimumNodeTextWidth, nodeLabelLayout } from '../shared/text-fit.mjs';import { brandLabelFitWidth, brandMarkFor, brandMetadataFor, brandTopRailProblem, renderBrandMark } from '../shared/brand-marks.mjs';import { translateMessage as i18nText } from '../shared/i18n.mjs';+import { minimumReadableSourceTextPx } from '../shared/desktop-readability.mjs';+import { placeAutomaticLabels } from '../shared/automatic-labels.mjs';import {asArray,isFinitePoint,@@ -23,6 +25,9 @@ import {suggestLabelPairFix,anchor,automaticPortSpread,+ automaticPortRhythmBridge,+ segmentIntersectsRect,+ segmentRectClearanceWithin,legacyDefaultFromSide as defaultFromSide,legacyDefaultToSide as defaultToSide,chosenSide,@@ -50,7 +55,6 @@ const { diagram: dataflow, template, outPath, sourceEvidence } = await loadDiagrdefaultExample: 'product-analytics.dataflow.json'});-const viewBox = dataflow.meta?.viewBox || [940, 720];const layout = {stageY: 46,stageH: 36,@@ -64,6 +68,20 @@ const layout = {labelH: 16};+// Explicit geometry opts the whole diagram into the established layout. This+// also preserves the spacing and typography around partially pinned nodes.+const automaticShowcase = dataflow.meta?.quality_profile === 'showcase'+ && dataflow.meta?.viewBox === undefined+ && !asArray(dataflow.nodes).some(node => node.width !== undefined);+const stageRight = stageX(asArray(dataflow.stages).length - 1) + layout.stageW / 2;+const viewBox = dataflow.meta?.viewBox || [+ automaticShowcase ? Math.max(940, Math.ceil(stageRight + 24)) : 940,+ 720,+];+const contextFontMinimum = automaticShowcase+ ? Math.max(6, Math.ceil(minimumReadableSourceTextPx(viewBox[0]) * 10) / 10)+ : 6;+function flowLabelSize(flow) {const longestLine = Math.max(textUnits(flow.label), textUnits(flow.classification || ''));return {@@ -89,12 +107,18 @@ function stageFrame(stage, index) {};}-const compositionFrames = asArray(dataflow.stages).map(stageFrame);-function measureNode(node) {- const width = node.width || layout.nodeW;- const height = node.height || layout.nodeH;const cx = stageX(node.stage);+ // Expand only unpinned showcase nodes, within their existing stage budget.+ // Very long text still gets an actionable error instead of an unbounded+ // canvas/typography feedback loop.+ const contextWidth = Math.max(0, ...[node.sublabel, node.tag].map(text =>+ text ? minimumNodeTextWidth(text, Math.max(7, contextFontMinimum)) + 8 : 0));+ const width = node.width || (automaticShowcase+ ? Math.max(layout.nodeW, Math.min(layout.stageW,+ (cx - 24) * 2, (viewBox[0] - 24 - cx) * 2, Math.ceil(contextWidth)))+ : layout.nodeW);+ const height = node.height || layout.nodeH;const y = layout.rowYs[node.row] + (node.yOffset || 0);return {...node,@@ -150,8 +174,8 @@ function validateDataflow() {// handles the ordinary case, this rejects what it cannot rescue.const availableTextW = availableNodeTextWidth(node.width);for (const [field, value, minimum] of [- ['Sublabel', node.sublabel, nodeTextFit.sublabelMinimum],- ['Tag', node.tag, nodeTextFit.tagMinimum],+ ['Sublabel', node.sublabel, contextFontMinimum],+ ['Tag', node.tag, contextFontMinimum],]) {if (!value) continue;const minimumW = minimumNodeTextWidth(value, minimum);@@ -285,13 +309,7 @@ function validateDataflow() {routeHint: 'adjust route/via or channelX/channelY so each turn uses a clear inter-stage corridor'}));- const labelRects = [];- for (const [flowIndex, flow] of asArray(dataflow.flows).entries()) {- if (!flow.label || !nodes.has(flow.from) || !nodes.has(flow.to)) continue;- const [lx, ly] = labelPoint(flow, pathFor(flow).points);- const { width, height } = flowLabelSize(flow);- labelRects.push({ relation: flow, relationIndex: flowIndex, label: flow.label, x: lx - width / 2, y: ly - 11, width, height, lx, ly });- }+ const labelRects = resolvedLabelRects;for (const rect of labelRects) {for (const node of nodes.values()) {if (rectsOverlap(rect, node, -2)) {@@ -356,6 +374,27 @@ function routeVia(flow, from, to, start, end) {}case 'auto':default: {+ const { fromSide, toSide } = flowSides(flow);+ const fromVertical = fromSide === 'top' || fromSide === 'bottom';+ const toVertical = toSide === 'top' || toSide === 'bottom';+ const acrossDelta = fromVertical && toVertical+ ? Math.abs(start[0] - end[0]) : Math.abs(start[1] - end[1]);+ if (automaticShowcase && acrossDelta > 0.0001 && acrossDelta < 16) {+ // Spread ports can differ by only 7px/14px. Reuse the bounded bridge+ // rather than emit a midpoint turn below our own rhythm floor.+ const bridge = automaticPortRhythmBridge(start, end, fromSide, toSide, {+ accept: points => ![...nodes.values()].some(node => (+ node.id !== from.id && node.id !== to.id && points.slice(1).some((point, index) =>+ segmentIntersectsRect({ start: points[index], end: point }, node, 2))+ )),+ });+ if (bridge) return bridge.slice(1, -1);+ }+ if (automaticShowcase && fromVertical && toVertical) {+ if (Math.abs(start[0] - end[0]) < 0.0001) return [];+ const midY = (start[1] + end[1]) / 2;+ return [[start[0], midY], [end[0], midY]];+ }if (Math.abs(start[1] - end[1]) < 4) return [];const midX = start[0] + (end[0] - start[0]) / 2;return [[midX, start[1]], [midX, end[1]]];@@ -406,6 +445,60 @@ function pathFor(flow) {return routed;}+const resolvedLabelPoints = new Map();+const initialLabelRects = asArray(dataflow.flows).flatMap((flow, relationIndex) => {+ if (!flow.label || !nodes.has(flow.from) || !nodes.has(flow.to)) return [];+ const [lx, ly] = labelPoint(flow, pathFor(flow).points);+ const { width, height } = flowLabelSize(flow);+ // The shared placer uses a 10px baseline inset; Dataflow masks use 11px.+ // Adapt the baseline so it tests exactly the rectangle we later render.+ return [{ relation: flow, relationIndex, label: flow.label,+ x: lx - width / 2, y: ly - 11, width, height, lx, ly: ly - 1 }];+});+// Routing depends on node geometry and canvas width, so its actual footprint+// can determine height without another copy of routeVia's preset rules.+const geometryBottom = Math.max(0,+ ...[...nodes.values()].map(node => node.y + node.height),+ ...asArray(dataflow.flows).flatMap(flow => nodes.has(flow.from) && nodes.has(flow.to)+ ? pathFor(flow).points.map(point => point[1]) : []));+function heightForLabels(labels) {+ const contentBottom = Math.max(geometryBottom, ...labels.map(rect => rect.y + rect.height));+ return Math.max(360, Math.ceil(contentBottom + 24 + layout.stageBottomPad));+}+if (automaticShowcase) viewBox[1] = heightForLabels(initialLabelRects);+const compositionFrames = asArray(dataflow.stages).map(stageFrame);++const resolvedLabelRects = (automaticShowcase ? placeAutomaticLabels({+ labels: initialLabelRects,+ routes: asArray(dataflow.flows).flatMap((flow, relationIndex) => (+ nodes.has(flow.from) && nodes.has(flow.to)+ ? [{ relationIndex, points: pathFor(flow).points }] : []+ )),+ components: [...nodes.values()],+ titles: compositionFrames.map(frame => ({ ...frame, height: layout.stageH })),+ viewBox,+ placementBottom: viewBox[1] - layout.stageBottomPad,+}) : initialLabelRects).map(rect => {+ // Dataflow has compact 16px plates. Permit one clearance gutter beyond+ // two plate heights (36px), which covers a label immediately above a node,+ // while rejecting a collision-free island far from the labelled route.+ const ownPoints = pathFor(rect.relation).points;+ const nearby = ownPoints.slice(1).some((point, index) =>+ segmentRectClearanceWithin({ start: ownPoints[index], end: point }, rect, 36) <= 36);+ const original = initialLabelRects.find(label => label.relation === rect.relation);+ const kept = nearby ? rect : original;+ const resolved = { ...kept, ly: kept.ly + 1 };+ if (automaticShowcase) resolvedLabelPoints.set(rect.relation, [resolved.lx, resolved.ly]);+ return resolved;+});++// A bounded label move may extend below the initial route footprint. Include+// its final rendered plate before drawing the stage frames and legend.+if (automaticShowcase) {+ viewBox[1] = heightForLabels(resolvedLabelRects);+ for (const frame of compositionFrames) frame.height = viewBox[1] - layout.stageY - layout.stageBottomPad;+}+// Header measurement follows 276970789's #257, including the ordinal.// Long titles wrap at the same legible floor instead of becoming invalid input.function stageHeaderText(stage, index) {@@ -458,8 +551,8 @@ function renderNode(node) {const accent = componentText[node.type] || 't-muted';const hasSub = node.sublabel != null && node.sublabel !== '';const labelFontSize = fittedNodeFontSize(node.label, brandLabelFitWidth(node, node.width), 10, 8);- const sublabelFontSize = fittedNodeFontSize(node.sublabel, node.width, nodeTextFit.sublabelPreferred, nodeTextFit.sublabelMinimum);- const tagFontSize = fittedNodeFontSize(node.tag, node.width, nodeTextFit.tagPreferred, nodeTextFit.tagMinimum);+ const sublabelFontSize = fittedNodeFontSize(node.sublabel, node.width, Math.max(nodeTextFit.sublabelPreferred, contextFontMinimum), contextFontMinimum);+ const tagFontSize = fittedNodeFontSize(node.tag, node.width, Math.max(nodeTextFit.tagPreferred, contextFontMinimum), contextFontMinimum);const textRows = [{ text: node.label, font: labelFontSize, y: 21 }];if (hasSub) textRows.push({ text: node.sublabel, font: sublabelFontSize, y: 37 });if (node.tag) textRows.push({ text: node.tag, font: tagFontSize, y: node.height - 11 });@@ -495,7 +588,7 @@ function renderFlowPath(flow, index) {function renderFlowLabel(flow, index) {const routed = pathFor(flow);- const [lx, ly] = labelPoint(flow, routed.points);+ const [lx, ly] = resolvedLabelPoints.get(flow) || labelPoint(flow, routed.points);const { width: labelW, height: labelH } = flowLabelSize(flow);const classification = flow.classification? `\n <text data-detail="fine" x="${lx}" y="${ly + 11}" class="t-dim" font-size="7" text-anchor="middle">${esc(flow.classification)}</text>`diff --git a/archify/renderers/shared/automatic-labels.mjs b/archify/renderers/shared/automatic-labels.mjsnew file mode 100644index 00000000..a44eb5fc--- /dev/null+++ b/archify/renderers/shared/automatic-labels.mjs@@ -0,0 +1,215 @@+import { normalizeRoutePoints, rectsOverlap, segmentRectClearanceWithin } from './geometry.mjs';+import { createSpatialGrid } from './spatial-grid.mjs';++// A bounded fallback for an unpinned label whose usual position collides.+// It never routes an edge, moves a node, expands the canvas, or rewrites input.+export function placeAutomaticLabels({+ labels, routes, components, titles, viewBox, placementBottom = viewBox[1], fallbackRing = true, keepFallbackNearRoute = false,+ gridSweep = false,+}) {+ const placed = [...labels];+ const obstacles = [...components, ...titles];+ const segments = routes.flatMap(({ relationIndex, points }) => {+ const normalized = normalizeRoutePoints(points);+ return normalized.slice(1).map((end, index) => ({ relationIndex, start: normalized[index], end }));+ });+ const inside = rect => (+ rect.x >= 0 && rect.y >= 0+ && rect.x + rect.width <= viewBox[0] && rect.y + rect.height <= viewBox[1]+ );+ // The mask test asked every segment about every candidate position. Segments+ // go into a uniform grid once, and a candidate only asks the cells it covers.+ const SEGMENT_CELL = 120;+ const segmentGrid = createSpatialGrid(SEGMENT_CELL);+ for (const segment of segments) {+ const [sx, sy] = segment.start;+ const [ex, ey] = segment.end;+ segmentGrid.insert({+ minX: Math.min(sx, ex), maxX: Math.max(sx, ex),+ minY: Math.min(sy, ey), maxY: Math.max(sy, ey),+ }, segment);+ }+ const segmentsNear = (rect, margin) => segmentGrid.query({+ minX: rect.x - margin, maxX: rect.x + rect.width + margin,+ minY: rect.y - margin, maxY: rect.y + rect.height + margin,+ });+ const masksRoute = rect => {+ for (const segment of segmentsNear(rect, 4)) {+ if (segment.relationIndex === rect.relationIndex) continue;+ if (segmentRectClearanceWithin(segment, rect, 4) + 0.0001 < 4) return true;+ }+ return false;+ };+ const overlapsLabel = (rect, index, gap = 0) => placed.some((other, otherIndex) => (+ otherIndex !== index && rectsOverlap(rect, other, gap)+ ));+ const clear = (rect, index) => (+ inside(rect) && rect.y + rect.height <= placementBottom+ && !obstacles.some(obstacle => rectsOverlap(rect, obstacle, 2))+ && !overlapsLabel(rect, index, 2) && !masksRoute(rect)+ );+ const rectAt = (label, lx, ly) => ({+ ...label, lx, ly, x: lx - label.width / 2, y: ly - 10,+ });+ // An opted-in grid layout runs parallel lines through shared gaps. Rank+ // every position along all of the label's own segments: beside the line+ // first, then centred on its own line (the plate interrupts only that+ // line), then stepping outward past neighbouring parallels.+ const gridCandidates = (label) => {+ const fractions = [0.5, 0.25, 0.75, 0.375, 0.625, 0.125, 0.875];+ const ranked = [];+ // A close parallel of another relationship on one side (a reciprocal+ // pair) makes a label on that side read as the neighbour's: prefer the+ // far side.+ const parallelOnLowSide = (a, b, axis) => {+ const across = 1 - axis;+ const [low, high] = [Math.min(a[axis], b[axis]), Math.max(a[axis], b[axis])];+ let nearest = null;+ for (const other of segments) {+ if (other.relationIndex === label.relationIndex) continue;+ if (Math.abs(other.start[across] - other.end[across]) > 0.0001) continue;+ const distance = other.start[across] - a[across];+ if (Math.abs(distance) < 0.0001 || Math.abs(distance) > 36) continue;+ const overlap = Math.min(high, Math.max(other.start[axis], other.end[axis]))+ - Math.max(low, Math.min(other.start[axis], other.end[axis]));+ if (overlap <= 0) continue;+ if (nearest === null || Math.abs(distance) < Math.abs(nearest)) nearest = distance;+ }+ return nearest !== null && nearest < 0;+ };+ for (const { start: a, end: b } of segments.filter(segment => segment.relationIndex === label.relationIndex)) {+ if (Math.abs(a[1] - b[1]) < 0.0001 && Math.abs(a[0] - b[0]) >= label.width + 16) {+ const [above, below] = parallelOnLowSide(a, b, 0) ? [1, 0] : [0, 1];+ for (const fraction of fractions) {+ const x = a[0] + (b[0] - a[0]) * fraction;+ if (Math.min(Math.abs(x - a[0]), Math.abs(x - b[0])) < label.width / 2 + 6) continue;+ ranked.push([above, x, a[1] - 10], [below, x, a[1] + 20], [2, x, a[1] + 3], [3, x, a[1] - 18], [3, x, a[1] + 28]);+ }+ } else if (Math.abs(a[0] - b[0]) < 0.0001 && Math.abs(a[1] - b[1]) >= label.height + 16) {+ const leftFirst = !parallelOnLowSide(a, b, 1);+ for (const fraction of fractions) {+ const y = a[1] + (b[1] - a[1]) * fraction;+ if (Math.min(Math.abs(y - a[1]), Math.abs(y - b[1])) < label.height / 2 + 6) continue;+ ranked.push([2, a[0], y + 3]);+ [6, 14, 22, 30, 38, 46, 54].forEach((offset, step) => {+ const tier = step === 0 ? 0 : step === 1 ? 1 : 2 + step;+ const left = [tier + (leftFirst ? 0 : 0.5), a[0] - label.width / 2 - offset, y + 3];+ const right = [tier + (leftFirst ? 0.5 : 0), a[0] + label.width / 2 + offset, y + 3];+ ranked.push(left, right);+ });+ }+ }+ }+ return ranked.map((entry, order) => [...entry, order])+ .sort((left, right) => left[0] - right[0] || left[3] - right[3])+ .map(([, lx, ly]) => [lx, ly]);+ };++ for (const [index, label] of placed.entries()) {+ const relation = label.relation;+ if (['labelAt', 'labelDx', 'labelDy', 'labelSegment'].some(key => relation[key] !== undefined)) continue;+ // Match actual defect thresholds before searching; a valid placement is+ // not a reason to restyle the diagram. New placements leave extra space.+ // The grid ranking already starts from the preferred position, so it+ // also re-ranks labels whose default spot is merely valid.+ if (!gridSweep && inside(label) && !components.some(component => rectsOverlap(label, component, -2))+ && !titles.some(title => rectsOverlap(label, title))+ && !overlapsLabel(label, index) && !masksRoute(label)) continue;+ if (gridSweep) {+ // Callers measure the plate one pixel higher than rectAt; test with a+ // pixel of slack so the chosen position also passes their clearance.+ const replacement = gridCandidates(label).map(([lx, ly]) => rectAt(label, lx, ly))+ .find(rect => clear({ ...rect, x: rect.x - 1, y: rect.y - 1, width: rect.width + 2, height: rect.height + 2 }, index));+ if (replacement) {+ placed[index] = replacement;+ continue;+ }+ }+ for (const segment of segments.filter(segment => segment.relationIndex === label.relationIndex)) {+ const [a, b] = [segment.start, segment.end];+ let candidates = [];+ if (Math.abs(a[1] - b[1]) < 0.0001 && Math.abs(a[0] - b[0]) >= label.width + 16) {+ candidates = [0.5, 0.25, 0.75, 0.125, 0.875].flatMap(fraction => {+ const x = a[0] + (b[0] - a[0]) * fraction;+ if (Math.min(Math.abs(x - a[0]), Math.abs(x - b[0])) < 8) return [];+ return [+ [x, a[1] - 10],+ [x, a[1] + 20],+ [x, a[1] - 18],+ [x, a[1] + 28],+ ];+ });+ } else if (Math.abs(a[0] - b[0]) < 0.0001 && Math.abs(a[1] - b[1]) >= label.height + 16) {+ candidates = [0.5, 0.25, 0.75, 0.125, 0.875].flatMap(fraction => {+ const y = a[1] + (b[1] - a[1]) * fraction;+ if (Math.min(Math.abs(y - a[1]), Math.abs(y - b[1])) < 8) return [];+ return [+ [a[0] - label.width / 2 - 6, y + 3],+ [a[0] + label.width / 2 + 6, y + 3],+ [a[0] - label.width / 2 - 14, y + 3],+ [a[0] + label.width / 2 + 14, y + 3],+ ];+ });+ }+ const replacement = candidates.map(([lx, ly]) => rectAt(label, lx, ly))+ .find(rect => clear(rect, index));+ if (replacement) {+ placed[index] = replacement;+ break;+ }+ }+ if (placed[index] !== label || !fallbackRing) continue;++ // Dense but valid topologies can leave every point directly beside the+ // relationship occupied by another route. Search a small deterministic+ // ring around the current anchor and the relationship's segment centres.+ // A collision-free island above a node is not a readable edge label.+ // Architecture opts into keeping the mask within two label heights of+ // its own route; shared callers retain their existing policy. If no nearby+ // slot fits, retain the collision so validation can request more space.+ const ownSegments = segments.filter(segment => segment.relationIndex === label.relationIndex);+ const baseAnchors = [+ [label.lx, label.ly],+ ...ownSegments.map(segment => [+ (segment.start[0] + segment.end[0]) / 2,+ (segment.start[1] + segment.end[1]) / 2,+ ]),+ ];+ const horizontalStep = label.width / 2 + 12;+ const ringOffsets = [+ [0, -28], [0, 38],+ [-horizontalStep, -28], [horizontalStep, -28],+ [-horizontalStep, 38], [horizontalStep, 38],+ [-(label.width + 20), -52], [label.width + 20, -52],+ [-(label.width + 20), 62], [label.width + 20, 62],+ [-(label.width + 20), -76], [label.width + 20, -76],+ [-(label.width + 20), 86], [label.width + 20, 86],+ ];+ const fallback = baseAnchors.flatMap(([baseX, baseY]) => (+ ringOffsets.map(([dx, dy]) => rectAt(label, baseX + dx, baseY + dy))+ )).find(rect => clear(rect, index) && (!keepFallbackNearRoute || ownSegments.some(segment => (+ segmentRectClearanceWithin(segment, rect, label.height * 2) <= label.height * 2+ ))));+ if (fallback) placed[index] = fallback;+ }+ return placed;+}++// The rect a single unpinned label would occupy given only its own route and+// the nodes: what the planner reserves before the remaining routes are laid.+// Only a placement beside the route itself is worth reserving; a label that+// would already need the fallback ring is left to the final placement pass.+export function reservedLabelRect({+ label, points, routes = [], labels = [], components, viewBox = [Infinity, Infinity], placementBottom = Infinity,+}) {+ const [rect] = placeAutomaticLabels({+ labels: [{ ...label, relationIndex: -1 }, ...labels.map(other => ({ ...other, relationIndex: -2 }))],+ routes: [{ relationIndex: -1, points }, ...routes],+ components,+ titles: [],+ viewBox,+ placementBottom,+ fallbackRing: false,+ });+ return components.some(component => rectsOverlap(rect, component, -2)) ? null : rect;+}diff --git a/test/dataflow-automatic-layout.test.mjs b/test/dataflow-automatic-layout.test.mjsnew file mode 100644index 00000000..e34ee419--- /dev/null+++ b/test/dataflow-automatic-layout.test.mjs@@ -0,0 +1,273 @@+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import { segmentRectClearanceWithin } from '../archify/renderers/shared/geometry.mjs';+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import test from 'node:test';+import { fileURLToPath } from 'node:url';++const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));+function inspect(t, diagram) {+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-dataflow-auto-'));+ t.after(() => fs.rmSync(cwd, { recursive: true, force: true }));+ const input = path.join(cwd, 'source.json');+ const source = JSON.stringify(diagram);+ fs.writeFileSync(input, source);+ const result = spawnSync(process.execPath, [cli, 'validate', 'dataflow', input, '--json'], { encoding: 'utf8' });+ assert.equal(fs.readFileSync(input, 'utf8'), source, 'automatic layout must not rewrite authored input');+ const receipt = JSON.parse(result.stdout);+ return { result, receipt, input, output: path.join(cwd, 'diagram.html') };+}+function pipeline() {+ return {+ schema_version: 1, diagram_type: 'dataflow',+ meta: { title: 'Request processing', output: 'diagram.html', quality_profile: 'showcase' },+ stages: ['Input', 'Prepare', 'Execute', 'Decode', 'Output'].map(label => ({ label })),+ nodes: [+ { id: 'input', type: 'frontend', label: 'Configuration', stage: 0, row: 0 },+ { id: 'prepare', type: 'backend', label: 'Invocation', stage: 1, row: 0 },+ { id: 'task', type: 'backend', label: 'Task', stage: 2, row: 0 },+ { id: 'provider', type: 'external', label: 'Provider', stage: 2, row: 2 },+ { id: 'bytes', type: 'external', label: 'Log bytes', stage: 3, row: 2 },+ { id: 'decoded', type: 'backend', label: 'Answer and status', stage: 3, row: 0,+ sublabel: 'success / failed / timeout / cancelled' },+ { id: 'output', type: 'backend', label: 'Ordered results', stage: 4, row: 0,+ sublabel: 'complete / partial / failed' },+ { id: 'archive', type: 'database', label: 'Archive', stage: 4, row: 2 },+ ],+ flows: [+ ['input', 'prepare', 'configuration'], ['prepare', 'task', 'task input'],+ ['task', 'provider', 'command'], ['provider', 'bytes', 'log bytes'],+ ['bytes', 'decoded', 'decode'], ['task', 'decoded', 'timeout / cancellation'],+ ['decoded', 'output', 'answer'], ['output', 'archive', 'save mode'],+ ].map(([from, to, label], index) => ({ id: `f${index}`, from, to, label })),+ };+}++test('five-stage unpinned pipeline passes first draft with complete text and projected typography', t => {+ const diagram = pipeline();+ const { result, receipt, input, output } = inspect(t, diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ assert.equal(receipt.composition.metrics.desktopReadabilityIssues, 0);+ assert.ok(receipt.composition.metrics.minProjectedNodeTextPx >= 6);+ const render = spawnSync(process.execPath, [cli, 'render', 'dataflow', input, output], { encoding: 'utf8' });+ assert.equal(render.status, 0, render.stderr);+ const html = fs.readFileSync(output, 'utf8');+ assert.match(html, /viewBox="0 0 1068 512"/);+ assert.match(html, /data-reader-fit="intrinsic-height"/);+ assert.ok(html.includes(diagram.nodes[5].sublabel));+ for (const flow of diagram.flows) {+ assert.ok(html.includes(flow.label), flow.label);+ const points = html.match(new RegExp(`<path[^>]*data-edge-id="${flow.id}"[^>]*data-composition-points="([^"]+)"`))[1]+ .split(';').map(point => point.split(',').map(Number));+ const mask = html.match(new RegExp(`<g data-detail="context"[^>]*data-edge-id="${flow.id}"[^>]*>\\s*<rect x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"`));+ const [x, y, width, height] = mask.slice(1).map(Number);+ assert.ok(points.slice(1).some((end, index) =>+ segmentRectClearanceWithin({ start: points[index], end }, { x, y, width, height }, 36) <= 36), flow.id);+ }+ assert.equal(receipt.composition.metrics.maxBends, 0, 'aligned routes must remain straight');+});++test('spread vertical ports use perpendicular bridges without tiny interior segments', t => {+ const diagram = pipeline();+ diagram.stages = [{ label: 'In' }, { label: 'Out' }];+ diagram.nodes = [+ { id: 'a', type: 'backend', label: 'Source', stage: 0, row: 0 },+ { id: 'b', type: 'backend', label: 'Local', stage: 0, row: 1 },+ { id: 'c', type: 'backend', label: 'Remote', stage: 1, row: 1 },+ ];+ diagram.flows = [+ { from: 'a', to: 'b', label: 'local' },+ { from: 'a', to: 'c', label: 'remote', fromSide: 'bottom', toSide: 'top' },+ ];+ const { result, receipt } = inspect(t, diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ assert.equal(receipt.composition.metrics.microSegmentCount, 0);+ assert.equal(receipt.composition.metrics.shortInteriorSegmentCount, 0);+ assert.ok(receipt.composition.metrics.minInteriorSegmentPx >= 16);+});++for (const pin of [{ labelAt: [530, 176] }, { labelDx: 0 }, { labelDy: 0 }, { labelSegment: 0 }]) {+ test(`authored ${Object.keys(pin)[0]} keeps its vertical-label collision`, t => {+ const diagram = pipeline();+ Object.assign(diagram.flows[2], pin);+ const { result, receipt } = inspect(t, diagram);+ assert.equal(result.status, 1);+ assert.ok(receipt.diagnostics.some(({ message }) => /Label "command" overlaps node "task"/.test(message)));+ });+}++test('explicit cross-row straight route and horizontal sides remain correctly rejected', t => {+ const diagram = pipeline();+ Object.assign(diagram.flows[3], { route: 'straight', fromSide: 'right', toSide: 'left' });+ diagram.nodes[4].row = 1;+ const { result, receipt } = inspect(t, diagram);+ assert.equal(result.status, 1);+ assert.ok(receipt.diagnostics.some(({ code }) => code === 'clean-flow/endpoint-side-direction'));+});++test('explicit canvas and node width retain the established typography and diagnostics', t => {+ const diagram = pipeline();+ diagram.meta.viewBox = [1180, 720];+ diagram.nodes[5].width = 160;+ const { result, receipt } = inspect(t, diagram);+ assert.equal(result.status, 1);+ assert.ok(receipt.diagnostics.some(({ message }) => /Label "command" overlaps node "task"/.test(message)));+ assert.ok(!receipt.diagnostics.some(({ message }) => /7\.7px legible minimum/.test(message)));+});++test('explicit wide adjacent nodes retain the 34px flow-length floor', t => {+ const diagram = pipeline();+ diagram.meta.viewBox = [1080, 720];+ diagram.nodes[5].width = 200;+ diagram.nodes[6].width = 180;+ const { result, receipt } = inspect(t, diagram);+ assert.equal(result.status, 1);+ assert.ok(receipt.diagnostics.some(({ message }) => /too short \(25px; minimum 34px\)/.test(message)));+});++test('standard keeps default node sizing and label failure instead of silently restyling', t => {+ const diagram = pipeline();+ diagram.meta.quality_profile = 'standard';+ const { result, receipt } = inspect(t, diagram);+ assert.equal(result.status, 1);+ assert.ok(receipt.diagnostics.some(({ message }) => /node "decoded" provides 104px/.test(message)));+ assert.ok(receipt.diagnostics.some(({ message }) => /Label "command" overlaps node "task"/.test(message)));+});++test('automatic labels reject a distant free island rather than lose the relationship', t => {+ const diagram = pipeline();+ diagram.stages = [{ label: 'In' }, { label: 'Out' }];+ diagram.nodes = [+ { id: 'a', type: 'backend', label: 'Source', stage: 0, row: 0,+ sublabel: 'Long supporting description for source', height: 100 },+ { id: 'b', type: 'backend', label: 'Target', stage: 1, row: 0,+ sublabel: 'Long supporting description for target', height: 100 },+ ];+ diagram.flows = [{ from: 'a', to: 'b', label: 'Long asset description' }];+ const { result, receipt } = inspect(t, diagram);+ assert.equal(result.status, 1);+ assert.ok(receipt.diagnostics.some(({ message }) => /Label "Long asset description" overlaps node/.test(message)));+});++test('natural height includes explicit outer route and two-line label plate', t => {+ const diagram = pipeline();+ diagram.stages = [{ label: 'In' }, { label: 'Out' }];+ diagram.nodes = [+ { id: 'a', type: 'backend', label: 'Source', stage: 0, row: 0 },+ { id: 'b', type: 'backend', label: 'Target', stage: 1, row: 0 },+ ];+ diagram.flows = [{ from: 'a', to: 'b', label: 'archive', classification: 'restricted',+ fromSide: 'bottom', toSide: 'bottom', via: [[100, 560], [315, 560]], labelAt: [210, 560] }];+ const { result, input, output } = inspect(t, diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ const render = spawnSync(process.execPath, [cli, 'render', 'dataflow', input, output], { encoding: 'utf8' });+ assert.equal(render.status, 0, render.stderr);+ const html = fs.readFileSync(output, 'utf8');+ assert.match(html, /viewBox="0 0 940 674"/);+ assert.match(html, /data-composition-points="100,186;100,560;315,560;315,186"/);+ assert.match(html, /<text x="210" y="560"/);+});++function smallFootprintDiagram(flow) {+ return {+ schema_version: 1, diagram_type: 'dataflow',+ meta: { title: 'Path footprint', output: 'diagram.html', quality_profile: 'showcase' },+ stages: [{ label: 'In' }, { label: 'Out' }],+ nodes: [+ { id: 'a', type: 'backend', label: 'Source', stage: 0, row: 0 },+ { id: 'b', type: 'backend', label: 'Target', stage: 1, row: 0 },+ ],+ flows: [{ from: 'a', to: 'b', label: 'data', ...flow }],+ };+}++function footprintSvg(t, diagram) {+ const { result, input, output } = inspect(t, diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ const render = spawnSync(process.execPath, [cli, 'render', 'dataflow', input, output], { encoding: 'utf8' });+ assert.equal(render.status, 0, render.stderr);+ return fs.readFileSync(output, 'utf8').match(/<svg\b[^]*?<\/svg>/)[0];+}++test('straight ignores inactive channelY in both route and natural height', t => {+ const plain = footprintSvg(t, smallFootprintDiagram({ route: 'straight' }));+ const inactive = footprintSvg(t, smallFootprintDiagram({ route: 'straight', channelY: 1500 }));+ assert.match(plain, /viewBox="0 0 940 360"/);+ assert.match(plain, /data-composition-points="156,157;259,157"/);+ assert.equal(inactive, plain);+});++test('explicit via overrides channelY in both route and natural height', t => {+ const flow = { route: 'bottom-channel', fromSide: 'bottom', toSide: 'bottom',+ via: [[100, 560], [315, 560]], labelAt: [210, 560], classification: 'restricted' };+ const plain = footprintSvg(t, smallFootprintDiagram(flow));+ const inactive = footprintSvg(t, smallFootprintDiagram({ ...flow, channelY: 1500 }));+ assert.match(plain, /viewBox="0 0 940 674"/);+ assert.equal(inactive, plain);+});++test('labelAt overrides labelDy in both label and natural height', t => {+ const flow = { route: 'straight', labelAt: [210, 210] };+ const plain = footprintSvg(t, smallFootprintDiagram(flow));+ const inactive = footprintSvg(t, smallFootprintDiagram({ ...flow, labelDy: 1500 }));+ assert.match(plain, /viewBox="0 0 940 360"/);+ assert.match(plain, /<text x="210" y="210"/);+ assert.equal(inactive, plain);+});++test('empty authored via also suppresses the preset channel footprint', t => {+ const flow = { route: 'bottom-channel', fromSide: 'right', toSide: 'left', via: [] };+ const plain = footprintSvg(t, smallFootprintDiagram(flow));+ const inactive = footprintSvg(t, smallFootprintDiagram({ ...flow, channelY: 1500 }));+ assert.match(plain, /viewBox="0 0 940 360"/);+ assert.equal(inactive, plain);+});++for (const [name, flow, expectedPoints, expectedHeight] of [+ ['default bottom channel', { route: 'bottom-channel', fromSide: 'bottom', toSide: 'bottom', labelAt: [210, 230] },+ '100,186;100,212;315,212;315,186', 360],+ ['authored bottom channel', { route: 'bottom-channel', fromSide: 'bottom', toSide: 'bottom', channelY: 700, labelAt: [210, 700], classification: 'restricted' },+ '100,186;100,700;315,700;315,186', 814],+ ['default top channel', { route: 'top-channel', fromSide: 'top', toSide: 'top', labelAt: [210, 100] },+ '100,128;100,104;315,104;315,128', 360],+ ['authored top channel', { route: 'top-channel', fromSide: 'bottom', toSide: 'bottom', channelY: 700, labelAt: [210, 700], classification: 'restricted' },+ '100,186;100,700;315,700;315,186', 814],+ ['authored label offset', { route: 'straight', labelDy: 550, classification: 'restricted' },+ '156,157;259,157', 811],+]) {+ test(`natural height contains actual points and final label plate for ${name}`, t => {+ const svg = footprintSvg(t, smallFootprintDiagram(flow));+ assert.ok(svg.includes(`viewBox="0 0 940 ${expectedHeight}"`), svg.slice(0, 200));+ assert.ok(svg.includes(`data-composition-points="${expectedPoints}"`));+ const contentBottom = expectedHeight - 74 - 24;+ for (const point of expectedPoints.split(';')) assert.ok(Number(point.split(',')[1]) <= contentBottom);+ const masks = [...svg.matchAll(/<rect\b[^>]*y="([\d.]+)"[^>]*height="([\d.]+)"[^>]*class="c-mask"/g)];+ assert.equal(masks.length, 3, 'two node masks and the rendered label plate must be measured');+ for (const match of masks) assert.ok(Number(match[1]) + Number(match[2]) <= contentBottom);+ });+}++// Frozen public SVG bytes from dev e23fc2c5. The complete HTML/receipt byte+// comparison is recorded in the PR evidence; SVG isolates renderer behavior+// from unrelated future Viewer-template changes.+for (const [name, mutate, expectedSha256] of [+ ['standard-auto', diagram => { diagram.meta.quality_profile = 'standard'; }, 'e0755ef81c30e0f0065b4766d586910f8d98354145ba7958776c3932ea40fc09'],+ ['explicit-viewbox', diagram => { diagram.meta.viewBox = [1080, 720]; }, '0517c0d97ba67919a6e3a0150abd4467fdcec0b01f32b667d086bba6be373e23'],+ ['explicit-one-width', diagram => { diagram.nodes[0].width = 152; }, 'd463001a31326170def94dce37c21967d24bc558ee404004cc9e29054db6cb36'],+ ['explicit-both', diagram => { diagram.meta.viewBox = [1080, 720]; diagram.nodes[0].width = 152; }, '258cb1e9c70c4e5377b69f4c7ef1dd04b964cc298f5061f963148f91037d9a61'],+]) {+ test(`dev byte compatibility for ${name}`, t => {+ const diagram = smallFootprintDiagram({ id: 'f' });+ diagram.nodes[0].sublabel = 'context text for processing';+ mutate(diagram);+ const { result, input, output } = inspect(t, diagram);+ assert.equal(result.status, name === 'explicit-viewbox' ? 1 : 0, result.stdout + result.stderr);+ const render = spawnSync(process.execPath, [cli, 'render', 'dataflow', input, output], { encoding: 'utf8' });+ assert.equal(render.status, 0, render.stderr);+ const svg = fs.readFileSync(output, 'utf8').match(/<svg\b[^]*?<\/svg>/)[0];+ assert.equal(crypto.createHash('sha256').update(svg).digest('hex'), expectedSha256);+ });+}