@vitavision/workbench 0.1.0 → 0.1.1

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.
package/README.md CHANGED
@@ -25,12 +25,12 @@ bun add @vitavision/workbench @vitavision/ui
25
25
  | `PlaybackBar` | Transport for a sampled timeline: step, play/pause, markers, scrubber, `t = k · dt`, speed, loop. |
26
26
  | `createPlayhead`, `usePlayhead`, `usePlaybackClock` | The playback position as an external store, and the real-time clock that drives it. |
27
27
  | `FileDrop` | Drop zone (or full-window `overlay`) plus an "Open files…" button; `accept` applied to both routes; dropped folders walked. |
28
- | `Toaster`, `toast()` | Notifications from anywhere; one `<Toaster />` near the root. |
28
+ | `Toaster`, `toast()` | Notifications from anywhere; one `<Toaster />` near the root. **Now lives in `@vitavision/ui`**; re-exported here (same bindings, one default store) so existing imports keep working. Prefer `import { toast } from "@vitavision/ui"`. |
29
29
 
30
30
  The pure logic behind them is exported too and tested without a DOM: `splitSize.ts`
31
31
  (`resolveSize`, `resolveLimits`, `clampSize`), `treeModel.ts` (`visibleRows`, `treeKeyAction`,
32
32
  `ancestorIds`, `parentIds`), `playhead.ts` (`advance`, `clampIndex`, `formatSeconds`),
33
- `dropFiles.ts` (`acceptsFile`, `collectDroppedFiles`), `toastStore.ts` (`createToastStore`).
33
+ `dropFiles.ts` (`acceptsFile`, `collectDroppedFiles`).
34
34
 
35
35
  ### Playback without re-rendering the app
36
36
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MeasureTone } from "@vitavision/ui";
1
+ import { MeasureTone, ToastOptions, ToastRecord, ToastStore, ToastTone, Toaster, ToasterProps, createToastStore, defaultToastStore, toast } from "@vitavision/ui";
2
2
  import { ReactNode } from "react";
3
3
  //#region src/components/splitSize.d.ts
4
4
  /**
@@ -576,96 +576,5 @@ interface DropEntry {
576
576
  */
577
577
  export declare function collectDroppedFiles(dataTransfer: Pick<DataTransfer, "files" | "items">): Promise<File[]>;
578
578
  //#endregion
579
- //#region src/components/toastStore.d.ts
580
- /** A toast's kind: a fact (`info`), a completed action (`success`), a caveat (`warn`), a failure (`error`). */
581
- type ToastTone = "info" | "success" | "warn" | "error";
582
- /** What `toast()` takes. */
583
- interface ToastOptions {
584
- /** One line: what happened. */
585
- title: string;
586
- /** More detail, and what to do about it. */
587
- description?: string | undefined;
588
- /** Defaults to `info`. */
589
- tone?: ToastTone | undefined;
590
- /**
591
- * How long it stays, in milliseconds, while not hovered or focused. Defaults to 5000
592
- * (8000 for `error`); `Infinity` keeps it until dismissed.
593
- */
594
- duration?: number | undefined;
595
- /** Replace the toast with this id instead of adding one — for progress that updates in place. */
596
- id?: string | undefined;
597
- }
598
- /** A toast in the store. */
599
- interface ToastRecord {
600
- /** Identifies the toast to `dismiss` and to `id` replacement. */
601
- id: string;
602
- /** One line: what happened. */
603
- title: string;
604
- /** More detail, if any. */
605
- description: string | undefined;
606
- /** Its kind. */
607
- tone: ToastTone;
608
- /** Milliseconds before it dismisses itself (`Infinity`: never). */
609
- duration: number;
610
- }
611
- /**
612
- * A toast store: what `toast()` writes to and `<Toaster />` reads. Every member may be called
613
- * detached.
614
- */
615
- interface ToastStore {
616
- /** Add a toast (or replace the one with `options.id`), returning its id. */
617
- readonly toast: (options: ToastOptions) => string;
618
- /** Remove one toast, or every toast when `id` is omitted. */
619
- readonly dismiss: (id?: string) => void;
620
- /** The toasts, oldest first. The same array until the store changes. */
621
- readonly getSnapshot: () => readonly ToastRecord[];
622
- /** Be told when the toasts change; returns the unsubscribe function. */
623
- readonly subscribe: (listener: () => void) => () => void;
624
- }
625
- /**
626
- * A new, empty toast store. The package keeps one (behind `toast()` and the default
627
- * `<Toaster />`); create another only to isolate a region or a test.
628
- *
629
- * @returns The store.
630
- */
631
- export declare function createToastStore(): ToastStore;
632
- /** The store behind `toast()` and a `<Toaster />` given no `store`. */
633
- export declare const defaultToastStore: ToastStore;
634
- /**
635
- * Raise a notification, from anywhere — shown by the mounted `<Toaster />`.
636
- *
637
- * `toast({ title: "Scenario loaded", tone: "success" })`. Pass `id` to update a toast in
638
- * place (a progress message that becomes a result). `toast.dismiss(id)` removes one early,
639
- * `toast.dismiss()` all of them.
640
- *
641
- * @param options - The message, its tone and its duration.
642
- * @returns The toast's id.
643
- */
644
- export declare const toast: ((options: ToastOptions) => string) & {
645
- /** Remove one toast, or every toast when `id` is omitted. */
646
- dismiss: (id?: string) => void;
647
- };
648
- //#endregion
649
- //#region src/components/Toaster.d.ts
650
- /** Props of `Toaster`. */
651
- interface ToasterProps {
652
- /** The store to show. Defaults to the one behind `toast()`. */
653
- store?: ToastStore | undefined;
654
- /** How many toasts are shown at once; older ones wait. Defaults to 5. */
655
- limit?: number | undefined;
656
- /** Merged with the stack's own classes through `cn` (it is fixed to the bottom-right corner). */
657
- className?: string | undefined;
658
- }
659
- /**
660
- * The stack of notifications raised with `toast()`. Mount it once, near the root.
661
- *
662
- * Fixed to the bottom-right corner, newest at the bottom. Each toast dismisses itself after
663
- * its `duration`; the countdown pauses while the pointer is over the stack or focus is inside
664
- * it. A `section` landmark ("Notifications") holding a polite live region, so new toasts are
665
- * announced; an `error` toast is a `role="alert"`, announced at once. Each toast carries
666
- * `data-tone` and a "Dismiss" button.
667
- */
668
- export declare function Toaster({ store, limit, className }: ToasterProps): import("react").JSX.Element;
669
- //#endregion
670
- export type { AdvanceResult, AppShellProps, DropEntry, FileDropProps, PaneSize, PlaybackBarProps, PlaybackClockOptions, PlaybackMarker, Playhead, SidePanelSize, SizedPane, SplitLimits, SplitOrientation, SplitPaneProps, ToastOptions, ToastRecord, ToastStore, ToastTone, ToasterProps, TreeKeyAction, TreeNode, TreeRow, TreeViewProps };
579
+ export { type AdvanceResult, type AppShellProps, type DropEntry, type FileDropProps, type PaneSize, type PlaybackBarProps, type PlaybackClockOptions, type PlaybackMarker, type Playhead, type SidePanelSize, type SizedPane, type SplitLimits, type SplitOrientation, type SplitPaneProps, type ToastOptions, type ToastRecord, type ToastStore, type ToastTone, Toaster, type ToasterProps, type TreeKeyAction, type TreeNode, type TreeRow, type TreeViewProps, createToastStore, defaultToastStore, toast };
671
580
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { Button, Select, Slider, byDensity, cn, focusRing, toneColor, useDensity } from "@vitavision/ui";
1
+ import { Button, Select, Slider, Toaster, byDensity, cn, createToastStore, defaultToastStore, focusRing, toast, toneColor, useDensity } from "@vitavision/ui";
2
2
  import { useCallback, useEffect, useEffectEvent, useId, useRef, useState, useSyncExternalStore } from "react";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
- import { ChevronFirst, ChevronLast, ChevronRight, CircleCheck, CircleX, FolderOpen, Info, Pause, Play, Repeat, SkipBack, SkipForward, StepBack, StepForward, TriangleAlert, X } from "lucide-react";
4
+ import { ChevronFirst, ChevronLast, ChevronRight, FolderOpen, Pause, Play, Repeat, SkipBack, SkipForward, StepBack, StepForward } from "lucide-react";
5
5
  //#region src/components/splitSize.ts
6
6
  /**
7
7
  * A size in pixels.
@@ -1283,187 +1283,6 @@ function FileDrop({ onFiles, onReject, accept, multiple = true, directory = fals
1283
1283
  });
1284
1284
  }
1285
1285
  //#endregion
1286
- //#region src/components/toastStore.ts
1287
- const DEFAULT_DURATION = 5e3;
1288
- const ERROR_DURATION = 8e3;
1289
- /**
1290
- * A new, empty toast store. The package keeps one (behind `toast()` and the default
1291
- * `<Toaster />`); create another only to isolate a region or a test.
1292
- *
1293
- * @returns The store.
1294
- */
1295
- function createToastStore() {
1296
- let toasts = [];
1297
- let sequence = 0;
1298
- const listeners = /* @__PURE__ */ new Set();
1299
- const commit = (next) => {
1300
- toasts = next;
1301
- for (const listener of [...listeners]) listener();
1302
- };
1303
- return {
1304
- toast: (options) => {
1305
- const tone = options.tone ?? "info";
1306
- sequence += 1;
1307
- const record = {
1308
- id: options.id ?? `toast-${sequence}`,
1309
- title: options.title,
1310
- description: options.description,
1311
- tone,
1312
- duration: options.duration ?? (tone === "error" ? ERROR_DURATION : DEFAULT_DURATION)
1313
- };
1314
- const existing = toasts.findIndex((t) => t.id === record.id);
1315
- commit(existing === -1 ? [...toasts, record] : toasts.map((t, i) => i === existing ? record : t));
1316
- return record.id;
1317
- },
1318
- dismiss: (id) => {
1319
- if (id === void 0) {
1320
- if (toasts.length > 0) commit([]);
1321
- return;
1322
- }
1323
- if (toasts.some((t) => t.id === id)) commit(toasts.filter((t) => t.id !== id));
1324
- },
1325
- getSnapshot: () => toasts,
1326
- subscribe: (listener) => {
1327
- listeners.add(listener);
1328
- return () => {
1329
- listeners.delete(listener);
1330
- };
1331
- }
1332
- };
1333
- }
1334
- /** The store behind `toast()` and a `<Toaster />` given no `store`. */
1335
- const defaultToastStore = createToastStore();
1336
- /**
1337
- * Raise a notification, from anywhere — shown by the mounted `<Toaster />`.
1338
- *
1339
- * `toast({ title: "Scenario loaded", tone: "success" })`. Pass `id` to update a toast in
1340
- * place (a progress message that becomes a result). `toast.dismiss(id)` removes one early,
1341
- * `toast.dismiss()` all of them.
1342
- *
1343
- * @param options - The message, its tone and its duration.
1344
- * @returns The toast's id.
1345
- */
1346
- const toast = Object.assign((options) => defaultToastStore.toast(options), { dismiss: (id) => defaultToastStore.dismiss(id) });
1347
- //#endregion
1348
- //#region src/components/Toaster.tsx
1349
- const TONE = {
1350
- info: {
1351
- border: "border-signal/30",
1352
- icon: "text-signal",
1353
- Icon: Info
1354
- },
1355
- success: {
1356
- border: "border-normal/30",
1357
- icon: "text-normal",
1358
- Icon: CircleCheck
1359
- },
1360
- warn: {
1361
- border: "border-warn/30",
1362
- icon: "text-warn",
1363
- Icon: TriangleAlert
1364
- },
1365
- error: {
1366
- border: "border-defect/30",
1367
- icon: "text-defect",
1368
- Icon: CircleX
1369
- }
1370
- };
1371
- const NO_TOASTS = [];
1372
- /**
1373
- * The stack of notifications raised with `toast()`. Mount it once, near the root.
1374
- *
1375
- * Fixed to the bottom-right corner, newest at the bottom. Each toast dismisses itself after
1376
- * its `duration`; the countdown pauses while the pointer is over the stack or focus is inside
1377
- * it. A `section` landmark ("Notifications") holding a polite live region, so new toasts are
1378
- * announced; an `error` toast is a `role="alert"`, announced at once. Each toast carries
1379
- * `data-tone` and a "Dismiss" button.
1380
- */
1381
- function Toaster({ store = defaultToastStore, limit = 5, className }) {
1382
- const toasts = useSyncExternalStore(store.subscribe, store.getSnapshot, () => NO_TOASTS);
1383
- const [hovered, setHovered] = useState(false);
1384
- const [focused, setFocused] = useState(false);
1385
- const shown = toasts.slice(-Math.max(1, limit));
1386
- const onBlur = (event) => {
1387
- if (!event.currentTarget.contains(event.relatedTarget)) setFocused(false);
1388
- };
1389
- return /* @__PURE__ */ jsx("section", {
1390
- "aria-label": "Notifications",
1391
- onPointerEnter: () => setHovered(true),
1392
- onPointerLeave: () => setHovered(false),
1393
- onFocus: () => setFocused(true),
1394
- onBlur,
1395
- className: cn("pointer-events-none fixed right-4 bottom-4 z-50 w-80 max-w-[calc(100vw-2rem)]", className),
1396
- children: /* @__PURE__ */ jsx("ol", {
1397
- "aria-live": "polite",
1398
- className: "flex flex-col gap-2",
1399
- children: shown.map((record) => /* @__PURE__ */ jsx(ToastItem, {
1400
- record,
1401
- paused: hovered || focused,
1402
- onDismiss: () => store.dismiss(record.id)
1403
- }, record.id))
1404
- })
1405
- });
1406
- }
1407
- function ToastItem({ record, paused, onDismiss }) {
1408
- const { border, icon, Icon } = TONE[record.tone];
1409
- const remainingRef = useRef({
1410
- record,
1411
- ms: record.duration
1412
- });
1413
- const dismissRef = useRef(onDismiss);
1414
- useEffect(() => {
1415
- dismissRef.current = onDismiss;
1416
- });
1417
- useEffect(() => {
1418
- if (remainingRef.current.record !== record) remainingRef.current = {
1419
- record,
1420
- ms: record.duration
1421
- };
1422
- if (paused || !Number.isFinite(remainingRef.current.ms)) return;
1423
- const started = Date.now();
1424
- const timer = setTimeout(() => dismissRef.current(), remainingRef.current.ms);
1425
- return () => {
1426
- clearTimeout(timer);
1427
- remainingRef.current.ms = Math.max(0, remainingRef.current.ms - (Date.now() - started));
1428
- };
1429
- }, [paused, record]);
1430
- return /* @__PURE__ */ jsx("li", {
1431
- className: "pointer-events-auto",
1432
- children: /* @__PURE__ */ jsxs("div", {
1433
- role: record.tone === "error" ? "alert" : void 0,
1434
- "data-tone": record.tone,
1435
- className: cn("flex items-start gap-2.5 rounded-panel border bg-overlay px-3 py-2.5 text-sm leading-snug shadow-lg shadow-black/25", "transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0", border),
1436
- children: [
1437
- /* @__PURE__ */ jsx(Icon, {
1438
- className: cn("mt-0.5 size-4 shrink-0", icon),
1439
- "aria-hidden": true
1440
- }),
1441
- /* @__PURE__ */ jsxs("div", {
1442
- className: "flex min-w-0 flex-1 flex-col gap-0.5",
1443
- children: [/* @__PURE__ */ jsx("p", {
1444
- className: "font-medium text-fg",
1445
- children: record.title
1446
- }), record.description && /* @__PURE__ */ jsx("p", {
1447
- className: "text-fg-muted",
1448
- children: record.description
1449
- })]
1450
- }),
1451
- /* @__PURE__ */ jsx("button", {
1452
- type: "button",
1453
- "aria-label": "Dismiss",
1454
- title: "Dismiss",
1455
- onClick: onDismiss,
1456
- className: cn("-mr-1 grid size-6 shrink-0 place-items-center rounded-control text-fg-subtle transition-colors hover:bg-raised hover:text-fg", focusRing),
1457
- children: /* @__PURE__ */ jsx(X, {
1458
- className: "size-3.5",
1459
- "aria-hidden": true
1460
- })
1461
- })
1462
- ]
1463
- })
1464
- });
1465
- }
1466
- //#endregion
1467
1286
  export { AppShell, DEFAULT_SPEEDS, FileDrop, PlaybackBar, SplitPane, Toaster, TreeView, acceptsFile, advance, ancestorIds, clampIndex, clampSize, collectDroppedFiles, createPlayhead, createToastStore, defaultToastStore, formatSeconds, parentIds, resolveLimits, resolveSize, toast, treeKeyAction, usePlaybackClock, usePlayhead, usePlayheadTimeline, visibleRows };
1468
1287
 
