Skip to content

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

fix(erd): give unpinned first drafts room and clear placement for labels and routes

tt-a1i67bf1aa53ec8
diff --git a/archify/renderers/architecture/routing.mjs b/archify/renderers/architecture/routing.mjs
index f2e8ed9c..fdfd40f7 100644
--- a/archify/renderers/architecture/routing.mjs
+++ b/archify/renderers/architecture/routing.mjs
@@ -45,6 +45,11 @@ import { shortestOrthogonalGridRoute } from '../shared/route-quality.mjs';
* @param {(context: {conn: object, from: object, to: object, start: number[], end: number[], fromSide: string, toSide: string}) => number[][][]} [options.preferredCandidates]
* candidate families tried before the shared ones, so a type-owned corridor
* (a bundled trunk, a dedicated lane) wins over the generic midpoint
+ * @param {boolean} [options.crossingFreeGridFirst = false] before the obstacle
+ * grid search that may cross earlier routes, try one that treats every
+ * unrelated resolved route as a wall. A type whose showcase gate rejects any
+ * proper crossing (erd) opts in so a later relationship takes a clear detour
+ * instead of the shorter crossing the gate would refuse.
* @param {boolean} [options.compositionFloors = true] hold every automatic
* route to the rhythm floors the showcase gate enforces, so the planner never
* accepts a route the gate will reject. A type that draws a route differently
@@ -64,6 +69,7 @@ export function createRouter(components, connections = [], {
maxPortSpacing = null,
preferredCandidates = null,
compositionFloors = true,
+ crossingFreeGridFirst = false,
} = {}) {
const frameBorders = frames.flatMap((frame) => frameBorderSegments(frame));
const LABEL_CLEARANCE = 4;
@@ -591,6 +597,41 @@ export function createRouter(components, connections = [], {
// ambiguous shared corridors without forcing the model to hand-route
// a sprawling perimeter detour. Cheap candidates above still prefer a
// genuinely crossing-free path whenever one is available.
+ if (crossingFreeGridFirst) {
+ const unrelatedSegments = unrelatedResolvedRoutes(conn, resolvedRoutes)
+ .flatMap((entry) => entry.points.slice(1).map((end, index) => ({ start: entry.points[index], end })));
+ if (unrelatedSegments.length) {
+ planningMetrics.gridSearchCount += 1;
+ const strict = shortestOrthogonalGridRoute({
+ start,
+ end,
+ points: [start, end],
+ obstacles: [...components.values(), ...reservedLabelObstacles(2)],
+ fromSide,
+ toSide,
+ clearance: 2,
+ maximumObstacleCount: 80,
+ endpointStubPx: 24,
+ maximumGridNodes: 4096,
+ avoidedSegments: unrelatedSegments,
+ allowAvoidedCrossings: false,
+ minimumAvoidedOverlapPx: 8,
+ routeSeparationPx: 8,
+ minimumSegmentPx: interiorSegmentPx,
+ borderSegments: frameBorders,
+ bendPenaltyPx: 48,
+ });
+ if (strict
+ && routeClearsEndpointComponents(strict.points, from, to)
+ && routeClearsComponents(conn, strict.points)
+ && !routeConflictsWithResolved(conn, strict.points, resolvedRoutes)
+ && !routeOverlapsResolved(conn, strict.points, resolvedRoutes)
+ && routeMeetsCompositionFloors(strict.points)) {
+ planningMetrics.gridRoutedCount += 1;
+ return strict.points.slice(1, -1);
+ }
+ }
+ }
const avoidedSegments = resolvedRoutes
.filter((entry) => distinctAutomaticPorts && relationshipsShareEndpoint(conn, entry.conn)
&& !hasAuthoredRouteGeometry(entry.conn) && !entry.conn.labelAt && !conn.labelAt)
@@ -1058,11 +1099,11 @@ export function createRouter(components, connections = [], {
const paired = new Set();
for (const first of resolvedRoutes) {
const conn = first.conn;
- if (paired.has(conn) || hasAuthoredRouteGeometry(conn) || hasAuthoredLabelPlacement(conn)
+ if (paired.has(conn) || typeOwned.has(conn) || hasAuthoredRouteGeometry(conn) || hasAuthoredLabelPlacement(conn)
|| (conn.fromSide && conn.fromSide !== 'auto')
|| (conn.toSide && conn.toSide !== 'auto')) continue;
const second = resolvedRoutes.find((entry) => entry !== first
- && entry.conn.from === conn.to && entry.conn.to === conn.from
+ && entry.conn.from === conn.to && entry.conn.to === conn.from && !typeOwned.has(entry.conn)
&& !hasAuthoredRouteGeometry(entry.conn) && !hasAuthoredLabelPlacement(entry.conn)
&& (!entry.conn.fromSide || entry.conn.fromSide === 'auto')
&& (!entry.conn.toSide || entry.conn.toSide === 'auto'));
@@ -1156,12 +1197,31 @@ export function createRouter(components, connections = [], {
}
}
}
+ // A type-owned corridor (an erd bundled trunk or dedicated lane) is the
+ // route its renderer draws around; the generic sweep must not trade it
+ // for a shorter lane and leave the bus without its branch.
+ const followsPreferredCorridor = (entry) => {
+ if (!preferredCandidates) return false;
+ const sides = selectedSides.get(entry.conn);
+ if (!sides) return false;
+ const interior = JSON.stringify(entry.points.slice(1, -1));
+ return (preferredCandidates({
+ conn: entry.conn,
+ from: components.get(entry.conn.from),
+ to: components.get(entry.conn.to),
+ start: entry.points[0],
+ end: entry.points.at(-1),
+ fromSide: sides.fromSide,
+ toSide: sides.toSide,
+ }) || []).some((candidate) => JSON.stringify(candidate) === interior);
+ };
+ const typeOwned = new Set(resolvedRoutes.filter(followsPreferredCorridor).map((entry) => entry.conn));
allowGridSearch = false;
try {
improveReciprocalPairs();
for (const entry of resolvedRoutes) {
const { conn } = entry;
- if (jointlyImproved.has(conn) || hasAuthoredRouteGeometry(conn) || hasAuthoredLabelPlacement(conn)) continue;
+ if (jointlyImproved.has(conn) || typeOwned.has(conn) || hasAuthoredRouteGeometry(conn) || hasAuthoredLabelPlacement(conn)) continue;
const others = resolvedRoutes.filter((other) => other !== entry);
// Preserve uncomplicated routes and their established inferred sides.
// Spend the comparison budget where the complete scene has a reading
@@ -1200,7 +1260,7 @@ export function createRouter(components, connections = [], {
// stays fixed, and the straight lane must pass the same checks.
for (const entry of resolvedRoutes) {
const { conn } = entry;
- if (entry.points.length < 4 || jointlyImproved.has(conn)
+ if (entry.points.length < 4 || jointlyImproved.has(conn) || typeOwned.has(conn)
|| hasAuthoredRouteGeometry(conn) || hasAuthoredLabelPlacement(conn)) continue;
const from = components.get(conn.from);
const to = components.get(conn.to);
diff --git a/archify/renderers/erd/grid.mjs b/archify/renderers/erd/grid.mjs
index 7985e705..3233d293 100644
--- a/archify/renderers/erd/grid.mjs
+++ b/archify/renderers/erd/grid.mjs
@@ -55,7 +55,10 @@ export function entityHeight(entity, grid) {
// column (a class grid's `col: 1.5`) is centred between two columns: it sizes
// its row but neither column.
const gridColumn = (col) => Number.isInteger(col * 2) && col >= 0;
-export function bandedLayout(entities, grid) {
+// `columnGaps` raises the gap after a column to a measured floor (see the
+// renderer's relationship-label demand); the authored or default gapX stays
+// the minimum everywhere, so an absent map reproduces the plain grid.
+export function bandedLayout(entities, grid, { columnGaps = null } = {}) {
const widths = new Map();
const heights = new Map();
let maxCol = -1;
@@ -71,7 +74,7 @@ export function bandedLayout(entities, grid) {
let x = grid.origin[0];
for (let col = 0; col <= maxCol; col += 1) {
columnX.set(col, x);
- x += (widths.get(col) || 0) + grid.gapX;
+ x += (widths.get(col) || 0) + Math.max(grid.gapX, columnGaps?.get(col) || 0);
}
// A half-column box may be wider than its empty neighbouring bands. Keep
// every grid box inside the left margin without changing integer-only grids.
diff --git a/archify/renderers/erd/render-erd.mjs b/archify/renderers/erd/render-erd.mjs
index 181b5b0c..142366ac 100644
--- a/archify/renderers/erd/render-erd.mjs
+++ b/archify/renderers/erd/render-erd.mjs
@@ -51,6 +51,7 @@ import {
variantAccent,
} from '../shared/geometry.mjs';
import { createRouter } from '../architecture/routing.mjs';
+import { placeAutomaticLabels } from '../shared/automatic-labels.mjs';
import { entityBox, connectionPath as relationshipPath } from '../shared/layout-report.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -147,7 +148,49 @@ const measuredEntities = asArray(er.entities).map((entity) => {
};
});
-const bands = grid ? bandedLayout(measuredEntities, grid) : null;
+// A relationship label is semantic data and the smallest text the diagram
+// carries: at the shared 8-unit default it projects to ~7.0px on a tall canvas,
+// under the 7.5px the canvas declares.
+const RELATIONSHIP_LABEL_FONT = 9;
+// The label's advance is measured from that size, not from a literal: the mask
+// the renderer draws, the rect the layout checks measure, and the obstacle the
+// legend measures must be the same rectangle, or a label can sit on a table edge
+// with no diagnostic (the checks would be measuring a narrower box than the ink).
+const RELATIONSHIP_LABEL_ADVANCE = 0.62;
+const relationshipLabelWidth = (label) => Math.max(30, textUnits(label) * RELATIONSHIP_LABEL_FONT * RELATIONSHIP_LABEL_ADVANCE + 10);
+
+// A label between two neighbouring columns is drawn in the gap between them:
+// on the straight line of a same-row relationship, or across the channel of a
+// bent one. The fixed gap was narrower than an ordinary two-word label plus the
+// cardinality glyph at each table edge, so most first drafts failed with a
+// label drawn over a table. When the grid owns every coordinate (no pinned
+// position, route, channel, or label point refers to absolute geometry), each
+// such gap widens just enough for its widest label to clear both glyphs.
+const LABEL_GLYPH_CLEARANCE = 24 + 4;
+function labelColumnGaps() {
+ if (!grid || Array.isArray(er.meta?.viewBox)) return null;
+ const rawEntities = asArray(er.entities);
+ const rawRelationships = asArray(er.relationships);
+ const absolute = rawEntities.some((entity) => Array.isArray(entity.pos))
+ || rawRelationships.some((relationship) => relationship.via?.length || relationship.labelAt
+ || (relationship.route && relationship.route !== 'auto')
+ || relationship.channelX !== undefined || relationship.channelY !== undefined);
+ if (absolute) return null;
+ const byId = new Map(rawEntities.map((entity) => [entity.id, entity]));
+ const gaps = new Map();
+ for (const relationship of rawRelationships) {
+ if (!relationship.label) continue;
+ const from = byId.get(relationship.from);
+ const to = byId.get(relationship.to);
+ if (![from?.col, to?.col].every(Number.isInteger) || Math.abs(from.col - to.col) !== 1) continue;
+ const gap = Math.min(from.col, to.col);
+ const demand = Math.ceil(relationshipLabelWidth(relationship.label) + LABEL_GLYPH_CLEARANCE * 2);
+ gaps.set(gap, Math.max(gaps.get(gap) || 0, demand));
+ }
+ return gaps.size ? gaps : null;
+}
+
+const bands = grid ? bandedLayout(measuredEntities, grid, { columnGaps: labelColumnGaps() }) : null;
const entities = new Map(measuredEntities.map((entity) => {
const [x, y] = resolveEntityPos(entity, grid, bands);
@@ -476,18 +519,9 @@ const viewBox = Array.isArray(er.meta?.viewBox) ? er.meta.viewBox : autoViewBox(
// skipped and the shared candidate families run unchanged.
const LANE_STEP = 12;
-// A relationship label is semantic data and the smallest text the diagram
-// carries: at the shared 8-unit default it projects to ~7.0px on a tall canvas,
-// under the 7.5px the canvas declares.
-const RELATIONSHIP_LABEL_FONT = 9;
-// The label's advance is measured from that size, not from a literal: the mask
-// the renderer draws, the rect the layout checks measure, and the obstacle the
-// legend measures must be the same rectangle, or a label can sit on a table edge
-// with no diagnostic (the checks would be measuring a narrower box than the ink).
-const RELATIONSHIP_LABEL_ADVANCE = 0.62;
function relationshipLabelBox(relationship) {
const [lx, ly] = erLabelPoint(relationship);
- const width = Math.max(30, textUnits(relationship.label) * RELATIONSHIP_LABEL_FONT * RELATIONSHIP_LABEL_ADVANCE + 10);
+ const width = relationshipLabelWidth(relationship.label);
return { x: lx - width / 2, y: ly - 10, width, height: 14 };
}
@@ -524,6 +558,15 @@ const { ports, pathFor, inferredSides, connectionEndpointSide } = createRouter(e
// A cardinality glyph is 14 units tall, so ports must clear it (see
// ERD_PORT_SPACING, which the trunk bridge is derived from).
maxPortSpacing: ERD_PORT_SPACING,
+ // Greedy planning routes each relationship against only the earlier ones, so
+ // a later route could cross an earlier corridor while an empty side of the
+ // table was free. Architecture's bounded readability sweep re-plans one
+ // route at a time against the complete scene and keeps a change only when it
+ // removes crossings or bends at bounded extra length.
+ preferReadableRoutes: true,
+ // A proper crossing fails the showcase gate, so a relationship that needs
+ // the obstacle search first looks for a detour that crosses nothing.
+ crossingFreeGridFirst: true,
});
function corridorKey(relationship) {
@@ -739,7 +782,14 @@ function relationshipTrunkRuns(relationship) {
const assignment = trunkAssignments.get(relationship);
if (!assignment) return [];
if (trunkRunCache.has(relationship)) return trunkRunCache.get(relationship);
- const { axis, coordinate } = assignment.group;
+ const { axis, coordinate, role, side } = assignment.group;
+ // The readability sweep may move a member to another table side after the
+ // groups were formed. Such a route no longer leaves through the shared side,
+ // so it is drawn whole instead of losing a coincidental stretch to the bus.
+ if (connectionEndpointSide(relationship, role === 'in' ? 'target' : 'source') !== side) {
+ trunkRunCache.set(relationship, []);
+ return [];
+ }
const points = pathFor(relationship).points;
const runs = [];
for (let index = 0; index < points.length - 1; index += 1) {
@@ -841,12 +891,95 @@ function bundledTrunkPaths() {
// Bundled labels default to the source-side stub so they never sit on the
// shared trunk, where they would read as annotating every branch at once.
-function erLabelPoint(relationship) {
+function defaultErLabelPoint(relationship) {
const points = pathFor(relationship).points;
if (!trunkAssignments.get(relationship)) return labelPoint(relationship, points);
return labelPoint({ ...relationship, labelSegment: relationship.labelSegment ?? 0 }, points);
}
+const resolvedLabelPoints = new Map();
+function erLabelPoint(relationship) {
+ return resolvedLabelPoints.get(relationship) ?? defaultErLabelPoint(relationship);
+}
+
+// ---- Automatic label placement ----------------------------------------------
+// The default point is the midpoint of one segment, which knows nothing about
+// the tables, glyphs, or other routes around it: a vertical relationship put
+// its label on the source table's cardinality glyph, and a label in a busy gap
+// sat over a neighbouring table or channel. The shared bounded placer (the one
+// architecture and dataflow use) keeps every clear default and moves only a
+// colliding unpinned label to the nearest clear spot beside its own route.
+// Each relationship end reserves its cardinality glyph, and a bundled member's
+// shared trunk counts as another route, so a moved label never annotates the
+// bus or covers a crow's foot.
+// Half the glyph's 16-unit height plus the 2-unit overlap the shared placer
+// tolerates before it moves a label, so even a default spot keeps clear ink.
+const GLYPH_HALF_HEIGHT = 10;
+function cardinalityGlyphBox(point, side) {
+ const [x, y] = point;
+ const reach = MARKER_GLYPH_WIDTH;
+ if (side === 'left') return { x: x - reach, y: y - GLYPH_HALF_HEIGHT, width: reach, height: GLYPH_HALF_HEIGHT * 2 };
+ if (side === 'right') return { x, y: y - GLYPH_HALF_HEIGHT, width: reach, height: GLYPH_HALF_HEIGHT * 2 };
+ if (side === 'top') return { x: x - GLYPH_HALF_HEIGHT, y: y - reach, width: GLYPH_HALF_HEIGHT * 2, height: reach };
+ return { x: x - GLYPH_HALF_HEIGHT, y, width: GLYPH_HALF_HEIGHT * 2, height: reach };
+}
+
+{
+ const placeable = relationships.filter(renderableRelationship);
+ const labels = placeable.filter((relationship) => relationship.label).map((relationship) => {
+ const [lx, ly] = defaultErLabelPoint(relationship);
+ const width = relationshipLabelWidth(relationship.label);
+ return {
+ relation: relationship, relationIndex: relationships.indexOf(relationship), label: relationship.label,
+ x: lx - width / 2, y: ly - 10, width, height: 14, lx, ly,
+ };
+ });
+ if (labels.length) {
+ const routes = [];
+ const glyphs = [];
+ placeable.forEach((relationship) => {
+ const relationIndex = relationships.indexOf(relationship);
+ const { points } = pathFor(relationship);
+ glyphs.push(cardinalityGlyphBox(points[0], connectionEndpointSide(relationship, 'source')));
+ glyphs.push(cardinalityGlyphBox(points.at(-1), connectionEndpointSide(relationship, 'target')));
+ const runs = relationshipTrunkRuns(relationship);
+ if (!runs.length) {
+ routes.push({ relationIndex, points });
+ return;
+ }
+ const inRun = new Set(runs.flatMap((run) => Array.from({ length: run.endIndex - run.startIndex }, (_, step) => run.startIndex + step)));
+ let piece = [points[0]];
+ for (let index = 0; index < points.length - 1; index += 1) {
+ if (inRun.has(index)) {
+ if (piece.length > 1) routes.push({ relationIndex, points: piece });
+ routes.push({ relationIndex: -1 - routes.length, points: [points[index], points[index + 1]] });
+ piece = [points[index + 1]];
+ } else {
+ piece.push(points[index + 1]);
+ }
+ }
+ if (piece.length > 1) routes.push({ relationIndex, points: piece });
+ });
+ const titles = domainGroups.map(({ tag, members }) => {
+ const caption = domainBandCaption(domainBandBox(members));
+ return { x: caption.x - 2, y: caption.y - 10, width: textUnits(tag) * 9 * 0.65 + 4, height: 13 };
+ });
+ const footprint = legendFootprint(erLegendEntries, { width: Math.max(1, viewBox[0] - layout.margin * 2) });
+ const placed = placeAutomaticLabels({
+ labels,
+ routes,
+ components: [...entities.values(), ...glyphs],
+ titles,
+ viewBox,
+ placementBottom: viewBox[1] - layout.legendH - footprint.extraHeight,
+ keepFallbackNearRoute: true,
+ });
+ placed.forEach((rect, index) => {
+ if (rect !== labels[index]) resolvedLabelPoints.set(rect.relation, [rect.lx, rect.ly]);
+ });
+ }
+}
+
function channelFallback({ conn, start, end, fromSide, toSide }) {
const horizontalPorts = fromSide === 'left' || fromSide === 'right';
const verticalPorts = fromSide === 'top' || fromSide === 'bottom';
diff --git a/test/erd-first-draft-layout.test.mjs b/test/erd-first-draft-layout.test.mjs
new file mode 100644
index 00000000..2862daf8
--- /dev/null
+++ b/test/erd-first-draft-layout.test.mjs
@@ -0,0 +1,146 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { properSegmentIntersection, rectsOverlap } from '../archify/renderers/shared/geometry.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const skillRoot = path.resolve(__dirname, '..', 'archify');
+const renderer = path.join(skillRoot, 'renderers', 'erd', 'render-erd.mjs');
+const checker = path.join(skillRoot, 'scripts', 'check-render-output.mjs');
+const fixtures = path.join(__dirname, 'fixtures', 'erd-first-draft');
+// The crow's foot reaches this far from the table edge and is 16 units tall.
+const GLYPH_REACH = 24;
+const GLYPH_HALF = 8;
+
+function render(diagram) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-erd-first-draft-'));
+ const input = path.join(directory, 'candidate.json');
+ const output = path.join(directory, 'candidate.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ const result = spawnSync(process.execPath, [renderer, input, output], { cwd: directory, encoding: 'utf8' });
+ return { ...result, output, html: result.status === 0 ? fs.readFileSync(output, 'utf8') : '' };
+}
+
+const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([a-zA-Z-]+)="([^"]*)"/g)].map((match) => [match[1], match[2]]));
+const svgOf = (html) => html.match(/<svg\b[\s\S]*?<\/svg>/i)[0];
+
+function entityBoxes(html) {
+ const boxes = new Map();
+ for (const match of svgOf(html).matchAll(/data-node-id="([a-z_]+)"[\s\S]{0,500}?<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)" rx="5" class="c-database(?: er-table)?"/g)) {
+ boxes.set(match[1], { x: +match[2], y: +match[3], width: +match[4], height: +match[5] });
+ }
+ return boxes;
+}
+
+function routes(html) {
+ return [...svgOf(html).matchAll(/<path\b[^>]*marker-end[^>]*>/g)].map((match) => attrs(match[0]))
+ .filter((route) => route['data-edge-from'] && route['data-composition-points'])
+ .map((route) => ({
+ id: route['data-edge-id'],
+ from: route['data-edge-from'],
+ to: route['data-edge-to'],
+ points: route['data-composition-points'].split(';').map((pair) => pair.split(',').map(Number)),
+ }));
+}
+
+function labelBoxes(html) {
+ return [...svgOf(html).matchAll(/<g data-detail="context"[^>]*data-edge-id="([^"]+)"[^>]*>\s*<rect x="([\d.-]+)" y="([\d.-]+)" width="([\d.]+)" height="([\d.]+)"/g)]
+ .map((match) => ({ id: match[1], x: +match[2], y: +match[3], width: +match[4], height: +match[5] }));
+}
+
+// The box a cardinality glyph occupies at a route end lying on a table edge.
+function glyphBox([x, y], box) {
+ const near = (a, b) => Math.abs(a - b) < 0.5;
+ if (near(x, box.x)) return { x: x - GLYPH_REACH, y: y - GLYPH_HALF, width: GLYPH_REACH, height: GLYPH_HALF * 2 };
+ if (near(x, box.x + box.width)) return { x, y: y - GLYPH_HALF, width: GLYPH_REACH, height: GLYPH_HALF * 2 };
+ if (near(y, box.y)) return { x: x - GLYPH_HALF, y: y - GLYPH_REACH, width: GLYPH_HALF * 2, height: GLYPH_REACH };
+ return { x: x - GLYPH_HALF, y, width: GLYPH_HALF * 2, height: GLYPH_REACH };
+}
+
+function properCrossings(html) {
+ const all = routes(html);
+ const crossings = [];
+ for (const [index, left] of all.entries()) {
+ for (const right of all.slice(index + 1)) {
+ if ([left.from, left.to].some((id) => id === right.from || id === right.to)) continue;
+ const crosses = left.points.slice(1).some((end, i) => right.points.slice(1).some((otherEnd, j) => (
+ properSegmentIntersection(left.points[i], end, right.points[j], otherEnd))));
+ if (crosses) crossings.push([left.id, right.id]);
+ }
+ }
+ return crossings;
+}
+
+function assertLabelsClear(html) {
+ const boxes = entityBoxes(html);
+ const glyphs = routes(html).flatMap((route) => [
+ glyphBox(route.points[0], boxes.get(route.from)),
+ glyphBox(route.points.at(-1), boxes.get(route.to)),
+ ]);
+ const labels = labelBoxes(html);
+ assert.ok(labels.length > 0, 'the fixture draws relationship labels');
+ for (const label of labels) {
+ for (const [id, box] of boxes) assert.ok(!rectsOverlap(label, box), `label ${label.id} overlaps table ${id}`);
+ for (const glyph of glyphs) assert.ok(!rectsOverlap(label, glyph), `label ${label.id} covers a cardinality glyph`);
+ }
+}
+
+for (const name of ['blog', 'shop', 'warehouse']) {
+ test(`unpinned ERD first draft "${name}" renders at showcase with clear labels and no crossings`, () => {
+ const diagram = JSON.parse(fs.readFileSync(path.join(fixtures, `${name}.erd.json`), 'utf8'));
+ assert.equal(diagram.meta.quality_profile, 'showcase');
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assertLabelsClear(result.html);
+ assert.deepEqual(properCrossings(result.html), []);
+ const check = spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' });
+ assert.equal(check.status, 0, check.stdout);
+ });
+}
+
+const twoTables = (relationship, extra = {}) => ({
+ schema_version: 1,
+ diagram_type: 'erd',
+ meta: { title: 'Label gap', locale: 'en', quality_profile: 'showcase' },
+ layout: { mode: 'grid', gapX: 56 },
+ entities: [
+ { id: 'left', label: 'left', row: 0, col: 0, attributes: [{ name: 'id', type: 'bigint', key: 'pk' }] },
+ { id: 'right', label: 'right', row: 0, col: 1, attributes: [{ name: 'id', type: 'bigint', key: 'pk' }, { name: 'left_id', type: 'bigint', key: 'fk', references: 'left.id' }] },
+ ],
+ relationships: [{ id: 'right_left', from: 'right', to: 'left', fromCardinality: 'many', toCardinality: 'one', ...relationship }],
+ ...extra,
+});
+
+test('a grid-owned gap widens to hold its label clear of both cardinality glyphs', () => {
+ const result = render(twoTables({ label: 'settled by invoice' }));
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const boxes = entityBoxes(result.html);
+ const [label] = labelBoxes(result.html);
+ const gap = boxes.get('right').x - (boxes.get('left').x + boxes.get('left').width);
+ assert.ok(gap >= label.width + GLYPH_REACH * 2, `gap ${gap} must hold the ${label.width}-unit label and both glyphs`);
+ assertLabelsClear(result.html);
+});
+
+test('an unlabelled grid keeps the authored gap', () => {
+ const result = render(twoTables({}));
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const boxes = entityBoxes(result.html);
+ assert.equal(boxes.get('right').x - (boxes.get('left').x + boxes.get('left').width), 56);
+});
+
+test('absolute geometry keeps the authored gap so pinned coordinates stay meaningful', () => {
+ const pinned = twoTables({ label: 'settled by invoice', labelDx: 0 });
+ pinned.relationships.push({ id: 'left_self', from: 'left', to: 'right', fromCardinality: 'one', toCardinality: 'many', via: [[300, 20]] });
+ pinned.relationships.pop();
+ pinned.entities[1].pos = [328, 40];
+ const result = render(pinned);
+ // The 56-unit corridor cannot hold the pinned label, so the author still
+ // gets the overlap diagnostic instead of a silently moved table.
+ assert.notEqual(result.status, 0);
+ assert.match(result.stdout + result.stderr, /Label "settled by invoice" overlaps entity/);
+});
diff --git a/test/erd-rendering.test.mjs b/test/erd-rendering.test.mjs
index 828707fe..badb90c2 100644
--- a/test/erd-rendering.test.mjs
+++ b/test/erd-rendering.test.mjs
@@ -677,7 +677,9 @@ test('same-side ports clear the marker glyph and the markers carry the stronger
// obstacle the legend measures are one rectangle. When the checks measured a
// narrower box than the ink, a label could sit on a table edge with nothing
// reported: this corridor is 60 units wide and the label's drawn mask is 65.8,
-// an overlap the old 8-unit measurement (58.0) did not see.
+// an overlap the old 8-unit measurement (58.0) did not see. Absolute positions
+// keep the corridor at 60 (a grid-owned layout would widen it for the label),
+// and a zero labelDx pins the label so the automatic placer leaves it there.
test('relationship labels are drawn and checked with one measured box', () => {
const diagram = {
schema_version: 1,
@@ -685,11 +687,11 @@ test('relationship labels are drawn and checked with one measured box', () => {
meta: { title: 'Label corridor', locale: 'en' },
layout: { mode: 'grid', gapX: 60, gapY: 44 },
entities: [
- { id: 'left', label: 'left', row: 0, col: 0, attributes: [{ name: 'id', type: 'bigint', key: 'pk' }] },
- { id: 'right', label: 'right', row: 0, col: 1, attributes: [{ name: 'id', type: 'bigint', key: 'pk' }, { name: 'left_id', type: 'bigint', key: 'fk', references: 'left.id' }] },
+ { id: 'left', label: 'left', pos: [32, 40], attributes: [{ name: 'id', type: 'bigint', key: 'pk' }] },
+ { id: 'right', label: 'right', pos: [332, 40], attributes: [{ name: 'id', type: 'bigint', key: 'pk' }, { name: 'left_id', type: 'bigint', key: 'fk', references: 'left.id' }] },
],
relationships: [
- { id: 'right_left', from: 'right', to: 'left', fromCardinality: 'many', toCardinality: 'one', label: 'settles by' },
+ { id: 'right_left', from: 'right', to: 'left', fromCardinality: 'many', toCardinality: 'one', label: 'settles by', labelDx: 0 },
],
};
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-er-label-box-'));
@@ -701,7 +703,7 @@ test('relationship labels are drawn and checked with one measured box', () => {
// The same corridor with room for the drawn mask is accepted, and the mask the
// renderer writes is the measured box.
const roomy = clone(diagram);
- roomy.layout.gapX = 88;
+ roomy.entities[1].pos = [360, 40];
const accepted = render(roomy, directory);
assert.equal(accepted.status, 0, accepted.stdout + accepted.stderr);
const html = fs.readFileSync(accepted.output, 'utf8');
diff --git a/test/fixtures/erd-first-draft/README.md b/test/fixtures/erd-first-draft/README.md
new file mode 100644
index 00000000..01917d4b
--- /dev/null
+++ b/test/fixtures/erd-first-draft/README.md
@@ -0,0 +1,17 @@
+# ERD first-draft regressions
+
+Unedited first drafts written from the Skill's ERD guidance (grid layout, one
+domain per column, every column with its SQL type and key role, automatic
+routes). None of them pinned a position, route, channel, or label point, and
+every one failed `validate --quality showcase` on `dev` before the ERD
+first-draft layout fixes:
+
+| Fixture | Failure on `dev` |
+| --- | --- |
+| `blog.erd.json` | "written by" overlapped a table in the 56-unit gap; a vertical label sat on a cardinality glyph |
+| `shop.erd.json` | four labels overlapped tables, one route crossed another, one label touched a route |
+| `warehouse.erd.json` | two proper crossings from an obstacle search that ignored earlier routes, three labels over tables |
+
+The regression test asserts that each renders at `showcase` and that the
+specific defects stay fixed. A draft that passes is one valid answer, not a
+layout recommendation.
diff --git a/test/fixtures/erd-first-draft/blog.erd.json b/test/fixtures/erd-first-draft/blog.erd.json
new file mode 100644
index 00000000..e61d4d94
--- /dev/null
+++ b/test/fixtures/erd-first-draft/blog.erd.json
@@ -0,0 +1,236 @@
+{
+ "schema_version": 1,
+ "diagram_type": "erd",
+ "meta": {
+ "title": "Blog platform schema",
+ "locale": "en",
+ "quality_profile": "showcase",
+ "output": "blog.html"
+ },
+ "layout": {
+ "mode": "grid"
+ },
+ "entities": [
+ {
+ "id": "users",
+ "label": "users",
+ "tag": "accounts",
+ "row": 0,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "email",
+ "type": "varchar(255)",
+ "key": "uk"
+ },
+ {
+ "name": "display_name",
+ "type": "varchar(80)"
+ },
+ {
+ "name": "created_at",
+ "type": "timestamptz"
+ }
+ ]
+ },
+ {
+ "id": "profiles",
+ "label": "profiles",
+ "tag": "accounts",
+ "row": 1,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "user_id",
+ "type": "bigint",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "users.id"
+ },
+ {
+ "name": "bio",
+ "type": "text"
+ },
+ {
+ "name": "avatar_url",
+ "type": "varchar(512)"
+ }
+ ]
+ },
+ {
+ "id": "posts",
+ "label": "posts",
+ "tag": "content",
+ "row": 0,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "author_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "users.id"
+ },
+ {
+ "name": "slug",
+ "type": "varchar(160)",
+ "key": "uk"
+ },
+ {
+ "name": "title",
+ "type": "varchar(200)"
+ },
+ {
+ "name": "body",
+ "type": "text"
+ },
+ {
+ "name": "published_at",
+ "type": "timestamptz"
+ }
+ ]
+ },
+ {
+ "id": "comments",
+ "label": "comments",
+ "tag": "content",
+ "row": 1,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "post_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "posts.id"
+ },
+ {
+ "name": "author_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "users.id"
+ },
+ {
+ "name": "body",
+ "type": "text"
+ },
+ {
+ "name": "created_at",
+ "type": "timestamptz"
+ }
+ ]
+ },
+ {
+ "id": "tags",
+ "label": "tags",
+ "tag": "taxonomy",
+ "row": 0,
+ "col": 2,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "int",
+ "key": "pk"
+ },
+ {
+ "name": "name",
+ "type": "varchar(60)",
+ "key": "uk"
+ }
+ ]
+ },
+ {
+ "id": "post_tags",
+ "label": "post_tags",
+ "tag": "taxonomy",
+ "row": 1,
+ "col": 2,
+ "attributes": [
+ {
+ "name": "post_id",
+ "type": "bigint",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "posts.id"
+ },
+ {
+ "name": "tag_id",
+ "type": "int",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "tags.id"
+ }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "id": "r_profile",
+ "from": "profiles",
+ "to": "users",
+ "fromCardinality": "one",
+ "toCardinality": "one",
+ "label": "extends"
+ },
+ {
+ "id": "r_author",
+ "from": "posts",
+ "to": "users",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "written by"
+ },
+ {
+ "id": "r_comment_post",
+ "from": "comments",
+ "to": "posts",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "fromOptional": true,
+ "label": "on"
+ },
+ {
+ "id": "r_comment_user",
+ "from": "comments",
+ "to": "users",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "by"
+ },
+ {
+ "id": "r_pt_post",
+ "from": "post_tags",
+ "to": "posts",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "identifying": true
+ },
+ {
+ "id": "r_pt_tag",
+ "from": "post_tags",
+ "to": "tags",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "identifying": true
+ }
+ ]
+}
diff --git a/test/fixtures/erd-first-draft/shop.erd.json b/test/fixtures/erd-first-draft/shop.erd.json
new file mode 100644
index 00000000..5ed67d85
--- /dev/null
+++ b/test/fixtures/erd-first-draft/shop.erd.json
@@ -0,0 +1,297 @@
+{
+ "schema_version": 1,
+ "diagram_type": "erd",
+ "meta": {
+ "title": "Online shop schema",
+ "locale": "en",
+ "quality_profile": "showcase",
+ "output": "shop.html"
+ },
+ "layout": {
+ "mode": "grid"
+ },
+ "entities": [
+ {
+ "id": "customers",
+ "label": "customers",
+ "tag": "accounts",
+ "row": 0,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "email",
+ "type": "varchar(255)",
+ "key": "uk"
+ },
+ {
+ "name": "name",
+ "type": "varchar(120)"
+ },
+ {
+ "name": "created_at",
+ "type": "timestamptz"
+ }
+ ]
+ },
+ {
+ "id": "addresses",
+ "label": "addresses",
+ "tag": "accounts",
+ "row": 1,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "customer_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "customers.id"
+ },
+ {
+ "name": "line1",
+ "type": "varchar(200)"
+ },
+ {
+ "name": "city",
+ "type": "varchar(80)"
+ },
+ {
+ "name": "postcode",
+ "type": "varchar(16)"
+ }
+ ]
+ },
+ {
+ "id": "orders",
+ "label": "orders",
+ "tag": "sales",
+ "row": 0,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "customer_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "customers.id"
+ },
+ {
+ "name": "shipping_address_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "addresses.id"
+ },
+ {
+ "name": "status",
+ "type": "varchar(20)"
+ },
+ {
+ "name": "total",
+ "type": "numeric(12,2)"
+ },
+ {
+ "name": "placed_at",
+ "type": "timestamptz"
+ }
+ ]
+ },
+ {
+ "id": "order_items",
+ "label": "order_items",
+ "tag": "sales",
+ "row": 1,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "order_id",
+ "type": "bigint",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "orders.id"
+ },
+ {
+ "name": "product_id",
+ "type": "bigint",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "products.id"
+ },
+ {
+ "name": "quantity",
+ "type": "int"
+ },
+ {
+ "name": "unit_price",
+ "type": "numeric(12,2)"
+ }
+ ]
+ },
+ {
+ "id": "payments",
+ "label": "payments",
+ "tag": "sales",
+ "row": 2,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "order_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "orders.id"
+ },
+ {
+ "name": "provider",
+ "type": "varchar(40)"
+ },
+ {
+ "name": "amount",
+ "type": "numeric(12,2)"
+ },
+ {
+ "name": "paid_at",
+ "type": "timestamptz"
+ }
+ ]
+ },
+ {
+ "id": "products",
+ "label": "products",
+ "tag": "catalog",
+ "row": 0,
+ "col": 2,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "sku",
+ "type": "varchar(40)",
+ "key": "uk"
+ },
+ {
+ "name": "category_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "categories.id"
+ },
+ {
+ "name": "name",
+ "type": "varchar(200)"
+ },
+ {
+ "name": "price",
+ "type": "numeric(12,2)"
+ }
+ ]
+ },
+ {
+ "id": "categories",
+ "label": "categories",
+ "tag": "catalog",
+ "row": 1,
+ "col": 2,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "parent_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "categories.id"
+ },
+ {
+ "name": "name",
+ "type": "varchar(80)"
+ }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "id": "addresses_customers",
+ "from": "addresses",
+ "to": "customers",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "belongs to"
+ },
+ {
+ "id": "orders_customers",
+ "from": "orders",
+ "to": "customers",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "placed by"
+ },
+ {
+ "id": "orders_addresses",
+ "from": "orders",
+ "to": "addresses",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "ships to"
+ },
+ {
+ "id": "order_items_orders",
+ "from": "order_items",
+ "to": "orders",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "line of",
+ "identifying": true
+ },
+ {
+ "id": "order_items_products",
+ "from": "order_items",
+ "to": "products",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "sells",
+ "identifying": true
+ },
+ {
+ "id": "payments_orders",
+ "from": "payments",
+ "to": "orders",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "pays",
+ "fromOptional": true
+ },
+ {
+ "id": "products_categories",
+ "from": "products",
+ "to": "categories",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "in category"
+ }
+ ]
+}
diff --git a/test/fixtures/erd-first-draft/warehouse.erd.json b/test/fixtures/erd-first-draft/warehouse.erd.json
new file mode 100644
index 00000000..a5c3c407
--- /dev/null
+++ b/test/fixtures/erd-first-draft/warehouse.erd.json
@@ -0,0 +1,245 @@
+{
+ "schema_version": 1,
+ "diagram_type": "erd",
+ "meta": {
+ "title": "Warehouse inventory schema",
+ "locale": "en",
+ "quality_profile": "showcase",
+ "output": "warehouse.html"
+ },
+ "layout": {
+ "mode": "grid"
+ },
+ "entities": [
+ {
+ "id": "suppliers",
+ "label": "suppliers",
+ "tag": "purchasing",
+ "row": 0,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "name",
+ "type": "varchar(120)"
+ },
+ {
+ "name": "country",
+ "type": "char(2)"
+ }
+ ]
+ },
+ {
+ "id": "purchase_orders",
+ "label": "purchase_orders",
+ "tag": "purchasing",
+ "row": 1,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "supplier_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "suppliers.id"
+ },
+ {
+ "name": "warehouse_id",
+ "type": "bigint",
+ "key": "fk",
+ "references": "warehouses.id"
+ },
+ {
+ "name": "ordered_at",
+ "type": "date"
+ },
+ {
+ "name": "status",
+ "type": "varchar(16)"
+ }
+ ]
+ },
+ {
+ "id": "po_lines",
+ "label": "po_lines",
+ "tag": "purchasing",
+ "row": 2,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "po_id",
+ "type": "bigint",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "purchase_orders.id"
+ },
+ {
+ "name": "product_id",
+ "type": "bigint",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "products.id"
+ },
+ {
+ "name": "qty",
+ "type": "int"
+ },
+ {
+ "name": "unit_cost",
+ "type": "numeric(10,2)"
+ }
+ ]
+ },
+ {
+ "id": "products",
+ "label": "products",
+ "tag": "stock",
+ "row": 0,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "sku",
+ "type": "varchar(32)",
+ "key": "uk"
+ },
+ {
+ "name": "name",
+ "type": "varchar(160)"
+ },
+ {
+ "name": "uom",
+ "type": "varchar(8)"
+ }
+ ]
+ },
+ {
+ "id": "stock_levels",
+ "label": "stock_levels",
+ "tag": "stock",
+ "row": 1,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "warehouse_id",
+ "type": "bigint",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "warehouses.id"
+ },
+ {
+ "name": "product_id",
+ "type": "bigint",
+ "key": [
+ "pk",
+ "fk"
+ ],
+ "references": "products.id"
+ },
+ {
+ "name": "on_hand",
+ "type": "int"
+ },
+ {
+ "name": "reserved",
+ "type": "int"
+ }
+ ]
+ },
+ {
+ "id": "warehouses",
+ "label": "warehouses",
+ "tag": "sites",
+ "row": 0,
+ "col": 2,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "bigint",
+ "key": "pk"
+ },
+ {
+ "name": "code",
+ "type": "varchar(8)",
+ "key": "uk"
+ },
+ {
+ "name": "city",
+ "type": "varchar(80)"
+ }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "id": "purchase_orders_suppliers",
+ "from": "purchase_orders",
+ "to": "suppliers",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "from supplier"
+ },
+ {
+ "id": "purchase_orders_warehouses",
+ "from": "purchase_orders",
+ "to": "warehouses",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "deliver to"
+ },
+ {
+ "id": "po_lines_purchase_orders",
+ "from": "po_lines",
+ "to": "purchase_orders",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "line of",
+ "identifying": true
+ },
+ {
+ "id": "po_lines_products",
+ "from": "po_lines",
+ "to": "products",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "orders",
+ "identifying": true
+ },
+ {
+ "id": "stock_levels_products",
+ "from": "stock_levels",
+ "to": "products",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "stock of",
+ "identifying": true
+ },
+ {
+ "id": "stock_levels_warehouses",
+ "from": "stock_levels",
+ "to": "warehouses",
+ "fromCardinality": "many",
+ "toCardinality": "one",
+ "label": "held at",
+ "identifying": true
+ }
+ ]
+}