@sentropic/diagram-canvas 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +21 -0
  2. package/dist/camera.d.ts +24 -3
  3. package/dist/camera.js +31 -8
  4. package/dist/index.d.ts +4 -0
  5. package/dist/index.js +4 -0
  6. package/dist/layout/cache.js +12 -2
  7. package/dist/layout/channels.d.ts +10 -0
  8. package/dist/layout/channels.js +13 -0
  9. package/dist/layout/conventions.d.ts +117 -0
  10. package/dist/layout/conventions.js +185 -0
  11. package/dist/layout/dock.d.ts +2 -0
  12. package/dist/layout/dock.js +5 -1
  13. package/dist/layout/fingerprint.d.ts +4 -2
  14. package/dist/layout/fingerprint.js +26 -2
  15. package/dist/layout/hints.d.ts +1 -1
  16. package/dist/layout/hints.js +10 -3
  17. package/dist/layout/index.d.ts +5 -3
  18. package/dist/layout/index.js +5 -3
  19. package/dist/layout/measure.d.ts +6 -0
  20. package/dist/layout/measure.js +28 -0
  21. package/dist/layout/measured.js +1047 -95
  22. package/dist/layout/route.d.ts +27 -1
  23. package/dist/layout/route.js +640 -32
  24. package/dist/layout/routeSpacing.d.ts +84 -0
  25. package/dist/layout/routeSpacing.js +472 -0
  26. package/dist/layout/spacing.generated.d.ts +10 -1
  27. package/dist/layout/spacing.generated.js +10 -1
  28. package/dist/layout/types.d.ts +33 -2
  29. package/dist/layout/types.js +2 -0
  30. package/dist/presentation/connectorPath.d.ts +32 -0
  31. package/dist/presentation/connectorPath.js +213 -0
  32. package/dist/presentation/connectorStyle.d.ts +70 -0
  33. package/dist/presentation/connectorStyle.js +99 -0
  34. package/dist/presentation/diagramSceneModel.d.ts +56 -4
  35. package/dist/presentation/diagramSceneModel.js +222 -31
  36. package/dist/presentation/diagramSceneTypes.d.ts +9 -0
  37. package/dist/presentation/index.d.ts +4 -0
  38. package/dist/presentation/index.js +4 -0
  39. package/dist/presentation/linkLegend.d.ts +132 -0
  40. package/dist/presentation/linkLegend.js +231 -0
  41. package/dist/presentation/renderSceneSvg.d.ts +3 -1
  42. package/dist/presentation/renderSceneSvg.js +81 -11
  43. package/dist/presentation/sceneLabelClearance.d.ts +1 -1
  44. package/dist/presentation/sceneLabelClearance.js +19 -3
  45. package/dist/r7Mode.d.ts +13 -0
  46. package/dist/r7Mode.js +67 -0
  47. package/dist/visibility.d.ts +1 -1
  48. package/dist/visibility.js +3 -2
  49. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import { flowIndex, parentOccurrenceOf, representativeOf } from "@sentropic/diagram-core";
1
+ import { flowIndex, parentOccurrenceOf, representativeOf, resolveArrowhead, resolveDashPattern, resolveLinkEmphasis, } from "@sentropic/diagram-core";
2
2
  import { DEFAULT_FLOW_STRINGS } from "./flowModel.js";
3
3
  import { measureErdCard, renderErdMarkerSvg, erdText, wrapErdText, placeErdRoleLabels, ERD_GEOMETRY } from "./erd.js";
4
4
  /**
@@ -14,12 +14,19 @@ import { measureErdCard, renderErdMarkerSvg, erdText, wrapErdText, placeErdRoleL
14
14
  * (layout, scene, camera). The semantic-document and view types are read
15
15
  * off the layout signature, so this package names no other diagram layer.
16
16
  */
17
- import { buildScene, cameraFit, clampZoom, CONTENT_INSET, DEFAULT_ALLOCATED_LINES, DEFAULT_LAYOUT_METRICS, FIT_PAINT_INSET, layoutFolded, layoutMeasured, placeEdgeLabels, rectUnion, relationRoute, sceneNodes, sceneEdges, } from "../index.js";
17
+ import { buildScene, cameraFit, clampZoom, CONTENT_INSET, DEFAULT_ALLOCATED_LINES, DEFAULT_EDGE_LABEL_SIZE, DEFAULT_LAYOUT_METRICS, DEFAULT_LINK_PRIMARY_STROKE_WIDTH, DEFAULT_LINK_RELATED_STROKE_WIDTH, DEFAULT_LINK_STROKE_WIDTH, DEFAULT_LINK_EMPHASIS_STROKE_WIDTH, FIT_PAINT_INSET, MIN_EDGE_LABEL_CSS_PX, diagramAnatomyOf, isR7ConnectorPresentation, layoutFolded, layoutMeasured, placeEdgeLabels, rectUnion, relationRoute, scaleEdgeLabelMeasurer, sceneNodes, sceneEdges, } from "../index.js";
18
18
  import { measureBundleLabel } from "../layout/bundleLabel.js";
19
19
  import { LABEL_CLEARANCE_REFERENCE_SCALE } from "../layout/labels.js";
20
20
  import { getDiagramGlyph } from "./registry.js";
21
21
  import { anatomyZoneGeometry, lineBoxHeight, ZONE_GEOMETRY } from "./diagramCardModel.js";
22
+ import { buildSceneLinkLegend } from "./linkLegend.js";
22
23
  import { clearSceneLabels } from "./sceneLabelClearance.js";
