Skip to content

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

fix(dataflow): keep classification labels clear of connectors

tt-a1i492f171e8123
diff --git a/archify/renderers/dataflow/render-dataflow.mjs b/archify/renderers/dataflow/render-dataflow.mjs
index cac08f32..f792b7ef 100644
--- a/archify/renderers/dataflow/render-dataflow.mjs
+++ b/archify/renderers/dataflow/render-dataflow.mjs
@@ -482,14 +482,27 @@ function pathFor(flow) {
}
const resolvedLabelPoints = new Map();
+const twoLineOcclusions = new Set();
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 }];
+ const rect = { relation: flow, relationIndex, label: flow.label,
+ x: lx - width / 2, y: ly - 11, width, height, lx, ly: ly - 1 };
+ // Only repair the additional footprint of an unpinned second line. A
+ // single-line plate may intentionally interrupt its own route, especially
+ // on a vertical segment; that established placement remains authoritative.
+ if (flow.classification && !['labelAt', 'labelDx', 'labelDy', 'labelSegment'].some(key => flow[key] !== undefined)) {
+ const points = pathFor(flow).points;
+ const segments = points.slice(1).map((end, index) => ({ start: points[index], end }));
+ if (segments.some(segment => segmentIntersectsRect(segment, rect))
+ && !segments.some(segment => segmentIntersectsRect(segment, { ...rect, height: layout.labelH }))) {
+ twoLineOcclusions.add(flow);
+ }
+ }
+ return [rect];
});
// Routing depends on node geometry and canvas width, so its actual footprint
// can determine height without another copy of routeVia's preset rules.
@@ -528,6 +541,60 @@ const resolvedLabelRects = (automaticShowcase ? placeAutomaticLabels({
return resolved;
});
+// The ordinary shared placer allows a plate to interrupt its own connector.
+// For the second-line defect above, keep the complete plate beside the route
+// instead. This local search freezes all other labels and authored geometry,
+// and uses the same node/title/label/other-route checks as ordinary placement.
+for (const [index, rect] of resolvedLabelRects.entries()) {
+ if (!twoLineOcclusions.has(rect.relation)) continue;
+ const ownPoints = pathFor(rect.relation).points;
+ if (!ownPoints.slice(1).some((end, segmentIndex) => segmentIntersectsRect({ start: ownPoints[segmentIndex], end }, rect))) continue;
+ const original = initialLabelRects.find(label => label.relation === rect.relation);
+ const extraHeight = original.height - layout.labelH;
+ const preferred = { ...original, y: original.y - extraHeight, ly: original.ly - extraHeight };
+ const ownRouteBands = ownPoints.slice(1).map((end, segmentIndex) => {
+ const start = ownPoints[segmentIndex];
+ return {
+ x: Math.min(start[0], end[0]) - 2, y: Math.min(start[1], end[1]) - 2,
+ width: Math.abs(end[0] - start[0]) + 4, height: Math.abs(end[1] - start[1]) + 4,
+ };
+ });
+ const labels = resolvedLabelRects.map((other, otherIndex) => otherIndex === index ? preferred : {
+ ...other, ly: other.ly - 1,
+ relation: { ...other.relation, labelAt: [other.lx, other.ly] },
+ });
+ const routes = asArray(dataflow.flows).flatMap((flow, relationIndex) => (
+ nodes.has(flow.from) && nodes.has(flow.to) ? [{ relationIndex, points: pathFor(flow).points }] : []
+ ));
+ const titles = compositionFrames.map(frame => ({ ...frame, height: layout.stageH }));
+ const replacement = placeAutomaticLabels({
+ labels, routes,
+ components: [...nodes.values(), ...ownRouteBands],
+ titles,
+ viewBox,
+ placementBottom: viewBox[1] - layout.stageBottomPad,
+ keepFallbackNearRoute: true,
+ })[index];
+ // An exhausted shared search returns its supplied preferred rect. That is
+ // not proof of a safe replacement: preserve the previously accepted label
+ // if the complete footprint cannot fit near its connector without collisions.
+ const clear = replacement.x >= 0 && replacement.y >= 0
+ && replacement.x + replacement.width <= viewBox[0]
+ && replacement.y + replacement.height <= viewBox[1] - layout.stageBottomPad
+ && ![...nodes.values(), ...titles].some(obstacle => rectsOverlap(replacement, obstacle, 2))
+ && !resolvedLabelRects.some((other, otherIndex) => otherIndex !== index && rectsOverlap(replacement, other, 2))
+ && routes.every(route => route.points.slice(1).every((end, segmentIndex) => (
+ segmentRectClearanceWithin({ start: route.points[segmentIndex], end }, replacement, 4) >= 4
+ )))
+ && ownPoints.slice(1).some((end, segmentIndex) => (
+ segmentRectClearanceWithin({ start: ownPoints[segmentIndex], end }, replacement, 36) <= 36
+ ));
+ if (!clear) continue;
+ const resolved = { ...replacement, ly: replacement.ly + 1 };
+ resolvedLabelRects[index] = resolved;
+ resolvedLabelPoints.set(rect.relation, [resolved.lx, resolved.ly]);
+}
+
// 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) {
diff --git a/scripts/run-browser-tests.mjs b/scripts/run-browser-tests.mjs
index 959b827a..ebbd95c3 100644
--- a/scripts/run-browser-tests.mjs
+++ b/scripts/run-browser-tests.mjs
@@ -41,6 +41,7 @@ const testFiles = [
'repository-evidence-types-browser.test.mjs',
'tree-branches-browser.test.mjs',
'class-motion-browser.test.mjs',
+ 'dataflow-label-visibility-browser.test.mjs',
];
let options;
diff --git a/test/dataflow-label-visibility-browser.test.mjs b/test/dataflow-label-visibility-browser.test.mjs
new file mode 100644
index 00000000..07250f46
--- /dev/null
+++ b/test/dataflow-label-visibility-browser.test.mjs
@@ -0,0 +1,100 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';
+
+const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));
+const fixture = fileURLToPath(new URL('./fixtures/dataflow-label-visibility.json', import.meta.url));
+
+test('dataflow classification plates preserve their own connector in Read and Detail', async (t) => {
+ if (!Object.hasOwn(process.env, 'ARCHIFY_CHROME')) return t.skip('Set ARCHIFY_CHROME for real browser checks');
+ const chrome = findChrome();
+ assert.ok(chrome, 'The configured browser regression requires Chrome');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-dataflow-label-visibility-'));
+ const browser = new ChromeVisualBrowser(chrome);
+ try {
+ const artifact = path.join(dir, 'diagram.html');
+ execFileSync(process.execPath, [cli, 'render', 'dataflow', fixture, artifact], { stdio: ['ignore', 'pipe', 'pipe'] });
+ const session = await browser.sessionPromise;
+ for (const theme of ['light', 'dark']) {
+ for (const mode of ['read', 'full']) {
+ await t.test(`${theme}/${mode}`, async () => {
+ await browser.inspect({ artifactPath: artifact, width: 1440, height: 900, theme });
+ const evaluated = await browser.cdp.send('Runtime.evaluate', {
+ awaitPromise: true, returnByValue: true,
+ expression: `(async () => {
+ const panel = document.querySelector('.diagram-container');
+ if (${JSON.stringify(mode)} === 'full') {
+ const zoomIn = panel.querySelector('button[data-view="in"]');
+ for (let click = 0; click < 5 && Archify.view.state().scale < 1.75; click++) zoomIn.click();
+ }
+ await document.fonts.ready;
+ // Detail opacity transitions must finish before measuring visibility.
+ await Promise.all([...panel.getAnimations({ subtree: true })].map(animation => animation.finished.catch(() => {})));
+ const svg = panel.querySelector(':scope > svg');
+ const route = svg.querySelector('path[data-edge-id="launch"]');
+ const label = svg.querySelector('g[data-detail="context"][data-edge-id="launch"]');
+ const mask = label.querySelector('rect');
+ const rect = element => {
+ const box = element.getBoundingClientRect();
+ return { left: box.left, right: box.right, top: box.top, bottom: box.bottom };
+ };
+ const maskBox = rect(mask), matrix = route.getScreenCTM();
+ const stroke = getComputedStyle(route);
+ const length = route.getTotalLength();
+ const covered = [];
+ // This reproduction has one horizontal connector. Sample its actual
+ // rendered centerline against the actual opaque plate drawn above it.
+ for (let sample = 0; sample <= 200; sample++) {
+ const point = route.getPointAtLength(length * sample / 200).matrixTransform(matrix);
+ if (point.x > maskBox.left && point.x < maskBox.right
+ && point.y > maskBox.top && point.y < maskBox.bottom) covered.push(sample);
+ }
+ return {
+ theme: document.documentElement.dataset.theme,
+ mode: panel.dataset.detailLevel, scale: Archify.view.state().scale,
+ stroke: stroke.stroke, strokeOpacity: Number(stroke.strokeOpacity),
+ mask: { box: maskBox, fill: getComputedStyle(mask).fill, opacity: Number(getComputedStyle(mask).opacity) },
+ coveredSamples: covered.length,
+ labels: [...label.querySelectorAll('text')].map(text => ({
+ value: text.textContent, box: rect(text), fine: text.dataset.detail === 'fine',
+ opacity: Number(getComputedStyle(text).opacity), fill: getComputedStyle(text).fill,
+ })),
+ };
+ })()`,
+ }, session);
+ assert.equal(evaluated.exceptionDetails, undefined, evaluated.exceptionDetails?.text);
+ const observed = evaluated.result.value;
+ assert.equal(observed.theme, theme);
+ assert.equal(observed.mode, mode);
+ if (mode === 'read') assert.equal(observed.scale, 1);
+ else assert.ok(observed.scale >= 1.75, 'Detail must use the real zoom control');
+ assert.deepEqual(observed.labels.map(({ value }) => value), ['argv / JSON-RPC', 'Native flags']);
+ assert.notEqual(observed.stroke, 'none');
+ assert.notEqual(observed.stroke, observed.mask.fill, 'the connector must contrast with its plate');
+ assert.ok(observed.strokeOpacity > 0);
+ assert.notEqual(observed.mask.fill, 'none');
+ assert.equal(observed.mask.opacity, 1);
+ const classification = observed.labels.find(({ fine }) => fine);
+ assert.equal(classification.opacity, mode === 'read' ? 0 : 1, 'Read hides classification; Detail reveals it');
+ for (const label of observed.labels.filter(({ opacity }) => opacity > 0)) {
+ const box = label.box, mask = observed.mask.box;
+ assert.ok(box.left >= mask.left - 0.5 && box.right <= mask.right + 0.5
+ && box.top >= mask.top - 0.5 && box.bottom <= mask.bottom + 0.5,
+ 'real visible glyph bounds must fit the complete label plate: ' + JSON.stringify({ label, mask }));
+ assert.notEqual(label.fill, observed.mask.fill, 'the themed label must remain visible against its plate');
+ }
+ assert.equal(observed.coveredSamples, 0,
+ 'the complete classification plate must not conceal its own connector: ' + JSON.stringify(observed));
+ });
+ }
+ }
+ } finally {
+ await browser.close();
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/test/dataflow-label-visibility.test.mjs b/test/dataflow-label-visibility.test.mjs
new file mode 100644
index 00000000..82af5831
--- /dev/null
+++ b/test/dataflow-label-visibility.test.mjs
@@ -0,0 +1,129 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawnSync } from 'node:child_process';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+import { rectsOverlap, segmentRectClearanceWithin } from '../archify/renderers/shared/geometry.mjs';
+
+const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));
+const fixture = JSON.parse(fs.readFileSync(new URL('./fixtures/dataflow-label-visibility.json', import.meta.url)));
+function render(t, diagram) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-dataflow-label-visibility-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const input = path.join(directory, 'source.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = JSON.stringify(diagram);
+ fs.writeFileSync(input, source);
+ const env = { ...process.env, ARCHIFY_UPDATE_CHECK_DISABLED: '1' };
+ delete env.ARCHIFY_QUALITY_PROFILE;
+ const result = spawnSync(process.execPath, [cli, 'render', 'dataflow', input, output], { encoding: 'utf8', env });
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assert.equal(fs.readFileSync(input, 'utf8'), source);
+ return fs.readFileSync(output, 'utf8');
+}
+function flow(html, id = 'launch') {
+ const points = html.match(new RegExp(`<path[^>]*data-edge-id="${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="${id}"[^>]*>\\s*<rect x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"`));
+ const [x, y, width, height] = mask.slice(1).map(Number);
+ return { points, mask: { x, y, width, height } };
+}
+function clearRoute(mask, points) {
+ return points.slice(1).every((end, index) => segmentRectClearanceWithin({ start: points[index], end }, mask, 4) >= 4);
+}
+for (const quality of ['standard', 'showcase']) {
+ for (const authoredCanvas of [true, false]) {
+ test(`${quality} ${authoredCanvas ? 'authored' : 'automatic'} canvas keeps the entire two-line label above its short connector`, t => {
+ const diagram = structuredClone(fixture);
+ diagram.meta.quality_profile = quality;
+ if (!authoredCanvas) delete diagram.meta.viewBox;
+ const html = render(t, diagram);
+ const { points, mask } = flow(html);
+ assert.deepEqual(points, [[156, 157], [259, 157]]);
+ assert.equal(mask.height, 27);
+ assert.ok(clearRoute(mask, points), JSON.stringify({ mask, points }));
+ assert.match(html, /font-size="8"[^>]*>argv \/ JSON-RPC<\/text>/);
+ assert.match(html, /font-size="7"[^>]*>Native flags<\/text>/);
+ if (authoredCanvas) assert.match(html, /viewBox="0 0 600 360"/);
+ });
+ }
+}
+for (const pin of [{ labelAt: [207.5, 147] }, { labelDx: 0 }, { labelDy: 0 }, { labelSegment: 0 }]) {
+ test(`explicit ${Object.keys(pin)[0]} retains the authored label geometry, including zero`, t => {
+ const diagram = structuredClone(fixture);
+ Object.assign(diagram.flows[0], pin);
+ const { points, mask } = flow(render(t, diagram));
+ assert.deepEqual(points, [[156, 157], [259, 157]]);
+ assert.deepEqual(mask, { x: 164.75, y: 136, width: 85.5, height: 27 });
+ });
+}
+test('single-line labels retain their existing geometry', t => {
+ const diagram = structuredClone(fixture);
+ delete diagram.flows[0].classification;
+ assert.deepEqual(flow(render(t, diagram)).mask, { x: 164.75, y: 136, width: 85.5, height: 16 });
+});
+test('a neighboring pinned label does not push the two-line label back over its connector', t => {
+ const diagram = structuredClone(fixture);
+ diagram.flows.push({ id: 'neighbor', from: 'adapter', to: 'provider', label: 'neighbor', labelAt: [207.5, 123] });
+ const html = render(t, diagram);
+ const launch = flow(html);
+ const neighbor = flow(html, 'neighbor');
+ assert.ok(!rectsOverlap(launch.mask, neighbor.mask), JSON.stringify({ launch, neighbor }));
+ assert.ok(clearRoute(launch.mask, launch.points), JSON.stringify(launch));
+});
+test('two-line labels respect stage titles and nodes with authored routes', t => {
+ const diagram = structuredClone(fixture);
+ diagram.flows[0].via = [[156, 90], [259, 90]];
+ const html = render(t, diagram);
+ const { points, mask } = flow(html);
+ assert.deepEqual(points, [[156, 157], [156, 90], [259, 90], [259, 157]]);
+ assert.ok(clearRoute(mask, points), JSON.stringify({ mask, points }));
+ for (const x of [16, 231]) assert.ok(!rectsOverlap(mask, { x, y: 46, width: 168, height: 36 }), JSON.stringify(mask));
+ for (const x of [44, 259]) assert.ok(!rectsOverlap(mask, { x, y: 128, width: 112, height: 58 }), JSON.stringify(mask));
+});
+test('a neighboring route cannot push the two-line label back over either connector', t => {
+ const diagram = structuredClone(fixture);
+ diagram.flows.push({ id: 'neighbor', from: 'adapter', to: 'provider', label: 'neighbor',
+ labelAt: [400, 100], via: [[156, 136], [259, 136]] });
+ const html = render(t, diagram);
+ const launch = flow(html);
+ const neighbor = flow(html, 'neighbor');
+ assert.ok(clearRoute(launch.mask, launch.points), JSON.stringify(launch));
+ assert.ok(clearRoute(launch.mask, neighbor.points), JSON.stringify({ launch, neighbor }));
+});
+test('a classified vertical label already beside its own connector retains its placement', t => {
+ const diagram = structuredClone(fixture);
+ delete diagram.meta.viewBox;
+ diagram.meta.quality_profile = 'showcase';
+ diagram.nodes[1].stage = 0;
+ diagram.nodes[1].row = 1;
+ const result = flow(render(t, diagram));
+ assert.deepEqual(result.points, [[100, 186], [100, 242]]);
+ assert.deepEqual(result.mask, { x: 8.5, y: 207, width: 85.5, height: 27 });
+});
+test('an authored two-line interruption on a long connector remains valid and unchanged', t => {
+ const diagram = structuredClone(fixture);
+ diagram.meta.viewBox = [1080, 360];
+ diagram.stages.push({ label: 'Middle' }, { label: 'End' });
+ diagram.nodes[1].stage = 3;
+ diagram.flows[0].labelAt = [422.5, 157];
+ const result = flow(render(t, diagram));
+ assert.deepEqual(result.points, [[156, 157], [689, 157]]);
+ assert.deepEqual(result.mask, { x: 379.75, y: 146, width: 85.5, height: 27 });
+ assert.ok(!clearRoute(result.mask, result.points), 'the intentionally interrupted own line must remain accepted');
+});
+test('an exhausted label search preserves the previous accepted placement instead of adding a collision', t => {
+ const diagram = structuredClone(fixture);
+ const anchors = [[100, 100], [100, 220], [207.5, 123], [207.5, 200], [315, 100], [315, 220]];
+ diagram.flows.push(...anchors.map((labelAt, index) => ({
+ id: `block${index}`, from: 'adapter', to: 'provider', label: 'neighbor label',
+ labelAt, via: [[156, 310], [259, 310]],
+ })));
+ const html = render(t, diagram);
+ const launch = flow(html);
+ assert.deepEqual(launch.points, [[156, 157], [259, 157]]);
+ assert.deepEqual(launch.mask, { x: 164.75, y: 136, width: 85.5, height: 27 });
+ for (const index of anchors.keys()) assert.ok(!rectsOverlap(launch.mask, flow(html, `block${index}`).mask, -2));
+});
diff --git a/test/fixtures/dataflow-label-visibility.json b/test/fixtures/dataflow-label-visibility.json
new file mode 100644
index 00000000..7938bb6f
--- /dev/null
+++ b/test/fixtures/dataflow-label-visibility.json
@@ -0,0 +1,11 @@
+{
+ "schema_version": 1,
+ "diagram_type": "dataflow",
+ "meta": { "title": "Two-line flow label visibility", "output": "diagram.html", "locale": "en", "viewBox": [600, 360] },
+ "stages": [{ "label": "Caller" }, { "label": "Process" }],
+ "nodes": [
+ { "id": "adapter", "type": "backend", "label": "Adapter", "stage": 0, "row": 0 },
+ { "id": "provider", "type": "external", "label": "Provider CLI", "stage": 1, "row": 0 }
+ ],
+ "flows": [{ "id": "launch", "from": "adapter", "to": "provider", "label": "argv / JSON-RPC", "classification": "Native flags", "variant": "security" }]
+}