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,class): keep obstacle detours a readable gap away from the boxes they pass

tt-a1id043041c022b
diff --git a/archify/renderers/architecture/routing.mjs b/archify/renderers/architecture/routing.mjs
index fdfd40f7..3f4a2792 100644
--- a/archify/renderers/architecture/routing.mjs
+++ b/archify/renderers/architecture/routing.mjs
@@ -50,6 +50,15 @@ import { shortestOrthogonalGridRoute } from '../shared/route-quality.mjs';
* 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 {number} [options.componentGapPx = 0] when positive, the obstacle
+ * grid first keeps a route this far from every component it merely passes
+ * (its own endpoints stay at the 2-unit clearance) and falls back to the
+ * tight search only when no spaced route is accepted, so a detour does not
+ * run along a neighbouring box edge 3 units away from its border.
+ * @param {number} [options.minimumTerminalSegmentPx = 0] shortest first and
+ * last segment any automatic route may have, applied even with
+ * compositionFloors off: a type that rounds its corners when drawing needs
+ * the end segment to outlast the corner radius plus the micro-segment floor.
* @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
@@ -70,6 +79,8 @@ export function createRouter(components, connections = [], {
preferredCandidates = null,
compositionFloors = true,
crossingFreeGridFirst = false,
+ componentGapPx = 0,
+ minimumTerminalSegmentPx = 0,
} = {}) {
const frameBorders = frames.flatMap((frame) => frameBorderSegments(frame));
const LABEL_CLEARANCE = 4;
@@ -108,6 +119,11 @@ export function createRouter(components, connections = [], {
// gate enforces afterwards. Accepting a route here that the gate rejects
// only hands the author a hand-routing repair the planner could have made.
function routeMeetsCompositionFloors(points) {
+ if (minimumTerminalSegmentPx > 0 && points.length > 2) {
+ const span = (a, b) => Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1]);
+ if (span(points[0], points[1]) < minimumTerminalSegmentPx
+ || span(points.at(-2), points.at(-1)) < minimumTerminalSegmentPx) return false;
+ }
if (compositionFloors
&& collectRouteRhythmIssues({ routedRelations: [{ points }], interiorSegmentPx, microSegmentPx }).length) {
return false;
@@ -137,6 +153,22 @@ export function createRouter(components, connections = [], {
};
// ---- Connection routing ------------------------------------------------------
+ const gridComponentGaps = componentGapPx > 0 ? [componentGapPx, 0] : [0];
+ // The spaced search is a readability preference, so its route must also be
+ // clean as drawn: full rhythm floors (even for a type that turns them off)
+ // and terminal segments long enough for a rounded corner and an end marker.
+ function spacedRouteIsClean(points, gap) {
+ if (gap === 0) return true;
+ const terminal = (a, b) => Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1]);
+ return terminal(points[0], points[1]) >= 16 && terminal(points.at(-2), points.at(-1)) >= 16
+ && collectRouteRhythmIssues({ routedRelations: [{ points }], interiorSegmentPx, microSegmentPx }).length === 0;
+ }
+ function gridComponentObstacles(conn, gap) {
+ return [...components.values()].map((component) => (gap === 0 || component.id === conn.from || component.id === conn.to
+ ? component
+ : { ...component, x: component.x - gap, y: component.y - gap, width: component.width + gap * 2, height: component.height + gap * 2 }));
+ }
+
function routeClearsComponents(conn, points, clearance = 2) {
const endpointIds = new Set([conn.from, conn.to]);
for (const component of components.values()) {
@@ -600,13 +632,13 @@ export function createRouter(components, connections = [], {
if (crossingFreeGridFirst) {
const unrelatedSegments = unrelatedResolvedRoutes(conn, resolvedRoutes)
.flatMap((entry) => entry.points.slice(1).map((end, index) => ({ start: entry.points[index], end })));
- if (unrelatedSegments.length) {
+ for (const gap of unrelatedSegments.length ? gridComponentGaps : []) {
planningMetrics.gridSearchCount += 1;
const strict = shortestOrthogonalGridRoute({
start,
end,
points: [start, end],
- obstacles: [...components.values(), ...reservedLabelObstacles(2)],
+ obstacles: [...gridComponentObstacles(conn, gap), ...reservedLabelObstacles(2)],
fromSide,
toSide,
clearance: 2,
@@ -626,7 +658,8 @@ export function createRouter(components, connections = [], {
&& routeClearsComponents(conn, strict.points)
&& !routeConflictsWithResolved(conn, strict.points, resolvedRoutes)
&& !routeOverlapsResolved(conn, strict.points, resolvedRoutes)
- && routeMeetsCompositionFloors(strict.points)) {
+ && routeMeetsCompositionFloors(strict.points)
+ && spacedRouteIsClean(strict.points, gap)) {
planningMetrics.gridRoutedCount += 1;
return strict.points.slice(1, -1);
}
@@ -638,66 +671,69 @@ export function createRouter(components, connections = [], {
.flatMap((entry) => entry.points.slice(1).map((end, index) => ({
start: entry.points[index], end,
})));
- const gridMetrics = {};
- planningMetrics.gridSearchCount += 1;
- planningMetrics.avoidedSegmentCount += avoidedSegments.length;
- const searched = shortestOrthogonalGridRoute({
- start,
- end,
- points: [start, end],
- obstacles: [...components.values(), ...reservedLabelObstacles(2)],
- fromSide,
- toSide,
- clearance: 2,
- maximumObstacleCount: 80,
- endpointStubPx: 24,
- maximumGridNodes: 4096,
- avoidedSegments,
- allowAvoidedCrossings: true,
- minimumAvoidedOverlapPx: 8,
- routeSeparationPx: 8,
- minimumSegmentPx: interiorSegmentPx,
- borderSegments: frameBorders,
- bendPenaltyPx: 48,
- metrics: gridMetrics,
- });
- planningMetrics.gridCandidateNodeCount += gridMetrics.candidateNodeCount || 0;
- planningMetrics.gridUsableNodeCount += gridMetrics.usableNodeCount || 0;
- planningMetrics.gridEdgeCount += gridMetrics.graphEdgeCount || 0;
- planningMetrics.gridVisitedNodeCount += gridMetrics.visitedNodeCount || 0;
- const clearsEndpoints = searched
- ? routeClearsEndpointComponents(searched.points, from, to) : false;
- const clearsComponents = searched
- ? routeClearsComponents(conn, searched.points) : false;
- const clearsRelationships = searched
- ? !routeConflictsWithResolved(conn, searched.points, resolvedRoutes) : false;
- const clearsSharedCorridors = searched
- ? !routeOverlapsResolved(conn, searched.points, resolvedRoutes) : false;
- const meetsFloors = searched ? routeMeetsCompositionFloors(searched.points) : false;
- const accepted = Boolean(
- searched && clearsEndpoints && clearsComponents && clearsSharedCorridors && meetsFloors,
- );
- planningMetrics.gridAttempts.push({
- relationship: conn.id || `${conn.from}->${conn.to}`,
- fromSide,
- toSide,
- inputAvoidedSegmentCount: avoidedSegments.length,
- ...gridMetrics,
- accepted,
- ...(!accepted && searched ? {
- rejectedBy: [
- ...(!clearsEndpoints ? ['endpoint-components'] : []),
- ...(!clearsComponents ? ['components'] : []),
- ...(!clearsSharedCorridors ? ['shared-corridor'] : []),
- ...(!meetsFloors ? ['composition-floors'] : []),
- ],
- candidatePoints: searched.points,
- } : {}),
- });
- if (accepted) {
- planningMetrics.gridRoutedCount += 1;
- if (!clearsRelationships) planningMetrics.crossoverRoutedCount += 1;
- return searched.points.slice(1, -1);
+ for (const gap of gridComponentGaps) {
+ const gridMetrics = {};
+ planningMetrics.gridSearchCount += 1;
+ planningMetrics.avoidedSegmentCount += avoidedSegments.length;
+ const searched = shortestOrthogonalGridRoute({
+ start,
+ end,
+ points: [start, end],
+ obstacles: [...gridComponentObstacles(conn, gap), ...reservedLabelObstacles(2)],
+ fromSide,
+ toSide,
+ clearance: 2,
+ maximumObstacleCount: 80,
+ endpointStubPx: 24,
+ maximumGridNodes: 4096,
+ avoidedSegments,
+ allowAvoidedCrossings: true,
+ minimumAvoidedOverlapPx: 8,
+ routeSeparationPx: 8,
+ minimumSegmentPx: interiorSegmentPx,
+ borderSegments: frameBorders,
+ bendPenaltyPx: 48,
+ metrics: gridMetrics,
+ });
+ planningMetrics.gridCandidateNodeCount += gridMetrics.candidateNodeCount || 0;
+ planningMetrics.gridUsableNodeCount += gridMetrics.usableNodeCount || 0;
+ planningMetrics.gridEdgeCount += gridMetrics.graphEdgeCount || 0;
+ planningMetrics.gridVisitedNodeCount += gridMetrics.visitedNodeCount || 0;
+ const clearsEndpoints = searched
+ ? routeClearsEndpointComponents(searched.points, from, to) : false;
+ const clearsComponents = searched
+ ? routeClearsComponents(conn, searched.points) : false;
+ const clearsRelationships = searched
+ ? !routeConflictsWithResolved(conn, searched.points, resolvedRoutes) : false;
+ const clearsSharedCorridors = searched
+ ? !routeOverlapsResolved(conn, searched.points, resolvedRoutes) : false;
+ const meetsFloors = searched
+ ? routeMeetsCompositionFloors(searched.points) && spacedRouteIsClean(searched.points, gap) : false;
+ const accepted = Boolean(
+ searched && clearsEndpoints && clearsComponents && clearsSharedCorridors && meetsFloors,
+ );
+ planningMetrics.gridAttempts.push({
+ relationship: conn.id || `${conn.from}->${conn.to}`,
+ fromSide,
+ toSide,
+ inputAvoidedSegmentCount: avoidedSegments.length,
+ ...gridMetrics,
+ accepted,
+ ...(!accepted && searched ? {
+ rejectedBy: [
+ ...(!clearsEndpoints ? ['endpoint-components'] : []),
+ ...(!clearsComponents ? ['components'] : []),
+ ...(!clearsSharedCorridors ? ['shared-corridor'] : []),
+ ...(!meetsFloors ? ['composition-floors'] : []),
+ ],
+ candidatePoints: searched.points,
+ } : {}),
+ });
+ if (accepted) {
+ planningMetrics.gridRoutedCount += 1;
+ if (!clearsRelationships) planningMetrics.crossoverRoutedCount += 1;
+ return searched.points.slice(1, -1);
+ }
}
// Both bounded doglegs are blocked. Keep the best endpoint-safe route
diff --git a/archify/renderers/class/render-class.mjs b/archify/renderers/class/render-class.mjs
index 9ae4b4bc..3a7afe63 100644
--- a/archify/renderers/class/render-class.mjs
+++ b/archify/renderers/class/render-class.mjs
@@ -443,6 +443,9 @@ const router = createRouter(types, routable.filter((relationship) => !busPaths.h
// any proper crossing, so the shorter crossing route only buys a repair.
preferReadableRoutes: true,
crossingFreeGridFirst: true,
+ // A detour keeps a readable gap from every type it only passes instead of
+ // running along its border at the grid's 2-unit clearance.
+ componentGapPx: 10,
});
function pathFor(relationship) {
const points = busPaths.get(relationship);
diff --git a/archify/renderers/erd/render-erd.mjs b/archify/renderers/erd/render-erd.mjs
index 142366ac..055e9454 100644
--- a/archify/renderers/erd/render-erd.mjs
+++ b/archify/renderers/erd/render-erd.mjs
@@ -567,6 +567,12 @@ const { ports, pathFor, inferredSides, connectionEndpointSide } = createRouter(e
// 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,
+ // A detour keeps a readable gap from every table it only passes instead of
+ // running along its border at the grid's 2-unit clearance.
+ componentGapPx: 10,
+ // Corners are drawn with a 6-unit radius; an end segment shorter than the
+ // radius plus the 8-unit micro-segment floor fails the drawn-route gate.
+ minimumTerminalSegmentPx: 14,
});
function corridorKey(relationship) {
diff --git a/test/class-first-draft-layout.test.mjs b/test/class-first-draft-layout.test.mjs
index 5f46f3d3..47cf2337 100644
--- a/test/class-first-draft-layout.test.mjs
+++ b/test/class-first-draft-layout.test.mjs
@@ -7,6 +7,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { properSegmentIntersection, rectsOverlap } from '../archify/renderers/shared/geometry.mjs';
+import { routeHugs } from './helpers/route-hugs.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.resolve(__dirname, '..', 'archify');
@@ -42,6 +43,14 @@ function labelBoxes(html) {
.map((match) => ({ id: match[1], x: +match[2], y: +match[3], width: +match[4], height: +match[5] }));
}
+function typeBoxes(html) {
+ const boxes = new Map();
+ for (const match of svgOf(html).matchAll(/data-node-id="([^"]+)"[^>]*>[\s\S]{0,600}?<rect x="([\d.-]+)" y="([\d.-]+)" width="([\d.]+)" height="([\d.]+)"/g)) {
+ if (!boxes.has(match[1])) boxes.set(match[1], { x: +match[2], y: +match[3], width: +match[4], height: +match[5] });
+ }
+ return boxes;
+}
+
function properCrossings(html) {
const all = routes(html);
const crossings = [];
@@ -63,6 +72,9 @@ for (const name of ['notifications', 'repository', 'shapes']) {
const result = render(diagram);
assert.equal(result.status, 0, result.stdout + result.stderr);
assert.deepEqual(properCrossings(result.html), []);
+ // shapes used to run 3 units along the Shape type, notifications along
+ // EmailChannel: a detour keeps a readable gap from the types it passes.
+ assert.deepEqual(routeHugs(routes(result.html), typeBoxes(result.html)), []);
assert.ok(labelBoxes(result.html).length > 0, 'the fixture draws relationship labels');
const validation = spawnSync(process.execPath, [cli, 'validate', 'class', result.input, '--quality', 'showcase', '--json'], { encoding: 'utf8' });
assert.equal(validation.status, 0, validation.stdout + validation.stderr);
diff --git a/test/erd-first-draft-layout.test.mjs b/test/erd-first-draft-layout.test.mjs
index 2862daf8..933526e5 100644
--- a/test/erd-first-draft-layout.test.mjs
+++ b/test/erd-first-draft-layout.test.mjs
@@ -7,6 +7,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { properSegmentIntersection, rectsOverlap } from '../archify/renderers/shared/geometry.mjs';
+import { routeHugs } from './helpers/route-hugs.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.resolve(__dirname, '..', 'archify');
@@ -98,6 +99,9 @@ for (const name of ['blog', 'shop', 'warehouse']) {
assert.equal(result.status, 0, result.stdout + result.stderr);
assertLabelsClear(result.html);
assert.deepEqual(properCrossings(result.html), []);
+ // A detour keeps a readable gap from the tables it passes (warehouse used
+ // to run 3 units along the products table for its full width).
+ assert.deepEqual(routeHugs(routes(result.html), entityBoxes(result.html)), []);
const check = spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' });
assert.equal(check.status, 0, check.stdout);
});
diff --git a/test/helpers/route-hugs.mjs b/test/helpers/route-hugs.mjs
new file mode 100644
index 00000000..9339fc47
--- /dev/null
+++ b/test/helpers/route-hugs.mjs
@@ -0,0 +1,26 @@
+// Route segments that run alongside a box they do not end on, closer than
+// `gap` units for more than `minimum` units: the line reads as that box's
+// border instead of a relationship passing by.
+export function routeHugs(routes, boxes, { gap = 8, minimum = 12 } = {}) {
+ const hits = [];
+ for (const route of routes) {
+ for (let index = 0; index < route.points.length - 1; index += 1) {
+ const [a, b] = [route.points[index], route.points[index + 1]];
+ for (const [id, box] of boxes) {
+ if ((id === route.from && index === 0) || (id === route.to && index === route.points.length - 2)) continue;
+ const horizontal = Math.abs(a[1] - b[1]) < 0.01;
+ if (!horizontal && Math.abs(a[0] - b[0]) >= 0.01) continue;
+ const [along, across, start, size, crossStart, crossSize] = horizontal
+ ? [0, 1, box.x, box.width, box.y, box.height]
+ : [1, 0, box.y, box.height, box.x, box.width];
+ const overlap = Math.min(Math.max(a[along], b[along]), start + size) - Math.max(Math.min(a[along], b[along]), start);
+ if (overlap < minimum) continue;
+ const position = a[across];
+ const distance = position < crossStart ? crossStart - position
+ : position > crossStart + crossSize ? position - crossStart - crossSize : -1;
+ if (distance >= 0 && distance < gap) hits.push({ route: route.id, box: id, distance, overlap });
+ }
+ }
+ }
+ return hits;
+}