24
+ import { DEFAULT_EDGE_CORNER_RADIUS } from "./connectorPath.js";
25
+ import { connectorStrokeWidth } from "./connectorStyle.js";
26
+ export { connectorPath, parseConnectorPath, DEFAULT_EDGE_CORNER_RADIUS } from "./connectorPath.js";
27
+ export { ARROWHEAD_MARKER_GEOMETRY, connectorDashArray, connectorDashPaint, connectorMarkerIds, connectorMarkerKind, connectorMarkerRef, extraConnectorMarkers, } from "./connectorStyle.js";
28
+ export { buildSceneLinkLegend, collectLinkLegendStyles, defaultLinkStyleLabel, LINK_LEGEND_ARROWHEAD_ORDER, LINK_LEGEND_EMPHASIS_ORDER, LINK_LEGEND_FONT_SIZE, LINK_LEGEND_GAP, LINK_LEGEND_HEADER_GAP, LINK_LEGEND_HEADER_HEIGHT, LINK_LEGEND_MIN_WIDTH, LINK_LEGEND_PADDING, LINK_LEGEND_ROW_GAP, LINK_LEGEND_ROW_HEIGHT, LINK_LEGEND_STROKE_ORDER, LINK_LEGEND_SWATCH_GAP, LINK_LEGEND_SWATCH_HEIGHT, LINK_LEGEND_SWATCH_WIDTH, linkLegendBoxStyle, linkLegendSwatchGeometry, linkStyleKey, } from "./linkLegend.js";
29
+ export { DEFAULT_EDGE_LABEL_SIZE, DEFAULT_LINK_STROKE_WIDTH, DEFAULT_LINK_RELATED_STROKE_WIDTH, DEFAULT_LINK_PRIMARY_STROKE_WIDTH, DEFAULT_LINK_EMPHASIS_STROKE_WIDTH, isR7ConnectorPresentation, };
23
30
  /**
24
31
  * Default layout report width. The measured path never re-packs on it (D-3).
25
32
  * Hosts use the measured frame width for the camera fit (Z-8).
@@ -47,9 +54,9 @@ export function resolveScenePresentation(document, presentation, bindings = {},
47
54
  * and its boxes inherit the pin unless they carry their own. Absent
48
55
  * everywhere means `"v1"` — existing views do not move.
49
56
  */
