strata-react 1.0.33 → 1.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +13 -3
  2. package/UPGRADING.md +2 -0
  3. package/dist/components/compare-parts.d.ts +16 -0
  4. package/dist/components/compare-video-grid.d.ts +5 -1
  5. package/dist/components/compare-video.d.ts +12 -1
  6. package/dist/components/compare.d.ts +8 -1
  7. package/dist/components/conversation.d.ts +67 -0
  8. package/dist/components/dialog.d.ts +1 -1
  9. package/dist/components/folder-picker.d.ts +42 -0
  10. package/dist/components/lightbox.d.ts +34 -0
  11. package/dist/components/markable-text.d.ts +56 -0
  12. package/dist/components/media-group.d.ts +25 -0
  13. package/dist/components/media-player.d.ts +80 -2
  14. package/dist/components/pair-vote.d.ts +3 -2
  15. package/dist/components/region-editor.d.ts +55 -0
  16. package/dist/components/sequence-timeline.d.ts +50 -0
  17. package/dist/components/transcript-view.d.ts +36 -0
  18. package/dist/components/tree.d.ts +41 -0
  19. package/dist/components/video-clock.d.ts +9 -1
  20. package/dist/components/viewport.d.ts +22 -0
  21. package/dist/components/waveform.d.ts +66 -0
  22. package/dist/{cursor-DplHNzj3.js → cursor-DDGBPiTJ.js} +2 -200
  23. package/dist/cursor-DDGBPiTJ.js.map +1 -0
  24. package/dist/field-7Z4N5r5g.js +178 -0
  25. package/dist/field-7Z4N5r5g.js.map +1 -0
  26. package/dist/format-B32-PVi2.js +201 -0
  27. package/dist/format-B32-PVi2.js.map +1 -0
  28. package/dist/hls/index.d.ts +19 -0
  29. package/dist/hls.js +84 -0
  30. package/dist/hls.js.map +1 -0
  31. package/dist/index.d.ts +17 -1
  32. package/dist/index.js +3646 -584
  33. package/dist/index.js.map +1 -1
  34. package/dist/lib/marks.d.ts +6 -0
  35. package/dist/lib/region.d.ts +46 -0
  36. package/dist/lib/rich-text.d.ts +44 -0
  37. package/dist/lib/sequence.d.ts +34 -0
  38. package/dist/lib/transcript.d.ts +28 -0
  39. package/dist/lib/waveform.d.ts +36 -0
  40. package/dist/map.js +4 -2
  41. package/dist/map.js.map +1 -1
  42. package/dist/panorama/gl.d.ts +16 -0
  43. package/dist/panorama/index.d.ts +2 -0
  44. package/dist/panorama/panorama-viewer.d.ts +56 -0
  45. package/dist/panorama/projection.d.ts +45 -0
  46. package/dist/panorama.js +657 -0
  47. package/dist/panorama.js.map +1 -0
  48. package/dist/{query-DgJMyXTT.js → query-BJcxJLhh.js} +3 -2
  49. package/dist/{query-DgJMyXTT.js.map → query-BJcxJLhh.js.map} +1 -1
  50. package/dist/{run-BqZGKhW9.js → run-DzyLrZlA.js} +23 -5
  51. package/dist/run-DzyLrZlA.js.map +1 -0
  52. package/dist/testing.js +2 -2
  53. package/dist/{theme-BgTOESmN.js → theme-CFNi6WUO.js} +5 -175
  54. package/dist/theme-CFNi6WUO.js.map +1 -0
  55. package/dist/value-controls-D6O9TsM6.js +356 -0
  56. package/dist/value-controls-D6O9TsM6.js.map +1 -0
  57. package/dist/visual-cli.js +1 -1
  58. package/dist/visual.js +1 -1
  59. package/package.json +19 -4
  60. package/dist/cursor-DplHNzj3.js.map +0 -1
  61. package/dist/run-BqZGKhW9.js.map +0 -1
  62. package/dist/theme-BgTOESmN.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,9 +1,12 @@
1
- import { _ as cn, a as useColorScheme, c as ChoiceGroup, d as NativeSelect, f as Textarea, g as KeyText, h as Tooltip, i as colorSchemeScript, l as Field, m as controlHeight, n as ColorSchemeChoice, o as useSystemColorScheme, p as useFieldControl, r as ThemeProvider, s as Density, t as COLOR_SCHEME_STORAGE_KEY, u as Input, v as typeSteps } from "./theme-BgTOESmN.js";
2
- import { a as NBSP, c as toDate, i as MISSING, n as useSharedCursor, o as createFormat, r as geo, s as format, t as CursorScope } from "./cursor-DplHNzj3.js";
3
- import { _ as IconButton, a as toLoad, c as toast, d as describeActionError, f as describeHttpError, g as Button, h as overlaySurface, i as staleOf, l as toastTimeout, m as readErrorBody, n as createQueryClient, o as useLoad, p as fieldErrorsOf, r as fetchJson, s as StrataToastRegion, t as StrataQueryProvider, u as HttpError, v as RowAction, y as buttonVariants } from "./query-DgJMyXTT.js";
1
+ import { a as Textarea, c as cn, i as NativeSelect, l as typeSteps, n as Field, r as Input, t as ChoiceGroup } from "./field-7Z4N5r5g.js";
2
+ import { a as toDate, i as format, n as NBSP, r as createFormat, t as MISSING } from "./format-B32-PVi2.js";
3
+ import { i as useInView, n as NumberField, r as Slider, t as ColorField } from "./value-controls-D6O9TsM6.js";
4
+ import { _ as IconButton, a as toLoad, c as toast, d as describeActionError, f as describeHttpError, g as Button, h as overlaySurface, i as staleOf, l as toastTimeout, m as readErrorBody, n as createQueryClient, o as useLoad, p as fieldErrorsOf, r as fetchJson, s as StrataToastRegion, t as StrataQueryProvider, u as HttpError, v as RowAction, y as buttonVariants } from "./query-BJcxJLhh.js";
5
+ import { a as useColorScheme, c as Tooltip, i as colorSchemeScript, l as KeyText, n as ColorSchemeChoice, o as useSystemColorScheme, r as ThemeProvider, s as Density, t as COLOR_SCHEME_STORAGE_KEY } from "./theme-CFNi6WUO.js";
6
+ import { n as useSharedCursor, r as geo, t as CursorScope } from "./cursor-DDGBPiTJ.js";
4
7
  import * as React from "react";
5
- import { Autocomplete, Button as Button$1, Cell, Checkbox as Checkbox$1, Collection, Column, Dialog as Dialog$1, DialogTrigger, Disclosure as Disclosure$1, DisclosurePanel, DropIndicator, DropZone, FileTrigger, GridLayout, GridList, GridListItem, Header, Heading, I18nProvider, Input as Input$1, Keyboard, ListLayout, ListStateContext, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, NumberField as NumberField$1, Popover as Popover$1, Row, SearchField, Separator, Slider as Slider$1, SliderOutput, SliderThumb, SliderTrack, SubmenuTrigger, Switch as Switch$1, Tab, TabList, TabPanel, Table, TableBody, TableHeader, TableLayout, Tabs as Tabs$1, Text, ToggleButton, ToggleButtonGroup, Toolbar as Toolbar$1, Virtualizer, useDragAndDrop, useFilter } from "react-aria-components";
6
- import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronRight, CircleAlert, CircleCheck, FileQuestion, Flag, GripVertical, History, ImageOff, Info, Loader, LoaderCircle, Maximize, Maximize2, Minimize, Minus, PanelBottomClose, PanelBottomOpen, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen, PanelTopClose, PanelTopOpen, Pause, Play, Redo2, RotateCcw, Scan, Search, SkipBack, SkipForward, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
8
+ import { Autocomplete, Button as Button$1, Cell, Checkbox as Checkbox$1, Collection, Column, Dialog as Dialog$1, DialogTrigger, Disclosure as Disclosure$1, DisclosurePanel, DropIndicator, DropZone, FileTrigger, GridLayout, GridList, GridListItem, Header, Heading, Input as Input$1, Keyboard, ListLayout, ListStateContext, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, Popover as Popover$1, Row, SearchField, Separator, Slider as Slider$1, SliderThumb, SliderTrack, SubmenuTrigger, Switch as Switch$1, Tab, TabList, TabPanel, Table, TableBody, TableHeader, TableLayout, Tabs as Tabs$1, Text, ToggleButton, ToggleButtonGroup, Toolbar as Toolbar$1, Tree as Tree$1, TreeItem, TreeItemContent, Virtualizer, useDragAndDrop, useFilter } from "react-aria-components";
9
+ import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, FileQuestion, Flag, Folder, FolderOpen, GripVertical, History, ImageOff, Info, Loader, LoaderCircle, Maximize, Maximize2, Minimize, Minus, PanelBottomClose, PanelBottomOpen, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen, PanelTopClose, PanelTopOpen, Pause, Pencil, Play, Redo2, RotateCcw, Scan, Search, Send, SkipBack, SkipForward, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
7
10
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
11
  import { Link, NavLink, useSearchParams } from "react-router";
9
12
  import { createSortedRowModel, flexRender, rowSortingFeature, tableFeatures, useTable } from "@tanstack/react-table";
