geometry.mjs
2073 lines · archify/renderers/shared/geometry.mjs at a406594
1// Geometry helpers shared by all typed renderers. Every function here is
2// pure; renderers own their layout tables and pass measured rects
3// ({x, y, width, height, cx, cy}) in.
5import { recordDiagnostic } from './diagnostics.mjs';
7// In degraded mode (no ajv) a type-wrong top-level field reaches the renderer.
8// Coerce non-arrays to [] so the module-level Maps build without throwing and
9// the friendly validator checks (which run later) report the real problem.
10export function asArray(value) {
11 return Array.isArray(value) ? value : [];
12}
14// A computed coordinate must be a finite number; NaN/undefined would silently
15// write `<rect x="NaN">` into the output. Used by the validators as a backstop.
16export function isFinitePoint(...coords) {
17 return coords.every((c) => Number.isFinite(c));
18}
20// Separation the layout solver guarantees and separation this check re-derives
21// travel through different arithmetic, so a pair the solver placed at exactly
22// its minimum can land a few ulps short of this comparison. In #583 the CLI's
23// own receipt has the pair `793.6 + 160 + 8` read as 2**-43 past a5's left edge
24// at 961.5999999999999 — one ulp at that magnitude. 0.0001 is the numeric
25// tolerance the route and layout geometry in this file already compares with.
26const NUMERIC_CLEARANCE_PX = 0.0001;
28export function rectsOverlap(a, b, gap = 0) {
29 // Non-finite geometry means "unknown", not "overlapping". Every comparison
30 // below is false for NaN, so without this guard the negation reports a
31 // collision for every pair. Callers surface non-finite pos/size through their
32 // own diagnostic; reporting it again as an overlap buries that message under
33 // one bogus separation hint per pair.
34 if (!isFinitePoint(a.x, a.y, a.width, a.height, b.x, b.y, b.width, b.height)) {
35 return false;
36 }
37 return !(
38 a.x + a.width + gap <= b.x + NUMERIC_CLEARANCE_PX ||
39 b.x + b.width + gap <= a.x + NUMERIC_CLEARANCE_PX ||
40 a.y + a.height + gap <= b.y + NUMERIC_CLEARANCE_PX ||
41 b.y + b.height + gap <= a.y + NUMERIC_CLEARANCE_PX
42 );
43}
45export function segmentIntersectsRect(segment, rect, gap = 0) {
46 const box = {
47 x1: rect.x - gap,
48 y1: rect.y - gap,
49 x2: rect.x + rect.width + gap,
50 y2: rect.y + rect.height + gap
51 };
52 const [a, b] = [segment.start, segment.end];
53 if (pointInBox(a, box) || pointInBox(b, box)) return true;
54 return (
55 segmentsIntersect(a, b, [box.x1, box.y1], [box.x2, box.y1]) ||
56 segmentsIntersect(a, b, [box.x2, box.y1], [box.x2, box.y2]) ||
57 segmentsIntersect(a, b, [box.x2, box.y2], [box.x1, box.y2]) ||
58 segmentsIntersect(a, b, [box.x1, box.y2], [box.x1, box.y1])
59 );
60}
62export function segmentRectClearance(segment, rect) {
63 if (!segment || !rect) return null;
64 const { start, end } = segment;
65 if (!Array.isArray(start) || !Array.isArray(end) || start.length !== 2 || end.length !== 2) return null;
66 if (!isFinitePoint(start[0], start[1], end[0], end[1], rect.x, rect.y, rect.width, rect.height)) return null;
67 if (rect.width < 0 || rect.height < 0) return null;
68 if (segmentIntersectsRect(segment, rect)) return 0;
70 const right = rect.x + rect.width;
71 const bottom = rect.y + rect.height;
72 let clearance = Math.min(pointRectDistance(start, rect), pointRectDistance(end, rect));
73 const corners = [rect.x, rect.y, right, rect.y, right, bottom, rect.x, bottom];
74 for (let index = 0; index < 8; index += 2) {
75 const distance = pointSegmentDistanceXY(corners[index], corners[index + 1], start, end);
76 if (distance < clearance) clearance = distance;
77 }
78 return clearance;
79}
81// The same clearance, but the caller already knows the threshold it compares
82// against: when an axis gap alone proves the distance cannot be smaller, the
83// exact distance is never computed and Infinity is returned.
84export function segmentRectClearanceWithin(segment, rect, limit) {
85 if (!segment || !rect) return segmentRectClearance(segment, rect);
86 const { start, end } = segment;
87 if (!Array.isArray(start) || !Array.isArray(end) || start.length !== 2 || end.length !== 2) return null;
88 if (!isFinitePoint(start[0], start[1], end[0], end[1], rect.x, rect.y, rect.width, rect.height)) return null;
89 if (rect.width < 0 || rect.height < 0) return null;
90 if (segmentIntersectsRect(segment, rect)) return 0;
91 const minX = Math.min(start[0], end[0]);
92 const maxX = Math.max(start[0], end[0]);
93 const minY = Math.min(start[1], end[1]);
94 const maxY = Math.max(start[1], end[1]);
95 const gapX = Math.max(rect.x - maxX, minX - (rect.x + rect.width));
96 const gapY = Math.max(rect.y - maxY, minY - (rect.y + rect.height));
97 if (Math.max(gapX, gapY) > limit) return Number.POSITIVE_INFINITY;
98 return segmentRectClearance(segment, rect);
99}
101export function segmentRectIntersectionLength(segment, rect) {
102 if (!segment || !rect) return null;
103 const { start, end } = segment;
104 if (!Array.isArray(start) || !Array.isArray(end) || start.length !== 2 || end.length !== 2) return null;
105 if (!isFinitePoint(...start, ...end, rect.x, rect.y, rect.width, rect.height)) return null;
106 if (rect.width < 0 || rect.height < 0) return null;
108 const dx = end[0] - start[0];
109 const dy = end[1] - start[1];
110 const length = Math.hypot(dx, dy);
111 if (length <= 0.0000001) return 0;
112 const bounds = [
113 [-dx, start[0] - rect.x],
114 [dx, rect.x + rect.width - start[0]],
115 [-dy, start[1] - rect.y],
116 [dy, rect.y + rect.height - start[1]],
117 ];
118 let enter = 0;
119 let leave = 1;
120 for (const [direction, distance] of bounds) {
121 if (Math.abs(direction) <= 0.0000001) {
122 if (distance < -0.0000001) return 0;
123 continue;
124 }
125 const ratio = distance / direction;
126 if (direction < 0) enter = Math.max(enter, ratio);
127 else leave = Math.min(leave, ratio);
128 if (enter > leave + 0.0000001) return 0;
129 }
130 return length * Math.max(0, leave - enter);
131}
133const ROUTE_INDEX_CELL_SIZE = 128;
134const ROUTE_INDEX_MAX_CELLS_PER_ROUTE = 256;
136function routeBounds(route) {
137 let x1 = Infinity;
138 let y1 = Infinity;
139 let x2 = -Infinity;
140 let y2 = -Infinity;
141 for (const [x, y] of route.points) {
142 x1 = Math.min(x1, x);
143 y1 = Math.min(y1, y);
144 x2 = Math.max(x2, x);
145 y2 = Math.max(y2, y);
146 }
147 return { x1, y1, x2, y2 };
148}
150function createRouteCandidateIndex(routes) {
151 const cells = new Map();
152 const globalRouteIndexes = [];
154 routes.forEach((route, routeIndex) => {
155 const bounds = routeBounds(route);
156 const x1 = Math.floor(bounds.x1 / ROUTE_INDEX_CELL_SIZE);
157 const y1 = Math.floor(bounds.y1 / ROUTE_INDEX_CELL_SIZE);
158 const x2 = Math.floor(bounds.x2 / ROUTE_INDEX_CELL_SIZE);
159 const y2 = Math.floor(bounds.y2 / ROUTE_INDEX_CELL_SIZE);
160 if (![x1, y1, x2, y2].every(Number.isSafeInteger)) {
161 globalRouteIndexes.push(routeIndex);
162 return;
163 }
164 const cellCount = (x2 - x1 + 1) * (y2 - y1 + 1);
166 // Very long routes are cheaper to test once per label than to duplicate
167 // across a large part of the index.
168 if (!Number.isSafeInteger(cellCount) || cellCount > ROUTE_INDEX_MAX_CELLS_PER_ROUTE) {
169 globalRouteIndexes.push(routeIndex);
170 return;
171 }
172 for (let y = y1; y <= y2; y += 1) {
173 for (let x = x1; x <= x2; x += 1) {
174 const key = `${x}:${y}`;
175 const bucket = cells.get(key);
176 if (bucket) bucket.push(routeIndex);
177 else cells.set(key, [routeIndex]);
178 }
179 }
180 });
182 return function candidates(rect, threshold) {
183 const x1 = Math.floor((rect.x - threshold) / ROUTE_INDEX_CELL_SIZE);
184 const y1 = Math.floor((rect.y - threshold) / ROUTE_INDEX_CELL_SIZE);
185 const x2 = Math.floor((rect.x + rect.width + threshold) / ROUTE_INDEX_CELL_SIZE);
186 const y2 = Math.floor((rect.y + rect.height + threshold) / ROUTE_INDEX_CELL_SIZE);
187 const cellCount = (x2 - x1 + 1) * (y2 - y1 + 1);
189 // A huge threshold offers no selectivity and can overflow cell iteration.
190 if (![x1, y1, x2, y2].every(Number.isSafeInteger)
191 || !Number.isSafeInteger(cellCount)
192 || cellCount > Math.max(64, cells.size * 4)) return routes;
194 const routeIndexes = new Set(globalRouteIndexes);
195 for (let y = y1; y <= y2; y += 1) {
196 for (let x = x1; x <= x2; x += 1) {
197 for (const routeIndex of cells.get(`${x}:${y}`) || []) routeIndexes.add(routeIndex);
198 }
199 }
200 return [...routeIndexes]
201 .sort((left, right) => left - right)
202 .map((routeIndex) => routes[routeIndex]);
203 };
204}
206export function collectLabelRouteClearance({ labels, routedRelations, threshold }) {
207 if (!Number.isFinite(threshold) || threshold < 0) return [];
208 if (threshold === 0) return [];
209 const routeCandidates = asArray(routedRelations).map((entry, fallbackIndex) => {
210 const relation = entry?.relation || entry;
211 const points = normalizeRoutePoints(entry?.points || relation?.routePoints);
212 if (!relation || points.length < 2) return null;
213 return {
214 relation,
215 relationIndex: Number.isInteger(entry?.relationIndex) ? entry.relationIndex : fallbackIndex,
216 points,
217 };
218 }).filter(Boolean);
219 const seenRoutes = new Set();
220 const routes = routeCandidates.filter((route) => {
221 const identity = relationshipIdentity(route.relation, route.relationIndex);
222 if (seenRoutes.has(identity)) return false;
223 seenRoutes.add(identity);
224 return true;
225 });
226 const hits = [];
227 const seenLabels = new Set();
228 const candidateRoutes = createRouteCandidateIndex(routes);
230 for (const [fallbackIndex, label] of asArray(labels).entries()) {
231 const rect = label?.rect || label;
232 if (!rect || !isFinitePoint(rect.x, rect.y, rect.width, rect.height) || rect.width < 0 || rect.height < 0) continue;
233 const relationIndex = Number.isInteger(label?.relationIndex) ? label.relationIndex : fallbackIndex;
234 const labelIdentity = relationshipIdentity(label?.relation, relationIndex);
235 if (seenLabels.has(labelIdentity)) continue;
236 seenLabels.add(labelIdentity);
237 for (const route of candidateRoutes(rect, threshold)) {
238 if (relationIndex === route.relationIndex || sameRelationship(label?.relation, route.relation)) continue;
239 let nearest = null;
240 for (let segmentIndex = 0; segmentIndex < route.points.length - 1; segmentIndex += 1) {
241 const start = route.points[segmentIndex];
242 const end = route.points[segmentIndex + 1];
243 const clearance = segmentRectClearance({ start, end }, rect);
244 if (clearance == null) continue;
245 if (!nearest || clearance < nearest.clearance) {
246 nearest = {
247 clearance,
248 intersectionLength: segmentRectIntersectionLength({ start, end }, rect),
249 segmentIndex,
250 start,
251 end,
252 };
253 }
254 }
255 if (!nearest || nearest.clearance + 0.0001 >= threshold) continue;
256 hits.push({
257 label,
258 labelRelation: label?.relation,
259 labelRelationIndex: relationIndex,
260 otherRelation: route.relation,
261 otherRelationIndex: route.relationIndex,
262 rect,
263 ...nearest,
264 threshold,
265 });
266 }
267 }
268 return hits;
269}
271export function minimumLabelRouteClearance(measurements) {
272 if (!asArray(measurements).length) return null;
273 const minimum = measurements.reduce(
274 (value, hit) => Math.min(value, hit.clearance),
275 Infinity,
276 );
277 return Math.round(minimum * 10) / 10;
278}
280function relationshipIdentity(relation, relationIndex) {
281 if (relation?.key !== undefined) return `key:${relation.key}`;
282 if (relation?.id) return `id:${relation.from || ''}\u0000${relation.to || ''}\u0000${relation.id}`;
283 return `index:${relationIndex}`;
284}
286function sameRelationship(left, right) {
287 if (!left || !right) return false;
288 if (left === right) return true;
289 if (left.key !== undefined && right.key !== undefined) return left.key === right.key;
290 return Boolean(left.id && right.id && left.id === right.id && left.from === right.from && left.to === right.to);
291}
293function relationshipSubject(diagramType, relationCollection, relationIndex, relation) {
294 return {
295 diagramType,
296 collection: relationCollection,
297 index: relationIndex,
298 ...(relation?.id ? { id: relation.id } : {}),
299 ...(relation?.from ? { from: relation.from } : {}),
300 ...(relation?.to ? { to: relation.to } : {}),
301 };
302}
304const AUTHORED_PLAN_KEYS = ['route', 'via', 'channelX', 'channelY', 'fromSide', 'toSide', 'bias', 'labelAt', 'labelDx', 'labelDy', 'labelSegment'];
306// Re-planning advice only applies when the failing relation actually carries
307// authored controls; telling an author to remove controls that do not exist
308// just sends them hunting for a field that was never written.
309function rePlanHint(relations, fallback) {
310 const controls = new Set();
311 for (const relation of asArray(relations)) {
312 for (const key of AUTHORED_PLAN_KEYS) if (relation?.[key] !== undefined) controls.add(key);
313 }
314 if (!controls.size) return fallback;
315 return `if the authored ${[...controls].join('/')} are not required by the user, remove them so the renderer can re-plan; otherwise preserve that intent and ${fallback}`;
316}
318const ENDPOINT_SIDE_RULES = {
319 left: {
320 axis: 'horizontal',
321 sourceSign: -1,
322 targetSign: 1,
323 sourceDirection: 'leftward',
324 targetDirection: 'rightward from the left',
325 },
326 right: {
327 axis: 'horizontal',
328 sourceSign: 1,
329 targetSign: -1,
330 sourceDirection: 'rightward',
331 targetDirection: 'leftward from the right',
332 },
333 top: {
334 axis: 'vertical',
335 sourceSign: -1,
336 targetSign: 1,
337 sourceDirection: 'upward',
338 targetDirection: 'downward from above',
339 },
340 bottom: {
341 axis: 'vertical',
342 sourceSign: 1,
343 targetSign: -1,
344 sourceDirection: 'downward',
345 targetDirection: 'upward from below',
346 },
347};
349function endpointSideIssue(points, endpoint, side) {
350 const rule = ENDPOINT_SIDE_RULES[side];
351 if (!rule) return null;
352 const normalized = normalizeRoutePoints(points);
353 if (normalized.length < 2) return null;
354 const segmentIndex = endpoint === 'source' ? 0 : normalized.length - 2;
355 const start = normalized[segmentIndex];
356 const end = normalized[segmentIndex + 1];
357 const dx = end[0] - start[0];
358 const dy = end[1] - start[1];
359 const along = rule.axis === 'horizontal' ? dx : dy;
360 const across = rule.axis === 'horizontal' ? dy : dx;
361 const expectedSign = endpoint === 'source' ? rule.sourceSign : rule.targetSign;
362 if (Math.abs(across) <= 0.0001 && along * expectedSign > 0.0001) return null;
363 return {
364 endpoint,
365 side,
366 segmentIndex,
367 start,
368 end,
369 expectedAxis: rule.axis,
370 expectedDirection: endpoint === 'source' ? rule.sourceDirection : rule.targetDirection,
371 };
372}
374// A side is a direction contract, not just a point on a box border. This pure
375// predicate lets automatic routers prefer a dogleg whose first and final
376// segments leave/enter the chosen sides perpendicularly.
377export function routeHonorsEndpointSides(points, fromSide, toSide) {
378 return !endpointSideIssue(points, 'source', fromSide)
379 && !endpointSideIssue(points, 'target', toSide);
380}
381// Explicit fromSide/toSide are authored geometry, so a tangent or backwards
382// endpoint segment changes their meaning. Fail this universally instead of
383// leaving a malformed arrow for visual review to discover. Named routes and
384// authored via points already carry their own geometry semantics: when they
385// omit endpoint sides, do not invent a relative-position side and then reject
386// the route for disagreeing with that invention. Pure automatic routes may
387// still be checked against renderer-inferred sides.
388export function cleanEndpointSideProblems({
389 relations,
390 endpointIds,
391 pathFor,
392 diagramType,
393 relationCollection,
394 fromSideFor,
395 toSideFor,
396 shouldCheckRelation = () => true,
397 routeHint = 'align the first/final via segment with fromSide/toSide, change the side, or remove explicit routing so auto can choose a perpendicular approach',
398}) {
399 const problems = [];
400 for (const [relationIndex, relation] of asArray(relations).entries()) {
401 if (!relation || !endpointIds?.has(relation.from) || !endpointIds?.has(relation.to)) continue;
402 if (!shouldCheckRelation(relation, relationIndex)) continue;
403 const points = pathFor(relation)?.points;
404 if (!Array.isArray(points) || points.length < 2) continue;
405 const authoredFromSide = relation.fromSide && relation.fromSide !== 'auto' ? relation.fromSide : null;
406 const authoredToSide = relation.toSide && relation.toSide !== 'auto' ? relation.toSide : null;
407 const hasAuthoredRouteGeometry = Boolean(
408 (relation.route && relation.route !== 'auto') || Array.isArray(relation.via),
409 );
410 const inferredFromSide = !hasAuthoredRouteGeometry && typeof fromSideFor === 'function'
411 ? fromSideFor(relation)
412 : null;
413 const inferredToSide = !hasAuthoredRouteGeometry && typeof toSideFor === 'function'
414 ? toSideFor(relation)
415 : null;
416 const fromSide = authoredFromSide ?? inferredFromSide;
417 const toSide = authoredToSide ?? inferredToSide;
418 const checks = [
419 fromSide
420 ? { ...endpointSideIssue(points, 'source', fromSide), sideOrigin: authoredFromSide ? 'authored' : 'inferred' }
421 : null,
422 toSide
423 ? { ...endpointSideIssue(points, 'target', toSide), sideOrigin: authoredToSide ? 'authored' : 'inferred' }
424 : null,
425 ].filter((issue) => issue?.endpoint);
426 for (const issue of checks) {
427 const relationId = relation.id ? ` id "${relation.id}"` : '';
428 const authoredField = issue.endpoint === 'source' ? 'fromSide' : 'toSide';
429 const sideField = issue.sideOrigin === 'inferred' ? `inferred ${authoredField}` : authoredField;
430 const segmentRole = issue.endpoint === 'source' ? 'first' : 'final';
431 const from = issue.start.map((value) => Math.round(value * 10) / 10).join(', ');
432 const to = issue.end.map((value) => Math.round(value * 10) / 10).join(', ');
433 const message = `[clean-flow/endpoint-side-direction] ${diagramType} ${relationCollection}[${relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" ${segmentRole} segment ${issue.segmentIndex} [${from}] -> [${to}] does not honor ${sideField} "${issue.side}" — it must run ${issue.expectedAxis} ${issue.expectedDirection}; ${routeHint}.`;
434 recordDiagnostic({
435 code: 'clean-flow/endpoint-side-direction',
436 severity: 'error',
437 message,
438 subject: relationshipSubject(diagramType, relationCollection, relationIndex, relation),
439 evidence: {
440 endpoint: issue.endpoint,
441 authoredField,
442 sideOrigin: issue.sideOrigin,
443 side: issue.side,
444 segmentIndex: issue.segmentIndex,
445 from: issue.start,
446 to: issue.end,
447 expectedAxis: issue.expectedAxis,
448 expectedDirection: issue.expectedDirection,
449 },
450 supportedFixes: [routeHint],
451 });
452 problems.push(message);
453 }
454 }
455 return problems;
456}
458// One mechanical quality gate for every renderer-owned relationship path.
459// A renderer supplies its semantic obstacle set; source/target boxes are
460// always exempt because paths are expected to terminate on their boundaries.
461// Containers, lifelines, and other intentionally pass-through geometry should
462// simply not be supplied as obstacles.
463export function cleanFlowProblems({
464 relations,
465 obstacles,
466 pathFor,
467 diagramType,
468 relationCollection,
469 obstacleKind,
470 clearance = 2,
471 routeHint = 'adjust fromSide/toSide, set route/via or channel coordinates, or move the obstacle'
472}) {
473 // A relationship hidden behind an unrelated opaque node changes the
474 // diagram's meaning, so this is a correctness invariant rather than an
475 // opt-in composition preference. Keep it active even when the author omits
476 // quality_profile; standard/showcase still control stricter visual budgets.
477 const problems = [];
478 const obstacleList = [...obstacles];
479 const obstacleIds = new Set(obstacleList.map((obstacle) => obstacle?.id));
480 for (const [relationIndex, relation] of asArray(relations).entries()) {
481 if (!relation || typeof relation.from !== 'string' || typeof relation.to !== 'string') continue;
482 if (!obstacleIds.has(relation.from) || !obstacleIds.has(relation.to)) continue;
483 const points = pathFor(relation)?.points;
484 if (!Array.isArray(points) || points.length < 2) continue;
485 if (!points.every((point) => Array.isArray(point) && point.length === 2 && isFinitePoint(...point))) continue;
487 const endpointIds = new Set([relation.from, relation.to]);
488 for (const obstacle of obstacleList) {
489 if (!obstacle || endpointIds.has(obstacle.id)) continue;
490 if (!isFinitePoint(obstacle.x, obstacle.y, obstacle.width, obstacle.height)) continue;
491 let hitSegment = -1;
492 for (let segmentIndex = 0; segmentIndex < points.length - 1; segmentIndex += 1) {
493 if (segmentIntersectsRect({ start: points[segmentIndex], end: points[segmentIndex + 1] }, obstacle, clearance)) {
494 hitSegment = segmentIndex;
495 break;
496 }
497 }
498 if (hitSegment === -1) continue;
499 const from = points[hitSegment].map(Math.round).join(', ');
500 const to = points[hitSegment + 1].map(Math.round).join(', ');
501 const relationId = relation.id ? ` id "${relation.id}"` : '';
502 const hint = rePlanHint([relation], routeHint);
503 const message = `[clean-flow/edge-through-node] ${diagramType} ${relationCollection}[${relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" crosses ${obstacleKind} "${obstacle.id}" (unrelated to this relationship) on segment ${hitSegment} [${from}] -> [${to}] (${clearance}px clearance) — ${hint}.`;
504 recordDiagnostic({
505 code: 'clean-flow/edge-through-node',
506 severity: 'error',
507 message,
508 subject: relationshipSubject(diagramType, relationCollection, relationIndex, relation),
509 evidence: {
510 obstacleKind,
511 obstacleId: obstacle.id,
512 segmentIndex: hitSegment,
513 from: points[hitSegment],
514 to: points[hitSegment + 1],
515 clearancePx: clearance,
516 },
517 supportedFixes: [hint],
518 });
519 problems.push(message);
520 }
521 }
522 return problems;
523}
525// Build a read-only analysis copy of a polyline with straight-through
526// waypoints removed. A waypoint on a forward-collinear run is not a visual
527// endpoint, so treating it as one would hide a proper X that lands exactly on
528// that waypoint. Reversals and real bends stay split: their shared point can
529// still be an authored touch rather than a crossing. The source points are
530// retained on every merged segment so diagnostics can name the authored
531// segment that contains a hit without changing rendered/receipt geometry.
532export function forwardCollinearAnalysisSegments(points) {
533 const segments = [];
534 for (let segmentIndex = 0; segmentIndex < asArray(points).length - 1; segmentIndex += 1) {
535 const authoredStart = points[segmentIndex];
536 const authoredEnd = points[segmentIndex + 1];
537 const start = Array.isArray(authoredStart) ? [...authoredStart] : authoredStart;
538 const end = Array.isArray(authoredEnd) ? [...authoredEnd] : authoredEnd;
539 const sourceSegment = { start, end, segmentIndex };
540 const previous = segments.at(-1);
541 if (previous && segmentsContinueForward(previous.start, previous.end, start, end)) {
542 previous.end = end;
543 previous.sourceSegments.push(sourceSegment);
544 continue;
545 }
546 segments.push({
547 start,
548 end,
549 segmentIndex,
550 sourceSegments: [sourceSegment],
551 });
552 }
553 return segments;
554}
556export function sourceSegmentIndexAtPoint(segment, point) {
557 const source = asArray(segment?.sourceSegments).find(({ start, end }) => (
558 pointLiesOnSegment(point, start, end)
559 ));
560 return source?.segmentIndex ?? segment?.segmentIndex ?? 0;
561}
563function authoredAnalysisSegments(points) {
564 return asArray(points).slice(0, -1).map((start, segmentIndex) => ({
565 start,
566 end: points[segmentIndex + 1],
567 segmentIndex,
568 sourceSegments: [{ start, end: points[segmentIndex + 1], segmentIndex }],
569 }));
570}
572function segmentsContinueForward(firstStart, firstEnd, secondStart, secondEnd) {
573 if (![firstStart, firstEnd, secondStart, secondEnd].every((point) => (
574 Array.isArray(point) && point.length === 2 && isFinitePoint(...point)
575 ))) return false;
576 const epsilon = 0.0001;
577 if (Math.abs(firstEnd[0] - secondStart[0]) > epsilon
578 || Math.abs(firstEnd[1] - secondStart[1]) > epsilon) return false;
579 const firstVector = [firstEnd[0] - firstStart[0], firstEnd[1] - firstStart[1]];
580 const secondVector = [secondEnd[0] - secondStart[0], secondEnd[1] - secondStart[1]];
581 const firstLength = Math.hypot(...firstVector);
582 const secondLength = Math.hypot(...secondVector);
583 if (firstLength <= epsilon || secondLength <= epsilon) return false;
584 const cross = firstVector[0] * secondVector[1] - firstVector[1] * secondVector[0];
585 if (Math.abs(cross) > epsilon) return false;
586 const dot = firstVector[0] * secondVector[0] + firstVector[1] * secondVector[1];
587 return dot > epsilon;
588}
590function pointLiesOnSegment(point, start, end) {
591 if (![point, start, end].every((candidate) => (
592 Array.isArray(candidate) && candidate.length === 2 && isFinitePoint(...candidate)
593 ))) return false;
594 const epsilon = 0.0001;
595 const length = Math.hypot(end[0] - start[0], end[1] - start[1]);
596 if (length <= epsilon) return Math.hypot(point[0] - start[0], point[1] - start[1]) <= epsilon;
597 if (Math.abs(crossProduct(start, end, point)) > epsilon * length) return false;
598 return point[0] >= Math.min(start[0], end[0]) - epsilon
599 && point[0] <= Math.max(start[0], end[0]) + epsilon
600 && point[1] >= Math.min(start[1], end[1]) - epsilon
601 && point[1] <= Math.max(start[1], end[1]) + epsilon;
602}
604// A bend meeting another route's interior can look like a branch even when
605// no pair of segment interiors forms a proper X. Keep actual route endpoints
606// out of this geometric query; callers decide which relationships are allowed
607// to share junctions. Collinear corridors remain a separate quality measure.
608export function polylineBendContacts(left, right) {
609 const contacts = [];
610 const near = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]) <= 0.0001;
611 for (const [points, other] of [[left, right], [right, left]]) {
612 if (other.length < 2) continue;
613 for (let index = 1; index < points.length - 1; index += 1) {
614 const point = points[index];
615 if (Math.abs(crossProduct(points[index - 1], point, points[index + 1])) <= 0.0001
616 || near(point, other[0]) || near(point, other.at(-1))) continue;
617 if (other.slice(1).some((end, segment) => pointLiesOnSegment(point, other[segment], end))
618 && !contacts.some(otherPoint => near(point, otherPoint))) contacts.push(point);
619 }
620 }
621 return contacts;
622}
624// Authored shared endpoints retain their junction interpretation by default.
625// Renderers can opt their automatic routes into proper interior X checks;
626// endpoint touches and collinear trunks still are not proper crossings.
627export function cleanCrossingProblems({
628 relations,
629 endpointIds,
630 pathFor,
631 diagramType,
632 relationCollection,
633 profile = 'standard',
634 profileIsAuthoritative = false,
635 mergeForwardCollinearWaypoints = false,
636 includeSharedEndpoints = () => false,
637 crossingResolved = () => false,
638 warnInStandard = false,
639 onDiagnostic = recordDiagnostic,
640 routeHint = 'adjust route/via or channel coordinates so the relationships use separate corridors'
641}) {
642 const severity = qualityProfileForGate(profile, profileIsAuthoritative) === 'showcase' ? 'error' : 'warning';
643 if (severity === 'warning' && !warnInStandard) return [];
644 const routed = asArray(relations).map((relation, index) => {
645 if (!relation || !endpointIds.has(relation.from) || !endpointIds.has(relation.to)) return null;
646 const points = pathFor(relation)?.points;
647 if (!Array.isArray(points) || points.length < 2) return null;
648 if (!points.every((point) => Array.isArray(point) && point.length === 2 && isFinitePoint(...point))) return null;
649 return {
650 relation,
651 index,
652 points,
653 analysisSegments: mergeForwardCollinearWaypoints
654 ? forwardCollinearAnalysisSegments(points)
655 : authoredAnalysisSegments(points),
656 };
657 }).filter(Boolean);
658 const problems = [];
660 for (let leftIndex = 0; leftIndex < routed.length; leftIndex += 1) {
661 const left = routed[leftIndex];
662 for (let rightIndex = leftIndex + 1; rightIndex < routed.length; rightIndex += 1) {
663 const right = routed[rightIndex];
664 if ([left.relation.from, left.relation.to].some((id) => id === right.relation.from || id === right.relation.to)
665 && !includeSharedEndpoints(left.relation, right.relation)) continue;
667 let hit = null;
668 for (const leftSegment of left.analysisSegments) {
669 if (hit) break;
670 for (const rightSegment of right.analysisSegments) {
671 const point = properSegmentIntersection(
672 leftSegment.start,
673 leftSegment.end,
674 rightSegment.start,
675 rightSegment.end
676 );
677 if (point) {
678 hit = {
679 point,
680 leftSegment: sourceSegmentIndexAtPoint(leftSegment, point),
681 rightSegment: sourceSegmentIndexAtPoint(rightSegment, point),
682 };
683 break;
684 }
685 }
686 }
687 if (!hit) continue;
688 if (crossingResolved(left.relation, right.relation, hit)) continue;
690 const describe = ({ relation, index }) => {
691 const id = relation.id ? ` id "${relation.id}"` : '';
692 return `${relationCollection}[${index}]${id} "${relation.from}" -> "${relation.to}"`;
693 };
694 const point = hit.point.map((value) => Math.round(value * 10) / 10).join(', ');
695 const hint = rePlanHint([left.relation, right.relation], routeHint);
696 const message = `[composition/proper-crossing] ${severity === 'error' ? 'showcase' : 'standard'} ${diagramType} ${describe(left)} crosses ${describe(right)} at [${point}] (segments ${hit.leftSegment} and ${hit.rightSegment}) — ${hint}.`;
697 onDiagnostic({
698 code: 'composition/proper-crossing',
699 severity,
700 message,
701 subject: relationshipSubject(diagramType, relationCollection, left.index, left.relation),
702 evidence: {
703 otherRelationship: relationshipSubject(diagramType, relationCollection, right.index, right.relation),
704 point: hit.point,
705 segmentIndex: hit.leftSegment,
706 otherSegmentIndex: hit.rightSegment,
707 },
708 supportedFixes: [hint],
709 });
710 if (severity === 'error') problems.push(message);
711 }
712 }
713 return problems;
714}
716// Two unrelated relationships that occupy the same visible corridor can read
717// as one authored branch or merge even when neither relationship crosses a
718// node or forms a proper X. Keep authored shared endpoints exempt by default;
719// automatic architecture routes opt in because they promise separate ports.
720// Workflow v2 opts into shared-endpoint checks with a bounded terminal-trunk
721// exception. Other callers keep their existing authored-junction contract.
722// The counterflow-only opt-in serves older workflow exports without a root
723// readable-v2 contract; full shared-endpoint checking takes precedence.
724// Relationships a renderer declares on one junction (a Lifecycle exit bracket)
725// may share that junction's horizontal bus, the first tick from a common
726// source port and, when they end at the same state, the merged drop into it;
727// other overlaps between them count.
728// Tiny overlaps below the route rhythm
729// floor are ignored to avoid turning sub-pixel rounding into a quality debt.
730export function collectAmbiguousCorridors({
731 routedRelations,
732 minOverlapPx = 8,
733 includeSharedEndpoints = () => false,
734 includeSharedEndpointCounterflow = () => false,
735 allowShortWorkflowTrunks = false,
736}) {
737 const routed = asArray(routedRelations).map((entry, fallbackIndex) => {
738 const relation = entry?.relation;
739 if (!relation || typeof relation.from !== 'string' || typeof relation.to !== 'string') return null;
740 const points = normalizeRoutePoints(entry?.points);
741 if (points.length < 2) return null;
742 return {
743 relation,
744 relationIndex: Number.isInteger(entry.relationIndex) ? entry.relationIndex : fallbackIndex,
745 points,
746 ...(entry.sourceEndpoint === false ? { sourceEndpoint: false } : {}),
747 ...(entry.targetEndpoint === false ? { targetEndpoint: false } : {}),
748 };
749 }).filter(Boolean);
750 const hits = [];
752 for (let leftIndex = 0; leftIndex < routed.length; leftIndex += 1) {
753 const left = routed[leftIndex];
754 for (let rightIndex = leftIndex + 1; rightIndex < routed.length; rightIndex += 1) {
755 const right = routed[rightIndex];
756 const sharedBus = Boolean(left.relation.junction) && left.relation.junction === right.relation.junction;
757 const sharedEndpoint = [left.relation.from, left.relation.to].some((id) => id === right.relation.from || id === right.relation.to);
758 const counterflowOnly = sharedEndpoint && !includeSharedEndpoints(left.relation, right.relation);
759 if (counterflowOnly && !includeSharedEndpointCounterflow(left.relation, right.relation)) continue;
761 let longest = null;
762 for (let leftSegment = 0; leftSegment < left.points.length - 1; leftSegment += 1) {
763 for (let rightSegment = 0; rightSegment < right.points.length - 1; rightSegment += 1) {
764 const overlap = collinearAxisOverlap(
765 left.points[leftSegment],
766 left.points[leftSegment + 1],
767 right.points[rightSegment],
768 right.points[rightSegment + 1],
769 );
770 if (!overlap || overlap.length + 0.0001 < minOverlapPx) continue;
771 if (allowShortWorkflowTrunks && shortWorkflowTrunk(left, right, leftSegment, rightSegment, overlap.length)) continue;
772 // A multi-target bracket repeats its source tick for each target.
773 // Limit that exemption to the first segment at the same source port:
774 // a common source identity cannot waive an interior vertical overlap.
775 const sharedSourceTick = left.sourceEndpoint !== false && right.sourceEndpoint !== false
776 && left.relation.from === right.relation.from && leftSegment === 0 && rightSegment === 0
777 && Math.abs(left.points[0][0] - right.points[0][0]) < 0.0001
778 && Math.abs(left.points[0][1] - right.points[0][1]) < 0.0001;
779 if (sharedBus && (Math.abs(overlap.start[1] - overlap.end[1]) < 0.0001
780 || left.relation.to === right.relation.to || sharedSourceTick)) continue;
781 if (counterflowOnly) {
782 const leftDelta = left.points[leftSegment + 1].map((value, axis) => value - left.points[leftSegment][axis]);
783 const rightDelta = right.points[rightSegment + 1].map((value, axis) => value - right.points[rightSegment][axis]);
784 if (leftDelta[0] * rightDelta[0] + leftDelta[1] * rightDelta[1] >= 0) continue;
785 }
786 if (!longest || overlap.length > longest.overlapLength + 0.0001) {
787 longest = {
788 left,
789 right,
790 leftSegment,
791 rightSegment,
792 overlapLength: overlap.length,
793 overlapStart: overlap.start,
794 overlapEnd: overlap.end,
795 };
796 }
797 }
798 }
799 if (longest) hits.push(longest);
800 }
801 }
802 return hits;
803}
805function shortWorkflowTrunk(left, right, leftSegment, rightSegment, length) {
806 if (length > 24 + 0.0001) return false;
807 const a = left.relation, b = right.relation;
808 const variant = (edge) => edge.variant || 'default';
809 const width = (edge) => edge.width || (variant(edge) === 'emphasis' ? 1.8 : 1.4);
810 if (variant(a) !== variant(b) || width(a) !== width(b) || (a.role || '') !== (b.role || '')) return false;
811 const same = (p, q) => Math.abs(p[0] - q[0]) < 0.0001 && Math.abs(p[1] - q[1]) < 0.0001;
812 const source = left.sourceEndpoint !== false && right.sourceEndpoint !== false
813 && a.from === b.from && leftSegment === 0 && rightSegment === 0
814 && same(left.points[0], right.points[0]);
815 const target = left.targetEndpoint !== false && right.targetEndpoint !== false
816 && a.to === b.to && leftSegment === left.points.length - 2 && rightSegment === right.points.length - 2
817 && same(left.points.at(-1), right.points.at(-1));
818 if (!source && !target) return false;
819 const p = left.points[leftSegment], q = left.points[leftSegment + 1];
820 const r = right.points[rightSegment], s = right.points[rightSegment + 1];
821 return (q[0] - p[0]) * (s[0] - r[0]) + (q[1] - p[1]) * (s[1] - r[1]) > 0;
822}
824// Bundled arrow markers are 7 stroke-widths across the direction of travel.
825// Callers select the automatic routes they own; explicit junctions are preserved,
826// and relations on one junction ending at the same state share a merged drop.
827export function collectArrowheadCollisions({ routedRelations, allowShortWorkflowTrunks = false }) {
828 const incoming = new Map();
829 const hits = [];
830 for (const entry of asArray(routedRelations)) {
831 const points = normalizeRoutePoints(entry.points);
832 if (points.length < 2 || !entry.relation?.to) continue;
833 const tip = points.at(-1);
834 const previous = points.at(-2);
835 const vertical = Math.abs(tip[0] - previous[0]) < 0.0001;
836 const axis = vertical ? 0 : 1;
837 const direction = Math.sign(tip[1 - axis] - previous[1 - axis]);
838 const halfWidth = 3.5 * (entry.relation.width || (entry.relation.variant === 'emphasis' ? 1.8 : 1.5));
839 const key = `${entry.relation.to}\u0000${axis}\u0000${direction}`;
840 const siblings = incoming.get(key) || [];
841 const current = { ...entry, tip, halfWidth };
842 for (const sibling of siblings) {
843 // One junction's merged drop into a state carries a single arrowhead.
844 if (sibling.relation.junction && sibling.relation.junction === entry.relation.junction
845 && sibling.relation.to === entry.relation.to) continue;
846 if (Math.abs(tip[1 - axis] - sibling.tip[1 - axis]) > 0.0001) continue;
847 const distance = Math.abs(tip[axis] - sibling.tip[axis]);
848 const minimum = halfWidth + sibling.halfWidth;
849 if (allowShortWorkflowTrunks) {
850 const left = { ...sibling, points: normalizeRoutePoints(sibling.points) };
851 const right = { ...entry, points };
852 const overlap = collinearAxisOverlap(left.points.at(-2), left.points.at(-1), points.at(-2), tip);
853 if (overlap && shortWorkflowTrunk(left, right, left.points.length - 2, points.length - 2, overlap.length)) continue;
854 }
855 if (distance < minimum - 0.0001) hits.push({ left: sibling, right: current, distance, minimum });
856 }
857 siblings.push(current);
858 incoming.set(key, siblings);
859 }
860 return hits;
861}
863export function cleanAmbiguousCorridorProblems({
864 relations,
865 endpointIds,
866 pathFor,
867 diagramType,
868 relationCollection,
869 profile = 'standard',
870 profileIsAuthoritative = false,
871 routeHint = 'adjust route/via or channel coordinates so the relationships use separate corridors',
872 minOverlapPx = 8,
873 includeSharedEndpoints = () => false,
874 includeSharedEndpointCounterflow = () => false,
875 allowShortWorkflowTrunks = false,
876 onDiagnostic = recordDiagnostic,
877}) {
878 const severity = qualityProfileForGate(profile, profileIsAuthoritative) === 'showcase' ? 'error' : 'warning';
879 if (severity === 'warning' && !allowShortWorkflowTrunks) return [];
880 const routedRelations = collectEligibleRoutedRelations({ relations, endpointIds, pathFor });
882 return collectAmbiguousCorridors({ routedRelations, minOverlapPx, includeSharedEndpoints, includeSharedEndpointCounterflow, allowShortWorkflowTrunks }).map((hit) => {
883 const describe = ({ relation, relationIndex }) => {
884 const id = relation.id ? ` id "${relation.id}"` : '';
885 return `${relationCollection}[${relationIndex}]${id} "${relation.from}" -> "${relation.to}"`;
886 };
887 const length = Math.round(hit.overlapLength * 10) / 10;
888 const from = hit.overlapStart.map((value) => Math.round(value * 10) / 10).join(', ');
889 const to = hit.overlapEnd.map((value) => Math.round(value * 10) / 10).join(', ');
890 const hint = rePlanHint([hit.left.relation, hit.right.relation], routeHint);
891 const message = `[composition/ambiguous-corridor] ${severity === 'error' ? 'showcase' : 'standard'} ${diagramType} ${describe(hit.left)} shares a ${length}px corridor with ${describe(hit.right)} at [${from}] -> [${to}] (segments ${hit.leftSegment} and ${hit.rightSegment}; minimum ${minOverlapPx}px) — ${hint}.`;
892 onDiagnostic({
893 code: 'composition/ambiguous-corridor',
894 severity,
895 message,
896 subject: relationshipSubject(diagramType, relationCollection, hit.left.relationIndex, hit.left.relation),
897 evidence: {
898 otherRelationship: relationshipSubject(diagramType, relationCollection, hit.right.relationIndex, hit.right.relation),
899 overlapLengthPx: length,
900 minimumPx: minOverlapPx,
901 from: hit.overlapStart,
902 to: hit.overlapEnd,
903 segmentIndex: hit.leftSegment,
904 otherSegmentIndex: hit.rightSegment,
905 },
906 supportedFixes: [hint],
907 });
908 return severity === 'error' ? message : null;
909 }).filter(Boolean);
910}
912// Relationship paths may cross a structural frame, but they must not borrow a
913// frame side as a routing corridor. Rounded rectangle corners are trimmed from
914// the modeled straight sides so a short corner touch is not mistaken for a
915// border run. Any positive straight overlap beyond the numeric epsilon is a
916// hard failure in every quality profile; 16px belongs only to the separate,
917// neutral short-segment metric and is not a corridor exemption.
918export function collectBorderRuns({ routedRelations, frames }) {
919 const hits = [];
920 for (const routed of asArray(routedRelations)) {
921 const routeSegments = Array.isArray(routed?.segments)
922 ? routed.segments
923 : asArray(routed?.points).slice(0, -1).map((start, index) => ({ start, end: routed.points[index + 1] }));
924 if (!routeSegments.length) continue;
925 if (!routeSegments.every((segment) => (
926 Array.isArray(segment?.start) && segment.start.length === 2 && isFinitePoint(...segment.start)
927 && Array.isArray(segment?.end) && segment.end.length === 2 && isFinitePoint(...segment.end)
928 ))) continue;
929 for (const [frameIndex, frame] of asArray(frames).entries()) {
930 for (const border of frameBorderSegments(frame)) {
931 const overlaps = [];
932 for (let segmentIndex = 0; segmentIndex < routeSegments.length; segmentIndex += 1) {
933 const segment = routeSegments[segmentIndex];
934 const overlap = collinearAxisOverlap(
935 segment.start,
936 segment.end,
937 border.start,
938 border.end,
939 );
940 if (!overlap || overlap.length <= 0.0001) continue;
941 overlaps.push({ ...overlap, segmentIndex });
942 }
943 if (!overlaps.length) continue;
944 const merged = mergeBorderOverlaps(overlaps, border);
945 const longest = [...merged].sort((left, right) => right.length - left.length || left.low - right.low)[0];
946 hits.push({
947 ...routed,
948 frame,
949 frameIndex,
950 side: border.side,
951 segmentIndex: overlaps.reduce((min, overlap) => Math.min(min, overlap.segmentIndex), Infinity),
952 overlapLength: merged.reduce((total, overlap) => total + overlap.length, 0),
953 overlapStart: longest.start,
954 overlapEnd: longest.end,
955 });
956 }
957 }
958 }
959 return hits;
960}
962export function cleanBorderRunProblems({
963 relations,
964 endpointIds,
965 frames,
966 pathFor,
967 diagramType,
968 relationCollection,
969 profile,
970 profileIsAuthoritative = false,
971 routeHint = 'adjust route/via or channel coordinates so the relationship crosses the frame perpendicularly through a clear opening'
972}) {
973 if (!qualityProfileForGate(profile, profileIsAuthoritative)) return [];
974 const routedRelations = collectEligibleRoutedRelations({ relations, endpointIds, pathFor });
975 return collectBorderRuns({ routedRelations, frames }).map((hit) => {
976 const relation = hit.relation || {};
977 const relationId = relation.id ? ` id "${relation.id}"` : '';
978 const frameKind = hit.frame?.kind || hit.frame?.shape || 'frame';
979 const frameIdentity = hit.frame?.label || hit.frame?.id || hit.frameIndex;
980 const length = Math.round(hit.overlapLength * 10) / 10;
981 const from = hit.overlapStart.map((value) => Math.round(value * 10) / 10).join(', ');
982 const to = hit.overlapEnd.map((value) => Math.round(value * 10) / 10).join(', ');
983 const hint = rePlanHint([relation], routeHint);
984 const message = `[composition/container-border-run] ${diagramType} ${relationCollection}[${hit.relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" follows ${frameKind} "${frameIdentity}" ${hit.side} border for ${length}px on segment ${hit.segmentIndex} [${from}] -> [${to}] — ${hint}.`;
985 recordDiagnostic({
986 code: 'composition/container-border-run',
987 severity: 'error',
988 message,
989 subject: relationshipSubject(diagramType, relationCollection, hit.relationIndex, relation),
990 evidence: {
991 frameKind,
992 frameId: hit.frame?.id,
993 frameLabel: hit.frame?.label,
994 side: hit.side,
995 segmentIndex: hit.segmentIndex,
996 overlapLengthPx: length,
997 from: hit.overlapStart,
998 to: hit.overlapEnd,
999 },
1000 supportedFixes: [hint],
1001 });
1002 return message;
1003 });
1004}
1006export function routeBudgetMetrics({
1007 routedRelations,
1008 bendsPerRelationship = 2,
1009 stretch = 1.35,
1010 segmentPx = 16,
1011 microSegmentPx = 8,
1012}) {
1013 let maxBends = 0;
1014 let routesOverSuggestedBends = 0;
1015 let maxStretch = null;
1016 let routesOverSuggestedStretch = 0;
1017 let minSegmentPx = null;
1018 let minInteriorSegmentPx = null;
1019 let shortSegmentCount = 0;
1020 let shortEndpointSegmentCount = 0;
1021 let shortInteriorSegmentCount = 0;
1022 let microSegmentCount = 0;
1024 for (const routed of asArray(routedRelations)) {
1025 const points = normalizeRoutePoints(routed?.points);
1026 if (points.length < 2) continue;
1027 const bends = Math.max(0, points.length - 2);
1028 maxBends = Math.max(maxBends, bends);
1029 if (bends > bendsPerRelationship) routesOverSuggestedBends += 1;
1031 let routeLength = 0;
1032 for (let index = 0; index < points.length - 1; index += 1) {
1033 const length = Math.abs(points[index + 1][0] - points[index][0]) + Math.abs(points[index + 1][1] - points[index][1]);
1034 if (length <= 0.0001) continue;
1035 const position = segmentPosition(index, points.length - 1);
1036 routeLength += length;
1037 minSegmentPx = minSegmentPx == null ? length : Math.min(minSegmentPx, length);
1038 if (position === 'interior') {
1039 minInteriorSegmentPx = minInteriorSegmentPx == null ? length : Math.min(minInteriorSegmentPx, length);
1040 }
1041 if (length < segmentPx) {
1042 shortSegmentCount += 1;
1043 if (position === 'interior') shortInteriorSegmentCount += 1;
1044 else shortEndpointSegmentCount += 1;
1045 }
1046 if (length < microSegmentPx) microSegmentCount += 1;
1047 }
1048 const direct = Math.abs(points.at(-1)[0] - points[0][0]) + Math.abs(points.at(-1)[1] - points[0][1]);
1049 if (direct > 0.0001) {
1050 const routeStretch = routeLength / direct;
1051 maxStretch = maxStretch == null ? routeStretch : Math.max(maxStretch, routeStretch);
1052 if (routeStretch > stretch + 0.0001) routesOverSuggestedStretch += 1;
1053 }
1054 }
1056 return {
1057 maxBends,
1058 routesOverSuggestedBends,
1059 maxStretch,
1060 routesOverSuggestedStretch,
1061 minSegmentPx,
1062 minInteriorSegmentPx,
1063 shortSegmentCount,
1064 shortEndpointSegmentCount,
1065 shortInteriorSegmentCount,
1066 microSegmentCount,
1067 };
1068}
1070export function collectRouteRhythmIssues({
1071 routedRelations,
1072 interiorSegmentPx = 16,
1073 microSegmentPx = 8,
1074}) {
1075 const issues = [];
1076 for (const [fallbackIndex, routed] of asArray(routedRelations).entries()) {
1077 const points = normalizeRoutePoints(routed?.points);
1078 if (points.length < 2) continue;
1079 for (let segmentIndex = 0; segmentIndex < points.length - 1; segmentIndex += 1) {
1080 const start = points[segmentIndex];
1081 const end = points[segmentIndex + 1];
1082 const length = Math.abs(end[0] - start[0]) + Math.abs(end[1] - start[1]);
1083 if (length <= 0.0001) continue;
1084 const position = segmentPosition(segmentIndex, points.length - 1);
1085 const code = length < microSegmentPx - 0.0001
1086 ? 'composition/micro-segment'
1087 : position === 'interior' && length < interiorSegmentPx - 0.0001
1088 ? 'composition/short-interior-segment'
1089 : null;
1090 if (!code) continue;
1091 issues.push({
1092 code,
1093 relation: routed.relation,
1094 relationIndex: Number.isInteger(routed.relationIndex) ? routed.relationIndex : fallbackIndex,
1095 segmentIndex,
1096 position,
1097 length,
1098 start,
1099 end,
1100 });
1101 }
1102 }
1103 return issues;
1104}
1106export function cleanRouteRhythmProblems({
1107 relations,
1108 endpointIds,
1109 pathFor,
1110 diagramType,
1111 relationCollection,
1112 profile,
1113 profileIsAuthoritative = false,
1114 routeHint = 'move the channel/via point to remove the cramped turn or give the route more corridor space',
1115 interiorSegmentPx = 16,
1116 microSegmentPx = 8,
1117}) {
1118 if (qualityProfileForGate(profile, profileIsAuthoritative) !== 'showcase') return [];
1119 const routedRelations = collectEligibleRoutedRelations({ relations, endpointIds, pathFor });
1120 return collectRouteRhythmIssues({ routedRelations, interiorSegmentPx, microSegmentPx }).map((hit) => {
1121 const relation = hit.relation || {};
1122 const relationId = relation.id ? ` id "${relation.id}"` : '';
1123 const length = Math.round(hit.length * 10) / 10;
1124 const from = hit.start.map((value) => Math.round(value * 10) / 10).join(', ');
1125 const to = hit.end.map((value) => Math.round(value * 10) / 10).join(', ');
1126 const rule = hit.code === 'composition/micro-segment'
1127 ? `is below the ${microSegmentPx}px micro-segment floor`
1128 : `is below the ${interiorSegmentPx}px interior-segment floor`;
1129 const hint = rePlanHint([relation], routeHint);
1130 const message = `[${hit.code}] showcase ${diagramType} ${relationCollection}[${hit.relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" has a ${length}px ${hit.position} segment ${hit.segmentIndex} [${from}] -> [${to}] that ${rule} — ${hint}.`;
1131 recordDiagnostic({
1132 code: hit.code,
1133 severity: 'error',
1134 message,
1135 subject: relationshipSubject(diagramType, relationCollection, hit.relationIndex, relation),
1136 evidence: {
1137 segmentIndex: hit.segmentIndex,
1138 position: hit.position,
1139 lengthPx: length,
1140 minimumPx: hit.code === 'composition/micro-segment' ? microSegmentPx : interiorSegmentPx,
1141 from: hit.start,
1142 to: hit.end,
1143 },
1144 supportedFixes: [hint],
1145 });
1146 return message;
1147 });
1148}
1150export function cleanLabelRouteClearanceProblems({
1151 relations,
1152 labels,
1153 endpointIds,
1154 pathFor,
1155 diagramType,
1156 relationCollection,
1157 profile,
1158 profileIsAuthoritative = false,
1159 threshold = 4,
1160 routeHint = 'adjust labelAt, labelDx, labelDy, or labelSegment; otherwise adjust the other relationship route/via/channel',
1161}) {
1162 if (qualityProfileForGate(profile, profileIsAuthoritative) !== 'showcase') return [];
1163 const routedRelations = collectEligibleRoutedRelations({ relations, endpointIds, pathFor });
1164 return collectLabelRouteClearance({ labels, routedRelations, threshold }).map((hit) => {
1165 const describe = (relation, relationIndex) => {
1166 const relationId = relation?.id ? ` id "${relation.id}"` : '';
1167 const relationLabel = relation?.label ? ` label "${relation.label}"` : '';
1168 return `${relationCollection}[${relationIndex}]${relationId} "${relation?.from}" -> "${relation?.to}"${relationLabel}`;
1169 };
1170 const clearance = Math.round(hit.clearance * 10) / 10;
1171 const from = hit.start.map((value) => Math.round(value * 10) / 10).join(', ');
1172 const to = hit.end.map((value) => Math.round(value * 10) / 10).join(', ');
1173 const hint = rePlanHint([hit.labelRelation, hit.otherRelation], routeHint);
1174 const message = `[composition/label-route-clearance] showcase ${diagramType} label "${hit.label?.label || hit.labelRelation?.label || ''}" on ${describe(hit.labelRelation, hit.labelRelationIndex)} is ${clearance}px from ${describe(hit.otherRelation, hit.otherRelationIndex)} segment ${hit.segmentIndex} [${from}] -> [${to}] (label rect ${formatRect(hit.rect)}; minimum ${threshold}px) — ${hint}.`;
1175 recordDiagnostic({
1176 code: 'composition/label-route-clearance',
1177 severity: 'error',
1178 message,
1179 subject: relationshipSubject(diagramType, relationCollection, hit.labelRelationIndex, hit.labelRelation),
1180 evidence: {
1181 label: hit.label?.label || hit.labelRelation?.label || '',
1182 otherRelationship: relationshipSubject(diagramType, relationCollection, hit.otherRelationIndex, hit.otherRelation),
1183 segmentIndex: hit.segmentIndex,
1184 clearancePx: clearance,
1185 minimumPx: threshold,
1186 labelRect: hit.rect,
1187 from: hit.start,
1188 to: hit.end,
1189 },
1190 supportedFixes: [hint],
1191 });
1192 return message;
1193 });
1194}
1196// How far [start, start + size) leaves [0, extent), per end of one axis. This
1197// is the single definition of "inside the canvas" that both the containment
1198// rule and the repair hints measure against; an unknown extent bounds nothing.
1199function axisCanvasOverflow(start, size, extent, origin = 0) {
1200 if (!Number.isFinite(extent)) return { start: 0, end: 0 };
1201 return { start: origin - start, end: start + size - (origin + extent) };
1202}
1204// THE CANVAS CONTAINMENT RATIONALE (referenced from the other call sites).
1205//
1206// The SVG canvas clips whatever leaves the viewBox, so an edge label that
1207// overhangs an edge ships as truncated text while every post-render check on
1208// the emitted markup still passes: clipped text is still well-formed markup.
1209// Renderers with a fixed canvas already bound their nodes, lanes, and legends
1210// against it; edge label rects were the exception.
1211//
1212// Not applied to readable-v2 workflows: that compiler grows its canvas around
1213// pinned label rects and rejects an authored viewBox that cannot hold the
1214// result, so the only gap growth cannot close is the origin its own rule
1215// already guards. Architecture's auto canvas grows the same way, which leaves
1216// this rule reporting authored viewBoxes and the origin side.
1217//
1218// Showcase only: a standard document authored before the rule exists may
1219// overhang by a few pixels, and failing it there would break compatibility
1220// instead of repairing a diagram.
1221export function collectLabelCanvasOverflow({ labels, viewBox, tolerance = 0.5 }) {
1222 // Renderers author origin-zero canvases (meta.viewBox is [width, height] by
1223 // schema), but `check` re-measures foreign artifacts whose SVG viewBox may
1224 // carry a legal non-zero min-x/min-y; those pass all four numbers.
1225 const box = asArray(viewBox);
1226 const [originX, originY, canvasWidth, canvasHeight] = box.length === 4 ? box : [0, 0, box[0], box[1]];
1227 if (!isFinitePoint(originX, originY, canvasWidth, canvasHeight)) return [];
1228 const hits = [];
1229 for (const [fallbackIndex, label] of asArray(labels).entries()) {
1230 const rect = label?.rect || label;
1231 if (!rect || !isFinitePoint(rect.x, rect.y, rect.width, rect.height)) continue;
1232 // `check` parses foreign markup, so a malformed negative-size rect is
1233 // skipped like the other label collectors do — its flipped interval would
1234 // otherwise read as contained.
1235 if (rect.width < 0 || rect.height < 0) continue;
1236 const horizontal = axisCanvasOverflow(rect.x, rect.width, canvasWidth, originX);
1237 const vertical = axisCanvasOverflow(rect.y, rect.height, canvasHeight, originY);
1238 const overflow = {
1239 left: horizontal.start,
1240 right: horizontal.end,
1241 top: vertical.start,
1242 bottom: vertical.end,
1243 };
1244 const sides = Object.keys(overflow).filter((side) => overflow[side] > tolerance);
1245 if (!sides.length) continue;
1246 hits.push({
1247 label,
1248 relation: label?.relation,
1249 relationIndex: Number.isInteger(label?.relationIndex) ? label.relationIndex : fallbackIndex,
1250 rect,
1251 viewBox: [canvasWidth, canvasHeight],
1252 viewBoxOrigin: [originX, originY],
1253 sides,
1254 overflowPx: Object.fromEntries(sides.map((side) => [side, Math.round(overflow[side] * 10) / 10])),
1255 tolerance,
1256 });
1257 }
1258 return hits;
1259}
1261export function describeLabelCanvasOverflow(hit) {
1262 return hit.sides.map((side) => `${side} edge by ${hit.overflowPx[side]}px`).join(' and ');
1263}
1265export function cleanLabelCanvasContainmentProblems({
1266 labels,
1267 viewBox,
1268 diagramType,
1269 relationCollection,
1270 profile,
1271 profileIsAuthoritative = false,
1272 routeHint = 'adjust labelAt, labelDx, labelDy, or labelSegment; otherwise enlarge meta.viewBox',
1273 // Label widths are estimated from the text, not measured, so sub-pixel
1274 // overhang is rounding noise rather than a visible truncation.
1275 tolerance = 0.5,
1276}) {
1277 if (qualityProfileForGate(profile, profileIsAuthoritative) !== 'showcase') return [];
1278 return collectLabelCanvasOverflow({ labels, viewBox, tolerance }).map((hit) => {
1279 const relation = hit.relation;
1280 const relationId = relation?.id ? ` id "${relation.id}"` : '';
1281 const labelText = hit.label?.label || relation?.label || '';
1282 const hint = rePlanHint([relation], routeHint);
1283 const message = `[composition/label-canvas-containment] showcase ${diagramType} label "${labelText}" on ${relationCollection}[${hit.relationIndex}]${relationId} "${relation?.from}" -> "${relation?.to}" extends past the ${describeLabelCanvasOverflow(hit)} (label rect ${formatRect(hit.rect)}; viewBox ${hit.viewBox[0]}x${hit.viewBox[1]}) — ${hint}.`;
1284 recordDiagnostic({
1285 code: 'composition/label-canvas-containment',
1286 severity: 'error',
1287 message,
1288 subject: relationshipSubject(diagramType, relationCollection, hit.relationIndex, relation),
1289 evidence: {
1290 label: labelText,
1291 labelRect: { x: hit.rect.x, y: hit.rect.y, width: hit.rect.width, height: hit.rect.height },
1292 viewBox: hit.viewBox,
1293 overflowPx: hit.overflowPx,
1294 tolerancePx: hit.tolerance,
1295 },
1296 supportedFixes: [hint],
1297 });
1298 return message;
1299 });
1300}
1302function qualityProfileForGate(profile, profileIsAuthoritative) {
1303 return profileIsAuthoritative
1304 ? profile
1305 : process.env.ARCHIFY_QUALITY_PROFILE || profile;
1306}
1308function collectEligibleRoutedRelations({ relations, endpointIds, pathFor }) {
1309 return asArray(relations).map((relation, relationIndex) => {
1310 if (!relation || typeof relation.from !== 'string' || typeof relation.to !== 'string') return null;
1311 if (endpointIds && (!endpointIds.has(relation.from) || !endpointIds.has(relation.to))) return null;
1312 return { relation, relationIndex, points: pathFor(relation)?.points };
1313 }).filter(Boolean);
1314}
1316function segmentPosition(index, segmentCount) {
1317 if (index === 0) return 'source-stub';
1318 if (index === segmentCount - 1) return 'target-stub';
1319 return 'interior';
1320}
1322// Normalizing a route is pure, and the same route array is normalized again by
1323// every predicate that inspects it. Keyed by the array itself, so a rebuilt
1324// route simply gets a new entry. The result's outer array is frozen. Callers
1325// must also treat input arrays and their coordinate pairs as immutable, since
1326// edits in place cannot invalidate this identity-based cache.
1327const NORMALIZED_ROUTE_POINTS = new WeakMap();
1329// Assembling a route from an anchor, corridor points and an anchor is the same
1330// normalization without the intermediate array, and the result is seeded in the
1331// cache so later predicates do not normalize it again.
1332export function joinRoutePoints(start, via, end) {
1333 const normalized = [];
1334 const accept = (point) => {
1335 if (!Array.isArray(point) || point.length !== 2 || !isFinitePoint(point[0], point[1])) return;
1336 const previous = normalized.at(-1);
1337 if (previous
1338 && Math.abs(point[0] - previous[0]) <= 0.0001
1339 && Math.abs(point[1] - previous[1]) <= 0.0001) return;
1340 while (normalized.length >= 2 && collinearForward(normalized.at(-2), normalized.at(-1), point)) normalized.pop();
1341 normalized.push(point);
1342 };
1343 accept(start);
1344 for (const point of Array.isArray(via) ? via : []) accept(point);
1345 accept(end);
1346 Object.freeze(normalized);
1347 NORMALIZED_ROUTE_POINTS.set(normalized, normalized);
1348 return normalized;
1349}
1351export function normalizeRoutePoints(points) {
1352 if (Array.isArray(points)) {
1353 const cached = NORMALIZED_ROUTE_POINTS.get(points);
1354 if (cached) return cached;
1355 }
1356 const normalized = [];
1357 for (const point of Array.isArray(points) ? points : []) {
1358 if (!Array.isArray(point) || point.length !== 2 || !isFinitePoint(point[0], point[1])) continue;
1359 const previous = normalized.at(-1);
1360 if (previous
1361 && Math.abs(point[0] - previous[0]) <= 0.0001
1362 && Math.abs(point[1] - previous[1]) <= 0.0001) continue;
1363 while (normalized.length >= 2 && collinearForward(normalized.at(-2), normalized.at(-1), point)) normalized.pop();
1364 normalized.push(point);
1365 }
1366 if (Array.isArray(points)) {
1367 Object.freeze(normalized);
1368 NORMALIZED_ROUTE_POINTS.set(points, normalized);
1369 }
1370 return normalized;
1371}
1373function pointRectDistance(point, rect) {
1374 const dx = Math.max(rect.x - point[0], 0, point[0] - (rect.x + rect.width));
1375 const dy = Math.max(rect.y - point[1], 0, point[1] - (rect.y + rect.height));
1376 return Math.hypot(dx, dy);
1377}
1379function pointSegmentDistanceXY(px, py, start, end) {
1380 const dx = end[0] - start[0];
1381 const dy = end[1] - start[1];
1382 const lengthSquared = dx * dx + dy * dy;
1383 if (lengthSquared <= 0.0000001) return Math.hypot(px - start[0], py - start[1]);
1384 const t = Math.max(0, Math.min(1, ((px - start[0]) * dx + (py - start[1]) * dy) / lengthSquared));
1385 return Math.hypot(px - (start[0] + t * dx), py - (start[1] + t * dy));
1386}
1388function pointSegmentDistance(point, start, end) {
1389 return pointSegmentDistanceXY(point[0], point[1], start, end);
1390}
1392function collinearForward(a, b, c) {
1393 if (Math.abs(crossProduct(a, b, c)) > 0.0001) return false;
1394 return (b[0] - a[0]) * (c[0] - b[0]) + (b[1] - a[1]) * (c[1] - b[1]) >= -0.0001;
1395}
1397export function frameBorderSegments(frame) {
1398 if (!frame || typeof frame !== 'object') return [];
1399 if (frame.shape === 'line') {
1400 const start = frame.start || [frame.x1, frame.y1];
1401 const end = frame.end || [frame.x2, frame.y2];
1402 return isFinitePoint(...start, ...end) ? [{ side: 'line', start, end }] : [];
1403 }
1404 if (!isFinitePoint(frame.x, frame.y, frame.width, frame.height) || frame.width <= 0 || frame.height <= 0) return [];
1405 const radius = Math.max(0, Math.min(Number(frame.radius) || 0, frame.width / 2, frame.height / 2));
1406 const left = frame.x;
1407 const right = frame.x + frame.width;
1408 const top = frame.y;
1409 const bottom = frame.y + frame.height;
1410 return [
1411 { side: 'top', start: [left + radius, top], end: [right - radius, top] },
1412 { side: 'right', start: [right, top + radius], end: [right, bottom - radius] },
1413 { side: 'bottom', start: [right - radius, bottom], end: [left + radius, bottom] },
1414 { side: 'left', start: [left, bottom - radius], end: [left, top + radius] },
1415 ].filter(({ start, end }) => Math.hypot(end[0] - start[0], end[1] - start[1]) > 0.0001);
1416}
1418function mergeBorderOverlaps(overlaps, border) {
1419 const horizontal = Math.abs(border.start[1] - border.end[1]) <= 0.0001;
1420 const axis = horizontal ? 0 : 1;
1421 const fixed = horizontal ? border.start[1] : border.start[0];
1422 const sorted = overlaps.map((overlap) => ({
1423 low: Math.min(overlap.start[axis], overlap.end[axis]),
1424 high: Math.max(overlap.start[axis], overlap.end[axis]),
1425 })).sort((left, right) => left.low - right.low || left.high - right.high);
1426 const merged = [];
1427 for (const interval of sorted) {
1428 const previous = merged.at(-1);
1429 if (previous && interval.low <= previous.high + 0.0001) previous.high = Math.max(previous.high, interval.high);
1430 else merged.push({ ...interval });
1431 }
1432 return merged.map((interval) => ({
1433 ...interval,
1434 length: interval.high - interval.low,
1435 start: horizontal ? [interval.low, fixed] : [fixed, interval.low],
1436 end: horizontal ? [interval.high, fixed] : [fixed, interval.high],
1437 }));
1438}
1440function collinearAxisOverlap(a, b, c, d) {
1441 const epsilon = 0.0001;
1442 const horizontal = Math.abs(a[1] - b[1]) <= epsilon
1443 && Math.abs(c[1] - d[1]) <= epsilon
1444 && Math.abs(a[1] - c[1]) <= epsilon;
1445 const vertical = Math.abs(a[0] - b[0]) <= epsilon
1446 && Math.abs(c[0] - d[0]) <= epsilon
1447 && Math.abs(a[0] - c[0]) <= epsilon;
1448 if (!horizontal && !vertical) return null;
1449 const axis = horizontal ? 0 : 1;
1450 const low = Math.max(Math.min(a[axis], b[axis]), Math.min(c[axis], d[axis]));
1451 const high = Math.min(Math.max(a[axis], b[axis]), Math.max(c[axis], d[axis]));
1452 if (high - low <= epsilon) return null;
1453 const fixed = horizontal ? a[1] : a[0];
1454 return {
1455 length: high - low,
1456 start: horizontal ? [low, fixed] : [fixed, low],
1457 end: horizontal ? [high, fixed] : [fixed, high],
1458 };
1459}
1461export function properSegmentIntersection(a, b, c, d) {
1462 const abC = crossProduct(a, b, c);
1463 const abD = crossProduct(a, b, d);
1464 const cdA = crossProduct(c, d, a);
1465 const cdB = crossProduct(c, d, b);
1466 const epsilon = 0.0001;
1467 const opposite = (left, right) => (left > epsilon && right < -epsilon) || (left < -epsilon && right > epsilon);
1468 if (!opposite(abC, abD) || !opposite(cdA, cdB)) return null;
1470 const denominator = (a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0]);
1471 if (Math.abs(denominator) < epsilon) return null;
1472 const ab = a[0] * b[1] - a[1] * b[0];
1473 const cd = c[0] * d[1] - c[1] * d[0];
1474 return [
1475 (ab * (c[0] - d[0]) - (a[0] - b[0]) * cd) / denominator,
1476 (ab * (c[1] - d[1]) - (a[1] - b[1]) * cd) / denominator
1477 ];
1478}
1480function crossProduct(a, b, c) {
1481 return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
1482}
1484function pointInBox(point, box) {
1485 return point[0] >= box.x1 && point[0] <= box.x2 && point[1] >= box.y1 && point[1] <= box.y2;
1486}
1488function segmentsIntersect(a, b, c, d) {
1489 const o1 = orientation(a, b, c);
1490 const o2 = orientation(a, b, d);
1491 const o3 = orientation(c, d, a);
1492 const o4 = orientation(c, d, b);
1494 if (o1 === 0 && onSegment(a, c, b)) return true;
1495 if (o2 === 0 && onSegment(a, d, b)) return true;
1496 if (o3 === 0 && onSegment(c, a, d)) return true;
1497 if (o4 === 0 && onSegment(c, b, d)) return true;
1499 return o1 !== o2 && o3 !== o4;
1500}
1502function orientation(a, b, c) {
1503 const value = (b[1] - a[1]) * (c[0] - b[0]) - (b[0] - a[0]) * (c[1] - b[1]);
1504 if (Math.abs(value) < 0.0001) return 0;
1505 return value > 0 ? 1 : 2;
1506}
1508function onSegment(a, b, c) {
1509 return (
1510 b[0] <= Math.max(a[0], c[0]) &&
1511 b[0] >= Math.min(a[0], c[0]) &&
1512 b[1] <= Math.max(a[1], c[1]) &&
1513 b[1] >= Math.min(a[1], c[1])
1514 );
1515}
1517export function anchor(rect, side) {
1518 switch (side) {
1519 case 'left': return [rect.x, rect.cy];
1520 case 'right': return [rect.x + rect.width, rect.cy];
1521 case 'top': return [rect.cx, rect.y];
1522 case 'bottom': return [rect.cx, rect.y + rect.height];
1523 default:
1524 return [rect.x + rect.width, rect.cy];
1525 }
1526}
1528export function portHasCornerClearance(rect, side, point) {
1529 if (side === 'left' || side === 'right') {
1530 const inset = Math.min(16, rect.height / 2);
1531 return point[1] >= rect.y + inset && point[1] <= rect.y + rect.height - inset;
1532 }
1533 if (side === 'top' || side === 'bottom') {
1534 const inset = Math.min(16, rect.width / 2);
1535 return point[0] >= rect.x + inset && point[0] <= rect.x + rect.width - inset;
1536 }
1537 return false;
1538}
1541// Reuse the same bounded alignment for facing automatic ports; callers own
1542// obstacle and occupied-port checks for their renderer. Spread slots stay fixed.
1543export function alignAutomaticFacingPorts(conn, from, to, start, end, fromSide, toSide, ports, { accept } = {}) {
1544 const hasExplicitGeometry = (
1545 conn.via
1546 || (conn.route && conn.route !== 'auto')
1547 || conn.channelX !== undefined
1548 || conn.channelY !== undefined
1549 || conn.labelAt
1550 );
1551 const horizontallyFacing = (
1552 (fromSide === 'right' && toSide === 'left')
1553 || (fromSide === 'left' && toSide === 'right')
1554 );
1555 const verticallyFacing = (
1556 (fromSide === 'bottom' && toSide === 'top')
1557 || (fromSide === 'top' && toSide === 'bottom')
1558 );
1559 if (hasExplicitGeometry || (!horizontallyFacing && !verticallyFacing)) return { start, end };
1561 const fromSpread = Boolean(ports?.from);
1562 const toSpread = Boolean(ports?.to);
1563 if (fromSpread && toSpread) return { start, end };
1564 const hasExplicitSides = (
1565 (conn.fromSide && conn.fromSide !== 'auto')
1566 || (conn.toSide && conn.toSide !== 'auto')
1567 );
1568 if (!fromSpread && !toSpread && hasExplicitSides) return { start, end };
1570 const alignmentDelta = horizontallyFacing
1571 ? Math.abs(start[1] - end[1])
1572 : Math.abs(start[0] - end[0]);
1573 if (alignmentDelta >= 16) return { start, end };
1575 // Keep the shared endpoint's distinct spread slot and move only the
1576 // relationship's unshared endpoint onto that axis. With no spread endpoint,
1577 // retain the existing least-movement choice between the two facing sides.
1578 // If both endpoints are shared, preserve the outside bridge so no competing
1579 // port is silently collapsed.
1580 const alignEndToStart = horizontallyFacing
1581 ? { start, end: [end[0], start[1]] }
1582 : { start, end: [start[0], end[1]] };
1583 const alignStartToEnd = horizontallyFacing
1584 ? { start: [start[0], end[1]], end }
1585 : { start: [end[0], start[1]], end };
1586 const candidates = fromSpread
1587 ? [alignEndToStart]
1588 : toSpread
1589 ? [alignStartToEnd]
1590 : [alignEndToStart, alignStartToEnd];
1591 for (const candidate of candidates) {
1592 const points = [candidate.start, candidate.end];
1593 if (portHasCornerClearance(from, fromSide, candidate.start)
1594 && portHasCornerClearance(to, toSide, candidate.end)
1595 && routeHonorsEndpointSides(points, fromSide, toSide)
1596 && (typeof accept !== 'function' || accept(points))) {
1597 return candidate;
1598 }
1599 }
1600 return { start, end };
1601}
1604const PORT_OUTWARD_VECTOR = {
1605 left: [-1, 0],
1606 right: [1, 0],
1607 top: [0, -1],
1608 bottom: [0, 1],
1609};
1611// Automatic port spreading can put otherwise parallel anchors only a few
1612// pixels apart. A conventional midpoint dogleg then violates the renderer's
1613// own 8px/16px route-rhythm floors. Return a full outside-channel route when
1614// that happens, or null when the normal automatic route remains appropriate.
1615export function automaticPortRhythmBridge(
1616 start,
1617 end,
1618 fromSide,
1619 toSide,
1620 { endpointStubPx = 24, interiorSegmentPx = 16, accept } = {},
1621) {
1622 if (!Array.isArray(start) || !Array.isArray(end)
1623 || start.length !== 2 || end.length !== 2
1624 || !isFinitePoint(...start, ...end)) return null;
1625 const fromVector = PORT_OUTWARD_VECTOR[fromSide];
1626 const toVector = PORT_OUTWARD_VECTOR[toSide];
1627 if (!fromVector || !toVector) return null;
1629 const opposedFacingGap = (
1630 (fromSide === 'right' && toSide === 'left' && end[0] > start[0])
1631 || (fromSide === 'left' && toSide === 'right' && start[0] > end[0])
1632 ) ? Math.abs(end[0] - start[0]) : (
1633 (fromSide === 'bottom' && toSide === 'top' && end[1] > start[1])
1634 || (fromSide === 'top' && toSide === 'bottom' && start[1] > end[1])
1635 ) ? Math.abs(end[1] - start[1]) : null;
1636 const boundedStubPx = opposedFacingGap != null
1637 && opposedFacingGap - endpointStubPx * 2 < interiorSegmentPx
1638 ? Math.max(8, Math.min(endpointStubPx, (opposedFacingGap - interiorSegmentPx) / 2))
1639 : null;
1640 const stubDistances = [endpointStubPx];
1641 if (boundedStubPx != null && boundedStubPx >= 8 && boundedStubPx !== endpointStubPx) {
1642 stubDistances.push(boundedStubPx);
1643 }
1644 const candidates = [];
1645 const verticalSides = new Set(['top', 'bottom']);
1646 const horizontalSides = new Set(['left', 'right']);
1648 for (const stubPx of stubDistances) {
1649 const startStub = [
1650 start[0] + fromVector[0] * stubPx,
1651 start[1] + fromVector[1] * stubPx,
1652 ];
1653 const endStub = [
1654 end[0] + toVector[0] * stubPx,
1655 end[1] + toVector[1] * stubPx,
1656 ];
1657 if (verticalSides.has(fromSide) && verticalSides.has(toSide)
1658 && Math.abs(start[0] - end[0]) < interiorSegmentPx) {
1659 for (const channelX of [
1660 Math.max(start[0], end[0]) + interiorSegmentPx,
1661 Math.min(start[0], end[0]) - interiorSegmentPx,
1662 ]) {
1663 candidates.push([
1664 start,
1665 startStub,
1666 [channelX, startStub[1]],
1667 [channelX, endStub[1]],
1668 endStub,
1669 end,
1670 ]);
1671 }
1672 }
1673 if (horizontalSides.has(fromSide) && horizontalSides.has(toSide)
1674 && Math.abs(start[1] - end[1]) < interiorSegmentPx) {
1675 for (const channelY of [
1676 Math.max(start[1], end[1]) + interiorSegmentPx,
1677 Math.min(start[1], end[1]) - interiorSegmentPx,
1678 ]) {
1679 candidates.push([
1680 start,
1681 startStub,
1682 [startStub[0], channelY],
1683 [endStub[0], channelY],
1684 endStub,
1685 end,
1686 ]);
1687 }
1688 }
1689 }
1691 return candidates
1692 .map((points) => normalizeRoutePoints(points))
1693 .find((points) => (
1694 routeHonorsEndpointSides(points, fromSide, toSide)
1695 && collectRouteRhythmIssues({ routedRelations: [{ points }], interiorSegmentPx }).length === 0
1696 && (typeof accept !== 'function' || accept(points))
1697 )) || null;
1698}
1700// Keep conservative auto-routed fan-out/fan-in relationships visually
1701// distinct without changing authored route controls. The returned map only
1702// contains endpoints that belong to a shared automatic midpoint anchor.
1703export function automaticPortSpread(relations, boxes, { gutter = 16, maxSpacing = 14, sideFor, spacingFor } = {}) {
1704 const groups = new Map();
1705 const spread = new Map();
1707 const add = (relation, endpoint, rect, side, counterpart) => {
1708 const key = `${rect.id}\u0000${side}`;
1709 const items = groups.get(key) || [];
1710 items.push({ relation, endpoint, rect, side, counterpart });
1711 groups.set(key, items);
1712 };
1714 for (const relation of asArray(relations)) {
1715 if (!relation || (relation.route && relation.route !== 'auto')) continue;
1716 if (relation.via || relation.channelX !== undefined || relation.channelY !== undefined || relation.labelAt) continue;
1717 const from = boxes.get(relation.from);
1718 const to = boxes.get(relation.to);
1719 if (!from || !to) continue;
1720 const fromSide = chosenSide(
1721 relation.fromSide,
1722 sideFor?.(relation, 'source') || defaultFromSide(from, to),
1723 );
1724 const toSide = chosenSide(
1725 relation.toSide,
1726 sideFor?.(relation, 'target') || defaultToSide(from, to),
1727 );
1728 add(relation, 'from', from, fromSide, to);
1729 add(relation, 'to', to, toSide, from);
1730 }
1732 for (const items of groups.values()) {
1733 if (items.length < 2) continue;
1734 const verticalSide = items[0].side === 'left' || items[0].side === 'right';
1735 items.sort((a, b) => {
1736 const aCoordinate = verticalSide ? a.counterpart.cy : a.counterpart.cx;
1737 const bCoordinate = verticalSide ? b.counterpart.cy : b.counterpart.cx;
1738 if (aCoordinate !== bCoordinate) return aCoordinate - bCoordinate;
1739 const aKey = `${a.relation.id || ''}\u0000${a.relation.from}\u0000${a.relation.to}\u0000${a.relation.label || ''}`;
1740 const bKey = `${b.relation.id || ''}\u0000${b.relation.from}\u0000${b.relation.to}\u0000${b.relation.label || ''}`;
1741 return aKey < bKey ? -1 : aKey > bKey ? 1 : 0;
1742 });
1744 const extent = verticalSide ? items[0].rect.height : items[0].rect.width;
1745 const usable = Math.max(0, extent - gutter * 2);
1746 const spacing = Math.min(maxSpacing, usable / (items.length - 1));
1747 if (!(spacing > 0)) continue;
1749 // Width-aware callers reserve the whole group together. Moving a single
1750 // port around the legacy 14px slots can wrongly report a full side while
1751 // its still-unrouted neighbours could have fitted farther apart.
1752 let offsets;
1753 if (spacingFor) {
1754 const gaps = items.slice(1).map((item, index) => Math.max(maxSpacing,
1755 spacingFor(items[index].relation, item.relation)));
1756 const span = gaps.reduce((sum, gap) => sum + gap, 0);
1757 if (span <= usable && gaps.some((gap) => gap > maxSpacing)) {
1758 let offset = -span / 2;
1759 offsets = [offset, ...gaps.map((gap) => (offset += gap))];
1760 }
1761 }
1763 for (const [index, item] of items.entries()) {
1764 const offset = offsets?.[index] ?? (index - (items.length - 1) / 2) * spacing;
1765 const point = anchor(item.rect, item.side);
1766 if (verticalSide) point[1] += offset;
1767 else point[0] += offset;
1768 const endpoints = spread.get(item.relation) || {};
1769 endpoints[item.endpoint] = point;
1770 spread.set(item.relation, endpoints);
1771 }
1772 }
1774 return spread;
1775}
1777// A centre delta on the horizontal axis does not by itself mean the route
1778// leaves sideways: a hub above an offset spoke has both a horizontal and a
1779// larger vertical delta, and the router draws the vertical dogleg. Compare the
1780// deltas so the inferred side matches the axis the route actually uses. Equal
1781// deltas select horizontal sides; dx === 0 preserves the previous vertical
1782// result, while a vertical-dominant nonzero dx selects vertical sides.
1783export function defaultFromSide(from, to) {
1784 const dx = to.cx - from.cx;
1785 const dy = to.cy - from.cy;
1786 if (dx !== 0 && Math.abs(dx) >= Math.abs(dy)) return dx < 0 ? 'left' : 'right';
1787 return dy > 0 ? 'bottom' : 'top';
1788}
1790export function defaultToSide(from, to) {
1791 const dx = to.cx - from.cx;
1792 const dy = to.cy - from.cy;
1793 if (dx !== 0 && Math.abs(dx) >= Math.abs(dy)) return dx < 0 ? 'right' : 'left';
1794 return dy > 0 ? 'top' : 'bottom';
1795}
1797// Non-architecture renderers retain their established horizontal-first
1798// endpoint contract. Architecture opts into dominant-axis inference above so
1799// a vertical hub-and-spoke route can use perpendicular automatic ports.
1800export function legacyDefaultFromSide(from, to) {
1801 if (to.cx < from.cx) return 'left';
1802 if (to.cx > from.cx) return 'right';
1803 if (to.cy > from.cy) return 'bottom';
1804 return 'top';
1805}
1807export function legacyDefaultToSide(from, to) {
1808 if (to.cx < from.cx) return 'right';
1809 if (to.cx > from.cx) return 'left';
1810 if (to.cy > from.cy) return 'top';
1811 return 'bottom';
1812}
1814export function chosenSide(side, fallback) {
1815 return side && side !== 'auto' ? side : fallback;
1816}
1818export function polylinePath(points) {
1819 return points.map(([x, y], index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' ');
1820}
1822export function routePointsValue(points) {
1823 return asArray(points)
1824 .filter((point) => Array.isArray(point) && point.length === 2 && isFinitePoint(...point))
1825 .map(([x, y]) => `${x},${y}`)
1826 .join(';');
1827}
1829// Only a direct, explicitly authored diagonal needs an artifact-check exception.
1830// Nonempty via takes precedence; empty via adds no intermediate geometry.
1831export function authoredStraightRouteAttrs(relation, points) {
1832 if (relation.route !== 'straight' || relation.via?.length || points.length !== 2) return '';
1833 const [start, end] = points;
1834 return Math.abs(start[0] - end[0]) > 0.01 && Math.abs(start[1] - end[1]) > 0.01
1835 ? ' data-composition-route="straight"'
1836 : '';
1837}
1839export function roundedPath(points, radius) {
1840 if (points.length < 3 || radius <= 0) {
1841 return polylinePath(points);
1842 }
1844 const commands = [`M ${points[0][0]} ${points[0][1]}`];
1845 for (let i = 1; i < points.length - 1; i += 1) {
1846 const [px, py] = points[i - 1];
1847 const [cx, cy] = points[i];
1848 const [nx, ny] = points[i + 1];
1849 const prevLen = Math.hypot(cx - px, cy - py);
1850 const nextLen = Math.hypot(nx - cx, ny - cy);
1851 const r = Math.min(radius, prevLen / 2, nextLen / 2);
1852 if (r < 1) {
1853 commands.push(`L ${cx} ${cy}`);
1854 continue;
1855 }
1856 const before = [cx - ((cx - px) / prevLen) * r, cy - ((cy - py) / prevLen) * r];
1857 const after = [cx + ((nx - cx) / nextLen) * r, cy + ((ny - cy) / nextLen) * r];
1858 commands.push(`L ${before[0]} ${before[1]}`);
1859 commands.push(`Q ${cx} ${cy} ${after[0]} ${after[1]}`);
1860 }
1861 const [endX, endY] = points[points.length - 1];
1862 commands.push(`L ${endX} ${endY}`);
1863 return commands.join(' ');
1864}
1866// Shared by edges/flows/transitions: all carry the same optional
1867// labelAt/labelDx/labelDy/labelSegment knobs.
1868export function labelPoint(item, points) {
1869 if (item.labelAt) return item.labelAt;
1870 if (points.length === 2) {
1871 return [
1872 (points[0][0] + points[1][0]) / 2 + (item.labelDx || 0),
1873 points[0][1] - 10 + (item.labelDy || 0)
1874 ];
1875 }
1876 const segmentIndex = Math.min(points.length - 2, Math.max(0, item.labelSegment ?? 1));
1877 const a = points[segmentIndex];
1878 const b = points[segmentIndex + 1];
1879 return [(a[0] + b[0]) / 2 + (item.labelDx || 0), (a[1] + b[1]) / 2 - 10 + (item.labelDy || 0)];
1880}
1882export const componentFill = {
1883 frontend: 'c-frontend',
1884 backend: 'c-backend',
1885 database: 'c-database',
1886 cloud: 'c-cloud',
1887 security: 'c-security',
1888 messagebus: 'c-messagebus',
1889 external: 'c-external'
1890};
1892export const componentText = {
1893 frontend: 't-frontend',
1894 backend: 't-backend',
1895 database: 't-database',
1896 cloud: 't-cloud',
1897 security: 't-security',
1898 messagebus: 't-messagebus',
1899 external: 't-external'
1900};
1902export const arrowClassMap = {
1903 default: ['a-default', 'arrowhead'],
1904 emphasis: ['a-emphasis', 'arrowhead-emphasis'],
1905 security: ['a-security', 'arrowhead-security'],
1906 dashed: ['a-dashed', 'arrowhead-dashed']
1907};
1909// Structural phase/group accents retain their existing semantic colors.
1910export function variantAccent(variant) {
1911 return variant === 'security' ? 't-security'
1912 : variant === 'emphasis' ? 't-backend'
1913 : variant === 'dashed' ? 't-messagebus' : 't-muted';
1914}
1916// Relationship labels use the same theme token as their path. Keep this map
1917// edge-specific: node-kind text colors only coincide with some path colors in
1918// the classic preset and must not define the relationship's visual meaning.
1919export function edgeLabelAccent(variant) {
1920 return variant === 'security'
1921 ? 't-edge-security'
1922 : variant === 'emphasis'
1923 ? 't-edge-emphasis'
1924 : variant === 'dashed'
1925 ? 't-edge-dashed'
1926 : 't-edge-default';
1927}
1929export function formatRect(r) {
1930 return `[${Math.round(r.x)}, ${Math.round(r.y)}, ${Math.round(r.width)}, ${Math.round(r.height)}]`;
1931}
1933function formatValue(n) {
1934 return String(Math.round(n));
1935}
1937// A label anchor is the text origin, so keeping a suggestion on the canvas
1938// means moving the whole rect: offset is `rect - anchor` on that axis.
1939function anchorFitsCanvas(anchorValue, offset, size, extent) {
1940 const overflow = axisCanvasOverflow(anchorValue + offset, size, extent);
1941 return overflow.start <= 0 && overflow.end <= 0;
1942}
1944// Suggestions are emitted as integers, so the real-valued bounds are tightened
1945// inward with ceil/floor first: every integer between them keeps the whole rect
1946// on the canvas, which a bound like 616.7 would not. Returns null when the rect
1947// is wider than the canvas and no anchor can contain it.
1948function clampAnchorToCanvas(anchorValue, offset, size, extent) {
1949 const rounded = Math.round(anchorValue);
1950 if (!Number.isFinite(extent)) return rounded;
1951 const min = Math.ceil(-offset);
1952 const max = Math.floor(extent - size - offset);
1953 return max < min ? null : Math.min(Math.max(rounded, min), max);
1954}
1956/**
1957 * Actionable hint when an edge label rect hits a node/component box (#7).
1958 * Every suggested value is a replacement for the authored field, not an
1959 * increment, and has to survive being applied to the document:
1960 * - the absolute form is nudged along x so the rect stays on the canvas, and a
1961 * vertical placement that cannot fit is dropped rather than clamped, since
1962 * clamping it back would push the label onto the obstacle it must clear;
1963 * - the relative form is offered only when labelDx/labelDy actually move this
1964 * label (labelPoint returns an authored labelAt as-is) and only when the
1965 * replacements, computed from the document's own labelDx/labelDy, land the
1966 * rect inside the canvas.
1967 * The authored values therefore come from `labelRect.relation`, the authored
1968 * relationship the renderer already attaches to every label record.
1969 * `obstacles` is every box the callers' own overlap loop tests (defaults to
1970 * the named obstacle alone): a placement that merely traded the named obstacle
1971 * for its neighbor would fail the same rule again when applied.
1972 */
1973export function suggestLabelObstacleFix(labelRect, lx, ly, obstacle, obstacleKind = 'component', viewBox, obstacles) {
1974 // Renderer canvases are origin-zero [width, height] by schema, but read a
1975 // 4-number [min-x, min-y, width, height] the same way the containment
1976 // collector does — degraded no-ajv runs must not clamp against the origin
1977 // pair as if it were the canvas size.
1978 const box = asArray(viewBox);
1979 const [canvasWidth, canvasHeight] = box.length === 4 ? box.slice(2) : box;
1980 const xOffset = labelRect.x - lx;
1981 const yOffset = labelRect.y - ly;
1982 const anchorX = clampAnchorToCanvas(lx, xOffset, labelRect.width, canvasWidth);
1983 // The placement anchors are derived from the label's own rect, not from the
1984 // obstacle alone: an obstacle-only "above" anchor assumes the 14px
1985 // single-line rect and lands a 27px two-line rect (dataflow classification,
1986 // lifecycle note) back on the obstacle it must clear. The overlap filter
1987 // uses the callers' own detection call, so a surviving hint cannot re-raise
1988 // the problem it repairs.
1989 const blockers = obstacles ? [...obstacles] : [obstacle];
1990 const placements = [
1991 { name: 'below', y: Math.round(obstacle.y + obstacle.height + 4 - yOffset) },
1992 { name: 'above', y: Math.round(obstacle.y - 4 - labelRect.height - yOffset) },
1993 ].filter(({ y }) => anchorX !== null
1994 && anchorFitsCanvas(y, yOffset, labelRect.height, canvasHeight)
1995 && blockers.every((blocker) => !rectsOverlap(
1996 { x: anchorX + xOffset, y: y + yOffset, width: labelRect.width, height: labelRect.height },
1997 blocker,
1998 -2,
1999 )));
2000 const lines = [
2001 ` label rect: ${formatRect(labelRect)}`,
2002 ` ${obstacleKind} "${obstacle.id}" rect: ${formatRect(obstacle)}`,
2003 ];
2004 if (!placements.length) {
2005 // Only the vertical slots beside the named obstacle were tried, so an
2006 // unclaimed spot elsewhere may still exist — never assert that none does.
2007 lines.push(anchorX === null
2008 ? ` Suggested fix: the ${Math.round(labelRect.width)}px label rect cannot fit the ${canvasWidth}x${canvasHeight} viewBox at any anchor — shorten the label or enlarge meta.viewBox`
2009 : ` Suggested fix: no placement directly above or below "${obstacle.id}" stays clear inside the ${canvasWidth}x${canvasHeight} viewBox — move the label to an open area with labelAt, shorten the label, move the ${obstacleKind}, or enlarge meta.viewBox`);
2010 return lines.join('\n');
2011 }
2012 const authored = labelRect.relation || {};
2013 const authoredDx = Number.isFinite(authored.labelDx) ? authored.labelDx : 0;
2014 const authoredDy = Number.isFinite(authored.labelDy) ? authored.labelDy : 0;
2015 const relativeHint = (y) => {
2016 if (Array.isArray(authored.labelAt)) return null;
2017 // Both replacements are measured from the automatic label point that the
2018 // authored offsets are applied to, and against the unrounded anchor: a
2019 // rounded base would shift the applied label by up to a pixel.
2020 const dx = Math.round(authoredDx + anchorX - lx);
2021 const dy = Math.round(authoredDy + y - ly);
2022 // labelDx is authored as a number, so an authored fraction must not read as
2023 // a needed nudge once the replacement is rounded to an integer.
2024 const movesX = Math.abs(dx - authoredDx) >= 0.5;
2025 const landsAtX = lx - authoredDx + (movesX ? dx : authoredDx);
2026 const landsAtY = ly - authoredDy + dy;
2027 if (!anchorFitsCanvas(landsAtX, xOffset, labelRect.width, canvasWidth)) return null;
2028 if (!anchorFitsCanvas(landsAtY, yOffset, labelRect.height, canvasHeight)) return null;
2029 return movesX
2030 ? `set labelDx ${formatValue(dx)} with labelDy ${formatValue(dy)}`
2031 : `set labelDy ${formatValue(dy)}`;
2032 };
2033 const hint = placements
2034 .map(({ name, y }) => {
2035 const relative = relativeHint(y);
2036 return `set labelAt [${anchorX}, ${y}]${relative ? ` or ${relative}` : ''} (${name})`;
2037 })
2038 .join('; or ');
2039 lines.push(` Suggested fix: ${hint}`);
2040 return lines.join('\n');
2041}
2043/** Hint when two edge labels collide. */
2044export function suggestLabelPairFix(a, b) {
2045 return [
2046 ` "${a.label}" ${formatRect(a)}; "${b.label}" ${formatRect(b)}`,
2047 ' Suggested fix: adjust labelDx/labelDy/labelSegment, or route one relationship through a separate corridor',
2048 ].join('\n');
2049}
2051/**
2052 * The two placements that separate b from a, in the order the prose hint
2053 * offers them. Shared so the text hint and its structured repair cannot
2054 * offer different coordinates.
2055 */
2056export function componentSeparationOptions(a, b, minGap = 8) {
2057 // Ceil, not round: on fractional geometry a rounded right/below coordinate
2058 // can land a fraction of a pixel short of minGap, and the advised position
2059 // would never clear the diagnostic that offered it.
2060 return [
2061 { pos: [Math.ceil(a.x + a.width + minGap), Math.round(b.y)], relation: `right of "${a.id}"` },
2062 { pos: [Math.round(b.x), Math.ceil(a.y + a.height + minGap)], relation: 'below' },
2063 ];
2064}
2066/** Hint when two components/nodes are too close. */
2067export function suggestComponentSeparation(a, b, minGap = 8) {
2068 const [right, below] = componentSeparationOptions(a, b, minGap);
2069 return [
2070 ` "${a.id}" ${formatRect(a)}; "${b.id}" ${formatRect(b)}`,
2071 ` Suggested fix: move "${b.id}" pos to [${right.pos[0]}, ${right.pos[1]}] (${right.relation}) or [${below.pos[0]}, ${below.pos[1]}] (${below.relation})`,
2072 ].join('\n');
2073}