@sentropic/diagram-canvas 0.0.0-stage → 0.2.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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE.THIRD-PARTY.md +28 -0
  3. package/README.md +434 -2
  4. package/contracts/diagram-anatomy.v1.json +2073 -0
  5. package/dist/camera.d.ts +72 -0
  6. package/dist/camera.js +64 -0
  7. package/dist/geometry.d.ts +57 -0
  8. package/dist/geometry.js +179 -0
  9. package/dist/hit.d.ts +87 -0
  10. package/dist/hit.js +117 -0
  11. package/dist/index.d.ts +26 -0
  12. package/dist/index.js +26 -0
  13. package/dist/layout/bundleLabel.d.ts +12 -0
  14. package/dist/layout/bundleLabel.js +16 -0
  15. package/dist/layout/cache.d.ts +28 -0
  16. package/dist/layout/cache.js +195 -0
  17. package/dist/layout/channels.d.ts +28 -0
  18. package/dist/layout/channels.js +14 -0
  19. package/dist/layout/dock.d.ts +110 -0
  20. package/dist/layout/dock.js +303 -0
  21. package/dist/layout/engine.d.ts +129 -0
  22. package/dist/layout/engine.js +959 -0
  23. package/dist/layout/erd.d.ts +5 -0
  24. package/dist/layout/erd.js +85 -0
  25. package/dist/layout/fingerprint.d.ts +18 -0
  26. package/dist/layout/fingerprint.js +89 -0
  27. package/dist/layout/flow-order.d.ts +3 -0
  28. package/dist/layout/flow-order.js +14 -0
  29. package/dist/layout/flows.d.ts +89 -0
  30. package/dist/layout/flows.js +120 -0
  31. package/dist/layout/graph.d.ts +72 -0
  32. package/dist/layout/graph.js +150 -0
  33. package/dist/layout/hints.d.ts +88 -0
  34. package/dist/layout/hints.js +156 -0
  35. package/dist/layout/index.d.ts +23 -0
  36. package/dist/layout/index.js +23 -0
  37. package/dist/layout/labels.d.ts +110 -0
  38. package/dist/layout/labels.js +228 -0
  39. package/dist/layout/measure.d.ts +111 -0
  40. package/dist/layout/measure.js +99 -0
  41. package/dist/layout/measured.d.ts +31 -0
  42. package/dist/layout/measured.js +2178 -0
  43. package/dist/layout/pack.d.ts +92 -0
  44. package/dist/layout/pack.js +209 -0
  45. package/dist/layout/place.d.ts +110 -0
  46. package/dist/layout/place.js +422 -0
  47. package/dist/layout/rank.d.ts +57 -0
  48. package/dist/layout/rank.js +169 -0
  49. package/dist/layout/route.d.ts +142 -0
  50. package/dist/layout/route.js +821 -0
  51. package/dist/layout/sceneMeasure.d.ts +13 -0
  52. package/dist/layout/sceneMeasure.js +57 -0
  53. package/dist/layout/spacing.generated.d.ts +13 -0
  54. package/dist/layout/spacing.generated.js +8 -0
  55. package/dist/layout/types.d.ts +239 -0
  56. package/dist/layout/types.js +58 -0
  57. package/dist/presentation/diagramCardModel.d.ts +660 -0
  58. package/dist/presentation/diagramCardModel.js +1150 -0
  59. package/dist/presentation/diagramSceneModel.d.ts +248 -0
  60. package/dist/presentation/diagramSceneModel.js +447 -0
  61. package/dist/presentation/diagramSceneTypes.d.ts +91 -0
  62. package/dist/presentation/diagramSceneTypes.js +2 -0
  63. package/dist/presentation/erd.d.ts +81 -0
  64. package/dist/presentation/erd.js +156 -0
  65. package/dist/presentation/flowModel.d.ts +82 -0
  66. package/dist/presentation/flowModel.js +206 -0
  67. package/dist/presentation/index.d.ts +20 -0
  68. package/dist/presentation/index.js +14 -0
  69. package/dist/presentation/registry.d.ts +52 -0
  70. package/dist/presentation/registry.js +81 -0
  71. package/dist/presentation/renderCardSvg.d.ts +73 -0
  72. package/dist/presentation/renderCardSvg.js +144 -0
  73. package/dist/presentation/renderSceneSvg.d.ts +38 -0
  74. package/dist/presentation/renderSceneSvg.js +56 -0
  75. package/dist/presentation/renderZoneSvg.d.ts +79 -0
  76. package/dist/presentation/renderZoneSvg.js +180 -0
  77. package/dist/scene.d.ts +126 -0
  78. package/dist/scene.js +240 -0
  79. package/dist/transform.d.ts +127 -0
  80. package/dist/transform.js +219 -0
  81. package/dist/visibility.d.ts +98 -0
  82. package/dist/visibility.js +231 -0
  83. package/package.json +65 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 rhanka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,28 @@