@@ -11,45 +14,6 @@ import { VisuallyHidden, mergeProps, useDrop, useFocusRing, useMove, useSlider,
11
14
  import { Size, useSliderState } from "react-stately";
12
15
  import { hashKey, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
13
16
  import pixelmatch from "pixelmatch";
14
- // src/lib/in-view.ts
15
- /**
16
- * Whether an element is within `rootMargin` of its scroll region (the nearest
17
- * `[data-strata-scroll]` ancestor, else the viewport). Returns a callback ref, so it follows the
18
- * element as it mounts and unmounts.
19
- */
20
- function useInView({ active = true, rootMargin = "0px", once = false, unsupported = false } = {}) {
21
- const [inView, setInView] = React.useState(false);
22
- const [el, setEl] = React.useState(null);
23
- const seen = once && inView;
24
- React.useEffect(() => {
25
- if (seen) return;
26
- if (!active || !el) {
27
- setInView(false);
28
- return;
29
- }
30
- if (typeof IntersectionObserver === "undefined") {
31
- setInView(unsupported);
32
- return;
33
- }
34
- const root = el.parentElement?.closest("[data-strata-scroll]") ?? null;
35
- const observer = new IntersectionObserver((entries) => setInView(entries[entries.length - 1].isIntersecting), {
36
- root,
37
- rootMargin
38
- });
39
- observer.observe(el);
40
- return () => observer.disconnect();
41
- }, [
42
- active,
43
- el,
44
- rootMargin,
45
- seen,
46
- unsupported
47
- ]);
48
- return {
49
- ref: setEl,
50
- inView
51
- };
52
- }
53
17
  // src/lib/chords.ts
54
18
  /** The platform this page runs on, read from the browser (`mac` for macOS and iOS). Server and test default: `other`. */
55
19
  function detectPlatform() {
@@ -679,7 +643,8 @@ function Switch({ label, detail, on, defaultOn, onChange, disabled, className })
679
643
  var sizes = {
680
644
  sm: "max-w-sm",
681
645
  md: "max-w-lg",
682
- lg: "max-w-3xl"
646
+ lg: "max-w-3xl",
647
+ full: "h-full max-w-none"
683
648
  };
684
649
  function Overlay({ trigger, open, onOpenChange, children }) {
685
650
  if (trigger) return /* @__PURE__ */ jsxs(DialogTrigger, {
@@ -724,7 +689,7 @@ function Dialog({ title, description, trigger, open, onOpenChange, className, ch
724
689
  children: /* @__PURE__ */ jsx(ModalOverlay, {
725
690
  isDismissable: closable,
726
691
  isKeyboardDismissDisabled: !closable,
727
- className: cn(overlayClass, placement === "end" ? "justify-items-end" : "place-items-center p-4"),
692
+ className: cn(overlayClass, placement === "end" ? "justify-items-end" : size === "full" ? "grid-cols-1 grid-rows-1 p-4" : "place-items-center p-4"),
728
693
  children: /* @__PURE__ */ jsx(Modal, {
729
694
  className: cn("flex max-h-full min-h-0 w-full flex-col outline-none", overlaySurface, placement === "end" ? "h-full max-w-md rounded-r-none" : sizes[size], className),
730
695
  children: /* @__PURE__ */ jsx(Dialog$1, {
@@ -1500,315 +1465,6 @@ function Skeleton({ className }) {
1500
1465
  className: cn("rounded-control bg-muted motion-safe:animate-pulse", className)
1501
1466
  });
1502
1467
  }
1503
- // src/lib/number-input.ts
1504
- /** Reads `#rgb`, `#rrggbb` (with or without the #) as lower-case `#rrggbb`, or null. */
1505
- function parseHex(text) {
1506
- const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text.trim());
1507
- if (!m) return null;
1508
- const h = m[1].toLowerCase();
1509
- return "#" + (h.length === 3 ? [...h].map((c) => c + c).join("") : h);
1510
- }
1511
- function luminance(hex) {
1512
- const v = [
1513
- 1,
1514
- 3,
1515
- 5
1516
- ].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => c <= .03928 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4);
1517
- return .2126 * v[0] + .7152 * v[1] + .0722 * v[2];
1518
- }
1519
- /** WCAG contrast ratio between two `#rrggbb` colours, 1 to 21. */
1520
- function contrastRatio(a, b) {
1521
- const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
1522
- return (hi + .05) / (lo + .05);
1523
- }
1524
- // src/components/value-controls.tsx
1525
- var box = "flex w-full min-w-0 items-center rounded-control border border-input bg-background px-3 type-body text-foreground transition-state disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 has-[input:disabled]:cursor-not-allowed has-[input:disabled]:bg-muted has-[input:disabled]:opacity-70 aria-invalid:border-danger has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-ring";
1526
- /** A number with its unit joined by a non-breaking space; `%` and `°` stay attached. */
1527
- function withUnit(text, unit) {
1528
- if (!unit) return text;
1529
- return unit === "%" || unit === "°" ? text + unit : text + "\xA0" + unit;
1530
- }
1531
- var intlUnits = {
1532
- "%": "percent",
1533
- "°": "degree",
1534
- ms: "millisecond",
1535
- s: "second",
1536
- kB: "kilobyte",
1537
- MB: "megabyte",
1538
- GB: "gigabyte",
1539
- kbps: "kilobit-per-second",
1540
- Mbps: "megabit-per-second"
1541
- };
1542
- function decimalsOf(n) {
1543
- const s = String(n);
1544
- if (s.includes("e-")) return Number(s.split("e-")[1]) + (s.split("e-")[0].split(".")[1]?.length ?? 0);
1545
- return s.split(".")[1]?.length ?? 0;
1546
- }
1547
- function useNumberText(locale, places) {
1548
- return React.useMemo(() => {
1549
- const f = new Intl.NumberFormat(locale, {
1550
- maximumFractionDigits: places,
1551
- minimumFractionDigits: 0
1552
- });
1553
- return (n) => f.format(n);
1554
- }, [locale, places]);
1555
- }
1556
- function formatOptionsFor(places, unit) {
1557
- const base = {
1558
- maximumFractionDigits: places,
1559
- minimumFractionDigits: 0
1560
- };
1561
- const known = unit ? intlUnits[unit] : void 0;
1562
- return known ? {
1563
- ...base,
1564
- style: "unit",
1565
- unit: known,
1566
- unitDisplay: "narrow"
1567
- } : base;
1568
- }
1569
- function describeRange(min, max, show, unit) {
1570
- const a = min === void 0 ? "" : withUnit(show(min), unit);
1571
- const b = max === void 0 ? "" : withUnit(show(max), unit);
1572
- if (min !== void 0 && max !== void 0) return `Enter a value from ${a} to ${b}.`;
1573
- if (min !== void 0) return `Enter ${a} or more.`;
1574
- if (max !== void 0) return `Enter ${b} or less.`;
1575
- return "Enter a number.";
1576
- }
1577
- /** A number with a unit on React Aria's number field: typed input is validated, not clamped, so an out-of-range value is explained in the surrounding `Field` and never passed on; empty stays `null`. */
1578
- function NumberField({ value, onChange, min, max, step = 1, places, unit, locale = format.locale, required = false, disabled, id: idProp, name, size = "default", className, "aria-label": ariaLabel }) {
1579
- const { field, report } = useFieldControl();
1580
- const digits = places ?? Math.max(decimalsOf(step), min === void 0 ? 0 : decimalsOf(min));
1581
- const show = useNumberText(locale, digits);
1582
- const [own, setOwn] = React.useState(false);
1583
- const unitId = React.useId();
1584
- const [local, setLocal] = React.useState(value ?? NaN);
1585
- const [seen, setSeen] = React.useState(value);
1586
- if (seen !== value) {
1587
- setSeen(value);
1588
- setLocal(value ?? NaN);
1589
- }
1590
- const fail = (message) => {
1591
- setOwn(true);
1592
- report(message);
1593
- };
1594
- const ok = () => {
1595
- setOwn(false);
1596
- report(void 0);
1597
- };
1598
- const handle = (n) => {
1599
- setLocal(n);
1600
- if (Number.isNaN(n)) {
1601
- if (required) return fail("Enter a value.");
1602
- ok();
1603
- if (value !== null) onChange(null);
1604
- return;
1605
- }
1606
- if (min !== void 0 && n < min || max !== void 0 && n > max) return fail(describeRange(min, max, show, unit));
1607
- ok();
1608
- if (n !== value) onChange(n);
1609
- };
1610
- const invalid = field?.invalid || own;
1611
- return /* @__PURE__ */ jsx(I18nProvider, {
1612
- locale,
1613
- children: /* @__PURE__ */ jsxs(NumberField$1, {
1614
- value: local,
1615
- onChange: handle,
1616
- minValue: min,
1617
- maxValue: max,
1618
- step,
1619
- formatOptions: {
1620
- maximumFractionDigits: digits,
1621
- minimumFractionDigits: 0
1622
- },
1623
- commitBehavior: "validate",
1624
- isDisabled: disabled,
1625
- isInvalid: invalid || void 0,
1626
- name,
1627
- "aria-label": ariaLabel ?? field?.label,
1628
- className: cn(box, controlHeight[size], className),
1629
- children: [/* @__PURE__ */ jsx(Input$1, {
1630
- id: idProp ?? field?.id,
1631
- placeholder: format.missing,
1632
- "aria-describedby": [field?.describedBy, unit ? unitId : void 0].filter(Boolean).join(" ") || void 0,
1633
- className: "min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
1634
- }), unit && /* @__PURE__ */ jsxs("span", {
1635
- id: unitId,
1636
- className: "ml-2 shrink-0 type-body-sm text-muted-foreground",
1637
- children: [/* @__PURE__ */ jsx("span", {
1638
- "aria-hidden": true,
1639
- children: unit
1640
- }), /* @__PURE__ */ jsx("span", {
1641
- className: "sr-only",
1642
- children: intlUnits[unit] ? intlUnits[unit].replace(/-/g, " ") : unit
1643
- })]
1644
- })]
1645
- })
1646
- });
1647
- }
1648
- /** A slider on React Aria with its current value always printed beside the track (and spoken with the unit when `Intl` knows it); `editable` adds a number field to type an exact value. */
1649
- function Slider({ value, onChange, min, max, step = 1, unit, locale = format.locale, editable = false, hideValue = false, places, disabled, className, "aria-label": ariaLabel }) {
1650
- const { field } = useFieldControl();
1651
- const digits = places ?? Math.max(decimalsOf(step), decimalsOf(min));
1652
- const show = useNumberText(locale, digits);
1653
- const name = ariaLabel ?? field?.label ?? "Value";
1654
- const text = withUnit(show(value), unit);
1655
- return /* @__PURE__ */ jsx(I18nProvider, {
1656
- locale,
1657
- children: /* @__PURE__ */ jsxs(Slider$1, {
1658
- value,
1659
- onChange: (v) => onChange(v),
1660
- minValue: min,
1661
- maxValue: max,
1662
- step,
1663
- formatOptions: formatOptionsFor(digits, unit),
1664
- isDisabled: disabled,
1665
- "aria-label": name,
1666
- "aria-describedby": field?.describedBy,
1667
- className: cn("flex min-w-0 items-center gap-3", className),
1668
- children: [/* @__PURE__ */ jsx(SliderTrack, {
1669
- className: "relative flex h-(--control-h) min-w-0 flex-1 cursor-pointer items-center disabled:cursor-not-allowed disabled:opacity-50",
1670
- children: ({ state }) => /* @__PURE__ */ jsxs(Fragment, { children: [
1671
- /* @__PURE__ */ jsx("span", {
1672
- "aria-hidden": true,
1673
- className: "absolute inset-x-0 h-1.5 rounded-pill bg-muted"
1674
- }),
1675
- /* @__PURE__ */ jsx("span", {
1676
- "aria-hidden": true,
1677
- className: "absolute left-0 h-1.5 rounded-pill bg-primary",
1678
- style: { width: `${state.getThumbPercent(0) * 100}%` }
1679
- }),
1680
- /* @__PURE__ */ jsx(SliderThumb, { className: "top-1/2 size-5 rounded-pill border-2 border-primary bg-background focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring" })
1681
- ] })
1682
- }), editable ? /* @__PURE__ */ jsx(NumberField, {
1683
- className: "w-28 shrink-0",
1684
- "aria-label": `${name}, exact value`,
1685
- value,
1686
- onChange: (v) => v !== null && onChange(v),
1687
- min,
1688
- max,
1689
- step,
1690
- unit,
1691
- locale,
1692
- places: digits,
1693
- required: true,
1694
- disabled
1695
- }) : !hideValue && /* @__PURE__ */ jsx(SliderOutput, {
1696
- "aria-hidden": true,
1697
- className: "w-16 shrink-0 text-right type-body-sm tabular-nums text-foreground",
1698
- children: text
1699
- })]
1700
- })
1701
- });
1702
- }
1703
- /** Choose a colour with the platform picker, see and type its hex value, pick from the app's suggestions, and get a note when it would be hard to see on `against`. A half-typed value is never passed on. */
1704
- function ColorField({ value, onChange, suggestions, against, againstLabel = "the background", minContrast = 3, disabled, id: idProp, className, "aria-label": ariaLabel }) {
1705
- const { field, report } = useFieldControl();
1706
- const label = ariaLabel ?? field?.label;
1707
- const pickerName = label ? `${label}, picker` : "Colour picker";
1708
- const [draft, setDraft] = React.useState(null);
1709
- const [own, setOwn] = React.useState(false);
1710
- const text = draft ?? value ?? "";
1711
- const ratio = value && against ? contrastRatio(value, against) : null;
1712
- const commitText = (t) => {
1713
- if (t.trim() === "") {
1714
- setOwn(false);
1715
- report(void 0);
1716
- if (value !== null) onChange(null);
1717
- return true;
1718
- }
1719
- const hex = parseHex(t);
1720
- if (!hex) {
1721
- setOwn(true);
1722
- report("Enter a colour like #1a7f64.");
1723
- return false;
1724
- }
1725
- setOwn(false);
1726
- report(void 0);
1727
- if (hex !== value) onChange(hex);
1728
- return true;
1729
- };
1730
- const pick = (hex) => {
1731
- setDraft(null);
1732
- setOwn(false);
1733
- report(void 0);
1734
- if (hex !== value) onChange(hex);
1735
- };
1736
- const invalid = field?.invalid || own;
1737
- return /* @__PURE__ */ jsxs("div", {
1738
- className: cn("grid min-w-0 gap-2", className),
1739
- children: [
1740
- /* @__PURE__ */ jsxs("div", {
1741
- className: cn(box, controlHeight.default, "gap-2 px-2"),
1742
- "aria-invalid": invalid || void 0,
1743
- children: [/* @__PURE__ */ jsxs("span", {
1744
- className: "relative size-6 shrink-0 overflow-hidden rounded-control border border-input",
1745
- children: [/* @__PURE__ */ jsx("span", {
1746
- "aria-hidden": true,
1747
- className: cn("absolute inset-0", value === null && "bg-muted"),
1748
- style: value ? { background: value } : void 0
1749
- }), /* @__PURE__ */ jsx("input", {
1750
- type: "color",
1751
- "aria-label": pickerName,
1752
- value: value ?? "#000000",
1753
- disabled,
1754
- onChange: (e) => pick(e.target.value),
1755
- className: "absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed"
1756
- })]
1757
- }), /* @__PURE__ */ jsx("input", {
1758
- id: idProp ?? field?.id,
1759
- type: "text",
1760
- autoComplete: "off",
1761
- spellCheck: false,
1762
- disabled,
1763
- "aria-label": ariaLabel,
1764
- "aria-describedby": field?.describedBy,
1765
- "aria-invalid": invalid || void 0,
1766
- placeholder: format.missing,
1767
- value: text,
1768
- onChange: (e) => setDraft(e.target.value),
1769
- onBlur: () => {
1770
- if (draft !== null && commitText(draft)) setDraft(null);
1771
- },
1772
- onKeyDown: (e) => {
1773
- if (e.key === "Enter" && draft !== null && commitText(draft)) setDraft(null);
1774
- if (e.key === "Escape" && draft !== null) {
1775
- setDraft(null);
1776
- setOwn(false);
1777
- report(void 0);
1778
- }
1779
- },
1780
- className: "min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
1781
- })]
1782
- }),
1783
- suggestions && suggestions.length > 0 && /* @__PURE__ */ jsx("div", {
1784
- role: "group",
1785
- "aria-label": "Suggested colours",
1786
- className: "flex flex-wrap gap-1.5",
1787
- children: suggestions.map((hex) => /* @__PURE__ */ jsx("button", {
1788
- type: "button",
1789
- disabled,
1790
- "aria-label": hex,
1791
- "aria-pressed": value === hex,
1792
- onClick: () => pick(hex),
1793
- className: "size-6 cursor-pointer rounded-control border border-input transition-state aria-pressed:outline-2 aria-pressed:outline-offset-2 aria-pressed:outline-foreground disabled:cursor-not-allowed disabled:opacity-50",
1794
- style: { background: hex }
1795
- }, hex))
1796
- }),
1797
- ratio !== null && ratio < minContrast && /* @__PURE__ */ jsxs("p", {
1798
- className: "type-body-sm text-warning",
1799
- children: [
1800
- "Hard to see on ",
1801
- againstLabel,
1802
- ": contrast ",
1803
- format.decimal(ratio),
1804
- ":1, aim for ",
1805
- format.decimal(minContrast),
1806
- ":1 or more."
1807
- ]
1808
- })
1809
- ]
1810
- });
1811
- }
1812
1468
  // src/components/alert.tsx
1813
1469
  var tones = {
1814
1470
  info: {
@@ -2629,7 +2285,7 @@ function TableSkeleton({ rows = 4, columns = 5 }) {
2629
2285
  });
2630
2286
  }
2631
2287
  // src/components/media.tsx
2632
- var clamp$2 = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
2288
+ var clamp$3 = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
2633
2289
  var timecode = (t, { precision, fps }) => format.timecode(t, {
2634
2290
  precision,
2635
2291
  fps
@@ -2676,8 +2332,8 @@ function SeekBar({ time, duration: known, onSeek, marks = [], onMarkPress, buffe
2676
2332
  const disabled = off || duration === 0;
2677
2333
  const track = React.useRef(null);
2678
2334
  const input = React.useRef(null);
2679
- const frac = duration > 0 ? clamp$2(time / duration, 0, 1) : 0;
2680
- const seekTo = (t) => onSeek(clamp$2(t, 0, duration));
2335
+ const frac = duration > 0 ? clamp$3(time / duration, 0, 1) : 0;
2336
+ const seekTo = (t) => onSeek(clamp$3(t, 0, duration));
2681
2337
  const shared = useSharedCursor();
2682
2338
  const joined = Boolean(cursorProp) && shared !== null;
2683
2339
  const mapping = typeof cursorProp === "object" ? cursorProp : void 0;
@@ -2714,7 +2370,7 @@ function SeekBar({ time, duration: known, onSeek, marks = [], onMarkPress, buffe
2714
2370
  minValue: 0,
2715
2371
  maxValue: Math.max(duration, fine),
2716
2372
  step: fine,
2717
- value: [clamp$2(time, 0, duration)],
2373
+ value: [clamp$3(time, 0, duration)],
2718
2374
  onChange: ([t]) => seekTo(t),
2719
2375
  numberFormatter: timeText,
2720
2376
  isDisabled: disabled
@@ -2756,7 +2412,7 @@ function SeekBar({ time, duration: known, onSeek, marks = [], onMarkPress, buffe
2756
2412
  onPointerMove: (e) => {
2757
2413
  if (!joined || duration === 0) return;
2758
2414
  const box = e.currentTarget.getBoundingClientRect();
2759
- shared.setPointer(toCursor(clamp$2((e.clientX - box.left) / (box.width || 1) * duration, 0, duration)));
2415
+ shared.setPointer(toCursor(clamp$3((e.clientX - box.left) / (box.width || 1) * duration, 0, duration)));
2760
2416
  },
2761
2417
  onPointerLeave: () => shared?.setPointer(null)
2762
2418
  }),
@@ -2770,7 +2426,7 @@ function SeekBar({ time, duration: known, onSeek, marks = [], onMarkPress, buffe
2770
2426
  buffered !== void 0 && duration > 0 && /* @__PURE__ */ jsx("span", {
2771
2427
  "aria-hidden": true,
2772
2428
  className: "absolute left-0 h-1.5 rounded-pill bg-neutral-4",
2773
- style: { width: `${clamp$2(buffered / duration, 0, 1) * 100}%` }
2429
+ style: { width: `${clamp$3(buffered / duration, 0, 1) * 100}%` }
2774
2430
  }),
2775
2431
  /* @__PURE__ */ jsx("span", {
2776
2432
  "aria-hidden": true,
@@ -2912,7 +2568,7 @@ function RateChoice({ rate, onRateChange, rates = [
2912
2568
  * to the ends, M mutes. Pass the player's actions; the labels are the legend's words.
2913
2569
  */
2914
2570
  function transportShortcuts({ toggle, seek, time, duration, frame = 1 / 30, jump = 1, toggleMute }) {
2915
- const to = (t) => () => seek(clamp$2(t, 0, duration));
2571
+ const to = (t) => () => seek(clamp$3(t, 0, duration));
2916
2572
  return [
2917
2573
  {
2918
2574
  keys: [" ", "k"],
@@ -3068,8 +2724,54 @@ function StageGuides({ safe, thirds, centre, className }) {
3068
2724
  children: [draw("stroke-foreground", 3), draw("stroke-background", 1)]
3069
2725
  });
3070
2726
  }
2727
+ // src/components/media-group.tsx
2728
+ var groups = /* @__PURE__ */ new Map();
2729
+ /** Adds an element to a named group until the returned function is called; whenever one plays, the others pause. */
2730
+ function joinMediaGroup(name, el) {
2731
+ let members = groups.get(name);
2732
+ if (!members) groups.set(name, members = /* @__PURE__ */ new Set());
2733
+ members.add(el);
2734
+ const onPlay = () => {
2735
+ for (const other of groups.get(name) ?? []) if (other !== el && !other.paused) other.pause();
2736
+ };
2737
+ el.addEventListener("play", onPlay);
2738
+ return () => {
2739
+ el.removeEventListener("play", onPlay);
2740
+ members.delete(el);
2741
+ if (members.size === 0 && groups.get(name) === members) groups.delete(name);
2742
+ };
2743
+ }
2744
+ var GroupContext = React.createContext(null);
2745
+ /** The group a `MediaGroup` above this point names, or null. */
2746
+ function useMediaGroupName() {
2747
+ return React.useContext(GroupContext);
2748
+ }
2749
+ /** Players and elements under it play one at a time: starting one pauses the others. */
2750
+ function MediaGroup({ name, children }) {
2751
+ const own = React.useId();
2752
+ return /* @__PURE__ */ jsx(GroupContext.Provider, {
2753
+ value: name ?? own,
2754
+ children
2755
+ });
2756
+ }
2757
+ /** Whether two windows are the same stretch. */
2758
+ var sameWindow = (a, b) => (a ?? null) === (b ?? null) || !!a && !!b && a.start === b.start && a.end === b.end;
2759
+ /** A row's play button for one window of a shared element: named for what it plays, pressed while it plays, a second press pauses. */
2760
+ function PlayWindowButton({ media, window: w, label, size = "sm", className }) {
2761
+ const playing = media.playing && sameWindow(media.window, w);
2762
+ return /* @__PURE__ */ jsx(IconButton, {
2763
+ icon: playing ? Pause : Play,
2764
+ label,
2765
+ size,
2766
+ className,
2767
+ "aria-pressed": playing,
2768
+ onClick: () => playing ? media.pause() : void media.playWindow(w)
2769
+ });
2770
+ }
3071
2771
  // src/components/media-player.tsx
3072
2772
  var idle = {
2773
+ ready: 0,
2774
+ waitingForMore: false,
3073
2775
  playing: false,
3074
2776
  time: 0,
3075
2777
  duration: null,
@@ -3129,41 +2831,100 @@ var EVENTS = [
3129
2831
  "error"
3130
2832
  ];
3131
2833
  /** Follows an `<audio>` or `<video>` and returns its state and the requests a player makes. Works with the browser's own controls too. */
3132
- function useMediaElement(ref) {
2834
+ function useMediaElement(ref, options = {}) {
3133
2835
  const [snapshot, setSnapshot] = React.useState(idle);
3134
2836
  const blocked = React.useRef(null);
3135
2837
  const pendingSeek = React.useRef(null);
2838
+ const [ownWindow, setOwnWindow] = React.useState(null);
2839
+ const active = options.window ?? ownWindow;
2840
+ const win = React.useRef(active);
2841
+ win.current = active;
2842
+ const opts = React.useRef(options);
2843
+ opts.current = options;
2844
+ const windowEnded = React.useRef(false);
2845
+ const streamProblem = React.useRef(null);
2846
+ const edgePause = React.useRef(false);
2847
+ const contextGroup = useMediaGroupName();
2848
+ const group = options.group ?? contextGroup;
3136
2849
  const read = React.useCallback(() => {
3137
2850
  const el = ref.current;
3138
2851
  if (!el) return;
3139
2852
  const finite = Number.isFinite(el.duration) && el.duration > 0;
3140
- let error = blocked.current;
2853
+ const growing = opts.current.growing === true;
2854
+ const seekEnd = el.seekable && el.seekable.length > 0 ? el.seekable.end(el.seekable.length - 1) : 0;
2855
+ const known = finite ? el.duration : growing && seekEnd > 0 ? seekEnd : null;
2856
+ const ready = growing ? seekEnd > 0 ? seekEnd : known ?? 0 : known ?? 0;
2857
+ const endedNow = el.ended && !growing;
2858
+ let error = blocked.current ?? (streamProblem.current ? {
2859
+ kind: "load",
2860
+ message: streamProblem.current
2861
+ } : null);
3141
2862
  if (el.error && el.error.code !== 1) error = {
3142
2863
  kind: "load",
3143
2864
  message: LOAD_MESSAGES[el.error.code] ?? "It could not be played."
3144
2865
  };
3145
2866
  const next = {
2867
+ ready,
2868
+ waitingForMore: growing && known !== null && (el.ended || el.readyState < 3 && !el.paused) && el.currentTime >= known - 2,
3146
2869
  playing: !el.paused && !el.ended,
3147
2870
  time: Number.isFinite(el.currentTime) ? el.currentTime : 0,
3148
- duration: finite ? el.duration : null,
2871
+ duration: known,
3149
2872
  buffered: bufferedAhead(el),
3150
2873
  volume: el.muted ? 0 : Math.round(el.volume * 100),
3151
2874
  muted: el.muted,
3152
2875
  rate: el.playbackRate,
3153
- ended: el.ended,
2876
+ ended: endedNow,
3154
2877
  loading: !error && el.networkState === 2 && el.readyState < 3 && !el.paused,
3155
2878
  error
3156
2879
  };
2880
+ if (growing && el.ended) edgePause.current = true;
2881
+ if (edgePause.current && known !== null && known > el.currentTime + .5 && el.paused) {
2882
+ edgePause.current = false;
2883
+ el.play().catch(() => {});
2884
+ }
3157
2885
  setSnapshot((previous) => Object.keys(next).every((k) => Object.is(previous[k], next[k]) || k === "error" && previous.error?.message === next.error?.message && previous.error?.kind === next.error?.kind) ? previous : next);
3158
2886
  }, [ref]);
2887
+ const enforce = React.useCallback((el) => {
2888
+ const w = win.current;
2889
+ if (!w || el.paused || windowEnded.current) return;
2890
+ if (el.currentTime < w.end) return;
2891
+ if (opts.current.loop) {
2892
+ el.currentTime = w.start;
2893
+ return;
2894
+ }
2895
+ windowEnded.current = true;
2896
+ el.pause();
2897
+ el.currentTime = w.end;
2898
+ opts.current.onWindowEnd?.();
2899
+ }, []);
3159
2900
  useElementListeners(ref, (el) => {
2901
+ el.preservesPitch = true;
3160
2902
  const on = (e) => {
3161
2903
  if (e.type === "play" || e.type === "playing") blocked.current = null;
2904
+ if (e.type === "play") {
2905
+ windowEnded.current = false;
2906
+ const w = win.current;
2907
+ if (w && (el.currentTime < w.start || el.currentTime >= w.end)) el.currentTime = w.start;
2908
+ }
2909
+ if (e.type === "ended" && win.current && !windowEnded.current) {
2910
+ if (opts.current.loop) {
2911
+ el.currentTime = win.current.start;
2912
+ el.play().catch(() => {});
2913
+ } else {
2914
+ windowEnded.current = true;
2915
+ opts.current.onWindowEnd?.();
2916
+ }
2917
+ }
2918
+ if (e.type === "timeupdate") enforce(el);
3162
2919
  if (e.type === "loadedmetadata" && pendingSeek.current !== null) {
3163
2920
  el.currentTime = pendingSeek.current;
3164
2921
  pendingSeek.current = null;
3165
2922
  }
3166
- if (e.type === "emptied" || e.type === "loadstart") blocked.current = null;
2923
+ if (e.type === "emptied" || e.type === "loadstart") {
2924
+ blocked.current = null;
2925
+ streamProblem.current = null;
2926
+ }
2927
+ if (e.type === "pause" && !el.ended) edgePause.current = false;
3167
2928
  read();
3168
2929
  };
3169
2930
  for (const type of EVENTS) el.addEventListener(type, on);
@@ -3172,6 +2933,51 @@ function useMediaElement(ref) {
3172
2933
  for (const type of EVENTS) el.removeEventListener(type, on);
3173
2934
  };
3174
2935
  });
2936
+ const joined = React.useRef(null);
2937
+ React.useEffect(() => {
2938
+ const el = ref.current;
2939
+ if (joined.current && (joined.current.el !== el || joined.current.name !== group)) {
2940
+ joined.current.leave();
2941
+ joined.current = null;
2942
+ }
2943
+ if (el && group && !joined.current) joined.current = {
2944
+ el,
2945
+ name: group,
2946
+ leave: joinMediaGroup(group, el)
2947
+ };
2948
+ });
2949
+ React.useEffect(() => () => {
2950
+ joined.current?.leave();
2951
+ joined.current = null;
2952
+ }, []);
2953
+ const startKey = active ? `${active.start}:${active.end}` : null;
2954
+ React.useEffect(() => {
2955
+ const el = ref.current;
2956
+ if (!el || !active) return;
2957
+ windowEnded.current = false;
2958
+ if (el.readyState < 1) pendingSeek.current = active.start;
2959
+ else if (el.currentTime < active.start || el.currentTime >= active.end) el.currentTime = active.start;
2960
+ }, [startKey]);
2961
+ React.useEffect(() => {
2962
+ if (!snapshot.playing || !active && !options.onTimeUpdate) return;
2963
+ let frame = 0;
2964
+ const tick = () => {
2965
+ const el = ref.current;
2966
+ if (el) {
2967
+ enforce(el);
2968
+ opts.current.onTimeUpdate?.(el.currentTime);
2969
+ }
2970
+ frame = requestAnimationFrame(tick);
2971
+ };
2972
+ frame = requestAnimationFrame(tick);
2973
+ return () => cancelAnimationFrame(frame);
2974
+ }, [
2975
+ snapshot.playing,
2976
+ active !== null,
2977
+ options.onTimeUpdate !== void 0,
2978
+ enforce,
2979
+ ref
2980
+ ]);
3175
2981
  return React.useMemo(() => {
3176
2982
  const play = async () => {
3177
2983
  const el = ref.current;
@@ -3188,8 +2994,24 @@ function useMediaElement(ref) {
3188
2994
  } else if (!(e instanceof DOMException && e.name === "AbortError")) read();
3189
2995
  }
3190
2996
  };
2997
+ const playWindow = async (w) => {
2998
+ const el = ref.current;
2999
+ if (!el) return;
3000
+ win.current = w;
3001
+ windowEnded.current = false;
3002
+ setOwnWindow(w);
3003
+ if (el.readyState < 1) pendingSeek.current = w.start;
3004
+ else el.currentTime = w.start;
3005
+ await play();
3006
+ };
3191
3007
  return {
3192
3008
  ...snapshot,
3009
+ window: active,
3010
+ playWindow,
3011
+ reportProblem: (message) => {
3012
+ streamProblem.current = message;
3013
+ read();
3014
+ },
3193
3015
  play,
3194
3016
  pause: () => ref.current?.pause(),
3195
3017
  toggle: () => {
@@ -3217,6 +3039,7 @@ function useMediaElement(ref) {
3217
3039
  if (!el) return;
3218
3040
  el.defaultPlaybackRate = rate;
3219
3041
  el.playbackRate = rate;
3042
+ el.preservesPitch = true;
3220
3043
  },
3221
3044
  retry: () => {
3222
3045
  const el = ref.current;
@@ -3224,6 +3047,12 @@ function useMediaElement(ref) {
3224
3047
  const resume = !el.paused;
3225
3048
  const at = el.currentTime;
3226
3049
  blocked.current = null;
3050
+ streamProblem.current = null;
3051
+ if (opts.current.onRetry) {
3052
+ opts.current.onRetry(at);
3053
+ read();
3054
+ return;
3055
+ }
3227
3056
  el.load();
3228
3057
  if (at > 0) pendingSeek.current = at;
3229
3058
  read();
@@ -3233,9 +3062,42 @@ function useMediaElement(ref) {
3233
3062
  }, [
3234
3063
  snapshot,
3235
3064
  ref,
3236
- read
3065
+ read,
3066
+ active
3237
3067
  ]);
3238
3068
  }
3069
+ /**
3070
+ * Hands `src` to a stream engine (`attach`) for the element in `ref`, and ends the hold when `src` changes, `attach` does, or the component unmounts.
3071
+ * Use it for a plain `<video>` the app owns, with `useMediaElement`; `MediaPlayer` does it for `attach`.
3072
+ * Returns `reload`, for the player's Try again (`useMediaElement`'s `onRetry`), and gives the engine's failures to `onProblem` (`reportProblem`).
3073
+ */
3074
+ function useAttachedSource(ref, src, attach, onProblem) {
3075
+ const hold = React.useRef(null);
3076
+ const problem = React.useRef(onProblem);
3077
+ problem.current = onProblem;
3078
+ React.useEffect(() => {
3079
+ const el = ref.current;
3080
+ const now = hold.current;
3081
+ if (now && now.el === el && now.src === src && now.attach === attach) return;
3082
+ now?.attachment.detach();
3083
+ hold.current = null;
3084
+ if (!el || !attach || !src) return;
3085
+ hold.current = {
3086
+ el,
3087
+ src,
3088
+ attach,
3089
+ attachment: attach(el, src, {
3090
+ startAt: 0,
3091
+ onProblem: (m) => problem.current?.(m)
3092
+ })
3093
+ };
3094
+ });
3095
+ React.useEffect(() => () => {
3096
+ hold.current?.attachment.detach();
3097
+ hold.current = null;
3098
+ }, []);
3099
+ return React.useMemo(() => ({ reload: (at) => hold.current?.attachment.reload(at) }), []);
3100
+ }
3239
3101
  var keyPlayers = (() => {
3240
3102
  const ids = /* @__PURE__ */ new Set();
3241
3103
  let active = null;
@@ -3307,7 +3169,7 @@ function useCoarsePointer() {
3307
3169
  * a touch device), with the failure to load shown and retried. For an editor or a replay, use the
3308
3170
  * parts and `useMediaElement` directly.
3309
3171
  */
3310
- function MediaPlayer({ label, kind = "audio", src, sources, index: controlledIndex, onIndexChange, autoAdvance = true, controls = "auto", autoPlay, poster, session, rates, shortcuts = true, onEnded, onTimeChange, className }) {
3172
+ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledIndex, onIndexChange, autoAdvance = true, controls = "auto", autoPlay, poster, session, rates, shortcuts = true, attach, growing, window: bound, loop, showFull, group, onTimeUpdate, onWindowEnd, onEnded, onTimeChange, className }) {
3311
3173
  const list = React.useMemo(() => sources ?? (src ? [{
3312
3174
  src,
3313
3175
  title: label
@@ -3320,7 +3182,17 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3320
3182
  const index = Math.min(controlledIndex ?? ownIndex, Math.max(list.length - 1, 0));
3321
3183
  const current = list[index];
3322
3184
  const ref = React.useRef(null);
3323
- const media = useMediaElement(ref);
3185
+ const stream = React.useRef({ reload: () => {} });
3186
+ const media = useMediaElement(ref, {
3187
+ window: bound,
3188
+ loop,
3189
+ group,
3190
+ onTimeUpdate,
3191
+ onWindowEnd,
3192
+ growing: growing !== void 0,
3193
+ onRetry: attach ? (t) => stream.current.reload(t) : void 0
3194
+ });
3195
+ stream.current = useAttachedSource(ref, current?.src, attach, media.reportProblem);
3324
3196
  const coarse = useCoarsePointer();
3325
3197
  const native = controls === "native" || controls === "auto" && coarse;
3326
3198
  const go = React.useCallback((to) => {
@@ -3359,8 +3231,11 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3359
3231
  media.play();
3360
3232
  }
3361
3233
  }, [current?.src]);
3234
+ const growingRef = React.useRef(growing !== void 0);
3235
+ growingRef.current = growing !== void 0;
3362
3236
  const onEnd = React.useCallback(() => {
3363
3237
  const k = keep.current;
3238
+ if (growingRef.current) return;
3364
3239
  if (k.autoAdvance && k.index < k.last) {
3365
3240
  resume.current = true;
3366
3241
  k.go(k.index + 1);
@@ -3380,9 +3255,13 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3380
3255
  });
3381
3256
  }, [list]);
3382
3257
  const total = offsets ? offsets[offsets.length - 1] + list[list.length - 1].duration : null;
3383
- const time = (offsets ? offsets[index] : 0) + media.time;
3384
- const duration = total ?? media.duration;
3258
+ const cut = bound && !showFull ? bound : null;
3259
+ const time = cut ? Math.min(Math.max(media.time - cut.start, 0), cut.end - cut.start) : (offsets ? offsets[index] : 0) + media.time;
3260
+ const wholeLength = growing && list.length === 1 && list[0].duration ? list[0].duration : null;
3261
+ const duration = cut ? cut.end - cut.start : total ?? wholeLength ?? media.duration;
3385
3262
  const seek = (t) => {
3263
+ if (growing && media.ready > 0) t = Math.min(t, media.ready);
3264
+ if (cut) return media.seek(cut.start + Math.min(Math.max(t, 0), cut.end - cut.start));
3386
3265
  if (!offsets) return media.seek(t);
3387
3266
  let to = offsets.length - 1;
3388
3267
  while (to > 0 && offsets[to] > t) to--;
@@ -3499,7 +3378,7 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3499
3378
  ]);
3500
3379
  const common = {
3501
3380
  ref,
3502
- src: current?.src,
3381
+ src: attach ? void 0 : current?.src,
3503
3382
  controls: native,
3504
3383
  autoPlay,
3505
3384
  preload: "metadata",
@@ -3540,6 +3419,37 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3540
3419
  className: "type-body-sm text-muted-foreground",
3541
3420
  children: media.error.message
3542
3421
  }),
3422
+ growing && /* @__PURE__ */ jsxs("div", {
3423
+ className: "flex flex-wrap items-center gap-x-3 gap-y-1",
3424
+ children: [
3425
+ /* @__PURE__ */ jsx(Status, {
3426
+ tone: "info",
3427
+ icon: LoaderCircle,
3428
+ children: "Still being made"
3429
+ }),
3430
+ growing.status && /* @__PURE__ */ jsx("span", {
3431
+ className: "type-body-sm text-muted-foreground",
3432
+ children: growing.status
3433
+ }),
3434
+ /* @__PURE__ */ jsx("span", {
3435
+ role: "status",
3436
+ className: "type-body-sm text-muted-foreground",
3437
+ children: media.waitingForMore ? "Waiting for more to be made. It will carry on by itself." : ""
3438
+ })
3439
+ ]
3440
+ }),
3441
+ bound && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("p", {
3442
+ className: "type-caption text-muted-foreground tabular-nums",
3443
+ children: [
3444
+ format.runningTime(bound.start),
3445
+ " to ",
3446
+ format.runningTime(bound.end),
3447
+ loop ? ", looping" : ""
3448
+ ]
3449
+ }), /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx("span", {
3450
+ role: "status",
3451
+ children: media.playing ? `Playing ${format.runningTime(bound.start)} to ${format.runningTime(bound.end)}` : ""
3452
+ }) })] }),
3543
3453
  !native && /* @__PURE__ */ jsxs("div", {
3544
3454
  className: "grid gap-2",
3545
3455
  children: [/* @__PURE__ */ jsxs("div", {
@@ -3548,8 +3458,14 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3548
3458
  time,
3549
3459
  duration,
3550
3460
  onSeek: seek,
3551
- buffered: offsets ? void 0 : media.buffered,
3552
- marks: offsets ? list.map((s, i) => ({
3461
+ buffered: growing ? media.ready : offsets ? void 0 : media.buffered,
3462
+ marks: bound && showFull ? [{
3463
+ time: bound.start,
3464
+ label: "Window starts"
3465
+ }, {
3466
+ time: bound.end,
3467
+ label: "Window ends"
3468
+ }] : offsets ? list.map((s, i) => ({
3553
3469
  time: offsets[i],
3554
3470
  label: s.title
3555
3471
  })).slice(1) : [],
@@ -3606,182 +3522,1079 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3606
3522
  ]
3607
3523
  });
3608
3524
  }
3609
- // src/lib/timeline.ts
3610
- /** Steps a person would write on a scale, in seconds: 1, 2, 5 and 10 × 10ⁿ below a minute, then 15 s, 30 s, minutes, quarter hours, hours, days. ux-research components.md §3.8: ticks land on values people would write. */
3611
- var STEPS = [
3612
- .01,
3613
- .02,
3614
- .05,
3615
- .1,
3616
- .2,
3617
- .5,
3618
- 1,
3619
- 2,
3620
- 5,
3621
- 10,
3622
- 15,
3623
- 30,
3624
- 60,
3625
- 120,
3626
- 300,
3627
- 600,
3628
- 900,
3629
- 1800,
3630
- 3600,
3631
- 7200,
3632
- 14400,
3633
- 21600,
3634
- 43200,
3635
- 86400
3636
- ];
3637
- /** The smallest step whose ticks are at least `minGapPx` apart at this zoom, so labels thin out instead of colliding. */
3638
- function tickStep(pxPerUnit, minGapPx = 80) {
3639
- return STEPS.find((s) => s * pxPerUnit >= minGapPx) ?? STEPS[STEPS.length - 1];
3640
- }
3641
- /** Tick times from `from` to `to` inclusive, on multiples of `step`. */
3642
- function ticksBetween(from, to, step) {
3643
- const out = [];
3644
- const first = Math.ceil(from / step - 1e-9);
3645
- for (let i = first; i * step <= to + 1e-9; i++) out.push(Math.round(i * step * 1e6) / 1e6 || 0);
3646
- return out;
3525
+ // src/lib/transcript.ts
3526
+ /** The phrase being heard at `time`, as an index into `phrases` (sorted by start), or -1. A phrase is heard from its `start` up to, not including, its `end`. */
3527
+ function phraseAt(phrases, time) {
3528
+ let lo = 0;
3529
+ let hi = phrases.length - 1;
3530
+ let found = -1;
3531
+ while (lo <= hi) {
3532
+ const mid = lo + hi >> 1;
3533
+ if (phrases[mid].start <= time) {
3534
+ found = mid;
3535
+ lo = mid + 1;
3536
+ } else hi = mid - 1;
3537
+ }
3538
+ for (let i = found; i >= 0 && i > found - 8; i--) if (time < phrases[i].end) return i;
3539
+ return -1;
3647
3540
  }
3648
- /** A tick's label: m:ss, h:mm:ss, with tenths or hundredths when the step is under a second. */
3649
- function tickLabel(time, step) {
3650
- const decimals = step < .1 ? 2 : step < 1 ? 1 : 0;
3651
- const whole = Math.floor(time + 1e-9);
3652
- const h = Math.floor(whole / 3600);
3653
- const m = Math.floor(whole % 3600 / 60);
3654
- const s = whole % 60;
3655
- const two = (n) => String(n).padStart(2, "0");
3656
- const base = h > 0 ? `${h}:${two(m)}:${two(s)}` : `${m}:${two(s)}`;
3657
- return decimals ? `${base}.${String(Math.round((time - whole) * 10 ** decimals)).padStart(decimals, "0")}` : base;
3541
+ /** The word being heard within a phrase at `time`: the last word that has started, until the phrase ends. -1 before the first word. */
3542
+ function wordAt(phrase, time) {
3543
+ if (time >= phrase.end) return -1;
3544
+ let found = -1;
3545
+ for (let i = 0; i < phrase.words.length; i++) if (phrase.words[i].start <= time) found = i;
3546
+ else break;
3547
+ return found;
3658
3548
  }
3659
- function clamp$1(value, min, max) {
3660
- return Math.min(Math.max(value, min), max);
3549
+ // src/components/virtual-list.tsx
3550
+ var FOOTER = "\0footer";
3551
+ /** A list that renders only its visible rows (React Aria's GridList and Virtualizer) from `virtualizeFrom` items, with arrow-key navigation between rows. */
3552
+ function VirtualList({ label, items, itemKey, children, estimateSize = 48, rowHeight, height = 480, virtualizeFrom = 100, bounded = false, footer, className }) {
3553
+ const virtual = items.length >= virtualizeFrom;
3554
+ const rows = React.useMemo(() => items.map((item, index) => ({
3555
+ id: itemKey(item),
3556
+ item,
3557
+ index
3558
+ })), [items, itemKey]);
3559
+ const layoutOptions = React.useMemo(() => rowHeight ? { rowHeight } : { estimatedRowHeight: estimateSize }, [rowHeight, estimateSize]);
3560
+ const virtualise = virtual || bounded;
3561
+ const scrolls = virtualise;
3562
+ const list = /* @__PURE__ */ jsxs(GridList, {
3563
+ "aria-label": label,
3564
+ selectionMode: "none",
3565
+ "data-strata-scroll": "",
3566
+ className: cn("min-w-0 outline-none", scrolls && "overflow-y-auto", className),
3567
+ style: scrolls ? virtual ? { height } : { maxHeight: height } : void 0,
3568
+ children: [/* @__PURE__ */ jsx(Collection, {
3569
+ items: rows,
3570
+ children: (row) => /* @__PURE__ */ jsx(GridListItem, {
3571
+ id: row.id,
3572
+ textValue: row.id,
3573
+ "data-index": row.index,
3574
+ className: cn("min-w-0 outline-offset-[-2px]", row.index > 0 && "border-t border-border"),
3575
+ children: children(row.item, row.index)
3576
+ })
3577
+ }), footer && /* @__PURE__ */ jsx(GridListItem, {
3578
+ id: FOOTER,
3579
+ textValue: "More",
3580
+ className: "min-w-0",
3581
+ children: footer
3582
+ })]
3583
+ });
3584
+ return virtualise ? /* @__PURE__ */ jsx(Virtualizer, {
3585
+ layout: ListLayout,
3586
+ layoutOptions,
3587
+ children: list
3588
+ }) : list;
3661
3589
  }
3662
- /** The point to snap `time` to: the nearest of `points` within `thresholdPx` at this zoom, or `null`. */
3663
- function snapTo(time, points, pxPerUnit, thresholdPx = 8) {
3664
- let best = null;
3665
- for (const p of points) if (Math.abs(p - time) * pxPerUnit <= thresholdPx && (best === null || Math.abs(p - time) < Math.abs(best - time))) best = p;
3666
- return best === null ? null : {
3667
- time: best,
3668
- point: best
3590
+ // src/components/transcript-view.tsx
3591
+ var ALL = "all";
3592
+ var capital = (s) => s.charAt(0).toUpperCase() + s.slice(1);
3593
+ var range = (a, b) => `${format.runningTime(a)}–${format.runningTime(b)}`;
3594
+ /** Timed text that follows playback: the heard word marked, any word or phrase pressed to play from, modes, speakers, follow and Jump to now. */
3595
+ function TranscriptView({ label, groups, time, onSeek, mode: controlledMode, onModeChange, modeLabels = {}, speaker: controlledSpeaker, onSpeakerChange, follow = true, announce = false, renderPlay, height = 480, className }) {
3596
+ const [ownMode, setOwnMode] = React.useState("original");
3597
+ const [ownSpeaker, setOwnSpeaker] = React.useState(ALL);
3598
+ const mode = controlledMode ?? ownMode;
3599
+ const speaker = controlledSpeaker ?? ownSpeaker;
3600
+ const modes = React.useMemo(() => ["original", ...new Set(groups.flatMap((g) => g.phrases.flatMap((p) => Object.keys(p.alt ?? {}))))], [groups]);
3601
+ const speakers = React.useMemo(() => [...new Set(groups.flatMap((g) => g.phrases.map((p) => p.speaker).filter((s) => Boolean(s))))], [groups]);
3602
+ const { rows, phrases } = React.useMemo(() => {
3603
+ const rows = [];
3604
+ const phrases = [];
3605
+ for (const g of groups) {
3606
+ const mine = g.phrases.filter((p) => speaker === ALL || p.speaker === speaker);
3607
+ if (mine.length === 0) continue;
3608
+ rows.push({
3609
+ kind: "heading",
3610
+ key: `group:${g.id}`,
3611
+ group: {
3612
+ ...g,
3613
+ start: g.start ?? mine[0].start,
3614
+ end: g.end ?? mine[mine.length - 1].end
3615
+ }
3616
+ });
3617
+ for (const p of mine) {
3618
+ rows.push({
3619
+ kind: "phrase",
3620
+ key: p.id,
3621
+ phrase: p,
3622
+ index: phrases.length
3623
+ });
3624
+ phrases.push(p);
3625
+ }
3626
+ }
3627
+ return {
3628
+ rows,
3629
+ phrases
3630
+ };
3631
+ }, [groups, speaker]);
3632
+ const heard = phraseAt(phrases, time);
3633
+ const heardPhrase = heard >= 0 ? phrases[heard] : null;
3634
+ const heardWord = heardPhrase ? wordAt(heardPhrase, time) : -1;
3635
+ const heardText = heardPhrase ? mode === "original" ? heardPhrase.words.map((w) => w.text).join(" ") : heardPhrase.alt?.[mode] ?? heardPhrase.words.map((w) => w.text).join(" ") : "";
3636
+ const root = React.useRef(null);
3637
+ const [following, setFollowing] = React.useState(follow);
3638
+ React.useEffect(() => setFollowing(follow), [follow]);
3639
+ const ours = React.useRef(0);
3640
+ const scrollBox = () => root.current?.querySelector("[data-strata-scroll]") ?? null;
3641
+ const scrollToHeard = React.useCallback((id, tries = 0) => {
3642
+ const el = root.current?.querySelector(`[data-phrase="${CSS.escape(id)}"]`);
3643
+ ours.current = Date.now();
3644
+ if (el) {
3645
+ el.scrollIntoView?.({ block: "center" });
3646
+ return;
3647
+ }
3648
+ if (tries > 5) return;
3649
+ const box = scrollBox();
3650
+ const mounted = box ? [...box.querySelectorAll("[data-index]")] : [];
3651
+ if (box && mounted.length > 0 && box.scrollHeight > box.clientHeight) {
3652
+ const avg = mounted.reduce((sum, m) => sum + m.getBoundingClientRect().height, 0) / mounted.length;
3653
+ const index = rows.findIndex((r) => r.key === id);
3654
+ box.scrollTop = Math.max(index * avg - box.clientHeight / 2, 0);
3655
+ }
3656
+ requestAnimationFrame(() => scrollToHeard(id, tries + 1));
3657
+ }, [rows]);
3658
+ const heardId = heardPhrase?.id;
3659
+ React.useEffect(() => {
3660
+ if (following && heardId) scrollToHeard(heardId);
3661
+ }, [
3662
+ heardId,
3663
+ following,
3664
+ scrollToHeard
3665
+ ]);
3666
+ React.useEffect(() => {
3667
+ let intent = 0;
3668
+ const meant = () => void (intent = Date.now());
3669
+ const onScroll = (e) => {
3670
+ const el = root.current;
3671
+ const target = e.target;
3672
+ if (!el || !target || !(target === document || target.contains?.(el) || el.contains(target))) return;
3673
+ if (Date.now() - ours.current < 400 || Date.now() - intent > 1e3) return;
3674
+ setFollowing(false);
3675
+ };
3676
+ const gestures = [
3677
+ "wheel",
3678
+ "touchstart",
3679
+ "touchmove",
3680
+ "keydown",
3681
+ "pointerdown"
3682
+ ];
3683
+ for (const g of gestures) document.addEventListener(g, meant, {
3684
+ capture: true,
3685
+ passive: true
3686
+ });
3687
+ document.addEventListener("scroll", onScroll, true);
3688
+ return () => {
3689
+ for (const g of gestures) document.removeEventListener(g, meant, true);
3690
+ document.removeEventListener("scroll", onScroll, true);
3691
+ };
3692
+ }, []);
3693
+ const [said, setSaid] = React.useState("");
3694
+ React.useEffect(() => {
3695
+ if (announce) setSaid(heardText);
3696
+ }, [
3697
+ announce,
3698
+ heardId,
3699
+ heardText
3700
+ ]);
3701
+ const setMode = (m) => {
3702
+ if (controlledMode === void 0) setOwnMode(m);
3703
+ onModeChange?.(m);
3669
3704
  };
3670
- }
3671
- /** Round away float noise from adding steps (0.1 + 0.2). */
3672
- var tidy = (n) => Math.round(n * 1e6) / 1e6;
3673
- // src/components/timeline.tsx
3674
- var EDGE_PX = 8;
3675
- var DRAG_THRESHOLD = 3;
3676
- var defaultFormat = (t) => tickLabel(t, 1);
3677
- /** Zoom state for a timeline: `zoomIn`, `zoomOut`, and `fit` to a viewport width. Pass `zoom` and `setZoom` as the timeline's `zoom` and `onZoomChange`. */
3678
- function useTimelineZoom({ initial = 20, min = .5, max = 400 } = {}) {
3679
- const [zoom, set] = React.useState(initial);
3680
- const setZoom = React.useCallback((z) => set(clamp$1(z, min, max)), [min, max]);
3681
- return {
3682
- zoom,
3683
- setZoom,
3684
- zoomIn: () => setZoom(zoom * 1.5),
3685
- zoomOut: () => setZoom(zoom / 1.5),
3686
- /** Zoom so `duration` fills `viewportWidth` pixels. */
3687
- fit: (viewportWidth, duration) => setZoom(viewportWidth / Math.max(duration, 1e-6))
3705
+ const setSpeaker = (s) => {
3706
+ if (controlledSpeaker === void 0) setOwnSpeaker(s);
3707
+ onSpeakerChange?.(s);
3688
3708
  };
3689
- }
3690
- /** Zoom in, zoom out and fit, as named icon buttons for a timeline's toolbar. */
3691
- function TimelineZoomControls({ zoom }) {
3709
+ const seek = (t, from) => {
3710
+ setFollowing(follow);
3711
+ onSeek(t, from);
3712
+ };
3713
+ const modeOptions = modes.map((m) => ({
3714
+ value: m,
3715
+ label: m === "original" ? modeLabels.original ?? "Original" : modeLabels[m] ?? capital(m)
3716
+ }));
3717
+ const speakerOptions = [{
3718
+ value: ALL,
3719
+ label: "Everyone"
3720
+ }, ...speakers.map((s) => ({
3721
+ value: s,
3722
+ label: s
3723
+ }))];
3692
3724
  return /* @__PURE__ */ jsxs("div", {
3693
- className: "flex items-center gap-1",
3725
+ ref: root,
3726
+ className: cn("grid min-w-0 gap-3", className),
3694
3727
  children: [
3695
- /* @__PURE__ */ jsx(IconButton, {
3696
- icon: ZoomOut,
3697
- label: "Zoom out",
3698
- hint: "-",
3699
- onClick: zoom.zoomOut
3728
+ (modes.length > 1 || speakers.length > 1) && /* @__PURE__ */ jsxs("div", {
3729
+ className: "flex flex-wrap items-center gap-x-4 gap-y-2",
3730
+ children: [modes.length > 1 && /* @__PURE__ */ jsx(ToggleGroup, {
3731
+ label: `${label}: text`,
3732
+ options: modeOptions,
3733
+ value: mode,
3734
+ onChange: setMode,
3735
+ size: "sm"
3736
+ }), speakers.length > 1 && (speakers.length <= 4 ? /* @__PURE__ */ jsx(ToggleGroup, {
3737
+ label: `${label}: speaker`,
3738
+ options: speakerOptions,
3739
+ value: speaker,
3740
+ onChange: setSpeaker,
3741
+ size: "sm"
3742
+ }) : /* @__PURE__ */ jsx(NativeSelect, {
3743
+ "aria-label": `${label}: speaker`,
3744
+ size: "sm",
3745
+ value: speaker,
3746
+ onChange: (e) => setSpeaker(e.target.value),
3747
+ children: speakerOptions.map((o) => /* @__PURE__ */ jsx("option", {
3748
+ value: o.value,
3749
+ children: o.label
3750
+ }, o.value))
3751
+ }))]
3700
3752
  }),
3701
- /* @__PURE__ */ jsx(IconButton, {
3702
- icon: ZoomIn,
3703
- label: "Zoom in",
3704
- hint: "+",
3705
- onClick: zoom.zoomIn
3753
+ /* @__PURE__ */ jsxs("div", {
3754
+ className: "relative",
3755
+ children: [/* @__PURE__ */ jsx(VirtualList, {
3756
+ label,
3757
+ items: rows,
3758
+ itemKey: (r) => r.key,
3759
+ estimateSize: 72,
3760
+ height,
3761
+ virtualizeFrom: 100,
3762
+ children: (row) => row.kind === "heading" ? /* @__PURE__ */ jsxs("div", {
3763
+ className: "flex items-baseline gap-3 bg-surface-sunken px-3 py-2",
3764
+ children: [/* @__PURE__ */ jsx("h3", {
3765
+ className: "type-label text-foreground",
3766
+ children: row.group.title
3767
+ }), /* @__PURE__ */ jsx("span", {
3768
+ className: "type-caption tabular-nums text-muted-foreground",
3769
+ children: range(row.group.start, row.group.end)
3770
+ })]
3771
+ }) : /* @__PURE__ */ jsx(PhraseRow, {
3772
+ phrase: row.phrase,
3773
+ mode,
3774
+ active: row.index === heard,
3775
+ word: row.index === heard ? heardWord : -1,
3776
+ onSeek: seek,
3777
+ play: renderPlay?.(row.phrase)
3778
+ })
3779
+ }), follow && !following && heardPhrase && /* @__PURE__ */ jsx("div", {
3780
+ className: "pointer-events-none absolute inset-x-0 bottom-2 flex justify-center",
3781
+ children: /* @__PURE__ */ jsx(Button, {
3782
+ className: "pointer-events-auto max-w-full shadow-overlay",
3783
+ onPress: () => setFollowing(true),
3784
+ children: /* @__PURE__ */ jsxs("span", {
3785
+ className: "truncate",
3786
+ children: ["Jump to now: ", heardText]
3787
+ })
3788
+ })
3789
+ })]
3706
3790
  }),
3707
- /* @__PURE__ */ jsx(IconButton, {
3708
- icon: Maximize2,
3709
- label: "Fit to view",
3710
- hint: "0",
3711
- onClick: zoom.fit
3712
- })
3791
+ /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx("span", {
3792
+ role: "status",
3793
+ children: said
3794
+ }) })
3713
3795
  ]
3714
3796
  });
3715
3797
  }
3716
- /** A rule that refuses an item overlapping another in its lane, for `validate`: names the item in the way. */
3717
- function noOverlap(items) {
3718
- return (id, next) => {
3719
- const me = items.find((i) => i.id === id);
3720
- const other = items.find((i) => i.id !== id && i.lane === next.lane && i.start < next.start + next.length - 1e-9 && next.start < i.start + i.length - 1e-9);
3721
- return other ? `${me?.label ?? "This"} would overlap ${other.label}.` : null;
3798
+ function PhraseRow({ phrase, mode, active, word, onSeek, play }) {
3799
+ const alt = mode === "original" ? null : phrase.alt?.[mode] ?? null;
3800
+ return /* @__PURE__ */ jsxs("div", {
3801
+ "data-phrase": phrase.id,
3802
+ "data-active": active ? "" : void 0,
3803
+ "aria-current": active ? "true" : void 0,
3804
+ className: cn("flex items-start gap-2 border-l-2 border-transparent px-3 py-2", active && "border-primary bg-accent"),
3805
+ children: [play, /* @__PURE__ */ jsxs("div", {
3806
+ className: "min-w-0 flex-1",
3807
+ children: [/* @__PURE__ */ jsxs("div", {
3808
+ className: "flex items-baseline gap-2",
3809
+ children: [phrase.speaker && /* @__PURE__ */ jsx("span", {
3810
+ className: "type-label text-muted-foreground",
3811
+ children: phrase.speaker
3812
+ }), /* @__PURE__ */ jsx(Button$1, {
3813
+ onPress: () => onSeek(phrase.start, { phraseId: phrase.id }),
3814
+ className: "rounded-control type-caption tabular-nums text-muted-foreground hover:text-foreground",
3815
+ "aria-label": `Play from ${format.runningTime(phrase.start)}`,
3816
+ children: format.runningTime(phrase.start)
3817
+ })]
3818
+ }), alt !== null ? /* @__PURE__ */ jsx(Button$1, {
3819
+ onPress: () => onSeek(phrase.start, { phraseId: phrase.id }),
3820
+ className: cn("rounded-control text-left type-body", active && "font-medium underline decoration-2 underline-offset-4"),
3821
+ children: alt
3822
+ }) : /* @__PURE__ */ jsx("p", {
3823
+ className: "type-body",
3824
+ children: phrase.words.map((w, i) => /* @__PURE__ */ jsxs(React.Fragment, { children: [i > 0 && " ", /* @__PURE__ */ jsx(Button$1, {
3825
+ "aria-current": i === word ? "true" : void 0,
3826
+ onPress: () => onSeek(w.start, {
3827
+ phraseId: phrase.id,
3828
+ wordIndex: i
3829
+ }),
3830
+ className: cn("rounded-control hover:bg-muted", i === word && "font-medium underline decoration-2 underline-offset-4"),
3831
+ children: w.text
3832
+ })] }, i))
3833
+ })]
3834
+ })]
3835
+ });
3836
+ }
3837
+ // src/lib/waveform.ts
3838
+ var isPair = (p) => typeof p.min === "object";
3839
+ /** Makes the lowest and highest sample of each slice from either form. A magnitude `m` is the pair `-m` to `m`. */
3840
+ function toPeakPair(peaks) {
3841
+ if (isPair(peaks)) {
3842
+ const n = Math.min(peaks.min.length, peaks.max.length);
3843
+ const min = new Float32Array(n);
3844
+ const max = new Float32Array(n);
3845
+ for (let i = 0; i < n; i++) {
3846
+ min[i] = Math.min(peaks.min[i], peaks.max[i]);
3847
+ max[i] = Math.max(peaks.min[i], peaks.max[i]);
3848
+ }
3849
+ return {
3850
+ min,
3851
+ max
3852
+ };
3853
+ }
3854
+ const n = peaks.length;
3855
+ const min = new Float32Array(n);
3856
+ const max = new Float32Array(n);
3857
+ for (let i = 0; i < n; i++) {
3858
+ const m = Math.abs(peaks[i]);
3859
+ min[i] = -m;
3860
+ max[i] = m;
3861
+ }
3862
+ return {
3863
+ min,
3864
+ max
3722
3865
  };
3723
3866
  }
3724
- /** Items placed on a zoomable time axis in lanes, with a current-time rule and markers. Reports every move, trim, selection and time change; the app applies them. Keyboard-complete, and only the items near the view are rendered. */
3725
- function Timeline({ label, lanes, items, from = 0, to, zoom, onZoomChange, position, onPositionChange, follow, markers = [], selectedIds, onSelect, onItemChange, onDelete, validate, snapPoints = [], snap = true, step = 1, minLength, renderItem, kindColours, laneRows = 1, dropTypes, dropLength, onDrop, validateDrop, formatTime = defaultFormat, empty, className }) {
3726
- const min = minLength ?? step;
3727
- const scroller = React.useRef(null);
3728
- const laneRefs = React.useRef(/* @__PURE__ */ new Map());
3729
- const [view, setView] = React.useState({
3730
- left: 0,
3731
- width: 640
3867
+ /** The lowest and highest of `pair` over the fraction `from` to `to` of its length (0 to 1). A slice narrower than one entry takes the entry it falls in, so zooming past the data never leaves a gap. */
3868
+ function peaksBetween(pair, from, to) {
3869
+ const n = pair.min.length;
3870
+ if (n === 0) return [0, 0];
3871
+ const a = Math.min(Math.max(from, 0), 1) * n;
3872
+ const b = Math.min(Math.max(to, 0), 1) * n;
3873
+ const first = Math.min(Math.floor(a), n - 1);
3874
+ const last = Math.min(Math.max(Math.ceil(b) - 1, first), n - 1);
3875
+ let lo = Infinity;
3876
+ let hi = -Infinity;
3877
+ for (let i = first; i <= last; i++) {
3878
+ if (pair.min[i] < lo) lo = pair.min[i];
3879
+ if (pair.max[i] > hi) hi = pair.max[i];
3880
+ }
3881
+ return [lo, hi];
3882
+ }
3883
+ /** Resamples peaks to `buckets` entries: each is the lowest and highest of the entries it covers. Any length in, any length out. */
3884
+ function resamplePeaks(peaks, buckets) {
3885
+ const pair = toPeakPair(peaks);
3886
+ const count = Math.max(Math.floor(buckets), 0);
3887
+ const min = new Float32Array(count);
3888
+ const max = new Float32Array(count);
3889
+ for (let i = 0; i < count; i++) [min[i], max[i]] = peaksBetween(pair, i / count, (i + 1) / count);
3890
+ return {
3891
+ min,
3892
+ max
3893
+ };
3894
+ }
3895
+ /**
3896
+ * Reduces decoded audio to `buckets` peaks over all channels, in chunks, calling `progress` with
3897
+ * the buckets done and awaiting between chunks so the page stays responsive and `signal` can stop it.
3898
+ */
3899
+ async function peaksFromAudio(audio, buckets, options = {}) {
3900
+ const { signal, progress, chunk = 256 } = options;
3901
+ const min = new Float32Array(buckets);
3902
+ const max = new Float32Array(buckets);
3903
+ const channels = Array.from({ length: audio.numberOfChannels }, (_, c) => audio.getChannelData(c));
3904
+ const size = audio.length / buckets;
3905
+ for (let i = 0; i < buckets; i++) {
3906
+ const from = Math.floor(i * size);
3907
+ const to = Math.max(Math.floor((i + 1) * size), from + 1);
3908
+ let lo = Infinity;
3909
+ let hi = -Infinity;
3910
+ for (const data of channels) for (let j = from; j < to && j < data.length; j++) {
3911
+ const v = data[j];
3912
+ if (v < lo) lo = v;
3913
+ if (v > hi) hi = v;
3914
+ }
3915
+ min[i] = Number.isFinite(lo) ? lo : 0;
3916
+ max[i] = Number.isFinite(hi) ? hi : 0;
3917
+ if ((i + 1) % chunk === 0 || i === buckets - 1) {
3918
+ progress?.(i + 1, buckets);
3919
+ if (signal?.aborted) throw new DOMException("The waveform was cancelled.", "AbortError");
3920
+ await new Promise((resolve) => setTimeout(resolve, 0));
3921
+ }
3922
+ }
3923
+ return {
3924
+ min,
3925
+ max
3926
+ };
3927
+ }
3928
+ /** The time at the pointer, given the visible range and the width. */
3929
+ var timeAt = (px, width, from, to) => from + Math.min(Math.max(px, 0), width) / (width || 1) * (to - from);
3930
+ /** Keeps a visible range of `span` seconds inside `0` to `duration`. */
3931
+ function clampView(from, span, duration) {
3932
+ const s = Math.min(Math.max(span, Math.min(duration, .05)), duration);
3933
+ const a = Math.min(Math.max(from, 0), Math.max(duration - s, 0));
3934
+ return [a, a + s];
3935
+ }
3936
+ // src/components/waveform.tsx
3937
+ var TONE$2 = {
3938
+ neutral: {
3939
+ fill: "var(--muted)",
3940
+ edge: "var(--muted-foreground)"
3941
+ },
3942
+ info: {
3943
+ fill: "var(--info-subtle)",
3944
+ edge: "var(--info)"
3945
+ },
3946
+ success: {
3947
+ fill: "var(--success-subtle)",
3948
+ edge: "var(--success)"
3949
+ },
3950
+ warning: {
3951
+ fill: "var(--warning-subtle)",
3952
+ edge: "var(--warning)"
3953
+ },
3954
+ danger: {
3955
+ fill: "var(--danger-subtle)",
3956
+ edge: "var(--danger)"
3957
+ }
3958
+ };
3959
+ var MARK_LINE = {
3960
+ beat: {
3961
+ width: 1,
3962
+ opacity: .16
3963
+ },
3964
+ bar: {
3965
+ width: 1.5,
3966
+ opacity: .55
3967
+ },
3968
+ downbeat: {
3969
+ width: 2.5,
3970
+ opacity: 1
3971
+ },
3972
+ chapter: {
3973
+ width: 1.5,
3974
+ opacity: .9,
3975
+ dash: "4 3"
3976
+ }
3977
+ };
3978
+ var WORDS = {
3979
+ running: "Reading the waveform",
3980
+ finished: "Waveform ready",
3981
+ failed: "Could not read the waveform"
3982
+ };
3983
+ async function defaultDecode(data) {
3984
+ const Context = typeof AudioContext !== "undefined" ? AudioContext : globalThis.webkitAudioContext;
3985
+ if (!Context) throw new Error("This browser cannot decode audio.");
3986
+ const ctx = new Context();
3987
+ try {
3988
+ return await ctx.decodeAudioData(data);
3989
+ } finally {
3990
+ ctx.close?.();
3991
+ }
3992
+ }
3993
+ var clamp$2 = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
3994
+ var clock = (t) => format.runningTime(t);
3995
+ /** An audio waveform with marks, spans and a playhead: one slider you click, drag or key to seek, zoom, and a range to select. */
3996
+ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks = [], spans = [], underlay, range: controlledRange, onRangeChange, step = 5, bigStep = 30, defaultView, buckets = 2e3, decode = defaultDecode, words = WORDS, disabled, className }) {
3997
+ const work = useClientWork(async ({ signal, progress }) => {
3998
+ const data = typeof source === "string" ? await (await fetch(source, { signal })).arrayBuffer() : await source.arrayBuffer();
3999
+ progress(0, buckets + 2);
4000
+ const audio = await decode(data);
4001
+ if (signal.aborted) throw new DOMException("The waveform was cancelled.", "AbortError");
4002
+ progress(1, buckets + 2);
4003
+ return {
4004
+ pair: await peaksFromAudio(audio, buckets, {
4005
+ signal,
4006
+ progress: (done) => progress(done + 1, buckets + 2)
4007
+ }),
4008
+ duration: audio.duration
4009
+ };
3732
4010
  });
4011
+ const startWork = work.start;
4012
+ const cancelWork = work.cancel;
4013
+ React.useEffect(() => {
4014
+ if (source === void 0) return;
4015
+ startWork();
4016
+ return cancelWork;
4017
+ }, [
4018
+ source,
4019
+ startWork,
4020
+ cancelWork
4021
+ ]);
4022
+ const pair = React.useMemo(() => peaks === void 0 ? null : toPeakPair(peaks), [peaks]) ?? (work.phase === "finished" ? work.result.pair : null);
4023
+ const duration = given ?? (work.phase === "finished" ? work.result.duration : 0);
4024
+ const ready = pair !== null && duration > 0;
4025
+ const [view, setView] = React.useState(defaultView ? [defaultView[0], defaultView[1]] : null);
4026
+ const [v0, v1] = view ? clampView(view[0], view[1] - view[0], duration || 1) : [0, duration];
4027
+ const zoomed = ready && v1 - v0 < duration - 1e-6;
4028
+ const span = Math.max(v1 - v0, 1e-6);
4029
+ const zoomBy = (factor, about) => {
4030
+ const centre = about ?? (time >= v0 && time <= v1 ? time : (v0 + v1) / 2);
4031
+ const next = clamp$2(span * factor, Math.min(duration, .5), duration);
4032
+ const from = centre - (centre - v0) / span * next;
4033
+ setView(next >= duration - 1e-6 ? null : clampView(from, next, duration));
4034
+ };
4035
+ const lastPan = React.useRef(0);
4036
+ React.useEffect(() => {
4037
+ if (!zoomed || time >= v0 && time <= v1 || Date.now() - lastPan.current < 3e3) return;
4038
+ setView(clampView(time - span * .2, span, duration));
4039
+ }, [time]);
4040
+ const [ownRange, setOwnRange] = React.useState(null);
4041
+ const range = controlledRange === void 0 ? ownRange : controlledRange;
4042
+ const setRange = (next) => {
4043
+ if (controlledRange === void 0) setOwnRange(next);
4044
+ onRangeChange?.(next);
4045
+ };
3733
4046
  const [drag, setDrag] = React.useState(null);
3734
- const dragRef = React.useRef(null);
3735
- const [focusId, setFocusId] = React.useState(null);
4047
+ const shown = drag ?? range;
3736
4048
  const [said, setSaid] = React.useState("");
3737
- const [hover, setHover] = React.useState(null);
3738
- const refocus = React.useRef(null);
3739
- const selected = selectedIds ?? /* @__PURE__ */ new Set();
3740
- const laneIndex = React.useMemo(() => new Map(lanes.map((l, i) => [l.id, i])), [lanes]);
3741
- const laneLabel = (id) => lanes.find((l) => l.id === id)?.label ?? id;
3742
- const width = Math.max((to - from) * zoom, 1);
3743
- const x = (t) => (t - from) * zoom;
3744
- React.useEffect(() => {
3745
- const el = scroller.current;
4049
+ const box = React.useRef(null);
4050
+ const [width, setWidth] = React.useState(0);
4051
+ React.useLayoutEffect(() => {
4052
+ const el = box.current;
3746
4053
  if (!el) return;
3747
- const read = () => setView({
3748
- left: el.scrollLeft,
3749
- width: el.clientWidth || 640
3750
- });
4054
+ const read = () => setWidth(Math.round(el.getBoundingClientRect().width));
3751
4055
  read();
4056
+ if (typeof ResizeObserver === "undefined") return;
3752
4057
  const ro = new ResizeObserver(read);
3753
4058
  ro.observe(el);
3754
- el.addEventListener("scroll", read, { passive: true });
3755
- return () => {
3756
- ro.disconnect();
3757
- el.removeEventListener("scroll", read);
3758
- };
4059
+ return () => ro.disconnect();
3759
4060
  }, []);
4061
+ const gesture = React.useRef({
4062
+ zoomed,
4063
+ v0,
4064
+ span,
4065
+ duration,
4066
+ zoomBy
4067
+ });
4068
+ gesture.current = {
4069
+ zoomed,
4070
+ v0,
4071
+ span,
4072
+ duration,
4073
+ zoomBy
4074
+ };
3760
4075
  React.useEffect(() => {
3761
- const el = scroller.current;
3762
- if (!follow || position === void 0 || !el) return;
3763
- const px = x(position);
3764
- if (px < el.scrollLeft || px > el.scrollLeft + el.clientWidth - 24) el.scrollLeft = Math.max(px - el.clientWidth * .25, 0);
4076
+ const el = box.current;
4077
+ if (!el) return;
4078
+ const onWheel = (e) => {
4079
+ const g = gesture.current;
4080
+ const rect = el.getBoundingClientRect();
4081
+ if (e.ctrlKey || e.metaKey) {
4082
+ e.preventDefault();
4083
+ lastPan.current = Date.now();
4084
+ g.zoomBy(e.deltaY < 0 ? .8 : 1.25, timeAt(e.clientX - rect.left, rect.width, g.v0, g.v0 + g.span));
4085
+ } else if (g.zoomed && Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
4086
+ e.preventDefault();
4087
+ lastPan.current = Date.now();
4088
+ setView(clampView(g.v0 + e.deltaX / (rect.width || 1) * g.span, g.span, g.duration));
4089
+ }
4090
+ };
4091
+ el.addEventListener("wheel", onWheel, { passive: false });
4092
+ return () => el.removeEventListener("wheel", onWheel);
4093
+ }, []);
4094
+ const track = React.useRef(null);
4095
+ const input = React.useRef(null);
4096
+ const off = disabled || !ready;
4097
+ const timeText = React.useMemo(() => ({
4098
+ format: clock,
4099
+ formatRange: (a, b) => `${clock(a)} to ${clock(b)}`,
4100
+ resolvedOptions: () => ({ locale: "en-US" })
4101
+ }), []);
4102
+ const state = useSliderState({
4103
+ minValue: v0,
4104
+ maxValue: Math.max(v1, v0 + .01),
4105
+ step: .01,
4106
+ value: [clamp$2(time, v0, Math.max(v1, v0 + .01))],
4107
+ onChange: ([t]) => onSeek(clamp$2(t, 0, duration)),
4108
+ numberFormatter: timeText,
4109
+ isDisabled: off
4110
+ });
4111
+ const { groupProps, trackProps } = useSlider({
4112
+ "aria-label": label,
4113
+ isDisabled: off
4114
+ }, state, track);
4115
+ const { thumbProps, inputProps } = useSliderThumb({
4116
+ index: 0,
4117
+ trackRef: track,
4118
+ inputRef: input,
4119
+ "aria-label": label,
4120
+ isDisabled: off
4121
+ }, state);
4122
+ const { focusProps, isFocusVisible } = useFocusRing();
4123
+ const seekTo = (t) => onSeek(clamp$2(t, 0, duration));
4124
+ const onKeyDownCapture = (e) => {
4125
+ if (off) return;
4126
+ const big = e.shiftKey ? bigStep : step;
4127
+ const moves = {
4128
+ ArrowLeft: -big,
4129
+ ArrowDown: -big,
4130
+ ArrowRight: big,
4131
+ ArrowUp: big,
4132
+ PageDown: -bigStep,
4133
+ PageUp: bigStep
4134
+ };
4135
+ if (e.key in moves) seekTo(time + moves[e.key]);
4136
+ else if (e.key === "Home") seekTo(0);
4137
+ else if (e.key === "End") seekTo(duration);
4138
+ else if (e.key === "+" || e.key === "=") {
4139
+ zoomBy(.5);
4140
+ setSaid("Zoomed in");
4141
+ } else if (e.key === "-" || e.key === "_") {
4142
+ zoomBy(2);
4143
+ setSaid("Zoomed out");
4144
+ } else if (e.key === "0") {
4145
+ setView(null);
4146
+ setSaid("Showing the whole file");
4147
+ } else if (e.key === "[") {
4148
+ const to = range ? Math.max(range[1], time) : duration;
4149
+ setRange([time, to]);
4150
+ setSaid(`Range starts at ${clock(time)}`);
4151
+ } else if (e.key === "]") {
4152
+ const from = range ? Math.min(range[0], time) : 0;
4153
+ setRange([from, time]);
4154
+ setSaid(`Range ends at ${clock(time)}`);
4155
+ } else if (e.key === "Escape" && range) {
4156
+ setRange(null);
4157
+ setSaid("Range cleared");
4158
+ } else return;
4159
+ e.preventDefault();
4160
+ e.stopPropagation();
4161
+ };
4162
+ const startRange = (e) => {
4163
+ if (!e.shiftKey || off) return;
4164
+ e.stopPropagation();
4165
+ e.preventDefault();
4166
+ const el = e.currentTarget;
4167
+ const rect = el.getBoundingClientRect();
4168
+ const at = (x) => timeAt(x - rect.left, rect.width, v0, v1);
4169
+ const from = at(e.clientX);
4170
+ setDrag([from, from]);
4171
+ el.setPointerCapture?.(e.pointerId);
4172
+ const move = (m) => setDrag([Math.min(from, at(m.clientX)), Math.max(from, at(m.clientX))]);
4173
+ const up = (u) => {
4174
+ el.removeEventListener("pointermove", move);
4175
+ el.removeEventListener("pointerup", up);
4176
+ el.removeEventListener("pointercancel", up);
4177
+ const a = Math.min(from, at(u.clientX));
4178
+ const b = Math.max(from, at(u.clientX));
4179
+ setDrag(null);
4180
+ if (b - a > .05) {
4181
+ setRange([a, b]);
4182
+ setSaid(`Range ${clock(a)} to ${clock(b)}`);
4183
+ }
4184
+ };
4185
+ el.addEventListener("pointermove", move);
4186
+ el.addEventListener("pointerup", up);
4187
+ el.addEventListener("pointercancel", up);
4188
+ };
4189
+ const column = 2;
4190
+ const bars = React.useMemo(() => {
4191
+ if (!pair || width === 0 || duration <= 0) return "";
4192
+ let d = "";
4193
+ for (let x = 0; x < width; x += column) {
4194
+ const [lo, hi] = peaksBetween(pair, (v0 + x / width * (v1 - v0)) / duration, (v0 + (x + column) / width * (v1 - v0)) / duration);
4195
+ if (!Number.isFinite(lo)) continue;
4196
+ const top = 50 - clamp$2(hi, -1, 1) * 48;
4197
+ const bottom = 50 - clamp$2(lo, -1, 1) * 48;
4198
+ d += `M${x + .5} ${top.toFixed(1)}V${Math.max(bottom, top + 1).toFixed(1)}`;
4199
+ }
4200
+ return d;
3765
4201
  }, [
3766
- follow,
3767
- position,
3768
- zoom
4202
+ pair,
4203
+ width,
4204
+ v0,
4205
+ v1,
4206
+ duration
3769
4207
  ]);
3770
- React.useEffect(() => {
3771
- const id = refocus.current;
3772
- if (!id) return;
3773
- refocus.current = null;
3774
- const el = scroller.current?.querySelector(`[data-item="${CSS.escape(id)}"]`);
3775
- if (el && document.activeElement !== el && (!document.activeElement || document.activeElement === document.body || !scroller.current?.contains(document.activeElement))) el.focus();
3776
- }, [items]);
3777
- const sorted = React.useMemo(() => {
3778
- const byLane = /* @__PURE__ */ new Map();
3779
- for (const l of lanes) byLane.set(l.id, []);
3780
- for (const i of items) byLane.get(i.lane)?.push(i);
3781
- for (const list of byLane.values()) list.sort((a, b) => a.start - b.start);
3782
- return byLane;
3783
- }, [lanes, items]);
3784
- const snapTimes = React.useMemo(() => {
4208
+ const clipId = React.useId();
4209
+ const px = (t) => (t - v0) / span * width;
4210
+ const visibleMarks = marks.filter((m) => m.time >= v0 && m.time <= v1);
4211
+ const thin = visibleMarks.length > width / 8;
4212
+ const listedMarks = marks.filter((m) => m.label && (m.listed ?? m.kind !== "beat"));
4213
+ const counts = marks.reduce((c, m) => (c[m.kind ?? "mark"] = (c[m.kind ?? "mark"] ?? 0) + 1, c), {});
4214
+ const summary = ready ? `${clock(duration)} long${Object.keys(counts).length ? `, ${Object.entries(counts).map(([k, n]) => `${n} ${k}${n === 1 ? "" : "s"}`).join(", ")}` : ""}${spans.length ? `, ${spans.length} span${spans.length === 1 ? "" : "s"}` : ""}${zoomed ? `, showing ${clock(v0)} to ${clock(v1)}` : ""}${range ? `, range ${clock(range[0])} to ${clock(range[1])}` : ""}` : "";
4215
+ const summaryId = React.useId();
4216
+ return /* @__PURE__ */ jsxs("div", {
4217
+ role: "group",
4218
+ "aria-label": label,
4219
+ className: cn("grid min-w-0 gap-2", className),
4220
+ children: [
4221
+ source !== void 0 && work.phase !== "finished" && work.phase !== "idle" && /* @__PURE__ */ jsx(JobStatus, {
4222
+ label: `${label}: reading`,
4223
+ running: work.phase === "running",
4224
+ words,
4225
+ summary: work.phase === "failed" ? work.error instanceof Error ? work.error.message : "The file could not be read." : work.phase === "cancelled" ? "Stopped." : "Reducing the sound to a picture.",
4226
+ current: work.current,
4227
+ total: work.total,
4228
+ failed: work.phase === "failed",
4229
+ cancelled: work.phase === "cancelled",
4230
+ onCancel: work.cancel
4231
+ }),
4232
+ source !== void 0 && (work.phase === "failed" || work.phase === "cancelled") && /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, {
4233
+ size: "sm",
4234
+ onPress: () => void work.start(),
4235
+ children: "Try again"
4236
+ }) }),
4237
+ /* @__PURE__ */ jsxs("div", {
4238
+ ref: box,
4239
+ className: cn("relative w-full overflow-hidden rounded-surface border border-border bg-surface-sunken", off && "opacity-60"),
4240
+ style: { height: "calc(var(--control-h) * 2.5)" },
4241
+ onPointerDownCapture: startRange,
4242
+ onMouseDownCapture: (e) => e.shiftKey && e.stopPropagation(),
4243
+ children: [
4244
+ underlay && ready && /* @__PURE__ */ jsx("div", {
4245
+ "aria-hidden": true,
4246
+ className: "absolute inset-y-0 [&>*]:size-full [&>img]:object-fill",
4247
+ style: {
4248
+ left: `${-v0 / span * 100}%`,
4249
+ width: `${duration / span * 100}%`
4250
+ },
4251
+ children: underlay
4252
+ }),
4253
+ ready && width > 0 && /* @__PURE__ */ jsxs("svg", {
4254
+ "aria-hidden": true,
4255
+ className: "absolute inset-0 size-full",
4256
+ viewBox: `0 0 ${width} 100`,
4257
+ preserveAspectRatio: "none",
4258
+ children: [
4259
+ /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("clipPath", {
4260
+ id: clipId,
4261
+ children: /* @__PURE__ */ jsx("rect", {
4262
+ x: 0,
4263
+ y: 0,
4264
+ width: Math.max(0, Math.min(px(time), width)),
4265
+ height: 100
4266
+ })
4267
+ }) }),
4268
+ spans.map((s) => {
4269
+ const a = clamp$2(px(s.from), 0, width);
4270
+ const b = clamp$2(px(s.to), 0, width);
4271
+ const tone = TONE$2[s.tone ?? "neutral"];
4272
+ return b > a ? /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("rect", {
4273
+ x: a,
4274
+ y: 0,
4275
+ width: b - a,
4276
+ height: 100,
4277
+ fill: tone.fill,
4278
+ opacity: .7
4279
+ }), /* @__PURE__ */ jsx("rect", {
4280
+ x: a,
4281
+ y: 0,
4282
+ width: b - a,
4283
+ height: 4,
4284
+ fill: tone.edge
4285
+ })] }, `${s.from}-${s.to}-${s.label}`) : null;
4286
+ }),
4287
+ shown && /* @__PURE__ */ jsx("rect", {
4288
+ x: clamp$2(px(shown[0]), 0, width),
4289
+ y: 0,
4290
+ width: Math.max(clamp$2(px(shown[1]), 0, width) - clamp$2(px(shown[0]), 0, width), 1),
4291
+ height: 100,
4292
+ fill: "var(--primary-5)",
4293
+ opacity: .45
4294
+ }),
4295
+ /* @__PURE__ */ jsx("path", {
4296
+ d: bars,
4297
+ stroke: "var(--muted-foreground)",
4298
+ strokeWidth: 1.5,
4299
+ vectorEffect: "non-scaling-stroke",
4300
+ fill: "none"
4301
+ }),
4302
+ /* @__PURE__ */ jsx("path", {
4303
+ d: bars,
4304
+ stroke: "var(--primary)",
4305
+ strokeWidth: 1.5,
4306
+ vectorEffect: "non-scaling-stroke",
4307
+ fill: "none",
4308
+ clipPath: `url(#${clipId})`
4309
+ }),
4310
+ visibleMarks.map((m) => {
4311
+ const kind = m.kind ?? "bar";
4312
+ if (thin && kind === "beat") return null;
4313
+ const line = MARK_LINE[kind];
4314
+ return /* @__PURE__ */ jsx("line", {
4315
+ x1: px(m.time),
4316
+ x2: px(m.time),
4317
+ y1: 0,
4318
+ y2: 100,
4319
+ stroke: "var(--foreground)",
4320
+ strokeWidth: line.width,
4321
+ strokeDasharray: line.dash,
4322
+ opacity: line.opacity,
4323
+ vectorEffect: "non-scaling-stroke"
4324
+ }, `${m.time}-${kind}`);
4325
+ }),
4326
+ shown && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("line", {
4327
+ x1: px(shown[0]),
4328
+ x2: px(shown[0]),
4329
+ y1: 0,
4330
+ y2: 100,
4331
+ stroke: "var(--primary)",
4332
+ strokeWidth: 2,
4333
+ vectorEffect: "non-scaling-stroke"
4334
+ }), /* @__PURE__ */ jsx("line", {
4335
+ x1: px(shown[1]),
4336
+ x2: px(shown[1]),
4337
+ y1: 0,
4338
+ y2: 100,
4339
+ stroke: "var(--primary)",
4340
+ strokeWidth: 2,
4341
+ vectorEffect: "non-scaling-stroke"
4342
+ })] }),
4343
+ time >= v0 && time <= v1 && /* @__PURE__ */ jsx("line", {
4344
+ x1: px(time),
4345
+ x2: px(time),
4346
+ y1: 0,
4347
+ y2: 100,
4348
+ stroke: "var(--primary)",
4349
+ strokeWidth: 2,
4350
+ vectorEffect: "non-scaling-stroke"
4351
+ })
4352
+ ]
4353
+ }),
4354
+ /* @__PURE__ */ jsx("div", {
4355
+ ...groupProps,
4356
+ className: "absolute inset-0",
4357
+ children: /* @__PURE__ */ jsx("div", {
4358
+ ...trackProps,
4359
+ ref: track,
4360
+ className: cn("relative size-full touch-none", off ? "cursor-not-allowed" : "cursor-pointer", isFocusVisible && "outline-2 -outline-offset-2 outline-ring"),
4361
+ children: /* @__PURE__ */ jsx("div", {
4362
+ ...thumbProps,
4363
+ className: "absolute inset-y-0 w-0",
4364
+ style: { left: `${clamp$2((time - v0) / span, 0, 1) * 100}%` },
4365
+ children: /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx("input", {
4366
+ ref: input,
4367
+ ...mergeProps(inputProps, focusProps, { "aria-describedby": summaryId }),
4368
+ "aria-labelledby": void 0,
4369
+ onKeyDownCapture
4370
+ }) })
4371
+ })
4372
+ })
4373
+ })
4374
+ ]
4375
+ }),
4376
+ /* @__PURE__ */ jsxs(VisuallyHidden, { children: [
4377
+ /* @__PURE__ */ jsx("p", {
4378
+ id: summaryId,
4379
+ children: summary
4380
+ }),
4381
+ /* @__PURE__ */ jsx("span", {
4382
+ role: "status",
4383
+ children: said
4384
+ }),
4385
+ spans.length > 0 && /* @__PURE__ */ jsx("ul", {
4386
+ "aria-label": "Spans",
4387
+ children: spans.map((s) => /* @__PURE__ */ jsxs("li", { children: [
4388
+ s.label,
4389
+ ": ",
4390
+ clock(s.from),
4391
+ " to ",
4392
+ clock(s.to)
4393
+ ] }, `${s.from}-${s.to}-${s.label}`))
4394
+ }),
4395
+ listedMarks.length > 0 && /* @__PURE__ */ jsx("ul", {
4396
+ "aria-label": "Marks",
4397
+ children: listedMarks.map((m) => /* @__PURE__ */ jsxs("li", { children: [
4398
+ m.label,
4399
+ ", ",
4400
+ clock(m.time)
4401
+ ] }, `${m.time}-${m.label}`))
4402
+ })
4403
+ ] }),
4404
+ spans.length > 0 && ready && /* @__PURE__ */ jsx("ul", {
4405
+ "aria-hidden": true,
4406
+ className: "flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground",
4407
+ children: [...new Map(spans.map((s) => [`${s.tone ?? "neutral"}:${s.label}`, s])).values()].map((s) => /* @__PURE__ */ jsxs("li", {
4408
+ className: "inline-flex items-center gap-1.5",
4409
+ children: [/* @__PURE__ */ jsx("span", {
4410
+ className: "h-2 w-3.5 rounded-sm border border-border",
4411
+ style: {
4412
+ background: TONE$2[s.tone ?? "neutral"].fill,
4413
+ borderTopColor: TONE$2[s.tone ?? "neutral"].edge,
4414
+ borderTopWidth: 3
4415
+ }
4416
+ }), s.label]
4417
+ }, `${s.tone}${s.label}`))
4418
+ })
4419
+ ]
4420
+ });
4421
+ }
4422
+ // src/lib/timeline.ts
4423
+ /** Steps a person would write on a scale, in seconds: 1, 2, 5 and 10 × 10ⁿ below a minute, then 15 s, 30 s, minutes, quarter hours, hours, days. ux-research components.md §3.8: ticks land on values people would write. */
4424
+ var STEPS = [
4425
+ .01,
4426
+ .02,
4427
+ .05,
4428
+ .1,
4429
+ .2,
4430
+ .5,
4431
+ 1,
4432
+ 2,
4433
+ 5,
4434
+ 10,
4435
+ 15,
4436
+ 30,
4437
+ 60,
4438
+ 120,
4439
+ 300,
4440
+ 600,
4441
+ 900,
4442
+ 1800,
4443
+ 3600,
4444
+ 7200,
4445
+ 14400,
4446
+ 21600,
4447
+ 43200,
4448
+ 86400
4449
+ ];
4450
+ /** The smallest step whose ticks are at least `minGapPx` apart at this zoom, so labels thin out instead of colliding. */
4451
+ function tickStep(pxPerUnit, minGapPx = 80) {
4452
+ return STEPS.find((s) => s * pxPerUnit >= minGapPx) ?? STEPS[STEPS.length - 1];
4453
+ }
4454
+ /** Tick times from `from` to `to` inclusive, on multiples of `step`. */
4455
+ function ticksBetween(from, to, step) {
4456
+ const out = [];
4457
+ const first = Math.ceil(from / step - 1e-9);
4458
+ for (let i = first; i * step <= to + 1e-9; i++) out.push(Math.round(i * step * 1e6) / 1e6 || 0);
4459
+ return out;
4460
+ }
4461
+ /** A tick's label: m:ss, h:mm:ss, with tenths or hundredths when the step is under a second. */
4462
+ function tickLabel(time, step) {
4463
+ const decimals = step < .1 ? 2 : step < 1 ? 1 : 0;
4464
+ const whole = Math.floor(time + 1e-9);
4465
+ const h = Math.floor(whole / 3600);
4466
+ const m = Math.floor(whole % 3600 / 60);
4467
+ const s = whole % 60;
4468
+ const two = (n) => String(n).padStart(2, "0");
4469
+ const base = h > 0 ? `${h}:${two(m)}:${two(s)}` : `${m}:${two(s)}`;
4470
+ return decimals ? `${base}.${String(Math.round((time - whole) * 10 ** decimals)).padStart(decimals, "0")}` : base;
4471
+ }
4472
+ function clamp$1(value, min, max) {
4473
+ return Math.min(Math.max(value, min), max);
4474
+ }
4475
+ /** The point to snap `time` to: the nearest of `points` within `thresholdPx` at this zoom, or `null`. */
4476
+ function snapTo(time, points, pxPerUnit, thresholdPx = 8) {
4477
+ let best = null;
4478
+ for (const p of points) if (Math.abs(p - time) * pxPerUnit <= thresholdPx && (best === null || Math.abs(p - time) < Math.abs(best - time))) best = p;
4479
+ return best === null ? null : {
4480
+ time: best,
4481
+ point: best
4482
+ };
4483
+ }
4484
+ /** Round away float noise from adding steps (0.1 + 0.2). */
4485
+ var tidy = (n) => Math.round(n * 1e6) / 1e6;
4486
+ // src/components/timeline.tsx
4487
+ var EDGE_PX = 8;
4488
+ var DRAG_THRESHOLD = 3;
4489
+ var defaultFormat = (t) => tickLabel(t, 1);
4490
+ /** Zoom state for a timeline: `zoomIn`, `zoomOut`, and `fit` to a viewport width. Pass `zoom` and `setZoom` as the timeline's `zoom` and `onZoomChange`. */
4491
+ function useTimelineZoom({ initial = 20, min = .5, max = 400 } = {}) {
4492
+ const [zoom, set] = React.useState(initial);
4493
+ const setZoom = React.useCallback((z) => set(clamp$1(z, min, max)), [min, max]);
4494
+ return {
4495
+ zoom,
4496
+ setZoom,
4497
+ zoomIn: () => setZoom(zoom * 1.5),
4498
+ zoomOut: () => setZoom(zoom / 1.5),
4499
+ /** Zoom so `duration` fills `viewportWidth` pixels. */
4500
+ fit: (viewportWidth, duration) => setZoom(viewportWidth / Math.max(duration, 1e-6))
4501
+ };
4502
+ }
4503
+ /** Zoom in, zoom out and fit, as named icon buttons for a timeline's toolbar. */
4504
+ function TimelineZoomControls({ zoom }) {
4505
+ return /* @__PURE__ */ jsxs("div", {
4506
+ className: "flex items-center gap-1",
4507
+ children: [
4508
+ /* @__PURE__ */ jsx(IconButton, {
4509
+ icon: ZoomOut,
4510
+ label: "Zoom out",
4511
+ hint: "-",
4512
+ onClick: zoom.zoomOut
4513
+ }),
4514
+ /* @__PURE__ */ jsx(IconButton, {
4515
+ icon: ZoomIn,
4516
+ label: "Zoom in",
4517
+ hint: "+",
4518
+ onClick: zoom.zoomIn
4519
+ }),
4520
+ /* @__PURE__ */ jsx(IconButton, {
4521
+ icon: Maximize2,
4522
+ label: "Fit to view",
4523
+ hint: "0",
4524
+ onClick: zoom.fit
4525
+ })
4526
+ ]
4527
+ });
4528
+ }
4529
+ /** A rule that refuses an item overlapping another in its lane, for `validate`: names the item in the way. */
4530
+ function noOverlap(items) {
4531
+ return (id, next) => {
4532
+ const me = items.find((i) => i.id === id);
4533
+ const other = items.find((i) => i.id !== id && i.lane === next.lane && i.start < next.start + next.length - 1e-9 && next.start < i.start + i.length - 1e-9);
4534
+ return other ? `${me?.label ?? "This"} would overlap ${other.label}.` : null;
4535
+ };
4536
+ }
4537
+ /** Items placed on a zoomable time axis in lanes, with a current-time rule and markers. Reports every move, trim, selection and time change; the app applies them. Keyboard-complete, and only the items near the view are rendered. */
4538
+ function Timeline({ label, lanes, items, from = 0, to, zoom, onZoomChange, position, onPositionChange, follow, markers = [], selectedIds, onSelect, onItemChange, onDelete, validate, snapPoints = [], snap = true, step = 1, minLength, renderItem, kindColours, laneRows = 1, dropTypes, dropLength, onDrop, validateDrop, formatTime = defaultFormat, empty, className }) {
4539
+ const min = minLength ?? step;
4540
+ const scroller = React.useRef(null);
4541
+ const laneRefs = React.useRef(/* @__PURE__ */ new Map());
4542
+ const [view, setView] = React.useState({
4543
+ left: 0,
4544
+ width: 640
4545
+ });
4546
+ const [drag, setDrag] = React.useState(null);
4547
+ const dragRef = React.useRef(null);
4548
+ const [focusId, setFocusId] = React.useState(null);
4549
+ const [said, setSaid] = React.useState("");
4550
+ const [hover, setHover] = React.useState(null);
4551
+ const refocus = React.useRef(null);
4552
+ const selected = selectedIds ?? /* @__PURE__ */ new Set();
4553
+ const laneIndex = React.useMemo(() => new Map(lanes.map((l, i) => [l.id, i])), [lanes]);
4554
+ const laneLabel = (id) => lanes.find((l) => l.id === id)?.label ?? id;
4555
+ const width = Math.max((to - from) * zoom, 1);
4556
+ const x = (t) => (t - from) * zoom;
4557
+ React.useEffect(() => {
4558
+ const el = scroller.current;
4559
+ if (!el) return;
4560
+ const read = () => setView({
4561
+ left: el.scrollLeft,
4562
+ width: el.clientWidth || 640
4563
+ });
4564
+ read();
4565
+ const ro = new ResizeObserver(read);
4566
+ ro.observe(el);
4567
+ el.addEventListener("scroll", read, { passive: true });
4568
+ return () => {
4569
+ ro.disconnect();
4570
+ el.removeEventListener("scroll", read);
4571
+ };
4572
+ }, []);
4573
+ React.useEffect(() => {
4574
+ const el = scroller.current;
4575
+ if (!follow || position === void 0 || !el) return;
4576
+ const px = x(position);
4577
+ if (px < el.scrollLeft || px > el.scrollLeft + el.clientWidth - 24) el.scrollLeft = Math.max(px - el.clientWidth * .25, 0);
4578
+ }, [
4579
+ follow,
4580
+ position,
4581
+ zoom
4582
+ ]);
4583
+ React.useEffect(() => {
4584
+ const id = refocus.current;
4585
+ if (!id) return;
4586
+ refocus.current = null;
4587
+ const el = scroller.current?.querySelector(`[data-item="${CSS.escape(id)}"]`);
4588
+ if (el && document.activeElement !== el && (!document.activeElement || document.activeElement === document.body || !scroller.current?.contains(document.activeElement))) el.focus();
4589
+ }, [items]);
4590
+ const sorted = React.useMemo(() => {
4591
+ const byLane = /* @__PURE__ */ new Map();
4592
+ for (const l of lanes) byLane.set(l.id, []);
4593
+ for (const i of items) byLane.get(i.lane)?.push(i);
4594
+ for (const list of byLane.values()) list.sort((a, b) => a.start - b.start);
4595
+ return byLane;
4596
+ }, [lanes, items]);
4597
+ const snapTimes = React.useMemo(() => {
3785
4598
  const pts = [...snapPoints, ...markers.map((m) => m.time)];
3786
4599
  if (position !== void 0) pts.push(position);
3787
4600
  return pts;
@@ -5080,47 +5893,6 @@ function TileBox({ label }) {
5080
5893
  })
5081
5894
  });
5082
5895
  }
5083
- // src/components/virtual-list.tsx
5084
- var FOOTER = "\0footer";
5085
- /** A list that renders only its visible rows (React Aria's GridList and Virtualizer) from `virtualizeFrom` items, with arrow-key navigation between rows. */
5086
- function VirtualList({ label, items, itemKey, children, estimateSize = 48, rowHeight, height = 480, virtualizeFrom = 100, bounded = false, footer, className }) {
5087
- const virtual = items.length >= virtualizeFrom;
5088
- const rows = React.useMemo(() => items.map((item, index) => ({
5089
- id: itemKey(item),
5090
- item,
5091
- index
5092
- })), [items, itemKey]);
5093
- const layoutOptions = React.useMemo(() => rowHeight ? { rowHeight } : { estimatedRowHeight: estimateSize }, [rowHeight, estimateSize]);
5094
- const virtualise = virtual || bounded;
5095
- const scrolls = virtualise;
5096
- const list = /* @__PURE__ */ jsxs(GridList, {
5097
- "aria-label": label,
5098
- selectionMode: "none",
5099
- "data-strata-scroll": "",
5100
- className: cn("min-w-0 outline-none", scrolls && "overflow-y-auto", className),
5101
- style: scrolls ? virtual ? { height } : { maxHeight: height } : void 0,
5102
- children: [/* @__PURE__ */ jsx(Collection, {
5103
- items: rows,
5104
- children: (row) => /* @__PURE__ */ jsx(GridListItem, {
5105
- id: row.id,
5106
- textValue: row.id,
5107
- "data-index": row.index,
5108
- className: cn("min-w-0 outline-offset-[-2px]", row.index > 0 && "border-t border-border"),
5109
- children: children(row.item, row.index)
5110
- })
5111
- }), footer && /* @__PURE__ */ jsx(GridListItem, {
5112
- id: FOOTER,
5113
- textValue: "More",
5114
- className: "min-w-0",
5115
- children: footer
5116
- })]
5117
- });
5118
- return virtualise ? /* @__PURE__ */ jsx(Virtualizer, {
5119
- layout: ListLayout,
5120
- layoutOptions,
5121
- children: list
5122
- }) : list;
5123
- }
5124
5896
  // src/components/infinite-list.tsx
5125
5897
  var PendingFocus = React.createContext(null);
5126
5898
  function MoreFailed({ message, retry }) {
@@ -6910,6 +7682,51 @@ function frameBoxToShares(rect, v, frame) {
6910
7682
  }
6911
7683
  // src/components/compare-parts.tsx
6912
7684
  var VIEWPORT_HEIGHT = "max(16rem, calc(100svh - 14rem))";
7685
+ /** What a pair's frames do with a click (issue #201): the same answer as the keys, only where a click is unambiguous. Blind: only a candidate's `label` is ever said. */
7686
+ function makePicker(a, b, onPick, words) {
7687
+ const choose = words?.choose ?? ((label) => `Click to choose ${label}`);
7688
+ const unavailable = words?.unavailable ?? ((view) => `A click does not choose in ${view}: use the keys or the buttons.`);
7689
+ const answer = (zone) => onPick(zone.value === "a" ? "a" : "b");
7690
+ const token = `${a.id}|${b.id}`;
7691
+ return {
7692
+ /** A frame that is one whole side. */
7693
+ one(side) {
7694
+ const text = choose((side === "a" ? a : b).label);
7695
+ return {
7696
+ zoneAt: () => ({
7697
+ value: side,
7698
+ from: 0,
7699
+ to: 1,
7700
+ hint: text
7701
+ }),
7702
+ onPick: answer,
7703
+ describe: text,
7704
+ token
7705
+ };
7706
+ },
7707
+ /** A frame cut by a swipe divider at `divider` percent: the left is A, the right is B. */
7708
+ split(divider) {
7709
+ const cut = divider / 100;
7710
+ return {
7711
+ zoneAt: (x) => x < cut ? {
7712
+ value: "a",
7713
+ from: 0,
7714
+ to: cut,
7715
+ hint: choose(a.label)
7716
+ } : {
7717
+ value: "b",
7718
+ from: cut,
7719
+ to: 1,
7720
+ hint: choose(b.label)
7721
+ },
7722
+ onPick: answer,
7723
+ token,
7724
+ describe: `${choose(a.label)} on the left, ${choose(b.label)} on the right`
7725
+ };
7726
+ },
7727
+ unavailable
7728
+ };
7729
+ }
6913
7730
  /** A word for a picture's name on the page: its label, with its note unless blind. */
6914
7731
  function Caption({ c, blind }) {
6915
7732
  return /* @__PURE__ */ jsxs("div", {
@@ -7203,8 +8020,14 @@ function useViewport(initial = FIT) {
7203
8020
  };
7204
8021
  }
7205
8022
  var PAN_STEP = 48;
8023
+ /** A pointer that moves further than this between down and up is a pan, not a click. */
8024
+ var CLICK_SLOP = 4;
8025
+ /** A press held longer than this is not a click. */
8026
+ var CLICK_MAX_MS = 500;
8027
+ /** A click counts only once this long has passed with no second press: a double click zooms instead. */
8028
+ var DOUBLE_CLICK_MS = 300;
7206
8029
  /** A clipped frame whose children zoom and pan together; the viewport is the caller's, so frames can share one. */
7207
- var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, viewport, setViewport, children, cover, overlay, maxHeight, onBox, outline, className }, forwardedRef) {
8030
+ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, viewport, setViewport, children, cover, overlay, maxHeight, onBox, outline, pick, className }, forwardedRef) {
7208
8031
  const ref = React.useRef(null);
7209
8032
  React.useImperativeHandle(forwardedRef, () => ref.current);
7210
8033
  const latest = React.useRef(viewport);
@@ -7213,6 +8036,21 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
7213
8036
  const [band, setBand] = React.useState(null);
7214
8037
  const bandRef = React.useRef(band);
7215
8038
  bandRef.current = band;
8039
+ const pickRef = React.useRef(pick);
8040
+ pickRef.current = pick;
8041
+ const press = React.useRef(null);
8042
+ const waiting = React.useRef(null);
8043
+ const [hover, setHover] = React.useState(null);
8044
+ const describeId = React.useId();
8045
+ const cancelPick = () => {
8046
+ if (waiting.current !== null) clearTimeout(waiting.current);
8047
+ waiting.current = null;
8048
+ };
8049
+ React.useEffect(() => cancelPick, []);
8050
+ const shareAcross = (clientX) => {
8051
+ const r = ref.current.getBoundingClientRect();
8052
+ return r.width > 0 ? Math.min(Math.max((clientX - r.left) / r.width, 0), 1) : .5;
8053
+ };
7216
8054
  const inFrame = (clientX, clientY) => {
7217
8055
  const r = ref.current.getBoundingClientRect();
7218
8056
  return {
@@ -7284,7 +8122,14 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
7284
8122
  "aria-roledescription": "zoomable picture",
7285
8123
  tabIndex: 0,
7286
8124
  onKeyDown,
8125
+ "aria-describedby": pick ? describeId : void 0,
7287
8126
  onPointerDown: (e) => {
8127
+ cancelPick();
8128
+ press.current = pickRef.current && e.button === 0 && !e.shiftKey ? {
8129
+ x: e.clientX,
8130
+ y: e.clientY,
8131
+ at: e.timeStamp
8132
+ } : null;
7288
8133
  if (e.shiftKey && onBox && e.button === 0) {
7289
8134
  const p = inFrame(e.clientX, e.clientY);
7290
8135
  setBand({
@@ -7304,6 +8149,10 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
7304
8149
  e.currentTarget.setPointerCapture?.(e.pointerId);
7305
8150
  },
7306
8151
  onPointerMove: (e) => {
8152
+ if (pickRef.current && e.pointerType !== "touch") {
8153
+ const zone = pickRef.current.zoneAt(shareAcross(e.clientX));
8154
+ setHover((prev) => prev?.value === zone?.value && prev?.from === zone?.from && prev?.to === zone?.to ? prev : zone);
8155
+ }
7307
8156
  if (bandRef.current) {
7308
8157
  const p = inFrame(e.clientX, e.clientY);
7309
8158
  setBand({
@@ -7326,8 +8175,22 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
7326
8175
  y: latest.current.y + dy
7327
8176
  }, size()));
7328
8177
  },
7329
- onPointerUp: () => {
8178
+ onPointerUp: (e) => {
7330
8179
  drag.current = null;
8180
+ const down = press.current;
8181
+ press.current = null;
8182
+ if (down && pickRef.current && !bandRef.current && e.timeStamp - down.at <= CLICK_MAX_MS && Math.hypot(e.clientX - down.x, e.clientY - down.y) <= CLICK_SLOP) {
8183
+ const zone = pickRef.current.zoneAt(shareAcross(e.clientX));
8184
+ if (zone) {
8185
+ cancelPick();
8186
+ const token = pickRef.current.token;
8187
+ waiting.current = setTimeout(() => {
8188
+ waiting.current = null;
8189
+ const now = pickRef.current;
8190
+ if (now && now.token === token) now.onPick(zone);
8191
+ }, DOUBLE_CLICK_MS);
8192
+ }
8193
+ }
7331
8194
  const b = bandRef.current;
7332
8195
  if (b) {
7333
8196
  setBand(null);
@@ -7336,9 +8199,12 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
7336
8199
  },
7337
8200
  onPointerCancel: () => {
7338
8201
  drag.current = null;
8202
+ press.current = null;
7339
8203
  setBand(null);
7340
8204
  },
8205
+ onPointerLeave: () => setHover(null),
7341
8206
  onDoubleClick: (e) => {
8207
+ cancelPick();
7342
8208
  const v = latest.current;
7343
8209
  setViewport(v.scale > 1 ? FIT : zoomAt(v, 2, fromCentre(e.clientX, e.clientY), size()));
7344
8210
  },
@@ -7350,7 +8216,7 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
7350
8216
  } : {},
7351
8217
  touchAction: zoomed ? "none" : "pan-y"
7352
8218
  },
7353
- className: cn("relative w-full overflow-hidden rounded-surface border border-border bg-muted select-none", zoomed ? "cursor-grab active:cursor-grabbing" : "cursor-zoom-in", "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring", className),
8219
+ className: cn("relative w-full overflow-hidden rounded-surface border border-border bg-muted select-none", zoomed ? "cursor-grab active:cursor-grabbing" : pick ? "cursor-pointer" : "cursor-zoom-in", "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring", className),
7354
8220
  children: [
7355
8221
  /* @__PURE__ */ jsx("div", {
7356
8222
  className: "absolute inset-0",
@@ -7382,6 +8248,24 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
7382
8248
  height: `${outline[3] * 100}%`
7383
8249
  }
7384
8250
  }),
8251
+ pick && hover && !band && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
8252
+ "aria-hidden": true,
8253
+ className: "pointer-events-none absolute inset-y-0 border-2 border-primary ring-1 ring-background",
8254
+ style: {
8255
+ left: `${hover.from * 100}%`,
8256
+ width: `${(hover.to - hover.from) * 100}%`
8257
+ }
8258
+ }), /* @__PURE__ */ jsx("p", {
8259
+ "aria-hidden": true,
8260
+ className: "pointer-events-none absolute top-2 -translate-x-1/2 whitespace-nowrap rounded-pill border border-border bg-background px-2 py-0.5 type-caption text-foreground",
8261
+ style: { left: `${(hover.from + hover.to) / 2 * 100}%` },
8262
+ children: hover.hint
8263
+ })] }),
8264
+ pick && /* @__PURE__ */ jsx("span", {
8265
+ id: describeId,
8266
+ className: "sr-only",
8267
+ children: pick.describe
8268
+ }),
7385
8269
  band && /* @__PURE__ */ jsx("div", {
7386
8270
  "aria-hidden": true,
7387
8271
  className: "pointer-events-none absolute border-2 border-dashed border-foreground",
@@ -7545,7 +8429,7 @@ var ALL_MODES = [
7545
8429
  "difference"
7546
8430
  ];
7547
8431
  /** Two pictures to judge, side by side or laid over each other, zoomed and panned together, and full screen. */
7548
- function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, regions, keys = true, extraShortcuts = [], footer, maxHeight, cannotCompare = "Could not read these pictures to compare their pixels.", readPixels, defaultDifference = "brightness", className }) {
8432
+ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, regions, onPick, pick = true, pickWords, keys = true, extraShortcuts = [], footer, maxHeight, cannotCompare = "Could not read these pictures to compare their pixels.", readPixels, defaultDifference = "brightness", className }) {
7549
8433
  const { viewport, setViewport } = useViewport();
7550
8434
  const [full, setFull] = React.useState(false);
7551
8435
  const pairKey = `${a.media.src}|${b.media.src}`;
@@ -7605,6 +8489,7 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7605
8489
  key: pairKey,
7606
8490
  size: [w, h]
7607
8491
  });
8492
+ const picker = pick && onPick ? makePicker(a, b, onPick, pickWords) : null;
7608
8493
  const frameProps = {
7609
8494
  viewport,
7610
8495
  setViewport: rg.setViewport,
@@ -7625,6 +8510,7 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7625
8510
  ...frameProps,
7626
8511
  label: blind ? `Picture ${c.label}` : `${c.label}`,
7627
8512
  ref: i === 0 ? frameRef : void 0,
8513
+ pick: picker?.one(i === 0 ? "a" : "b"),
7628
8514
  children: pane(c, i === 0 ? imgRef : void 0, i === 0 ? learn : void 0)
7629
8515
  })]
7630
8516
  }, i))
@@ -7703,6 +8589,7 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7703
8589
  content: pane(a, imgRef, learn),
7704
8590
  shown: divider
7705
8591
  } : void 0,
8592
+ pick: mode === "swipe" ? picker?.split(divider) : mode === "blink" ? picker?.one(showing) : void 0,
7706
8593
  label: mode === "blink" ? `Picture ${top.label}` : `${a.label} over ${b.label}`,
7707
8594
  overlay: mode === "swipe" && /* @__PURE__ */ jsx(Slider$1, {
7708
8595
  "aria-label": `Divider between ${a.label} and ${b.label}`,
@@ -7772,6 +8659,10 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7772
8659
  ]
7773
8660
  }),
7774
8661
  /* @__PURE__ */ jsx(RegionChips, { state: rg }),
8662
+ picker && (mode === "fade" || mode === "difference") && /* @__PURE__ */ jsx("p", {
8663
+ className: "type-caption text-muted-foreground",
8664
+ children: picker.unavailable(MODE_LABEL$1[mode])
8665
+ }),
7775
8666
  mode === "fade" && /* @__PURE__ */ jsxs("div", {
7776
8667
  className: "flex items-center gap-3",
7777
8668
  children: [
@@ -8044,7 +8935,8 @@ function Judged({ pair, onAnswer, pending, flagReasons, words, last, view }) {
8044
8935
  });
8045
8936
  return /* @__PURE__ */ jsx(Fragment, { children: view({
8046
8937
  extraShortcuts: shortcuts,
8047
- footer
8938
+ footer,
8939
+ onPick: pending ? void 0 : (side) => answer({ answer: side })
8048
8940
  }, pair) });
8049
8941
  }
8050
8942
  var db$1 = (x) => x > 0 ? 20 * Math.log10(x) : -Infinity;
@@ -8421,7 +9313,7 @@ var SLOW_RATES = [
8421
9313
  2
8422
9314
  ];
8423
9315
  /** Plays, pauses, seeks, steps and loops any number of videos together. */
8424
- function useVideoClock({ fps, loop: loopProp, onLoopChange, audio }) {
9316
+ function useVideoClock({ fps, loop: loopProp, onLoopChange, audio, autoPlay = false, loopWhole = false, pairKey }) {
8425
9317
  const els = React.useRef(/* @__PURE__ */ new Map());
8426
9318
  const leaderRef = React.useRef(null);
8427
9319
  const cleanups = React.useRef(/* @__PURE__ */ new Map());
@@ -8434,6 +9326,7 @@ function useVideoClock({ fps, loop: loopProp, onLoopChange, audio }) {
8434
9326
  const [started, setStarted] = React.useState(false);
8435
9327
  const [volume, setVolume] = React.useState(100);
8436
9328
  const [muted, setMuted] = React.useState(false);
9329
+ const soundChosen = React.useRef(false);
8437
9330
  const [behind, setBehind] = React.useState(/* @__PURE__ */ new Set());
8438
9331
  const chosenRate = React.useRef(1);
8439
9332
  const holdRef = React.useRef(false);
@@ -8459,11 +9352,14 @@ function useVideoClock({ fps, loop: loopProp, onLoopChange, audio }) {
8459
9352
  };
8460
9353
  const loopRef = React.useRef(loop);
8461
9354
  loopRef.current = loop;
9355
+ const wholeRef = React.useRef(loopWhole);
9356
+ wholeRef.current = loopWhole;
8462
9357
  const onEnded = () => {
8463
9358
  const { start, end } = loopRef.current;
8464
9359
  const list = active();
8465
- if (wantedRef.current && start !== null && end !== null) {
8466
- for (const el of list) el.currentTime = start;
9360
+ const ranged = start !== null && end !== null;
9361
+ if (wantedRef.current && (ranged || wholeRef.current)) {
9362
+ for (const el of list) el.currentTime = ranged ? start : 0;
8467
9363
  for (const el of list) startRef.current(el);
8468
9364
  return;
8469
9365
  }
@@ -8641,6 +9537,43 @@ function useVideoClock({ fps, loop: loopProp, onLoopChange, audio }) {
8641
9537
  const index = [...els.current.entries()].find(([, e]) => e === el)?.[0];
8642
9538
  if (resume.current.playing && (index === void 0 || !hidden.current.has(index))) start(el);
8643
9539
  };
9540
+ const lastPair = React.useRef(pairKey);
9541
+ const armed = React.useRef(void 0);
9542
+ React.useEffect(() => {
9543
+ if (lastPair.current === pairKey) return;
9544
+ lastPair.current = pairKey;
9545
+ armed.current = void 0;
9546
+ resume.current = {
9547
+ time: 0,
9548
+ playing: false
9549
+ };
9550
+ pauseAll();
9551
+ for (const el of els.current.values()) el.currentTime = 0;
9552
+ setWanted(false);
9553
+ setStarted(false);
9554
+ setInfos(Object.fromEntries([...els.current].map(([i, el]) => [i, {
9555
+ duration: Number.isFinite(el.duration) && el.duration > 0 ? el.duration : null,
9556
+ error: !!el.error && el.error.code !== 1
9557
+ }])));
9558
+ }, [pairKey]);
9559
+ const [reduced] = React.useState(() => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
9560
+ const auto = autoPlay === "always" || autoPlay === true && !reduced;
9561
+ const playRef = React.useRef(play);
9562
+ playRef.current = play;
9563
+ React.useEffect(() => {
9564
+ if (!auto || !loaded || armed.current === (pairKey ?? "")) return;
9565
+ armed.current = pairKey ?? "";
9566
+ if (audio !== null && !soundChosen.current) {
9567
+ setMuted(true);
9568
+ for (const el of els.current.values()) el.muted = true;
9569
+ }
9570
+ playRef.current();
9571
+ }, [
9572
+ auto,
9573
+ loaded,
9574
+ pairKey,
9575
+ audio
9576
+ ]);
8644
9577
  React.useEffect(() => {
8645
9578
  for (const [i, el] of els.current) {
8646
9579
  el.muted = audio !== i || muted || volume === 0;
@@ -8696,7 +9629,7 @@ function useVideoClock({ fps, loop: loopProp, onLoopChange, audio }) {
8696
9629
  ...audio === null ? [] : [{
8697
9630
  keys: ["m"],
8698
9631
  label: "Mute",
8699
- run: () => setMuted((m) => !m)
9632
+ run: () => (soundChosen.current = true, setMuted((m) => !m))
8700
9633
  }]
8701
9634
  ];
8702
9635
  return {
@@ -8718,11 +9651,13 @@ function useVideoClock({ fps, loop: loopProp, onLoopChange, audio }) {
8718
9651
  failed,
8719
9652
  loop,
8720
9653
  looping: loop.start !== null && loop.end !== null,
9654
+ /** The whole clip loops: asked for, and no range set to override it. */
9655
+ loopsWhole: loopWhole && !(loop.start !== null && loop.end !== null),
8721
9656
  setPoint,
8722
9657
  clearLoop,
8723
9658
  volume,
8724
9659
  muted,
8725
- setVolume: (v) => (setMuted(false), setVolume(v)),
9660
+ setVolume: (v) => (soundChosen.current = true, setMuted(false), setVolume(v)),
8726
9661
  behind,
8727
9662
  setVisible,
8728
9663
  shortcuts,
@@ -8807,7 +9742,7 @@ function VideoControls({ clock, rates = SLOW_RATES, moments = [] }) {
8807
9742
  /* @__PURE__ */ jsx("span", {
8808
9743
  role: "status",
8809
9744
  className: "type-caption tabular-nums text-muted-foreground",
8810
- children: clock.looping ? `Looping ${at(loop.start)} to ${at(loop.end)}` : loop.start !== null ? `Loop starts at ${at(loop.start)}` : loop.end !== null ? `Loop ends at ${at(loop.end)}` : "No loop"
9745
+ children: clock.looping ? `Looping ${at(loop.start)} to ${at(loop.end)}` : clock.loopsWhole ? "Looping the whole clip" : loop.start !== null ? `Loop starts at ${at(loop.start)}` : loop.end !== null ? `Loop ends at ${at(loop.end)}` : "No loop"
8811
9746
  })
8812
9747
  ]
8813
9748
  })] });
@@ -8837,22 +9772,25 @@ function Cell$1({ c, index, clock, blind, isReference, children }) {
8837
9772
  });
8838
9773
  }
8839
9774
  /** Many videos in a grid on one clock, zoomed and panned together, with regions, a loop, stepping and full screen. */
8840
- function CompareVideoGrid({ label, items, reference, blind, missing, catchingUp = "Catching up", actions, columns = 3, regions, rates = SLOW_RATES, moments = [], loop, onLoopChange, audio = null, pixelated = "zoomed", keys = true, extraShortcuts = [], footer, className }) {
9775
+ function CompareVideoGrid({ label, items, reference, blind, missing, catchingUp = "Catching up", actions, columns = 3, regions, rates = SLOW_RATES, moments = [], loop, onLoopChange, audio = null, autoPlay = false, loopWhole = false, pixelated = "zoomed", keys = true, extraShortcuts = [], footer, className }) {
8841
9776
  const cells = reference ? [reference, ...items] : [...items];
8842
9777
  const first = cells[0];
8843
9778
  const fps = first?.media.fps ?? 30;
8844
9779
  const audioIndex = audio === null ? null : cells.findIndex((c) => c.id === audio);
9780
+ const key = cells.map((c) => c.media.src).join("|");
8845
9781
  const clock = useVideoClock({
8846
9782
  fps,
8847
9783
  loop,
8848
9784
  onLoopChange,
8849
- audio: audioIndex === null || audioIndex < 0 ? null : audioIndex
9785
+ audio: audioIndex === null || audioIndex < 0 ? null : audioIndex,
9786
+ autoPlay,
9787
+ loopWhole,
9788
+ pairKey: key
8850
9789
  });
8851
9790
  const { viewport, setViewport } = useViewport();
8852
9791
  const [full, setFull] = React.useState(false);
8853
9792
  const frameRef = React.useRef(null);
8854
9793
  const frameWidth = useWidth(frameRef);
8855
- const key = cells.map((c) => c.media.src).join("|");
8856
9794
  const aspect = first ? first.media.width / first.media.height : 4 / 3;
8857
9795
  const natural = first ? [first.media.width, first.media.height] : null;
8858
9796
  const rg = useRegions({
@@ -8990,13 +9928,17 @@ var MODE_LABEL = {
8990
9928
  blink: "Blink"
8991
9929
  };
8992
9930
  /** Two videos to judge by eye on one clock: side by side, swipe, fade or blink, zoomed together, with matched sound and full screen. */
8993
- function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates = SLOW_RATES, regions, moments = [], loop: loopProp, onLoopChange, audio = "a", pixelated = "zoomed", maxHeight, keys = true, extraShortcuts = [], footer, className }) {
9931
+ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates = SLOW_RATES, regions, moments = [], loop: loopProp, onLoopChange, audio = "a", onPick, pick = true, pickWords, autoPlay = false, loopWhole = false, pixelated = "zoomed", maxHeight, keys = true, extraShortcuts = [], footer, className }) {
8994
9932
  const clock = useVideoClock({
8995
9933
  fps: a.media.fps ?? 30,
8996
9934
  loop: loopProp,
8997
9935
  onLoopChange,
8998
- audio: audio === "none" ? null : audio === "a" ? 0 : 1
9936
+ audio: audio === "none" ? null : audio === "a" ? 0 : 1,
9937
+ autoPlay,
9938
+ loopWhole,
9939
+ pairKey: `${a.media.src}|${b.media.src}`
8999
9940
  });
9941
+ const picker = pick && onPick ? makePicker(a, b, onPick, pickWords) : null;
9000
9942
  const { viewport, setViewport } = useViewport();
9001
9943
  const [full, setFull] = React.useState(false);
9002
9944
  const [divider, setDivider] = React.useState(50);
@@ -9081,6 +10023,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
9081
10023
  ...frameProps,
9082
10024
  label: `Frame ${c.label}`,
9083
10025
  ref: i === 0 ? frameRef : void 0,
10026
+ pick: picker?.one(i === 0 ? "a" : "b"),
9084
10027
  children: [i === 0 && skeleton, video(c, i)]
9085
10028
  })]
9086
10029
  }, i))
@@ -9106,6 +10049,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
9106
10049
  content: video(a, 0),
9107
10050
  shown: divider
9108
10051
  } : void 0,
10052
+ pick: mode === "swipe" ? picker?.split(divider) : mode === "blink" ? picker?.one(showing) : void 0,
9109
10053
  label: mode === "blink" ? `Frame ${(showing === "a" ? a : b).label}` : `${a.label} over ${b.label}`,
9110
10054
  overlay: mode === "swipe" && /* @__PURE__ */ jsx(Slider$1, {
9111
10055
  "aria-label": `Divider between ${a.label} and ${b.label}`,
@@ -9178,6 +10122,10 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
9178
10122
  ]
9179
10123
  }),
9180
10124
  /* @__PURE__ */ jsx(RegionChips, { state: rg }),
10125
+ picker && mode === "fade" && /* @__PURE__ */ jsx("p", {
10126
+ className: "type-caption text-muted-foreground",
10127
+ children: picker.unavailable(MODE_LABEL.fade)
10128
+ }),
9181
10129
  mode === "fade" && /* @__PURE__ */ jsxs("div", {
9182
10130
  className: "flex items-center gap-3",
9183
10131
  children: [
@@ -10157,6 +11105,2120 @@ function SaveStatus({ state, onRetry, className }) {
10157
11105
  ]
10158
11106
  });
10159
11107
  }
10160
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, CompositionBar, ContextMenu, CursorScope, DEFAULT_TOLERANCE, DataTable, DataView, Density, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, PairJudge, PairVote, Pane, Popover, PropertyList, PropertyRow, RateChoice, RowAction, SPEECH_RATES, SaveStatus, SeekBar, SelectableGrid, SideNav, Skeleton, Slider, SortableList, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, Transport, UndoBar, ViewportFrame, VirtualList, VolumeControl, Workspace, actualPixelsScale, boxViewport, buttonVariants, canFullscreen, clampViewport, cn, colorSchemeScript, commandShortcut, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, detectPlatform, diffWords, differences, fetchJson, fieldErrorsOf, format, formatChord, gainToVolume, geo, isReservedChord, isTypingTarget, labelOf, logScale, loudnessOf, matchGains, matchesAccept, matchesChord, measureLoudness, noOverlap, parseChord, parseSort, readErrorBody, readPixels, regionShares, resample, serialiseSort, staleOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toast, toastTimeout, transportShortcuts, typeSteps, useActiveItem, useAsyncAction, useAutoSave, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useLeaveGuard, useLoad, useMediaElement, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, useWorkspaceState, valueAt, zoomAt };
11108
+ // src/lib/rich-text.ts
11109
+ var WORD = /[\p{L}\p{N}_-]/u;
11110
+ /** Finds ids in `text`, longest first, never inside a longer word. Overlaps go to the earlier, longer match. */
11111
+ function matchEntities(text, matcher) {
11112
+ if (!matcher) return [];
11113
+ if (typeof matcher === "function") return [...matcher(text)].sort((a, b) => a.start - b.start);
11114
+ const ids = [...new Set(matcher)].filter(Boolean).sort((a, b) => b.length - a.length);
11115
+ const found = [];
11116
+ let i = 0;
11117
+ while (i < text.length) {
11118
+ let hit;
11119
+ if (i === 0 || !WORD.test(text[i - 1])) {
11120
+ for (const id of ids) if (text.startsWith(id, i) && (i + id.length >= text.length || !WORD.test(text[i + id.length]))) {
11121
+ hit = id;
11122
+ break;
11123
+ }
11124
+ }
11125
+ if (hit) {
11126
+ found.push({
11127
+ start: i,
11128
+ end: i + hit.length,
11129
+ id: hit
11130
+ });
11131
+ i += hit.length;
11132
+ } else i++;
11133
+ }
11134
+ return found;
11135
+ }
11136
+ /** A link is safe when its scheme is http, https or mailto. */
11137
+ function safeHref(href) {
11138
+ try {
11139
+ const url = new URL(href);
11140
+ return [
11141
+ "http:",
11142
+ "https:",
11143
+ "mailto:"
11144
+ ].includes(url.protocol) ? url.href : null;
11145
+ } catch {
11146
+ return null;
11147
+ }
11148
+ }
11149
+ function plain(text, matcher) {
11150
+ const out = [];
11151
+ let at = 0;
11152
+ for (const m of matchEntities(text, matcher)) {
11153
+ if (m.start < at) continue;
11154
+ if (m.start > at) out.push({
11155
+ type: "text",
11156
+ text: text.slice(at, m.start)
11157
+ });
11158
+ out.push({
11159
+ type: "entity",
11160
+ id: m.id,
11161
+ text: text.slice(m.start, m.end)
11162
+ });
11163
+ at = m.end;
11164
+ }
11165
+ if (at < text.length) out.push({
11166
+ type: "text",
11167
+ text: text.slice(at)
11168
+ });
11169
+ return out;
11170
+ }
11171
+ /** Parses one line's inline marks. Unclosed marks stay as the text they were typed as. */
11172
+ function parseInline(text, matcher) {
11173
+ const out = [];
11174
+ let buffer = "";
11175
+ const flush = () => {
11176
+ if (buffer) out.push(...plain(buffer, matcher));
11177
+ buffer = "";
11178
+ };
11179
+ let i = 0;
11180
+ while (i < text.length) {
11181
+ if (text.startsWith("**", i)) {
11182
+ const end = text.indexOf("**", i + 2);
11183
+ if (end > i + 2) {
11184
+ flush();
11185
+ out.push({
11186
+ type: "bold",
11187
+ children: parseInline(text.slice(i + 2, end), matcher)
11188
+ });
11189
+ i = end + 2;
11190
+ continue;
11191
+ }
11192
+ } else if (text[i] === "`") {
11193
+ const end = text.indexOf("`", i + 1);
11194
+ if (end > i + 1) {
11195
+ flush();
11196
+ out.push({
11197
+ type: "code",
11198
+ text: text.slice(i + 1, end)
11199
+ });
11200
+ i = end + 1;
11201
+ continue;
11202
+ }
11203
+ } else if (text[i] === "[") {
11204
+ const m = /^\[([^\]]+)\]\(([^)\s]+)\)/.exec(text.slice(i));
11205
+ if (m) {
11206
+ const href = safeHref(m[2]);
11207
+ flush();
11208
+ if (href) out.push({
11209
+ type: "link",
11210
+ href,
11211
+ children: parseInline(m[1], matcher)
11212
+ });
11213
+ else out.push({
11214
+ type: "text",
11215
+ text: m[1]
11216
+ });
11217
+ i += m[0].length;
11218
+ continue;
11219
+ }
11220
+ }
11221
+ buffer += text[i];
11222
+ i++;
11223
+ }
11224
+ flush();
11225
+ return out;
11226
+ }
11227
+ /** Parses blocks: blank-line separated paragraphs, and runs of `- ` or `1. ` lines as lists. */
11228
+ function parseRichText(text, matcher) {
11229
+ const blocks = [];
11230
+ let paragraph = [];
11231
+ let list = null;
11232
+ const endParagraph = () => {
11233
+ if (paragraph.length) blocks.push({
11234
+ type: "paragraph",
11235
+ children: parseInline(paragraph.join(" "), matcher)
11236
+ });
11237
+ paragraph = [];
11238
+ };
11239
+ const endList = () => {
11240
+ if (list) blocks.push({
11241
+ type: "list",
11242
+ ...list
11243
+ });
11244
+ list = null;
11245
+ };
11246
+ for (const line of text.split(/\r?\n/)) {
11247
+ const item = /^\s*(?:([-*])|(\d+)[.)])\s+(.*)$/.exec(line);
11248
+ if (item) {
11249
+ endParagraph();
11250
+ const ordered = item[2] !== void 0;
11251
+ if (list && list.ordered !== ordered) endList();
11252
+ list ??= {
11253
+ ordered,
11254
+ items: []
11255
+ };
11256
+ list.items.push(parseInline(item[3], matcher));
11257
+ } else if (!line.trim()) {
11258
+ endParagraph();
11259
+ endList();
11260
+ } else {
11261
+ endList();
11262
+ paragraph.push(line.trim());
11263
+ }
11264
+ }
11265
+ endParagraph();
11266
+ endList();
11267
+ return blocks;
11268
+ }
11269
+ /** The plain words of a text with the marks removed: what a live region announces. */
11270
+ function plainText(text) {
11271
+ return text.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/\*\*|`/g, "").replace(/^\s*(?:[-*]|\d+[.)])\s+/gm, "").replace(/\s+/g, " ").trim();
11272
+ }
11273
+ // src/components/conversation.tsx
11274
+ var LINK = "text-primary underline underline-offset-2 hover:no-underline";
11275
+ function renderInline(nodes, onOpen, keyBase = "") {
11276
+ return nodes.map((n, i) => {
11277
+ const key = `${keyBase}${i}`;
11278
+ switch (n.type) {
11279
+ case "text": return /* @__PURE__ */ jsx(React.Fragment, { children: n.text }, key);
11280
+ case "bold": return /* @__PURE__ */ jsx("strong", {
11281
+ className: "font-semibold",
11282
+ children: renderInline(n.children, onOpen, `${key}.`)
11283
+ }, key);
11284
+ case "code": return /* @__PURE__ */ jsx("code", {
11285
+ className: "rounded-control bg-muted px-1 py-0.5 font-mono type-caption",
11286
+ children: n.text
11287
+ }, key);
11288
+ case "link": return /* @__PURE__ */ jsx("a", {
11289
+ href: n.href,
11290
+ target: "_blank",
11291
+ rel: "noopener noreferrer",
11292
+ className: LINK,
11293
+ children: renderInline(n.children, onOpen, `${key}.`)
11294
+ }, key);
11295
+ case "entity": return onOpen ? /* @__PURE__ */ jsx("button", {
11296
+ type: "button",
11297
+ onClick: () => onOpen(n.id),
11298
+ className: cn(LINK, "cursor-pointer font-mono type-caption"),
11299
+ children: n.text
11300
+ }, key) : /* @__PURE__ */ jsx("code", {
11301
+ className: "font-mono type-caption",
11302
+ children: n.text
11303
+ }, key);
11304
+ }
11305
+ });
11306
+ }
11307
+ function renderBlocks(blocks, onOpen) {
11308
+ return blocks.map((b, i) => b.type === "paragraph" ? /* @__PURE__ */ jsx("p", { children: renderInline(b.children, onOpen) }, i) : b.ordered ? /* @__PURE__ */ jsx("ol", {
11309
+ className: "list-decimal space-y-1 pl-5",
11310
+ children: b.items.map((it, j) => /* @__PURE__ */ jsx("li", { children: renderInline(it, onOpen) }, j))
11311
+ }, i) : /* @__PURE__ */ jsx("ul", {
11312
+ className: "list-disc space-y-1 pl-5",
11313
+ children: b.items.map((it, j) => /* @__PURE__ */ jsx("li", { children: renderInline(it, onOpen) }, j))
11314
+ }, i));
11315
+ }
11316
+ /** Draws a small safe subset of text (bold, code, lists, http links) and turns known ids into buttons. Never HTML: whatever the string holds is shown as text. */
11317
+ function RichText({ children, entities, onOpen, className }) {
11318
+ const blocks = React.useMemo(() => parseRichText(children, entities), [children, entities]);
11319
+ return /* @__PURE__ */ jsx("div", {
11320
+ className: cn("space-y-2 break-words type-body", className),
11321
+ children: renderBlocks(blocks, onOpen)
11322
+ });
11323
+ }
11324
+ var NEAR_BOTTOM = 24;
11325
+ /** A thread of turns: answers stream, finish or fail in place; the log follows only while the person is at the bottom (with Jump to latest), and a finished answer is announced once, politely. */
11326
+ function Conversation({ label, turns, answerName, personName = "You", entities, onOpen, onRetry, empty, lookedUpLabel = "What it looked up", className }) {
11327
+ const box = React.useRef(null);
11328
+ const [atBottom, setAtBottom] = React.useState(true);
11329
+ const following = React.useRef(true);
11330
+ const [announcement, setAnnouncement] = React.useState("");
11331
+ const last = turns[turns.length - 1];
11332
+ const toBottom = React.useCallback(() => {
11333
+ const el = box.current;
11334
+ if (el) el.scrollTop = el.scrollHeight;
11335
+ following.current = true;
11336
+ setAtBottom(true);
11337
+ }, []);
11338
+ const onScroll = () => {
11339
+ const el = box.current;
11340
+ if (!el) return;
11341
+ const near = el.scrollHeight - el.scrollTop - el.clientHeight <= NEAR_BOTTOM;
11342
+ following.current = near;
11343
+ setAtBottom(near);
11344
+ };
11345
+ React.useLayoutEffect(() => {
11346
+ if (last?.role === "person" || following.current) toBottom();
11347
+ }, [
11348
+ turns.length,
11349
+ last?.text,
11350
+ last?.state,
11351
+ last?.role,
11352
+ toBottom
11353
+ ]);
11354
+ const states = React.useRef(/* @__PURE__ */ new Map());
11355
+ React.useEffect(() => {
11356
+ for (const t of turns) {
11357
+ const before = states.current.get(t.id);
11358
+ if (t.role === "answer" && before === "streaming" && t.state !== "streaming") setAnnouncement(t.state === "failed" ? `${answerName} could not answer: ${t.error}` : `${answerName} answered: ${plainText(t.text).slice(0, 160)}`);
11359
+ states.current.set(t.id, t.state ?? "done");
11360
+ }
11361
+ }, [turns, answerName]);
11362
+ return /* @__PURE__ */ jsxs("div", {
11363
+ className: cn("relative flex min-h-0 flex-col", className),
11364
+ children: [
11365
+ /* @__PURE__ */ jsx("div", {
11366
+ role: "region",
11367
+ "aria-label": label,
11368
+ ref: box,
11369
+ onScroll,
11370
+ tabIndex: 0,
11371
+ className: "min-h-0 flex-1 space-y-4 overflow-y-auto rounded-surface p-1",
11372
+ children: turns.length === 0 ? empty : turns.map((t) => /* @__PURE__ */ jsxs("article", {
11373
+ "aria-label": `${t.role === "person" ? personName : answerName}, ${format.clock(t.time)}`,
11374
+ "aria-busy": t.state === "streaming",
11375
+ className: cn("flex flex-col gap-1", t.role === "person" && "items-end"),
11376
+ children: [
11377
+ /* @__PURE__ */ jsxs("header", {
11378
+ className: "flex items-baseline gap-2 type-caption text-muted-foreground",
11379
+ children: [/* @__PURE__ */ jsx("span", {
11380
+ className: "type-label text-foreground",
11381
+ children: t.role === "person" ? personName : answerName
11382
+ }), /* @__PURE__ */ jsx("time", {
11383
+ dateTime: new Date(t.time).toISOString(),
11384
+ children: format.clock(t.time)
11385
+ })]
11386
+ }),
11387
+ /* @__PURE__ */ jsxs("div", {
11388
+ className: cn("max-w-prose rounded-surface px-3 py-2", t.role === "person" ? "bg-muted" : "border border-border"),
11389
+ children: [
11390
+ t.state === "streaming" && !t.text ? /* @__PURE__ */ jsxs("p", {
11391
+ className: "type-body-sm text-muted-foreground",
11392
+ children: [answerName, " is working on it…"]
11393
+ }) : /* @__PURE__ */ jsx(RichText, {
11394
+ entities,
11395
+ onOpen,
11396
+ children: t.text
11397
+ }),
11398
+ t.state === "streaming" && t.text && /* @__PURE__ */ jsx("p", {
11399
+ className: "mt-1 type-caption text-muted-foreground",
11400
+ children: "Still writing…"
11401
+ }),
11402
+ t.state === "failed" && /* @__PURE__ */ jsxs("div", {
11403
+ className: "mt-2 flex flex-wrap items-center gap-3 type-body-sm text-danger",
11404
+ children: [/* @__PURE__ */ jsx("span", { children: t.error }), /* @__PURE__ */ jsx(Button, {
11405
+ size: "sm",
11406
+ onClick: () => onRetry(t.id),
11407
+ children: "Try again"
11408
+ })]
11409
+ })
11410
+ ]
11411
+ }),
11412
+ t.lookedUp && t.state !== "streaming" && /* @__PURE__ */ jsx(Disclosure, {
11413
+ summary: lookedUpLabel,
11414
+ className: "max-w-prose type-body-sm",
11415
+ children: t.lookedUp
11416
+ })
11417
+ ]
11418
+ }, t.id))
11419
+ }),
11420
+ !atBottom && /* @__PURE__ */ jsxs(Button, {
11421
+ size: "sm",
11422
+ variant: "outline",
11423
+ onClick: toBottom,
11424
+ className: "absolute bottom-2 left-1/2 -translate-x-1/2 shadow-overlay",
11425
+ children: [/* @__PURE__ */ jsx(ArrowDown, {}), " Jump to latest"]
11426
+ }),
11427
+ /* @__PURE__ */ jsx("div", {
11428
+ role: "status",
11429
+ "aria-live": "polite",
11430
+ className: "sr-only",
11431
+ children: announcement
11432
+ })
11433
+ ]
11434
+ });
11435
+ }
11436
+ /** The box a question is typed in: Enter sends, Shift+Enter is a new line, disabled with its reason while answering (and Stop), suggestions as buttons. */
11437
+ function Composer({ label, onSend, answering = false, onStop, answeringReason, suggestions, sendLabel = "Send", className }) {
11438
+ const [text, setText] = React.useState("");
11439
+ const reasonId = React.useId();
11440
+ const send = (value) => {
11441
+ const v = value.trim();
11442
+ if (!v || answering) return;
11443
+ onSend(v);
11444
+ setText("");
11445
+ };
11446
+ return /* @__PURE__ */ jsxs("div", {
11447
+ className: cn("space-y-2", className),
11448
+ children: [
11449
+ suggestions && suggestions.length > 0 && !answering && /* @__PURE__ */ jsx("div", {
11450
+ role: "group",
11451
+ "aria-label": "Suggested questions",
11452
+ className: "flex flex-wrap gap-2",
11453
+ children: suggestions.map((s) => /* @__PURE__ */ jsx(Button, {
11454
+ size: "sm",
11455
+ onClick: () => send(s),
11456
+ children: s
11457
+ }, s))
11458
+ }),
11459
+ /* @__PURE__ */ jsxs("form", {
11460
+ className: "flex items-end gap-2",
11461
+ onSubmit: (e) => {
11462
+ e.preventDefault();
11463
+ send(text);
11464
+ },
11465
+ children: [/* @__PURE__ */ jsx(Textarea, {
11466
+ "aria-label": label,
11467
+ "aria-describedby": answering ? reasonId : void 0,
11468
+ rows: 2,
11469
+ value: text,
11470
+ disabled: answering,
11471
+ onChange: (e) => setText(e.target.value),
11472
+ onKeyDown: (e) => {
11473
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
11474
+ e.preventDefault();
11475
+ send(text);
11476
+ }
11477
+ },
11478
+ className: "min-h-0 flex-1 resize-none"
11479
+ }), answering ? /* @__PURE__ */ jsxs(Button, {
11480
+ onClick: onStop,
11481
+ children: [/* @__PURE__ */ jsx(Square, {}), " Stop"]
11482
+ }) : /* @__PURE__ */ jsxs(Button, {
11483
+ type: "submit",
11484
+ variant: "default",
11485
+ disabled: !text.trim(),
11486
+ children: [
11487
+ /* @__PURE__ */ jsx(Send, {}),
11488
+ " ",
11489
+ sendLabel
11490
+ ]
11491
+ })]
11492
+ }),
11493
+ answering && /* @__PURE__ */ jsx("p", {
11494
+ id: reasonId,
11495
+ className: "type-caption text-muted-foreground",
11496
+ children: answeringReason
11497
+ })
11498
+ ]
11499
+ });
11500
+ }
11501
+ // src/components/lightbox.tsx
11502
+ var NARROW = "(max-width: 719px)";
11503
+ function useNarrow() {
11504
+ const [narrow, setNarrow] = React.useState(() => typeof matchMedia === "function" && matchMedia(NARROW).matches);
11505
+ React.useEffect(() => {
11506
+ if (typeof matchMedia !== "function") return;
11507
+ const q = matchMedia(NARROW);
11508
+ const on = () => setNarrow(q.matches);
11509
+ on();
11510
+ q.addEventListener("change", on);
11511
+ return () => q.removeEventListener("change", on);
11512
+ }, []);
11513
+ return narrow;
11514
+ }
11515
+ /** A picture from a set in a full-size dialog: previous/next and arrow keys, "3 of 40", zoom and pan, details beside it, neighbours preloaded, a `missing` sentence for one that fails, and a Compare ticked hand-off. Focus returns to the tile that opened it. */
11516
+ function Lightbox({ title, items, index, onIndexChange, open, onOpenChange, missing, details, detailsLabel = "Details", ticked, onCompare, aspect = 3 / 2 }) {
11517
+ const last = items.length - 1;
11518
+ const at = Math.min(Math.max(index, 0), Math.max(last, 0));
11519
+ const item = items[at];
11520
+ const narrow = useNarrow();
11521
+ const [failed, setFailed] = React.useState(/* @__PURE__ */ new Set());
11522
+ const [natural, setNatural] = React.useState(null);
11523
+ const frame = React.useRef(null);
11524
+ const { viewport, setViewport } = useViewport(FIT);
11525
+ const zoom = useZoom({
11526
+ viewport,
11527
+ setViewport,
11528
+ frame,
11529
+ natural: natural ?? item?.natural ?? null
11530
+ });
11531
+ React.useEffect(() => {
11532
+ setViewport(FIT);
11533
+ setNatural(null);
11534
+ }, [item?.id, setViewport]);
11535
+ React.useEffect(() => {
11536
+ if (!open || typeof Image === "undefined") return;
11537
+ for (const n of [items[at - 1], items[at + 1]]) if (n) new Image().src = n.src;
11538
+ }, [
11539
+ open,
11540
+ at,
11541
+ items
11542
+ ]);
11543
+ const go = (to) => onIndexChange(Math.min(Math.max(to, 0), last));
11544
+ const keys = React.useRef((_) => {});
11545
+ keys.current = (e) => {
11546
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
11547
+ if (e.target.closest?.("[role=\"toolbar\"], input, textarea, select, [contenteditable=\"true\"]")) return;
11548
+ const to = e.key === "ArrowLeft" ? at - 1 : e.key === "ArrowRight" ? at + 1 : e.key === "Home" ? 0 : e.key === "End" ? last : null;
11549
+ if (to === null) return;
11550
+ e.preventDefault();
11551
+ go(to);
11552
+ };
11553
+ React.useEffect(() => {
11554
+ if (!open) return;
11555
+ const on = (e) => keys.current(e);
11556
+ window.addEventListener("keydown", on);
11557
+ return () => window.removeEventListener("keydown", on);
11558
+ }, [open]);
11559
+ const ready = ticked && onCompare && ticked.length >= 2;
11560
+ const body = item && details ? details(item) : null;
11561
+ return /* @__PURE__ */ jsx(Dialog, {
11562
+ open,
11563
+ onOpenChange,
11564
+ title,
11565
+ size: "full",
11566
+ children: item && /* @__PURE__ */ jsxs("div", {
11567
+ className: "flex h-full min-h-0 flex-col gap-3 outline-none",
11568
+ children: [/* @__PURE__ */ jsxs("div", {
11569
+ className: "flex flex-wrap items-center gap-2",
11570
+ children: [
11571
+ /* @__PURE__ */ jsx(IconButton, {
11572
+ icon: ChevronLeft,
11573
+ label: "Previous picture",
11574
+ onPress: () => go(at - 1),
11575
+ disabled: at === 0
11576
+ }),
11577
+ /* @__PURE__ */ jsx(IconButton, {
11578
+ icon: ChevronRight,
11579
+ label: "Next picture",
11580
+ onPress: () => go(at + 1),
11581
+ disabled: at === last
11582
+ }),
11583
+ /* @__PURE__ */ jsxs("span", {
11584
+ className: "type-label tabular-nums",
11585
+ "aria-live": "polite",
11586
+ "aria-atomic": "true",
11587
+ children: [
11588
+ at + 1,
11589
+ " of ",
11590
+ items.length
11591
+ ]
11592
+ }),
11593
+ /* @__PURE__ */ jsx(Toolbar, {
11594
+ label: "Zoom",
11595
+ className: "ml-2 flex items-center gap-1",
11596
+ children: /* @__PURE__ */ jsx(ZoomControls, {
11597
+ viewport,
11598
+ zoom,
11599
+ natural: natural ?? item.natural ?? null
11600
+ })
11601
+ }),
11602
+ onCompare && ticked && /* @__PURE__ */ jsxs(Button, {
11603
+ size: "sm",
11604
+ className: "ml-auto",
11605
+ disabled: !ready,
11606
+ onPress: () => onCompare(ticked),
11607
+ children: [
11608
+ "Compare ticked (",
11609
+ ticked.length,
11610
+ ")"
11611
+ ]
11612
+ })
11613
+ ]
11614
+ }), /* @__PURE__ */ jsxs("div", {
11615
+ className: cn("flex min-h-0 flex-1 gap-4", narrow ? "flex-col" : "flex-row"),
11616
+ children: [/* @__PURE__ */ jsx("div", {
11617
+ className: "min-h-0 min-w-0 flex-1",
11618
+ children: failed.has(item.id) ? /* @__PURE__ */ jsx("p", {
11619
+ role: "img",
11620
+ "aria-label": item.label,
11621
+ className: "grid h-full min-h-40 place-items-center rounded-surface border border-dashed border-border p-6 text-center type-body text-muted-foreground",
11622
+ children: missing
11623
+ }) : /* @__PURE__ */ jsx(ViewportFrame, {
11624
+ ref: frame,
11625
+ label: item.label,
11626
+ aspect,
11627
+ viewport,
11628
+ setViewport,
11629
+ maxHeight: narrow ? "50svh" : "calc(100svh - 12rem)",
11630
+ children: /* @__PURE__ */ jsx("img", {
11631
+ src: item.src,
11632
+ alt: item.label,
11633
+ draggable: false,
11634
+ className: "size-full object-contain",
11635
+ onLoad: (e) => setNatural([e.currentTarget.naturalWidth, e.currentTarget.naturalHeight]),
11636
+ onError: () => setFailed((f) => new Set(f).add(item.id))
11637
+ }, item.id)
11638
+ })
11639
+ }), body && (narrow ? /* @__PURE__ */ jsx(Disclosure, {
11640
+ summary: detailsLabel,
11641
+ className: "shrink-0",
11642
+ children: body
11643
+ }) : /* @__PURE__ */ jsx("aside", {
11644
+ "aria-label": detailsLabel,
11645
+ className: "min-h-0 w-72 shrink-0 overflow-y-auto",
11646
+ children: body
11647
+ }))]
11648
+ })]
11649
+ })
11650
+ });
11651
+ }
11652
+ // src/lib/region.ts
11653
+ var HANDLES = [
11654
+ "nw",
11655
+ "n",
11656
+ "ne",
11657
+ "e",
11658
+ "se",
11659
+ "s",
11660
+ "sw",
11661
+ "w"
11662
+ ];
11663
+ /** Moves a rectangle by (dx, dy), stopping at the bounds (it keeps its size). */
11664
+ function moveRect(r, dx, dy, bounds) {
11665
+ const x = Math.min(Math.max(r.x + dx, bounds.x), bounds.x + bounds.w - r.w);
11666
+ const y = Math.min(Math.max(r.y + dy, bounds.y), bounds.y + bounds.h - r.h);
11667
+ return {
11668
+ ...r,
11669
+ x,
11670
+ y
11671
+ };
11672
+ }
11673
+ /** Puts a rectangle inside the bounds and at least `min` size, keeping its aspect if one is set (shrinking it to fit). */
11674
+ function fitRect(r, { bounds, min, aspect }) {
11675
+ let { w, h } = r;
11676
+ const mw = min?.w ?? 0;
11677
+ const mh = min?.h ?? 0;
11678
+ if (aspect) {
11679
+ w = Math.max(w, mw, mh * aspect);
11680
+ h = w / aspect;
11681
+ const scale = Math.min(1, bounds.w / w, bounds.h / h);
11682
+ w *= scale;
11683
+ h *= scale;
11684
+ } else {
11685
+ w = Math.min(Math.max(w, mw), bounds.w);
11686
+ h = Math.min(Math.max(h, mh), bounds.h);
11687
+ }
11688
+ return moveRect({
11689
+ x: r.x,
11690
+ y: r.y,
11691
+ w,
11692
+ h
11693
+ }, 0, 0, bounds);
11694
+ }
11695
+ /**
11696
+ * Drags `handle` of `r` by (dx, dy). The opposite edge or corner stays where it is. Without an
11697
+ * aspect each edge stops at the bounds and at `min` from the edge opposite; with one the rectangle
11698
+ * keeps its shape: a corner follows the larger of the two movements, an edge changes its own
11699
+ * dimension and the other grows or shrinks about the middle. The result is always inside the bounds.
11700
+ */
11701
+ function resizeRect(r, handle, dx, dy, { bounds, min, aspect }) {
11702
+ const mw = Math.max(min?.w ?? 0, aspect ? (min?.h ?? 0) * aspect : 0, 0);
11703
+ const mh = Math.max(min?.h ?? 0, aspect ? mw / aspect : 0, 0);
11704
+ const left = r.x;
11705
+ const top = r.y;
11706
+ const right = r.x + r.w;
11707
+ const bottom = r.y + r.h;
11708
+ const hasW = handle.includes("w");
11709
+ const hasE = handle.includes("e");
11710
+ const hasN = handle.includes("n");
11711
+ const hasS = handle.includes("s");
11712
+ if (!aspect) {
11713
+ const nl = hasW ? Math.min(Math.max(left + dx, bounds.x), right - mw) : left;
11714
+ const nr = hasE ? Math.max(Math.min(right + dx, bounds.x + bounds.w), left + mw) : right;
11715
+ const nt = hasN ? Math.min(Math.max(top + dy, bounds.y), bottom - mh) : top;
11716
+ const nb = hasS ? Math.max(Math.min(bottom + dy, bounds.y + bounds.h), top + mh) : bottom;
11717
+ return {
11718
+ x: nl,
11719
+ y: nt,
11720
+ w: nr - nl,
11721
+ h: nb - nt
11722
+ };
11723
+ }
11724
+ const corner = (hasW || hasE) && (hasN || hasS);
11725
+ const ax = hasW ? right : left;
11726
+ const ay = hasN ? bottom : top;
11727
+ const cx = r.x + r.w / 2;
11728
+ const cy = r.y + r.h / 2;
11729
+ const roomW = hasW ? ax - bounds.x : hasE ? bounds.x + bounds.w - ax : 2 * Math.min(cx - bounds.x, bounds.x + bounds.w - cx);
11730
+ const roomH = hasN ? ay - bounds.y : hasS ? bounds.y + bounds.h - ay : 2 * Math.min(cy - bounds.y, bounds.y + bounds.h - cy);
11731
+ let w;
11732
+ if (corner) {
11733
+ const wantW = r.w + (hasW ? -dx : dx);
11734
+ const wantH = r.h + (hasN ? -dy : dy);
11735
+ w = Math.max(wantW, wantH * aspect);
11736
+ } else if (hasW || hasE) w = r.w + (hasW ? -dx : dx);
11737
+ else w = (r.h + (hasN ? -dy : dy)) * aspect;
11738
+ w = Math.min(Math.max(w, mw), roomW, roomH * aspect);
11739
+ const h = w / aspect;
11740
+ return {
11741
+ x: hasW ? ax - w : hasE ? ax : cx - w / 2,
11742
+ y: hasN ? ay - h : hasS ? ay : cy - h / 2,
11743
+ w,
11744
+ h
11745
+ };
11746
+ }
11747
+ /** A rectangle drawn by dragging from one corner point to another, ordered and fitted to the limits. */
11748
+ function drawRect(start, b, limits) {
11749
+ const { bounds, aspect } = limits;
11750
+ const a = {
11751
+ x: Math.min(Math.max(start.x, bounds.x), bounds.x + bounds.w),
11752
+ y: Math.min(Math.max(start.y, bounds.y), bounds.y + bounds.h)
11753
+ };
11754
+ const px = Math.min(Math.max(b.x, bounds.x), bounds.x + bounds.w);
11755
+ const py = Math.min(Math.max(b.y, bounds.y), bounds.y + bounds.h);
11756
+ let w = Math.abs(px - a.x);
11757
+ let h = Math.abs(py - a.y);
11758
+ if (aspect) {
11759
+ w = Math.max(w, h * aspect);
11760
+ h = w / aspect;
11761
+ const roomW = px < a.x ? a.x - bounds.x : bounds.x + bounds.w - a.x;
11762
+ const roomH = py < a.y ? a.y - bounds.y : bounds.y + bounds.h - a.y;
11763
+ const scale = Math.min(1, roomW / w, roomH / h);
11764
+ w *= scale;
11765
+ h *= scale;
11766
+ }
11767
+ return {
11768
+ x: px < a.x ? a.x - w : a.x,
11769
+ y: py < a.y ? a.y - h : a.y,
11770
+ w,
11771
+ h
11772
+ };
11773
+ }
11774
+ /** The eased share of the way at time `t` (0 to 1). */
11775
+ function ease(t, easing = "ease-in-out") {
11776
+ const c = Math.min(Math.max(t, 0), 1);
11777
+ return easing === "linear" ? c : c < .5 ? 2 * c * c : 1 - (-2 * c + 2) ** 2 / 2;
11778
+ }
11779
+ /** The rectangle part-way from `a` to `b` at time `t` (0 to 1), eased. Corner and size move together. */
11780
+ function lerpRect(a, b, t, easing = "ease-in-out") {
11781
+ const k = ease(t, easing);
11782
+ const mix = (p, q) => p + (q - p) * k;
11783
+ return {
11784
+ x: mix(a.x, b.x),
11785
+ y: mix(a.y, b.y),
11786
+ w: mix(a.w, b.w),
11787
+ h: mix(a.h, b.h)
11788
+ };
11789
+ }
11790
+ /** True when two rectangles are the same to the unit's thousandth. */
11791
+ var sameRect = (a, b) => [
11792
+ "x",
11793
+ "y",
11794
+ "w",
11795
+ "h"
11796
+ ].every((k) => Math.abs(a[k] - b[k]) < .001);
11797
+ // src/components/region-editor.tsx
11798
+ var TONE$1 = {
11799
+ neutral: {
11800
+ edge: "var(--foreground)",
11801
+ fill: "var(--muted)"
11802
+ },
11803
+ info: {
11804
+ edge: "var(--info)",
11805
+ fill: "var(--info-subtle)"
11806
+ },
11807
+ success: {
11808
+ edge: "var(--success)",
11809
+ fill: "var(--success-subtle)"
11810
+ },
11811
+ warning: {
11812
+ edge: "var(--warning)",
11813
+ fill: "var(--warning-subtle)"
11814
+ },
11815
+ danger: {
11816
+ edge: "var(--danger)",
11817
+ fill: "var(--danger-subtle)"
11818
+ }
11819
+ };
11820
+ var CURSOR = {
11821
+ n: "ns-resize",
11822
+ s: "ns-resize",
11823
+ e: "ew-resize",
11824
+ w: "ew-resize",
11825
+ ne: "nesw-resize",
11826
+ sw: "nesw-resize",
11827
+ nw: "nwse-resize",
11828
+ se: "nwse-resize"
11829
+ };
11830
+ var HANDLE_AT = {
11831
+ nw: "left-0 top-0 -translate-x-1/2 -translate-y-1/2",
11832
+ n: "left-1/2 top-0 -translate-x-1/2 -translate-y-1/2",
11833
+ ne: "right-0 top-0 translate-x-1/2 -translate-y-1/2",
11834
+ e: "right-0 top-1/2 translate-x-1/2 -translate-y-1/2",
11835
+ se: "right-0 bottom-0 translate-x-1/2 translate-y-1/2",
11836
+ s: "left-1/2 bottom-0 -translate-x-1/2 translate-y-1/2",
11837
+ sw: "left-0 bottom-0 -translate-x-1/2 translate-y-1/2",
11838
+ w: "left-0 top-1/2 -translate-x-1/2 -translate-y-1/2"
11839
+ };
11840
+ var round = (n) => format.integer(Math.round(n));
11841
+ /** A window said in words. */
11842
+ var describeRegion = (r) => `${r.label}: ${round(r.w)} wide by ${round(r.h)} high, ${round(r.x)} across and ${round(r.y)} down`;
11843
+ /** Draw and move one or two named windows on a picture, with pointer, keyboard and numbers kept in step; aspect and bounds hold through all three; two windows make a from/to move with a Watch preview. */
11844
+ function RegionEditor({ label, children, size, regions, onChange, selectedId, onSelectedChange, aspect, min, bounds, step, onDraw, mode = "single", onPreview, duration = 1500, easing = "ease-in-out", fields = true, unit = "px", defaults, className }) {
11845
+ const [w, h] = size;
11846
+ const limits = React.useMemo(() => ({
11847
+ bounds: bounds ?? {
11848
+ x: 0,
11849
+ y: 0,
11850
+ w,
11851
+ h
11852
+ },
11853
+ min: min ?? {
11854
+ w: w / 20,
11855
+ h: h / 20
11856
+ },
11857
+ aspect
11858
+ }), [
11859
+ bounds,
11860
+ min,
11861
+ w,
11862
+ h,
11863
+ aspect
11864
+ ]);
11865
+ const stride = step ?? Math.max(w, h) / 100;
11866
+ const [own, setOwn] = React.useState(regions[0]?.id ?? null);
11867
+ const selected = selectedId !== void 0 ? selectedId : own;
11868
+ const select = (id) => {
11869
+ setOwn(id);
11870
+ onSelectedChange?.(id);
11871
+ };
11872
+ const overlay = React.useRef(null);
11873
+ const [draft, setDraft] = React.useState(null);
11874
+ const [drawing, setDrawing] = React.useState(null);
11875
+ const gesture = React.useRef(null);
11876
+ const [said, setSaid] = React.useState("");
11877
+ const hintId = React.useId();
11878
+ const rectOf = (r) => draft?.id === r.id ? draft.rect : r;
11879
+ const shown = regions.map((r) => ({
11880
+ ...r,
11881
+ ...rectOf(r)
11882
+ }));
11883
+ const keep = (id, rect) => {
11884
+ const before = regions.find((r) => r.id === id);
11885
+ setDraft(null);
11886
+ if (before && !sameRect(before, rect)) onChange(regions.map((r) => r.id === id ? {
11887
+ ...r,
11888
+ ...rect
11889
+ } : r));
11890
+ };
11891
+ const say = (r) => setSaid(describeRegion(r));
11892
+ const unitsAt = (e) => {
11893
+ const box = overlay.current?.getBoundingClientRect();
11894
+ if (!box || !box.width || !box.height) return {
11895
+ x: 0,
11896
+ y: 0
11897
+ };
11898
+ return {
11899
+ x: (e.clientX - box.left) / box.width * w,
11900
+ y: (e.clientY - box.top) / box.height * h
11901
+ };
11902
+ };
11903
+ const capture = (e) => e.currentTarget.setPointerCapture?.(e.pointerId);
11904
+ const beginMove = (e, r) => {
11905
+ if (e.button !== 0) return;
11906
+ e.stopPropagation();
11907
+ capture(e);
11908
+ select(r.id);
11909
+ gesture.current = {
11910
+ kind: "move",
11911
+ id: r.id,
11912
+ start: rectOf(r),
11913
+ from: unitsAt(e)
11914
+ };
11915
+ };
11916
+ const beginResize = (e, r, handle) => {
11917
+ if (e.button !== 0) return;
11918
+ e.stopPropagation();
11919
+ capture(e);
11920
+ select(r.id);
11921
+ gesture.current = {
11922
+ kind: "resize",
11923
+ id: r.id,
11924
+ handle,
11925
+ start: rectOf(r),
11926
+ from: unitsAt(e)
11927
+ };
11928
+ };
11929
+ const beginDraw = (e) => {
11930
+ if (e.button !== 0 || !onDraw || e.target !== e.currentTarget) return;
11931
+ capture(e);
11932
+ gesture.current = {
11933
+ kind: "draw",
11934
+ from: unitsAt(e)
11935
+ };
11936
+ };
11937
+ const onMove = (e) => {
11938
+ const g = gesture.current;
11939
+ if (!g) return;
11940
+ const at = unitsAt(e);
11941
+ if (g.kind === "draw") setDrawing(drawRect(g.from, at, limits));
11942
+ else {
11943
+ const dx = at.x - g.from.x;
11944
+ const dy = at.y - g.from.y;
11945
+ setDraft({
11946
+ id: g.id,
11947
+ rect: g.kind === "move" ? moveRect(g.start, dx, dy, limits.bounds) : resizeRect(g.start, g.handle, dx, dy, limits)
11948
+ });
11949
+ }
11950
+ };
11951
+ const onUp = () => {
11952
+ const g = gesture.current;
11953
+ gesture.current = null;
11954
+ if (!g) return;
11955
+ if (g.kind === "draw") {
11956
+ const r = drawing;
11957
+ setDrawing(null);
11958
+ if (r && r.w >= limits.min.w && r.h >= limits.min.h) onDraw?.(r);
11959
+ } else if (draft) {
11960
+ keep(draft.id, draft.rect);
11961
+ const kept = regions.find((x) => x.id === draft.id);
11962
+ if (kept) say({
11963
+ ...kept,
11964
+ ...draft.rect
11965
+ });
11966
+ }
11967
+ };
11968
+ const keys = (e, r) => {
11969
+ const now = rectOf(r);
11970
+ if (e.key === "Escape") {
11971
+ if (draft?.id === r.id) {
11972
+ e.preventDefault();
11973
+ e.stopPropagation();
11974
+ setDraft(null);
11975
+ setSaid(`${r.label}: change undone`);
11976
+ }
11977
+ return;
11978
+ }
11979
+ if (e.key === "Enter") {
11980
+ if (draft?.id === r.id) {
11981
+ e.preventDefault();
11982
+ e.stopPropagation();
11983
+ keep(r.id, draft.rect);
11984
+ say({
11985
+ ...r,
11986
+ ...draft.rect
11987
+ });
11988
+ }
11989
+ return;
11990
+ }
11991
+ const dir = {
11992
+ ArrowLeft: [-1, 0],
11993
+ ArrowRight: [1, 0],
11994
+ ArrowUp: [0, -1],
11995
+ ArrowDown: [0, 1]
11996
+ }[e.key];
11997
+ if (!dir || e.altKey || e.ctrlKey || e.metaKey) return;
11998
+ e.preventDefault();
11999
+ e.stopPropagation();
12000
+ const next = e.shiftKey ? resizeRect(now, dir[0] ? "e" : "s", dir[0] * stride, dir[1] * stride, limits) : moveRect(now, dir[0] * stride, dir[1] * stride, limits.bounds);
12001
+ setDraft({
12002
+ id: r.id,
12003
+ rect: next
12004
+ });
12005
+ say({
12006
+ ...r,
12007
+ ...next
12008
+ });
12009
+ };
12010
+ const chosen = shown.find((r) => r.id === selected);
12011
+ const setSide = (key, value) => {
12012
+ if (!chosen || value === null) return;
12013
+ const cur = rectOf(chosen);
12014
+ const next = key === "x" || key === "y" ? moveRect(cur, key === "x" ? value - cur.x : 0, key === "y" ? value - cur.y : 0, limits.bounds) : resizeRect(cur, key === "w" ? "e" : "s", key === "w" ? value - cur.w : 0, key === "h" ? value - cur.h : 0, limits);
12015
+ keep(chosen.id, next);
12016
+ say({
12017
+ ...chosen,
12018
+ ...next
12019
+ });
12020
+ };
12021
+ const [watching, setWatching] = React.useState(null);
12022
+ const frame = React.useRef(0);
12023
+ const [from, to] = [shown[0], shown[1]];
12024
+ const stopWatch = React.useCallback(() => {
12025
+ cancelAnimationFrame(frame.current);
12026
+ setWatching(null);
12027
+ }, []);
12028
+ React.useEffect(() => () => cancelAnimationFrame(frame.current), []);
12029
+ const watch = () => {
12030
+ if (!from || !to) return;
12031
+ if (watching) return stopWatch();
12032
+ const a = {
12033
+ x: from.x,
12034
+ y: from.y,
12035
+ w: from.w,
12036
+ h: from.h
12037
+ };
12038
+ const b = {
12039
+ x: to.x,
12040
+ y: to.y,
12041
+ w: to.w,
12042
+ h: to.h
12043
+ };
12044
+ if (typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches) {
12045
+ onPreview?.(b, 1);
12046
+ setWatching(b);
12047
+ frame.current = window.setTimeout(() => setWatching(null), 600);
12048
+ return;
12049
+ }
12050
+ const began = performance.now();
12051
+ setWatching(a);
12052
+ const tick = (now) => {
12053
+ const t = Math.min((now - began) / duration, 1);
12054
+ const rect = lerpRect(a, b, t, easing);
12055
+ onPreview?.(rect, t);
12056
+ setWatching(rect);
12057
+ if (t < 1) frame.current = requestAnimationFrame(tick);
12058
+ else frame.current = window.setTimeout(() => setWatching(null), 400);
12059
+ };
12060
+ frame.current = requestAnimationFrame(tick);
12061
+ };
12062
+ const pct = (r) => ({
12063
+ left: `${r.x / w * 100}%`,
12064
+ top: `${r.y / h * 100}%`,
12065
+ width: `${r.w / w * 100}%`,
12066
+ height: `${r.h / h * 100}%`
12067
+ });
12068
+ const modified = defaults ? !(defaults.length === regions.length && defaults.every((d, i) => regions[i] && sameRect(d, regions[i]) && d.id === regions[i].id)) : false;
12069
+ return /* @__PURE__ */ jsxs("div", {
12070
+ className: cn("space-y-3", className),
12071
+ children: [
12072
+ /* @__PURE__ */ jsxs("div", {
12073
+ className: "relative overflow-hidden rounded-surface border border-border bg-surface-sunken",
12074
+ style: { aspectRatio: `${w} / ${h}` },
12075
+ children: [children, /* @__PURE__ */ jsxs("div", {
12076
+ ref: overlay,
12077
+ role: "group",
12078
+ "aria-label": label,
12079
+ "aria-describedby": hintId,
12080
+ className: cn("absolute inset-0 touch-none select-none", onDraw && "cursor-crosshair"),
12081
+ onPointerDown: beginDraw,
12082
+ onPointerMove: onMove,
12083
+ onPointerUp: onUp,
12084
+ onPointerCancel: () => {
12085
+ gesture.current = null;
12086
+ setDraft(null);
12087
+ setDrawing(null);
12088
+ },
12089
+ children: [
12090
+ mode === "move" && from && to && /* @__PURE__ */ jsxs("svg", {
12091
+ className: "pointer-events-none absolute inset-0 size-full",
12092
+ viewBox: `0 0 ${w} ${h}`,
12093
+ preserveAspectRatio: "none",
12094
+ "aria-hidden": true,
12095
+ children: [/* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("marker", {
12096
+ id: `${hintId}-arrow`,
12097
+ viewBox: "0 0 10 10",
12098
+ refX: "8",
12099
+ refY: "5",
12100
+ markerWidth: "6",
12101
+ markerHeight: "6",
12102
+ orient: "auto-start-reverse",
12103
+ children: /* @__PURE__ */ jsx("path", {
12104
+ d: "M0 0 10 5 0 10z",
12105
+ fill: "var(--foreground)"
12106
+ })
12107
+ }) }), /* @__PURE__ */ jsx("line", {
12108
+ x1: from.x + from.w / 2,
12109
+ y1: from.y + from.h / 2,
12110
+ x2: to.x + to.w / 2,
12111
+ y2: to.y + to.h / 2,
12112
+ stroke: "var(--foreground)",
12113
+ strokeWidth: 2,
12114
+ vectorEffect: "non-scaling-stroke",
12115
+ strokeDasharray: "6 4",
12116
+ markerEnd: `url(#${hintId}-arrow)`
12117
+ })]
12118
+ }),
12119
+ shown.map((r) => {
12120
+ const tone = TONE$1[r.tone ?? "neutral"];
12121
+ const active = r.id === selected;
12122
+ return /* @__PURE__ */ jsxs("div", {
12123
+ role: "group",
12124
+ "aria-roledescription": "region",
12125
+ "aria-label": describeRegion(r),
12126
+ tabIndex: 0,
12127
+ "data-region": r.id,
12128
+ "data-selected": active || void 0,
12129
+ onFocus: () => select(r.id),
12130
+ onBlur: (e) => {
12131
+ if (draft?.id === r.id && !e.currentTarget.contains(e.relatedTarget)) keep(r.id, draft.rect);
12132
+ },
12133
+ onKeyDown: (e) => keys(e, r),
12134
+ onPointerDown: (e) => beginMove(e, r),
12135
+ className: cn("absolute cursor-move border-2 outline-offset-2 transition-state", active ? "z-10" : "opacity-90"),
12136
+ style: {
12137
+ ...pct(r),
12138
+ borderColor: tone.edge,
12139
+ backgroundColor: `color-mix(in oklab, ${tone.fill} 35%, transparent)`,
12140
+ borderStyle: active ? "solid" : "dashed"
12141
+ },
12142
+ children: [/* @__PURE__ */ jsx("span", {
12143
+ className: "pointer-events-none absolute left-0 top-0 max-w-full -translate-y-full truncate rounded-t-control px-1.5 type-caption",
12144
+ style: {
12145
+ backgroundColor: tone.edge,
12146
+ color: "var(--background)"
12147
+ },
12148
+ children: r.label
12149
+ }), active && HANDLES.map((handle) => /* @__PURE__ */ jsx("span", {
12150
+ "aria-hidden": true,
12151
+ "data-handle": handle,
12152
+ onPointerDown: (e) => beginResize(e, r, handle),
12153
+ className: cn("absolute size-3 rounded-pill border-2 bg-background", HANDLE_AT[handle]),
12154
+ style: {
12155
+ borderColor: tone.edge,
12156
+ cursor: CURSOR[handle]
12157
+ }
12158
+ }, handle))]
12159
+ }, r.id);
12160
+ }),
12161
+ drawing && /* @__PURE__ */ jsx("div", {
12162
+ "aria-hidden": true,
12163
+ className: "pointer-events-none absolute border-2 border-dashed border-foreground bg-foreground/10",
12164
+ style: pct(drawing)
12165
+ }),
12166
+ watching && /* @__PURE__ */ jsx("div", {
12167
+ "aria-hidden": true,
12168
+ "data-preview": true,
12169
+ className: "pointer-events-none absolute z-20 border-2 border-foreground bg-foreground/15",
12170
+ style: pct(watching)
12171
+ })
12172
+ ]
12173
+ })]
12174
+ }),
12175
+ /* @__PURE__ */ jsxs("p", {
12176
+ id: hintId,
12177
+ className: "type-caption text-muted-foreground",
12178
+ children: [onDraw ? "Drag on the picture to draw a window. " : "", "Drag a window to move it, or its handles to resize. Keys: arrows move, Shift and arrows resize, Enter keeps, Escape undoes."]
12179
+ }),
12180
+ (mode === "move" || defaults && modified) && /* @__PURE__ */ jsxs("div", {
12181
+ className: "flex flex-wrap items-center gap-2",
12182
+ children: [mode === "move" && /* @__PURE__ */ jsxs(Button, {
12183
+ size: "sm",
12184
+ onPress: watch,
12185
+ disabled: !from || !to,
12186
+ children: [
12187
+ watching ? /* @__PURE__ */ jsx(Square, {}) : /* @__PURE__ */ jsx(Play, {}),
12188
+ " ",
12189
+ watching ? "Stop" : "Watch"
12190
+ ]
12191
+ }), defaults && modified && /* @__PURE__ */ jsx(Button, {
12192
+ size: "sm",
12193
+ variant: "ghost",
12194
+ onPress: () => {
12195
+ stopWatch();
12196
+ onChange(defaults);
12197
+ setSaid("Windows put back as they began");
12198
+ },
12199
+ children: "Reset"
12200
+ })]
12201
+ }),
12202
+ fields && chosen && /* @__PURE__ */ jsxs("div", {
12203
+ role: "group",
12204
+ "aria-label": `Position and size of ${chosen.label}`,
12205
+ className: "grid grid-cols-2 gap-3 sm:grid-cols-4",
12206
+ children: [
12207
+ /* @__PURE__ */ jsx(PropertyRow, {
12208
+ label: "Across",
12209
+ children: /* @__PURE__ */ jsx(NumberField, {
12210
+ value: Math.round(chosen.x),
12211
+ onChange: (v) => setSide("x", v),
12212
+ min: limits.bounds.x,
12213
+ max: limits.bounds.x + limits.bounds.w - chosen.w,
12214
+ unit,
12215
+ size: "sm"
12216
+ })
12217
+ }),
12218
+ /* @__PURE__ */ jsx(PropertyRow, {
12219
+ label: "Down",
12220
+ children: /* @__PURE__ */ jsx(NumberField, {
12221
+ value: Math.round(chosen.y),
12222
+ onChange: (v) => setSide("y", v),
12223
+ min: limits.bounds.y,
12224
+ max: limits.bounds.y + limits.bounds.h - chosen.h,
12225
+ unit,
12226
+ size: "sm"
12227
+ })
12228
+ }),
12229
+ /* @__PURE__ */ jsx(PropertyRow, {
12230
+ label: "Width",
12231
+ children: /* @__PURE__ */ jsx(NumberField, {
12232
+ value: Math.round(chosen.w),
12233
+ onChange: (v) => setSide("w", v),
12234
+ min: Math.ceil(limits.min.w),
12235
+ max: Math.floor(limits.bounds.w),
12236
+ unit,
12237
+ size: "sm"
12238
+ })
12239
+ }),
12240
+ /* @__PURE__ */ jsx(PropertyRow, {
12241
+ label: "Height",
12242
+ children: /* @__PURE__ */ jsx(NumberField, {
12243
+ value: Math.round(chosen.h),
12244
+ onChange: (v) => setSide("h", v),
12245
+ min: Math.ceil(limits.min.h),
12246
+ max: Math.floor(limits.bounds.h),
12247
+ unit,
12248
+ size: "sm"
12249
+ })
12250
+ })
12251
+ ]
12252
+ }),
12253
+ /* @__PURE__ */ jsx("div", {
12254
+ role: "status",
12255
+ "aria-live": "polite",
12256
+ className: "sr-only",
12257
+ children: said
12258
+ })
12259
+ ]
12260
+ });
12261
+ }
12262
+ // src/lib/sequence.ts
12263
+ var EPS = 1e-9;
12264
+ /** The grid point nearest to `time`, or `time` itself when there is no grid. */
12265
+ function snapToGrid(time, grid) {
12266
+ if (grid === void 0) return time;
12267
+ if (typeof grid === "number") return grid > 0 ? tidy(Math.round(time / grid) * grid) : time;
12268
+ let best = time;
12269
+ let gap = Infinity;
12270
+ for (const p of grid) if (Math.abs(p - time) < gap) [best, gap] = [p, Math.abs(p - time)];
12271
+ return best;
12272
+ }
12273
+ /** The next grid point after `time` in a direction (`1` later, `-1` earlier); `fallback` is the step when there is no grid. A point `time` is already on is stepped past. */
12274
+ function stepOnGrid(time, dir, grid, fallback) {
12275
+ if (grid === void 0) return tidy(time + dir * fallback);
12276
+ if (typeof grid === "number") {
12277
+ if (grid <= 0) return tidy(time + dir * fallback);
12278
+ return tidy((dir > 0 ? Math.floor(time / grid + EPS) + 1 : Math.ceil(time / grid - EPS) - 1) * grid);
12279
+ }
12280
+ const points = [...grid].sort((a, b) => a - b);
12281
+ return (dir > 0 ? points.find((p) => p > time + EPS) : [...points].reverse().find((p) => p < time - EPS)) ?? tidy(time + dir * fallback);
12282
+ }
12283
+ /** Grid points inside `[from, to]`, for drawing on a ruler. At most `limit`, so a fine grid on a long axis stays cheap. */
12284
+ function gridPoints(grid, from, to, limit = 2e3) {
12285
+ if (grid === void 0) return [];
12286
+ if (typeof grid !== "number") return grid.filter((p) => p >= from - EPS && p <= to + EPS).slice(0, limit);
12287
+ if (grid <= 0) return [];
12288
+ const out = [];
12289
+ for (let i = Math.ceil(from / grid - EPS); i * grid <= to + EPS && out.length < limit; i++) out.push(tidy(i * grid) || 0);
12290
+ return out;
12291
+ }
12292
+ /** Puts `time` inside the room, and says which end held it (with the app's reason) when one did. */
12293
+ function clampToRoom(time, room) {
12294
+ const t = clamp$1(time, room.min, room.max);
12295
+ if (t > time + EPS) return {
12296
+ time: t,
12297
+ limit: {
12298
+ side: "min",
12299
+ at: room.min,
12300
+ reason: room.minReason
12301
+ }
12302
+ };
12303
+ if (t < time - EPS) return {
12304
+ time: t,
12305
+ limit: {
12306
+ side: "max",
12307
+ at: room.max,
12308
+ reason: room.maxReason
12309
+ }
12310
+ };
12311
+ return {
12312
+ time: t,
12313
+ limit: null
12314
+ };
12315
+ }
12316
+ /** Where a dragged cut lands: held by the room (saying which end, if the pointer is beyond it), otherwise snapped to the grid, and never to a grid point outside the room. */
12317
+ function settleCut(wanted, grid, room) {
12318
+ const held = clampToRoom(wanted, room);
12319
+ const snapped = snapToGrid(held.time, grid);
12320
+ return {
12321
+ time: snapped >= room.min - EPS && snapped <= room.max + EPS ? snapped : held.time,
12322
+ limit: held.limit
12323
+ };
12324
+ }
12325
+ // src/components/sequence-timeline.tsx
12326
+ var seconds = (n) => `${tidy(Math.round(n * 10) / 10)} s`;
12327
+ var at = (t) => tickLabel(t, .1);
12328
+ /** A gapless strip of windows whose cuts are dragged or stepped, snapping to a beat grid inside the room the app gives; each cut is a slider that announces both windows' new lengths; Shift+click chooses a run. */
12329
+ function SequenceTimeline({ label, items, zoom, onCutChange, room, minLength = .1, grid, step = .1, selected = [], onSelectRange, renderItem, height = "5rem", className }) {
12330
+ const start = items[0]?.start ?? 0;
12331
+ const end = items[items.length - 1]?.end ?? 0;
12332
+ const span = Math.max(end - start, 1e-6);
12333
+ const track = React.useRef(null);
12334
+ const [fit, setFit] = React.useState(800);
12335
+ React.useLayoutEffect(() => {
12336
+ const el = track.current?.parentElement;
12337
+ if (!el || typeof ResizeObserver === "undefined") return;
12338
+ const read = () => setFit(el.clientWidth || 800);
12339
+ read();
12340
+ const ro = new ResizeObserver(read);
12341
+ ro.observe(el);
12342
+ return () => ro.disconnect();
12343
+ }, []);
12344
+ const pxPerUnit = zoom ?? fit / span;
12345
+ const [drag, setDrag] = React.useState(null);
12346
+ const [said, setSaid] = React.useState("");
12347
+ const anchor = React.useRef(null);
12348
+ const roomFor = React.useCallback((i) => room?.(i) ?? {
12349
+ min: items[i].start + minLength,
12350
+ max: items[i + 1].end - minLength
12351
+ }, [
12352
+ room,
12353
+ items,
12354
+ minLength
12355
+ ]);
12356
+ const view = items.map((it, i) => ({
12357
+ ...it,
12358
+ start: drag && drag.index === i - 1 ? drag.time : it.start,
12359
+ end: drag && drag.index === i ? drag.time : it.end
12360
+ }));
12361
+ const change = (i, time) => ({
12362
+ before: {
12363
+ ...items[i],
12364
+ end: time
12365
+ },
12366
+ after: {
12367
+ ...items[i + 1],
12368
+ start: time
12369
+ }
12370
+ });
12371
+ const words = (i, time) => `Cut ${i + 1} moved to ${at(time)}. Window ${i + 1} is ${seconds(time - items[i].start)}, window ${i + 2} is ${seconds(items[i + 1].end - time)}.`;
12372
+ const timeAt = (clientX) => {
12373
+ const box = track.current?.getBoundingClientRect();
12374
+ if (!box || !box.width) return start;
12375
+ return start + (clientX - box.left) / box.width * span;
12376
+ };
12377
+ const keys = (e, i) => {
12378
+ const r = roomFor(i);
12379
+ const now = items[i].end;
12380
+ let target = null;
12381
+ if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
12382
+ const dir = e.key === "ArrowRight" ? 1 : -1;
12383
+ target = e.shiftKey ? now + dir : stepOnGrid(now, dir, grid, step);
12384
+ } else if (e.key === "Home") target = r.min;
12385
+ else if (e.key === "End") target = r.max;
12386
+ if (target === null) return;
12387
+ e.preventDefault();
12388
+ const { time, limit } = clampToRoom(tidy(target), r);
12389
+ if (Math.abs(time - now) < 1e-9) {
12390
+ const why = limit?.reason ?? (e.key === "End" || e.key === "ArrowRight" ? r.maxReason : r.minReason);
12391
+ setSaid(`Cut ${i + 1} stays at ${at(now)}.${why ? ` ${why}` : ""}`);
12392
+ return;
12393
+ }
12394
+ onCutChange(i, time, change(i, time));
12395
+ setSaid(words(i, time) + (limit?.reason ? ` ${limit.reason}` : ""));
12396
+ };
12397
+ const begin = (e, i) => {
12398
+ if (e.button !== 0) return;
12399
+ e.currentTarget.setPointerCapture?.(e.pointerId);
12400
+ setDrag({
12401
+ index: i,
12402
+ time: items[i].end,
12403
+ refused: null
12404
+ });
12405
+ };
12406
+ const drive = (e) => {
12407
+ if (!drag) return;
12408
+ const { time, limit } = settleCut(timeAt(e.clientX), grid, roomFor(drag.index));
12409
+ setDrag({
12410
+ index: drag.index,
12411
+ time,
12412
+ refused: limit ? `Cut ${drag.index + 1} stops at ${at(limit.at)}.${limit.reason ? ` ${limit.reason}` : ""}` : null
12413
+ });
12414
+ };
12415
+ const release = () => {
12416
+ if (!drag) return;
12417
+ const d = drag;
12418
+ setDrag(null);
12419
+ if (Math.abs(d.time - items[d.index].end) > 1e-9) {
12420
+ onCutChange(d.index, d.time, change(d.index, d.time));
12421
+ setSaid(words(d.index, d.time) + (d.refused ? ` ${d.refused}` : ""));
12422
+ } else if (d.refused) setSaid(d.refused);
12423
+ };
12424
+ const step0 = tickStep(pxPerUnit);
12425
+ const ticks = ticksBetween(start, end, step0);
12426
+ const all = gridPoints(grid, start, end);
12427
+ const beats = (end - start) / Math.max(all.length, 1) * pxPerUnit >= 4 ? all : [];
12428
+ const pct = (t) => `${(t - start) / span * 100}%`;
12429
+ const choose = (e, id) => {
12430
+ if (!onSelectRange) return;
12431
+ const here = items.findIndex((x) => x.id === id);
12432
+ const from = anchor.current ? items.findIndex((x) => x.id === anchor.current) : -1;
12433
+ if (e.shiftKey && from >= 0) {
12434
+ const [a, b] = from <= here ? [from, here] : [here, from];
12435
+ onSelectRange(items.slice(a, b + 1).map((x) => x.id));
12436
+ } else {
12437
+ anchor.current = id;
12438
+ onSelectRange([id]);
12439
+ }
12440
+ };
12441
+ return /* @__PURE__ */ jsxs("div", {
12442
+ className: cn("min-w-0", className),
12443
+ children: [
12444
+ /* @__PURE__ */ jsx("div", {
12445
+ role: "group",
12446
+ "aria-label": label,
12447
+ className: "overflow-x-auto pb-2",
12448
+ children: /* @__PURE__ */ jsxs("div", {
12449
+ ref: track,
12450
+ className: "relative",
12451
+ style: { width: zoom ? `${span * zoom}px` : "100%" },
12452
+ children: [/* @__PURE__ */ jsxs("div", {
12453
+ "aria-hidden": true,
12454
+ className: "relative h-6 border-b border-border",
12455
+ children: [ticks.map((t) => /* @__PURE__ */ jsx("span", {
12456
+ className: "absolute top-0 -translate-x-1/2 type-caption tabular-nums text-muted-foreground",
12457
+ style: { left: pct(t) },
12458
+ children: tickLabel(t, step0)
12459
+ }, t)), beats.map((p) => /* @__PURE__ */ jsx("span", {
12460
+ "data-beat": true,
12461
+ className: "absolute bottom-0 h-1.5 w-px bg-border",
12462
+ style: { left: pct(p) }
12463
+ }, `b${p}`))]
12464
+ }), /* @__PURE__ */ jsxs("div", {
12465
+ className: "relative mt-1",
12466
+ style: { height },
12467
+ children: [view.map((it) => {
12468
+ const on = selected.includes(it.id);
12469
+ return /* @__PURE__ */ jsx("button", {
12470
+ type: "button",
12471
+ "aria-pressed": on,
12472
+ "aria-label": `${it.label}, ${at(it.start)} to ${at(it.end)}`,
12473
+ onClick: (e) => choose(e, it.id),
12474
+ className: cn("absolute inset-y-0 min-w-0 cursor-pointer overflow-hidden rounded-control border px-1.5 text-left transition-state", on ? "border-primary bg-primary/10" : "border-border bg-muted hover:bg-muted/70"),
12475
+ style: {
12476
+ left: pct(it.start),
12477
+ width: `calc(${(it.end - it.start) / span * 100}% - 2px)`
12478
+ },
12479
+ children: renderItem ? renderItem(it, on) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
12480
+ className: "block truncate type-label",
12481
+ children: it.label
12482
+ }), /* @__PURE__ */ jsx("span", {
12483
+ className: "block truncate type-caption tabular-nums text-muted-foreground",
12484
+ children: seconds(it.end - it.start)
12485
+ })] })
12486
+ }, it.id);
12487
+ }), items.slice(0, -1).map((it, i) => {
12488
+ const r = roomFor(i);
12489
+ const now = drag?.index === i ? drag.time : it.end;
12490
+ return /* @__PURE__ */ jsx("div", {
12491
+ role: "slider",
12492
+ tabIndex: 0,
12493
+ "aria-label": `Cut ${i + 1}, between window ${i + 1} and window ${i + 2}`,
12494
+ "aria-orientation": "horizontal",
12495
+ "aria-valuemin": r.min,
12496
+ "aria-valuemax": r.max,
12497
+ "aria-valuenow": now,
12498
+ "aria-valuetext": at(now),
12499
+ "data-cut": i,
12500
+ onKeyDown: (e) => keys(e, i),
12501
+ onPointerDown: (e) => begin(e, i),
12502
+ onPointerMove: drive,
12503
+ onPointerUp: release,
12504
+ onPointerCancel: () => setDrag(null),
12505
+ className: "group absolute inset-y-0 z-10 w-3 -translate-x-1/2 cursor-ew-resize touch-none outline-offset-1",
12506
+ style: { left: pct(now) },
12507
+ children: /* @__PURE__ */ jsx("span", { className: "absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 rounded-pill bg-foreground group-hover:w-1 group-focus-visible:w-1" })
12508
+ }, `cut${it.id}`);
12509
+ })]
12510
+ })]
12511
+ })
12512
+ }),
12513
+ drag?.refused && /* @__PURE__ */ jsxs("p", {
12514
+ className: "mt-1 flex items-center gap-1.5 type-body-sm text-danger",
12515
+ children: [
12516
+ /* @__PURE__ */ jsx(Ban, {
12517
+ className: "size-4 shrink-0",
12518
+ "aria-hidden": true
12519
+ }),
12520
+ " ",
12521
+ drag.refused
12522
+ ]
12523
+ }),
12524
+ /* @__PURE__ */ jsx("div", {
12525
+ role: "status",
12526
+ "aria-live": "polite",
12527
+ className: "sr-only",
12528
+ children: said
12529
+ })
12530
+ ]
12531
+ });
12532
+ }
12533
+ // src/components/tree.tsx
12534
+ var Context = React.createContext(null);
12535
+ var useCtx = () => React.useContext(Context);
12536
+ var NOTE = "\0";
12537
+ var isNote = (key) => key.includes(NOTE);
12538
+ var ROW = "flex min-h-(--control-h-sm) min-w-0 items-center gap-1 rounded-control pr-2 type-body-sm";
12539
+ function Row$1({ level, children }) {
12540
+ return /* @__PURE__ */ jsx("div", {
12541
+ className: ROW,
12542
+ style: { paddingInlineStart: `${level * 1.25 + .25}rem` },
12543
+ children
12544
+ });
12545
+ }
12546
+ function Node$1({ node }) {
12547
+ const c = useCtx();
12548
+ const key = c.nodeKey(node);
12549
+ c.nodes.set(key, node);
12550
+ const branch = c.isBranch ? c.isBranch(node) : true;
12551
+ const open = branch && c.expanded.isOpen(key);
12552
+ const name = c.nodeLabel(node);
12553
+ return /* @__PURE__ */ jsxs(TreeItem, {
12554
+ id: key,
12555
+ textValue: name,
12556
+ hasChildItems: branch,
12557
+ className: "outline-none",
12558
+ children: [/* @__PURE__ */ jsx(TreeItemContent, { children: ({ level, isSelected, isExpanded }) => /* @__PURE__ */ jsxs("div", {
12559
+ title: name,
12560
+ className: cn(ROW, "cursor-pointer outline-offset-[-2px] hover:bg-muted", isSelected && "bg-surface-sunken font-medium"),
12561
+ style: { paddingInlineStart: `${(level - 1) * 1.25 + .25}rem` },
12562
+ "data-selected": isSelected || void 0,
12563
+ children: [
12564
+ branch ? /* @__PURE__ */ jsx(Button$1, {
12565
+ slot: "chevron",
12566
+ className: "grid size-6 shrink-0 place-items-center rounded-control text-muted-foreground",
12567
+ children: /* @__PURE__ */ jsx(ChevronRight, {
12568
+ "aria-hidden": true,
12569
+ className: cn("size-4", isExpanded && "rotate-90")
12570
+ })
12571
+ }) : /* @__PURE__ */ jsx("span", {
12572
+ "aria-hidden": true,
12573
+ className: "size-6 shrink-0"
12574
+ }),
12575
+ branch ? isExpanded ? /* @__PURE__ */ jsx(FolderOpen, {
12576
+ "aria-hidden": true,
12577
+ className: "size-4 shrink-0 text-muted-foreground"
12578
+ }) : /* @__PURE__ */ jsx(Folder, {
12579
+ "aria-hidden": true,
12580
+ className: "size-4 shrink-0 text-muted-foreground"
12581
+ }) : null,
12582
+ /* @__PURE__ */ jsx("span", {
12583
+ className: "min-w-0 flex-1 truncate",
12584
+ children: c.renderNode ? c.renderNode(node, {
12585
+ expanded: isExpanded,
12586
+ selected: isSelected,
12587
+ level,
12588
+ branch
12589
+ }) : name
12590
+ })
12591
+ ]
12592
+ }) }), open ? /* @__PURE__ */ jsx(Children, { node }) : branch && /* @__PURE__ */ jsx(ClosedChild, { id: `${key}${NOTE}closed` })]
12593
+ });
12594
+ }
12595
+ function ClosedChild({ id }) {
12596
+ return /* @__PURE__ */ jsx(TreeItem, {
12597
+ id,
12598
+ textValue: "",
12599
+ isDisabled: true,
12600
+ children: /* @__PURE__ */ jsx(TreeItemContent, { children: () => null })
12601
+ }, "closed");
12602
+ }
12603
+ function Nodes({ nodes }) {
12604
+ const c = useCtx();
12605
+ return /* @__PURE__ */ jsx(Fragment, { children: nodes.map((n) => /* @__PURE__ */ jsx(Node$1, { node: n }, c.nodeKey(n))) });
12606
+ }
12607
+ function Children({ node }) {
12608
+ const c = useCtx();
12609
+ const key = c.nodeKey(node);
12610
+ const load = c.useChildren(node);
12611
+ if (load.status === "loading") return /* @__PURE__ */ jsx(TreeItem, {
12612
+ id: `${key}${NOTE}loading`,
12613
+ textValue: "Loading",
12614
+ isDisabled: true,
12615
+ className: "outline-none",
12616
+ children: /* @__PURE__ */ jsx(TreeItemContent, { children: ({ level }) => /* @__PURE__ */ jsxs(Row$1, {
12617
+ level: level - 1,
12618
+ children: [
12619
+ /* @__PURE__ */ jsx("span", {
12620
+ "aria-hidden": true,
12621
+ className: "size-6 shrink-0"
12622
+ }),
12623
+ /* @__PURE__ */ jsx("span", {
12624
+ role: "status",
12625
+ className: "sr-only",
12626
+ children: "Loading"
12627
+ }),
12628
+ c.loadingRow ?? /* @__PURE__ */ jsx("span", {
12629
+ "aria-hidden": true,
12630
+ className: "h-3 w-32 animate-pulse rounded-pill bg-muted"
12631
+ })
12632
+ ]
12633
+ }) })
12634
+ }, "loading");
12635
+ if (load.status === "error") return /* @__PURE__ */ jsx(TreeItem, {
12636
+ id: `${key}${NOTE}error`,
12637
+ textValue: load.message,
12638
+ className: "outline-none",
12639
+ children: /* @__PURE__ */ jsx(TreeItemContent, { children: ({ level }) => /* @__PURE__ */ jsxs(Row$1, {
12640
+ level: level - 1,
12641
+ children: [
12642
+ /* @__PURE__ */ jsx(CircleAlert, {
12643
+ "aria-hidden": true,
12644
+ className: "size-4 shrink-0 text-danger"
12645
+ }),
12646
+ /* @__PURE__ */ jsx("span", {
12647
+ className: "min-w-0 flex-1 truncate text-danger",
12648
+ title: load.message,
12649
+ children: load.message
12650
+ }),
12651
+ /* @__PURE__ */ jsx(Button, {
12652
+ size: "sm",
12653
+ onPress: load.retry,
12654
+ children: "Try again"
12655
+ })
12656
+ ]
12657
+ }) })
12658
+ }, "error");
12659
+ if (load.data.length === 0) return /* @__PURE__ */ jsx(TreeItem, {
12660
+ id: `${key}${NOTE}empty`,
12661
+ textValue: c.emptyRow,
12662
+ isDisabled: true,
12663
+ className: "outline-none",
12664
+ children: /* @__PURE__ */ jsx(TreeItemContent, { children: ({ level }) => /* @__PURE__ */ jsxs(Row$1, {
12665
+ level: level - 1,
12666
+ children: [/* @__PURE__ */ jsx("span", {
12667
+ "aria-hidden": true,
12668
+ className: "size-6 shrink-0"
12669
+ }), /* @__PURE__ */ jsx("span", {
12670
+ className: "text-muted-foreground",
12671
+ children: c.emptyRow
12672
+ })]
12673
+ }) })
12674
+ }, "empty");
12675
+ return /* @__PURE__ */ jsx(Nodes, { nodes: load.data });
12676
+ }
12677
+ /** A hierarchy whose children load as each node opens (a `useChildren` hook per open node): a skeleton row, a Try again row and an "empty" row per node, type-ahead and arrow keys, single selection, open state optionally in the URL, always virtualised. */
12678
+ function Tree({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderNode, selected, onSelect, expanded, loadingRow, emptyRow, height = "24rem", className }) {
12679
+ const nodes = React.useRef(/* @__PURE__ */ new Map()).current;
12680
+ const ctx = {
12681
+ useChildren,
12682
+ nodeKey,
12683
+ nodeLabel,
12684
+ isBranch,
12685
+ renderNode,
12686
+ selected,
12687
+ onSelect,
12688
+ expanded,
12689
+ loadingRow,
12690
+ emptyRow,
12691
+ nodes
12692
+ };
12693
+ if (roots.status === "loading") return /* @__PURE__ */ jsx("div", {
12694
+ role: "status",
12695
+ "aria-label": `${label}: loading`,
12696
+ className: cn("space-y-2 p-2", className),
12697
+ children: [
12698
+ 0,
12699
+ 1,
12700
+ 2,
12701
+ 3
12702
+ ].map((i) => /* @__PURE__ */ jsx("div", {
12703
+ "aria-hidden": true,
12704
+ className: "h-4 animate-pulse rounded-pill bg-muted",
12705
+ style: { width: `${70 - i * 10}%` }
12706
+ }, i))
12707
+ });
12708
+ if (roots.status === "error") return /* @__PURE__ */ jsxs("div", {
12709
+ role: "alert",
12710
+ className: cn("flex items-center gap-3 rounded-surface bg-danger-subtle p-3 text-danger", className),
12711
+ children: [
12712
+ /* @__PURE__ */ jsx(CircleAlert, {
12713
+ "aria-hidden": true,
12714
+ className: "size-5 shrink-0"
12715
+ }),
12716
+ /* @__PURE__ */ jsx("p", {
12717
+ className: "min-w-0 flex-1 type-body-sm",
12718
+ children: roots.message
12719
+ }),
12720
+ /* @__PURE__ */ jsx(Button, {
12721
+ size: "sm",
12722
+ onPress: roots.retry,
12723
+ children: "Try again"
12724
+ })
12725
+ ]
12726
+ });
12727
+ const choose = (keys) => {
12728
+ const first = keys === "all" ? void 0 : [...keys][0];
12729
+ if (first === void 0 || isNote(String(first))) return;
12730
+ const key = String(first);
12731
+ const node = nodes.get(key);
12732
+ if (node !== void 0) onSelect(key, node);
12733
+ };
12734
+ const tree = /* @__PURE__ */ jsx(Tree$1, {
12735
+ "aria-label": label,
12736
+ selectionMode: "single",
12737
+ disallowEmptySelection: true,
12738
+ selectedKeys: selected === null ? [] : [selected],
12739
+ onSelectionChange: choose,
12740
+ expandedKeys: expanded.expanded,
12741
+ onExpandedChange: (keys) => expanded.onChange(new Set([...keys].map(String).filter((k) => !isNote(k)))),
12742
+ renderEmptyState: () => /* @__PURE__ */ jsx("p", {
12743
+ className: "p-3 type-body-sm text-muted-foreground",
12744
+ children: emptyRow
12745
+ }),
12746
+ className: cn("min-w-0 overflow-y-auto outline-none", className),
12747
+ style: { maxHeight: height },
12748
+ "data-strata-scroll": "",
12749
+ children: /* @__PURE__ */ jsx(Nodes, { nodes: roots.data })
12750
+ });
12751
+ return /* @__PURE__ */ jsx(Context.Provider, {
12752
+ value: ctx,
12753
+ children: /* @__PURE__ */ jsx(Virtualizer, {
12754
+ layout: ListLayout,
12755
+ layoutOptions: { rowHeight: 32 },
12756
+ children: tree
12757
+ })
12758
+ });
12759
+ }
12760
+ // src/components/folder-picker.tsx
12761
+ var SEP = "/";
12762
+ var parts = (path) => path.split(SEP).filter(Boolean);
12763
+ var join = (parent, name) => `${parent === SEP ? "" : parent}${SEP}${name}`;
12764
+ /** The parent of a path, or `null` at the top. */
12765
+ var parentOf = (path) => {
12766
+ const p = parts(path);
12767
+ return p.length <= 1 ? null : `${SEP}${p.slice(0, -1).join(SEP)}`;
12768
+ };
12769
+ /** Every folder from the top down to `path`, which the tree must have open to show it. */
12770
+ var ancestorsOf = (path) => parts(path).slice(0, -1).map((_, i, a) => `${SEP}${a.slice(0, i + 1).join(SEP)}`);
12771
+ /** A server folder chooser: a lazy tree, a breadcrumb that is also editable text, Up, recents, a New folder field that shows the server's refusal, and Choose this folder as the one filled button. */
12772
+ function FolderPicker({ label, useFolders, value, onChange, onChoose, expanded, recent, onCreate, topLabel = "Top", emptyRow = "No folders", height = "18rem", className }) {
12773
+ const roots = useFolders(null);
12774
+ const [editing, setEditing] = React.useState(false);
12775
+ const [text, setText] = React.useState("");
12776
+ const go = (path) => onChange(path);
12777
+ React.useEffect(() => {
12778
+ if (!value) return;
12779
+ const open = ancestorsOf(value).filter((a) => !expanded.isOpen(a));
12780
+ if (open.length) expanded.onChange(/* @__PURE__ */ new Set([...expanded.expanded, ...open]));
12781
+ }, [value, expanded]);
12782
+ const [name, setName] = React.useState("");
12783
+ const created = useAsyncAction(async (name) => {
12784
+ if (!value) return;
12785
+ await onCreate?.(value, name);
12786
+ setName("");
12787
+ go(join(value, name));
12788
+ expanded.setOpen(value, true);
12789
+ }, { validate: (name) => name.trim() ? void 0 : { name: "Name the new folder." } });
12790
+ const crumbs = value ? parts(value) : [];
12791
+ return /* @__PURE__ */ jsxs("section", {
12792
+ "aria-label": label,
12793
+ className: cn("space-y-3", className),
12794
+ children: [
12795
+ /* @__PURE__ */ jsxs("div", {
12796
+ className: "flex flex-wrap items-center gap-2",
12797
+ children: [/* @__PURE__ */ jsx(IconButton, {
12798
+ icon: ArrowUp,
12799
+ label: "Up one folder",
12800
+ onPress: () => go(value ? parentOf(value) : null),
12801
+ disabled: !value
12802
+ }), editing ? /* @__PURE__ */ jsxs("form", {
12803
+ className: "flex min-w-0 flex-1 items-center gap-2",
12804
+ onSubmit: (e) => {
12805
+ e.preventDefault();
12806
+ const typed = text.trim();
12807
+ go(typed ? (typed.startsWith(SEP) ? typed : `${SEP}${typed}`).replace(/\/+$/, "") || SEP : null);
12808
+ setEditing(false);
12809
+ },
12810
+ children: [/* @__PURE__ */ jsx(Input, {
12811
+ "aria-label": "Folder path",
12812
+ value: text,
12813
+ autoFocus: true,
12814
+ onChange: (e) => setText(e.target.value),
12815
+ onKeyDown: (e) => e.key === "Escape" && (e.stopPropagation(), setEditing(false)),
12816
+ className: "min-w-0 flex-1 font-mono",
12817
+ size: "sm"
12818
+ }), /* @__PURE__ */ jsx(Button, {
12819
+ size: "sm",
12820
+ type: "submit",
12821
+ children: "Go"
12822
+ })]
12823
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("nav", {
12824
+ "aria-label": "Folder path",
12825
+ className: "min-w-0 flex-1",
12826
+ children: /* @__PURE__ */ jsxs("ol", {
12827
+ className: "flex flex-wrap items-center gap-x-1 type-body-sm",
12828
+ children: [/* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(Button, {
12829
+ size: "sm",
12830
+ variant: "ghost",
12831
+ onPress: () => go(null),
12832
+ "aria-current": value ? void 0 : "location",
12833
+ children: topLabel
12834
+ }) }), crumbs.map((c, i) => {
12835
+ const path = `${SEP}${crumbs.slice(0, i + 1).join(SEP)}`;
12836
+ const last = i === crumbs.length - 1;
12837
+ return /* @__PURE__ */ jsxs("li", {
12838
+ className: "flex min-w-0 items-center gap-1",
12839
+ children: [/* @__PURE__ */ jsx("span", {
12840
+ "aria-hidden": true,
12841
+ className: "text-muted-foreground",
12842
+ children: "/"
12843
+ }), /* @__PURE__ */ jsx(Button, {
12844
+ size: "sm",
12845
+ variant: "ghost",
12846
+ title: path,
12847
+ onPress: () => go(path),
12848
+ "aria-current": last ? "location" : void 0,
12849
+ className: cn("max-w-48 truncate", last && "font-medium"),
12850
+ children: c
12851
+ })]
12852
+ }, path);
12853
+ })]
12854
+ })
12855
+ }), /* @__PURE__ */ jsx(IconButton, {
12856
+ icon: Pencil,
12857
+ label: "Edit path",
12858
+ onPress: () => {
12859
+ setText(value ?? "");
12860
+ setEditing(true);
12861
+ }
12862
+ })] })]
12863
+ }),
12864
+ /* @__PURE__ */ jsx("div", {
12865
+ className: "rounded-surface border border-border",
12866
+ children: /* @__PURE__ */ jsx(Tree, {
12867
+ label: `${label}: folders`,
12868
+ roots,
12869
+ useChildren: (f) => useFolders(f.path),
12870
+ nodeKey: (f) => f.path,
12871
+ nodeLabel: (f) => f.name,
12872
+ renderNode: (f) => /* @__PURE__ */ jsxs("span", {
12873
+ className: "flex min-w-0 items-baseline gap-2",
12874
+ children: [/* @__PURE__ */ jsx("span", {
12875
+ className: "truncate",
12876
+ children: f.name
12877
+ }), f.count !== void 0 && /* @__PURE__ */ jsx("span", {
12878
+ className: "type-caption tabular-nums text-muted-foreground",
12879
+ children: format.integer(f.count)
12880
+ })]
12881
+ }),
12882
+ selected: value,
12883
+ onSelect: (key) => onChange(key),
12884
+ expanded,
12885
+ emptyRow,
12886
+ height
12887
+ })
12888
+ }),
12889
+ recent && recent.length > 0 && /* @__PURE__ */ jsxs("div", {
12890
+ role: "group",
12891
+ "aria-label": "Recent folders",
12892
+ className: "flex flex-wrap items-center gap-2",
12893
+ children: [/* @__PURE__ */ jsx("span", {
12894
+ className: "type-caption text-muted-foreground",
12895
+ children: "Recent"
12896
+ }), recent.map((r) => /* @__PURE__ */ jsx(Button, {
12897
+ size: "sm",
12898
+ variant: "outline",
12899
+ title: r,
12900
+ onPress: () => go(r),
12901
+ className: "max-w-64 truncate font-mono",
12902
+ children: r
12903
+ }, r))]
12904
+ }),
12905
+ onCreate && /* @__PURE__ */ jsx("form", {
12906
+ onSubmit: (e) => {
12907
+ e.preventDefault();
12908
+ created.run(name.trim());
12909
+ },
12910
+ children: /* @__PURE__ */ jsx(Field, {
12911
+ label: "New folder",
12912
+ hint: value ? `It will be made in ${value}.` : "Open a folder first.",
12913
+ error: created.fieldErrors.name ?? (created.phase === "error" ? created.error : void 0),
12914
+ action: /* @__PURE__ */ jsx(AsyncButton, {
12915
+ type: "submit",
12916
+ phase: created.phase,
12917
+ error: created.error,
12918
+ disabled: !value,
12919
+ labels: {
12920
+ idle: "Make folder",
12921
+ pending: "Making…",
12922
+ done: "Made"
12923
+ }
12924
+ }),
12925
+ children: /* @__PURE__ */ jsx(Input, {
12926
+ value: name,
12927
+ disabled: !value,
12928
+ onChange: (e) => {
12929
+ setName(e.target.value);
12930
+ created.clearFieldError("name");
12931
+ }
12932
+ })
12933
+ })
12934
+ }),
12935
+ /* @__PURE__ */ jsx("div", {
12936
+ className: "flex justify-end",
12937
+ children: /* @__PURE__ */ jsx(Button, {
12938
+ variant: "default",
12939
+ disabled: !value,
12940
+ onPress: () => value && onChoose(value),
12941
+ children: "Choose this folder"
12942
+ })
12943
+ })
12944
+ ]
12945
+ });
12946
+ }
12947
+ // src/lib/marks.ts
12948
+ /** The ids from `a` to `b` inclusive, in document order whichever way round they are given. Empty when either is not in `ids`. */
12949
+ function rangeBetween(ids, a, b) {
12950
+ if (a === null || b === null) return [];
12951
+ const i = ids.indexOf(a);
12952
+ const j = ids.indexOf(b);
12953
+ if (i < 0 || j < 0) return [];
12954
+ return ids.slice(Math.min(i, j), Math.max(i, j) + 1);
12955
+ }
12956
+ /** How many ids carry each mark key. Ids with no mark are not counted. */
12957
+ function countMarks(marks, ids) {
12958
+ const out = {};
12959
+ for (const id of ids ?? Object.keys(marks)) {
12960
+ const m = marks[id];
12961
+ if (m) out[m] = (out[m] ?? 0) + 1;
12962
+ }
12963
+ return out;
12964
+ }
12965
+ /** The id `by` places from `from` in `ids`, held to the ends; the first (or last) when `from` is not set. */
12966
+ function stepId(ids, from, by) {
12967
+ if (ids.length === 0) return null;
12968
+ const i = from === null ? -1 : ids.indexOf(from);
12969
+ if (i < 0) return by >= 0 ? ids[0] : ids[ids.length - 1];
12970
+ return ids[Math.min(Math.max(i + by, 0), ids.length - 1)];
12971
+ }
12972
+ // src/components/markable-text.tsx
12973
+ var TONE = {
12974
+ neutral: {
12975
+ fill: "var(--muted)",
12976
+ edge: "var(--muted-foreground)"
12977
+ },
12978
+ info: {
12979
+ fill: "var(--info-subtle)",
12980
+ edge: "var(--info)"
12981
+ },
12982
+ success: {
12983
+ fill: "var(--success-subtle)",
12984
+ edge: "var(--success)"
12985
+ },
12986
+ warning: {
12987
+ fill: "var(--warning-subtle)",
12988
+ edge: "var(--warning)"
12989
+ },
12990
+ danger: {
12991
+ fill: "var(--danger-subtle)",
12992
+ edge: "var(--danger)"
12993
+ }
12994
+ };
12995
+ var MarksContext = React.createContext(null);
12996
+ /** One word (or phrase, or clip) that can be marked. Draws its mark, its selection and the caret; inside a `MarkableText`. */
12997
+ function Mark({ id, children, className }) {
12998
+ const c = React.useContext(MarksContext);
12999
+ if (!c) return /* @__PURE__ */ jsx("span", {
13000
+ className,
13001
+ children
13002
+ });
13003
+ const kind = c.kinds.find((k) => k.key === c.marks[id]);
13004
+ const tone = kind && TONE[kind.tone];
13005
+ const on = c.selected.has(id);
13006
+ return /* @__PURE__ */ jsxs("span", {
13007
+ "data-mark-id": id,
13008
+ "data-mark": kind?.key,
13009
+ "data-selected": on || void 0,
13010
+ "data-caret": c.caret === id || void 0,
13011
+ onPointerDown: (e) => c.press(e, id),
13012
+ onPointerEnter: () => c.over(id),
13013
+ className: cn("cursor-text rounded-control px-px", on && "bg-primary/20", c.caret === id && "outline-2 outline-primary", className),
13014
+ style: kind && tone ? {
13015
+ backgroundColor: on ? void 0 : tone.fill,
13016
+ textDecorationLine: "underline",
13017
+ textDecorationStyle: kind.pattern,
13018
+ textDecorationColor: tone.edge,
13019
+ textDecorationThickness: "2px",
13020
+ textUnderlineOffset: "3px"
13021
+ } : void 0,
13022
+ children: [children, kind && /* @__PURE__ */ jsxs("span", {
13023
+ className: "sr-only",
13024
+ children: [
13025
+ " (",
13026
+ kind.label.toLowerCase(),
13027
+ ")"
13028
+ ]
13029
+ })]
13030
+ });
13031
+ }
13032
+ /** "12 words must use, 3 never": a count for each kind in use, with its icon. */
13033
+ function MarkSummary({ marks, kinds, unit = ["word", "words"], className }) {
13034
+ const counts = countMarks(marks);
13035
+ const used = kinds.filter((k) => counts[k.key]);
13036
+ if (!used.length) return /* @__PURE__ */ jsx("p", {
13037
+ className: cn("type-caption text-muted-foreground", className),
13038
+ children: "Nothing marked yet."
13039
+ });
13040
+ return /* @__PURE__ */ jsx("ul", {
13041
+ "aria-label": "Marked",
13042
+ className: cn("flex flex-wrap gap-x-4 gap-y-1 type-body-sm", className),
13043
+ children: used.map((k) => {
13044
+ const Icon = k.icon;
13045
+ return /* @__PURE__ */ jsxs("li", {
13046
+ className: "inline-flex items-center gap-1.5",
13047
+ children: [
13048
+ Icon && /* @__PURE__ */ jsx(Icon, {
13049
+ "aria-hidden": true,
13050
+ className: "size-4"
13051
+ }),
13052
+ /* @__PURE__ */ jsx("span", {
13053
+ className: "tabular-nums",
13054
+ children: format.count(counts[k.key], unit[0], unit[1])
13055
+ }),
13056
+ " ",
13057
+ k.label.toLowerCase()
13058
+ ]
13059
+ }, k.key);
13060
+ })
13061
+ });
13062
+ }
13063
+ /** Selects ids over `<Mark>` words by drag, Shift+click and Shift+arrows (a run in the app's order, so it holds across virtualised rows), offers the app's marks as chorded commands in a bar, says each change in words, and lists what is marked. */
13064
+ function MarkableText({ label, ids, marks, kinds, onMark, clearKeys = [], onCaretChange, unit = ["word", "words"], summary = true, children, className }) {
13065
+ const [anchor, setAnchor] = React.useState(null);
13066
+ const [caret, setCaret] = React.useState(null);
13067
+ const [said, setSaid] = React.useState("");
13068
+ const dragging = React.useRef(false);
13069
+ const hintId = React.useId();
13070
+ const run = React.useMemo(() => rangeBetween(ids, anchor, caret), [
13071
+ ids,
13072
+ anchor,
13073
+ caret
13074
+ ]);
13075
+ const selected = React.useMemo(() => new Set(run), [run]);
13076
+ const n = run.length;
13077
+ const counted = (k) => format.count(k, unit[0], unit[1]);
13078
+ const moveCaret = (id, extend) => {
13079
+ if (id === null) return;
13080
+ setCaret(id);
13081
+ if (!extend || anchor === null) setAnchor(id);
13082
+ onCaretChange?.(id);
13083
+ };
13084
+ const apply = (kind) => {
13085
+ if (!n) return;
13086
+ onMark(run, kind);
13087
+ const k = kinds.find((x) => x.key === kind);
13088
+ setSaid(kind === null ? `${counted(n)} cleared` : `${counted(n)} marked ${k?.label.toLowerCase() ?? kind}`);
13089
+ };
13090
+ const commands = [...kinds.map((k) => ({
13091
+ id: `mark-${k.key}`,
13092
+ label: k.label,
13093
+ keys: k.keys,
13094
+ icon: k.icon,
13095
+ disabled: n ? false : "Select words first",
13096
+ run: () => apply(k.key)
13097
+ })), {
13098
+ id: "mark-clear",
13099
+ label: "Clear mark",
13100
+ keys: clearKeys,
13101
+ disabled: n ? false : "Select words first",
13102
+ run: () => apply(null)
13103
+ }];
13104
+ useCommands(commands);
13105
+ React.useEffect(() => {
13106
+ const stop = () => dragging.current = false;
13107
+ window.addEventListener("pointerup", stop);
13108
+ return () => window.removeEventListener("pointerup", stop);
13109
+ }, []);
13110
+ const ctx = {
13111
+ kinds,
13112
+ marks,
13113
+ selected,
13114
+ caret,
13115
+ press: (e, id) => {
13116
+ if (e.button !== 0) return;
13117
+ dragging.current = true;
13118
+ if (e.shiftKey && anchor !== null) setCaret(id);
13119
+ else {
13120
+ setAnchor(id);
13121
+ setCaret(id);
13122
+ }
13123
+ onCaretChange?.(id);
13124
+ setSaid("");
13125
+ },
13126
+ over: (id) => {
13127
+ if (dragging.current && id !== caret) setCaret(id);
13128
+ }
13129
+ };
13130
+ React.useEffect(() => {
13131
+ if (n > 1) setSaid(`${counted(n)} selected`);
13132
+ else if (n === 1 && caret) setSaid(`${document.querySelector(`[data-mark-id="${CSS.escape(caret)}"]`)?.textContent ?? caret}`);
13133
+ }, [n, caret]);
13134
+ const keys = (e) => {
13135
+ if (e.altKey || e.ctrlKey || e.metaKey) return;
13136
+ const to = e.key === "ArrowRight" ? stepId(ids, caret, 1) : e.key === "ArrowLeft" ? stepId(ids, caret, -1) : e.key === "Home" ? ids[0] ?? null : e.key === "End" ? ids[ids.length - 1] ?? null : void 0;
13137
+ if (to !== void 0) {
13138
+ e.preventDefault();
13139
+ moveCaret(to, e.shiftKey);
13140
+ } else if (e.key === "Escape" && (anchor !== null || caret !== null)) {
13141
+ e.preventDefault();
13142
+ setAnchor(null);
13143
+ setCaret(null);
13144
+ setSaid("Selection cleared");
13145
+ }
13146
+ };
13147
+ return /* @__PURE__ */ jsxs("div", {
13148
+ className: cn("space-y-2", className),
13149
+ children: [
13150
+ n > 0 && /* @__PURE__ */ jsxs(Toolbar, {
13151
+ label: "Marks",
13152
+ className: "sticky top-0 z-10 flex flex-wrap items-center gap-2 rounded-surface border border-border bg-background p-1.5",
13153
+ children: [
13154
+ /* @__PURE__ */ jsxs("span", {
13155
+ className: "px-1 type-label tabular-nums",
13156
+ children: [counted(n), " selected"]
13157
+ }),
13158
+ kinds.map((k) => {
13159
+ const Icon = k.icon;
13160
+ return /* @__PURE__ */ jsxs(Button, {
13161
+ size: "sm",
13162
+ onPress: () => apply(k.key),
13163
+ children: [
13164
+ Icon && /* @__PURE__ */ jsx(Icon, {}),
13165
+ " ",
13166
+ k.label
13167
+ ]
13168
+ }, k.key);
13169
+ }),
13170
+ /* @__PURE__ */ jsx(Button, {
13171
+ size: "sm",
13172
+ variant: "ghost",
13173
+ onPress: () => apply(null),
13174
+ children: "Clear mark"
13175
+ }),
13176
+ /* @__PURE__ */ jsx(Button, {
13177
+ size: "sm",
13178
+ variant: "ghost",
13179
+ onPress: () => {
13180
+ setAnchor(null);
13181
+ setCaret(null);
13182
+ },
13183
+ children: "Deselect"
13184
+ })
13185
+ ]
13186
+ }),
13187
+ /* @__PURE__ */ jsx(MarksContext.Provider, {
13188
+ value: ctx,
13189
+ children: /* @__PURE__ */ jsx("div", {
13190
+ role: "group",
13191
+ "aria-label": label,
13192
+ "aria-describedby": hintId,
13193
+ tabIndex: 0,
13194
+ onKeyDown: keys,
13195
+ className: "select-none rounded-surface outline-offset-2",
13196
+ children
13197
+ })
13198
+ }),
13199
+ /* @__PURE__ */ jsx("p", {
13200
+ id: hintId,
13201
+ className: "type-caption text-muted-foreground",
13202
+ children: "Drag across words, or Shift+click, to select. Left and Right move; Shift and arrows select; Escape clears."
13203
+ }),
13204
+ /* @__PURE__ */ jsx(CommandLegend, {
13205
+ commands,
13206
+ label: "Mark keys"
13207
+ }),
13208
+ summary && /* @__PURE__ */ jsx(MarkSummary, {
13209
+ marks,
13210
+ kinds,
13211
+ unit
13212
+ }),
13213
+ /* @__PURE__ */ jsx("div", {
13214
+ role: "status",
13215
+ "aria-live": "polite",
13216
+ className: "sr-only",
13217
+ children: said
13218
+ })
13219
+ ]
13220
+ });
13221
+ }
13222
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, ContextMenu, Conversation, CursorScope, DEFAULT_TOLERANCE, DataTable, DataView, Density, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, PairJudge, PairVote, Pane, PlayWindowButton, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, SaveStatus, SeekBar, SelectableGrid, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewportFrame, VirtualList, VolumeControl, Waveform, Workspace, actualPixelsScale, ancestorsOf, boxViewport, buttonVariants, canFullscreen, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, fetchJson, fieldErrorsOf, fitRect, format, formatChord, gainToVolume, geo, gridPoints, isReservedChord, isTypingTarget, joinMediaGroup, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveRect, noOverlap, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, plainText, rangeBetween, readErrorBody, readPixels, regionShares, resample, resamplePeaks, resizeRect, safeHref, serialiseSort, settleCut, snapToGrid, staleOf, stepId, stepOnGrid, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoSave, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useLeaveGuard, useLoad, useMediaElement, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, useWorkspaceState, valueAt, wordAt, zoomAt };
10161
13223
 
10162
13224
  //# sourceMappingURL=index.js.map