1469
1288
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/components/splitSize.ts","../src/components/SplitPane.tsx","../src/components/AppShell.tsx","../src/components/treeModel.ts","../src/components/TreeView.tsx","../src/components/playhead.ts","../src/components/usePlayback.ts","../src/components/PlaybackBar.tsx","../src/components/dropFiles.ts","../src/components/FileDrop.tsx","../src/components/toastStore.ts","../src/components/Toaster.tsx"],"sourcesContent":["/*\n * The arithmetic behind `SplitPane`: resolving sizes given in pixels or percent, clamping a\n * drag or a key press to the pane's limits, and remembering a size across reloads.\n *\n * Kept out of the component so every rule — which key moves the divider which way, where a\n * collapsible pane snaps shut — is tested without a DOM.\n */\n\n/**\n * A pane size: CSS pixels as a number, or a share of the split's length as a percentage\n * string (`\"30%\"`).\n */\nexport type PaneSize = number | `${number}%`;\n\n/** The limits a `SplitPane`'s sized pane is held to, resolved to pixels. */\nexport interface SplitLimits {\n /** The smallest open size, in pixels. */\n min: number;\n /** The largest size, in pixels. */\n max: number;\n /** Whether the pane may close to 0 below `min`. */\n collapsible: boolean;\n}\n\n/**\n * A size in pixels.\n *\n * @param size - Pixels, or a percentage of `length`.\n * @param length - The split's length along its axis, in pixels.\n * @returns The size in pixels (never negative).\n */\nexport function resolveSize(size: PaneSize, length: number): number {\n const px = typeof size === \"number\" ? size : (Number.parseFloat(size) / 100) * length;\n return Number.isFinite(px) ? Math.max(0, px) : 0;\n}\n\n/**\n * The limits in pixels for a split of `length`. `max` never exceeds `length`, and `min`\n * never exceeds `max`.\n *\n * @param length - The split's length along its axis, in pixels.\n * @param minSize - The smallest open size. Defaults to 0.\n * @param maxSize - The largest size. Defaults to the whole length.\n * @param collapsible - Whether the pane may close below `minSize`.\n * @returns The resolved limits.\n */\nexport function resolveLimits(\n length: number,\n minSize: PaneSize = 0,\n maxSize: PaneSize = \"100%\",\n collapsible = false,\n): SplitLimits {\n const max = Math.min(resolveSize(maxSize, length), Math.max(0, length));\n const min = Math.min(resolveSize(minSize, length), max);\n return { min, max, collapsible };\n}\n\n/**\n * Hold a proposed size to the limits. A collapsible pane dragged below half its minimum\n * snaps shut (0); between half the minimum and the minimum it stays at the minimum.\n *\n * @param size - The proposed size, in pixels.\n * @param limits - The resolved limits.\n * @returns The size to apply, in pixels, rounded to whole pixels.\n */\nexport function clampSize(size: number, limits: SplitLimits): number {\n if (limits.collapsible && size < limits.min / 2) return 0;\n return Math.round(Math.min(limits.max, Math.max(limits.min, size)));\n}\n\n/** Which way a `SplitPane` lays out its two panes. */\nexport type SplitOrientation = \"horizontal\" | \"vertical\";\n\n/** Which of the two panes carries the explicit size; the other takes the rest. */\nexport type SizedPane = \"start\" | \"end\";\n\n/** What a key press on the divider asks for. */\nexport type SplitKeyAction =\n | { type: \"resize\"; size: number }\n | { type: \"toggle-collapse\" };\n\n/**\n * The divider's keyboard (the WAI-ARIA window-splitter pattern).\n *\n * The arrow keys along the split's axis move the divider the way they point — so the sized\n * pane grows or shrinks depending on which side it is on — by `step`, or four steps with\n * Shift. Home gives the sized pane its minimum, End its maximum, and Enter collapses or\n * restores a collapsible pane.\n *\n * @param key - `KeyboardEvent.key`.\n * @param shift - Whether Shift is held.\n * @param size - The sized pane's current size, in pixels.\n * @param options - The layout, the step in pixels and the resolved limits.\n * @returns The action, or `null` when the key is not the divider's.\n */\nexport function splitKeyAction(\n key: string,\n shift: boolean,\n size: number,\n options: { orientation: SplitOrientation; sizedPane: SizedPane; step: number; limits: SplitLimits },\n): SplitKeyAction | null {\n const { orientation, sizedPane, step, limits } = options;\n const [back, forward] =\n orientation === \"horizontal\" ? [\"ArrowLeft\", \"ArrowRight\"] : [\"ArrowUp\", \"ArrowDown\"];\n const grow = sizedPane === \"start\" ? 1 : -1;\n const delta = shift ? step * 4 : step;\n\n switch (key) {\n case forward:\n return { type: \"resize\", size: clampOpen(size + grow * delta, limits) };\n case back:\n return { type: \"resize\", size: clampOpen(size - grow * delta, limits) };\n case \"Home\":\n return { type: \"resize\", size: Math.round(limits.min) };\n case \"End\":\n return { type: \"resize\", size: Math.round(limits.max) };\n case \"Enter\":\n return limits.collapsible ? { type: \"toggle-collapse\" } : null;\n default:\n return null;\n }\n}\n\n/** A key step never snaps a pane shut (that is Enter's job): clamp to the open range. */\nfunction clampOpen(size: number, limits: SplitLimits): number {\n return Math.round(Math.min(limits.max, Math.max(limits.min, size)));\n}\n\n/**\n * The size stored under `key`, if any.\n *\n * @param key - The `localStorage` key.\n * @returns The stored size in pixels, or `null` when nothing valid is stored or storage\n * cannot be read (private browsing, the server).\n */\nexport function readStoredSize(key: string): number | null {\n try {\n const raw = window.localStorage.getItem(key);\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Remember a size under `key`. Failures (storage full, disabled, the server) are ignored: a\n * size that is not remembered is not worth an error.\n *\n * @param key - The `localStorage` key.\n * @param size - The size in pixels.\n */\nexport function writeStoredSize(key: string, size: number): void {\n try {\n window.localStorage.setItem(key, String(Math.round(size)));\n } catch {\n // Nothing to do: the size simply is not remembered.\n }\n}\n","/*\n * Two panes and the divider between them.\n *\n * A studio screen is a handful of permanent surfaces — a tree, a viewport, an inspector, a\n * timeline — whose relative size is the user's decision, not the layout's. The divider is\n * therefore a real control: draggable, operable from the keyboard (the WAI-ARIA\n * window-splitter pattern), announced with its position, and remembered across reloads\n * when asked to be.\n *\n * One pane carries the size and the other takes the rest, so nesting composes: the rest of\n * one split is simply another split. `AppShell` builds its side panels exactly that way.\n */\n\nimport { useCallback, useId, useRef, useState } from \"react\";\nimport type {\n CSSProperties,\n KeyboardEvent,\n PointerEvent as ReactPointerEvent,\n ReactNode,\n} from \"react\";\n\nimport { cn, focusRing } from \"@vitavision/ui\";\n\nimport {\n type PaneSize,\n type SizedPane,\n type SplitOrientation,\n clampSize,\n readStoredSize,\n resolveLimits,\n resolveSize,\n splitKeyAction,\n writeStoredSize,\n} from \"./splitSize\";\n\n/** Props of `SplitPane`. */\nexport interface SplitPaneProps {\n /**\n * The two panes, in reading order (left then right, or top then bottom). Exactly two;\n * nest another `SplitPane` in either for more.\n */\n children: readonly [ReactNode, ReactNode];\n /**\n * `horizontal` (the default) lays the panes side by side with a vertical divider;\n * `vertical` stacks them with a horizontal one.\n */\n orientation?: SplitOrientation | undefined;\n /** Which pane carries the size; the other takes the rest. Defaults to `start`. */\n sizedPane?: SizedPane | undefined;\n /** The sized pane's size in pixels, controlled. Pair with `onSizeChange`. */\n size?: number | undefined;\n /** The initial size when uncontrolled: pixels or a percentage. Defaults to `\"50%\"`. */\n defaultSize?: PaneSize | undefined;\n /** Called with the new size in pixels on every drag move and key press (0 when collapsed). */\n onSizeChange?: ((size: number) => void) | undefined;\n /** The sized pane's smallest open size: pixels or a percentage. Defaults to 0. */\n minSize?: PaneSize | undefined;\n /** The sized pane's largest size: pixels or a percentage. Defaults to `\"100%\"`. */\n maxSize?: PaneSize | undefined;\n /**\n * Lets the sized pane close: dragging it below half its minimum snaps it shut, and Enter\n * on the divider collapses it or restores the last open size.\n */\n collapsible?: boolean | undefined;\n /** How far one arrow-key press moves the divider, in pixels (four times with Shift). Defaults to 16. */\n step?: number | undefined;\n /**\n * Remember the size under this `localStorage` key, and start from it. Uncontrolled only:\n * a controlled split's size is the caller's to keep.\n */\n storageKey?: string | undefined;\n /** Names the divider for assistive technology. Defaults to \"Resize panes\". */\n \"aria-label\"?: string | undefined;\n /** Merged with the split's own classes through `cn`. */\n className?: string | undefined;\n}\n\n/**\n * Two panes with a draggable, keyboard-operable divider between them.\n *\n * The divider is a `role=\"separator\"` focusable control carrying `aria-valuenow` (the sized\n * pane's size in pixels), `aria-valuemin`/`aria-valuemax` and `aria-controls` (the sized\n * pane). Arrow keys along the axis move it by `step` (Shift: four steps), Home/End give the\n * sized pane its minimum/maximum, Enter collapses or restores a `collapsible` pane. Dragging\n * uses pointer capture, so the drag survives the pointer leaving the divider.\n *\n * Fills its container (`h-full w-full`), so it nests. State is exposed as `data-orientation`\n * on the root, `data-dragging` on the root and the divider while a drag is in progress, and\n * `data-collapsed` on the root and the sized pane while it is closed.\n */\nexport function SplitPane({\n children,\n orientation = \"horizontal\",\n sizedPane = \"start\",\n size: controlledSize,\n defaultSize = \"50%\",\n onSizeChange,\n minSize = 0,\n maxSize = \"100%\",\n collapsible = false,\n step = 16,\n storageKey,\n \"aria-label\": ariaLabel = \"Resize panes\",\n className,\n}: SplitPaneProps) {\n const paneId = useId();\n const horizontal = orientation === \"horizontal\";\n const [length, setLength] = useState<number | null>(null);\n const [internalSize, setInternalSize] = useState<number | null>(null);\n const [dragging, setDragging] = useState(false);\n const rootRef = useRef<HTMLDivElement | null>(null);\n // The drag in progress: where it started, and the size it has reached. The reached size is\n // kept here, not read back from state, because a pointer move's update is rendered at\n // continuous priority and may not have landed when the pointer is released.\n const dragRef = useRef<{ origin: number; start: number; length: number; reached: number } | null>(null);\n const lastOpenRef = useRef<number | null>(null);\n\n const limits = length === null ? null : resolveLimits(length, minSize, maxSize, collapsible);\n const size =\n controlledSize ??\n internalSize ??\n (length === null || limits === null ? null : clampSize(resolveSize(defaultSize, length), limits));\n const collapsed = size === 0;\n const controlled = controlledSize !== undefined;\n\n /*\n * Measure the split along its axis — synchronously on attach, so the first paint has the\n * limits, then on every resize — and pick up a remembered size. A callback ref rather than\n * an effect: the subscription lives exactly as long as the element.\n */\n const attach = useCallback(\n (element: HTMLDivElement | null) => {\n rootRef.current = element;\n if (!element) return;\n const measure = () => {\n const rect = element.getBoundingClientRect();\n setLength(horizontal ? rect.width : rect.height);\n };\n measure();\n if (storageKey !== undefined && !controlled) {\n const stored = readStoredSize(storageKey);\n if (stored !== null) setInternalSize(stored);\n }\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n },\n [horizontal, storageKey, controlled],\n );\n\n /** The live length and limits, measured now (a drag or a key press must not use stale ones). */\n const measureNow = () => {\n const element = rootRef.current;\n const rect = element?.getBoundingClientRect();\n const now = rect ? (horizontal ? rect.width : rect.height) : (length ?? 0);\n return { length: now, limits: resolveLimits(now, minSize, maxSize, collapsible) };\n };\n\n /** Take a new size: state, the caller, and (on `commit`) storage. `changed` defaults to a comparison with the rendered size. */\n const apply = (next: number, commit: boolean, changed = next !== size) => {\n if (next > 0) lastOpenRef.current = next;\n if (!controlled) setInternalSize(next);\n if (changed) onSizeChange?.(next);\n if (commit && storageKey !== undefined && !controlled) {\n writeStoredSize(storageKey, next);\n }\n };\n\n const coordinate = (event: ReactPointerEvent) => (horizontal ? event.clientX : event.clientY);\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return;\n event.preventDefault();\n const { length: now } = measureNow();\n const current = size ?? 0;\n dragRef.current = { origin: coordinate(event), start: current, length: now, reached: current };\n event.currentTarget.setPointerCapture(event.pointerId);\n event.currentTarget.focus();\n setDragging(true);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n const drag = dragRef.current;\n if (drag === null) return;\n const delta = (coordinate(event) - drag.origin) * (sizedPane === \"start\" ? 1 : -1);\n const next = clampSize(drag.start + delta, resolveLimits(drag.length, minSize, maxSize, collapsible));\n if (next === drag.reached) return;\n drag.reached = next;\n // Compared with the drag's own last size above: the rendered one may lag behind.\n apply(next, false, true);\n };\n\n const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {\n const drag = dragRef.current;\n if (drag === null) return;\n dragRef.current = null;\n if (event.currentTarget.hasPointerCapture(event.pointerId)) {\n event.currentTarget.releasePointerCapture(event.pointerId);\n }\n setDragging(false);\n if (drag.reached > 0) lastOpenRef.current = drag.reached;\n if (storageKey !== undefined && !controlled) writeStoredSize(storageKey, drag.reached);\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n const { limits: now } = measureNow();\n const current = size ?? 0;\n const action = splitKeyAction(event.key, event.shiftKey, current, {\n orientation,\n sizedPane,\n step,\n limits: now,\n });\n if (action === null) return;\n event.preventDefault();\n if (action.type === \"resize\") {\n apply(action.size, true);\n } else if (current > 0) {\n lastOpenRef.current = current;\n apply(0, true);\n } else {\n apply(clampSize(lastOpenRef.current ?? now.min, { ...now, collapsible: false }), true);\n }\n };\n\n // Before the first measurement (and on the server) the pane is sized by CSS alone, from\n // the default; afterwards by the measured size. The limits stay in CSS too, so a window\n // resize never pushes the pane outside them between two measurements.\n const basis =\n size !== null ? `${size}px` : typeof defaultSize === \"number\" ? `${defaultSize}px` : defaultSize;\n const cssSize = (value: PaneSize) => (typeof value === \"number\" ? `${value}px` : value);\n const sizedStyle: CSSProperties = {\n flex: `0 0 ${basis}`,\n ...(collapsed\n ? {}\n : horizontal\n ? { minWidth: cssSize(minSize), maxWidth: cssSize(maxSize) }\n : { minHeight: cssSize(minSize), maxHeight: cssSize(maxSize) }),\n };\n\n const [first, second] = children;\n const paneClasses = \"relative min-h-0 min-w-0 overflow-hidden\";\n const sized = (\n <div\n id={paneId}\n style={sizedStyle}\n className={paneClasses}\n data-collapsed={collapsed ? \"\" : undefined}\n // A closed pane keeps its content mounted (a tree keeps its expansion), but nothing in\n // it may take focus or be read out.\n inert={collapsed}\n >\n {sizedPane === \"start\" ? first : second}\n </div>\n );\n const rest = (\n <div className={cn(paneClasses, \"flex-1 basis-0\")}>{sizedPane === \"start\" ? second : first}</div>\n );\n\n return (\n <div\n ref={attach}\n data-orientation={orientation}\n data-dragging={dragging ? \"\" : undefined}\n data-collapsed={collapsed ? \"\" : undefined}\n className={cn(\n \"flex h-full min-h-0 w-full min-w-0\",\n horizontal ? \"flex-row\" : \"flex-col\",\n dragging && (horizontal ? \"cursor-col-resize select-none\" : \"cursor-row-resize select-none\"),\n className,\n )}\n >\n {sizedPane === \"start\" ? sized : rest}\n <div\n role=\"separator\"\n tabIndex={0}\n aria-label={ariaLabel}\n // The separator's own orientation is across the split: side-by-side panes are divided\n // by a vertical line.\n aria-orientation={horizontal ? \"vertical\" : \"horizontal\"}\n aria-controls={paneId}\n aria-valuenow={size === null ? undefined : Math.round(size)}\n aria-valuemin={limits === null ? undefined : collapsible ? 0 : Math.round(limits.min)}\n aria-valuemax={limits === null ? undefined : Math.round(limits.max)}\n data-dragging={dragging ? \"\" : undefined}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endDrag}\n onPointerCancel={endDrag}\n onKeyDown={onKeyDown}\n className={cn(\n // A 1px rule with a wider invisible hit area on either side of it.\n \"relative z-10 shrink-0 touch-none bg-line transition-colors\",\n \"before:absolute before:content-['']\",\n horizontal\n ? \"w-px cursor-col-resize before:inset-y-0 before:-right-1 before:-left-1\"\n : \"h-px cursor-row-resize before:inset-x-0 before:-top-1 before:-bottom-1\",\n \"hover:bg-signal data-dragging:bg-signal\",\n focusRing,\n )}\n />\n {sizedPane === \"start\" ? rest : sized}\n </div>\n );\n}\n","/*\n * The frame of a studio app: a header across the top, a main surface, optional side panels\n * either side of it, and an optional strip along the bottom.\n *\n * `@vitavision/ui` deliberately has no opinion on how an app fills the viewport — a page\n * scrolls. A studio is the other kind of screen: every surface is permanent, nothing scrolls\n * but the insides of panels, and the side panels are resized by hand. This is that frame,\n * built from `SplitPane`, and nothing more: no routing, no menus, no state of its own beyond\n * the panel sizes it is asked to remember.\n */\n\nimport type { ReactNode } from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\n\nimport { SplitPane } from \"./SplitPane\";\nimport type { PaneSize } from \"./splitSize\";\n\n/** How one side panel of an `AppShell` is sized. */\nexport interface SidePanelSize {\n /** The initial width: pixels or a percentage. */\n defaultSize?: PaneSize | undefined;\n /** The narrowest the panel may be dragged. */\n minSize?: PaneSize | undefined;\n /** The widest the panel may be dragged. */\n maxSize?: PaneSize | undefined;\n /** Lets the panel close (drag it under half its minimum, or Enter on its divider). */\n collapsible?: boolean | undefined;\n}\n\n/** Props of `AppShell`. */\nexport interface AppShellProps {\n /** The top bar: the app's name, the file actions, the theme toggle. */\n header?: ReactNode;\n /** The panel left of the main surface — a navigator such as a `TreeView`. */\n left?: ReactNode;\n /** The main surface — the viewport. Always present. */\n main: ReactNode;\n /** The panel right of the main surface — an inspector. */\n right?: ReactNode;\n /** The strip along the bottom, across the whole width — a `PlaybackBar`, a status line. */\n bottom?: ReactNode;\n /** Names the left panel's landmark (`<aside>`). Defaults to \"Navigator\". */\n leftLabel?: string | undefined;\n /** Names the right panel's landmark (`<aside>`). Defaults to \"Inspector\". */\n rightLabel?: string | undefined;\n /** The left panel's sizing. Defaults to 280 px, 180 px to 50%. */\n leftSize?: SidePanelSize | undefined;\n /** The right panel's sizing. Defaults to 320 px, 220 px to 50%. */\n rightSize?: SidePanelSize | undefined;\n /**\n * Remember the side panels' widths in `localStorage`, under `<storageKey>:left` and\n * `<storageKey>:right`.\n */\n storageKey?: string | undefined;\n /** Merged with the shell's own classes through `cn` — override `h-dvh` to embed it. */\n className?: string | undefined;\n}\n\nconst LEFT_DEFAULTS = { defaultSize: 280, minSize: 180, maxSize: \"50%\" } as const;\nconst RIGHT_DEFAULTS = { defaultSize: 320, minSize: 220, maxSize: \"50%\" } as const;\n\n/**\n * The full-viewport frame of a studio app: `header` across the top, `left` | `main` |\n * `right` in the middle with resizable side panels, `bottom` across the foot. Every slot but\n * `main` is optional, and an absent slot takes no space.\n *\n * Landmarks: the header is a `<header>`, the main surface a `<main>`, the side panels\n * `<aside>`s named by `leftLabel` and `rightLabel`. Each side panel is divided from the main\n * surface by a `SplitPane` divider (drag, or focus it and use the arrow keys). Only the\n * insides of the panels scroll; the shell itself is fixed to the viewport (`h-dvh`).\n */\nexport function AppShell({\n header,\n left,\n main,\n right,\n bottom,\n leftLabel = \"Navigator\",\n rightLabel = \"Inspector\",\n leftSize,\n rightSize,\n storageKey,\n className,\n}: AppShellProps) {\n const leftSizing = { ...LEFT_DEFAULTS, ...leftSize };\n const rightSizing = { ...RIGHT_DEFAULTS, ...rightSize };\n const hasLeft = left !== undefined && left !== null && left !== false;\n const hasRight = right !== undefined && right !== null && right !== false;\n\n const mainSurface = <main className=\"relative h-full min-h-0 min-w-0 overflow-hidden\">{main}</main>;\n\n const withRight = hasRight ? (\n <SplitPane\n sizedPane=\"end\"\n {...rightSizing}\n storageKey={storageKey === undefined ? undefined : `${storageKey}:right`}\n aria-label={`Resize ${rightLabel.toLowerCase()}`}\n >\n {mainSurface}\n <aside aria-label={rightLabel} className=\"h-full overflow-auto bg-surface\">\n {right}\n </aside>\n </SplitPane>\n ) : (\n mainSurface\n );\n\n const middle = hasLeft ? (\n <SplitPane\n sizedPane=\"start\"\n {...leftSizing}\n storageKey={storageKey === undefined ? undefined : `${storageKey}:left`}\n aria-label={`Resize ${leftLabel.toLowerCase()}`}\n >\n <aside aria-label={leftLabel} className=\"h-full overflow-auto bg-surface\">\n {left}\n </aside>\n {withRight}\n </SplitPane>\n ) : (\n withRight\n );\n\n return (\n <div\n className={cn(\n \"grid h-dvh w-full grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden bg-ground text-fg\",\n className,\n )}\n >\n {header ? (\n <header className=\"min-w-0 border-b border-line bg-surface\">{header}</header>\n ) : (\n <div aria-hidden />\n )}\n <div className=\"min-h-0 min-w-0\">{middle}</div>\n {bottom ? <div className=\"min-w-0 border-t border-line bg-surface\">{bottom}</div> : <div aria-hidden />}\n </div>\n );\n}\n","/*\n * The model behind `TreeView`: which rows are visible, where each sits in its set, and what\n * each key does (the WAI-ARIA tree pattern).\n *\n * Kept out of the component so the keyboard contract — the part a tree most often gets\n * subtly wrong — is tested as a function from (rows, focus, key) to an action.\n */\n\nimport type { ReactNode } from \"react\";\n\n/** One node of a `TreeView`. */\nexport interface TreeNode {\n /** Identifies the node to `selectedId`, `onSelect` and `expanded`. Unique in the tree. */\n id: string;\n /** The node's name: shown, read out, and matched by type-ahead. */\n label: string;\n /** A leading icon (decorative) — typically a lucide icon at `size-3.5`. */\n icon?: ReactNode;\n /** Child nodes. A node with a (possibly empty) array is a parent; without, a leaf. */\n children?: readonly TreeNode[] | undefined;\n /** A quiet trailing annotation — a type, a count, a frame name. Shown in mono. */\n meta?: ReactNode;\n /** Shown and focusable, but not selectable. */\n disabled?: boolean | undefined;\n}\n\n/** A node as it is laid out: one visible row of the tree. */\nexport interface TreeRow {\n /** The node. */\n node: TreeNode;\n /** Depth, from 1 at the root (`aria-level`). */\n level: number;\n /** The parent's id, or `null` at the root. */\n parentId: string | null;\n /** 1-based position among its siblings (`aria-posinset`). */\n posInSet: number;\n /** How many siblings, itself included (`aria-setsize`). */\n setSize: number;\n /** Whether the node has a children array. */\n isParent: boolean;\n /** Whether the node is a parent and expanded. */\n isExpanded: boolean;\n}\n\n/**\n * The rows a reader can see: every root, and the children of every expanded parent, in\n * document order.\n *\n * @param nodes - The roots.\n * @param expanded - The ids of the expanded parents.\n * @returns The visible rows, in order.\n */\nexport function visibleRows(nodes: readonly TreeNode[], expanded: ReadonlySet<string>): TreeRow[] {\n const rows: TreeRow[] = [];\n const walk = (siblings: readonly TreeNode[], level: number, parentId: string | null) => {\n siblings.forEach((node, index) => {\n const isParent = node.children !== undefined;\n const isExpanded = isParent && expanded.has(node.id);\n rows.push({\n node,\n level,\n parentId,\n posInSet: index + 1,\n setSize: siblings.length,\n isParent,\n isExpanded,\n });\n if (isExpanded && node.children) walk(node.children, level + 1, node.id);\n });\n };\n walk(nodes, 1, null);\n return rows;\n}\n\n/**\n * Every parent's id — the expanded set for \"everything open\".\n *\n * @param nodes - The roots.\n * @returns The ids of every node with a children array, at any depth.\n */\nexport function parentIds(nodes: readonly TreeNode[]): string[] {\n const ids: string[] = [];\n const walk = (siblings: readonly TreeNode[]) => {\n for (const node of siblings) {\n if (node.children === undefined) continue;\n ids.push(node.id);\n walk(node.children);\n }\n };\n walk(nodes);\n return ids;\n}\n\n/**\n * The ancestors of a node, root first — what must be expanded for it to be visible.\n *\n * @param nodes - The roots.\n * @param id - The node.\n * @returns The ancestor ids, root first; empty for a root or an id not in the tree.\n */\nexport function ancestorIds(nodes: readonly TreeNode[], id: string): string[] {\n const walk = (siblings: readonly TreeNode[], path: string[]): string[] | null => {\n for (const node of siblings) {\n if (node.id === id) return path;\n if (node.children) {\n const found = walk(node.children, [...path, node.id]);\n if (found) return found;\n }\n }\n return null;\n };\n return walk(nodes, []) ?? [];\n}\n\n/** What a key press on a tree asks for. */\nexport type TreeKeyAction =\n | { type: \"focus\"; id: string }\n | { type: \"expand\"; id: string }\n | { type: \"collapse\"; id: string }\n | { type: \"select\"; id: string }\n | { type: \"expand-siblings\"; ids: string[] };\n\n/**\n * The tree's keyboard (the WAI-ARIA tree pattern), as a pure function.\n *\n * ↓/↑ move to the next/previous visible row; → expands a closed parent, or moves into an\n * open one's first child; ← collapses an open parent, or moves to the parent; Home/End go to\n * the first/last visible row; Enter and Space select; `*` expands every sibling of the\n * focused row; a printable character moves to the next row whose label starts with it\n * (type-ahead, wrapping).\n *\n * @param rows - The visible rows, from `visibleRows`.\n * @param focusedId - The row with focus.\n * @param key - `KeyboardEvent.key`.\n * @returns The action, or `null` when the key does nothing here.\n */\nexport function treeKeyAction(rows: readonly TreeRow[], focusedId: string, key: string): TreeKeyAction | null {\n const index = rows.findIndex((row) => row.node.id === focusedId);\n const row = rows[index];\n if (row === undefined) return null;\n const focus = (target: TreeRow | undefined): TreeKeyAction | null =>\n target === undefined || target === row ? null : { type: \"focus\", id: target.node.id };\n\n switch (key) {\n case \"ArrowDown\":\n return focus(rows[index + 1]);\n case \"ArrowUp\":\n return focus(rows[index - 1]);\n case \"Home\":\n return focus(rows[0]);\n case \"End\":\n return focus(rows[rows.length - 1]);\n case \"ArrowRight\":\n if (!row.isParent) return null;\n if (!row.isExpanded) return { type: \"expand\", id: row.node.id };\n // An open parent's first child is the next row, if it has one.\n return rows[index + 1]?.parentId === row.node.id ? focus(rows[index + 1]) : null;\n case \"ArrowLeft\":\n if (row.isExpanded) return { type: \"collapse\", id: row.node.id };\n return row.parentId === null\n ? null\n : focus(rows.find((candidate) => candidate.node.id === row.parentId));\n case \"Enter\":\n case \" \":\n return row.node.disabled ? null : { type: \"select\", id: row.node.id };\n case \"*\": {\n const ids = rows\n .filter((candidate) => candidate.parentId === row.parentId && candidate.isParent && !candidate.isExpanded)\n .map((candidate) => candidate.node.id);\n return ids.length === 0 ? null : { type: \"expand-siblings\", ids };\n }\n default:\n return typeAhead(rows, index, key);\n }\n}\n\n/** The next row after `from` (wrapping) whose label starts with `key`, for a single printable character. */\nfunction typeAhead(rows: readonly TreeRow[], from: number, key: string): TreeKeyAction | null {\n if (key.length !== 1 || key.trim() === \"\") return null;\n const needle = key.toLocaleLowerCase();\n for (let offset = 1; offset <= rows.length; offset += 1) {\n const candidate = rows[(from + offset) % rows.length];\n if (candidate?.node.label.toLocaleLowerCase().startsWith(needle)) {\n return offset === rows.length ? null : { type: \"focus\", id: candidate.node.id };\n }\n }\n return null;\n}\n","/*\n * A hierarchy you can walk with the keyboard.\n *\n * Built for the navigator column of a studio — a robot cell's frame tree, world → robots →\n * links → rigs → cameras — where the tree is data the app already has, the icons are the\n * app's own, and selection is shared with a viewport that can also pick things. So the tree\n * is data-driven, selection is controlled, and selecting something hidden opens the way to it.\n *\n * Rendered flat: one `treeitem` per visible row, carrying its level, position and set size\n * (the WAI-ARIA tree pattern's \"flat\" form). The focus ring then belongs to one row rather\n * than to a subtree, and the keyboard contract is a function over the same list the DOM is\n * — see `treeModel.ts`.\n */\n\nimport { ChevronRight } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent, MouseEvent } from \"react\";\n\nimport { byDensity, cn, useDensity } from \"@vitavision/ui\";\n\nimport {\n type TreeNode,\n type TreeRow,\n ancestorIds,\n parentIds,\n treeKeyAction,\n visibleRows,\n} from \"./treeModel\";\n\n/** Props of `TreeView`. */\nexport interface TreeViewProps {\n /** The roots of the tree. */\n nodes: readonly TreeNode[];\n /** The selected node's id, controlled; `null` or absent for none. */\n selectedId?: string | null | undefined;\n /** Called with the node's id (and the node) on click, Enter or Space. Not called for a disabled node. */\n onSelect?: ((id: string, node: TreeNode) => void) | undefined;\n /** The expanded parents' ids, controlled. Pair with `onExpandedChange`. */\n expanded?: readonly string[] | undefined;\n /** The initially expanded parents' ids, when uncontrolled. */\n defaultExpanded?: readonly string[] | undefined;\n /** Start with every parent expanded, when uncontrolled (overrides `defaultExpanded`). */\n defaultExpandAll?: boolean | undefined;\n /** Called with the new set of expanded ids whenever a parent opens or closes. */\n onExpandedChange?: ((expanded: string[]) => void) | undefined;\n /** Names the tree for assistive technology. */\n \"aria-label\": string;\n /** Merged with the tree's own classes through `cn`. */\n className?: string | undefined;\n}\n\n/**\n * A data-driven tree (the WAI-ARIA tree pattern) with single selection.\n *\n * Keyboard: the tree is one Tab stop (roving `tabindex`). ↓/↑ move between visible rows, →\n * expands a parent or enters it, ← collapses a parent or goes up to its parent, Home/End jump\n * to the ends, Enter/Space select, `*` expands the focused row's siblings, and a letter jumps\n * to the next row starting with it. Clicking a row selects it; clicking its chevron toggles it.\n *\n * Selection is controlled (`selectedId`/`onSelect`). When `selectedId` changes to a node\n * inside a collapsed parent, its ancestors are expanded (through `onExpandedChange` when\n * `expanded` is controlled) and the row is scrolled into view — so a pick in a viewport can\n * drive the tree.\n *\n * Each row is a `treeitem` with `aria-level`, `aria-posinset`, `aria-setsize`,\n * `aria-selected` and, for parents, `aria-expanded`; also `data-selected` and, for parents,\n * `data-state` (`open`/`closed`). Row height follows the density in force.\n */\nexport function TreeView({\n nodes,\n selectedId = null,\n onSelect,\n expanded: controlledExpanded,\n defaultExpanded,\n defaultExpandAll = false,\n onExpandedChange,\n \"aria-label\": ariaLabel,\n className,\n}: TreeViewProps) {\n const density = useDensity();\n const [internalExpanded, setInternalExpanded] = useState<readonly string[]>(() =>\n defaultExpandAll ? parentIds(nodes) : (defaultExpanded ?? []),\n );\n const expandedIds = controlledExpanded ?? internalExpanded;\n const expandedSet = new Set(expandedIds);\n const rows = visibleRows(nodes, expandedSet);\n const [focusedId, setFocusedId] = useState<string | null>(null);\n const rowElementsRef = useRef(new Map<string, HTMLDivElement>());\n\n const setExpanded = (next: readonly string[]) => {\n if (controlledExpanded === undefined) setInternalExpanded(next);\n onExpandedChange?.([...next]);\n };\n\n const toggle = (id: string, open: boolean) => {\n if (open === expandedSet.has(id)) return;\n setExpanded(open ? [...expandedIds, id] : expandedIds.filter((other) => other !== id));\n };\n\n // Reveal a selection made elsewhere: open its ancestors and bring its row into view.\n const latestRef = useRef({ nodes, expandedIds, setExpanded });\n useEffect(() => {\n latestRef.current = { nodes, expandedIds, setExpanded };\n });\n useEffect(() => {\n if (selectedId === null) return;\n const { nodes: tree, expandedIds: open, setExpanded: update } = latestRef.current;\n const missing = ancestorIds(tree, selectedId).filter((id) => !open.includes(id));\n if (missing.length > 0) update([...open, ...missing]);\n }, [selectedId]);\n useEffect(() => {\n if (selectedId === null) return;\n const element = rowElementsRef.current.get(selectedId);\n // `scrollIntoView` is absent in some test DOMs.\n if (typeof element?.scrollIntoView === \"function\") element.scrollIntoView({ block: \"nearest\" });\n }, [selectedId, rows.length]);\n\n const isVisible = (id: string | null) => id !== null && rows.some((row) => row.node.id === id);\n const tabStop = isVisible(focusedId) ? focusedId : isVisible(selectedId) ? selectedId : (rows[0]?.node.id ?? null);\n\n const focusRow = (id: string) => {\n setFocusedId(id);\n rowElementsRef.current.get(id)?.focus();\n };\n\n const select = (row: TreeRow) => {\n if (!row.node.disabled) onSelect?.(row.node.id, row.node);\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.altKey || event.ctrlKey || event.metaKey) return;\n const id = (event.target as HTMLElement).dataset[\"treeId\"];\n if (id === undefined) return;\n const action = treeKeyAction(rows, id, event.key);\n if (action === null) return;\n event.preventDefault();\n switch (action.type) {\n case \"focus\":\n focusRow(action.id);\n break;\n case \"expand\":\n toggle(action.id, true);\n break;\n case \"collapse\":\n toggle(action.id, false);\n break;\n case \"select\": {\n const row = rows.find((candidate) => candidate.node.id === action.id);\n if (row) select(row);\n break;\n }\n case \"expand-siblings\":\n setExpanded([...expandedIds, ...action.ids]);\n break;\n }\n };\n\n const onChevron = (event: MouseEvent, row: TreeRow) => {\n event.stopPropagation();\n toggle(row.node.id, !row.isExpanded);\n focusRow(row.node.id);\n };\n\n return (\n <div\n role=\"tree\"\n aria-label={ariaLabel}\n onKeyDown={onKeyDown}\n className={cn(\"flex flex-col py-1 select-none\", className)}\n >\n {rows.map((row) => {\n const { node } = row;\n const selected = node.id === selectedId;\n return (\n <div\n key={node.id}\n ref={(element) => {\n if (element) rowElementsRef.current.set(node.id, element);\n else rowElementsRef.current.delete(node.id);\n }}\n role=\"treeitem\"\n aria-level={row.level}\n aria-posinset={row.posInSet}\n aria-setsize={row.setSize}\n aria-selected={selected}\n aria-expanded={row.isParent ? row.isExpanded : undefined}\n aria-disabled={node.disabled || undefined}\n tabIndex={node.id === tabStop ? 0 : -1}\n data-tree-id={node.id}\n data-selected={selected ? \"\" : undefined}\n data-state={row.isParent ? (row.isExpanded ? \"open\" : \"closed\") : undefined}\n onFocus={(event) => {\n if (event.target === event.currentTarget) setFocusedId(node.id);\n }}\n onClick={() => {\n focusRow(node.id);\n select(row);\n }}\n style={{ paddingLeft: `calc(${row.level - 1} * 0.875rem + 0.25rem)` }}\n className={cn(\n \"mx-1 flex shrink-0 cursor-default items-center gap-1.5 rounded-control pr-2 text-fg transition-colors\",\n \"outline-none focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-signal\",\n byDensity(density, \"h-7 text-sm\", \"h-6 text-xs\"),\n selected ? \"bg-signal/12\" : \"hover:bg-raised\",\n node.disabled && \"text-fg-subtle\",\n )}\n >\n {row.isParent ? (\n <span\n aria-hidden\n onClick={(event) => onChevron(event, row)}\n className=\"grid size-4 shrink-0 place-items-center rounded-sm text-fg-subtle hover:text-fg\"\n >\n <ChevronRight\n className={cn(\"size-3.5 transition-transform\", row.isExpanded && \"rotate-90\")}\n />\n </span>\n ) : (\n <span aria-hidden className=\"size-4 shrink-0\" />\n )}\n {node.icon !== undefined && (\n <span\n aria-hidden\n className={cn(\n \"grid shrink-0 place-items-center [&>svg]:size-3.5\",\n selected ? \"text-signal\" : \"text-fg-muted\",\n )}\n >\n {node.icon}\n </span>\n )}\n <span className=\"min-w-0 flex-1 truncate\">{node.label}</span>\n {node.meta !== undefined && (\n // On the selected row's tint both `fg-subtle` and `fg-muted` fall below AA at this size.\n <span className={cn(\"shrink-0 font-mono text-[11px]\", selected ? \"text-fg\" : \"text-fg-subtle\")}>\n {node.meta}\n </span>\n )}\n </div>\n );\n })}\n </div>\n );\n}\n","/*\n * Where playback is, as a store outside React.\n *\n * A sampled timeline plays at display rate, and the things that follow it — a robot's joint\n * angles, a camera frustum, a highlighted capture — are drawn by a render loop, not by\n * React. If the current frame lived in React state, every frame of playback would re-render\n * every component that reads it, including the whole scene graph. So it lives here: a tiny\n * store a render loop reads with `get()` at no cost, and that React components subscribe to\n * (through `usePlayhead`) only where they display it — the playback bar, a time readout.\n *\n * The store holds an integer sample index and nothing else that changes per frame. The\n * sub-sample position real-time playback needs is the clock's business (`advance`,\n * `usePlaybackClock`), not the store's, so a reader never sees a fractional frame.\n */\n\n/**\n * A sampled timeline's current position: an external store shared by React and render loops.\n *\n * Every function member may be called detached (`const { get } = playhead`), which is how\n * `useSyncExternalStore` and a render loop hold them.\n */\nexport interface Playhead {\n /** The current sample index, an integer in `0 … count − 1` (0 when `count` is 0). Cheap: call it every frame. */\n readonly get: () => number;\n /**\n * Move to sample `k`. Rounded to an integer and clamped to `0 … count − 1`; listeners are\n * notified only if the index changed.\n */\n readonly set: (k: number) => void;\n /**\n * Be told when the index or the timeline changes.\n *\n * @returns The unsubscribe function.\n */\n readonly subscribe: (listener: () => void) => () => void;\n /** How many samples the timeline has. */\n readonly count: number;\n /** The time between samples, in seconds. Sample `k` is at `t = k · dt`. */\n readonly dt: number;\n /**\n * Swap in a new timeline — a newly loaded or re-baked scenario — keeping the one store\n * every subscriber already holds. The index is clamped into the new range (not reset:\n * call `set(0)` for that). Listeners are notified if anything changed.\n */\n readonly setTimeline: (count: number, dt: number) => void;\n}\n\n/**\n * A playhead over `count` samples spaced `dt` seconds apart, starting at sample 0.\n *\n * Create one per app (not per render — keep it in a `useState` initialiser or module\n * scope), hand it to `PlaybackBar` and to the render loop, and replace its timeline with\n * `setTimeline` when a new scenario loads.\n *\n * @param count - The number of samples (a non-negative integer).\n * @param dt - Seconds between samples (positive).\n * @returns The store.\n */\nexport function createPlayhead(count: number, dt: number): Playhead {\n let index = 0;\n let timeline = checkTimeline(count, dt);\n const listeners = new Set<() => void>();\n const notify = () => {\n for (const listener of [...listeners]) listener();\n };\n\n return {\n get: () => index,\n set: (k) => {\n const next = clampIndex(k, timeline.count);\n if (next === index) return;\n index = next;\n notify();\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n get count() {\n return timeline.count;\n },\n get dt() {\n return timeline.dt;\n },\n setTimeline: (nextCount, nextDt) => {\n const next = checkTimeline(nextCount, nextDt);\n const nextIndex = clampIndex(index, next.count);\n if (next.count === timeline.count && next.dt === timeline.dt && nextIndex === index) return;\n timeline = next;\n index = nextIndex;\n notify();\n },\n };\n}\n\nfunction checkTimeline(count: number, dt: number): { count: number; dt: number } {\n if (!Number.isInteger(count) || count < 0) {\n throw new RangeError(`playhead: count must be a non-negative integer, got ${count}`);\n }\n if (!(dt > 0) || !Number.isFinite(dt)) {\n throw new RangeError(`playhead: dt must be a positive number of seconds, got ${dt}`);\n }\n return { count, dt };\n}\n\n/**\n * A sample index made legal: rounded, and clamped to `0 … count − 1`.\n *\n * @param k - Any number (`NaN` reads as 0).\n * @param count - The number of samples.\n * @returns The index; 0 when `count` is 0.\n */\nexport function clampIndex(k: number, count: number): number {\n if (count <= 0 || Number.isNaN(k)) return 0;\n return Math.min(count - 1, Math.max(0, Math.round(k)));\n}\n\n/** The outcome of one clock step: the new fractional position, and whether playback ran off the end. */\nexport interface AdvanceResult {\n /** The new position in samples (fractional); the index to show is its floor. */\n position: number;\n /** True when a non-looping timeline reached its last sample on this step. */\n ended: boolean;\n}\n\n/**\n * One step of real-time playback, in samples.\n *\n * Each sample is shown for `dt`: a looping timeline has period `count · dt` and wraps from\n * the last sample to the first; a non-looping one stops on the last sample and reports\n * `ended`. The position is fractional so that playback slower than one sample per frame\n * still advances.\n *\n * @param position - The current position in samples (fractional).\n * @param delta - How many samples to advance (elapsed seconds × speed ÷ dt); not negative.\n * @param count - The number of samples.\n * @param loop - Whether to wrap at the end.\n * @returns The new position and whether playback ended.\n */\nexport function advance(position: number, delta: number, count: number, loop: boolean): AdvanceResult {\n if (count <= 1) return { position: 0, ended: !loop };\n const next = position + Math.max(0, delta);\n if (loop) return { position: next % count, ended: false };\n const last = count - 1;\n return next >= last ? { position: last, ended: true } : { position: next, ended: false };\n}\n\n/**\n * The default time readout: seconds with millisecond resolution, `\"1.234 s\"`.\n *\n * @param seconds - The time.\n * @returns The formatted time.\n */\nexport function formatSeconds(seconds: number): string {\n return `${seconds.toFixed(3)} s`;\n}\n","/*\n * The React side of the playhead: subscribing to it, and driving it in real time.\n */\n\nimport { useEffect, useEffectEvent, useSyncExternalStore } from \"react\";\n\nimport { advance, type Playhead } from \"./playhead\";\n\n/**\n * The playhead's current sample index, re-rendering the calling component when it changes.\n *\n * Use it only where the index is *displayed* (the playback bar, a readout). A render loop\n * reads `playhead.get()` in its own frame callback instead, and re-renders nothing.\n *\n * @param playhead - The store.\n * @returns The current sample index.\n */\nexport function usePlayhead(playhead: Playhead): number {\n return useSyncExternalStore(playhead.subscribe, playhead.get, playhead.get);\n}\n\n/**\n * The playhead's timeline — `count` and `dt` — re-rendering when `setTimeline` changes it.\n *\n * @param playhead - The store.\n * @returns The number of samples and the seconds between them.\n */\nexport function usePlayheadTimeline(playhead: Playhead): { count: number; dt: number } {\n const count = useSyncExternalStore(playhead.subscribe, () => playhead.count, () => playhead.count);\n const dt = useSyncExternalStore(playhead.subscribe, () => playhead.dt, () => playhead.dt);\n return { count, dt };\n}\n\n/** Options of `usePlaybackClock`. */\nexport interface PlaybackClockOptions {\n /** The store to advance. */\n playhead: Playhead;\n /** Whether the clock runs. */\n playing: boolean;\n /** Playback rate: 1 is real time. Defaults to 1. */\n speed?: number | undefined;\n /** Wrap from the last sample to the first instead of stopping. Defaults to false. */\n loop?: boolean | undefined;\n /** Called once when a non-looping timeline reaches its last sample; set `playing` false here. */\n onEnd?: (() => void) | undefined;\n /**\n * The longest wall-clock gap one frame may advance by, in milliseconds. A tab in the\n * background gets no animation frames, and without this cap the first frame back would\n * jump by the whole time away. Defaults to 100.\n */\n maxFrameMs?: number | undefined;\n}\n\n/**\n * Advance a playhead in real time × `speed` while `playing`, from `requestAnimationFrame`.\n *\n * Position is accumulated fractionally, so slow playback of a finely sampled timeline still\n * moves; the store only ever holds the integer index. A seek from elsewhere (the scrubber, a\n * marker) is picked up on the next frame. Starting a non-looping timeline that sits on its\n * last sample rewinds it to 0 first. `speed`, `loop` and `onEnd` may change while playing\n * without restarting the clock.\n *\n * Renders nothing and re-renders nothing: call it once, in the component that owns the\n * `playing` state.\n *\n * @param options - The playhead and the transport state.\n */\nexport function usePlaybackClock({\n playhead,\n playing,\n speed = 1,\n loop = false,\n onEnd,\n maxFrameMs = 100,\n}: PlaybackClockOptions): void {\n const step = useEffectEvent((position: number, elapsedMs: number) => {\n const delta = (Math.min(elapsedMs, maxFrameMs) / 1000) * (speed / playhead.dt);\n return advance(position, delta, playhead.count, loop);\n });\n const end = useEffectEvent(() => onEnd?.());\n const rewindIfAtEnd = useEffectEvent(() => {\n if (!loop && playhead.count > 0 && playhead.get() >= playhead.count - 1) playhead.set(0);\n });\n\n useEffect(() => {\n if (!playing) return;\n rewindIfAtEnd();\n let position = playhead.get();\n let last: number | null = null;\n let frame = requestAnimationFrame(function tick(now: number) {\n // A seek since the last frame (scrubber, marker, step button) wins over the clock.\n if (Math.floor(position) !== playhead.get()) position = playhead.get();\n const result = last === null ? { position, ended: false } : step(position, now - last);\n last = now;\n position = result.position;\n playhead.set(Math.floor(position));\n if (result.ended) {\n end();\n return;\n }\n frame = requestAnimationFrame(tick);\n });\n return () => cancelAnimationFrame(frame);\n }, [playing, playhead]);\n}\n","/*\n * The transport for a sampled timeline.\n *\n * Playback state splits by how often it changes. Whether it is playing, how fast, and\n * whether it loops change when someone clicks — ordinary controlled props. Where it is\n * changes every frame — so that is a `Playhead` store the bar subscribes to itself, and a\n * playing timeline re-renders this bar and nothing else in the app.\n *\n * The bar is chrome over a viewport, like the image stage's toolbar: one row, icon buttons\n * named for what they do, the time in mono so it does not jitter as digits change.\n */\n\nimport {\n ChevronFirst,\n ChevronLast,\n Pause,\n Play,\n Repeat,\n SkipBack,\n SkipForward,\n StepBack,\n StepForward,\n} from \"lucide-react\";\nimport type { ComponentPropsWithRef, KeyboardEvent, ReactNode } from \"react\";\n\nimport { type MeasureTone, Select, Slider, byDensity, cn, focusRing, toneColor, useDensity } from \"@vitavision/ui\";\n\nimport { formatSeconds, type Playhead } from \"./playhead\";\nimport { usePlayhead, usePlayheadTimeline } from \"./usePlayback\";\n\n/** A point of interest on the timeline — a capture, an event — drawn as a tick on the scrubber. */\nexport interface PlaybackMarker {\n /** The sample the marker sits on. */\n index: number;\n /** What happens there; names the tick for assistive technology and its tooltip. */\n label?: string | undefined;\n /** The tick's colour. Defaults to `signal`. */\n tone?: MeasureTone | undefined;\n}\n\n/** The speeds offered by default. */\nexport const DEFAULT_SPEEDS: readonly number[] = [0.25, 0.5, 1, 2, 4];\n\n/** Props of `PlaybackBar`. */\nexport interface PlaybackBarProps {\n /** Where playback is. The bar subscribes to it; seeking writes to it. */\n playhead: Playhead;\n /** Whether playback is running, controlled. */\n playing: boolean;\n /** Called with the requested playing state (the play/pause button, Space). */\n onPlayingChange: (playing: boolean) => void;\n /** The playback rate, controlled. Defaults to 1. */\n speed?: number | undefined;\n /** Called with the chosen rate. Without it the speed selector is not shown. */\n onSpeedChange?: ((speed: number) => void) | undefined;\n /** The rates the selector offers. Defaults to 0.25×, 0.5×, 1×, 2×, 4×. */\n speeds?: readonly number[] | undefined;\n /** Whether playback wraps at the end, controlled. */\n loop?: boolean | undefined;\n /** Called with the new loop state. Without it the loop toggle is not shown. */\n onLoopChange?: ((loop: boolean) => void) | undefined;\n /** Ticks on the scrubber, each a click target that seeks to it. */\n markers?: readonly PlaybackMarker[] | undefined;\n /** Called after a marker tick is clicked (the playhead has already moved to it). */\n onMarkerSelect?: ((marker: PlaybackMarker) => void) | undefined;\n /** Formats `t = k · dt` in seconds for the readout. Defaults to `\"1.234 s\"`. */\n formatTime?: ((seconds: number) => string) | undefined;\n /** Names the bar (a `toolbar`). Defaults to \"Playback\". */\n \"aria-label\"?: string | undefined;\n /** Merged with the bar's own classes through `cn`. */\n className?: string | undefined;\n}\n\n/**\n * The transport for a sampled timeline: jump to start, previous marker, step back,\n * play/pause, step forward, next marker, jump to end; a scrubber over the samples with the\n * markers as ticks; the time `t = k · dt`; the speed; loop.\n *\n * `playing`, `speed` and `loop` are controlled props. The position is the `playhead` store,\n * which the bar subscribes to itself — so during playback only the bar re-renders. Drive the\n * store with `usePlaybackClock`, and read `playhead.get()` in a render loop.\n *\n * A `role=\"toolbar\"`. Keyboard, while focus is inside it: the scrubber is a slider (←/→ one\n * sample, PageUp/PageDown ten, Home/End); on the buttons, ←/→ step one sample; Space\n * toggles playback anywhere in the bar except on a button, where it presses the button. The\n * root carries `data-playing` while playing and `data-empty` when the timeline has no samples.\n */\nexport function PlaybackBar({\n playhead,\n playing,\n onPlayingChange,\n speed = 1,\n onSpeedChange,\n speeds = DEFAULT_SPEEDS,\n loop = false,\n onLoopChange,\n markers = [],\n onMarkerSelect,\n formatTime = formatSeconds,\n \"aria-label\": ariaLabel = \"Playback\",\n className,\n}: PlaybackBarProps) {\n const density = useDensity();\n const index = usePlayhead(playhead);\n const { count, dt } = usePlayheadTimeline(playhead);\n const last = Math.max(0, count - 1);\n const empty = count === 0;\n\n const sorted = [...markers].filter((m) => m.index >= 0 && m.index <= last).sort((a, b) => a.index - b.index);\n const previousMarker = sorted.filter((m) => m.index < index).at(-1);\n const nextMarker = sorted.find((m) => m.index > index);\n\n const seek = (k: number) => playhead.set(k);\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n const target = event.target as HTMLElement;\n const onButton = target.tagName === \"BUTTON\";\n if (event.key === \" \" && !onButton && target.getAttribute(\"role\") !== \"combobox\") {\n event.preventDefault();\n if (!empty) onPlayingChange(!playing);\n } else if (onButton && (event.key === \"ArrowLeft\" || event.key === \"ArrowRight\")) {\n event.preventDefault();\n seek(index + (event.key === \"ArrowRight\" ? 1 : -1));\n }\n };\n\n return (\n <div\n role=\"toolbar\"\n aria-label={ariaLabel}\n data-playing={playing ? \"\" : undefined}\n data-empty={empty ? \"\" : undefined}\n onKeyDown={onKeyDown}\n className={cn(\n \"flex w-full min-w-0 items-center bg-surface\",\n byDensity(density, \"gap-3 px-3 py-2\", \"gap-2 px-2 py-1\"),\n className,\n )}\n >\n <div className=\"flex shrink-0 items-center gap-0.5\">\n <BarButton label=\"Jump to start\" onClick={() => seek(0)} disabled={empty || index === 0}>\n <ChevronFirst className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton\n label=\"Previous marker\"\n onClick={() => previousMarker && seek(previousMarker.index)}\n disabled={previousMarker === undefined}\n >\n <SkipBack className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton label=\"Step back\" onClick={() => seek(index - 1)} disabled={empty || index === 0}>\n <StepBack className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton\n label={playing ? \"Pause\" : \"Play\"}\n onClick={() => onPlayingChange(!playing)}\n disabled={empty}\n className=\"text-fg\"\n >\n {playing ? <Pause className=\"size-4\" aria-hidden /> : <Play className=\"size-4\" aria-hidden />}\n </BarButton>\n <BarButton label=\"Step forward\" onClick={() => seek(index + 1)} disabled={empty || index >= last}>\n <StepForward className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton\n label=\"Next marker\"\n onClick={() => nextMarker && seek(nextMarker.index)}\n disabled={nextMarker === undefined}\n >\n <SkipForward className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton label=\"Jump to end\" onClick={() => seek(last)} disabled={empty || index >= last}>\n <ChevronLast className=\"size-4\" aria-hidden />\n </BarButton>\n </div>\n\n <div className=\"relative flex min-w-24 flex-1 flex-col justify-center\">\n {sorted.length > 0 && (\n // The ticks sit on a rail above the track, positioned as Radix positions the thumb:\n // its centre travels from half a thumb (7 px) in from either end.\n <div className=\"relative h-2.5\">\n {sorted.map((marker) => (\n <MarkerTick\n key={`${marker.index}:${marker.label ?? \"\"}`}\n marker={marker}\n fraction={last === 0 ? 0 : marker.index / last}\n time={formatTime(marker.index * dt)}\n active={marker.index === index}\n onClick={() => {\n seek(marker.index);\n onMarkerSelect?.(marker);\n }}\n />\n ))}\n </div>\n )}\n <Slider\n value={index}\n onValueChange={seek}\n min={0}\n max={last}\n step={1}\n disabled={empty}\n aria-label=\"Playback position\"\n />\n </div>\n\n {/* Not an <output>: that is a live region, and this changes every frame. */}\n <span className=\"shrink-0 font-mono text-xs whitespace-nowrap text-fg tabular-nums\">\n <span className=\"text-fg-subtle\">t = </span>\n {formatTime(index * dt)}\n <span className=\"ml-2 text-fg-subtle\">\n {empty ? \"–\" : index}/{last}\n </span>\n </span>\n\n {onSpeedChange && (\n <Select\n value={String(speed)}\n onValueChange={(value) => value !== \"\" && onSpeedChange(Number(value))}\n options={speeds.map((s) => ({ value: String(s), label: `${s}×` }))}\n aria-label=\"Playback speed\"\n className={cn(\"w-20 shrink-0 font-mono\", byDensity(density, \"h-8\", \"h-7\"))}\n />\n )}\n\n {onLoopChange && (\n <BarButton label=\"Loop\" pressed={loop} onClick={() => onLoopChange(!loop)}>\n <Repeat className=\"size-4\" aria-hidden />\n </BarButton>\n )}\n </div>\n );\n}\n\nfunction MarkerTick({\n marker,\n fraction,\n time,\n active,\n onClick,\n}: {\n marker: PlaybackMarker;\n fraction: number;\n time: string;\n active: boolean;\n onClick: () => void;\n}) {\n const name = marker.label ? `${marker.label} (${time})` : `Marker at ${time}`;\n return (\n <button\n type=\"button\"\n // The previous/next-marker buttons are the keyboard's way to the markers; one tab stop\n // per tick would bury the rest of the bar behind a long capture list.\n tabIndex={-1}\n title={name}\n aria-label={name}\n data-active={active ? \"\" : undefined}\n onClick={onClick}\n style={{ left: `calc(7px + ${fraction} * (100% - 14px))` }}\n className=\"group absolute top-0 flex h-full w-2.5 -translate-x-1/2 cursor-pointer justify-center\"\n >\n <span\n aria-hidden\n className=\"h-full w-0.5 rounded-full opacity-70 transition-opacity group-hover:opacity-100 group-data-active:w-1 group-data-active:opacity-100\"\n style={{ backgroundColor: toneColor(marker.tone) }}\n />\n </button>\n );\n}\n\n/** Props of the bar's icon button. */\ninterface BarButtonProps\n extends Omit<ComponentPropsWithRef<\"button\">, \"type\" | \"title\" | \"aria-label\" | \"aria-pressed\" | \"children\"> {\n label: string;\n pressed?: boolean | undefined;\n children: ReactNode;\n}\n\n/** An icon button in the style of `@vitavision/stage2d`'s `StageButton`, sized by density. */\nfunction BarButton({ label, pressed, className, children, ...props }: BarButtonProps) {\n const density = useDensity();\n return (\n <button\n {...props}\n type=\"button\"\n title={label}\n aria-label={label}\n aria-pressed={pressed}\n data-state={pressed === undefined ? undefined : pressed ? \"on\" : \"off\"}\n className={cn(\n \"grid place-items-center rounded-control text-fg-muted transition-colors\",\n byDensity(density, \"size-8\", \"size-7\"),\n \"hover:bg-raised hover:text-fg disabled:pointer-events-none disabled:opacity-40\",\n pressed && \"bg-signal/15 text-signal\",\n focusRing,\n className,\n )}\n >\n {children}\n </button>\n );\n}\n","/*\n * What `FileDrop` does with a drop: which files match `accept`, and what a dropped folder\n * contains.\n *\n * The browser enforces `accept` only in the file picker, and only as a hint; a drop brings\n * whatever was dragged. So the filter is applied here, to both routes. And a dropped folder\n * arrives as a zero-byte \"file\" unless its entries are walked — which is how a scenario\n * folder (a scene, a scenario, its meshes) is opened in one gesture.\n */\n\n/**\n * Whether a file matches an `accept` string, as `<input type=\"file\" accept>` reads it:\n * comma-separated extensions (`.json`), MIME types (`application/json`) and MIME wildcards\n * (`image/*`). Matching is case-insensitive.\n *\n * @param file - The file's name and MIME type.\n * @param accept - The accept string; empty or absent accepts everything.\n * @returns Whether the file is accepted.\n */\nexport function acceptsFile(file: { name: string; type: string }, accept: string | undefined): boolean {\n const tokens = (accept ?? \"\")\n .split(\",\")\n .map((token) => token.trim().toLowerCase())\n .filter((token) => token !== \"\");\n if (tokens.length === 0) return true;\n const name = file.name.toLowerCase();\n const type = file.type.toLowerCase();\n return tokens.some((token) => {\n if (token.startsWith(\".\")) return name.endsWith(token);\n if (token.endsWith(\"/*\")) return type.startsWith(token.slice(0, -1));\n return type === token;\n });\n}\n\n/**\n * Split files by `accept`.\n *\n * @param files - The candidates.\n * @param accept - The accept string.\n * @returns The accepted files and the rejected ones, each in their original order.\n */\nexport function partitionFiles(\n files: readonly File[],\n accept: string | undefined,\n): { accepted: File[]; rejected: File[] } {\n const accepted: File[] = [];\n const rejected: File[] = [];\n for (const file of files) (acceptsFile(file, accept) ? accepted : rejected).push(file);\n return { accepted, rejected };\n}\n\n/**\n * Whether a drag carries files (rather than text or a link) — the only drags `FileDrop`\n * reacts to.\n *\n * @param dataTransfer - The drag's data, or `null`.\n * @returns Whether `Files` is among its types.\n */\nexport function carriesFiles(dataTransfer: Pick<DataTransfer, \"types\"> | null): boolean {\n return dataTransfer !== null && Array.from(dataTransfer.types).includes(\"Files\");\n}\n\n/** The part of the File and Directory Entries API a drop walk needs (`webkitGetAsEntry`). */\nexport interface DropEntry {\n /** A file (`FileSystemFileEntry`). */\n isFile: boolean;\n /** A folder (`FileSystemDirectoryEntry`). */\n isDirectory: boolean;\n /** The entry's own name. */\n name: string;\n /** The entry's path from the drop root, with a leading `/`. */\n fullPath: string;\n /** A file entry's contents, as a `File`. */\n file?: (success: (file: File) => void, failure?: (error: unknown) => void) => void;\n /** A folder entry's reader; `readEntries` yields the children in batches, then an empty one. */\n createReader?: () => {\n readEntries: (success: (entries: DropEntry[]) => void, failure?: (error: unknown) => void) => void;\n };\n}\n\n/**\n * Every file in a drop, with dropped folders walked recursively.\n *\n * Files found inside a folder carry `webkitRelativePath` (`scene/meshes/base.glb`), as the\n * files of `<input webkitdirectory>` do, so both routes give the same shape. Where the entries\n * API is missing, the drop's plain file list is returned.\n *\n * @param dataTransfer - The drop's data.\n * @returns The files, in the order the browser listed them.\n */\nexport async function collectDroppedFiles(\n dataTransfer: Pick<DataTransfer, \"files\" | \"items\">,\n): Promise<File[]> {\n // Everything is read before the first `await`: a drop's data is emptied once its event\n // handler returns.\n const plain = Array.from(dataTransfer.files);\n const entries = Array.from(dataTransfer.items ?? [])\n .filter((item) => item.kind === \"file\")\n .map((item) => (typeof item.webkitGetAsEntry === \"function\" ? (item.webkitGetAsEntry() as DropEntry | null) : null));\n // No folder among them (or no entries API): the plain list is already the answer.\n if (!entries.some((entry) => entry?.isDirectory)) return plain;\n const files: File[] = [];\n for (const entry of entries) if (entry) await walkEntry(entry, files);\n return files;\n}\n\nasync function walkEntry(entry: DropEntry, out: File[]): Promise<void> {\n if (entry.isFile && entry.file) {\n const read = entry.file.bind(entry);\n const file = await new Promise<File>((resolve, reject) => read(resolve, reject));\n const path = entry.fullPath.replace(/^\\//, \"\");\n out.push(path.includes(\"/\") ? withRelativePath(file, path) : file);\n } else if (entry.isDirectory && entry.createReader) {\n const reader = entry.createReader();\n // `readEntries` returns a directory in batches (100 in Chromium) until an empty one.\n for (;;) {\n const batch = await new Promise<DropEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));\n if (batch.length === 0) break;\n for (const child of batch) await walkEntry(child, out);\n }\n }\n}\n\n/**\n * The file, carrying `webkitRelativePath` — a read-only accessor on `File.prototype`,\n * shadowed here on the instance.\n */\nfunction withRelativePath(file: File, path: string): File {\n Object.defineProperty(file, \"webkitRelativePath\", { value: path, configurable: true });\n return file;\n}\n","/*\n * Opening local files: by dropping them, or through the picker.\n *\n * Both routes are always offered. A drop target alone is invisible to a keyboard and to\n * anyone who does not know it is there; a picker alone makes a folder of scenario files a\n * dozen clicks. The picker is a real `<button>`, so the component is operable without a\n * pointer.\n */\n\nimport { FolderOpen } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport type { ChangeEvent, DragEvent, ReactNode } from \"react\";\n\nimport { Button, cn } from \"@vitavision/ui\";\n\nimport { carriesFiles, collectDroppedFiles, partitionFiles } from \"./dropFiles\";\n\n/** Props of `FileDrop`. */\nexport interface FileDropProps {\n /** Called with the accepted files of a drop or a pick (never with an empty list). */\n onFiles: (files: File[]) => void;\n /** Called with the files a drop or a pick brought that `accept` turned away. */\n onReject?: ((files: File[]) => void) | undefined;\n /**\n * Which files to take, as `<input accept>`: extensions (`.json`), MIME types and MIME\n * wildcards (`image/*`), comma-separated. Applied to drops as well as the picker. Default: all.\n */\n accept?: string | undefined;\n /** Take several files at once. Defaults to true; when false only the first accepted file is passed. */\n multiple?: boolean | undefined;\n /**\n * The picker chooses a folder (`webkitdirectory`) instead of files. Dropped folders are\n * walked either way; files found in a folder carry `webkitRelativePath`.\n */\n directory?: boolean | undefined;\n /**\n * Take drops anywhere in the window, showing a full-window overlay while files are dragged\n * over it; the component itself then renders only the picker button (for a header). Without\n * it, the component is an inline drop zone.\n */\n overlay?: boolean | undefined;\n /** Refuses drops and blocks the picker. */\n disabled?: boolean | undefined;\n /** The picker button's label. Defaults to \"Open files…\" (or \"Open folder…\" with `directory`). */\n buttonLabel?: string | undefined;\n /** The overlay's message. Defaults to \"Drop to open\". */\n overlayMessage?: ReactNode;\n /** The inline zone's message, before the button. Defaults to \"Drop files here, or\". */\n children?: ReactNode;\n /** Merged with the zone's (or, with `overlay`, the button's) own classes through `cn`. */\n className?: string | undefined;\n}\n\n/**\n * A drop target plus an \"Open files…\" button over a hidden `<input type=\"file\">`.\n *\n * Inline (the default) it is a dashed zone with a message and the button, carrying\n * `data-dragging` while files are dragged over it. With `overlay` it renders only the button\n * and takes drops anywhere in the window, showing a full-window overlay (`aria-hidden`: the\n * button is the accessible route) while a drag carrying files is over the window. Only drags\n * that carry files are reacted to; text and links pass through.\n *\n * Files are filtered by `accept` on both routes (the browser applies it to neither drops nor,\n * reliably, the picker); the rest go to `onReject`. A dropped folder is walked recursively.\n */\nexport function FileDrop({\n onFiles,\n onReject,\n accept,\n multiple = true,\n directory = false,\n overlay = false,\n disabled = false,\n buttonLabel,\n overlayMessage = \"Drop to open\",\n children = \"Drop files here, or\",\n className,\n}: FileDropProps) {\n const inputRef = useRef<HTMLInputElement | null>(null);\n const depthRef = useRef(0);\n const [dragging, setDragging] = useState(false);\n const label = buttonLabel ?? (directory ? \"Open folder…\" : \"Open files…\");\n\n const deliver = (files: readonly File[]) => {\n const { accepted, rejected } = partitionFiles(files, accept);\n if (accepted.length > 0) onFiles(multiple ? accepted : accepted.slice(0, 1));\n if (rejected.length > 0) onReject?.(rejected);\n };\n const deliverRef = useRef(deliver);\n useEffect(() => {\n deliverRef.current = deliver;\n });\n\n // The window-wide target. `dragenter`/`dragleave` fire for every element crossed, so the\n // overlay's visibility is a depth count rather than the last event seen.\n useEffect(() => {\n if (!overlay || disabled) return;\n const onEnter = (event: globalThis.DragEvent) => {\n if (!carriesFiles(event.dataTransfer)) return;\n depthRef.current += 1;\n setDragging(true);\n };\n const onLeave = (event: globalThis.DragEvent) => {\n if (!carriesFiles(event.dataTransfer)) return;\n depthRef.current = Math.max(0, depthRef.current - 1);\n if (depthRef.current === 0) setDragging(false);\n };\n const onOver = (event: globalThis.DragEvent) => {\n if (!carriesFiles(event.dataTransfer)) return;\n event.preventDefault();\n if (event.dataTransfer) event.dataTransfer.dropEffect = \"copy\";\n };\n const onDrop = (event: globalThis.DragEvent) => {\n if (!event.dataTransfer || !carriesFiles(event.dataTransfer)) return;\n event.preventDefault();\n depthRef.current = 0;\n setDragging(false);\n void collectDroppedFiles(event.dataTransfer).then((files) => deliverRef.current(files));\n };\n window.addEventListener(\"dragenter\", onEnter);\n window.addEventListener(\"dragleave\", onLeave);\n window.addEventListener(\"dragover\", onOver);\n window.addEventListener(\"drop\", onDrop);\n return () => {\n window.removeEventListener(\"dragenter\", onEnter);\n window.removeEventListener(\"dragleave\", onLeave);\n window.removeEventListener(\"dragover\", onOver);\n window.removeEventListener(\"drop\", onDrop);\n depthRef.current = 0;\n };\n }, [overlay, disabled]);\n\n const onPick = (event: ChangeEvent<HTMLInputElement>) => {\n const files = Array.from(event.currentTarget.files ?? []);\n // Cleared so that choosing the same file again is still a change.\n event.currentTarget.value = \"\";\n if (files.length > 0) deliver(files);\n };\n\n const picker = (\n <>\n <input\n ref={(element) => {\n inputRef.current = element;\n if (element) element.webkitdirectory = directory;\n }}\n type=\"file\"\n hidden\n tabIndex={-1}\n accept={accept}\n multiple={multiple || directory}\n disabled={disabled}\n onChange={onPick}\n />\n <Button\n icon={<FolderOpen />}\n disabled={disabled}\n onClick={() => inputRef.current?.click()}\n className={overlay ? className : undefined}\n >\n {label}\n </Button>\n </>\n );\n\n if (overlay) {\n return (\n <>\n {picker}\n {dragging && (\n <div\n aria-hidden\n data-dragging=\"\"\n className=\"pointer-events-none fixed inset-0 z-50 grid place-items-center bg-ground/80 p-8 backdrop-blur-sm\"\n >\n <div className=\"rounded-panel border-2 border-dashed border-signal bg-surface px-10 py-8 text-sm font-medium text-fg shadow-lg\">\n {overlayMessage}\n </div>\n </div>\n )}\n </>\n );\n }\n\n const zoneDrag = (event: DragEvent<HTMLDivElement>, change: 1 | -1 | 0) => {\n if (disabled || !carriesFiles(event.dataTransfer)) return;\n event.preventDefault();\n if (change === 0) {\n event.dataTransfer.dropEffect = \"copy\";\n return;\n }\n depthRef.current = Math.max(0, depthRef.current + change);\n setDragging(depthRef.current > 0);\n };\n\n return (\n <div\n data-dragging={dragging ? \"\" : undefined}\n data-disabled={disabled ? \"\" : undefined}\n onDragEnter={(event) => zoneDrag(event, 1)}\n onDragLeave={(event) => zoneDrag(event, -1)}\n onDragOver={(event) => zoneDrag(event, 0)}\n onDrop={(event) => {\n if (disabled || !carriesFiles(event.dataTransfer)) return;\n event.preventDefault();\n depthRef.current = 0;\n setDragging(false);\n void collectDroppedFiles(event.dataTransfer).then(deliver);\n }}\n className={cn(\n \"flex flex-col items-center justify-center gap-3 rounded-panel border-2 border-dashed border-line-strong px-6 py-8 text-center text-sm text-fg-muted transition-colors\",\n \"data-dragging:border-signal data-dragging:bg-signal/8 data-dragging:text-fg\",\n // Not `opacity-50`: the message would fall below AA. The disabled button and the quieter\n // border say it instead.\n \"data-disabled:border-line\",\n className,\n )}\n >\n <p>{children}</p>\n {picker}\n </div>\n );\n}\n","/*\n * Notifications, as a store any module can write to.\n *\n * A toast is raised from wherever the news is — a file loader, a worker's error handler, a\n * bake that finished — which is rarely a component with a context in reach. So `toast()` is\n * a plain function over a module-level store, and `<Toaster />`, mounted once, is its only\n * reader. The store holds no timers and touches no DOM: auto-dismissal belongs to the\n * `Toaster`, which is what knows whether a reader is hovering it.\n */\n\n/** A toast's kind: a fact (`info`), a completed action (`success`), a caveat (`warn`), a failure (`error`). */\nexport type ToastTone = \"info\" | \"success\" | \"warn\" | \"error\";\n\n/** What `toast()` takes. */\nexport interface ToastOptions {\n /** One line: what happened. */\n title: string;\n /** More detail, and what to do about it. */\n description?: string | undefined;\n /** Defaults to `info`. */\n tone?: ToastTone | undefined;\n /**\n * How long it stays, in milliseconds, while not hovered or focused. Defaults to 5000\n * (8000 for `error`); `Infinity` keeps it until dismissed.\n */\n duration?: number | undefined;\n /** Replace the toast with this id instead of adding one — for progress that updates in place. */\n id?: string | undefined;\n}\n\n/** A toast in the store. */\nexport interface ToastRecord {\n /** Identifies the toast to `dismiss` and to `id` replacement. */\n id: string;\n /** One line: what happened. */\n title: string;\n /** More detail, if any. */\n description: string | undefined;\n /** Its kind. */\n tone: ToastTone;\n /** Milliseconds before it dismisses itself (`Infinity`: never). */\n duration: number;\n}\n\n/**\n * A toast store: what `toast()` writes to and `<Toaster />` reads. Every member may be called\n * detached.\n */\nexport interface ToastStore {\n /** Add a toast (or replace the one with `options.id`), returning its id. */\n readonly toast: (options: ToastOptions) => string;\n /** Remove one toast, or every toast when `id` is omitted. */\n readonly dismiss: (id?: string) => void;\n /** The toasts, oldest first. The same array until the store changes. */\n readonly getSnapshot: () => readonly ToastRecord[];\n /** Be told when the toasts change; returns the unsubscribe function. */\n readonly subscribe: (listener: () => void) => () => void;\n}\n\nconst DEFAULT_DURATION = 5000;\nconst ERROR_DURATION = 8000;\n\n/**\n * A new, empty toast store. The package keeps one (behind `toast()` and the default\n * `<Toaster />`); create another only to isolate a region or a test.\n *\n * @returns The store.\n */\nexport function createToastStore(): ToastStore {\n let toasts: readonly ToastRecord[] = [];\n let sequence = 0;\n const listeners = new Set<() => void>();\n const commit = (next: readonly ToastRecord[]) => {\n toasts = next;\n for (const listener of [...listeners]) listener();\n };\n\n return {\n toast: (options) => {\n const tone = options.tone ?? \"info\";\n sequence += 1;\n const record: ToastRecord = {\n id: options.id ?? `toast-${sequence}`,\n title: options.title,\n description: options.description,\n tone,\n duration: options.duration ?? (tone === \"error\" ? ERROR_DURATION : DEFAULT_DURATION),\n };\n const existing = toasts.findIndex((t) => t.id === record.id);\n commit(existing === -1 ? [...toasts, record] : toasts.map((t, i) => (i === existing ? record : t)));\n return record.id;\n },\n dismiss: (id) => {\n if (id === undefined) {\n if (toasts.length > 0) commit([]);\n return;\n }\n if (toasts.some((t) => t.id === id)) commit(toasts.filter((t) => t.id !== id));\n },\n getSnapshot: () => toasts,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n\n/** The store behind `toast()` and a `<Toaster />` given no `store`. */\nexport const defaultToastStore: ToastStore = createToastStore();\n\n/**\n * Raise a notification, from anywhere — shown by the mounted `<Toaster />`.\n *\n * `toast({ title: \"Scenario loaded\", tone: \"success\" })`. Pass `id` to update a toast in\n * place (a progress message that becomes a result). `toast.dismiss(id)` removes one early,\n * `toast.dismiss()` all of them.\n *\n * @param options - The message, its tone and its duration.\n * @returns The toast's id.\n */\nexport const toast: ((options: ToastOptions) => string) & {\n /** Remove one toast, or every toast when `id` is omitted. */\n dismiss: (id?: string) => void;\n} = Object.assign((options: ToastOptions) => defaultToastStore.toast(options), {\n dismiss: (id?: string) => defaultToastStore.dismiss(id),\n});\n","/*\n * Where `toast()` shows up.\n *\n * Toasts are for news that does not need an answer — a file loaded, a bake finished, a\n * worker failed in the background. Anything that must be acknowledged is a `Dialog`, and\n * anything tied to one control is that control's `Field` error. So a toast never carries an\n * action beyond dismissing it, it goes away by itself, and it holds still while someone is\n * reading it (pointer over the stack, or focus inside it).\n *\n * The tones reuse the `Callout` vocabulary — the accent for a fact, the verdict colours for\n * success, caveat and failure — on an opaque `overlay` surface, since a toast floats over\n * whatever the viewport is drawing.\n */\n\nimport { CircleCheck, CircleX, Info, TriangleAlert, X } from \"lucide-react\";\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { FocusEvent } from \"react\";\n\nimport { cn, focusRing } from \"@vitavision/ui\";\n\nimport { defaultToastStore, type ToastRecord, type ToastStore, type ToastTone } from \"./toastStore\";\n\nconst TONE: Record<ToastTone, { border: string; icon: string; Icon: typeof Info }> = {\n info: { border: \"border-signal/30\", icon: \"text-signal\", Icon: Info },\n success: { border: \"border-normal/30\", icon: \"text-normal\", Icon: CircleCheck },\n warn: { border: \"border-warn/30\", icon: \"text-warn\", Icon: TriangleAlert },\n error: { border: \"border-defect/30\", icon: \"text-defect\", Icon: CircleX },\n};\n\nconst NO_TOASTS: readonly ToastRecord[] = [];\n\n/** Props of `Toaster`. */\nexport interface ToasterProps {\n /** The store to show. Defaults to the one behind `toast()`. */\n store?: ToastStore | undefined;\n /** How many toasts are shown at once; older ones wait. Defaults to 5. */\n limit?: number | undefined;\n /** Merged with the stack's own classes through `cn` (it is fixed to the bottom-right corner). */\n className?: string | undefined;\n}\n\n/**\n * The stack of notifications raised with `toast()`. Mount it once, near the root.\n *\n * Fixed to the bottom-right corner, newest at the bottom. Each toast dismisses itself after\n * its `duration`; the countdown pauses while the pointer is over the stack or focus is inside\n * it. A `section` landmark (\"Notifications\") holding a polite live region, so new toasts are\n * announced; an `error` toast is a `role=\"alert\"`, announced at once. Each toast carries\n * `data-tone` and a \"Dismiss\" button.\n */\nexport function Toaster({ store = defaultToastStore, limit = 5, className }: ToasterProps) {\n const toasts = useSyncExternalStore(store.subscribe, store.getSnapshot, () => NO_TOASTS);\n const [hovered, setHovered] = useState(false);\n const [focused, setFocused] = useState(false);\n const shown = toasts.slice(-Math.max(1, limit));\n\n const onBlur = (event: FocusEvent<HTMLElement>) => {\n if (!event.currentTarget.contains(event.relatedTarget)) setFocused(false);\n };\n\n return (\n <section\n aria-label=\"Notifications\"\n onPointerEnter={() => setHovered(true)}\n onPointerLeave={() => setHovered(false)}\n onFocus={() => setFocused(true)}\n onBlur={onBlur}\n className={cn(\n \"pointer-events-none fixed right-4 bottom-4 z-50 w-80 max-w-[calc(100vw-2rem)]\",\n className,\n )}\n >\n <ol aria-live=\"polite\" className=\"flex flex-col gap-2\">\n {shown.map((record) => (\n <ToastItem\n key={record.id}\n record={record}\n paused={hovered || focused}\n onDismiss={() => store.dismiss(record.id)}\n />\n ))}\n </ol>\n </section>\n );\n}\n\nfunction ToastItem({\n record,\n paused,\n onDismiss,\n}: {\n record: ToastRecord;\n paused: boolean;\n onDismiss: () => void;\n}) {\n const { border, icon, Icon } = TONE[record.tone];\n // What is left of the countdown, carried across pauses; restarted when the toast is\n // replaced in place (a new record under the same id).\n const remainingRef = useRef({ record, ms: record.duration });\n const dismissRef = useRef(onDismiss);\n useEffect(() => {\n dismissRef.current = onDismiss;\n });\n\n useEffect(() => {\n if (remainingRef.current.record !== record) remainingRef.current = { record, ms: record.duration };\n if (paused || !Number.isFinite(remainingRef.current.ms)) return;\n const started = Date.now();\n const timer = setTimeout(() => dismissRef.current(), remainingRef.current.ms);\n return () => {\n clearTimeout(timer);\n remainingRef.current.ms = Math.max(0, remainingRef.current.ms - (Date.now() - started));\n };\n }, [paused, record]);\n\n return (\n // The `alert` role sits on the toast inside the list item, not on the `<li>`: an item with\n // another role is no longer a list item, and the list would be malformed.\n <li className=\"pointer-events-auto\">\n <div\n role={record.tone === \"error\" ? \"alert\" : undefined}\n data-tone={record.tone}\n className={cn(\n \"flex items-start gap-2.5 rounded-panel border bg-overlay px-3 py-2.5 text-sm leading-snug shadow-lg shadow-black/25\",\n \"transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0\",\n border,\n )}\n >\n <Icon className={cn(\"mt-0.5 size-4 shrink-0\", icon)} aria-hidden />\n <div className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <p className=\"font-medium text-fg\">{record.title}</p>\n {record.description && <p className=\"text-fg-muted\">{record.description}</p>}\n </div>\n <button\n type=\"button\"\n aria-label=\"Dismiss\"\n title=\"Dismiss\"\n onClick={onDismiss}\n className={cn(\n \"-mr-1 grid size-6 shrink-0 place-items-center rounded-control text-fg-subtle transition-colors hover:bg-raised hover:text-fg\",\n focusRing,\n )}\n >\n <X className=\"size-3.5\" aria-hidden />\n </button>\n </div>\n </li>\n );\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,SAAgB,YAAY,MAAgB,QAAwB;CAClE,MAAM,KAAK,OAAO,SAAS,WAAW,OAAQ,OAAO,WAAW,IAAI,IAAI,MAAO;CAC/E,OAAO,OAAO,SAAS,EAAE,IAAI,KAAK,IAAI,GAAG,EAAE,IAAI;AACjD;;;;;;;;;;;AAYA,SAAgB,cACd,QACA,UAAoB,GACpB,UAAoB,QACpB,cAAc,OACD;CACb,MAAM,MAAM,KAAK,IAAI,YAAY,SAAS,MAAM,GAAG,KAAK,IAAI,GAAG,MAAM,CAAC;CAEtE,OAAO;EAAE,KADG,KAAK,IAAI,YAAY,SAAS,MAAM,GAAG,GACxC;EAAG;EAAK;CAAY;AACjC;;;;;;;;;AAUA,SAAgB,UAAU,MAAc,QAA6B;CACnE,IAAI,OAAO,eAAe,OAAO,OAAO,MAAM,GAAG,OAAO;CACxD,OAAO,KAAK,MAAM,KAAK,IAAI,OAAO,KAAK,KAAK,IAAI,OAAO,KAAK,IAAI,CAAC,CAAC;AACpE;;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C;CAED,gBAAgB;EACd,IAAI,aAAa,QAAQ,WAAW,QAAQ,aAAa,UAAU;GAAE;GAAQ,IAAI,OAAO;EAAS;EACjG,IAAI,UAAU,CAAC,OAAO,SAAS,aAAa,QAAQ,EAAE,GAAG;EACzD,MAAM,UAAU,KAAK,IAAI;EACzB,MAAM,QAAQ,iBAAiB,WAAW,QAAQ,GAAG,aAAa,QAAQ,EAAE;EAC5E,aAAa;GACX,aAAa,KAAK;GAClB,aAAa,QAAQ,KAAK,KAAK,IAAI,GAAG,aAAa,QAAQ,MAAM,KAAK,IAAI,IAAI,QAAQ;EACxF;CACF,GAAG,CAAC,QAAQ,MAAM,CAAC;CAEnB,OAGE,oBAAC,MAAD;EAAI,WAAU;EACZ,UAAA,qBAAC,OAAD;GACE,MAAM,OAAO,SAAS,UAAU,UAAU,KAAA;GAC1C,aAAW,OAAO;GAClB,WAAW,GACT,uHACA,yFACA,MACF;GAPF,UAAA;IASE,oBAAC,MAAD;KAAM,WAAW,GAAG,0BAA0B,IAAI;KAAG,eAAA;IAAa,CAAA;IAClE,qBAAC,OAAD;KAAK,WAAU;KAAf,UAAA,CACE,oBAAC,KAAD;MAAG,WAAU;MAAuB,UAAA,OAAO;KAAS,CAAA,GACnD,OAAO,eAAe,oBAAC,KAAD;MAAG,WAAU;MAAiB,UAAA,OAAO;KAAe,CAAA,CACxE;;IACL,oBAAC,UAAD;KACE,MAAK;KACL,cAAW;KACX,OAAM;KACN,SAAS;KACT,WAAW,GACT,gIACA,SACF;KAEA,UAAA,oBAAC,GAAD;MAAG,WAAU;MAAW,eAAA;KAAa,CAAA;IAC/B,CAAA;GACL;;CACH,CAAA;AAER"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/components/splitSize.ts","../src/components/SplitPane.tsx","../src/components/AppShell.tsx","../src/components/treeModel.ts","../src/components/TreeView.tsx","../src/components/playhead.ts","../src/components/usePlayback.ts","../src/components/PlaybackBar.tsx","../src/components/dropFiles.ts","../src/components/FileDrop.tsx"],"sourcesContent":["/*\n * The arithmetic behind `SplitPane`: resolving sizes given in pixels or percent, clamping a\n * drag or a key press to the pane's limits, and remembering a size across reloads.\n *\n * Kept out of the component so every rule — which key moves the divider which way, where a\n * collapsible pane snaps shut — is tested without a DOM.\n */\n\n/**\n * A pane size: CSS pixels as a number, or a share of the split's length as a percentage\n * string (`\"30%\"`).\n */\nexport type PaneSize = number | `${number}%`;\n\n/** The limits a `SplitPane`'s sized pane is held to, resolved to pixels. */\nexport interface SplitLimits {\n /** The smallest open size, in pixels. */\n min: number;\n /** The largest size, in pixels. */\n max: number;\n /** Whether the pane may close to 0 below `min`. */\n collapsible: boolean;\n}\n\n/**\n * A size in pixels.\n *\n * @param size - Pixels, or a percentage of `length`.\n * @param length - The split's length along its axis, in pixels.\n * @returns The size in pixels (never negative).\n */\nexport function resolveSize(size: PaneSize, length: number): number {\n const px = typeof size === \"number\" ? size : (Number.parseFloat(size) / 100) * length;\n return Number.isFinite(px) ? Math.max(0, px) : 0;\n}\n\n/**\n * The limits in pixels for a split of `length`. `max` never exceeds `length`, and `min`\n * never exceeds `max`.\n *\n * @param length - The split's length along its axis, in pixels.\n * @param minSize - The smallest open size. Defaults to 0.\n * @param maxSize - The largest size. Defaults to the whole length.\n * @param collapsible - Whether the pane may close below `minSize`.\n * @returns The resolved limits.\n */\nexport function resolveLimits(\n length: number,\n minSize: PaneSize = 0,\n maxSize: PaneSize = \"100%\",\n collapsible = false,\n): SplitLimits {\n const max = Math.min(resolveSize(maxSize, length), Math.max(0, length));\n const min = Math.min(resolveSize(minSize, length), max);\n return { min, max, collapsible };\n}\n\n/**\n * Hold a proposed size to the limits. A collapsible pane dragged below half its minimum\n * snaps shut (0); between half the minimum and the minimum it stays at the minimum.\n *\n * @param size - The proposed size, in pixels.\n * @param limits - The resolved limits.\n * @returns The size to apply, in pixels, rounded to whole pixels.\n */\nexport function clampSize(size: number, limits: SplitLimits): number {\n if (limits.collapsible && size < limits.min / 2) return 0;\n return Math.round(Math.min(limits.max, Math.max(limits.min, size)));\n}\n\n/** Which way a `SplitPane` lays out its two panes. */\nexport type SplitOrientation = \"horizontal\" | \"vertical\";\n\n/** Which of the two panes carries the explicit size; the other takes the rest. */\nexport type SizedPane = \"start\" | \"end\";\n\n/** What a key press on the divider asks for. */\nexport type SplitKeyAction =\n | { type: \"resize\"; size: number }\n | { type: \"toggle-collapse\" };\n\n/**\n * The divider's keyboard (the WAI-ARIA window-splitter pattern).\n *\n * The arrow keys along the split's axis move the divider the way they point — so the sized\n * pane grows or shrinks depending on which side it is on — by `step`, or four steps with\n * Shift. Home gives the sized pane its minimum, End its maximum, and Enter collapses or\n * restores a collapsible pane.\n *\n * @param key - `KeyboardEvent.key`.\n * @param shift - Whether Shift is held.\n * @param size - The sized pane's current size, in pixels.\n * @param options - The layout, the step in pixels and the resolved limits.\n * @returns The action, or `null` when the key is not the divider's.\n */\nexport function splitKeyAction(\n key: string,\n shift: boolean,\n size: number,\n options: { orientation: SplitOrientation; sizedPane: SizedPane; step: number; limits: SplitLimits },\n): SplitKeyAction | null {\n const { orientation, sizedPane, step, limits } = options;\n const [back, forward] =\n orientation === \"horizontal\" ? [\"ArrowLeft\", \"ArrowRight\"] : [\"ArrowUp\", \"ArrowDown\"];\n const grow = sizedPane === \"start\" ? 1 : -1;\n const delta = shift ? step * 4 : step;\n\n switch (key) {\n case forward:\n return { type: \"resize\", size: clampOpen(size + grow * delta, limits) };\n case back:\n return { type: \"resize\", size: clampOpen(size - grow * delta, limits) };\n case \"Home\":\n return { type: \"resize\", size: Math.round(limits.min) };\n case \"End\":\n return { type: \"resize\", size: Math.round(limits.max) };\n case \"Enter\":\n return limits.collapsible ? { type: \"toggle-collapse\" } : null;\n default:\n return null;\n }\n}\n\n/** A key step never snaps a pane shut (that is Enter's job): clamp to the open range. */\nfunction clampOpen(size: number, limits: SplitLimits): number {\n return Math.round(Math.min(limits.max, Math.max(limits.min, size)));\n}\n\n/**\n * The size stored under `key`, if any.\n *\n * @param key - The `localStorage` key.\n * @returns The stored size in pixels, or `null` when nothing valid is stored or storage\n * cannot be read (private browsing, the server).\n */\nexport function readStoredSize(key: string): number | null {\n try {\n const raw = window.localStorage.getItem(key);\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Remember a size under `key`. Failures (storage full, disabled, the server) are ignored: a\n * size that is not remembered is not worth an error.\n *\n * @param key - The `localStorage` key.\n * @param size - The size in pixels.\n */\nexport function writeStoredSize(key: string, size: number): void {\n try {\n window.localStorage.setItem(key, String(Math.round(size)));\n } catch {\n // Nothing to do: the size simply is not remembered.\n }\n}\n","/*\n * Two panes and the divider between them.\n *\n * A studio screen is a handful of permanent surfaces — a tree, a viewport, an inspector, a\n * timeline — whose relative size is the user's decision, not the layout's. The divider is\n * therefore a real control: draggable, operable from the keyboard (the WAI-ARIA\n * window-splitter pattern), announced with its position, and remembered across reloads\n * when asked to be.\n *\n * One pane carries the size and the other takes the rest, so nesting composes: the rest of\n * one split is simply another split. `AppShell` builds its side panels exactly that way.\n */\n\nimport { useCallback, useId, useRef, useState } from \"react\";\nimport type {\n CSSProperties,\n KeyboardEvent,\n PointerEvent as ReactPointerEvent,\n ReactNode,\n} from \"react\";\n\nimport { cn, focusRing } from \"@vitavision/ui\";\n\nimport {\n type PaneSize,\n type SizedPane,\n type SplitOrientation,\n clampSize,\n readStoredSize,\n resolveLimits,\n resolveSize,\n splitKeyAction,\n writeStoredSize,\n} from \"./splitSize\";\n\n/** Props of `SplitPane`. */\nexport interface SplitPaneProps {\n /**\n * The two panes, in reading order (left then right, or top then bottom). Exactly two;\n * nest another `SplitPane` in either for more.\n */\n children: readonly [ReactNode, ReactNode];\n /**\n * `horizontal` (the default) lays the panes side by side with a vertical divider;\n * `vertical` stacks them with a horizontal one.\n */\n orientation?: SplitOrientation | undefined;\n /** Which pane carries the size; the other takes the rest. Defaults to `start`. */\n sizedPane?: SizedPane | undefined;\n /** The sized pane's size in pixels, controlled. Pair with `onSizeChange`. */\n size?: number | undefined;\n /** The initial size when uncontrolled: pixels or a percentage. Defaults to `\"50%\"`. */\n defaultSize?: PaneSize | undefined;\n /** Called with the new size in pixels on every drag move and key press (0 when collapsed). */\n onSizeChange?: ((size: number) => void) | undefined;\n /** The sized pane's smallest open size: pixels or a percentage. Defaults to 0. */\n minSize?: PaneSize | undefined;\n /** The sized pane's largest size: pixels or a percentage. Defaults to `\"100%\"`. */\n maxSize?: PaneSize | undefined;\n /**\n * Lets the sized pane close: dragging it below half its minimum snaps it shut, and Enter\n * on the divider collapses it or restores the last open size.\n */\n collapsible?: boolean | undefined;\n /** How far one arrow-key press moves the divider, in pixels (four times with Shift). Defaults to 16. */\n step?: number | undefined;\n /**\n * Remember the size under this `localStorage` key, and start from it. Uncontrolled only:\n * a controlled split's size is the caller's to keep.\n */\n storageKey?: string | undefined;\n /** Names the divider for assistive technology. Defaults to \"Resize panes\". */\n \"aria-label\"?: string | undefined;\n /** Merged with the split's own classes through `cn`. */\n className?: string | undefined;\n}\n\n/**\n * Two panes with a draggable, keyboard-operable divider between them.\n *\n * The divider is a `role=\"separator\"` focusable control carrying `aria-valuenow` (the sized\n * pane's size in pixels), `aria-valuemin`/`aria-valuemax` and `aria-controls` (the sized\n * pane). Arrow keys along the axis move it by `step` (Shift: four steps), Home/End give the\n * sized pane its minimum/maximum, Enter collapses or restores a `collapsible` pane. Dragging\n * uses pointer capture, so the drag survives the pointer leaving the divider.\n *\n * Fills its container (`h-full w-full`), so it nests. State is exposed as `data-orientation`\n * on the root, `data-dragging` on the root and the divider while a drag is in progress, and\n * `data-collapsed` on the root and the sized pane while it is closed.\n */\nexport function SplitPane({\n children,\n orientation = \"horizontal\",\n sizedPane = \"start\",\n size: controlledSize,\n defaultSize = \"50%\",\n onSizeChange,\n minSize = 0,\n maxSize = \"100%\",\n collapsible = false,\n step = 16,\n storageKey,\n \"aria-label\": ariaLabel = \"Resize panes\",\n className,\n}: SplitPaneProps) {\n const paneId = useId();\n const horizontal = orientation === \"horizontal\";\n const [length, setLength] = useState<number | null>(null);\n const [internalSize, setInternalSize] = useState<number | null>(null);\n const [dragging, setDragging] = useState(false);\n const rootRef = useRef<HTMLDivElement | null>(null);\n // The drag in progress: where it started, and the size it has reached. The reached size is\n // kept here, not read back from state, because a pointer move's update is rendered at\n // continuous priority and may not have landed when the pointer is released.\n const dragRef = useRef<{ origin: number; start: number; length: number; reached: number } | null>(null);\n const lastOpenRef = useRef<number | null>(null);\n\n const limits = length === null ? null : resolveLimits(length, minSize, maxSize, collapsible);\n const size =\n controlledSize ??\n internalSize ??\n (length === null || limits === null ? null : clampSize(resolveSize(defaultSize, length), limits));\n const collapsed = size === 0;\n const controlled = controlledSize !== undefined;\n\n /*\n * Measure the split along its axis — synchronously on attach, so the first paint has the\n * limits, then on every resize — and pick up a remembered size. A callback ref rather than\n * an effect: the subscription lives exactly as long as the element.\n */\n const attach = useCallback(\n (element: HTMLDivElement | null) => {\n rootRef.current = element;\n if (!element) return;\n const measure = () => {\n const rect = element.getBoundingClientRect();\n setLength(horizontal ? rect.width : rect.height);\n };\n measure();\n if (storageKey !== undefined && !controlled) {\n const stored = readStoredSize(storageKey);\n if (stored !== null) setInternalSize(stored);\n }\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n },\n [horizontal, storageKey, controlled],\n );\n\n /** The live length and limits, measured now (a drag or a key press must not use stale ones). */\n const measureNow = () => {\n const element = rootRef.current;\n const rect = element?.getBoundingClientRect();\n const now = rect ? (horizontal ? rect.width : rect.height) : (length ?? 0);\n return { length: now, limits: resolveLimits(now, minSize, maxSize, collapsible) };\n };\n\n /** Take a new size: state, the caller, and (on `commit`) storage. `changed` defaults to a comparison with the rendered size. */\n const apply = (next: number, commit: boolean, changed = next !== size) => {\n if (next > 0) lastOpenRef.current = next;\n if (!controlled) setInternalSize(next);\n if (changed) onSizeChange?.(next);\n if (commit && storageKey !== undefined && !controlled) {\n writeStoredSize(storageKey, next);\n }\n };\n\n const coordinate = (event: ReactPointerEvent) => (horizontal ? event.clientX : event.clientY);\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return;\n event.preventDefault();\n const { length: now } = measureNow();\n const current = size ?? 0;\n dragRef.current = { origin: coordinate(event), start: current, length: now, reached: current };\n event.currentTarget.setPointerCapture(event.pointerId);\n event.currentTarget.focus();\n setDragging(true);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n const drag = dragRef.current;\n if (drag === null) return;\n const delta = (coordinate(event) - drag.origin) * (sizedPane === \"start\" ? 1 : -1);\n const next = clampSize(drag.start + delta, resolveLimits(drag.length, minSize, maxSize, collapsible));\n if (next === drag.reached) return;\n drag.reached = next;\n // Compared with the drag's own last size above: the rendered one may lag behind.\n apply(next, false, true);\n };\n\n const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {\n const drag = dragRef.current;\n if (drag === null) return;\n dragRef.current = null;\n if (event.currentTarget.hasPointerCapture(event.pointerId)) {\n event.currentTarget.releasePointerCapture(event.pointerId);\n }\n setDragging(false);\n if (drag.reached > 0) lastOpenRef.current = drag.reached;\n if (storageKey !== undefined && !controlled) writeStoredSize(storageKey, drag.reached);\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n const { limits: now } = measureNow();\n const current = size ?? 0;\n const action = splitKeyAction(event.key, event.shiftKey, current, {\n orientation,\n sizedPane,\n step,\n limits: now,\n });\n if (action === null) return;\n event.preventDefault();\n if (action.type === \"resize\") {\n apply(action.size, true);\n } else if (current > 0) {\n lastOpenRef.current = current;\n apply(0, true);\n } else {\n apply(clampSize(lastOpenRef.current ?? now.min, { ...now, collapsible: false }), true);\n }\n };\n\n // Before the first measurement (and on the server) the pane is sized by CSS alone, from\n // the default; afterwards by the measured size. The limits stay in CSS too, so a window\n // resize never pushes the pane outside them between two measurements.\n const basis =\n size !== null ? `${size}px` : typeof defaultSize === \"number\" ? `${defaultSize}px` : defaultSize;\n const cssSize = (value: PaneSize) => (typeof value === \"number\" ? `${value}px` : value);\n const sizedStyle: CSSProperties = {\n flex: `0 0 ${basis}`,\n ...(collapsed\n ? {}\n : horizontal\n ? { minWidth: cssSize(minSize), maxWidth: cssSize(maxSize) }\n : { minHeight: cssSize(minSize), maxHeight: cssSize(maxSize) }),\n };\n\n const [first, second] = children;\n const paneClasses = \"relative min-h-0 min-w-0 overflow-hidden\";\n const sized = (\n <div\n id={paneId}\n style={sizedStyle}\n className={paneClasses}\n data-collapsed={collapsed ? \"\" : undefined}\n // A closed pane keeps its content mounted (a tree keeps its expansion), but nothing in\n // it may take focus or be read out.\n inert={collapsed}\n >\n {sizedPane === \"start\" ? first : second}\n </div>\n );\n const rest = (\n <div className={cn(paneClasses, \"flex-1 basis-0\")}>{sizedPane === \"start\" ? second : first}</div>\n );\n\n return (\n <div\n ref={attach}\n data-orientation={orientation}\n data-dragging={dragging ? \"\" : undefined}\n data-collapsed={collapsed ? \"\" : undefined}\n className={cn(\n \"flex h-full min-h-0 w-full min-w-0\",\n horizontal ? \"flex-row\" : \"flex-col\",\n dragging && (horizontal ? \"cursor-col-resize select-none\" : \"cursor-row-resize select-none\"),\n className,\n )}\n >\n {sizedPane === \"start\" ? sized : rest}\n <div\n role=\"separator\"\n tabIndex={0}\n aria-label={ariaLabel}\n // The separator's own orientation is across the split: side-by-side panes are divided\n // by a vertical line.\n aria-orientation={horizontal ? \"vertical\" : \"horizontal\"}\n aria-controls={paneId}\n aria-valuenow={size === null ? undefined : Math.round(size)}\n aria-valuemin={limits === null ? undefined : collapsible ? 0 : Math.round(limits.min)}\n aria-valuemax={limits === null ? undefined : Math.round(limits.max)}\n data-dragging={dragging ? \"\" : undefined}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endDrag}\n onPointerCancel={endDrag}\n onKeyDown={onKeyDown}\n className={cn(\n // A 1px rule with a wider invisible hit area on either side of it.\n \"relative z-10 shrink-0 touch-none bg-line transition-colors\",\n \"before:absolute before:content-['']\",\n horizontal\n ? \"w-px cursor-col-resize before:inset-y-0 before:-right-1 before:-left-1\"\n : \"h-px cursor-row-resize before:inset-x-0 before:-top-1 before:-bottom-1\",\n \"hover:bg-signal data-dragging:bg-signal\",\n focusRing,\n )}\n />\n {sizedPane === \"start\" ? rest : sized}\n </div>\n );\n}\n","/*\n * The frame of a studio app: a header across the top, a main surface, optional side panels\n * either side of it, and an optional strip along the bottom.\n *\n * `@vitavision/ui` deliberately has no opinion on how an app fills the viewport — a page\n * scrolls. A studio is the other kind of screen: every surface is permanent, nothing scrolls\n * but the insides of panels, and the side panels are resized by hand. This is that frame,\n * built from `SplitPane`, and nothing more: no routing, no menus, no state of its own beyond\n * the panel sizes it is asked to remember.\n */\n\nimport type { ReactNode } from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\n\nimport { SplitPane } from \"./SplitPane\";\nimport type { PaneSize } from \"./splitSize\";\n\n/** How one side panel of an `AppShell` is sized. */\nexport interface SidePanelSize {\n /** The initial width: pixels or a percentage. */\n defaultSize?: PaneSize | undefined;\n /** The narrowest the panel may be dragged. */\n minSize?: PaneSize | undefined;\n /** The widest the panel may be dragged. */\n maxSize?: PaneSize | undefined;\n /** Lets the panel close (drag it under half its minimum, or Enter on its divider). */\n collapsible?: boolean | undefined;\n}\n\n/** Props of `AppShell`. */\nexport interface AppShellProps {\n /** The top bar: the app's name, the file actions, the theme toggle. */\n header?: ReactNode;\n /** The panel left of the main surface — a navigator such as a `TreeView`. */\n left?: ReactNode;\n /** The main surface — the viewport. Always present. */\n main: ReactNode;\n /** The panel right of the main surface — an inspector. */\n right?: ReactNode;\n /** The strip along the bottom, across the whole width — a `PlaybackBar`, a status line. */\n bottom?: ReactNode;\n /** Names the left panel's landmark (`<aside>`). Defaults to \"Navigator\". */\n leftLabel?: string | undefined;\n /** Names the right panel's landmark (`<aside>`). Defaults to \"Inspector\". */\n rightLabel?: string | undefined;\n /** The left panel's sizing. Defaults to 280 px, 180 px to 50%. */\n leftSize?: SidePanelSize | undefined;\n /** The right panel's sizing. Defaults to 320 px, 220 px to 50%. */\n rightSize?: SidePanelSize | undefined;\n /**\n * Remember the side panels' widths in `localStorage`, under `<storageKey>:left` and\n * `<storageKey>:right`.\n */\n storageKey?: string | undefined;\n /** Merged with the shell's own classes through `cn` — override `h-dvh` to embed it. */\n className?: string | undefined;\n}\n\nconst LEFT_DEFAULTS = { defaultSize: 280, minSize: 180, maxSize: \"50%\" } as const;\nconst RIGHT_DEFAULTS = { defaultSize: 320, minSize: 220, maxSize: \"50%\" } as const;\n\n/**\n * The full-viewport frame of a studio app: `header` across the top, `left` | `main` |\n * `right` in the middle with resizable side panels, `bottom` across the foot. Every slot but\n * `main` is optional, and an absent slot takes no space.\n *\n * Landmarks: the header is a `<header>`, the main surface a `<main>`, the side panels\n * `<aside>`s named by `leftLabel` and `rightLabel`. Each side panel is divided from the main\n * surface by a `SplitPane` divider (drag, or focus it and use the arrow keys). Only the\n * insides of the panels scroll; the shell itself is fixed to the viewport (`h-dvh`).\n */\nexport function AppShell({\n header,\n left,\n main,\n right,\n bottom,\n leftLabel = \"Navigator\",\n rightLabel = \"Inspector\",\n leftSize,\n rightSize,\n storageKey,\n className,\n}: AppShellProps) {\n const leftSizing = { ...LEFT_DEFAULTS, ...leftSize };\n const rightSizing = { ...RIGHT_DEFAULTS, ...rightSize };\n const hasLeft = left !== undefined && left !== null && left !== false;\n const hasRight = right !== undefined && right !== null && right !== false;\n\n const mainSurface = <main className=\"relative h-full min-h-0 min-w-0 overflow-hidden\">{main}</main>;\n\n const withRight = hasRight ? (\n <SplitPane\n sizedPane=\"end\"\n {...rightSizing}\n storageKey={storageKey === undefined ? undefined : `${storageKey}:right`}\n aria-label={`Resize ${rightLabel.toLowerCase()}`}\n >\n {mainSurface}\n <aside aria-label={rightLabel} className=\"h-full overflow-auto bg-surface\">\n {right}\n </aside>\n </SplitPane>\n ) : (\n mainSurface\n );\n\n const middle = hasLeft ? (\n <SplitPane\n sizedPane=\"start\"\n {...leftSizing}\n storageKey={storageKey === undefined ? undefined : `${storageKey}:left`}\n aria-label={`Resize ${leftLabel.toLowerCase()}`}\n >\n <aside aria-label={leftLabel} className=\"h-full overflow-auto bg-surface\">\n {left}\n </aside>\n {withRight}\n </SplitPane>\n ) : (\n withRight\n );\n\n return (\n <div\n className={cn(\n \"grid h-dvh w-full grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden bg-ground text-fg\",\n className,\n )}\n >\n {header ? (\n <header className=\"min-w-0 border-b border-line bg-surface\">{header}</header>\n ) : (\n <div aria-hidden />\n )}\n <div className=\"min-h-0 min-w-0\">{middle}</div>\n {bottom ? <div className=\"min-w-0 border-t border-line bg-surface\">{bottom}</div> : <div aria-hidden />}\n </div>\n );\n}\n","/*\n * The model behind `TreeView`: which rows are visible, where each sits in its set, and what\n * each key does (the WAI-ARIA tree pattern).\n *\n * Kept out of the component so the keyboard contract — the part a tree most often gets\n * subtly wrong — is tested as a function from (rows, focus, key) to an action.\n */\n\nimport type { ReactNode } from \"react\";\n\n/** One node of a `TreeView`. */\nexport interface TreeNode {\n /** Identifies the node to `selectedId`, `onSelect` and `expanded`. Unique in the tree. */\n id: string;\n /** The node's name: shown, read out, and matched by type-ahead. */\n label: string;\n /** A leading icon (decorative) — typically a lucide icon at `size-3.5`. */\n icon?: ReactNode;\n /** Child nodes. A node with a (possibly empty) array is a parent; without, a leaf. */\n children?: readonly TreeNode[] | undefined;\n /** A quiet trailing annotation — a type, a count, a frame name. Shown in mono. */\n meta?: ReactNode;\n /** Shown and focusable, but not selectable. */\n disabled?: boolean | undefined;\n}\n\n/** A node as it is laid out: one visible row of the tree. */\nexport interface TreeRow {\n /** The node. */\n node: TreeNode;\n /** Depth, from 1 at the root (`aria-level`). */\n level: number;\n /** The parent's id, or `null` at the root. */\n parentId: string | null;\n /** 1-based position among its siblings (`aria-posinset`). */\n posInSet: number;\n /** How many siblings, itself included (`aria-setsize`). */\n setSize: number;\n /** Whether the node has a children array. */\n isParent: boolean;\n /** Whether the node is a parent and expanded. */\n isExpanded: boolean;\n}\n\n/**\n * The rows a reader can see: every root, and the children of every expanded parent, in\n * document order.\n *\n * @param nodes - The roots.\n * @param expanded - The ids of the expanded parents.\n * @returns The visible rows, in order.\n */\nexport function visibleRows(nodes: readonly TreeNode[], expanded: ReadonlySet<string>): TreeRow[] {\n const rows: TreeRow[] = [];\n const walk = (siblings: readonly TreeNode[], level: number, parentId: string | null) => {\n siblings.forEach((node, index) => {\n const isParent = node.children !== undefined;\n const isExpanded = isParent && expanded.has(node.id);\n rows.push({\n node,\n level,\n parentId,\n posInSet: index + 1,\n setSize: siblings.length,\n isParent,\n isExpanded,\n });\n if (isExpanded && node.children) walk(node.children, level + 1, node.id);\n });\n };\n walk(nodes, 1, null);\n return rows;\n}\n\n/**\n * Every parent's id — the expanded set for \"everything open\".\n *\n * @param nodes - The roots.\n * @returns The ids of every node with a children array, at any depth.\n */\nexport function parentIds(nodes: readonly TreeNode[]): string[] {\n const ids: string[] = [];\n const walk = (siblings: readonly TreeNode[]) => {\n for (const node of siblings) {\n if (node.children === undefined) continue;\n ids.push(node.id);\n walk(node.children);\n }\n };\n walk(nodes);\n return ids;\n}\n\n/**\n * The ancestors of a node, root first — what must be expanded for it to be visible.\n *\n * @param nodes - The roots.\n * @param id - The node.\n * @returns The ancestor ids, root first; empty for a root or an id not in the tree.\n */\nexport function ancestorIds(nodes: readonly TreeNode[], id: string): string[] {\n const walk = (siblings: readonly TreeNode[], path: string[]): string[] | null => {\n for (const node of siblings) {\n if (node.id === id) return path;\n if (node.children) {\n const found = walk(node.children, [...path, node.id]);\n if (found) return found;\n }\n }\n return null;\n };\n return walk(nodes, []) ?? [];\n}\n\n/** What a key press on a tree asks for. */\nexport type TreeKeyAction =\n | { type: \"focus\"; id: string }\n | { type: \"expand\"; id: string }\n | { type: \"collapse\"; id: string }\n | { type: \"select\"; id: string }\n | { type: \"expand-siblings\"; ids: string[] };\n\n/**\n * The tree's keyboard (the WAI-ARIA tree pattern), as a pure function.\n *\n * ↓/↑ move to the next/previous visible row; → expands a closed parent, or moves into an\n * open one's first child; ← collapses an open parent, or moves to the parent; Home/End go to\n * the first/last visible row; Enter and Space select; `*` expands every sibling of the\n * focused row; a printable character moves to the next row whose label starts with it\n * (type-ahead, wrapping).\n *\n * @param rows - The visible rows, from `visibleRows`.\n * @param focusedId - The row with focus.\n * @param key - `KeyboardEvent.key`.\n * @returns The action, or `null` when the key does nothing here.\n */\nexport function treeKeyAction(rows: readonly TreeRow[], focusedId: string, key: string): TreeKeyAction | null {\n const index = rows.findIndex((row) => row.node.id === focusedId);\n const row = rows[index];\n if (row === undefined) return null;\n const focus = (target: TreeRow | undefined): TreeKeyAction | null =>\n target === undefined || target === row ? null : { type: \"focus\", id: target.node.id };\n\n switch (key) {\n case \"ArrowDown\":\n return focus(rows[index + 1]);\n case \"ArrowUp\":\n return focus(rows[index - 1]);\n case \"Home\":\n return focus(rows[0]);\n case \"End\":\n return focus(rows[rows.length - 1]);\n case \"ArrowRight\":\n if (!row.isParent) return null;\n if (!row.isExpanded) return { type: \"expand\", id: row.node.id };\n // An open parent's first child is the next row, if it has one.\n return rows[index + 1]?.parentId === row.node.id ? focus(rows[index + 1]) : null;\n case \"ArrowLeft\":\n if (row.isExpanded) return { type: \"collapse\", id: row.node.id };\n return row.parentId === null\n ? null\n : focus(rows.find((candidate) => candidate.node.id === row.parentId));\n case \"Enter\":\n case \" \":\n return row.node.disabled ? null : { type: \"select\", id: row.node.id };\n case \"*\": {\n const ids = rows\n .filter((candidate) => candidate.parentId === row.parentId && candidate.isParent && !candidate.isExpanded)\n .map((candidate) => candidate.node.id);\n return ids.length === 0 ? null : { type: \"expand-siblings\", ids };\n }\n default:\n return typeAhead(rows, index, key);\n }\n}\n\n/** The next row after `from` (wrapping) whose label starts with `key`, for a single printable character. */\nfunction typeAhead(rows: readonly TreeRow[], from: number, key: string): TreeKeyAction | null {\n if (key.length !== 1 || key.trim() === \"\") return null;\n const needle = key.toLocaleLowerCase();\n for (let offset = 1; offset <= rows.length; offset += 1) {\n const candidate = rows[(from + offset) % rows.length];\n if (candidate?.node.label.toLocaleLowerCase().startsWith(needle)) {\n return offset === rows.length ? null : { type: \"focus\", id: candidate.node.id };\n }\n }\n return null;\n}\n","/*\n * A hierarchy you can walk with the keyboard.\n *\n * Built for the navigator column of a studio — a robot cell's frame tree, world → robots →\n * links → rigs → cameras — where the tree is data the app already has, the icons are the\n * app's own, and selection is shared with a viewport that can also pick things. So the tree\n * is data-driven, selection is controlled, and selecting something hidden opens the way to it.\n *\n * Rendered flat: one `treeitem` per visible row, carrying its level, position and set size\n * (the WAI-ARIA tree pattern's \"flat\" form). The focus ring then belongs to one row rather\n * than to a subtree, and the keyboard contract is a function over the same list the DOM is\n * — see `treeModel.ts`.\n */\n\nimport { ChevronRight } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent, MouseEvent } from \"react\";\n\nimport { byDensity, cn, useDensity } from \"@vitavision/ui\";\n\nimport {\n type TreeNode,\n type TreeRow,\n ancestorIds,\n parentIds,\n treeKeyAction,\n visibleRows,\n} from \"./treeModel\";\n\n/** Props of `TreeView`. */\nexport interface TreeViewProps {\n /** The roots of the tree. */\n nodes: readonly TreeNode[];\n /** The selected node's id, controlled; `null` or absent for none. */\n selectedId?: string | null | undefined;\n /** Called with the node's id (and the node) on click, Enter or Space. Not called for a disabled node. */\n onSelect?: ((id: string, node: TreeNode) => void) | undefined;\n /** The expanded parents' ids, controlled. Pair with `onExpandedChange`. */\n expanded?: readonly string[] | undefined;\n /** The initially expanded parents' ids, when uncontrolled. */\n defaultExpanded?: readonly string[] | undefined;\n /** Start with every parent expanded, when uncontrolled (overrides `defaultExpanded`). */\n defaultExpandAll?: boolean | undefined;\n /** Called with the new set of expanded ids whenever a parent opens or closes. */\n onExpandedChange?: ((expanded: string[]) => void) | undefined;\n /** Names the tree for assistive technology. */\n \"aria-label\": string;\n /** Merged with the tree's own classes through `cn`. */\n className?: string | undefined;\n}\n\n/**\n * A data-driven tree (the WAI-ARIA tree pattern) with single selection.\n *\n * Keyboard: the tree is one Tab stop (roving `tabindex`). ↓/↑ move between visible rows, →\n * expands a parent or enters it, ← collapses a parent or goes up to its parent, Home/End jump\n * to the ends, Enter/Space select, `*` expands the focused row's siblings, and a letter jumps\n * to the next row starting with it. Clicking a row selects it; clicking its chevron toggles it.\n *\n * Selection is controlled (`selectedId`/`onSelect`). When `selectedId` changes to a node\n * inside a collapsed parent, its ancestors are expanded (through `onExpandedChange` when\n * `expanded` is controlled) and the row is scrolled into view — so a pick in a viewport can\n * drive the tree.\n *\n * Each row is a `treeitem` with `aria-level`, `aria-posinset`, `aria-setsize`,\n * `aria-selected` and, for parents, `aria-expanded`; also `data-selected` and, for parents,\n * `data-state` (`open`/`closed`). Row height follows the density in force.\n */\nexport function TreeView({\n nodes,\n selectedId = null,\n onSelect,\n expanded: controlledExpanded,\n defaultExpanded,\n defaultExpandAll = false,\n onExpandedChange,\n \"aria-label\": ariaLabel,\n className,\n}: TreeViewProps) {\n const density = useDensity();\n const [internalExpanded, setInternalExpanded] = useState<readonly string[]>(() =>\n defaultExpandAll ? parentIds(nodes) : (defaultExpanded ?? []),\n );\n const expandedIds = controlledExpanded ?? internalExpanded;\n const expandedSet = new Set(expandedIds);\n const rows = visibleRows(nodes, expandedSet);\n const [focusedId, setFocusedId] = useState<string | null>(null);\n const rowElementsRef = useRef(new Map<string, HTMLDivElement>());\n\n const setExpanded = (next: readonly string[]) => {\n if (controlledExpanded === undefined) setInternalExpanded(next);\n onExpandedChange?.([...next]);\n };\n\n const toggle = (id: string, open: boolean) => {\n if (open === expandedSet.has(id)) return;\n setExpanded(open ? [...expandedIds, id] : expandedIds.filter((other) => other !== id));\n };\n\n // Reveal a selection made elsewhere: open its ancestors and bring its row into view.\n const latestRef = useRef({ nodes, expandedIds, setExpanded });\n useEffect(() => {\n latestRef.current = { nodes, expandedIds, setExpanded };\n });\n useEffect(() => {\n if (selectedId === null) return;\n const { nodes: tree, expandedIds: open, setExpanded: update } = latestRef.current;\n const missing = ancestorIds(tree, selectedId).filter((id) => !open.includes(id));\n if (missing.length > 0) update([...open, ...missing]);\n }, [selectedId]);\n useEffect(() => {\n if (selectedId === null) return;\n const element = rowElementsRef.current.get(selectedId);\n // `scrollIntoView` is absent in some test DOMs.\n if (typeof element?.scrollIntoView === \"function\") element.scrollIntoView({ block: \"nearest\" });\n }, [selectedId, rows.length]);\n\n const isVisible = (id: string | null) => id !== null && rows.some((row) => row.node.id === id);\n const tabStop = isVisible(focusedId) ? focusedId : isVisible(selectedId) ? selectedId : (rows[0]?.node.id ?? null);\n\n const focusRow = (id: string) => {\n setFocusedId(id);\n rowElementsRef.current.get(id)?.focus();\n };\n\n const select = (row: TreeRow) => {\n if (!row.node.disabled) onSelect?.(row.node.id, row.node);\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.altKey || event.ctrlKey || event.metaKey) return;\n const id = (event.target as HTMLElement).dataset[\"treeId\"];\n if (id === undefined) return;\n const action = treeKeyAction(rows, id, event.key);\n if (action === null) return;\n event.preventDefault();\n switch (action.type) {\n case \"focus\":\n focusRow(action.id);\n break;\n case \"expand\":\n toggle(action.id, true);\n break;\n case \"collapse\":\n toggle(action.id, false);\n break;\n case \"select\": {\n const row = rows.find((candidate) => candidate.node.id === action.id);\n if (row) select(row);\n break;\n }\n case \"expand-siblings\":\n setExpanded([...expandedIds, ...action.ids]);\n break;\n }\n };\n\n const onChevron = (event: MouseEvent, row: TreeRow) => {\n event.stopPropagation();\n toggle(row.node.id, !row.isExpanded);\n focusRow(row.node.id);\n };\n\n return (\n <div\n role=\"tree\"\n aria-label={ariaLabel}\n onKeyDown={onKeyDown}\n className={cn(\"flex flex-col py-1 select-none\", className)}\n >\n {rows.map((row) => {\n const { node } = row;\n const selected = node.id === selectedId;\n return (\n <div\n key={node.id}\n ref={(element) => {\n if (element) rowElementsRef.current.set(node.id, element);\n else rowElementsRef.current.delete(node.id);\n }}\n role=\"treeitem\"\n aria-level={row.level}\n aria-posinset={row.posInSet}\n aria-setsize={row.setSize}\n aria-selected={selected}\n aria-expanded={row.isParent ? row.isExpanded : undefined}\n aria-disabled={node.disabled || undefined}\n tabIndex={node.id === tabStop ? 0 : -1}\n data-tree-id={node.id}\n data-selected={selected ? \"\" : undefined}\n data-state={row.isParent ? (row.isExpanded ? \"open\" : \"closed\") : undefined}\n onFocus={(event) => {\n if (event.target === event.currentTarget) setFocusedId(node.id);\n }}\n onClick={() => {\n focusRow(node.id);\n select(row);\n }}\n style={{ paddingLeft: `calc(${row.level - 1} * 0.875rem + 0.25rem)` }}\n className={cn(\n \"mx-1 flex shrink-0 cursor-default items-center gap-1.5 rounded-control pr-2 text-fg transition-colors\",\n \"outline-none focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-signal\",\n byDensity(density, \"h-7 text-sm\", \"h-6 text-xs\"),\n selected ? \"bg-signal/12\" : \"hover:bg-raised\",\n node.disabled && \"text-fg-subtle\",\n )}\n >\n {row.isParent ? (\n <span\n aria-hidden\n onClick={(event) => onChevron(event, row)}\n className=\"grid size-4 shrink-0 place-items-center rounded-sm text-fg-subtle hover:text-fg\"\n >\n <ChevronRight\n className={cn(\"size-3.5 transition-transform\", row.isExpanded && \"rotate-90\")}\n />\n </span>\n ) : (\n <span aria-hidden className=\"size-4 shrink-0\" />\n )}\n {node.icon !== undefined && (\n <span\n aria-hidden\n className={cn(\n \"grid shrink-0 place-items-center [&>svg]:size-3.5\",\n selected ? \"text-signal\" : \"text-fg-muted\",\n )}\n >\n {node.icon}\n </span>\n )}\n <span className=\"min-w-0 flex-1 truncate\">{node.label}</span>\n {node.meta !== undefined && (\n // On the selected row's tint both `fg-subtle` and `fg-muted` fall below AA at this size.\n <span className={cn(\"shrink-0 font-mono text-[11px]\", selected ? \"text-fg\" : \"text-fg-subtle\")}>\n {node.meta}\n </span>\n )}\n </div>\n );\n })}\n </div>\n );\n}\n","/*\n * Where playback is, as a store outside React.\n *\n * A sampled timeline plays at display rate, and the things that follow it — a robot's joint\n * angles, a camera frustum, a highlighted capture — are drawn by a render loop, not by\n * React. If the current frame lived in React state, every frame of playback would re-render\n * every component that reads it, including the whole scene graph. So it lives here: a tiny\n * store a render loop reads with `get()` at no cost, and that React components subscribe to\n * (through `usePlayhead`) only where they display it — the playback bar, a time readout.\n *\n * The store holds an integer sample index and nothing else that changes per frame. The\n * sub-sample position real-time playback needs is the clock's business (`advance`,\n * `usePlaybackClock`), not the store's, so a reader never sees a fractional frame.\n */\n\n/**\n * A sampled timeline's current position: an external store shared by React and render loops.\n *\n * Every function member may be called detached (`const { get } = playhead`), which is how\n * `useSyncExternalStore` and a render loop hold them.\n */\nexport interface Playhead {\n /** The current sample index, an integer in `0 … count − 1` (0 when `count` is 0). Cheap: call it every frame. */\n readonly get: () => number;\n /**\n * Move to sample `k`. Rounded to an integer and clamped to `0 … count − 1`; listeners are\n * notified only if the index changed.\n */\n readonly set: (k: number) => void;\n /**\n * Be told when the index or the timeline changes.\n *\n * @returns The unsubscribe function.\n */\n readonly subscribe: (listener: () => void) => () => void;\n /** How many samples the timeline has. */\n readonly count: number;\n /** The time between samples, in seconds. Sample `k` is at `t = k · dt`. */\n readonly dt: number;\n /**\n * Swap in a new timeline — a newly loaded or re-baked scenario — keeping the one store\n * every subscriber already holds. The index is clamped into the new range (not reset:\n * call `set(0)` for that). Listeners are notified if anything changed.\n */\n readonly setTimeline: (count: number, dt: number) => void;\n}\n\n/**\n * A playhead over `count` samples spaced `dt` seconds apart, starting at sample 0.\n *\n * Create one per app (not per render — keep it in a `useState` initialiser or module\n * scope), hand it to `PlaybackBar` and to the render loop, and replace its timeline with\n * `setTimeline` when a new scenario loads.\n *\n * @param count - The number of samples (a non-negative integer).\n * @param dt - Seconds between samples (positive).\n * @returns The store.\n */\nexport function createPlayhead(count: number, dt: number): Playhead {\n let index = 0;\n let timeline = checkTimeline(count, dt);\n const listeners = new Set<() => void>();\n const notify = () => {\n for (const listener of [...listeners]) listener();\n };\n\n return {\n get: () => index,\n set: (k) => {\n const next = clampIndex(k, timeline.count);\n if (next === index) return;\n index = next;\n notify();\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n get count() {\n return timeline.count;\n },\n get dt() {\n return timeline.dt;\n },\n setTimeline: (nextCount, nextDt) => {\n const next = checkTimeline(nextCount, nextDt);\n const nextIndex = clampIndex(index, next.count);\n if (next.count === timeline.count && next.dt === timeline.dt && nextIndex === index) return;\n timeline = next;\n index = nextIndex;\n notify();\n },\n };\n}\n\nfunction checkTimeline(count: number, dt: number): { count: number; dt: number } {\n if (!Number.isInteger(count) || count < 0) {\n throw new RangeError(`playhead: count must be a non-negative integer, got ${count}`);\n }\n if (!(dt > 0) || !Number.isFinite(dt)) {\n throw new RangeError(`playhead: dt must be a positive number of seconds, got ${dt}`);\n }\n return { count, dt };\n}\n\n/**\n * A sample index made legal: rounded, and clamped to `0 … count − 1`.\n *\n * @param k - Any number (`NaN` reads as 0).\n * @param count - The number of samples.\n * @returns The index; 0 when `count` is 0.\n */\nexport function clampIndex(k: number, count: number): number {\n if (count <= 0 || Number.isNaN(k)) return 0;\n return Math.min(count - 1, Math.max(0, Math.round(k)));\n}\n\n/** The outcome of one clock step: the new fractional position, and whether playback ran off the end. */\nexport interface AdvanceResult {\n /** The new position in samples (fractional); the index to show is its floor. */\n position: number;\n /** True when a non-looping timeline reached its last sample on this step. */\n ended: boolean;\n}\n\n/**\n * One step of real-time playback, in samples.\n *\n * Each sample is shown for `dt`: a looping timeline has period `count · dt` and wraps from\n * the last sample to the first; a non-looping one stops on the last sample and reports\n * `ended`. The position is fractional so that playback slower than one sample per frame\n * still advances.\n *\n * @param position - The current position in samples (fractional).\n * @param delta - How many samples to advance (elapsed seconds × speed ÷ dt); not negative.\n * @param count - The number of samples.\n * @param loop - Whether to wrap at the end.\n * @returns The new position and whether playback ended.\n */\nexport function advance(position: number, delta: number, count: number, loop: boolean): AdvanceResult {\n if (count <= 1) return { position: 0, ended: !loop };\n const next = position + Math.max(0, delta);\n if (loop) return { position: next % count, ended: false };\n const last = count - 1;\n return next >= last ? { position: last, ended: true } : { position: next, ended: false };\n}\n\n/**\n * The default time readout: seconds with millisecond resolution, `\"1.234 s\"`.\n *\n * @param seconds - The time.\n * @returns The formatted time.\n */\nexport function formatSeconds(seconds: number): string {\n return `${seconds.toFixed(3)} s`;\n}\n","/*\n * The React side of the playhead: subscribing to it, and driving it in real time.\n */\n\nimport { useEffect, useEffectEvent, useSyncExternalStore } from \"react\";\n\nimport { advance, type Playhead } from \"./playhead\";\n\n/**\n * The playhead's current sample index, re-rendering the calling component when it changes.\n *\n * Use it only where the index is *displayed* (the playback bar, a readout). A render loop\n * reads `playhead.get()` in its own frame callback instead, and re-renders nothing.\n *\n * @param playhead - The store.\n * @returns The current sample index.\n */\nexport function usePlayhead(playhead: Playhead): number {\n return useSyncExternalStore(playhead.subscribe, playhead.get, playhead.get);\n}\n\n/**\n * The playhead's timeline — `count` and `dt` — re-rendering when `setTimeline` changes it.\n *\n * @param playhead - The store.\n * @returns The number of samples and the seconds between them.\n */\nexport function usePlayheadTimeline(playhead: Playhead): { count: number; dt: number } {\n const count = useSyncExternalStore(playhead.subscribe, () => playhead.count, () => playhead.count);\n const dt = useSyncExternalStore(playhead.subscribe, () => playhead.dt, () => playhead.dt);\n return { count, dt };\n}\n\n/** Options of `usePlaybackClock`. */\nexport interface PlaybackClockOptions {\n /** The store to advance. */\n playhead: Playhead;\n /** Whether the clock runs. */\n playing: boolean;\n /** Playback rate: 1 is real time. Defaults to 1. */\n speed?: number | undefined;\n /** Wrap from the last sample to the first instead of stopping. Defaults to false. */\n loop?: boolean | undefined;\n /** Called once when a non-looping timeline reaches its last sample; set `playing` false here. */\n onEnd?: (() => void) | undefined;\n /**\n * The longest wall-clock gap one frame may advance by, in milliseconds. A tab in the\n * background gets no animation frames, and without this cap the first frame back would\n * jump by the whole time away. Defaults to 100.\n */\n maxFrameMs?: number | undefined;\n}\n\n/**\n * Advance a playhead in real time × `speed` while `playing`, from `requestAnimationFrame`.\n *\n * Position is accumulated fractionally, so slow playback of a finely sampled timeline still\n * moves; the store only ever holds the integer index. A seek from elsewhere (the scrubber, a\n * marker) is picked up on the next frame. Starting a non-looping timeline that sits on its\n * last sample rewinds it to 0 first. `speed`, `loop` and `onEnd` may change while playing\n * without restarting the clock.\n *\n * Renders nothing and re-renders nothing: call it once, in the component that owns the\n * `playing` state.\n *\n * @param options - The playhead and the transport state.\n */\nexport function usePlaybackClock({\n playhead,\n playing,\n speed = 1,\n loop = false,\n onEnd,\n maxFrameMs = 100,\n}: PlaybackClockOptions): void {\n const step = useEffectEvent((position: number, elapsedMs: number) => {\n const delta = (Math.min(elapsedMs, maxFrameMs) / 1000) * (speed / playhead.dt);\n return advance(position, delta, playhead.count, loop);\n });\n const end = useEffectEvent(() => onEnd?.());\n const rewindIfAtEnd = useEffectEvent(() => {\n if (!loop && playhead.count > 0 && playhead.get() >= playhead.count - 1) playhead.set(0);\n });\n\n useEffect(() => {\n if (!playing) return;\n rewindIfAtEnd();\n let position = playhead.get();\n let last: number | null = null;\n let frame = requestAnimationFrame(function tick(now: number) {\n // A seek since the last frame (scrubber, marker, step button) wins over the clock.\n if (Math.floor(position) !== playhead.get()) position = playhead.get();\n const result = last === null ? { position, ended: false } : step(position, now - last);\n last = now;\n position = result.position;\n playhead.set(Math.floor(position));\n if (result.ended) {\n end();\n return;\n }\n frame = requestAnimationFrame(tick);\n });\n return () => cancelAnimationFrame(frame);\n }, [playing, playhead]);\n}\n","/*\n * The transport for a sampled timeline.\n *\n * Playback state splits by how often it changes. Whether it is playing, how fast, and\n * whether it loops change when someone clicks — ordinary controlled props. Where it is\n * changes every frame — so that is a `Playhead` store the bar subscribes to itself, and a\n * playing timeline re-renders this bar and nothing else in the app.\n *\n * The bar is chrome over a viewport, like the image stage's toolbar: one row, icon buttons\n * named for what they do, the time in mono so it does not jitter as digits change.\n */\n\nimport {\n ChevronFirst,\n ChevronLast,\n Pause,\n Play,\n Repeat,\n SkipBack,\n SkipForward,\n StepBack,\n StepForward,\n} from \"lucide-react\";\nimport type { ComponentPropsWithRef, KeyboardEvent, ReactNode } from \"react\";\n\nimport { type MeasureTone, Select, Slider, byDensity, cn, focusRing, toneColor, useDensity } from \"@vitavision/ui\";\n\nimport { formatSeconds, type Playhead } from \"./playhead\";\nimport { usePlayhead, usePlayheadTimeline } from \"./usePlayback\";\n\n/** A point of interest on the timeline — a capture, an event — drawn as a tick on the scrubber. */\nexport interface PlaybackMarker {\n /** The sample the marker sits on. */\n index: number;\n /** What happens there; names the tick for assistive technology and its tooltip. */\n label?: string | undefined;\n /** The tick's colour. Defaults to `signal`. */\n tone?: MeasureTone | undefined;\n}\n\n/** The speeds offered by default. */\nexport const DEFAULT_SPEEDS: readonly number[] = [0.25, 0.5, 1, 2, 4];\n\n/** Props of `PlaybackBar`. */\nexport interface PlaybackBarProps {\n /** Where playback is. The bar subscribes to it; seeking writes to it. */\n playhead: Playhead;\n /** Whether playback is running, controlled. */\n playing: boolean;\n /** Called with the requested playing state (the play/pause button, Space). */\n onPlayingChange: (playing: boolean) => void;\n /** The playback rate, controlled. Defaults to 1. */\n speed?: number | undefined;\n /** Called with the chosen rate. Without it the speed selector is not shown. */\n onSpeedChange?: ((speed: number) => void) | undefined;\n /** The rates the selector offers. Defaults to 0.25×, 0.5×, 1×, 2×, 4×. */\n speeds?: readonly number[] | undefined;\n /** Whether playback wraps at the end, controlled. */\n loop?: boolean | undefined;\n /** Called with the new loop state. Without it the loop toggle is not shown. */\n onLoopChange?: ((loop: boolean) => void) | undefined;\n /** Ticks on the scrubber, each a click target that seeks to it. */\n markers?: readonly PlaybackMarker[] | undefined;\n /** Called after a marker tick is clicked (the playhead has already moved to it). */\n onMarkerSelect?: ((marker: PlaybackMarker) => void) | undefined;\n /** Formats `t = k · dt` in seconds for the readout. Defaults to `\"1.234 s\"`. */\n formatTime?: ((seconds: number) => string) | undefined;\n /** Names the bar (a `toolbar`). Defaults to \"Playback\". */\n \"aria-label\"?: string | undefined;\n /** Merged with the bar's own classes through `cn`. */\n className?: string | undefined;\n}\n\n/**\n * The transport for a sampled timeline: jump to start, previous marker, step back,\n * play/pause, step forward, next marker, jump to end; a scrubber over the samples with the\n * markers as ticks; the time `t = k · dt`; the speed; loop.\n *\n * `playing`, `speed` and `loop` are controlled props. The position is the `playhead` store,\n * which the bar subscribes to itself — so during playback only the bar re-renders. Drive the\n * store with `usePlaybackClock`, and read `playhead.get()` in a render loop.\n *\n * A `role=\"toolbar\"`. Keyboard, while focus is inside it: the scrubber is a slider (←/→ one\n * sample, PageUp/PageDown ten, Home/End); on the buttons, ←/→ step one sample; Space\n * toggles playback anywhere in the bar except on a button, where it presses the button. The\n * root carries `data-playing` while playing and `data-empty` when the timeline has no samples.\n */\nexport function PlaybackBar({\n playhead,\n playing,\n onPlayingChange,\n speed = 1,\n onSpeedChange,\n speeds = DEFAULT_SPEEDS,\n loop = false,\n onLoopChange,\n markers = [],\n onMarkerSelect,\n formatTime = formatSeconds,\n \"aria-label\": ariaLabel = \"Playback\",\n className,\n}: PlaybackBarProps) {\n const density = useDensity();\n const index = usePlayhead(playhead);\n const { count, dt } = usePlayheadTimeline(playhead);\n const last = Math.max(0, count - 1);\n const empty = count === 0;\n\n const sorted = [...markers].filter((m) => m.index >= 0 && m.index <= last).sort((a, b) => a.index - b.index);\n const previousMarker = sorted.filter((m) => m.index < index).at(-1);\n const nextMarker = sorted.find((m) => m.index > index);\n\n const seek = (k: number) => playhead.set(k);\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n const target = event.target as HTMLElement;\n const onButton = target.tagName === \"BUTTON\";\n if (event.key === \" \" && !onButton && target.getAttribute(\"role\") !== \"combobox\") {\n event.preventDefault();\n if (!empty) onPlayingChange(!playing);\n } else if (onButton && (event.key === \"ArrowLeft\" || event.key === \"ArrowRight\")) {\n event.preventDefault();\n seek(index + (event.key === \"ArrowRight\" ? 1 : -1));\n }\n };\n\n return (\n <div\n role=\"toolbar\"\n aria-label={ariaLabel}\n data-playing={playing ? \"\" : undefined}\n data-empty={empty ? \"\" : undefined}\n onKeyDown={onKeyDown}\n className={cn(\n \"flex w-full min-w-0 items-center bg-surface\",\n byDensity(density, \"gap-3 px-3 py-2\", \"gap-2 px-2 py-1\"),\n className,\n )}\n >\n <div className=\"flex shrink-0 items-center gap-0.5\">\n <BarButton label=\"Jump to start\" onClick={() => seek(0)} disabled={empty || index === 0}>\n <ChevronFirst className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton\n label=\"Previous marker\"\n onClick={() => previousMarker && seek(previousMarker.index)}\n disabled={previousMarker === undefined}\n >\n <SkipBack className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton label=\"Step back\" onClick={() => seek(index - 1)} disabled={empty || index === 0}>\n <StepBack className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton\n label={playing ? \"Pause\" : \"Play\"}\n onClick={() => onPlayingChange(!playing)}\n disabled={empty}\n className=\"text-fg\"\n >\n {playing ? <Pause className=\"size-4\" aria-hidden /> : <Play className=\"size-4\" aria-hidden />}\n </BarButton>\n <BarButton label=\"Step forward\" onClick={() => seek(index + 1)} disabled={empty || index >= last}>\n <StepForward className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton\n label=\"Next marker\"\n onClick={() => nextMarker && seek(nextMarker.index)}\n disabled={nextMarker === undefined}\n >\n <SkipForward className=\"size-4\" aria-hidden />\n </BarButton>\n <BarButton label=\"Jump to end\" onClick={() => seek(last)} disabled={empty || index >= last}>\n <ChevronLast className=\"size-4\" aria-hidden />\n </BarButton>\n </div>\n\n <div className=\"relative flex min-w-24 flex-1 flex-col justify-center\">\n {sorted.length > 0 && (\n // The ticks sit on a rail above the track, positioned as Radix positions the thumb:\n // its centre travels from half a thumb (7 px) in from either end.\n <div className=\"relative h-2.5\">\n {sorted.map((marker) => (\n <MarkerTick\n key={`${marker.index}:${marker.label ?? \"\"}`}\n marker={marker}\n fraction={last === 0 ? 0 : marker.index / last}\n time={formatTime(marker.index * dt)}\n active={marker.index === index}\n onClick={() => {\n seek(marker.index);\n onMarkerSelect?.(marker);\n }}\n />\n ))}\n </div>\n )}\n <Slider\n value={index}\n onValueChange={seek}\n min={0}\n max={last}\n step={1}\n disabled={empty}\n aria-label=\"Playback position\"\n />\n </div>\n\n {/* Not an <output>: that is a live region, and this changes every frame. */}\n <span className=\"shrink-0 font-mono text-xs whitespace-nowrap text-fg tabular-nums\">\n <span className=\"text-fg-subtle\">t = </span>\n {formatTime(index * dt)}\n <span className=\"ml-2 text-fg-subtle\">\n {empty ? \"–\" : index}/{last}\n </span>\n </span>\n\n {onSpeedChange && (\n <Select\n value={String(speed)}\n onValueChange={(value) => value !== \"\" && onSpeedChange(Number(value))}\n options={speeds.map((s) => ({ value: String(s), label: `${s}×` }))}\n aria-label=\"Playback speed\"\n className={cn(\"w-20 shrink-0 font-mono\", byDensity(density, \"h-8\", \"h-7\"))}\n />\n )}\n\n {onLoopChange && (\n <BarButton label=\"Loop\" pressed={loop} onClick={() => onLoopChange(!loop)}>\n <Repeat className=\"size-4\" aria-hidden />\n </BarButton>\n )}\n </div>\n );\n}\n\nfunction MarkerTick({\n marker,\n fraction,\n time,\n active,\n onClick,\n}: {\n marker: PlaybackMarker;\n fraction: number;\n time: string;\n active: boolean;\n onClick: () => void;\n}) {\n const name = marker.label ? `${marker.label} (${time})` : `Marker at ${time}`;\n return (\n <button\n type=\"button\"\n // The previous/next-marker buttons are the keyboard's way to the markers; one tab stop\n // per tick would bury the rest of the bar behind a long capture list.\n tabIndex={-1}\n title={name}\n aria-label={name}\n data-active={active ? \"\" : undefined}\n onClick={onClick}\n style={{ left: `calc(7px + ${fraction} * (100% - 14px))` }}\n className=\"group absolute top-0 flex h-full w-2.5 -translate-x-1/2 cursor-pointer justify-center\"\n >\n <span\n aria-hidden\n className=\"h-full w-0.5 rounded-full opacity-70 transition-opacity group-hover:opacity-100 group-data-active:w-1 group-data-active:opacity-100\"\n style={{ backgroundColor: toneColor(marker.tone) }}\n />\n </button>\n );\n}\n\n/** Props of the bar's icon button. */\ninterface BarButtonProps\n extends Omit<ComponentPropsWithRef<\"button\">, \"type\" | \"title\" | \"aria-label\" | \"aria-pressed\" | \"children\"> {\n label: string;\n pressed?: boolean | undefined;\n children: ReactNode;\n}\n\n/** An icon button in the style of `@vitavision/stage2d`'s `StageButton`, sized by density. */\nfunction BarButton({ label, pressed, className, children, ...props }: BarButtonProps) {\n const density = useDensity();\n return (\n <button\n {...props}\n type=\"button\"\n title={label}\n aria-label={label}\n aria-pressed={pressed}\n data-state={pressed === undefined ? undefined : pressed ? \"on\" : \"off\"}\n className={cn(\n \"grid place-items-center rounded-control text-fg-muted transition-colors\",\n byDensity(density, \"size-8\", \"size-7\"),\n \"hover:bg-raised hover:text-fg disabled:pointer-events-none disabled:opacity-40\",\n pressed && \"bg-signal/15 text-signal\",\n focusRing,\n className,\n )}\n >\n {children}\n </button>\n );\n}\n","/*\n * What `FileDrop` does with a drop: which files match `accept`, and what a dropped folder\n * contains.\n *\n * The browser enforces `accept` only in the file picker, and only as a hint; a drop brings\n * whatever was dragged. So the filter is applied here, to both routes. And a dropped folder\n * arrives as a zero-byte \"file\" unless its entries are walked — which is how a scenario\n * folder (a scene, a scenario, its meshes) is opened in one gesture.\n */\n\n/**\n * Whether a file matches an `accept` string, as `<input type=\"file\" accept>` reads it:\n * comma-separated extensions (`.json`), MIME types (`application/json`) and MIME wildcards\n * (`image/*`). Matching is case-insensitive.\n *\n * @param file - The file's name and MIME type.\n * @param accept - The accept string; empty or absent accepts everything.\n * @returns Whether the file is accepted.\n */\nexport function acceptsFile(file: { name: string; type: string }, accept: string | undefined): boolean {\n const tokens = (accept ?? \"\")\n .split(\",\")\n .map((token) => token.trim().toLowerCase())\n .filter((token) => token !== \"\");\n if (tokens.length === 0) return true;\n const name = file.name.toLowerCase();\n const type = file.type.toLowerCase();\n return tokens.some((token) => {\n if (token.startsWith(\".\")) return name.endsWith(token);\n if (token.endsWith(\"/*\")) return type.startsWith(token.slice(0, -1));\n return type === token;\n });\n}\n\n/**\n * Split files by `accept`.\n *\n * @param files - The candidates.\n * @param accept - The accept string.\n * @returns The accepted files and the rejected ones, each in their original order.\n */\nexport function partitionFiles(\n files: readonly File[],\n accept: string | undefined,\n): { accepted: File[]; rejected: File[] } {\n const accepted: File[] = [];\n const rejected: File[] = [];\n for (const file of files) (acceptsFile(file, accept) ? accepted : rejected).push(file);\n return { accepted, rejected };\n}\n\n/**\n * Whether a drag carries files (rather than text or a link) — the only drags `FileDrop`\n * reacts to.\n *\n * @param dataTransfer - The drag's data, or `null`.\n * @returns Whether `Files` is among its types.\n */\nexport function carriesFiles(dataTransfer: Pick<DataTransfer, \"types\"> | null): boolean {\n return dataTransfer !== null && Array.from(dataTransfer.types).includes(\"Files\");\n}\n\n/** The part of the File and Directory Entries API a drop walk needs (`webkitGetAsEntry`). */\nexport interface DropEntry {\n /** A file (`FileSystemFileEntry`). */\n isFile: boolean;\n /** A folder (`FileSystemDirectoryEntry`). */\n isDirectory: boolean;\n /** The entry's own name. */\n name: string;\n /** The entry's path from the drop root, with a leading `/`. */\n fullPath: string;\n /** A file entry's contents, as a `File`. */\n file?: (success: (file: File) => void, failure?: (error: unknown) => void) => void;\n /** A folder entry's reader; `readEntries` yields the children in batches, then an empty one. */\n createReader?: () => {\n readEntries: (success: (entries: DropEntry[]) => void, failure?: (error: unknown) => void) => void;\n };\n}\n\n/**\n * Every file in a drop, with dropped folders walked recursively.\n *\n * Files found inside a folder carry `webkitRelativePath` (`scene/meshes/base.glb`), as the\n * files of `<input webkitdirectory>` do, so both routes give the same shape. Where the entries\n * API is missing, the drop's plain file list is returned.\n *\n * @param dataTransfer - The drop's data.\n * @returns The files, in the order the browser listed them.\n */\nexport async function collectDroppedFiles(\n dataTransfer: Pick<DataTransfer, \"files\" | \"items\">,\n): Promise<File[]> {\n // Everything is read before the first `await`: a drop's data is emptied once its event\n // handler returns.\n const plain = Array.from(dataTransfer.files);\n const entries = Array.from(dataTransfer.items ?? [])\n .filter((item) => item.kind === \"file\")\n .map((item) => (typeof item.webkitGetAsEntry === \"function\" ? (item.webkitGetAsEntry() as DropEntry | null) : null));\n // No folder among them (or no entries API): the plain list is already the answer.\n if (!entries.some((entry) => entry?.isDirectory)) return plain;\n const files: File[] = [];\n for (const entry of entries) if (entry) await walkEntry(entry, files);\n return files;\n}\n\nasync function walkEntry(entry: DropEntry, out: File[]): Promise<void> {\n if (entry.isFile && entry.file) {\n const read = entry.file.bind(entry);\n const file = await new Promise<File>((resolve, reject) => read(resolve, reject));\n const path = entry.fullPath.replace(/^\\//, \"\");\n out.push(path.includes(\"/\") ? withRelativePath(file, path) : file);\n } else if (entry.isDirectory && entry.createReader) {\n const reader = entry.createReader();\n // `readEntries` returns a directory in batches (100 in Chromium) until an empty one.\n for (;;) {\n const batch = await new Promise<DropEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));\n if (batch.length === 0) break;\n for (const child of batch) await walkEntry(child, out);\n }\n }\n}\n\n/**\n * The file, carrying `webkitRelativePath` — a read-only accessor on `File.prototype`,\n * shadowed here on the instance.\n */\nfunction withRelativePath(file: File, path: string): File {\n Object.defineProperty(file, \"webkitRelativePath\", { value: path, configurable: true });\n return file;\n}\n","/*\n * Opening local files: by dropping them, or through the picker.\n *\n * Both routes are always offered. A drop target alone is invisible to a keyboard and to\n * anyone who does not know it is there; a picker alone makes a folder of scenario files a\n * dozen clicks. The picker is a real `<button>`, so the component is operable without a\n * pointer.\n */\n\nimport { FolderOpen } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport type { ChangeEvent, DragEvent, ReactNode } from \"react\";\n\nimport { Button, cn } from \"@vitavision/ui\";\n\nimport { carriesFiles, collectDroppedFiles, partitionFiles } from \"./dropFiles\";\n\n/** Props of `FileDrop`. */\nexport interface FileDropProps {\n /** Called with the accepted files of a drop or a pick (never with an empty list). */\n onFiles: (files: File[]) => void;\n /** Called with the files a drop or a pick brought that `accept` turned away. */\n onReject?: ((files: File[]) => void) | undefined;\n /**\n * Which files to take, as `<input accept>`: extensions (`.json`), MIME types and MIME\n * wildcards (`image/*`), comma-separated. Applied to drops as well as the picker. Default: all.\n */\n accept?: string | undefined;\n /** Take several files at once. Defaults to true; when false only the first accepted file is passed. */\n multiple?: boolean | undefined;\n /**\n * The picker chooses a folder (`webkitdirectory`) instead of files. Dropped folders are\n * walked either way; files found in a folder carry `webkitRelativePath`.\n */\n directory?: boolean | undefined;\n /**\n * Take drops anywhere in the window, showing a full-window overlay while files are dragged\n * over it; the component itself then renders only the picker button (for a header). Without\n * it, the component is an inline drop zone.\n */\n overlay?: boolean | undefined;\n /** Refuses drops and blocks the picker. */\n disabled?: boolean | undefined;\n /** The picker button's label. Defaults to \"Open files…\" (or \"Open folder…\" with `directory`). */\n buttonLabel?: string | undefined;\n /** The overlay's message. Defaults to \"Drop to open\". */\n overlayMessage?: ReactNode;\n /** The inline zone's message, before the button. Defaults to \"Drop files here, or\". */\n children?: ReactNode;\n /** Merged with the zone's (or, with `overlay`, the button's) own classes through `cn`. */\n className?: string | undefined;\n}\n\n/**\n * A drop target plus an \"Open files…\" button over a hidden `<input type=\"file\">`.\n *\n * Inline (the default) it is a dashed zone with a message and the button, carrying\n * `data-dragging` while files are dragged over it. With `overlay` it renders only the button\n * and takes drops anywhere in the window, showing a full-window overlay (`aria-hidden`: the\n * button is the accessible route) while a drag carrying files is over the window. Only drags\n * that carry files are reacted to; text and links pass through.\n *\n * Files are filtered by `accept` on both routes (the browser applies it to neither drops nor,\n * reliably, the picker); the rest go to `onReject`. A dropped folder is walked recursively.\n */\nexport function FileDrop({\n onFiles,\n onReject,\n accept,\n multiple = true,\n directory = false,\n overlay = false,\n disabled = false,\n buttonLabel,\n overlayMessage = \"Drop to open\",\n children = \"Drop files here, or\",\n className,\n}: FileDropProps) {\n const inputRef = useRef<HTMLInputElement | null>(null);\n const depthRef = useRef(0);\n const [dragging, setDragging] = useState(false);\n const label = buttonLabel ?? (directory ? \"Open folder…\" : \"Open files…\");\n\n const deliver = (files: readonly File[]) => {\n const { accepted, rejected } = partitionFiles(files, accept);\n if (accepted.length > 0) onFiles(multiple ? accepted : accepted.slice(0, 1));\n if (rejected.length > 0) onReject?.(rejected);\n };\n const deliverRef = useRef(deliver);\n useEffect(() => {\n deliverRef.current = deliver;\n });\n\n // The window-wide target. `dragenter`/`dragleave` fire for every element crossed, so the\n // overlay's visibility is a depth count rather than the last event seen.\n useEffect(() => {\n if (!overlay || disabled) return;\n const onEnter = (event: globalThis.DragEvent) => {\n if (!carriesFiles(event.dataTransfer)) return;\n depthRef.current += 1;\n setDragging(true);\n };\n const onLeave = (event: globalThis.DragEvent) => {\n if (!carriesFiles(event.dataTransfer)) return;\n depthRef.current = Math.max(0, depthRef.current - 1);\n if (depthRef.current === 0) setDragging(false);\n };\n const onOver = (event: globalThis.DragEvent) => {\n if (!carriesFiles(event.dataTransfer)) return;\n event.preventDefault();\n if (event.dataTransfer) event.dataTransfer.dropEffect = \"copy\";\n };\n const onDrop = (event: globalThis.DragEvent) => {\n if (!event.dataTransfer || !carriesFiles(event.dataTransfer)) return;\n event.preventDefault();\n depthRef.current = 0;\n setDragging(false);\n void collectDroppedFiles(event.dataTransfer).then((files) => deliverRef.current(files));\n };\n window.addEventListener(\"dragenter\", onEnter);\n window.addEventListener(\"dragleave\", onLeave);\n window.addEventListener(\"dragover\", onOver);\n window.addEventListener(\"drop\", onDrop);\n return () => {\n window.removeEventListener(\"dragenter\", onEnter);\n window.removeEventListener(\"dragleave\", onLeave);\n window.removeEventListener(\"dragover\", onOver);\n window.removeEventListener(\"drop\", onDrop);\n depthRef.current = 0;\n };\n }, [overlay, disabled]);\n\n const onPick = (event: ChangeEvent<HTMLInputElement>) => {\n const files = Array.from(event.currentTarget.files ?? []);\n // Cleared so that choosing the same file again is still a change.\n event.currentTarget.value = \"\";\n if (files.length > 0) deliver(files);\n };\n\n const picker = (\n <>\n <input\n ref={(element) => {\n inputRef.current = element;\n if (element) element.webkitdirectory = directory;\n }}\n type=\"file\"\n hidden\n tabIndex={-1}\n accept={accept}\n multiple={multiple || directory}\n disabled={disabled}\n onChange={onPick}\n />\n <Button\n icon={<FolderOpen />}\n disabled={disabled}\n onClick={() => inputRef.current?.click()}\n className={overlay ? className : undefined}\n >\n {label}\n </Button>\n </>\n );\n\n if (overlay) {\n return (\n <>\n {picker}\n {dragging && (\n <div\n aria-hidden\n data-dragging=\"\"\n className=\"pointer-events-none fixed inset-0 z-50 grid place-items-center bg-ground/80 p-8 backdrop-blur-sm\"\n >\n <div className=\"rounded-panel border-2 border-dashed border-signal bg-surface px-10 py-8 text-sm font-medium text-fg shadow-lg\">\n {overlayMessage}\n </div>\n </div>\n )}\n </>\n );\n }\n\n const zoneDrag = (event: DragEvent<HTMLDivElement>, change: 1 | -1 | 0) => {\n if (disabled || !carriesFiles(event.dataTransfer)) return;\n event.preventDefault();\n if (change === 0) {\n event.dataTransfer.dropEffect = \"copy\";\n return;\n }\n depthRef.current = Math.max(0, depthRef.current + change);\n setDragging(depthRef.current > 0);\n };\n\n return (\n <div\n data-dragging={dragging ? \"\" : undefined}\n data-disabled={disabled ? \"\" : undefined}\n onDragEnter={(event) => zoneDrag(event, 1)}\n onDragLeave={(event) => zoneDrag(event, -1)}\n onDragOver={(event) => zoneDrag(event, 0)}\n onDrop={(event) => {\n if (disabled || !carriesFiles(event.dataTransfer)) return;\n event.preventDefault();\n depthRef.current = 0;\n setDragging(false);\n void collectDroppedFiles(event.dataTransfer).then(deliver);\n }}\n className={cn(\n \"flex flex-col items-center justify-center gap-3 rounded-panel border-2 border-dashed border-line-strong px-6 py-8 text-center text-sm text-fg-muted transition-colors\",\n \"data-dragging:border-signal data-dragging:bg-signal/8 data-dragging:text-fg\",\n // Not `opacity-50`: the message would fall below AA. The disabled button and the quieter\n // border say it instead.\n \"data-disabled:border-line\",\n className,\n )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P,EAAA,CAAA;CAIN,MAAM,YAAY,OAAkC,WAAuB;EACzE,IAAI,YAAY,CAAC,aAAa,MAAM,YAAY,GAAG;EACnD,MAAM,eAAe;EACrB,IAAI,WAAW,GAAG;GAChB,MAAM,aAAa,aAAa;GAChC;EACF;EACA,SAAS,UAAU,KAAK,IAAI,GAAG,SAAS,UAAU,MAAM;EACxD,YAAY,SAAS,UAAU,CAAC;CAClC;CAEA,OACE,qBAAC,OAAD;EACE,iBAAe,WAAW,KAAK,KAAA;EAC/B,iBAAe,WAAW,KAAK,KAAA;EAC/B,cAAc,UAAU,SAAS,OAAO,CAAC;EACzC,cAAc,UAAU,SAAS,OAAO,EAAE;EAC1C,aAAa,UAAU,SAAS,OAAO,CAAC;EACxC,SAAS,UAAU;GACjB,IAAI,YAAY,CAAC,aAAa,MAAM,YAAY,GAAG;GACnD,MAAM,eAAe;GACrB,SAAS,UAAU;GACnB,YAAY,KAAK;GACjB,oBAAyB,MAAM,YAAY,CAAC,CAAC,KAAK,OAAO;EAC3D;EACA,WAAW,GACT,yKACA,+EAGA,6BACA,SACF;EApBF,UAAA,CAsBE,oBAAC,KAAD,EAAI,SAAY,CAAA,GACf,MACE;;AAET"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vitavision/workbench",
3
- "version": "0.1.0",
4
- "description": "Studio-app building blocks on @vitavision/ui: app shell, split panes, tree view, playback bar and playhead store, file drop, toasts.",
3
+ "version": "0.1.1",
4
+ "description": "Studio-app building blocks on @vitavision/ui: app shell, split panes, tree view, playback bar and playhead store, file drop (toasts re-exported from @vitavision/ui).",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -46,7 +46,7 @@
46
46
  "react-dom": "^19.2.0"
47
47
  },
48
48
  "dependencies": {
49
- "@vitavision/ui": "^0.8.0",
49
+ "@vitavision/ui": "^0.9.0",
50
50
  "lucide-react": "^1.48.0"
51
51
  },
52
52
  "devDependencies": {
package/src/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `@vitavision/workbench` — the building blocks of a studio app on `@vitavision/ui`: the
3
3
  * shell and its split panes, a tree navigator, a playback transport over a sampled timeline,
4
- * file opening, and notifications.
4
+ * file opening, and (re-exported from `@vitavision/ui`) notifications.
5
5
  *
6
6
  * Import `@vitavision/workbench/styles.css` after `@vitavision/ui/styles.css`.
7
7
  *
@@ -55,13 +55,16 @@ export {
55
55
  export { FileDrop, type FileDropProps } from "./components/FileDrop";
56
56
  export { acceptsFile, collectDroppedFiles, type DropEntry } from "./components/dropFiles";
57
57
 
58
- export { Toaster, type ToasterProps } from "./components/Toaster";
58
+ // Notifications moved to `@vitavision/ui` (a second app needed them). These are re-exports of
59
+ // the same bindings, so there is still one default store; prefer importing from `@vitavision/ui`.
59
60
  export {
60
61
  createToastStore,
61
62
  defaultToastStore,
63
+ Toaster,
62
64
  toast,
65
+ type ToasterProps,
63
66
  type ToastOptions,
64
67
  type ToastRecord,
65
68
  type ToastStore,
66
69
  type ToastTone,
67
- } from "./components/toastStore";
70
+ } from "@vitavision/ui";
@@ -1,149 +0,0 @@
1
- /*
2
- * Where `toast()` shows up.
3
- *
4
- * Toasts are for news that does not need an answer — a file loaded, a bake finished, a
5
- * worker failed in the background. Anything that must be acknowledged is a `Dialog`, and
6
- * anything tied to one control is that control's `Field` error. So a toast never carries an
7
- * action beyond dismissing it, it goes away by itself, and it holds still while someone is
8
- * reading it (pointer over the stack, or focus inside it).
9
- *
10
- * The tones reuse the `Callout` vocabulary — the accent for a fact, the verdict colours for
11
- * success, caveat and failure — on an opaque `overlay` surface, since a toast floats over
12
- * whatever the viewport is drawing.
13
- */
14
-
15
- import { CircleCheck, CircleX, Info, TriangleAlert, X } from "lucide-react";
16
- import { useEffect, useRef, useState, useSyncExternalStore } from "react";
17
- import type { FocusEvent } from "react";
18
-
19
- import { cn, focusRing } from "@vitavision/ui";
20
-
21
- import { defaultToastStore, type ToastRecord, type ToastStore, type ToastTone } from "./toastStore";
22
-
23
- const TONE: Record<ToastTone, { border: string; icon: string; Icon: typeof Info }> = {
24
- info: { border: "border-signal/30", icon: "text-signal", Icon: Info },
25
- success: { border: "border-normal/30", icon: "text-normal", Icon: CircleCheck },
26
- warn: { border: "border-warn/30", icon: "text-warn", Icon: TriangleAlert },
27
- error: { border: "border-defect/30", icon: "text-defect", Icon: CircleX },
28
- };
29
-
30
- const NO_TOASTS: readonly ToastRecord[] = [];
31
-
32
- /** Props of `Toaster`. */
33
- export interface ToasterProps {
34
- /** The store to show. Defaults to the one behind `toast()`. */
35
- store?: ToastStore | undefined;
36
- /** How many toasts are shown at once; older ones wait. Defaults to 5. */
37
- limit?: number | undefined;
38
- /** Merged with the stack's own classes through `cn` (it is fixed to the bottom-right corner). */
39
- className?: string | undefined;
40
- }
41
-
42
- /**
43
- * The stack of notifications raised with `toast()`. Mount it once, near the root.
44
- *
45
- * Fixed to the bottom-right corner, newest at the bottom. Each toast dismisses itself after
46
- * its `duration`; the countdown pauses while the pointer is over the stack or focus is inside
47
- * it. A `section` landmark ("Notifications") holding a polite live region, so new toasts are
48
- * announced; an `error` toast is a `role="alert"`, announced at once. Each toast carries
49
- * `data-tone` and a "Dismiss" button.
50
- */
51
- export function Toaster({ store = defaultToastStore, limit = 5, className }: ToasterProps) {
52
- const toasts = useSyncExternalStore(store.subscribe, store.getSnapshot, () => NO_TOASTS);
53
- const [hovered, setHovered] = useState(false);
54
- const [focused, setFocused] = useState(false);
55
- const shown = toasts.slice(-Math.max(1, limit));
56
-
57
- const onBlur = (event: FocusEvent<HTMLElement>) => {
58
- if (!event.currentTarget.contains(event.relatedTarget)) setFocused(false);
59
- };
60
-
61
- return (
62
- <section
63
- aria-label="Notifications"
64
- onPointerEnter={() => setHovered(true)}
65
- onPointerLeave={() => setHovered(false)}
66
- onFocus={() => setFocused(true)}
67
- onBlur={onBlur}
68
- className={cn(
69
- "pointer-events-none fixed right-4 bottom-4 z-50 w-80 max-w-[calc(100vw-2rem)]",
70
- className,
71
- )}
72
- >
73
- <ol aria-live="polite" className="flex flex-col gap-2">
74
- {shown.map((record) => (
75
- <ToastItem
76
- key={record.id}
77
- record={record}
78
- paused={hovered || focused}
79
- onDismiss={() => store.dismiss(record.id)}
80
- />
81
- ))}
82
- </ol>
83
- </section>
84
- );
85
- }
86
-
87
- function ToastItem({
88
- record,
89
- paused,
90
- onDismiss,
91
- }: {
92
- record: ToastRecord;
93
- paused: boolean;
94
- onDismiss: () => void;
95
- }) {
96
- const { border, icon, Icon } = TONE[record.tone];
97
- // What is left of the countdown, carried across pauses; restarted when the toast is
98
- // replaced in place (a new record under the same id).
99
- const remainingRef = useRef({ record, ms: record.duration });
100
- const dismissRef = useRef(onDismiss);
101
- useEffect(() => {
102
- dismissRef.current = onDismiss;
103
- });
104
-
105
- useEffect(() => {
106
- if (remainingRef.current.record !== record) remainingRef.current = { record, ms: record.duration };
107
- if (paused || !Number.isFinite(remainingRef.current.ms)) return;
108
- const started = Date.now();
109
- const timer = setTimeout(() => dismissRef.current(), remainingRef.current.ms);
110
- return () => {
111
- clearTimeout(timer);
112
- remainingRef.current.ms = Math.max(0, remainingRef.current.ms - (Date.now() - started));
113
- };
114
- }, [paused, record]);
115
-
116
- return (
117
- // The `alert` role sits on the toast inside the list item, not on the `<li>`: an item with
118
- // another role is no longer a list item, and the list would be malformed.
119
- <li className="pointer-events-auto">
120
- <div
121
- role={record.tone === "error" ? "alert" : undefined}
122
- data-tone={record.tone}
123
- className={cn(
124
- "flex items-start gap-2.5 rounded-panel border bg-overlay px-3 py-2.5 text-sm leading-snug shadow-lg shadow-black/25",
125
- "transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0",
126
- border,
127
- )}
128
- >
129
- <Icon className={cn("mt-0.5 size-4 shrink-0", icon)} aria-hidden />
130
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
131
- <p className="font-medium text-fg">{record.title}</p>
132
- {record.description && <p className="text-fg-muted">{record.description}</p>}
133
- </div>
134
- <button
135
- type="button"
136
- aria-label="Dismiss"
137
- title="Dismiss"
138
- onClick={onDismiss}
139
- className={cn(
140
- "-mr-1 grid size-6 shrink-0 place-items-center rounded-control text-fg-subtle transition-colors hover:bg-raised hover:text-fg",
141
- focusRing,
142
- )}
143
- >
144
- <X className="size-3.5" aria-hidden />
145
- </button>
146
- </div>
147
- </li>
148
- );
149
- }
@@ -1,128 +0,0 @@
1
- /*
2
- * Notifications, as a store any module can write to.
3
- *
4
- * A toast is raised from wherever the news is — a file loader, a worker's error handler, a
5
- * bake that finished — which is rarely a component with a context in reach. So `toast()` is
6
- * a plain function over a module-level store, and `<Toaster />`, mounted once, is its only
7
- * reader. The store holds no timers and touches no DOM: auto-dismissal belongs to the
8
- * `Toaster`, which is what knows whether a reader is hovering it.
9
- */
10
-
11
- /** A toast's kind: a fact (`info`), a completed action (`success`), a caveat (`warn`), a failure (`error`). */
12
- export type ToastTone = "info" | "success" | "warn" | "error";
13
-
14
- /** What `toast()` takes. */
15
- export interface ToastOptions {
16
- /** One line: what happened. */
17
- title: string;
18
- /** More detail, and what to do about it. */
19
- description?: string | undefined;
20
- /** Defaults to `info`. */
21
- tone?: ToastTone | undefined;
22
- /**
23
- * How long it stays, in milliseconds, while not hovered or focused. Defaults to 5000
24
- * (8000 for `error`); `Infinity` keeps it until dismissed.
25
- */
26
- duration?: number | undefined;
27
- /** Replace the toast with this id instead of adding one — for progress that updates in place. */
28
- id?: string | undefined;
29
- }
30
-
31
- /** A toast in the store. */
32
- export interface ToastRecord {
33
- /** Identifies the toast to `dismiss` and to `id` replacement. */
34
- id: string;
35
- /** One line: what happened. */
36
- title: string;
37
- /** More detail, if any. */
38
- description: string | undefined;
39
- /** Its kind. */
40
- tone: ToastTone;
41
- /** Milliseconds before it dismisses itself (`Infinity`: never). */
42
- duration: number;
43
- }
44
-
45
- /**
46
- * A toast store: what `toast()` writes to and `<Toaster />` reads. Every member may be called
47
- * detached.
48
- */
49
- export interface ToastStore {
50
- /** Add a toast (or replace the one with `options.id`), returning its id. */
51
- readonly toast: (options: ToastOptions) => string;
52
- /** Remove one toast, or every toast when `id` is omitted. */
53
- readonly dismiss: (id?: string) => void;
54
- /** The toasts, oldest first. The same array until the store changes. */
55
- readonly getSnapshot: () => readonly ToastRecord[];
56
- /** Be told when the toasts change; returns the unsubscribe function. */
57
- readonly subscribe: (listener: () => void) => () => void;
58
- }
59
-
60
- const DEFAULT_DURATION = 5000;
61
- const ERROR_DURATION = 8000;
62
-
63
- /**
64
- * A new, empty toast store. The package keeps one (behind `toast()` and the default
65
- * `<Toaster />`); create another only to isolate a region or a test.
66
- *
67
- * @returns The store.
68
- */
69
- export function createToastStore(): ToastStore {
70
- let toasts: readonly ToastRecord[] = [];
71
- let sequence = 0;
72
- const listeners = new Set<() => void>();
73
- const commit = (next: readonly ToastRecord[]) => {
74
- toasts = next;
75
- for (const listener of [...listeners]) listener();
76
- };
77
-
78
- return {
79
- toast: (options) => {
80
- const tone = options.tone ?? "info";
81
- sequence += 1;
82
- const record: ToastRecord = {
83
- id: options.id ?? `toast-${sequence}`,
84
- title: options.title,
85
- description: options.description,
86
- tone,
87
- duration: options.duration ?? (tone === "error" ? ERROR_DURATION : DEFAULT_DURATION),
88
- };
89
- const existing = toasts.findIndex((t) => t.id === record.id);
90
- commit(existing === -1 ? [...toasts, record] : toasts.map((t, i) => (i === existing ? record : t)));
91
- return record.id;
92
- },
93
- dismiss: (id) => {
94
- if (id === undefined) {
95
- if (toasts.length > 0) commit([]);
96
- return;
97
- }
98
- if (toasts.some((t) => t.id === id)) commit(toasts.filter((t) => t.id !== id));
99
- },
100
- getSnapshot: () => toasts,
101
- subscribe: (listener) => {
102
- listeners.add(listener);
103
- return () => {
104
- listeners.delete(listener);
105
- };
106
- },
107
- };
108
- }
109
-
110
- /** The store behind `toast()` and a `<Toaster />` given no `store`. */
111
- export const defaultToastStore: ToastStore = createToastStore();
112
-
113
- /**
114
- * Raise a notification, from anywhere — shown by the mounted `<Toaster />`.
115
- *
116
- * `toast({ title: "Scenario loaded", tone: "success" })`. Pass `id` to update a toast in
117
- * place (a progress message that becomes a result). `toast.dismiss(id)` removes one early,
118
- * `toast.dismiss()` all of them.
119
- *
120
- * @param options - The message, its tone and its duration.
121
- * @returns The toast's id.
122
- */
123
- export const toast: ((options: ToastOptions) => string) & {
124
- /** Remove one toast, or every toast when `id` is omitted. */
125
- dismiss: (id?: string) => void;
126
- } = Object.assign((options: ToastOptions) => defaultToastStore.toast(options), {
127
- dismiss: (id?: string) => defaultToastStore.dismiss(id),
128
- });