50
- const viewAnatomy = view?.presentation?.anatomy;
51
- const withViewAnatomy = (entry) => {
52
- const resolved = entry.anatomy === undefined && viewAnatomy !== undefined ? { ...entry, anatomy: viewAnatomy } : entry;
57
+ const withViewAnatomy = (id, entry) => {
58
+ const anatomy = diagramAnatomyOf(presentation, view, id);
59
+ const resolved = entry.anatomy === undefined && anatomy === "v2" ? { ...entry, anatomy } : entry;
53
60
  // View-level centring applies only when explicitly requested on compact v2 anatomy.
54
61
  if (resolved.anatomy !== "v2" && resolved.align === "center") {
55
62
  const { align: _ignored, ...rest } = resolved;
@@ -59,23 +66,23 @@ export function resolveScenePresentation(document, presentation, bindings = {},
59
66
  };
60
67
  const entities = Object.fromEntries(Object.entries(presentation.entities).map(([id, entry]) => {
61
68
  if (entry.form !== "card" && entry.form !== "container" && entry.form !== "legend")
62
- return [id, withViewAnatomy(entry)];
69
+ return [id, withViewAnatomy(id, entry)];
63
70
  const entityId = view?.entityOccurrences[id]?.entity ?? id.replace(/^occurrence:e\./, "entity:");
64
71
  const entity = document.entities[entityId];
65
72
  if (entity?.profile === "erd@1")
66
- return [id, withViewAnatomy(entry)];
73
+ return [id, withViewAnatomy(id, entry)];
67
74
  const binding = bindings[entity === undefined ? "" : entity.profile + ":" + entity.type] ?? bindings[entity?.type ?? ""];
68
75
  if (binding?.shape !== undefined && binding.shape !== "component")
69
- return [id, withViewAnatomy({ ...entry, icon: entry.icon ?? "none" })];
76
+ return [id, withViewAnatomy(id, { ...entry, icon: entry.icon ?? "none" })];
70
77
  const role = binding?.role ?? (entry.form === "card" ? "card" : "zone");
71
78
  const icon = entry.icon ?? binding?.icon ?? ROLE_ICONS[role];
72
79
  if (icon === "none")
73
- return [id, withViewAnatomy({ ...entry, icon: "none" })];
80
+ return [id, withViewAnatomy(id, { ...entry, icon: "none" })];
74
81
  if (icon === undefined || resolveGlyph(icon) === undefined) {
75
82
  missing.push(id);
76
- return [id, withViewAnatomy({ ...entry, icon: strict ? "unknown" : "none" })];
83
+ return [id, withViewAnatomy(id, { ...entry, icon: strict ? "unknown" : "none" })];
77
84
  }
78
- return [id, withViewAnatomy({ ...entry, icon })];
85
+ return [id, withViewAnatomy(id, { ...entry, icon })];
79
86
  }));
80
87
  /**
81
88
  * Owner addendum 1 — stamp nesting depth from the view groups (or from
@@ -168,6 +175,7 @@ export function layoutScene(input) {
168
175
  targetWidth: input.targetWidth ?? DEFAULT_SCENE_TARGET_WIDTH,
169
176
  ...(input.previousOrientation === undefined ? {} : { previousOrientation: input.previousOrientation }),
170
177
  ...(input.reportSurfaceSame === undefined ? {} : { reportSurfaceSame: input.reportSurfaceSame }),
178
+ ...(input.conventions === undefined ? {} : { conventions: input.conventions }),
171
179
  };
172
180
  const result = input.cache !== undefined
173
181
  ? (input.view === undefined
@@ -237,7 +245,24 @@ function edgeLabelOf(document, relation) {
237
245
  * collapsed boxes and the title band of each expanded zone — an expanded
238
246
  * zone's interior is not a blocker on the row-pack path).
239
247
  */
240
- export function resolveScene(result, input) {
248
+ export function resolveScene(result, input, viewport) {
249
+ let scene = resolveSceneAtZoom(result, input);
250
+ if (!viewport?.fitToWindow || !scene.r7Connectors)
251
+ return scene;
252
+ const labelSize = input.metrics?.edgeLabelSize ?? DEFAULT_EDGE_LABEL_SIZE;
253
+ let paintZoom = Math.max(LABEL_CLEARANCE_REFERENCE_SCALE, MIN_EDGE_LABEL_CSS_PX / labelSize);
254
+ // Enlarging labels can extend the bounds. Repeat only when the resulting
255
+ // fit needs more clearance, with a bound for extremely small viewports.
256
+ for (let pass = 0; pass < 4 && scene.bounds !== undefined; pass += 1) {
257
+ const { zoom } = sceneFit({ ...viewport, bounds: scene.bounds });
258
+ if (!(zoom > 0 && zoom < paintZoom))
259
+ break;
260
+ paintZoom = zoom;
261
+ scene = resolveSceneAtZoom(result, input, paintZoom);
262
+ }
263
+ return scene;
264
+ }
265
+ function resolveSceneAtZoom(result, input, paintZoom) {
241
266
  const view = result.view;
242
267
  const resolved = resolveScenePresentation(input.document, input.presentation, input.iconBindings, input.strictIcons, view, input.resolveGlyph, input.depthParityStart === undefined ? {} : { depthParityStart: input.depthParityStart });
243
268
  const frame = buildScene({ document: input.document, views: { [view.viewId]: view } }, view.viewId);
@@ -276,9 +301,23 @@ export function resolveScene(result, input) {
276
301
  const connectorCutouts = [];
277
302
  const footerWidths = new Map((result.measurements?.slots ?? []).filter((slot) => slot.role === "footer").map((slot) => [slot.occurrence, slot.layout.width]));
278
303
  const margin = input.metrics?.labelMargin ?? DEFAULT_LAYOUT_METRICS.labelMargin;
279
- // Add a fixed allowance for non-scaling ink to the host’s label-padding token.
280
- const paintClearance = margin + ZONE_GEOMETRY.borderWidth / (2 * LABEL_CLEARANCE_REFERENCE_SCALE);
304
+ const erd = input.document.profileRefs.length === 1 && input.document.profileRefs[0] === 'erd@1';
305
+ const r7Connectors = !erd && (result.routeSpacing !== undefined || isR7ConnectorPresentation(input.presentation, input.view ?? view, input.document));
306
+ const edgeLabelMeasure = scaleEdgeLabelMeasurer(input.measureLines, r7Connectors ? input.metrics?.edgeLabelSize : undefined, DEFAULT_EDGE_LABEL_SIZE);
307
+ const baseLabelSize = input.metrics?.edgeLabelSize ?? DEFAULT_EDGE_LABEL_SIZE;
308
+ const overviewEdgeLabelSize = r7Connectors && paintZoom !== undefined && baseLabelSize * paintZoom < MIN_EDGE_LABEL_CSS_PX
309
+ ? Math.ceil(MIN_EDGE_LABEL_CSS_PX / paintZoom * 64) / 64
310
+ : undefined;
311
+ const labelScale = overviewEdgeLabelSize === undefined ? 1 : overviewEdgeLabelSize / baseLabelSize;
312
+ const clearanceZoom = Math.min(LABEL_CLEARANCE_REFERENCE_SCALE, paintZoom ?? LABEL_CLEARANCE_REFERENCE_SCALE);
313
+ // Non-scaling connector paint occupies more world units at a smaller zoom.
314
+ const relationPresentation = input.presentation.relations;
315
+ const baseLinkStrokeWidth = r7Connectors
316
+ ? (input.metrics?.linkStrokeWidth ?? DEFAULT_LINK_STROKE_WIDTH)
317
+ : 1.5;
318
+ const paintClearance = margin + baseLinkStrokeWidth / (2 * clearanceZoom);
281
319
  const zoneInset = input.metrics?.containerPadding ?? ZONE_GEOMETRY.contentInsetInline;
320
+ const pendingCutouts = [];
282
321
  for (const node of nodes) {
283
322
  if (node.kind !== "zone" || node.collapsed) {
284
323
  blockers.push(node.rect);
@@ -288,7 +327,7 @@ export function resolveScene(result, input) {
288
327
  if (height === undefined)
289
328
  continue;
290
329
  const zoneGeo = anatomyZoneGeometry(node.presentation?.anatomy);
291
- const ruleClearance = (zoneGeo.ruleHeight / 2 + 1) / LABEL_CLEARANCE_REFERENCE_SCALE;
330
+ const ruleClearance = (zoneGeo.ruleHeight / 2 + 1) / clearanceZoom;
292
331
  blockers.push({
293
332
  x: node.rect.x,
294
333
  y: node.rect.y,
@@ -302,19 +341,10 @@ export function resolveScene(result, input) {
302
341
  if (reserve > 0) {
303
342
  blockers.push({ x: node.rect.x, y: node.rect.y + node.rect.height - reserve - zoneGeo.borderWidth - ruleClearance,
304
343
  width: node.rect.width, height: reserve + zoneGeo.borderWidth + ruleClearance });
305
- // The footer line as `layoutZone` seats it: one line box pinned above
306
- // the bottom border, from the content inset, as wide as its measured
307
- // text (the whole inner width when the result carries no measurement).
308
344
  const inner = Math.max(0, node.rect.width - 2 * zoneInset);
309
345
  const lineHeight = lineBoxHeight(zoneGeo.footer.size);
310
346
  const bottom = node.rect.y + node.rect.height - zoneGeo.borderWidth - zoneGeo.footerBottomInset;
311
- const pad = paintClearance + CONNECTOR_CUTOUT_SLACK;
312
- connectorCutouts.push({
313
- x: node.rect.x + zoneInset - pad,
314
- y: bottom - lineHeight - pad,
315
- width: Math.min(footerWidths.get(node.occurrence) ?? inner, inner) + 2 * pad,
316
- height: lineHeight + 2 * pad,
317
- });
347
+ pendingCutouts.push({ node, inner, lineHeight, bottom });
318
348
  }
319
349
  }
320
350
  const allFlows = flowIndex(input.document);
@@ -367,7 +397,27 @@ export function resolveScene(result, input) {
367
397
  const first = points[0], second = points[1], last = points[points.length - 1], before = points[points.length - 2];
368
398
  markers = renderErdMarkerSvg(erdText(semantic.attributes, 'fromCardinality'), first, { x: second.x - first.x, y: second.y - first.y }) + renderErdMarkerSvg(erdText(semantic.attributes, 'toCardinality'), last, { x: before.x - last.x, y: before.y - last.y });
369
399
  }
370
- edges.push({ ...(markers === undefined ? {} : { markers }), occurrence: occurrence.id, points, directed: flow !== undefined, arrows: result.arrowBoxes?.[occurrence.id] ?? [], ...(flow === undefined ? {} : { flow }), ...(bundle === undefined ? {} : { bundle }) });
400
+ const relStyle = relationPresentation?.[occurrence.id] ?? relationPresentation?.[occurrence.relation];
401
+ const rawStrokeStyle = occurrence.strokeStyle ?? relStyle?.strokeStyle;
402
+ const resolvedStrokeStyle = rawStrokeStyle === undefined ? undefined : resolveDashPattern(rawStrokeStyle)?.style;
403
+ const rawArrowhead = occurrence.arrowhead ?? relStyle?.arrowhead;
404
+ const resolvedArrowhead = rawArrowhead === undefined ? undefined : resolveArrowhead(rawArrowhead)?.canonicalKind;
405
+ const rawEmphasis = occurrence.emphasis ?? relStyle?.emphasis;
406
+ const resolvedEmphasis = rawEmphasis === undefined ? undefined : resolveLinkEmphasis(rawEmphasis)?.emphasis;
407
+ const isR7Edge = r7Connectors && markers === undefined && flow === undefined;
408
+ edges.push({
409
+ ...(markers === undefined ? {} : { markers }),
410
+ ...(isR7Edge ? { r7: true } : {}),
411
+ occurrence: occurrence.id,
412
+ points,
413
+ directed: flow !== undefined,
414
+ arrows: result.arrowBoxes?.[occurrence.id] ?? [],
415
+ ...(flow === undefined ? {} : { flow }),
416
+ ...(bundle === undefined ? {} : { bundle }),
417
+ ...(isR7Edge && resolvedStrokeStyle !== undefined && resolvedStrokeStyle !== "solid" ? { strokeStyle: resolvedStrokeStyle } : {}),
418
+ ...(isR7Edge && resolvedArrowhead !== undefined && resolvedArrowhead !== "arrow" ? { arrowhead: resolvedArrowhead } : {}),
419
+ ...(isR7Edge && resolvedEmphasis === "emphasis" ? { emphasis: resolvedEmphasis } : {}),
420
+ });
371
421
  if (result.labelBoxes !== undefined && result.labelBoxes[id] === undefined)
372
422
  continue;
373
423
  const label = result.edgeBundles?.[id]?.label ?? (semantic?.profile === 'erd@1'
@@ -375,7 +425,7 @@ export function resolveScene(result, input) {
375
425
  : edgeLabelOf(input.document, occurrence.relation));
376
426
  if (label === undefined)
377
427
  continue;
378
- const layout = measuredLabels.get(id) ?? input.measureLines({
428
+ const layout = measuredLabels.get(id) ?? edgeLabelMeasure({
379
429
  text: label,
380
430
  role: "edge-label",
381
431
  availableWidth: EDGE_LABEL_ALLOCATION,
@@ -392,7 +442,6 @@ export function resolveScene(result, input) {
392
442
  const box = item.kind === "edge" ? item.bounds : item.rect;
393
443
  bounds = bounds === undefined ? box : rectUnion(bounds, box);
394
444
  }
395
- const erd = input.document.profileRefs.length === 1 && input.document.profileRefs[0] === 'erd@1';
396
445
  const placements = erd ? placeErdRoleLabels(entries, blockers, margin) : result.labelBoxes === undefined
397
446
  ? placeEdgeLabels(entries, blockers, margin)
398
447
  : new Map(Object.entries(result.labelBoxes).map(([id, box]) => [id, { box }]));
@@ -402,9 +451,21 @@ export function resolveScene(result, input) {
402
451
  for (const [id, placement] of placements) {
403
452
  if (placement === undefined || !labelled.has(id))
404
453
  continue;
405
- labels.push({ occurrence: id, lines: labelLines.get(id) ?? [], box: placement.box, ...(erd ? { erd: true } : {}), ...("leader" in placement ? { leader: placement.leader } : {}),
454
+ const { box } = placement;
455
+ const scaledBox = labelScale === 1 ? box : {
456
+ x: box.x - box.width * (labelScale - 1) / 2,
457
+ y: box.y - box.height * (labelScale - 1) / 2,
458
+ width: box.width * labelScale,
459
+ height: box.height * labelScale,
460
+ };
461
+ const bundle = result.edgeBundles?.[id];
462
+ const chip = bundle?.relations === undefined ? undefined
463
+ : bundle.chip ?? measureBundleLabel(bundle.relations, edgeLabelMeasure, input.metrics?.bundleLabelMaxWidth);
464
+ labels.push({ occurrence: id, lines: labelLines.get(id) ?? [], box: scaledBox, ...(erd ? { erd: true } : {}), ...("leader" in placement ? { leader: placement.leader } : {}),
406
465
  ...(result.edgeBundles?.[id] === undefined ? {} : { title: result.edgeBundles[id].title }),
407
- ...(result.edgeBundles?.[id]?.relations === undefined ? {} : { bundle: result.edgeBundles[id].chip ?? measureBundleLabel(result.edgeBundles[id].relations, input.measureLines, input.metrics?.bundleLabelMaxWidth) }) });
466
+ ...(chip === undefined ? {} : { bundle: labelScale === 1 ? chip : {
467
+ ...chip, groups: chip.groups.map(group => ({ ...group, top: group.top * labelScale, height: group.height * labelScale })),
468
+ } }) });
408
469
  }
409
470
  const badges = [];
410
471
  for (const step of flows.scenarios.flatMap((scenario) => scenario.steps)) {
@@ -422,11 +483,68 @@ export function resolveScene(result, input) {
422
483
  for (const arrows of Object.values(result.arrowBoxes ?? {}))
423
484
  for (const arrow of arrows)
424
485
  bounds = bounds === undefined ? arrow.box : rectUnion(bounds, arrow.box);
425
- const clearedLabels = clearSceneLabels(labels, edges.map(edge => edge.points), [...blockers, ...badges.map(badge => badge.box), ...edges.flatMap(edge => edge.arrows.map(arrow => arrow.box))], paintClearance);
486
+ const cornerRadius = r7Connectors ? (input.metrics?.edgeCornerRadius ?? DEFAULT_EDGE_CORNER_RADIUS) : 0;
487
+ for (const { node, inner, lineHeight, bottom } of pendingCutouts) {
488
+ if (!r7Connectors) {
489
+ const pad = paintClearance + CONNECTOR_CUTOUT_SLACK;
490
+ connectorCutouts.push({
491
+ x: node.rect.x + zoneInset - pad,
492
+ y: bottom - lineHeight - pad,
493
+ width: Math.min(footerWidths.get(node.occurrence) ?? inner, inner) + 2 * pad,
494
+ height: lineHeight + 2 * pad,
495
+ });
496
+ continue;
497
+ }
498
+ const basePad = Math.max(paintClearance + CONNECTOR_CUTOUT_SLACK, margin + baseLinkStrokeWidth / clearanceZoom + 1.15);
499
+ let pad = basePad;
500
+ for (const edge of edges) {
501
+ if (!edge.r7)
502
+ continue;
503
+ const width = connectorStrokeWidth(edge, input.metrics);
504
+ const edgePad = Math.max(margin + width / (2 * clearanceZoom) + CONNECTOR_CUTOUT_SLACK, margin + width / clearanceZoom + 1.15);
505
+ if (edgePad <= pad)
506
+ continue;
507
+ const cutoutLeft = node.rect.x + zoneInset - edgePad;
508
+ const cutoutRight = cutoutLeft + Math.min(footerWidths.get(node.occurrence) ?? inner, inner) + 2 * edgePad;
509
+ const cutoutTop = bottom - lineHeight - edgePad;
510
+ const cutoutBottom = Math.min(node.rect.y + node.rect.height, bottom + edgePad);
511
+ if (edge.points.slice(1).some((point, i) => {
512
+ const prev = edge.points[i];
513
+ return Math.min(prev.x, point.x) <= cutoutRight && cutoutLeft <= Math.max(prev.x, point.x)
514
+ && Math.min(prev.y, point.y) <= cutoutBottom && cutoutTop <= Math.max(prev.y, point.y);
515
+ }))
516
+ pad = edgePad;
517
+ }
518
+ const cutoutTop = bottom - lineHeight - pad;
519
+ const cutoutBottom = Math.min(node.rect.y + node.rect.height, bottom + pad);
520
+ connectorCutouts.push({
521
+ x: node.rect.x + zoneInset - pad,
522
+ y: cutoutTop,
523
+ width: Math.min(footerWidths.get(node.occurrence) ?? inner, inner) + 2 * pad,
524
+ height: cutoutBottom - cutoutTop,
525
+ });
526
+ }
527
+ const clearedLabels = r7Connectors
528
+ ? clearSceneLabels(labels, edges.map(edge => edge.points), [...blockers, ...badges.map(badge => badge.box), ...edges.flatMap(edge => edge.arrows.map(arrow => arrow.box))], paintClearance, cornerRadius, edges.map(edge => edge.r7
529
+ ? Math.max(0, connectorStrokeWidth(edge, input.metrics) - baseLinkStrokeWidth) / (2 * clearanceZoom)
530
+ : 0))
531
+ : clearSceneLabels(labels, edges.map(edge => edge.points), [...blockers, ...badges.map(badge => badge.box), ...edges.flatMap(edge => edge.arrows.map(arrow => arrow.box))], paintClearance);
426
532
  for (const { box } of clearedLabels) {
427
533
  const padded = { x: box.x - margin, y: box.y - margin, width: box.width + 2 * margin, height: box.height + 2 * margin };
428
534
  bounds = bounds === undefined ? padded : rectUnion(bounds, padded);
429
535
  }
536
+ const linkLegend = buildSceneLinkLegend({
537
+ edges,
538
+ contentBounds: bounds,
539
+ measureLines: input.measureLines,
540
+ ...(input.legend === undefined ? {} : { anchor: input.legend }),
541
+ ...(input.legendTitle === undefined ? {} : { title: input.legendTitle }),
542
+ ...(input.legendLabels === undefined ? {} : { labels: input.legendLabels }),
543
+ ...(input.metrics?.edgeLabelSize === undefined ? {} : { fontSize: input.metrics.edgeLabelSize }),
544
+ });
545
+ if (linkLegend !== undefined) {
546
+ bounds = bounds === undefined ? linkLegend.rect : rectUnion(bounds, linkLegend.rect);
547
+ }
430
548
  if (bounds !== undefined) {
431
549
  const x = Math.floor(bounds.x * 64) / 64, y = Math.floor(bounds.y * 64) / 64;
432
550
  bounds = { x, y, width: Math.ceil((bounds.x + bounds.width) * 64) / 64 - x, height: Math.ceil((bounds.y + bounds.height) * 64) / 64 - y };
@@ -439,7 +557,10 @@ export function resolveScene(result, input) {
439
557
  nodes,
440
558
  edges,
441
559
  labels: clearedLabels,
560
+ ...(overviewEdgeLabelSize === undefined ? {} : { overviewEdgeLabelSize }),
561
+ r7Connectors,
442
562
  connectorCutouts,
563
+ ...(linkLegend === undefined ? {} : { linkLegend }),
443
564
  ...(bounds === undefined ? {} : { bounds }),
444
565
  orientations: result.orientations ?? {},
445
566
  };
@@ -456,6 +577,7 @@ export const DEFAULT_SCENE_LABELS = Object.freeze({
456
577
  expand: (title) => `Expand ${title}`,
457
578
  collapse: (title) => `Collapse ${title}`,
458
579
  contains: "includes",
580
+ legend: "Legend",
459
581
  });
460
582
  /** Full presentation text retained alongside the textual relations (A14, DE-1b). */
461
583
  export function sceneTextRows(scene, document, labels) {
@@ -488,6 +610,7 @@ export function sceneFit(input) {
488
610
  ...(input.scrollbarHeight === undefined ? {} : { scrollbarHeight: input.scrollbarHeight }),
489
611
  ...(input.maxDisplayScale === undefined ? {} : { maxDisplayScale: input.maxDisplayScale }),
490
612
  ...(input.minReadableScale === undefined ? {} : { minReadableScale: input.minReadableScale }),
613
+ ...(input.fitToWindow === undefined ? {} : { fitToWindow: input.fitToWindow }),
491
614
  zoomQuantum: FIT_QUANTUM,
492
615
  });
493
616
  }
@@ -542,6 +665,73 @@ export function parseScale(value) {
542
665
  const amount = Number(value);
543
666
  return Number.isFinite(amount) && amount > 0 ? amount : undefined;
544
667
  }
668
+ /**
669
+ * Parse a CSS length token (`px`, unitless, `rem`, `em`, `pt`, `pc`, `in`, `cm`, `mm`, `q`)
670
+ * into CSS px / world units. Resolves `rem` against `rootFontSize` (default 16) and `em`
671
+ * against `elementFontSize` (default `rootFontSize`, 16).
672
+ */
673
+ export function parseCssLengthPx(value, context = {}) {
674
+ if (value === undefined)
675
+ return undefined;
676
+ const trimmed = value.trim();
677
+ if (trimmed === "")
678
+ return undefined;
679
+ const match = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)\s*([a-z%]*)$/i.exec(trimmed);
680
+ if (match === null)
681
+ return undefined;
682
+ const amount = Number(match[1]);
683
+ if (!Number.isFinite(amount))
684
+ return undefined;
685
+ const unit = match[2].toLowerCase();
686
+ const rootPx = context.rootFontSize !== undefined && Number.isFinite(context.rootFontSize) && context.rootFontSize > 0
687
+ ? context.rootFontSize
688
+ : 16;
689
+ const elementPx = context.elementFontSize !== undefined && Number.isFinite(context.elementFontSize) && context.elementFontSize > 0
690
+ ? context.elementFontSize
691
+ : rootPx;
692
+ switch (unit) {
693
+ case "":
694
+ case "px":
695
+ return amount;
696
+ case "rem":
697
+ return amount * rootPx;
698
+ case "em":
699
+ return amount * elementPx;
700
+ case "pt":
701
+ return amount * (96 / 72);
702
+ case "pc":
703
+ return amount * 16;
704
+ case "in":
705
+ return amount * 96;
706
+ case "cm":
707
+ return amount * (96 / 2.54);
708
+ case "mm":
709
+ return amount * (96 / 25.4);
710
+ case "q":
711
+ return amount * (96 / 101.6);
712
+ default:
713
+ return undefined;
714
+ }
715
+ }
716
+ /**
717
+ * Resolve the effective edge-label font size from both the DE-2 `edgeLabelSize`
718
+ * token and the legacy `edgeLabelFontSize` token. Core themes define both at
719
+ * `18px`, so r7 also honours consumer overrides on `edgeLabelFontSize`
720
+ * when `edgeLabelSize` has its default value.
721
+ */
722
+ export function resolveEdgeLabelSizeToken(edgeLabelSize, edgeLabelFontSize) {
723
+ if (edgeLabelSize !== undefined && edgeLabelSize > 0 && edgeLabelSize !== DEFAULT_EDGE_LABEL_SIZE) {
724
+ return edgeLabelSize;
725
+ }
726
+ if (edgeLabelFontSize !== undefined && edgeLabelFontSize > 0 && edgeLabelFontSize !== DEFAULT_EDGE_LABEL_SIZE) {
727
+ return edgeLabelFontSize;
728
+ }
729
+ if (edgeLabelSize !== undefined && edgeLabelSize > 0)
730
+ return edgeLabelSize;
731
+ if (edgeLabelFontSize !== undefined && edgeLabelFontSize > 0)
732
+ return edgeLabelFontSize;
733
+ return undefined;
734
+ }
545
735
  const linear = (progress) => progress;
546
736
  /**
547
737
  * The easing of a CSS `cubic-bezier(x1, y1, x2, y2)` token value. Any other
@@ -613,4 +803,5 @@ export function sameRects(left, right) {
613
803
  }
614
804
  return true;
615
805
  }
806
+ export { scaleEdgeLabelMeasurer };
616
807
  //# sourceMappingURL=diagramSceneModel.js.map
@@ -1,6 +1,7 @@
1
1
  import type { LayoutOptions, LayoutHints, LayoutMetrics, LayoutResult, LineMeasurer, RowPackOptions } from '../index.js';
2
2
  import type { CardLineMeasure, DiagramGlyphPaths } from './diagramCardModel.js';
3
3
  import type { StepChange, EffectiveTarget } from './flowModel.js';
4
+ import type { LinkLegendAnchor } from './linkLegend.js';
4
5
  import type { SceneDocument, SceneView, ScenePresentation, SceneOccurrenceRef, SceneLayoutCache, DiagramSceneSize } from './diagramSceneModel.js';
5
6
  export interface DiagramSceneFigureLabels {
6
7
  "navigator": string;
@@ -25,6 +26,8 @@ export interface DiagramSceneFigureLabels {
25
26
  collapse: (title: string) => string;
26
27
  /** Localized fallback label for containment relations without an explicit edge label (DE-1b). */
27
28
  contains?: string;
29
+ /** Heading for the automatic link-style legend strip (DE-2). */
30
+ legend?: string;
28
31
  }
29
32
  export interface DiagramSceneCamera {
30
33
  readonly zoom: number;
@@ -66,6 +69,10 @@ export interface DiagramSceneFigureProps {
66
69
  strictIcons?: boolean;
67
70
  /** Selectable start parity for alternating zone depth surfaces (`0` default, `1` flipped). */
68
71
  depthParityStart?: 0 | 1;
72
+ /** Automatic link-style legend anchor (`"right"` default; `"none"` suppresses; single-style scenes never emit one). */
73
+ legend?: LinkLegendAnchor;
74
+ /** Optional custom labels for automatic link-style legend entries, keyed by `linkStyleKey(...)`. */
75
+ legendLabels?: Readonly<Record<string, string>>;
69
76
  /** Layout line measurer. Defaults to the bridge over `measure`. */
70
77
  measureLines?: LineMeasurer;
71
78
  /** Controlled fold state: collapsed occurrence ids. */
@@ -76,6 +83,8 @@ export interface DiagramSceneFigureProps {
76
83
  /** Accessible name of the figure. Defaults to `title`. */
77
84
  label?: string;
78
85
  compact?: boolean;
86
+ /** Opt-in fit-to-window host framing (`max-height: calc(100vh - 24px)`, `max-width: 100%`, centred; DE-2 ask 9). Default `false` preserves `Z-3 / AC-23`. */
87
+ fitToWindow?: boolean;
79
88
  labels?: Partial<DiagramSceneFigureLabels>;
80
89
  resolveGlyph?: (name: string) => DiagramGlyphPaths | undefined;
81
90
  onFoldChange?: (collapsed: readonly SceneOccurrenceRef[], change: {
@@ -1,4 +1,8 @@
1
1
  export { renderSceneSvg } from "./renderSceneSvg.js";
2
+ export { ARROW_DIRECTION_CONVENTION, DEFAULT_ZONE_TAG_ACRONYM_ALLOWLIST, isOpaqueAcronymZoneTag, lintArrowDirection, lintDiagramConventions, lintZoneTagAcronyms, type ArrowDirectionEdgeInput, type DiagramConventionLintOptions, type LintArrowDirectionInput, type LintDiagramConventionsInput, type LintZoneTagAcronymsInput, type ZoneTagLintEntry, } from "../layout/conventions.js";
3
+ export { connectorPath, parseConnectorPath, DEFAULT_EDGE_CORNER_RADIUS } from "./connectorPath.js";
4
+ export { ARROWHEAD_MARKER_GEOMETRY, connectorDashArray, connectorMarkerIds, connectorMarkerKind, connectorMarkerRef, extraConnectorMarkers, type ConnectorMarkerEdgeInput, type ConnectorMarkerIds, type ConnectorMarkerSpec, } from "./connectorStyle.js";
5
+ export { buildSceneLinkLegend, collectLinkLegendStyles, defaultLinkStyleLabel, LINK_LEGEND_ARROWHEAD_ORDER, LINK_LEGEND_EMPHASIS_ORDER, LINK_LEGEND_FONT_SIZE, LINK_LEGEND_GAP, LINK_LEGEND_HEADER_GAP, LINK_LEGEND_HEADER_HEIGHT, LINK_LEGEND_MIN_WIDTH, LINK_LEGEND_PADDING, LINK_LEGEND_ROW_GAP, LINK_LEGEND_ROW_HEIGHT, LINK_LEGEND_STROKE_ORDER, LINK_LEGEND_SWATCH_GAP, LINK_LEGEND_SWATCH_HEIGHT, LINK_LEGEND_SWATCH_WIDTH, linkLegendBoxStyle, linkLegendSwatchGeometry, linkStyleKey, type BuildSceneLinkLegendInput, type LinkLegendAnchor, type LinkLegendEdgeInput, type LinkLegendEntry, type LinkLegendStyleKey, type LinkLegendSwatchGeometry, type SceneLinkLegend, } from "./linkLegend.js";
2
6
  import { renderCardSvg, renderCardSvgFromPresentation, projectCardProps, type CardSvgResult } from "./renderCardSvg.js";
3
7
  import { renderZoneSvg, renderZoneSvgFromPresentation, projectZoneProps, zoneContent, type ZoneSvgResult } from "./renderZoneSvg.js";
4
8
  import { cardLineMeasurer, type CardLineLayout, type CardMeasureRequest } from "./diagramCardModel.js";
@@ -1,4 +1,8 @@
1
1
  export { renderSceneSvg } from "./renderSceneSvg.js";
2
+ export { ARROW_DIRECTION_CONVENTION, DEFAULT_ZONE_TAG_ACRONYM_ALLOWLIST, isOpaqueAcronymZoneTag, lintArrowDirection, lintDiagramConventions, lintZoneTagAcronyms, } from "../layout/conventions.js";
3
+ export { connectorPath, parseConnectorPath, DEFAULT_EDGE_CORNER_RADIUS } from "./connectorPath.js";
4
+ export { ARROWHEAD_MARKER_GEOMETRY, connectorDashArray, connectorMarkerIds, connectorMarkerKind, connectorMarkerRef, extraConnectorMarkers, } from "./connectorStyle.js";
5
+ export { buildSceneLinkLegend, collectLinkLegendStyles, defaultLinkStyleLabel, LINK_LEGEND_ARROWHEAD_ORDER, LINK_LEGEND_EMPHASIS_ORDER, LINK_LEGEND_FONT_SIZE, LINK_LEGEND_GAP, LINK_LEGEND_HEADER_GAP, LINK_LEGEND_HEADER_HEIGHT, LINK_LEGEND_MIN_WIDTH, LINK_LEGEND_PADDING, LINK_LEGEND_ROW_GAP, LINK_LEGEND_ROW_HEIGHT, LINK_LEGEND_STROKE_ORDER, LINK_LEGEND_SWATCH_GAP, LINK_LEGEND_SWATCH_HEIGHT, LINK_LEGEND_SWATCH_WIDTH, linkLegendBoxStyle, linkLegendSwatchGeometry, linkStyleKey, } from "./linkLegend.js";
2
6
  import { renderCardSvg, renderCardSvgFromPresentation, projectCardProps, } from "./renderCardSvg.js";
3
7
  import { renderZoneSvg, renderZoneSvgFromPresentation, projectZoneProps, zoneContent, } from "./renderZoneSvg.js";
4
8
  import { cardLineMeasurer, } from "./diagramCardModel.js";
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Automatic link-style legend for `SceneModel` (DE-2, OWNER-ADDENDA ask 4).
3
+ *
4
+ * Inspects the visible connector styles actually drawn in the current fold
5
+ * state, orders them in a fixed canonical order, and places a self-contained
6
+ * legend strip anchored on an edge (right by default) outside the flow of
7
+ * functional zones. Suppressed automatically when fewer than two distinct
8
+ * connector styles are visible, or when `anchor === "none"`.
9
+ *
10
+ * Pure geometry and presentation data: zero DOM, zero framework dependencies.
11
+ */
12
+ import type { CanonicalArrowheadKind, LinkEmphasis, StrokeStyle } from "@sentropic/diagram-core";
13
+ import type { LineMeasurer } from "../layout/measure.js";
14
+ import type { LayoutMetrics } from "../layout/types.js";
15
+ import type { Rect } from "../transform.js";
16
+ /** Where the automatic link-style legend strip sits relative to the functional drawing. */
17
+ export type LinkLegendAnchor = "right" | "bottom" | "none";
18
+ /** Canonical sort orders over the three closed connector registry axes. */
19
+ export declare const LINK_LEGEND_STROKE_ORDER: readonly StrokeStyle[];
20
+ export declare const LINK_LEGEND_EMPHASIS_ORDER: readonly LinkEmphasis[];
21
+ export declare const LINK_LEGEND_ARROWHEAD_ORDER: readonly CanonicalArrowheadKind[];
22
+ /** World-unit geometry constants shared by SVG, Svelte and Vue renderers. */
23
+ export declare const LINK_LEGEND_GAP = 48;
24
+ export declare const LINK_LEGEND_PADDING = 16;
25
+ export declare const LINK_LEGEND_HEADER_HEIGHT = 30;
26
+ export declare const LINK_LEGEND_HEADER_GAP = 8;
27
+ export declare const LINK_LEGEND_SWATCH_WIDTH = 56;
28
+ export declare const LINK_LEGEND_SWATCH_HEIGHT = 16;
29
+ export declare const LINK_LEGEND_SWATCH_GAP = 14;
30
+ export declare const LINK_LEGEND_ROW_HEIGHT = 28;
31
+ export declare const LINK_LEGEND_ROW_GAP = 8;
32
+ export declare const LINK_LEGEND_MIN_WIDTH = 240;
33
+ export declare const LINK_LEGEND_FONT_SIZE = 18;
34
+ export interface LinkLegendEdgeInput {
35
+ readonly markers?: string;
36
+ readonly directed?: boolean;
37
+ readonly strokeStyle?: StrokeStyle;
38
+ readonly arrowhead?: "arrow" | CanonicalArrowheadKind;
39
+ readonly emphasis?: LinkEmphasis;
40
+ }
41
+ export interface LinkLegendStyleKey {
42
+ readonly strokeStyle: StrokeStyle;
43
+ readonly arrowhead: CanonicalArrowheadKind;
44
+ readonly emphasis: LinkEmphasis;
45
+ }
46
+ export interface LinkLegendEntry extends LinkLegendStyleKey {
47
+ /** Deterministic key: `<strokeStyle>:<arrowhead>:<emphasis>`. */
48
+ readonly key: string;
49
+ /** Human-readable label shown beside the sample swatch. */
50
+ readonly label: string;
51
+ /** Count of visible connectors using this style in the current fold state. */
52
+ readonly count: number;
53
+ /** Top offset of this row inside the legend box (world units). */
54
+ readonly rowY: number;
55
+ /** Height of this row inside the legend box (world units). */
56
+ readonly rowHeight: number;
57
+ }
58
+ export interface SceneLinkLegend {
59
+ readonly anchor: Exclude<LinkLegendAnchor, "none">;
60
+ readonly title: string;
61
+ /** Outer bounding rectangle in world coordinates, outside the functional flow. */
62
+ readonly rect: Rect;
63
+ /** Visible styles in fixed canonical order (always length >= 2). */
64
+ readonly entries: readonly LinkLegendEntry[];
65
+ readonly padding: number;
66
+ readonly headerHeight: number;
67
+ readonly headerGap: number;
68
+ readonly rowHeight: number;
69
+ readonly rowGap: number;
70
+ readonly swatchWidth: number;
71
+ readonly swatchHeight: number;
72
+ readonly swatchGap: number;
73
+ readonly fontSize: number;
74
+ }
75
+ export interface LinkLegendSwatchGeometry {
76
+ readonly viewBox: string;
77
+ readonly width: number;
78
+ readonly height: number;
79
+ readonly linePath: string;
80
+ readonly arrowPath?: string;
81
+ readonly stroke: string;
82
+ readonly strokeWidth: number;
83
+ readonly dashArray?: string;
84
+ readonly arrowFill?: string;
85
+ readonly arrowStroke?: string;
86
+ readonly arrowStrokeWidth?: number;
87
+ }
88
+ /** Stable canonical key for a connector style triple. */
89
+ export declare function linkStyleKey(style: LinkLegendStyleKey): string;
90
+ /** Default human-readable label derived strictly from the closed registry words. */
91
+ export declare function defaultLinkStyleLabel(style: LinkLegendStyleKey): string;
92
+ /**
93
+ * Collect distinct visible connector styles in fixed canonical order.
94
+ * Returns an empty list when fewer than two distinct styles are drawn
95
+ * (single-style and edgeless scenes omit the legend).
96
+ */
97
+ export declare function collectLinkLegendStyles(edges: readonly LinkLegendEdgeInput[]): readonly (LinkLegendStyleKey & {
98
+ readonly key: string;
99
+ readonly count: number;
100
+ })[];
101
+ export interface BuildSceneLinkLegendInput {
102
+ readonly edges: readonly LinkLegendEdgeInput[];
103
+ readonly contentBounds: Rect | undefined;
104
+ readonly measureLines: LineMeasurer;
105
+ /** Anchor edge strip (`"right"` by default). `"none"` suppresses the legend. */
106
+ readonly anchor?: LinkLegendAnchor;
107
+ /** Legend heading text (defaults to `"Legend"`). */
108
+ readonly title?: string;
109
+ /** Optional custom labels keyed by `linkStyleKey(...)`. */
110
+ readonly labels?: Readonly<Record<string, string>>;
111
+ /** Optional world-unit font size override (defaults to `edgeLabelSize`, 18). */
112
+ readonly fontSize?: number;
113
+ }
114
+ /**
115
+ * Compute the automatic link-style legend and its anchored world rectangle
116
+ * outside `contentBounds`. Returns `undefined` when suppressed or when fewer
117
+ * than two distinct styles are drawn.
118
+ */
119
+ export declare function buildSceneLinkLegend(input: BuildSceneLinkLegendInput): SceneLinkLegend | undefined;
120
+ /**
121
+ * Shared inline CSS positioning and geometry custom properties for HTML legend
122
+ * hosts (Svelte and Vue), keeping every box, header, gap, row and swatch pixel
123
+ * identical to `buildSceneLinkLegend` and `renderSceneSvg` at every `edgeLabelSize`.
124
+ */
125
+ export declare function linkLegendBoxStyle(legend: SceneLinkLegend, opacity?: number): string;
126
+ /**
127
+ * Inline SVG swatch geometry for a legend entry. Draws the sample line and
128
+ * arrowhead directly without `<marker>` ids so SVG, Svelte and Vue stay
129
+ * id-collision-free and DOM-identical.
130
+ */
131
+ export declare function linkLegendSwatchGeometry(style: LinkLegendStyleKey, widths?: Pick<LayoutMetrics, "linkStrokeWidth" | "linkRelatedStrokeWidth" | "linkEmphasisStrokeWidth">): LinkLegendSwatchGeometry;
132
+ //# sourceMappingURL=linkLegend.d.ts.map