1
+ <!-- GÉNÉRÉ par scripts/generate-third-party-notices.mjs — ne pas éditer à la main. -->
2
+ <!-- Régénérer : `npm run notices:generate`. La dérive fait échouer `npm run licensing:check`. -->
3
+
4
+ # Notices de tiers — `@sentropic/diagram-canvas`
5
+
6
+ Licence de ce paquet : **MIT** — voir `LICENSE`.
7
+ Ce fichier couvre le code **tiers**, et lui seul.
8
+
9
+ Périmètre, littéralement : le code tiers recopié dans ce paquet (§1) et la
10
+ fermeture transitive de ses dépendances d'exécution (§2). Hors périmètre, et
11
+ c'est délibéré : les `peerDependencies`, fournies par le consommateur, et les
12
+ `devDependencies`, qui n'entrent dans aucun tarball.
13
+
14
+ ## 1. Code tiers recopié dans ce paquet
15
+
16
+ **Rien de mesuré.** Ce qui a été cherché, littéralement : les données de
17
+ tracé publiées par `lucide`, comparées octet pour octet aux sources de ce
18
+ paquet. Aucune n'y figure.
19
+
20
+ Ce qui n'a **pas** été cherché : tout amont non déclaré dans
21
+ `scripts/third-party-sources.json`. L'absence ci-dessus est donc l'absence
22
+ de ces données-là, et non un constat d'absence générale de code tiers dans
23
+ ce paquet.
24
+
25
+ ## 2. Dépendances installées avec ce paquet
26
+
27
+ Aucune. Ce paquet ne déclare aucune dépendance tierce : installer ce paquet
28
+ n'installe aucun code tiers de notre fait.
package/README.md CHANGED
@@ -1,3 +1,435 @@
1
- # Temporary Holding Version
1
+ # @sentropic/diagram-canvas
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The headless **scene** and its **hit test** for a diagram view, and the
4
+ **layout engine** that produces a view from a semantic document. Pure computation:
5
+ no DOM, no renderer, no framework, no design system package. One bare import
6
+ specifier, `@sentropic/diagram-core`.
7
+
8
+ This is the first slice of `GD-M2-CANVAS`. It delivers the `Scene` /
9
+ `GeometryFrame` of the study's five objects (§4.1) and the geometric selection
10
+ primitives of §7; the layout engine (SPEC_EVOL_DS_JSON_RENDER_STANDARD §10.5,
11
+ L8) was added after it. What it deliberately leaves out is listed
12
+ under *What is not covered yet*, with the lot that owns each item.
13
+
14
+ ## Publication
15
+
16
+ The manifest is publishable since DC-2a (SPEC_EVOL_DC2A Appendix D, BF-5): no
17
+ `private` flag, `publishConfig.access: "public"`, and `files` shipping `dist`
18
+ without maps or the build stamp — the same shape as `@sentropic/diagram-core`.
19
+ The reason is the edge `@sentropic/design-system-svelte → @sentropic/diagram-canvas`
20
+ (the scene host `DiagramSceneFigure`), which `docs/graph-dataviz-architecture-dag.json`
21
+ declares: a published package that names a private dependency installs broken
22
+ for every consumer, the failure `pack:smoke` caught once in this repository
23
+ (see the header of `scripts/verify-layering.test.mjs` on PR #65).
24
+
25
+ It is published through `.github/workflows/diagram-canvas-publish.yml` on tags
26
+ `diagram-canvas-v<version>` (CI only; release order in `docs/release.md`:
27
+ diagram-core → diagram-canvas → tokens if changed → svelte). Until
28
+ `@sentropic/diagram-canvas@0.1.0` is on the registry, the fail-closed step of
29
+ `svelte-publish.yml` (`scripts/verify-deps-published.mjs`) refuses to publish
30
+ the Svelte package, by design.
31
+
32
+ Its only dependency, `@sentropic/diagram-core`, is public and pinned exact.
33
+ Inside the workspace it resolves by link, which `package-lock.json` records as
34
+ `"resolved": "packages/diagram-core", "link": true` — no registry URL. The
35
+ publishable package count is pinned by
36
+ `scripts/verify-publishable-licensing.test.mjs`; it is not restated here.
37
+
38
+ ## The three contracts this slice fixes
39
+
40
+ `diagram-core` persists data and states, in as many words, that the meaning of
41
+ some of it belongs here. Each of the three is fixed in one module, with the
42
+ reasoning in that module's header.
43
+
44
+ ### 1. The camera, and the one transform — `transform.ts`
45
+
46
+ `PresentationState.camera` is `{ x, y, zoom }`. `validateView` checks the three
47
+ are finite and that `zoom > 0`. **Nothing in `diagram-core` says what `x` and `y`
48
+ mean** — not `view.ts`, not its README, not a fixture. The comment there says only
49
+ that "a renderer adapter maps these three numbers to its own camera contract;
50
+ that adapter is GD-M2-CANVAS work".
51
+
52
+ This package fixes the reading:
53
+
54
+ > `camera.x`, `camera.y` are the **world point drawn at the view origin**, and
55
+ > `camera.zoom` is **CSS pixels per world unit**.
56
+
57
+ Chosen over a centre-based reading because it needs no viewport size, so
58
+ `worldToView` is a function of the camera alone and a scene can be built and
59
+ hit-tested with no viewport at all.
60
+
61
+ `worldToDevice(camera, viewport)` is the whole world → view → CSS pixel → device
62
+ pixel chain of study invariant 8, and `hitTestAtDevicePoint` **inverts that same
63
+ composition** rather than deriving its own. A test sweeps three cameras × three
64
+ viewports × five probe points and asserts the device-space answer and the
65
+ world-space answer name the same occurrence.
66
+
67
+ Note for a future `diagram-canvas → graph` edge: `packages/graph/src/gitflow-labels.ts`
68
+ carries a **different, centre-based** camera reading (`(wx - camera.x) * zoom +
69
+ camera.width / 2`) in four private closures, over a `GitFlowLabelCamera` that also
70
+ holds `width`/`height`. Two readings coexist in the repository today. Unifying
71
+ them means changing a published package's semantics, which is not this lot's to
72
+ do — it is recorded here so it is not discovered by surprise.
73
+
74
+ ### 2. Filter evaluation and the cascade — `visibility.ts`
75
+
76
+ `diagram-core` declares, validates and persists `ViewFilter` and says it does not
77
+ evaluate it, naming this lot. Four points the schema leaves open are decided
78
+ there, each with its reason: how several filters of one kind combine, what
79
+ `attribute-equals` applies to, what it means for a `collection` attribute (which
80
+ has `items` and **no `value` field**, so the schema comment cannot be read
81
+ literally), and the cascade — **a relation occurrence whose endpoint is hidden is
82
+ excluded with reason `endpoint-hidden` and reported**, never dropped, because
83
+ study invariant 1 forbids an edge disappearing in silence.
84
+
85
+ ### 3. Paint order and hit regions — `scene.ts`, `hit.ts`
86
+
87
+ `EntityOccurrence.z` is the only paint-order field in the model; a
88
+ `RelationOccurrence` and a `PortOccurrence` have none. So the scene derives a
89
+ **total** order — plane, then kind (edge, node, port), then port order, then
90
+ occurrence reference — a port inheriting its owner's plane and an edge taking the
91
+ lowest plane of the occurrences it joins. `hitTest` walks that same order
92
+ backwards, so "topmost" cannot disagree with what a renderer draws on top.
93
+
94
+ Two measured details that shaped the code rather than being assumed:
95
+
96
+ - **`width` and `height` may be negative.** `validateView` checks only that
97
+ geometry values are *finite*; there is no non-negativity branch. So
98
+ `{ x: 40, y: 25, width: -30, height: -20 }` is valid persisted data, and a
99
+ scene that read `x .. x + width` as the span would make that shape
100
+ unselectable while every normalising renderer drew it perfectly.
101
+ `normaliseRect` is therefore required, not a nicety.
102
+ - **Negative zero is normalised away.** `invert(IDENTITY)` returned `-0` in four
103
+ of six components on the first run. `-0 === 0`, so nothing miscomputed, but
104
+ `Object.is(-0, 0)` is false while `canonicalise` writes both as `0` — two
105
+ frames could compare unequal and hash identically, which is the one thing a
106
+ revision must never do.
107
+
108
+ ## `sceneRevision` holds no camera
109
+
110
+ The frame carries no camera, deliberately. A pan or a zoom changes no geometry
111
+ and no paint order, so folding the camera in would move `sceneRevision` on every
112
+ wheel event and destroy its only use. Asserted both ways: panning and zooming
113
+ leaves the revision alone, and moving one coordinate by one unit moves it.
114
+
115
+ `sceneRevision` is `fnv1a64` through `diagram-core`'s `hashContent` —
116
+ **non-cryptographic**, like that package's own caveat. It detects change; it
117
+ proves nothing.
118
+
119
+ ## Conservation
120
+
121
+ Every occurrence of the view is either an item of the frame or an entry of
122
+ `exclusions`, exactly once. `sceneOccurrenceCount(frame)` is that sum and a test
123
+ compares it with the view's own count, including under the cascade that removes
124
+ most of the view. An occurrence dropped in silence breaks it, and an empty scene
125
+ cannot satisfy it unless the view was empty too.
126
+
127
+ ## The graph edge this slice does not pose
128
+
129
+ `docs/graph-dataviz-architecture-dag.json` declares `diagram-canvas → graph`.
130
+ This slice does **not** pose it, and `tests/no-dom.test.ts` forbids the import so
131
+ the omission is enforced rather than merely intended. The reason: this scene is
132
+ built from **persisted view geometry**, where every rectangle carries its own
133
+ width and height, so there is no layout to run and no drawn radius to derive.
134
+ The layout engine (see Layout) does not change that: it writes such geometry
135
+ into a `ViewDocument` and imports nothing from `@sentropic/graph`.
136
+
137
+ When the canvas later hit-tests a **graph-rendered** scene — nodes sized from
138
+ `nodeSizes` through `drawnRadius`, edges tessellated into curves — it MUST consume
139
+ `packages/graph/src/render-geometry.ts`, which declares itself the single source
140
+ "so Canvas2D, WebGL, and the hit-test all consume ONE computation". Recomputing
141
+ those radii here would be the hit↔render drift that module exists to prevent.
142
+ That is the next slice's obligation, and it is written down here so it is not
143
+ rediscovered.
144
+
145
+ ## What is not covered yet
146
+
147
+ | Not here | Owner |
148
+ |---|---|
149
+ | Selection state, marquee lifecycle, focus, keyboard traversal | next `GD-M2-CANVAS` slice |
150
+ | Geometric port editing (moving a port along a side, re-siding it) | next `GD-M2-CANVAS` slice, by SPEC 3.5 |
151
+ | Annotations and circling | `GD-M2-CANVAS`, later |
152
+ | Framework adapters (Svelte / React / Vue / Angular) | `GD-M2-DS-PRESENTATION` and the four DS packages |
153
+ | Rendering: SVG, Canvas2D, WebGL, export | `@sentropic/graph`'s renderer and later slices |
154
+ | Labels in the scene | the layout engine measures text through an injected function and places labels (`placeEdgeLabels`); `SceneFrame` still carries no label item |
155
+ | The group box of a collapsed group, and aggregate edges | later; this lot evaluates the `collapsed` flag and nothing more |
156
+ | Projection, `LayoutOutcome.inverse` | `@sentropic/graph/processing`, already delivered; the L-R1–L-R11 layout is here (see Layout) |
157
+ | Lasso and polygon selection | later; point and rectangle are what a selection needs first |
158
+ | A spatial index (quadtree, grid) | not yet warranted — see below |
159
+ | The renderer's viewport part of L-R7 (measure the effective content width, set the box to exactly it, pass it as `W`, re-lay out on change) | no renderer lives in this package (L8): `targetWidth` carries the measured width in, covered by `tests/layout/ac-l8-geometry.test.ts`; the box-setting itself stays not covered |
160
+
161
+ ### Why no spatial index
162
+
163
+ Hit testing is a linear scan over `SceneFrame.items`. Measured on this machine
164
+ (Node v22.22.1) rather than assumed, with `scripts/` untouched — see
165
+ `spec/SPEC_EVOL_GD_M2_CANVAS.md` §6 for the figures and the command. An index
166
+ would be the right answer above a node count this slice's scenes do not reach,
167
+ and adding one before the measurement said so would have been a second spatial
168
+ structure to keep correct. `packages/graph` already holds two private ones
169
+ (`OccupancyGrid` in `gitflow-labels.ts`, the Barnes-Hut `Quad` in
170
+ `processing/graph-layout.ts`); neither answers a point query, and neither is
171
+ exported.
172
+
173
+ ## Layout
174
+
175
+ `layoutDocument(document, options)` is the layout engine of SPEC §10.5: it
176
+ implements the rules L-R1–L-R11, written in this repository from the rule text.
177
+ Pure TypeScript in `src/layout/`, no DOM, no dependency beyond
178
+ `@sentropic/diagram-core`.
179
+
180
+ **Input.** A `diagram-core` `SemanticDocument` under `generic@1`: `node` and
181
+ `container` entities, `link` relations, nesting through the `contains` tree, with
182
+ no view and no geometry. It goes through `validateDocument` first; an invalid
183
+ document is refused with those diagnostics, verbatim (`document-invalid`). A
184
+ relation or entity the engine does not lay out (`association`, another profile)
185
+ is refused by name, never dropped. `options` holds the profile registry, the
186
+ effective viewport inner width (`targetWidth`, content-box CSS px, measured by
187
+ the renderer — or the host acting for it — at layout time, never a wider nominal
188
+ host width) and a **text measurer**: the engine has no font metric source, so
189
+ the host injects one, and must draw labels with the same one. Tests use a
190
+ fixed-width measurer.
191
+
192
+ **Output.** A `diagram-core` `ViewDocument`, which `validateView` accepts, and
193
+ no other structure to persist:
194
+
195
+ - one entity occurrence per entity, with its bounds; containers have `z` below
196
+ nodes (outermost lowest), nodes `z = 0`;
197
+ - one relation occurrence per `link`, whose `waypoints` are the whole route,
198
+ dock to dock, source to target (`relationRoute` reads it back); `contains` is
199
+ drawn by nesting and has no relation occurrence;
200
+ - one port occurrence per semantic port a link targets, with the side, slot order
201
+ and anchor the docking chose — one shared occurrence per port, except parallel
202
+ ends, which each take their own occurrence identified by relation and role;
203
+ - `presentation.camera.zoom` is the L-R7 scale.
204
+
205
+ The call also returns `fit` (direction, size at scale 1, zoom, `pans`, `phone`)
206
+ and `warnings` for what it could not fully satisfy (`label-unplaced`,
207
+ `label-budget-exhausted`, `route-obstructed`, `row-fill-partial`), reported
208
+ rather than dropped. A zero, negative or non-finite `targetWidth` is refused
209
+ as `target-width-invalid`, with no view and no scale.
210
+
211
+ | Rule | What the engine does | Fixture |
212
+ |---|---|---|
213
+ | L-R1 side choice and lone edge at the centre | flow side first when separated on that axis; cross side on along-flow overlap; greater centre-offset axis on double overlap (horizontal on a tie); ancestor pairs on the inner entity's nearest wall (ties east, south, west, north); self-loops out east/south, back north/west; a lone end at the exact centre | `tests/layout/rules.test.ts`, `tests/layout/amended.test.ts` |
214
+ | L-R2 shared side spread symmetrically | slots by the representative end's other centre (smallest by relation id, role), ties by slot key; a parallel end never takes the port key (`~port` for a non-parallel port end, else `relation#role`); `s` from `slotSpacing`, raised for labelled sides, node growth to `s(n+1)` effective from the next attempt | idem, `tests/layout/sol-pass2.test.ts` |
215
+ | L-R3 bends minimised after docking, route tie-break | A* on boundaries, channel midlines and clearance points; bend count first, weighted length next (×3 on another pair's units, same-pair units forbidden); ties by frontier (estimated cost, then row, column, heading); checked against an independent 0-1 BFS oracle | idem |
216
+ | L-R4 row constitution, alignment and fill | rows constituted once per attempt from the pre-row geometry — one rank top-to-bottom, one overlap component left-to-right split into rank-compatible rows (never two of one rank); rank start and rank extent, or common cross start and size, with push-down to the minimum separation including any L-R10 `siblingExtra`; at most 20 rounds, else `row-fill-partial` for that level | idem, `tests/layout/ac-l8-geometry.test.ts` |
217
+ | L-R5 flow direction, measured after labels | both drawings finalized (L-R10 attempts complete) before comparing the bounds-union widths `B` (`xmax − xmin` over entity rectangles, dock-to-dock routes and placed label boxes): left-to-right when `B_lr ≤ W`, else top-to-bottom when `B_tb ≤ W`, else the narrower, top-to-bottom on a tie; a function of graph and `W` only | idem, `tests/layout/ac-l8-geometry.test.ts` |
218
+ | L-R6 rank, cycles, self-loops, sibling order | per-level lifted edges, same-member lifts skipped; self-loops skipped everywhere (no rank, no dummy, direction kept); cycles broken in ascending relation id (greatest on each cycle reversed, ranking only); longest-path rank; one dummy per intermediate rank (`~`-suffixed, after entities); barycentre from key order, at most 24 sweeps, (weight, key) sort, best seen kept | idem, `tests/layout/sol.test.ts` |
219
+ | L-R7 target width, scale and phone fallback | `W` is the effective viewport inner width; `s = min(1, max(0.75, W / B))` on the chosen finalized union width (`B = 0`: left-to-right, zoom 1, no pan); pans exactly when `B·s > W`; the reported width is `B`; L-R5 chooses at every width | idem, `tests/layout/ac-l8-geometry.test.ts` |
220
+ | L-R8 edges across containers | every node and container is an obstacle, grown by `clearance`, except the strict ancestors of either end; segments run on grown boundaries at most; the only exception is `route-obstructed` | idem |
221
+ | L-R9 parallel edges | a relation is parallel when another shares its unordered entity pair (direction ignored; two self-loops on one entity are parallel); never a shared slot at either end, including on a shared port; same slot order at both ends; a grid unit used by an edge of the same unordered pair is forbidden to the next | idem, `tests/layout/sol.test.ts`, `tests/layout/sol-pass2.test.ts` |
222
+ | L-R10 edge labels | centred, unrotated, on the longest holdable segment (decreasing length, ascending index; ascending relation id across labels); otherwise at most 12 placement attempts, one composite request per label per attempt (rank plus every sibling amount, by maximum, effective next attempt; the 12th attempt's requests are recorded, never applied); canonical gap (nearest, deepest, lowest rank, earliest level); every blocker evaluated, both transformations independently; a cross-flow too-short segment is closed for requests; (c) only for a lane-owned blocker; the cap rejects one transformation only; progress-guard withdrawal is budget, never proof; `label-unplaced` only when every segment is proof-closed under (a)–(d), otherwise `label-budget-exhausted`, never merged | idem, `tests/layout/sol.test.ts`, `tests/layout/sol-pass2.test.ts` |
223
+ | L-R11 legend | none: the view holds no legend occurrence, group or field, and the options have no switch | `tests/layout/rules.test.ts` |
224
+
225
+ Determinism: the same document laid out twice, and with its entity, relation
226
+ and `contains` records shuffled, gives byte-identical `serialiseView` output
227
+ (`tests/layout/determinism.test.ts`). Time: a document of 40 nodes in 3 nesting
228
+ levels (9 containers, 44 links, 4 labels, one cycle) lays out in a median of
229
+ about 9–15 ms on the development machine (Node v22.22.1), against a 1000 ms
230
+ budget in `tests/layout/performance.test.ts`, which prints the figure.
231
+
232
+ Limits, stated rather than hidden:
233
+
234
+ - A label is `label-unplaced` only when every segment is proof-closed on the
235
+ final geometry: no requestable transformation and every failing dimension
236
+ under (a) across-flow and too short, (b) a flow-aligned deficit with no
237
+ crossing or holding gap, (c) a lane-owned shape spanning the padded label on
238
+ both sides, (d) lane and blocker sharing one member at every pairing. One
239
+ fixture per reason lives in `tests/layout/amended.test.ts`, each
240
+ re-evaluated with `residualUnplaceable` and `diagnoseLabels`; (e) over the
241
+ cap, the progress-guard stall and the request outstanding after 12 rounds
242
+ are the three `label-budget-exhausted` exits, pinned in the same file.
243
+ - A label that still has a widening request after the 12th round is
244
+ `label-budget-exhausted`, never `label-unplaced`. Seen on the 40-node
245
+ fixture laid out left to right (`relation:x4`, a hand-off label thrown over
246
+ the top of the drawing), pinned in `tests/layout/rules.test.ts`.
247
+ - A docking point on an entity occurrence is held as the first or last waypoint:
248
+ a relation occurrence endpoint drawn on an entity cannot hold one, and a port
249
+ occurrence may only draw the relation's own semantic port
250
+ (`diagram-core/src/validate.ts`, the `occurrence-endpoint-mismatch` check).
251
+ `buildScene` therefore adds a stub from the entity's centre to that first
252
+ waypoint (`src/scene.ts`), which lies inside the entity and is painted under it.
253
+ - Cross positions come from barycentric isotonic placement per level, not a
254
+ global straightening pass: a long edge can bend around a rank where a lane is
255
+ not aligned with its docks. L-R3 holds for the docks it gets.
256
+ - Semantic ports no link targets get no port occurrence.
257
+
258
+ ## Source tree
259
+
260
+ ```
261
+ src/transform.ts the camera contract and the one world -> device composition
262
+ src/geometry.ts rectangles, points, segments, polylines; the two conventions
263
+ src/visibility.ts filter evaluation, the cascade, the exclusion reasons
264
+ src/scene.ts SceneFrame, port anchors, relation routes, paint order
265
+ src/hit.ts point, region and device-space hit testing
266
+ src/layout/ the layout engine, L-R1–L-R11 (see Layout)
267
+ tests/ 8 suites; types-nominal.test.ts is a COMPILER test
268
+ tests/layout/ one fixture per layout rule, contract, determinism, time budget, h2a dossiers
269
+ ```
270
+
271
+ ## Gates
272
+
273
+ ```
274
+ npm run --workspace @sentropic/diagram-canvas build # tsc -> dist
275
+ npm run --workspace @sentropic/diagram-canvas check # tsc over src AND tests
276
+ npm run --workspace @sentropic/diagram-canvas test # vitest, node environment
277
+ ```
278
+
279
+ `check` compiles the tests on purpose. `tests/types-nominal.test.ts` proves the
280
+ nominal references survive this package's boundary with one `@ts-expect-error` per
281
+ illegitimate assignment; widen `sceneItemOf`'s parameter to `string` and `check`
282
+ reports three × TS2578 ("Unused '@ts-expect-error' directive") — measured, not
283
+ assumed. Remove one key from `REASON_KEYS` and it reports TS2741 naming the
284
+ missing reason.
285
+
286
+ Unlike `node --test`, `vitest run` exits **1** when its include pattern resolves
287
+ to nothing (measured: `npx vitest run --root packages/diagram-canvas
288
+ 'tests/**/*.nomatch-zzz.ts'` prints "No test files found, exiting with code 1").
289
+ So this package's test gate cannot go green on an empty set, and needs no file
290
+ floor of its own.
291
+
292
+ ## Row-pack placement (DC-2a)
293
+
294
+ Spec: `spec/SPEC_EVOL_DC2A_ROWPACK_AUTOLAYOUT.md`. Every measured view
295
+ (`layoutMeasured` / `layoutFolded`) is row-packed: every level, the root and
296
+ each expanded zone alike, is shelf-packed toward a 16:9 outer aspect. The
297
+ optional `rowPack` option only tunes the objective (target aspect, tall bias,
298
+ empty penalty, hysteresis); absent or empty, the DS defaults apply.
299
+
300
+ - `packRows` / `packColumns` (`layout/pack.ts`) fill boxes into shelves in
301
+ declaration order, score each candidate on its distance to the target aspect
302
+ (taller than target is penalised more) plus a shelf-slack term, and never
303
+ reorder siblings. With two boxes or more, the candidate that stacks every
304
+ box in one single vertical column is inadmissible in both forms.
305
+ - `chooseOrientation` scores both forms per level and keeps the lower total
306
+ score, so the orientation follows the fold state. The result reports
307
+ `orientations` per level key (`"root"` or the placement-parent representative
308
+ occurrence id); a host feeds it back as `previousOrientation`, and a level
309
+ whose two scores are closer than `orientationHysteresis` keeps its previous
310
+ orientation.
311
+ - Authored `hints.grouping` partitions a level before packing: each group is
312
+ its own sub-level packed in its authored direction — `rows` = horizontal
313
+ shelves read left to right then down, `columns` = vertical shelves read top
314
+ to bottom then right — and the ungrouped siblings form one more packed run
315
+ (orientation key `<level>#rest`). Both directions changed meaning with
316
+ DC-2a: `rows` used to be one vertical stack and `columns` one horizontal
317
+ row. `gapAfter` replaces the base gap after its group.
318
+ - Sibling gaps are the base gap on both axes (`metrics.rowGapInline` /
319
+ `rowGapBlock`, default 24, tokens `diagramZone.childGapInline` /
320
+ `childGapBlock`). Placement is two-pass: pass 1 packs at the base gaps,
321
+ routes and places labels, and its shelves are frozen; later passes widen
322
+ only the gutters in which a label had no room — by the label thickness plus
323
+ its two margins, never past `metrics.gapInlineMax` / `gapBlockMax`
324
+ (default 32) — and release every widened gutter that ends up holding no
325
+ label. The root uses the same gaps and never `rankGap`. A gap hint (or a
326
+ `gapAfter`) above the cap refuses as `layout-hint-invalid`; an invalid
327
+ objective refuses as `row-pack-invalid`.
328
+ - `hints.rootOrder` gives the root reading order; `hints.ordering` keeps
329
+ giving it per zone.
330
+ - Routes: an edge whose two ends share an expanded container stays inside the
331
+ content box of that container (`RouteRequest.within`); the title band of an
332
+ expanded container is an obstacle for every route. A labelled edge between
333
+ two side-by-side boxes docks both ends on one same side and runs along the
334
+ lane under (or over) them, where its label fits.
335
+ - Labels: the result carries `labelBoxes`, the box of every placed edge
336
+ label by relation occurrence id. A label sits on its route but not
337
+ necessarily centred on it (`placePackedLabel`); one the capped gutters
338
+ cannot hold has no box and one `label-unplaced` warning. A host draws labels
339
+ from `labelBoxes` and unions them into its fit bounds.
340
+ - `layoutFingerprint` (`layout/fingerprint.ts`) is the cache-key digest of a
341
+ measured call over resolved numbers: fold state, row-pack objective, gaps
342
+ and caps, previous-orientation map, hints, token numbers, engine version.
343
+ `createLayoutCache` wraps the complete call using this fingerprint (DC-2b).
344
+
345
+ `camera.ts` holds the pure half of the camera contract (spec §5):
346
+ `cameraFit` frames the scene bounds on both axes against the 16:9 fit box
347
+ (`fitW = viewW`, `fitH = min(viewW × 9/16, 0.85 × windowH)`), never above the
348
+ maximum display scale (0.62: readout 100 %, a card renders at about
349
+ 285 × 124 CSS px) and holds a fit at the readability floor (0.45: an 18 px
350
+ edge label renders at 8.1 CSS px) when the drawing is larger, reporting
351
+ `pans`; `clampZoom` and `zoomReadout` complete it. No DOM lives here: a scene
352
+ host passes its measured sizes in.
353
+
354
+ The acceptance scenes, the §7 metrics helper, the column baseline as recorded
355
+ before the placement changed (`baseline.json`), the numbers of the shipped
356
+ engine (`after.json`), the gates it misses by name (`misses.json`), the fold
357
+ stability pins (`stability.json`) and the §7.5 tuning grid (`tuning.json`)
358
+ are under `tests/layout/dc2a/`. Measured-path timings: the three cluster
359
+ scenes (25–32 boxes, 20–23 links) lay out in a median of 112–176 ms, against
360
+ the 1000 ms budget of `tests/layout/performance.test.ts`.
361
+
362
+ ## DC-2b performance
363
+
364
+ `createLayoutCache()` is an opt-in, framework-neutral wrapper over the complete
365
+ layout and routing pipeline. Each host owns one instance, or receives a cache
366
+ from its caller. Defaults are **32 entries** and **16 MiB** of estimated UTF-8
367
+ view, measurement and label-box bytes, with LRU eviction. Refusals and oversized
368
+ results are returned without retention. `has()` leaves counters and recency
369
+ unchanged; `clear()` releases entries; idempotent `dispose()` permanently disables
370
+ hits and insertion. Statistics remain cumulative after either operation.
371
+
372
+ Keys consume the DC-2a fingerprint and include target width, compatibility
373
+ metrics (including the effective `hints.rankGap` override), document/presentation/source-view content, profile declarations and
374
+ bindings, and a version plus role probe of the injected measurer. Effective
375
+ folds are sorted and deduplicated. Compatible previous-orientation fixed points
376
+ reuse the original entry; a genuine hysteresis flip misses. Orientation aliases
377
+ are bounded too. Camera and motion tokens are excluded; layout tokens invalidate.
378
+ Documents, views, presentations and profile declarations must remain immutable:
379
+ their content digests use per-instance weak keys. Replace a measurer reference
380
+ or update its optional `version` when its metrics change. Production hits return
381
+ the original result by reference; `verifyImmutability: true` additionally checks
382
+ the stored view on every hit and throws on caller mutation.
383
+
384
+ The `@sentropic/diagram-canvas/diagramSceneModel` subpath exports the shared
385
+ presentation model and the named `SceneLayoutCache` host type. `LayoutCacheConfig`
386
+ aliases the existing cache options. `layoutScene({ cache, ...input })` uses that same seam for
387
+ both hosts; `resolveScene` reads emitted label boxes and measured label lines
388
+ without repeating placement or measurement. `sceneContentSize(result)` and
389
+ `SceneModel.contentSize` expose the union size at zoom 1 (zero when absent,
390
+ refused or empty). Camera fit, zoom and placement remain pure calculations over
391
+ the current scene, including on container resize. No scene frames are retained
392
+ per fold state, and the engine creates no background work or rendering resources.
393
+
394
+ Measured in Vitest/Node 22.22.1 on 2026-11-12, with the existing 10 s timeout:
395
+
396
+ | Gate | Witness/test | Measured | Bound |
397
+ | --- | --- | --- | --- |
398
+ | AC-P1 stress heap | `cache-performance.test.ts`, cache + `resolveScene`, 240 complete fold/unfold cycles after two warm-up cycles | 0.239 MiB | ≤ 5 MiB |
399
+ | AC-P1 idle heap | Same, 60 s virtual time + 500 ms real drain | −0.003 MiB | ≤ 1 MiB |
400
+ | AC-P2 idle | `diagramSceneModel.test.ts`, 60 s virtual + 1 s real drain; source guard | 0 timer/frame/observer/worker/layout calls | 0 |
401
+ | AC-P3 revisit | `vue-globale/after`, 240 hits | 0.098 ms p95; 2 entries, 91,807 bytes | ≤ 5 ms; ≤ 32 / 16 MiB |
402
+ | AC-P3 capacity | `cache.test.ts`, two passes over 32 states, then a separate 40-state sequence | 32 hits / 0 evictions; 8 oldest evicted for 40 states | 32 retained states |
403
+ | AC-P4 model camera | 120 pan + 120 zoom steps and resize | 0.025 ms p95; 0 cache/scene/measurement calls | ≤ 16.7 ms; 0 calls |
404
+ | AC-P5 engine disposal | Ten create/fold/dispose cycles per sample | 0.194 MiB; 0 retained entries/bytes | ≤ 2 MiB |
405
+ | AC-P6 shared size | Refused, empty and laid-out results | Exact `fit.width` × `fit.height`, or 0 × 0 | Exact equality |
406
+ | M3 engine/model | 600 actions, including 240 stress toggles | Worst 184.849 ms | < 1800 ms |
407
+
408
+ Heap numbers use V8 forced GC before each reading, an event-loop turn between
409
+ two collections, and median-of-three samples. The ten-cycle disposal samples
410
+ are separate tests so each fits the unchanged timeout. Cold cache calls have
411
+ median/worst **198.878/245.786 ms** on `vue-globale/after`, and
412
+ **61.465/64.943 ms** on `largeDocumentSpec()`; neither reaches the 900 ms worker
413
+ follow-up trigger. These are engine/model measurements; host integration gates
414
+ are listed in [the host handoff](../../patches/DC2B_HOST_WIRING.md).
415
+
416
+ Reproduce from `packages/diagram-canvas`:
417
+
418
+ ```sh
419
+ rtk npx vitest run --maxWorkers=1
420
+ rtk npx tsc -p tsconfig.check.json
421
+ rtk npm run build
422
+ ```
423
+
424
+ For printed measurements, use `rtk proxy node ../../node_modules/vitest/vitest.mjs
425
+ run tests/layout/cache-performance.test.ts tests/presentation/diagramSceneModel.test.ts
426
+ --disableConsoleIntercept --reporter=verbose --maxWorkers=1` (one shell command).
427
+
428
+ ## Numbered flows (DC-2c.1)
429
+
430
+ Measured layouts support `flows.fanOutMax` (default 4), `countTemplate`, engine
431
+ flow tokens, bundles, arrows, badges and internal targets. The pure
432
+ `@sentropic/diagram-canvas/flowModel` subpath owns interaction semantics and
433
+ static `flowMarksSvg`; selection/filter changes require no layout. Shared host
434
+ acceptance cases are imported directly from unpublished `test-support` source. See
435
+ [the contract, Vue handoff and limitations](../../docs/DC2C_NUMBERED_FLOWS.md).