@sentropic/design-system-svelte 0.39.0 → 0.40.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.
@@ -0,0 +1,841 @@
1
+ <script lang="ts">
2
+ import { tick, untrack } from "svelte";
3
+ import { Minus, Plus } from "@lucide/svelte";
4
+ import {
5
+ clampZoom,
6
+ createLayoutCache,
7
+ FIT_ASPECT,
8
+ zoomReadout,
9
+ type LayoutHints,
10
+ type LayoutMetrics,
11
+ type LayoutOptions,
12
+ type LayoutResult,
13
+ type LineMeasurer,
14
+ type Rect,
15
+ type RowPackOptions,
16
+ } from "@sentropic/diagram-canvas";
17
+ import Button from "./Button.svelte";
18
+ import DiagramCard from "./DiagramCard.svelte";
19
+ import DiagramZone from "./DiagramZone.svelte";
20
+ import IconButton from "./IconButton.svelte";
21
+ import {
22
+ cardLineMeasurer,
23
+ defaultCardMeasure,
24
+ projectCardProps,
25
+ projectZoneProps,
26
+ type CardLineMeasure,
27
+ type DiagramGlyphPaths,
28
+ } from "./diagramCardModel.js";
29
+ import {
30
+ collapsedOccurrencesOf,
31
+ sceneContentSize,
32
+ type DiagramSceneSize,
33
+ type SceneLayoutCache,
34
+ DEFAULT_SCENE_TARGET_WIDTH,
35
+ displayedRects,
36
+ layoutScene,
37
+ parseDurationMs,
38
+ parseEasing,
39
+ parseScale,
40
+ rectsOf,
41
+ resolveScene,
42
+ resolveZoom,
43
+ sameRects,
44
+ sceneFit,
45
+ scenePlacement,
46
+ WHEEL_ZOOM_RATE,
47
+ ZOOM_STEP_RATIO,
48
+ type Easing,
49
+ type SceneDocument,
50
+ type SceneModel,
51
+ type SceneNodeModel,
52
+ type SceneOccurrenceRef,
53
+ type SceneOrientations,
54
+ type ScenePresentation,
55
+ type SceneView,
56
+ } from "@sentropic/diagram-canvas/diagramSceneModel";
57
+
58
+ /**
59
+ * `DiagramSceneFigure` — the generic scene host (DC-2a lot L4,
60
+ * SPEC_EVOL_DC2A §4.3, §5, §6.7 and Appendix D; CARDS §7.6).
61
+ *
62
+ * The figure lays a scene out with the `@sentropic/diagram-canvas`
63
+ * row-pack engine and draws it at emitted geometry with `DiagramCard` /
64
+ * `DiagramZone`. It keeps no packer of its own.
65
+ *
66
+ * Camera (Z-1–Z-8). Readout 100 % is the maximum display scale (token
67
+ * `diagramScene.maxDisplayScale`), never zoom 1: no input — buttons,
68
+ * keys, Ctrl + wheel, pinch, `setZoom` — goes above it. The fit frames
69
+ * the scene bounds plus the placed label boxes on both axes inside the
70
+ * fit box `viewW × min(viewW × 9/16, 0.85 × windowH)`; it holds at the
71
+ * readability floor (token `diagramScene.minReadableScale`), where the
72
+ * viewport scrolls the overflowing axis from its start, and zoom-out
73
+ * still reaches the whole drawing. The camera is never seeded from the
74
+ * layout fit report. Zoom is a transform: it re-runs no layout.
75
+ *
76
+ * Folds. A fold toggle re-runs the whole layout, feeding the previous
77
+ * orientation record back so a level keeps its orientation inside the
78
+ * hysteresis band (O-4), reclamps the zoom into the new range, then
79
+ * moves every box from its displayed to its new rectangle over the
80
+ * `diagramScene.transitionDuration` token with the
81
+ * `foundation.motion.easing` token. Under `prefers-reduced-motion:
82
+ * reduce`, read at toggle time, the new geometry applies at once. A
83
+ * toggle during a transition retargets from the displayed rectangles.
84
+ *
85
+ * The figure owns no model: the documents are props, and the fold state
86
+ * is either controlled (`collapsed` + `onFoldChange`) or starts from
87
+ * `defaultFolds` / the source view's fold groups.
88
+ *
89
+ * SSR-safe: `window`, `document` and the observers are read in effects
90
+ * and handlers only; a server render draws the scene at its fit in a
91
+ * nominal 16:9 box.
92
+ */
93
+ export interface DiagramSceneFigureLabels {
94
+ /** Accessible name of the camera control group. */
95
+ controls: string;
96
+ zoomIn: string;
97
+ zoomOut: string;
98
+ /** Visible text of the fit / reset control (« Ajuster »). */
99
+ fit: string;
100
+ /** Accessible name of the readout, e.g. « Zoom 85 % ». */
101
+ zoomLevel: (percent: number) => string;
102
+ /** Accessible name of the scrollable drawing region. */
103
+ viewport: string;
104
+ expand: (title: string) => string;
105
+ collapse: (title: string) => string;
106
+ }
107
+
108
+ export interface DiagramSceneCamera {
109
+ readonly zoom: number;
110
+ /** `round(zoom / maxDisplayScale × 100)`. */
111
+ readonly readout: number;
112
+ readonly minZoom: number;
113
+ readonly maxZoom: number;
114
+ /** The zoom a fit or reset applies. */
115
+ readonly fitZoom: number;
116
+ readonly pans: boolean;
117
+ }
118
+
119
+ export interface DiagramSceneFigureProps {
120
+ document: SceneDocument;
121
+ /** Retained source view (occurrences, fold groups). Optional: the engine synthesises one. */
122
+ view?: SceneView;
123
+ registry: LayoutOptions["registry"];
124
+ bindings?: LayoutOptions["bindings"];
125
+ presentation: ScenePresentation;
126
+ /** Declaration order (`rootOrder`, `ordering[parent]`) and the other layout hints. */
127
+ hints?: LayoutHints;
128
+ /** Runtime token numbers for the engine (gaps, caps). */
129
+ metrics?: Partial<LayoutMetrics>;
130
+ rowPack?: RowPackOptions;
131
+ /** L-R7 report width. The measured path never re-packs on it (D-3). */
132
+ targetWidth?: number;
133
+ /** Card text measurer, shared by the cards, the zones and the layout. */
134
+ measure?: CardLineMeasure;
135
+ /** Layout line measurer. Defaults to the bridge over `measure`. */
136
+ measureLines?: LineMeasurer;
137
+ /** Controlled fold state: collapsed occurrence ids. */
138
+ collapsed?: readonly SceneOccurrenceRef[];
139
+ /** Initial collapsed occurrence ids when `collapsed` is not controlled. */
140
+ defaultFolds?: readonly SceneOccurrenceRef[];
141
+ title?: string;
142
+ /** Accessible name of the figure. Defaults to `title`. */
143
+ label?: string;
144
+ compact?: boolean;
145
+ labels?: Partial<DiagramSceneFigureLabels>;
146
+ resolveGlyph?: (name: string) => DiagramGlyphPaths | undefined;
147
+ onFoldChange?: (
148
+ collapsed: readonly SceneOccurrenceRef[],
149
+ change: { occurrence: SceneOccurrenceRef; collapsed: boolean },
150
+ ) => void;
151
+ onSelect?: (event: { entityId: string }) => void;
152
+ /** One call per layout pass, with the engine result (warnings, refusals, orientations). */
153
+ onLayout?: (result: LayoutResult) => void;
154
+ onCameraChange?: (camera: DiagramSceneCamera) => void;
155
+ layoutCache?: SceneLayoutCache;
156
+ contentSize?: DiagramSceneSize;
157
+ onSizeChange?: (size: DiagramSceneSize) => void;
158
+ }
159
+
160
+ const DEFAULT_LABELS: DiagramSceneFigureLabels = {
161
+ controls: "Zoom",
162
+ zoomIn: "Zoom in",
163
+ zoomOut: "Zoom out",
164
+ fit: "Fit",
165
+ zoomLevel: (percent) => `Zoom ${percent} %`,
166
+ viewport: "Diagram",
167
+ expand: (title) => `Expand ${title}`,
168
+ collapse: (title) => `Collapse ${title}`,
169
+ };
170
+
171
+ const TOKEN_MAX_DISPLAY_SCALE = "--st-component-diagramScene-maxDisplayScale";
172
+ const TOKEN_MIN_READABLE_SCALE = "--st-component-diagramScene-minReadableScale";
173
+ const TOKEN_TRANSITION_DURATION = "--st-component-diagramScene-transitionDuration";
174
+ const TOKEN_EASING = "--st-foundation-motion-easing";
175
+ const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
176
+
177
+ let {
178
+ document: semanticDocument,
179
+ view,
180
+ registry,
181
+ bindings,
182
+ presentation,
183
+ hints,
184
+ metrics,
185
+ rowPack,
186
+ targetWidth,
187
+ measure = defaultCardMeasure,
188
+ measureLines,
189
+ collapsed,
190
+ defaultFolds,
191
+ title,
192
+ label,
193
+ compact = false,
194
+ labels,
195
+ resolveGlyph,
196
+ onFoldChange,
197
+ onSelect,
198
+ onLayout,
199
+ onCameraChange,
200
+ layoutCache,
201
+ contentSize = $bindable({ width: 0, height: 0 }),
202
+ onSizeChange,
203
+ }: DiagramSceneFigureProps = $props();
204
+
205
+ const ownedCache = createLayoutCache();
206
+ let publishedSize: DiagramSceneSize | undefined;
207
+
208
+ const strings = $derived({ ...DEFAULT_LABELS, ...labels });
209
+
210
+ /* ── fold state and layout ─────────────────────────────────────── */
211
+
212
+ let foldState = $state.raw<readonly SceneOccurrenceRef[]>(
213
+ untrack(() => defaultFolds ?? collapsedOccurrencesOf(view)),
214
+ );
215
+ const collapsedNow = $derived(collapsed ?? foldState);
216
+ const lineMeasurer = $derived<LineMeasurer>(measureLines ?? cardLineMeasurer(measure));
217
+
218
+ // O-4: the orientation record last emitted, fed back to the next layout
219
+ // call. Deliberately not reactive state: it is an input of the next pass,
220
+ // never a reason to run one. A different document starts with no record.
221
+ let previousOrientation: SceneOrientations | undefined;
222
+ let orientationDocument: string | undefined;
223
+
224
+ const layoutResult = $derived.by<LayoutResult>(() => {
225
+ if (orientationDocument !== semanticDocument.documentId) {
226
+ orientationDocument = semanticDocument.documentId;
227
+ previousOrientation = undefined;
228
+ }
229
+ const result = layoutScene({
230
+ cache: layoutCache ?? ownedCache,
231
+ document: semanticDocument,
232
+ ...(view === undefined ? {} : { view }),
233
+ registry,
234
+ ...(bindings === undefined ? {} : { bindings }),
235
+ presentation,
236
+ measureLines: lineMeasurer,
237
+ collapsed: collapsedNow,
238
+ ...(hints === undefined ? {} : { hints }),
239
+ ...(metrics === undefined ? {} : { metrics }),
240
+ ...(rowPack === undefined ? {} : { rowPack }),
241
+ ...(targetWidth === undefined ? {} : { targetWidth }),
242
+ ...(previousOrientation === undefined ? {} : { previousOrientation }),
243
+ });
244
+ if (result.status === "laid-out" && result.orientations !== undefined) {
245
+ previousOrientation = result.orientations;
246
+ }
247
+ return result;
248
+ });
249
+
250
+ const scene = $derived<SceneModel | undefined>(
251
+ layoutResult.status === "laid-out"
252
+ ? resolveScene(layoutResult, {
253
+ document: semanticDocument,
254
+ presentation,
255
+ measureLines: lineMeasurer,
256
+ ...(metrics === undefined ? {} : { metrics }),
257
+ })
258
+ : undefined,
259
+ );
260
+ const sceneRects = $derived<ReadonlyMap<string, Rect>>(scene === undefined ? new Map() : rectsOf(scene));
261
+
262
+ $effect(() => {
263
+ const result = layoutResult;
264
+ untrack(() => onLayout?.(result));
265
+ });
266
+
267
+ $effect(() => {
268
+ const size = sceneContentSize(layoutResult);
269
+ if (publishedSize?.width === size.width && publishedSize?.height === size.height) return;
270
+ publishedSize = size;
271
+ contentSize = size;
272
+ untrack(() => onSizeChange?.(size));
273
+ });
274
+
275
+ /* ── measured frame and tokens (client only) ───────────────────── */
276
+
277
+ let frameEl = $state<HTMLElement>();
278
+ let viewportEl = $state<HTMLElement>();
279
+ let viewWidth = $state<number>();
280
+ let windowHeight = $state<number>();
281
+ let maxDisplayScale = $state<number>();
282
+ let minReadableScale = $state<number>();
283
+
284
+ function tokenValue(name: string): string | undefined {
285
+ if (frameEl === undefined) return undefined;
286
+ const value = getComputedStyle(frameEl).getPropertyValue(name).trim();
287
+ return value === "" ? undefined : value;
288
+ }
289
+
290
+ // The camera sits at the fit until an input moves it; a resize keeps a
291
+ // camera that is still at the fit on the fit, and reclamps any other.
292
+ let requestedZoom = $state<number>();
293
+ let atFit = true;
294
+
295
+ // m3: camera tokens are re-read on every measure and before every camera
296
+ // input, so a post-mount theme change applies without waiting for a resize.
297
+ function readCameraTokens(): void {
298
+ maxDisplayScale = parseScale(tokenValue(TOKEN_MAX_DISPLAY_SCALE));
299
+ minReadableScale = parseScale(tokenValue(TOKEN_MIN_READABLE_SCALE));
300
+ }
301
+
302
+ function measureFrame(): void {
303
+ if (frameEl === undefined) return;
304
+ // m6: the fit width is the viewport narrowed by its scrollbar, not the
305
+ // frame wrapper.
306
+ const viewportWidth = viewportEl?.clientWidth ?? 0;
307
+ const width = viewportWidth > 0 ? viewportWidth : frameEl.clientWidth;
308
+ viewWidth = width > 0 ? width : undefined;
309
+ windowHeight = window.innerHeight > 0 ? window.innerHeight : undefined;
310
+ readCameraTokens();
311
+ if (atFit) requestedZoom = undefined;
312
+ }
313
+
314
+ $effect(() => {
315
+ const element = frameEl;
316
+ if (element === undefined) return;
317
+ untrack(measureFrame);
318
+ const onResize = (): void => measureFrame();
319
+ window.addEventListener("resize", onResize);
320
+ const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(onResize);
321
+ observer?.observe(element);
322
+ return () => {
323
+ window.removeEventListener("resize", onResize);
324
+ observer?.disconnect();
325
+ };
326
+ });
327
+
328
+ /* ── camera (Z-1–Z-8) ──────────────────────────────────────────── */
329
+
330
+ const measured = $derived(viewWidth !== undefined && windowHeight !== undefined);
331
+ const fit = $derived(
332
+ sceneFit({
333
+ ...(scene?.bounds === undefined ? {} : { bounds: scene.bounds }),
334
+ // Before the frame is measured (server render, hidden mount) the fit
335
+ // box is the nominal 16:9 box of the layout target width.
336
+ viewWidth: viewWidth ?? targetWidth ?? DEFAULT_SCENE_TARGET_WIDTH,
337
+ windowHeight: windowHeight ?? Number.POSITIVE_INFINITY,
338
+ ...(maxDisplayScale === undefined ? {} : { maxDisplayScale }),
339
+ ...(minReadableScale === undefined ? {} : { minReadableScale }),
340
+ }),
341
+ );
342
+ const zoom = $derived(resolveZoom(requestedZoom, fit));
343
+ const readout = $derived(zoomReadout(zoom, fit.maxZoom));
344
+ const placement = $derived(scenePlacement(scene?.bounds, zoom, fit));
345
+ const canZoomIn = $derived(zoom < fit.maxZoom);
346
+ const canZoomOut = $derived(zoom > fit.minZoom);
347
+
348
+ // A new scene starts at its fit (Z-8).
349
+ let cameraDocument: string | undefined;
350
+ $effect.pre(() => {
351
+ const id = semanticDocument.documentId;
352
+ if (cameraDocument !== undefined && cameraDocument !== id) {
353
+ atFit = true;
354
+ requestedZoom = undefined;
355
+ }
356
+ cameraDocument = id;
357
+ });
358
+
359
+ // Z-7: once the frame is measured the camera holds a number, clamped to
360
+ // the nearest bound of the current range; a zoom inside the range stays.
361
+ $effect(() => {
362
+ if (!measured) return;
363
+ const current = zoom;
364
+ const fitZoom = fit.zoom;
365
+ untrack(() => {
366
+ if (requestedZoom !== current) requestedZoom = current;
367
+ if (current !== fitZoom) atFit = false;
368
+ });
369
+ });
370
+
371
+ $effect(() => {
372
+ const camera: DiagramSceneCamera = {
373
+ zoom,
374
+ readout,
375
+ minZoom: fit.minZoom,
376
+ maxZoom: fit.maxZoom,
377
+ fitZoom: fit.zoom,
378
+ pans: placement.overflowX || placement.overflowY,
379
+ };
380
+ untrack(() => onCameraChange?.(camera));
381
+ });
382
+
383
+ /** Z-1: any request lands inside the current range. The viewport centre is kept where scrolling allows. */
384
+ export function setZoom(next: number): void {
385
+ if (!Number.isFinite(next)) return;
386
+ readCameraTokens();
387
+ const before = zoom;
388
+ const target = clampZoom(next, fit);
389
+ atFit = target === fit.zoom;
390
+ if (target === before) return;
391
+ const element = viewportEl;
392
+ const centre =
393
+ element === undefined
394
+ ? undefined
395
+ : {
396
+ x: (element.scrollLeft + element.clientWidth / 2 - placement.translateX) / before,
397
+ y: (element.scrollTop + element.clientHeight / 2 - placement.translateY) / before,
398
+ };
399
+ requestedZoom = target;
400
+ if (element === undefined || centre === undefined) return;
401
+ void tick().then(() => {
402
+ element.scrollLeft = centre.x * zoom + placement.translateX - element.clientWidth / 2;
403
+ element.scrollTop = centre.y * zoom + placement.translateY - element.clientHeight / 2;
404
+ });
405
+ }
406
+
407
+ export function zoomIn(): void {
408
+ setZoom(zoom * ZOOM_STEP_RATIO);
409
+ }
410
+
411
+ export function zoomOut(): void {
412
+ setZoom(zoom / ZOOM_STEP_RATIO);
413
+ }
414
+
415
+ /** Z-3/Z-4: fit and reset are one action. An overflowing axis scrolls from its start. */
416
+ export function fitToFrame(): void {
417
+ readCameraTokens();
418
+ atFit = true;
419
+ requestedZoom = fit.zoom;
420
+ const element = viewportEl;
421
+ if (element === undefined) return;
422
+ void tick().then(() => {
423
+ element.scrollLeft = 0;
424
+ element.scrollTop = 0;
425
+ });
426
+ }
427
+
428
+ export function getCamera(): DiagramSceneCamera {
429
+ return {
430
+ zoom,
431
+ readout,
432
+ minZoom: fit.minZoom,
433
+ maxZoom: fit.maxZoom,
434
+ fitZoom: fit.zoom,
435
+ pans: placement.overflowX || placement.overflowY,
436
+ };
437
+ }
438
+
439
+ function onKeydown(event: KeyboardEvent): void {
440
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
441
+ // m5: shortcuts work from non-input descendants (card buttons, nodes);
442
+ // only typing targets keep the keys.
443
+ const target = event.target as HTMLElement | null;
444
+ if (target !== null && target !== event.currentTarget) {
445
+ const tag = target.tagName;
446
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable) return;
447
+ }
448
+ if (event.key === "+" || event.key === "=") zoomIn();
449
+ else if (event.key === "-" || event.key === "_") zoomOut();
450
+ else if (event.key === "0") fitToFrame();
451
+ else return;
452
+ event.preventDefault();
453
+ }
454
+
455
+ // Ctrl + wheel (and the trackpad pinch browsers report as Ctrl + wheel)
456
+ // zooms; a plain wheel scrolls. Registered non-passive so the page zoom
457
+ // is not triggered as well.
458
+ $effect(() => {
459
+ const element = viewportEl;
460
+ if (element === undefined) return;
461
+ const onWheel = (event: WheelEvent): void => {
462
+ if (!event.ctrlKey && !event.metaKey) return;
463
+ event.preventDefault();
464
+ setZoom(zoom * Math.exp(-event.deltaY * WHEEL_ZOOM_RATE));
465
+ };
466
+ element.addEventListener("wheel", onWheel, { passive: false });
467
+ return () => element.removeEventListener("wheel", onWheel);
468
+ });
469
+
470
+ // Two-finger pinch on a touch screen.
471
+ const touches = new Map<number, { x: number; y: number }>();
472
+ let pinch: { distance: number; zoom: number } | undefined;
473
+ const touchDistance = (): number => {
474
+ const [first, second] = [...touches.values()];
475
+ return first === undefined || second === undefined ? 0 : Math.hypot(first.x - second.x, first.y - second.y);
476
+ };
477
+ function onPointerDown(event: PointerEvent): void {
478
+ if (event.pointerType !== "touch") return;
479
+ touches.set(event.pointerId, { x: event.clientX, y: event.clientY });
480
+ pinch = touches.size === 2 ? { distance: touchDistance(), zoom } : undefined;
481
+ }
482
+ function onPointerMove(event: PointerEvent): void {
483
+ if (!touches.has(event.pointerId)) return;
484
+ touches.set(event.pointerId, { x: event.clientX, y: event.clientY });
485
+ if (pinch === undefined || pinch.distance <= 0) return;
486
+ event.preventDefault();
487
+ setZoom(pinch.zoom * (touchDistance() / pinch.distance));
488
+ }
489
+ function onPointerEnd(event: PointerEvent): void {
490
+ touches.delete(event.pointerId);
491
+ pinch = undefined;
492
+ }
493
+
494
+ /* ── fold transition (T-1–T-4) ─────────────────────────────────── */
495
+
496
+ let origin = $state.raw<ReadonlyMap<string, Rect>>();
497
+ let progress = $state(1);
498
+ let easing: Easing = (value) => value;
499
+ let duration = 0;
500
+ let startedAt = 0;
501
+ let frameHandle: number | undefined;
502
+ // The rectangles on screen after the last render: the start of the next
503
+ // transition, interpolated ones included (T-4).
504
+ let shown: ReadonlyMap<string, Rect> | undefined;
505
+ let shownDocument: string | undefined;
506
+
507
+ const eased = $derived(origin === undefined ? 1 : easing(progress));
508
+ const displayed = $derived(origin === undefined ? sceneRects : displayedRects(origin, sceneRects, eased));
509
+ const animating = $derived(origin !== undefined);
510
+
511
+ function stopFrames(): void {
512
+ if (frameHandle !== undefined) cancelAnimationFrame(frameHandle);
513
+ frameHandle = undefined;
514
+ }
515
+
516
+ function settle(): void {
517
+ stopFrames();
518
+ origin = undefined;
519
+ progress = 1;
520
+ }
521
+
522
+ function step(): void {
523
+ frameHandle = undefined;
524
+ const elapsed = performance.now() - startedAt;
525
+ if (elapsed >= duration) {
526
+ settle();
527
+ return;
528
+ }
529
+ progress = elapsed / duration;
530
+ frameHandle = requestAnimationFrame(step);
531
+ }
532
+
533
+ // Runs before the DOM is patched with a new layout, so the first frame
534
+ // of a transition already draws the displayed rectangles, never a jump.
535
+ $effect.pre(() => {
536
+ const next = sceneRects;
537
+ const documentId = semanticDocument.documentId;
538
+ untrack(() => {
539
+ const from = shown;
540
+ const sameScene = shownDocument === documentId;
541
+ shownDocument = documentId;
542
+ if (from === undefined || !sameScene || sameRects(from, next)) {
543
+ settle();
544
+ return;
545
+ }
546
+ // T-3: the reduced-motion preference is read at toggle time.
547
+ const reduced = typeof window.matchMedia === "function" && window.matchMedia(REDUCED_MOTION_QUERY).matches;
548
+ duration = reduced ? 0 : parseDurationMs(tokenValue(TOKEN_TRANSITION_DURATION));
549
+ if (duration <= 0) {
550
+ settle();
551
+ return;
552
+ }
553
+ // T-4: retarget from what is displayed; no queue of stale targets.
554
+ stopFrames();
555
+ easing = parseEasing(tokenValue(TOKEN_EASING));
556
+ origin = from;
557
+ progress = 0;
558
+ startedAt = performance.now();
559
+ frameHandle = requestAnimationFrame(step);
560
+ });
561
+ });
562
+
563
+ $effect(() => {
564
+ shown = displayed;
565
+ });
566
+
567
+ $effect(() => () => {
568
+ stopFrames();
569
+ touches.clear();
570
+ pinch = undefined;
571
+ ownedCache.dispose();
572
+ });
573
+
574
+ /* ── drawing ───────────────────────────────────────────────────── */
575
+
576
+ const rectOf = (node: SceneNodeModel): Rect => displayed.get(node.occurrence) ?? node.rect;
577
+ const entering = (node: SceneNodeModel): boolean => origin !== undefined && !origin.has(node.occurrence);
578
+
579
+ function toggleFold(node: SceneNodeModel): void {
580
+ const next = node.collapsed
581
+ ? collapsedNow.filter((id) => id !== node.occurrence)
582
+ : [...collapsedNow, node.occurrence];
583
+ if (collapsed === undefined) foldState = next;
584
+ onFoldChange?.(next, { occurrence: node.occurrence, collapsed: !node.collapsed });
585
+ // The toggle button is re-created by the fold: give the focus back to it.
586
+ const element = viewportEl;
587
+ if (element === undefined) return;
588
+ void tick().then(() => {
589
+ for (const candidate of element.querySelectorAll<HTMLElement>("[data-scene-occurrence]")) {
590
+ if (candidate.dataset["sceneOccurrence"] !== node.occurrence) continue;
591
+ candidate.querySelector<HTMLElement>("button[aria-expanded]")?.focus({ preventScroll: true });
592
+ return;
593
+ }
594
+ });
595
+ }
596
+
597
+ const cardPropsOf = (node: SceneNodeModel) => {
598
+ const projected = projectCardProps(node.presentation, {
599
+ entityId: node.entity,
600
+ ...(resolveGlyph === undefined ? {} : { resolveGlyph }),
601
+ });
602
+ return projected.kind === "card" ? projected.props : undefined;
603
+ };
604
+
605
+ const zonePropsOf = (node: SceneNodeModel, rect: Rect) => {
606
+ const zoneTitle = node.presentation?.text.title ?? "";
607
+ const projected = projectZoneProps(node.presentation, {
608
+ entityId: node.entity,
609
+ collapsed: node.collapsed,
610
+ toggleLabel: node.collapsed ? strings.expand(zoneTitle) : strings.collapse(zoneTitle),
611
+ ...(node.collapsed ? {} : { width: rect.width, height: rect.height }),
612
+ ...(resolveGlyph === undefined ? {} : { resolveGlyph }),
613
+ });
614
+ return projected.kind === "zone" ? projected.props : undefined;
615
+ };
616
+
617
+ const pointsOf = (points: readonly { readonly x: number; readonly y: number }[]): string =>
618
+ points.map((point) => `${point.x},${point.y}`).join(" ");
619
+
620
+ const viewportStyle = $derived(
621
+ `${measured ? `height:${fit.fitHeight}px` : `aspect-ratio:${FIT_ASPECT}`};--st-diagram-zoom:${zoom}`,
622
+ );
623
+ const worldStyle = $derived(
624
+ `transform:translate(${placement.translateX}px,${placement.translateY}px) scale(${zoom})`,
625
+ );
626
+ </script>
627
+
628
+ <figure
629
+ class="st-diagramSceneFigure{compact ? " st-diagramSceneFigure--compact" : ""}"
630
+ aria-label={label ?? title}
631
+ data-zoom={zoom}
632
+ data-zoom-readout={readout}
633
+ data-scene-refused={layoutResult.status === "refused" ? layoutResult.refusals[0]?.code : undefined}
634
+ >
635
+ {#if title !== undefined}
636
+ <figcaption class="st-diagramSceneFigure-title">{title}</figcaption>
637
+ {/if}
638
+ <div class="st-diagramSceneFigure-controls" role="group" aria-label={strings.controls}>
639
+ <IconButton size="sm" variant="secondary" aria-label={strings.zoomOut} disabled={!canZoomOut} onclick={zoomOut}>
640
+ <Minus size="var(--st-component-button-anatomy-density-sm-fontSize)" aria-hidden="true" />
641
+ </IconButton>
642
+ <output class="st-diagramSceneFigure-readout" aria-live="polite" aria-label={strings.zoomLevel(readout)}>
643
+ {readout} %
644
+ </output>
645
+ <IconButton size="sm" variant="secondary" aria-label={strings.zoomIn} disabled={!canZoomIn} onclick={zoomIn}>
646
+ <Plus size="var(--st-component-button-anatomy-density-sm-fontSize)" aria-hidden="true" />
647
+ </IconButton>
648
+ <Button size="sm" variant="secondary" onclick={fitToFrame}>{strings.fit}</Button>
649
+ </div>
650
+ <div class="st-diagramSceneFigure-frame" bind:this={frameEl}>
651
+ <!-- m5: a refused layout draws visible text, not only the data attribute. -->
652
+ {#if layoutResult.status === "refused"}
653
+ <p class="st-diagramSceneFigure-refused" role="alert">
654
+ Diagram unavailable ({layoutResult.refusals[0]?.code ?? "refused"})
655
+ </p>
656
+ {/if}
657
+ <!-- The scrollable drawing region is focusable so the keyboard reaches
658
+ both the scroll (arrow keys) and the camera keys (+, −, 0). -->
659
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
660
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
661
+ <div
662
+ class="st-diagramSceneFigure-viewport"
663
+ bind:this={viewportEl}
664
+ role="group"
665
+ tabindex="0"
666
+ aria-label={strings.viewport}
667
+ aria-keyshortcuts="+ - 0"
668
+ aria-busy={animating}
669
+ data-pans={placement.overflowX || placement.overflowY ? "true" : "false"}
670
+ style={viewportStyle}
671
+ onkeydown={onKeydown}
672
+ onpointerdown={onPointerDown}
673
+ onpointermove={onPointerMove}
674
+ onpointerup={onPointerEnd}
675
+ onpointercancel={onPointerEnd}
676
+ >
677
+ <div
678
+ class="st-diagramSceneFigure-extent"
679
+ style={`width:${placement.contentWidth}px;height:${placement.contentHeight}px`}
680
+ >
681
+ <div class="st-diagramSceneFigure-world" style={worldStyle}>
682
+ {#if scene !== undefined}
683
+ <!-- m4: edges paint before nodes, labels last; edges and labels
684
+ fade in with the transition (T-1) while the boxes move. -->
685
+ <svg
686
+ class="st-diagramSceneFigure-edges"
687
+ aria-hidden="true"
688
+ style={animating ? `opacity:${eased}` : undefined}
689
+ >
690
+ {#each scene.edges as edge (edge.occurrence)}
691
+ <polyline class="st-diagramSceneFigure-edge" data-scene-edge={edge.occurrence} points={pointsOf(edge.points)} />
692
+ {/each}
693
+ </svg>
694
+ {#each scene.nodes as node (node.occurrence)}
695
+ {@const rect = rectOf(node)}
696
+ <div
697
+ class="st-diagramSceneFigure-node"
698
+ data-scene-occurrence={node.occurrence}
699
+ data-scene-kind={node.kind}
700
+ style={`left:${rect.x}px;top:${rect.y}px;width:${rect.width}px;height:${rect.height}px${entering(node) ? `;opacity:${eased}` : ""}`}
701
+ >
702
+ {#if node.kind === "card"}
703
+ {@const cardProps = cardPropsOf(node)}
704
+ {#if cardProps !== undefined}
705
+ <DiagramCard {...cardProps} {measure} {onSelect} />
706
+ {/if}
707
+ {:else if node.kind === "zone"}
708
+ {@const zoneProps = zonePropsOf(node, rect)}
709
+ {#if zoneProps !== undefined}
710
+ <DiagramZone {...zoneProps} {measure} {onSelect} onToggle={() => toggleFold(node)} />
711
+ {/if}
712
+ {:else}
713
+ <div class="st-diagramSceneFigure-label" data-entity={node.entity}>{node.text}</div>
714
+ {/if}
715
+ </div>
716
+ {/each}
717
+ {#each scene.labels as edgeLabel (edgeLabel.occurrence)}
718
+ <div
719
+ class="st-diagramSceneFigure-edgeLabel"
720
+ data-scene-label={edgeLabel.occurrence}
721
+ style={`left:${edgeLabel.box.x}px;top:${edgeLabel.box.y}px;width:${edgeLabel.box.width}px;height:${edgeLabel.box.height}px${animating ? `;opacity:${eased}` : ""}`}
722
+ >
723
+ {#each edgeLabel.lines as line, lineIndex (lineIndex)}
724
+ <span>{line}</span>
725
+ {/each}
726
+ </div>
727
+ {/each}
728
+ {/if}
729
+ </div>
730
+ </div>
731
+ </div>
732
+ </div>
733
+ </figure>
734
+
735
+ <style>
736
+ .st-diagramSceneFigure {
737
+ /* Title and camera controls share the first row; the frame spans both. */
738
+ align-items: center;
739
+ display: grid;
740
+ gap: var(--st-spacing-2, 0.5rem);
741
+ grid-template-columns: minmax(0, 1fr) auto;
742
+ margin: 0;
743
+ min-width: 0;
744
+ }
745
+ .st-diagramSceneFigure--compact {
746
+ gap: var(--st-spacing-1, 0.25rem);
747
+ }
748
+ .st-diagramSceneFigure-title {
749
+ color: var(--st-semantic-text-primary);
750
+ grid-column: 1;
751
+ font-weight: 600;
752
+ }
753
+ .st-diagramSceneFigure--compact .st-diagramSceneFigure-title {
754
+ font-size: var(--st-component-button-anatomy-density-sm-fontSize, 0.875rem);
755
+ }
756
+ .st-diagramSceneFigure-controls {
757
+ align-items: center;
758
+ display: inline-flex;
759
+ gap: var(--st-spacing-1, 0.25rem);
760
+ grid-column: 2;
761
+ }
762
+ .st-diagramSceneFigure-readout {
763
+ color: var(--st-semantic-text-secondary);
764
+ font-size: var(--st-component-button-anatomy-density-sm-fontSize, 0.875rem);
765
+ font-variant-numeric: tabular-nums;
766
+ min-width: 4ch;
767
+ text-align: center;
768
+ }
769
+ .st-diagramSceneFigure-frame {
770
+ grid-column: 1 / -1;
771
+ min-width: 0;
772
+ width: 100%;
773
+ }
774
+ .st-diagramSceneFigure-viewport {
775
+ /* The fit box: its height comes from the camera (inline). It scrolls
776
+ only the axis the drawing overflows at the current zoom. */
777
+ box-sizing: border-box;
778
+ overflow: auto;
779
+ position: relative;
780
+ touch-action: pan-x pan-y;
781
+ width: 100%;
782
+ }
783
+ .st-diagramSceneFigure-viewport:focus-visible {
784
+ box-shadow: inset 0 0 0 2px var(--st-component-iconButton-focusRing, var(--st-semantic-border-interactive));
785
+ outline: none;
786
+ }
787
+ .st-diagramSceneFigure-extent {
788
+ min-height: 100%;
789
+ min-width: 100%;
790
+ position: relative;
791
+ }
792
+ .st-diagramSceneFigure-world {
793
+ left: 0;
794
+ position: absolute;
795
+ top: 0;
796
+ transform-origin: 0 0;
797
+ }
798
+ .st-diagramSceneFigure-node {
799
+ position: absolute;
800
+ }
801
+ .st-diagramSceneFigure-label {
802
+ align-items: center;
803
+ box-sizing: border-box;
804
+ color: var(--st-component-diagramCard-text, var(--st-semantic-text-primary));
805
+ display: flex;
806
+ font-family: var(--st-component-diagramCard-fontFamily, inherit);
807
+ font-size: var(--st-component-diagramCard-bodyFontSize, 24px);
808
+ height: 100%;
809
+ line-height: var(--st-component-diagramCard-bodyLineHeight, 1.3);
810
+ width: 100%;
811
+ }
812
+ .st-diagramSceneFigure-edges {
813
+ height: 1px;
814
+ left: 0;
815
+ overflow: visible;
816
+ pointer-events: none;
817
+ position: absolute;
818
+ top: 0;
819
+ width: 1px;
820
+ }
821
+ .st-diagramSceneFigure-edge {
822
+ fill: none;
823
+ stroke: var(--st-component-diagramCard-border, var(--st-semantic-border-strong));
824
+ stroke-linejoin: round;
825
+ stroke-width: var(--st-component-diagramZone-borderWidth, 1.5px);
826
+ vector-effect: non-scaling-stroke;
827
+ }
828
+ .st-diagramSceneFigure-edgeLabel {
829
+ align-items: center;
830
+ color: var(--st-semantic-text-secondary);
831
+ display: flex;
832
+ flex-direction: column;
833
+ font-family: var(--st-component-diagramCard-fontFamily, inherit);
834
+ font-size: var(--st-component-diagramScene-edgeLabelFontSize, 18px);
835
+ justify-content: center;
836
+ line-height: var(--st-component-diagramScene-edgeLabelLineHeight, 22px);
837
+ pointer-events: none;
838
+ position: absolute;
839
+ white-space: nowrap;
840
+ }
841
+ </style>