strata-react 1.0.39 → 1.0.41

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 (44) hide show
  1. package/README.md +29 -5
  2. package/UPGRADING.md +11 -0
  3. package/bin/strata-stock-classes.js +5 -0
  4. package/dist/components/button.d.ts +3 -0
  5. package/dist/components/checkbox.d.ts +3 -2
  6. package/dist/components/compare-parts.d.ts +25 -0
  7. package/dist/components/compare-video.d.ts +4 -2
  8. package/dist/components/compare.d.ts +4 -2
  9. package/dist/components/secret-field.d.ts +34 -0
  10. package/dist/components/selection.d.ts +45 -1
  11. package/dist/components/toast.d.ts +3 -2
  12. package/dist/components/transcript-view.d.ts +18 -2
  13. package/dist/components/tree.d.ts +16 -6
  14. package/dist/components/value-controls.d.ts +20 -4
  15. package/dist/{query-CJ1pSPiC.js → errors-BunUBqpA.js} +5 -176
  16. package/dist/errors-BunUBqpA.js.map +1 -0
  17. package/dist/{field-7Z4N5r5g.js → field-DeKNvGox.js} +74 -5
  18. package/dist/field-DeKNvGox.js.map +1 -0
  19. package/dist/index.d.ts +4 -2
  20. package/dist/index.js +847 -332
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/choice.d.ts +29 -0
  23. package/dist/lib/transcript.d.ts +16 -0
  24. package/dist/map.js +2 -2
  25. package/dist/migrate/cli.d.ts +2 -0
  26. package/dist/migrate/stock-classes.d.ts +11 -0
  27. package/dist/migrate-cli.js +128 -0
  28. package/dist/migrate-cli.js.map +1 -0
  29. package/dist/panorama.js +2 -2
  30. package/dist/query-B934ufsW.js +209 -0
  31. package/dist/query-B934ufsW.js.map +1 -0
  32. package/dist/strata.css +6 -0
  33. package/dist/strata.migrate.css +224 -0
  34. package/dist/testing.js +2 -2
  35. package/dist/{theme-CFNi6WUO.js → theme-DVaIxyNn.js} +6 -75
  36. package/dist/theme-DVaIxyNn.js.map +1 -0
  37. package/dist/value-controls-FO4zQiHP.js +735 -0
  38. package/dist/value-controls-FO4zQiHP.js.map +1 -0
  39. package/package.json +7 -2
  40. package/dist/field-7Z4N5r5g.js.map +0 -1
  41. package/dist/query-CJ1pSPiC.js.map +0 -1
  42. package/dist/theme-CFNi6WUO.js.map +0 -1
  43. package/dist/value-controls-D6O9TsM6.js +0 -356
  44. package/dist/value-controls-D6O9TsM6.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
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";
1
+ import { a as Textarea, c as Tooltip, d as typeSteps, i as NativeSelect, l as KeyText, n as Field, o as useFieldControl, r as Input, s as controlHeight, t as ChoiceGroup, u as cn } from "./field-DeKNvGox.js";
2
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-CJ1pSPiC.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";
3
+ import { a as useAsyncAction, c as KeysLegend, d as useInView, i as AsyncButton, l as isTypingTarget, n as NumberField, o as Toolbar, r as Slider, s as ToolbarSeparator, t as ColorField, u as useHotkeys } from "./value-controls-FO4zQiHP.js";
4
+ import { a as readErrorBody, c as RowAction, i as fieldErrorsOf, l as buttonVariants, n as describeActionError, o as Button, r as describeHttpError, s as IconButton, t as HttpError } from "./errors-BunUBqpA.js";
5
+ import { a as toLoad, c as toast, i as staleOf, l as toastTimeout, n as createQueryClient, o as useLoad, r as fetchJson, s as StrataToastRegion, t as StrataQueryProvider, u as overlaySurface } from "./query-B934ufsW.js";
6
6
  import { n as useSharedCursor, r as geo, t as CursorScope } from "./cursor-DDGBPiTJ.js";
7
+ import { a as useColorScheme, i as colorSchemeScript, n as ColorSchemeChoice, o as useSystemColorScheme, r as ThemeProvider, s as Density, t as COLOR_SCHEME_STORAGE_KEY } from "./theme-DVaIxyNn.js";
7
8
  import * as React from "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";
9
+ 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, Tree as Tree$1, TreeItem, TreeItemContent, Virtualizer, useDragAndDrop, useFilter } from "react-aria-components";
10
+ import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, Ellipsis, Eye, EyeOff, FileQuestion, Flag, Folder, FolderOpen, GripVertical, History, ImageOff, Info, KeyRound, Loader, LoaderCircle, Lock, 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";
10
11
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
12
  import { Link, NavLink, useSearchParams } from "react-router";
12
13
  import { createSortedRowModel, flexRender, rowSortingFeature, tableFeatures, useTable } from "@tanstack/react-table";
@@ -142,84 +143,6 @@ function isReservedChord(chord, platform = detectPlatform()) {
142
143
  return p.ctrl === c.ctrl && p.meta === c.meta && p.alt === c.alt && p.shift === c.shift && p.key.toLowerCase() === c.key.toLowerCase();
143
144
  });
144
145
  }
145
- // src/components/hotkeys.tsx
146
- var TEXT_INPUTS_EXEMPT = /* @__PURE__ */ new Set([
147
- "checkbox",
148
- "radio",
149
- "button",
150
- "submit",
151
- "reset",
152
- "range",
153
- "color",
154
- "file"
155
- ]);
156
- /** True when a key pressed on this element is the person typing, so single-key shortcuts must leave it alone. */
157
- function isTypingTarget(target) {
158
- if (!(target instanceof HTMLElement)) return false;
159
- if (target.isContentEditable || target.closest("[contenteditable=''],[contenteditable='true']")) return true;
160
- if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;
161
- if (target instanceof HTMLInputElement) return !TEXT_INPUTS_EXEMPT.has(target.type);
162
- return false;
163
- }
164
- function toShortcuts(input) {
165
- return Array.isArray(input) ? input : Object.entries(input).map(([key, run]) => ({
166
- keys: [key],
167
- label: key,
168
- run
169
- }));
170
- }
171
- /**
172
- * Binds single-key shortcuts on the window, ignoring keys typed into fields, chords with Ctrl, Meta
173
- * or Alt, IME composition and (unless `repeat`) held keys. Pass the same list to `KeysLegend`.
174
- */
175
- function useHotkeys(shortcuts, { enabled = true } = {}) {
176
- const latest = React.useRef([]);
177
- latest.current = toShortcuts(shortcuts);
178
- React.useEffect(() => {
179
- if (!enabled) return;
180
- const onKeyDown = (e) => {
181
- if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey) return;
182
- if (isTypingTarget(e.target)) return;
183
- const hit = latest.current.find((s) => !s.disabled && s.keys.includes(e.key));
184
- if (!hit || e.repeat && !hit.repeat) return;
185
- e.preventDefault();
186
- hit.run();
187
- };
188
- window.addEventListener("keydown", onKeyDown);
189
- return () => window.removeEventListener("keydown", onKeyDown);
190
- }, [enabled]);
191
- }
192
- var KEY_NAMES = {
193
- ArrowDown: "↓",
194
- ArrowUp: "↑",
195
- ArrowLeft: "←",
196
- ArrowRight: "→",
197
- Escape: "Esc",
198
- Enter: "Enter",
199
- Backspace: "Backspace",
200
- Delete: "Delete",
201
- " ": "Space"
202
- };
203
- /** A quiet legend of the screen's shortcuts, from the same list `useHotkeys` binds. Hidden on touch screens. */
204
- function KeysLegend({ shortcuts, label = "Keyboard shortcuts", className }) {
205
- return /* @__PURE__ */ jsx("dl", {
206
- "aria-label": label,
207
- className: cn("flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden", className),
208
- children: shortcuts.map((s) => /* @__PURE__ */ jsxs("div", {
209
- className: cn("flex items-center gap-1.5", s.disabled && "opacity-50"),
210
- children: [/* @__PURE__ */ jsx("dt", {
211
- className: "flex items-center gap-1",
212
- children: s.keys.map((k, i) => /* @__PURE__ */ jsxs(React.Fragment, { children: [i > 0 && /* @__PURE__ */ jsx("span", {
213
- className: "sr-only",
214
- children: " or "
215
- }), /* @__PURE__ */ jsx("kbd", {
216
- className: "min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground",
217
- children: /* @__PURE__ */ jsx(KeyText, { children: KEY_NAMES[k] ?? k })
218
- })] }, k))
219
- }), /* @__PURE__ */ jsx("dd", { children: s.label })]
220
- }, s.keys.join(" ")))
221
- });
222
- }
223
146
  // src/components/commands.tsx
224
147
  /** The text of a command's label, whether it is a string or a function. */
225
148
  var labelOf = (c) => typeof c.label === "function" ? c.label() : c.label;
@@ -514,33 +437,6 @@ function CommandMenu({ commands, open, onOpenChange, shortcut = "Mod+K", label =
514
437
  })
515
438
  });
516
439
  }
517
- // src/components/toolbar.tsx
518
- /** A group of controls with one tab stop and arrow-key movement (the WAI-ARIA toolbar pattern). Needs a `label`. */
519
- function Toolbar({ label, orientation = "horizontal", children, className }) {
520
- const jump = (e) => {
521
- if (e.key !== "Home" && e.key !== "End" || isTypingTarget(e.target) || !e.currentTarget.contains(e.target)) return;
522
- const items = [...e.currentTarget.querySelectorAll("button, input, select, textarea, a[href], [tabindex]")].filter((el) => !el.hasAttribute("disabled") && el.getAttribute("aria-disabled") !== "true" && el.tabIndex >= -1 && el.getAttribute("role") !== "separator");
523
- const target = e.key === "Home" ? items[0] : items[items.length - 1];
524
- if (!target) return;
525
- e.preventDefault();
526
- e.stopPropagation();
527
- target.focus();
528
- };
529
- return /* @__PURE__ */ jsx("div", {
530
- className: "contents",
531
- onKeyDownCapture: jump,
532
- children: /* @__PURE__ */ jsx(Toolbar$1, {
533
- "aria-label": label,
534
- orientation,
535
- className: cn("flex flex-wrap items-center gap-1", orientation === "vertical" && "flex-col items-stretch", className),
536
- children
537
- })
538
- });
539
- }
540
- /** A hairline between groups of controls inside a `Toolbar`. */
541
- function ToolbarSeparator({ className }) {
542
- return /* @__PURE__ */ jsx(Separator, { className: cn("mx-1 h-5 w-px self-center border-0 bg-border", className) });
543
- }
544
440
  // src/components/toggle.tsx
545
441
  var base = "inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control border type-label transition-state press [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border-input bg-background text-muted-foreground hover:bg-muted hover:text-foreground selected:border-foreground selected:bg-muted selected:text-foreground disabled:pointer-events-none disabled:opacity-50";
546
442
  var sizes$1 = {
@@ -909,11 +805,12 @@ function CheckboxBox({ selected, indeterminate, hideLabel }) {
909
805
  * fight the table's own selection state. Not exported from the package: `DataTable` uses it.
910
806
  * @internal
911
807
  */
912
- function TableSelectionCheckbox({ label, className, disabled }) {
808
+ function TableSelectionCheckbox({ label, className, disabled, mixed }) {
913
809
  const id = React.useId();
914
810
  return /* @__PURE__ */ jsx(Checkbox$1, {
915
811
  slot: "selection",
916
812
  isDisabled: disabled,
813
+ isIndeterminate: mixed,
917
814
  id,
918
815
  "aria-labelledby": id,
919
816
  "aria-label": label,
@@ -925,147 +822,6 @@ function TableSelectionCheckbox({ label, className, disabled }) {
925
822
  })
926
823
  });
927
824
  }
928
- // src/components/async-button.tsx
929
- /** One button through idle, pending, done and error, with the label changing in place and its width fixed by the longest label. The outcome is announced politely, with the error's own words when `error` is given. */
930
- function AsyncButton({ phase, labels, error, disabled, ...props }) {
931
- const errorLabel = labels.error ?? "Try again";
932
- const current = {
933
- idle: labels.idle,
934
- pending: labels.pending,
935
- done: labels.done,
936
- error: errorLabel
937
- }[phase];
938
- const Icon = {
939
- idle: null,
940
- pending: LoaderCircle,
941
- done: Check,
942
- error: CircleAlert
943
- }[phase];
944
- const announcement = phase === "done" ? labels.done : phase === "error" ? error ? `${error} ${errorLabel}` : errorLabel : "";
945
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Button, {
946
- ...props,
947
- "data-phase": phase,
948
- disabled: disabled || phase === "pending",
949
- "aria-disabled": phase === "pending" || void 0,
950
- children: [Icon && /* @__PURE__ */ jsx(Icon, {
951
- "aria-hidden": true,
952
- className: phase === "pending" ? "motion-safe:animate-spin" : void 0
953
- }), /* @__PURE__ */ jsx("span", {
954
- className: "grid",
955
- children: [
956
- labels.idle,
957
- labels.pending,
958
- labels.done,
959
- errorLabel
960
- ].map((l) => /* @__PURE__ */ jsx("span", {
961
- "aria-hidden": l !== current,
962
- className: l === current ? "[grid-area:1/1]" : "invisible [grid-area:1/1]",
963
- children: l
964
- }, l))
965
- })]
966
- }), /* @__PURE__ */ jsx("span", {
967
- role: "status",
968
- className: "sr-only",
969
- children: announcement
970
- })] });
971
- }
972
- /** Runs an async action and reports its phase, its error and any field messages. `done` returns to `idle` after `settleMs`; `run` never changes identity. */
973
- function useAsyncAction(action, { settleMs = 2e3, onError, describeError = describeActionError, validate, onInvalid } = {}) {
974
- const [state, setState] = React.useState(idle$1);
975
- const timer = React.useRef(void 0);
976
- const unreported = React.useRef(void 0);
977
- const latest = React.useRef({
978
- action,
979
- onError,
980
- settleMs,
981
- describeError,
982
- validate,
983
- onInvalid
984
- });
985
- React.useLayoutEffect(() => {
986
- latest.current = {
987
- action,
988
- onError,
989
- settleMs,
990
- describeError,
991
- validate,
992
- onInvalid
993
- };
994
- });
995
- React.useEffect(() => () => window.clearTimeout(timer.current), []);
996
- const run = React.useCallback(async (...args) => {
997
- window.clearTimeout(timer.current);
998
- const invalid = messages(latest.current.validate?.(...args));
999
- if (invalid) {
1000
- unreported.current = { invalid };
1001
- setState({
1002
- ...idle$1,
1003
- fieldErrors: invalid
1004
- });
1005
- return;
1006
- }
1007
- setState({
1008
- ...idle$1,
1009
- phase: "pending"
1010
- });
1011
- try {
1012
- await latest.current.action(...args);
1013
- setState({
1014
- ...idle$1,
1015
- phase: "done"
1016
- });
1017
- timer.current = window.setTimeout(() => setState(idle$1), latest.current.settleMs);
1018
- } catch (thrown) {
1019
- unreported.current = { thrown };
1020
- setState({
1021
- phase: "error",
1022
- error: latest.current.describeError(thrown),
1023
- thrown,
1024
- fieldErrors: fieldErrorsOf(thrown)
1025
- });
1026
- }
1027
- }, []);
1028
- React.useEffect(() => {
1029
- const note = unreported.current;
1030
- if (!note) return;
1031
- if ("thrown" in note && state.phase === "error") latest.current.onError?.(note.thrown);
1032
- else if ("invalid" in note) latest.current.onInvalid?.(note.invalid);
1033
- else return;
1034
- unreported.current = void 0;
1035
- }, [state]);
1036
- const clearFieldError = React.useCallback((field) => setState((s) => {
1037
- if (field === void 0) return Object.keys(s.fieldErrors).length ? {
1038
- ...s,
1039
- fieldErrors: {}
1040
- } : s;
1041
- if (!(field in s.fieldErrors)) return s;
1042
- const { [field]: _gone, ...rest } = s.fieldErrors;
1043
- return {
1044
- ...s,
1045
- fieldErrors: rest
1046
- };
1047
- }), []);
1048
- return {
1049
- phase: state.phase,
1050
- run,
1051
- error: state.error,
1052
- thrown: state.thrown,
1053
- fieldErrors: state.fieldErrors,
1054
- clearFieldError
1055
- };
1056
- }
1057
- var idle$1 = {
1058
- phase: "idle",
1059
- error: void 0,
1060
- thrown: void 0,
1061
- fieldErrors: {}
1062
- };
1063
- /** The messages `validate` returned, without the empty ones; undefined when there are none. */
1064
- function messages(found) {
1065
- if (!found) return void 0;
1066
- const kept = Object.fromEntries(Object.entries(found).filter((e) => Boolean(e[1])));
1067
- return Object.keys(kept).length ? kept : void 0;
1068
- }
1069
825
  // src/components/status.tsx
1070
826
  var tones$1 = {
1071
827
  neutral: "bg-muted text-muted-foreground",
@@ -1465,6 +1221,183 @@ function Skeleton({ className }) {
1465
1221
  className: cn("rounded-control bg-muted motion-safe:animate-pulse", className)
1466
1222
  });
1467
1223
  }
1224
+ // src/components/secret-field.tsx
1225
+ var input = "w-full min-w-0 rounded-control border border-input bg-background pl-3 pr-1 type-body text-foreground transition-state placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 aria-invalid:border-danger";
1226
+ /** A credential the server keeps and never shows again: "Not set", "Set" (no characters, not even its length), a masked entry with a named Show toggle, Replace, a confirmed Remove that says what stops working, and a Test with its result beside it. A set, untouched field reports nothing. */
1227
+ function SecretField({ noun, isSet, setAt, onChange, onSave, onRemove, consequence, test, disabled, id: idProp, name, className }) {
1228
+ const { field } = useFieldControl();
1229
+ const id = idProp ?? field?.id;
1230
+ const [editing, setEditing] = React.useState(false);
1231
+ const [value, setValue] = React.useState("");
1232
+ const [shown, setShown] = React.useState(false);
1233
+ const [testing, setTesting] = React.useState(false);
1234
+ const [result, setResult] = React.useState(null);
1235
+ const asked = React.useRef(0);
1236
+ const entering = editing || !isSet;
1237
+ const change = (next) => {
1238
+ asked.current++;
1239
+ setValue(next);
1240
+ setResult(null);
1241
+ onChange?.(next === "" ? null : next);
1242
+ };
1243
+ const stop = () => {
1244
+ asked.current++;
1245
+ setTesting(false);
1246
+ setEditing(false);
1247
+ setValue("");
1248
+ setShown(false);
1249
+ setResult(null);
1250
+ };
1251
+ const cancel = () => {
1252
+ stop();
1253
+ onChange?.(null);
1254
+ };
1255
+ const version = `${isSet}|${setAt == null ? "" : new Date(setAt).getTime()}`;
1256
+ const [seen, setSeen] = React.useState(version);
1257
+ if (seen !== version) {
1258
+ setSeen(version);
1259
+ if (value !== "" || editing) stop();
1260
+ }
1261
+ const save = useAsyncAction(async () => {
1262
+ await onSave?.(value);
1263
+ stop();
1264
+ });
1265
+ const runTest = async () => {
1266
+ if (!test) return;
1267
+ const mine = ++asked.current;
1268
+ setTesting(true);
1269
+ setResult(null);
1270
+ let outcome;
1271
+ try {
1272
+ outcome = await test(entering ? value : null);
1273
+ } catch (thrown) {
1274
+ outcome = {
1275
+ ok: false,
1276
+ message: thrown instanceof Error && thrown.message ? thrown.message : `The ${noun} could not be tested. Try again.`
1277
+ };
1278
+ }
1279
+ if (mine !== asked.current) return;
1280
+ setResult(outcome);
1281
+ setTesting(false);
1282
+ };
1283
+ const describedBy = field?.describedBy;
1284
+ return /* @__PURE__ */ jsxs("div", {
1285
+ className: cn("grid min-w-0 gap-2", className),
1286
+ children: [entering ? /* @__PURE__ */ jsxs("div", {
1287
+ className: "flex min-w-0 flex-wrap items-center gap-2",
1288
+ children: [
1289
+ /* @__PURE__ */ jsxs("div", {
1290
+ className: "relative flex min-w-40 flex-1 items-center",
1291
+ children: [/* @__PURE__ */ jsx("input", {
1292
+ id,
1293
+ name,
1294
+ type: shown ? "text" : "password",
1295
+ value,
1296
+ onChange: (e) => change(e.target.value),
1297
+ disabled,
1298
+ autoComplete: "new-password",
1299
+ autoCapitalize: "off",
1300
+ autoCorrect: "off",
1301
+ spellCheck: false,
1302
+ "data-1p-ignore": "",
1303
+ "data-lpignore": "true",
1304
+ "data-form-type": "other",
1305
+ "aria-describedby": describedBy,
1306
+ "aria-invalid": field?.invalid || void 0,
1307
+ placeholder: isSet ? `New ${noun}` : `Paste the ${noun}`,
1308
+ className: cn(input, controlHeight.default, "pr-11")
1309
+ }), /* @__PURE__ */ jsx("span", {
1310
+ className: "absolute right-0.5",
1311
+ children: /* @__PURE__ */ jsx(IconButton, {
1312
+ icon: shown ? EyeOff : Eye,
1313
+ label: shown ? `Hide ${noun}` : `Show ${noun}`,
1314
+ size: "sm",
1315
+ disabled,
1316
+ onPress: () => setShown((s) => !s)
1317
+ })
1318
+ })]
1319
+ }),
1320
+ onSave && /* @__PURE__ */ jsx(AsyncButton, {
1321
+ variant: "default",
1322
+ phase: save.phase,
1323
+ error: save.error,
1324
+ labels: {
1325
+ idle: `Save ${noun}`,
1326
+ pending: "Saving…",
1327
+ done: "Saved"
1328
+ },
1329
+ disabled: disabled || value === "",
1330
+ onPress: () => void save.run()
1331
+ }),
1332
+ isSet && /* @__PURE__ */ jsx(Button, {
1333
+ variant: "ghost",
1334
+ onPress: cancel,
1335
+ disabled: disabled || save.phase === "pending",
1336
+ children: "Cancel"
1337
+ }),
1338
+ test && /* @__PURE__ */ jsx(Button, {
1339
+ onPress: () => void runTest(),
1340
+ disabled: disabled || testing || value === "",
1341
+ children: testing ? "Testing…" : `Test ${noun}`
1342
+ })
1343
+ ]
1344
+ }) : /* @__PURE__ */ jsxs("div", {
1345
+ className: "flex min-w-0 flex-wrap items-center gap-2",
1346
+ children: [
1347
+ /* @__PURE__ */ jsxs("output", {
1348
+ id,
1349
+ "aria-describedby": describedBy,
1350
+ className: cn("flex min-w-48 flex-1 items-center gap-2 whitespace-nowrap rounded-control border border-input bg-muted px-3 type-body text-foreground", controlHeight.default),
1351
+ children: [
1352
+ /* @__PURE__ */ jsx(KeyRound, {
1353
+ "aria-hidden": true,
1354
+ className: "size-4 shrink-0 text-muted-foreground"
1355
+ }),
1356
+ /* @__PURE__ */ jsx("span", { children: "Set" }),
1357
+ setAt != null && /* @__PURE__ */ jsx("span", {
1358
+ className: "min-w-0 truncate text-muted-foreground",
1359
+ children: format.dateTime(setAt)
1360
+ })
1361
+ ]
1362
+ }),
1363
+ /* @__PURE__ */ jsx(Button, {
1364
+ onPress: () => setEditing(true),
1365
+ disabled,
1366
+ children: `Replace ${noun}`
1367
+ }),
1368
+ onRemove && /* @__PURE__ */ jsx(AlertDialog, {
1369
+ title: `Remove the ${noun}?`,
1370
+ description: consequence,
1371
+ confirm: `Remove ${noun}`,
1372
+ onConfirm: onRemove,
1373
+ trigger: /* @__PURE__ */ jsx(Button, {
1374
+ variant: "ghost",
1375
+ disabled,
1376
+ children: `Remove ${noun}`
1377
+ })
1378
+ }),
1379
+ test && /* @__PURE__ */ jsx(Button, {
1380
+ onPress: () => void runTest(),
1381
+ disabled: disabled || testing,
1382
+ children: testing ? "Testing…" : `Test ${noun}`
1383
+ })
1384
+ ]
1385
+ }), /* @__PURE__ */ jsx("div", {
1386
+ role: "status",
1387
+ className: result ? "flex items-start gap-1.5 type-body-sm" : "sr-only",
1388
+ children: result && (result.ok ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(CircleCheck, {
1389
+ "aria-hidden": true,
1390
+ className: "mt-0.5 size-4 shrink-0 text-success"
1391
+ }), /* @__PURE__ */ jsx("span", { children: result.message ?? `${noun.charAt(0).toUpperCase()}${noun.slice(1)} accepted` })] }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(CircleAlert, {
1392
+ "aria-hidden": true,
1393
+ className: "mt-0.5 size-4 shrink-0 text-danger"
1394
+ }), /* @__PURE__ */ jsx("span", {
1395
+ className: "text-danger",
1396
+ children: result.message
1397
+ })] }))
1398
+ })]
1399
+ });
1400
+ }
1468
1401
  // src/components/alert.tsx
1469
1402
  var tones = {
1470
1403
  info: {
@@ -1765,6 +1698,57 @@ function ThumbnailSkeleton({ aspect = 1, className }) {
1765
1698
  children: /* @__PURE__ */ jsx(Skeleton, { className: "absolute inset-0" })
1766
1699
  });
1767
1700
  }
1701
+ // src/lib/choice.ts
1702
+ function resolve(explicit, implies) {
1703
+ const all = new Set(explicit);
1704
+ const because = /* @__PURE__ */ new Map();
1705
+ if (implies) for (const root of explicit) {
1706
+ const seen = /* @__PURE__ */ new Set([root]);
1707
+ const queue = [root];
1708
+ while (queue.length) {
1709
+ const key = queue.shift();
1710
+ for (const next of implies(key) ?? []) {
1711
+ if (seen.has(next)) continue;
1712
+ seen.add(next);
1713
+ queue.push(next);
1714
+ all.add(next);
1715
+ because.set(next, [...because.get(next) ?? [], root]);
1716
+ }
1717
+ }
1718
+ }
1719
+ const locked = new Set(because.keys());
1720
+ return {
1721
+ all,
1722
+ locked,
1723
+ dependents: new Set([...locked].filter((k) => !explicit.has(k))),
1724
+ because
1725
+ };
1726
+ }
1727
+ /**
1728
+ * Apply a surface's request for the set it wants shown chosen (`next`, what a tree or table gives
1729
+ * back) to the explicit choice. A dependent (implied, not chosen) in `next` is not made explicit
1730
+ * (it is already in), and one missing from `next` is put back, not cleared.
1731
+ */
1732
+ function applyChange(explicit, next, implies) {
1733
+ const before = resolve(explicit, implies);
1734
+ const wanted = new Set([...next].filter((k) => !before.dependents.has(k)));
1735
+ const after = resolve(wanted, implies);
1736
+ const refused = [...before.all].filter((k) => !next.has(k) && after.all.has(k)).length;
1737
+ return {
1738
+ explicit: wanted,
1739
+ added: [...after.dependents].filter((k) => !before.all.has(k)).length,
1740
+ dropped: [...before.all].filter((k) => !after.all.has(k)).length,
1741
+ refused
1742
+ };
1743
+ }
1744
+ /** The sentence a screen reader hears for a change, or "" when nothing worth saying happened. */
1745
+ function noteFor({ added, dropped, refused }) {
1746
+ const parts = [];
1747
+ if (added > 0) parts.push(added === 1 ? "1 more chosen because it depends on it" : `${added} more chosen because they depend on it`);
1748
+ if (dropped > 0 && added === 0) parts.push(dropped === 1 ? "1 fewer chosen" : `${dropped} fewer chosen`);
1749
+ if (refused > 0) parts.push(refused === 1 ? "1 stays chosen because something chosen depends on it" : `${refused} stay chosen because something chosen depends on them`);
1750
+ return parts.join(". ");
1751
+ }
1768
1752
  // src/components/selection.tsx
1769
1753
  function reconcile(prev, rows, keys, initial) {
1770
1754
  const present = new Set(keys);
@@ -1789,7 +1773,9 @@ var sameKeys = (a, b) => a.length === b.length && a.every((k, i) => k === b[i]);
1789
1773
  * the row) chooses each row the first time it appears, so a selection seeded from data that loads
1790
1774
  * later, or a next page, still starts right.
1791
1775
  */
1792
- function useSelection(rows, rowKey, initial = []) {
1776
+ function useSelection(rows, rowKey, initial = [], { implies, format: fmt = format } = {}) {
1777
+ const impliesRef = React.useRef(implies);
1778
+ impliesRef.current = implies;
1793
1779
  const initialRef = React.useRef(initial);
1794
1780
  initialRef.current = initial;
1795
1781
  const initialKeys = React.useRef(void 0);
@@ -1813,26 +1799,63 @@ function useSelection(rows, rowKey, initial = []) {
1813
1799
  current = reconcile(state, rows, keys, test);
1814
1800
  setState(current);
1815
1801
  }
1816
- const selected = current.raw;
1802
+ const resolved = React.useMemo(() => resolve(current.raw, impliesRef.current), [current.raw, implies]);
1803
+ const selected = React.useMemo(() => {
1804
+ const present = new Set(current.keys);
1805
+ return implies ? new Set([...resolved.all].filter((k) => present.has(k))) : current.raw;
1806
+ }, [
1807
+ resolved,
1808
+ current.keys,
1809
+ current.raw,
1810
+ implies
1811
+ ]);
1817
1812
  const selectedRows = React.useMemo(() => rows.filter((r) => selected.has(rowKey(r))), [rows, selected]);
1818
1813
  const onChange = React.useCallback((next) => setState((s) => {
1819
1814
  const present = new Set(s.keys);
1815
+ const before = resolve(s.raw, impliesRef.current).all;
1816
+ const asked = new Set([...next].filter((k) => present.has(k)));
1817
+ for (const k of before) if (!present.has(k)) asked.add(k);
1818
+ const change = applyChange(s.raw, asked, impliesRef.current);
1820
1819
  return {
1821
1820
  ...s,
1822
- raw: new Set([...next].filter((k) => present.has(k)))
1821
+ raw: change.explicit,
1822
+ note: noteFor(change)
1823
1823
  };
1824
1824
  }), []);
1825
1825
  const clear = React.useCallback(() => setState((s) => ({
1826
1826
  ...s,
1827
- raw: /* @__PURE__ */ new Set()
1827
+ raw: /* @__PURE__ */ new Set(),
1828
+ note: ""
1828
1829
  })), []);
1830
+ const implied = React.useMemo(() => new Set([...resolved.locked].filter((k) => selected.has(k))), [resolved, selected]);
1831
+ const counts = {
1832
+ chosen: [...current.raw].filter((k) => selected.has(k)).length,
1833
+ dependents: [...resolved.dependents].filter((k) => selected.has(k)).length,
1834
+ total: selected.size
1835
+ };
1829
1836
  return {
1830
1837
  selected,
1831
1838
  selectedRows,
1832
1839
  count: selected.size,
1833
1840
  onChange,
1834
- clear
1835
- };
1841
+ clear,
1842
+ /** Keys that cannot be cleared on their own because something chosen implies them. */
1843
+ implied,
1844
+ /** The chosen keys that bring `key` in (all of them), for the text that says why it is ticked. */
1845
+ because: (key) => resolved.because.get(key) ?? [],
1846
+ counts,
1847
+ /** "12 results will be forgotten: 8 chosen, 4 that depend on them": the confirm's own words. */
1848
+ summary: (noun, then) => summarise(counts, noun, then, fmt),
1849
+ /** A polite sentence about the last change ("3 more chosen because they depend on it"), for a live region. */
1850
+ note: current.note ?? ""
1851
+ };
1852
+ }
1853
+ /** The line that names a choice's whole and where it came from: "12 results will be forgotten: 8 chosen, 4 that depend on them". With nothing brought in it is just "8 results will be forgotten". */
1854
+ function summarise(counts, noun, then, fmt) {
1855
+ const [one, many] = typeof noun === "string" ? [noun, `${noun}s`] : noun;
1856
+ if (counts.total === 0) return `No ${many} chosen`;
1857
+ const head = `${fmt.count(counts.total, one, many)} ${then}`;
1858
+ return counts.dependents > 0 ? `${head}: ${counts.chosen} chosen, ${counts.dependents} that depend on them` : head;
1836
1859
  }
1837
1860
  /**
1838
1861
  * Selecting rows of a surface in the order it shows them: one row, a range with Shift, and all
@@ -1886,6 +1909,57 @@ function useSelectRows(rows, rowKey, selection) {
1886
1909
  }
1887
1910
  };
1888
1911
  }
1912
+ /**
1913
+ * Choices that are not rows: the keys of a lazy tree, chosen before their rows have loaded. The same
1914
+ * rules as `useSelection`'s `implies` (explicit and implied kept apart, implied keys locked, a
1915
+ * summary and a note), with nothing to prune to. Spread into `Tree`'s `choices`. `initial` is what
1916
+ * the app chose for the person; it is read once.
1917
+ */
1918
+ function useChoices({ initial = [], implies, format: fmt = format } = {}) {
1919
+ const [state, setState] = React.useState(() => ({
1920
+ raw: new Set(initial),
1921
+ note: ""
1922
+ }));
1923
+ const impliesRef = React.useRef(implies);
1924
+ impliesRef.current = implies;
1925
+ const resolved = React.useMemo(() => resolve(state.raw, impliesRef.current), [state.raw, implies]);
1926
+ const onChange = React.useCallback((next) => setState((s) => {
1927
+ const change = applyChange(s.raw, next, impliesRef.current);
1928
+ return {
1929
+ raw: change.explicit,
1930
+ note: noteFor(change)
1931
+ };
1932
+ }), []);
1933
+ const clear = React.useCallback(() => setState({
1934
+ raw: /* @__PURE__ */ new Set(),
1935
+ note: ""
1936
+ }), []);
1937
+ const add = React.useCallback((keys) => setState((s) => {
1938
+ const change = applyChange(s.raw, /* @__PURE__ */ new Set([...resolve(s.raw, impliesRef.current).all, ...keys]), impliesRef.current);
1939
+ return {
1940
+ raw: change.explicit,
1941
+ note: noteFor(change)
1942
+ };
1943
+ }), []);
1944
+ const counts = {
1945
+ chosen: state.raw.size,
1946
+ dependents: resolved.dependents.size,
1947
+ total: resolved.all.size
1948
+ };
1949
+ return {
1950
+ /** Everything chosen: what the person chose and what that implies. */
1951
+ selected: resolved.all,
1952
+ count: resolved.all.size,
1953
+ onChange,
1954
+ add,
1955
+ clear,
1956
+ implied: resolved.locked,
1957
+ because: (key) => resolved.because.get(key) ?? [],
1958
+ counts,
1959
+ summary: (noun, then) => summarise(counts, noun, then, fmt),
1960
+ note: state.note
1961
+ };
1962
+ }
1889
1963
  /** The bar for a selection: a polite live count ("2 bookings selected"), the bulk actions, and Clear selection. Renders only the live region while nothing is chosen. */
1890
1964
  function BulkBar({ count, noun, onClear, children, format: format$1 = format, className }) {
1891
1965
  const [one, many] = typeof noun === "string" ? [noun, `${noun}s`] : noun;
@@ -3838,6 +3912,14 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3838
3912
  });
3839
3913
  }
3840
3914
  // src/lib/transcript.ts
3915
+ /** Whether a word is doubtful: the recogniser said so, or its confidence is under `below`. */
3916
+ function isDoubtful(word, below = .6) {
3917
+ return word.doubtful ?? (word.confidence !== void 0 && word.confidence < below);
3918
+ }
3919
+ /** Whether any word of a phrase is doubtful. */
3920
+ function phraseDoubtful(phrase, below = .6) {
3921
+ return phrase.words.some((w) => isDoubtful(w, below));
3922
+ }
3841
3923
  /** 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`. */
3842
3924
  function phraseAt(phrases, time) {
3843
3925
  let lo = 0;
@@ -3907,18 +3989,34 @@ var ALL = "all";
3907
3989
  var capital = (s) => s.charAt(0).toUpperCase() + s.slice(1);
3908
3990
  var range = (a, b) => `${format.runningTime(a)}–${format.runningTime(b)}`;
3909
3991
  /** Timed text that follows playback: the heard word marked, any word or phrase pressed to play from, modes, speakers, follow and Jump to now. */
3910
- function TranscriptView({ label, groups, time, onSeek, mode: controlledMode, onModeChange, modeLabels = {}, speaker: controlledSpeaker, onSpeakerChange, follow = true, announce = false, renderPlay, height = 480, className }) {
3992
+ function TranscriptView({ label, groups, time, onSeek, mode: controlledMode, onModeChange, modeLabels = {}, speaker: controlledSpeaker, onSpeakerChange, follow = true, announce = false, renderPlay, doubtfulBelow = .6, states = [], onPhraseState, renderActions, onEdit, renderCard, cardDelay = 500, height = 480, className }) {
3911
3993
  const [ownMode, setOwnMode] = React.useState("original");
3912
3994
  const [ownSpeaker, setOwnSpeaker] = React.useState(ALL);
3913
3995
  const mode = controlledMode ?? ownMode;
3914
3996
  const speaker = controlledSpeaker ?? ownSpeaker;
3915
3997
  const modes = React.useMemo(() => ["original", ...new Set(groups.flatMap((g) => g.phrases.flatMap((p) => Object.keys(p.alt ?? {}))))], [groups]);
3916
3998
  const speakers = React.useMemo(() => [...new Set(groups.flatMap((g) => g.phrases.map((p) => p.speaker).filter((s) => Boolean(s))))], [groups]);
3999
+ const [onlyDoubtful, setOnlyDoubtful] = React.useState(false);
4000
+ const summary = React.useMemo(() => {
4001
+ const mine = groups.flatMap((g) => g.phrases).filter((p) => speaker === ALL || p.speaker === speaker);
4002
+ const doubtful = mine.filter((p) => phraseDoubtful(p, doubtfulBelow)).length;
4003
+ const marked = /* @__PURE__ */ new Map();
4004
+ for (const p of mine) if (p.state) marked.set(p.state.label, (marked.get(p.state.label) ?? 0) + 1);
4005
+ return {
4006
+ doubtful,
4007
+ marked: [...marked]
4008
+ };
4009
+ }, [
4010
+ groups,
4011
+ speaker,
4012
+ doubtfulBelow
4013
+ ]);
4014
+ const filtering = onlyDoubtful && summary.doubtful > 0;
3917
4015
  const { rows, phrases } = React.useMemo(() => {
3918
4016
  const rows = [];
3919
4017
  const phrases = [];
3920
4018
  for (const g of groups) {
3921
- const mine = g.phrases.filter((p) => speaker === ALL || p.speaker === speaker);
4019
+ const mine = g.phrases.filter((p) => (speaker === ALL || p.speaker === speaker) && (!filtering || phraseDoubtful(p, doubtfulBelow)));
3922
4020
  if (mine.length === 0) continue;
3923
4021
  rows.push({
3924
4022
  kind: "heading",
@@ -3943,7 +4041,12 @@ function TranscriptView({ label, groups, time, onSeek, mode: controlledMode, onM
3943
4041
  rows,
3944
4042
  phrases
3945
4043
  };
3946
- }, [groups, speaker]);
4044
+ }, [
4045
+ groups,
4046
+ speaker,
4047
+ filtering,
4048
+ doubtfulBelow
4049
+ ]);
3947
4050
  const heard = phraseAt(phrases, time);
3948
4051
  const heardPhrase = heard >= 0 ? phrases[heard] : null;
3949
4052
  const heardWord = heardPhrase ? wordAt(heardPhrase, time) : -1;
@@ -4013,6 +4116,64 @@ function TranscriptView({ label, groups, time, onSeek, mode: controlledMode, onM
4013
4116
  heardId,
4014
4117
  heardText
4015
4118
  ]);
4119
+ const [editing, setEditing] = React.useState(null);
4120
+ const textOf = (p) => mode === "original" ? p.words.map((w) => w.text).join(" ") : p.alt?.[mode] ?? p.words.map((w) => w.text).join(" ");
4121
+ const rowEl = (id) => root.current?.querySelector(`[data-phrase="${CSS.escape(id)}"]`)?.closest("[role=\"row\"]") ?? null;
4122
+ const startEdit = (id) => {
4123
+ const p = phrases.find((x) => x.id === id);
4124
+ if (!p || !onEdit) return;
4125
+ setEditing({
4126
+ id,
4127
+ text: textOf(p),
4128
+ mode
4129
+ });
4130
+ setSaid(`Editing the phrase at ${format.runningTime(p.start)}. Control Enter saves, Escape cancels.`);
4131
+ };
4132
+ const stopEdit = (saved) => {
4133
+ const id = editing?.id;
4134
+ if (editing && saved) {
4135
+ const p = phrases.find((x) => x.id === editing.id);
4136
+ const was = p && (editing.mode === "original" ? p.words.map((w) => w.text).join(" ") : p.alt?.[editing.mode] ?? p.words.map((w) => w.text).join(" "));
4137
+ if (p && editing.text.trim() !== was) {
4138
+ onEdit?.(editing.id, editing.text.trim(), { mode: editing.mode });
4139
+ setSaid(`Saved the phrase at ${format.runningTime(p.start)}.`);
4140
+ } else setSaid("No change.");
4141
+ } else if (editing) setSaid("Edit cancelled.");
4142
+ setEditing(null);
4143
+ if (id) requestAnimationFrame(() => rowEl(id)?.focus());
4144
+ };
4145
+ const [card, setCard] = React.useState(null);
4146
+ const cardTimer = React.useRef(void 0);
4147
+ const dismissed = React.useRef(null);
4148
+ const showCard = (id) => {
4149
+ window.clearTimeout(cardTimer.current);
4150
+ if (id === null) return setCard(null);
4151
+ if (!renderCard || dismissed.current === id) return;
4152
+ cardTimer.current = window.setTimeout(() => setCard(id), cardDelay);
4153
+ };
4154
+ React.useEffect(() => () => window.clearTimeout(cardTimer.current), []);
4155
+ React.useEffect(() => {
4156
+ if (!card) return;
4157
+ const close = (e) => {
4158
+ if (e.key !== "Escape") return;
4159
+ dismissed.current = card;
4160
+ showCard(null);
4161
+ };
4162
+ document.addEventListener("keydown", close);
4163
+ return () => document.removeEventListener("keydown", close);
4164
+ }, [card]);
4165
+ const phraseOfEvent = (target) => {
4166
+ return (target?.closest?.("[role=\"row\"]"))?.querySelector("[data-phrase]")?.getAttribute("data-phrase") ?? null;
4167
+ };
4168
+ const onKeys = (e) => {
4169
+ if (!onEdit || editing) return;
4170
+ const id = phraseOfEvent(e.target);
4171
+ if (!id) return;
4172
+ if (e.key === "F2" || e.key === "Enter" && e.target.getAttribute("role") === "row") {
4173
+ e.preventDefault();
4174
+ startEdit(id);
4175
+ }
4176
+ };
4016
4177
  const setMode = (m) => {
4017
4178
  if (controlledMode === void 0) setOwnMode(m);
4018
4179
  onModeChange?.(m);
@@ -4040,33 +4201,55 @@ function TranscriptView({ label, groups, time, onSeek, mode: controlledMode, onM
4040
4201
  ref: root,
4041
4202
  className: cn("grid min-w-0 gap-3", className),
4042
4203
  children: [
4043
- (modes.length > 1 || speakers.length > 1) && /* @__PURE__ */ jsxs("div", {
4204
+ (modes.length > 1 || speakers.length > 1 || summary.doubtful > 0 || summary.marked.length > 0) && /* @__PURE__ */ jsxs("div", {
4044
4205
  className: "flex flex-wrap items-center gap-x-4 gap-y-2",
4045
- children: [modes.length > 1 && /* @__PURE__ */ jsx(ToggleGroup, {
4046
- label: `${label}: text`,
4047
- options: modeOptions,
4048
- value: mode,
4049
- onChange: setMode,
4050
- size: "sm"
4051
- }), speakers.length > 1 && (speakers.length <= 4 ? /* @__PURE__ */ jsx(ToggleGroup, {
4052
- label: `${label}: speaker`,
4053
- options: speakerOptions,
4054
- value: speaker,
4055
- onChange: setSpeaker,
4056
- size: "sm"
4057
- }) : /* @__PURE__ */ jsx(NativeSelect, {
4058
- "aria-label": `${label}: speaker`,
4059
- size: "sm",
4060
- value: speaker,
4061
- onChange: (e) => setSpeaker(e.target.value),
4062
- children: speakerOptions.map((o) => /* @__PURE__ */ jsx("option", {
4063
- value: o.value,
4064
- children: o.label
4065
- }, o.value))
4066
- }))]
4206
+ children: [
4207
+ modes.length > 1 && /* @__PURE__ */ jsx(ToggleGroup, {
4208
+ label: `${label}: text`,
4209
+ options: modeOptions,
4210
+ value: mode,
4211
+ onChange: setMode,
4212
+ size: "sm"
4213
+ }),
4214
+ speakers.length > 1 && (speakers.length <= 4 ? /* @__PURE__ */ jsx(ToggleGroup, {
4215
+ label: `${label}: speaker`,
4216
+ options: speakerOptions,
4217
+ value: speaker,
4218
+ onChange: setSpeaker,
4219
+ size: "sm"
4220
+ }) : /* @__PURE__ */ jsx(NativeSelect, {
4221
+ "aria-label": `${label}: speaker`,
4222
+ size: "sm",
4223
+ value: speaker,
4224
+ onChange: (e) => setSpeaker(e.target.value),
4225
+ children: speakerOptions.map((o) => /* @__PURE__ */ jsx("option", {
4226
+ value: o.value,
4227
+ children: o.label
4228
+ }, o.value))
4229
+ })),
4230
+ (summary.doubtful > 0 || summary.marked.length > 0) && /* @__PURE__ */ jsx("p", {
4231
+ className: "type-body-sm tabular-nums text-muted-foreground",
4232
+ children: [...summary.doubtful > 0 ? [`${summary.doubtful} doubtful`] : [], ...summary.marked.map(([name, n]) => `${n} ${name.toLowerCase()}`)].join(" · ")
4233
+ }),
4234
+ summary.doubtful > 0 && /* @__PURE__ */ jsx(Toggle, {
4235
+ label: "Only doubtful",
4236
+ size: "sm",
4237
+ pressed: onlyDoubtful,
4238
+ onChange: setOnlyDoubtful
4239
+ })
4240
+ ]
4067
4241
  }),
4068
4242
  /* @__PURE__ */ jsxs("div", {
4069
4243
  className: "relative",
4244
+ onKeyDown: onKeys,
4245
+ onFocus: (e) => showCard(phraseOfEvent(e.target)),
4246
+ onBlur: (e) => {
4247
+ if (!root.current?.contains(e.relatedTarget)) showCard(null);
4248
+ },
4249
+ onPointerLeave: () => {
4250
+ dismissed.current = null;
4251
+ showCard(null);
4252
+ },
4070
4253
  children: [/* @__PURE__ */ jsx(VirtualList, {
4071
4254
  label,
4072
4255
  items: rows,
@@ -4089,7 +4272,23 @@ function TranscriptView({ label, groups, time, onSeek, mode: controlledMode, onM
4089
4272
  active: row.index === heard,
4090
4273
  word: row.index === heard ? heardWord : -1,
4091
4274
  onSeek: seek,
4092
- play: renderPlay?.(row.phrase)
4275
+ play: renderPlay?.(row.phrase),
4276
+ doubtfulBelow,
4277
+ states,
4278
+ onPhraseState,
4279
+ actions: renderActions?.(row.phrase),
4280
+ edit: editing?.id === row.phrase.id ? {
4281
+ text: editing.text,
4282
+ change: (text) => setEditing({
4283
+ ...editing,
4284
+ text
4285
+ }),
4286
+ done: stopEdit
4287
+ } : void 0,
4288
+ onHover: (on) => {
4289
+ if (!on) dismissed.current = null;
4290
+ showCard(on ? row.phrase.id : null);
4291
+ }
4093
4292
  })
4094
4293
  }), follow && !following && heardPhrase && /* @__PURE__ */ jsx("div", {
4095
4294
  className: "pointer-events-none absolute inset-x-0 bottom-2 flex justify-center",
@@ -4106,47 +4305,132 @@ function TranscriptView({ label, groups, time, onSeek, mode: controlledMode, onM
4106
4305
  /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx("span", {
4107
4306
  role: "status",
4108
4307
  children: said
4109
- }) })
4308
+ }) }),
4309
+ card && renderCard && (() => {
4310
+ const p = phrases.find((x) => x.id === card);
4311
+ const anchor = rowEl(card);
4312
+ return p && anchor ? /* @__PURE__ */ jsx(Popover$1, {
4313
+ triggerRef: { current: anchor },
4314
+ isOpen: true,
4315
+ isNonModal: true,
4316
+ placement: "bottom start",
4317
+ offset: 4,
4318
+ className: cn("layer-overlay max-w-xs p-3", "rounded-overlay border border-border bg-popover text-popover-foreground shadow-overlay enter-overlay"),
4319
+ children: /* @__PURE__ */ jsx("div", {
4320
+ "data-card": card,
4321
+ children: renderCard(p)
4322
+ })
4323
+ }) : null;
4324
+ })()
4110
4325
  ]
4111
4326
  });
4112
4327
  }
4113
- function PhraseRow({ phrase, mode, active, word, onSeek, play }) {
4328
+ function PhraseRow({ phrase, mode, active, word, onSeek, play, doubtfulBelow, states, onPhraseState, actions, edit, onHover }) {
4114
4329
  const alt = mode === "original" ? null : phrase.alt?.[mode] ?? null;
4330
+ const doubtful = phraseDoubtful(phrase, doubtfulBelow);
4331
+ const marks = states.filter((s) => s.id !== phrase.state?.id).map((s) => ({
4332
+ id: s.id,
4333
+ label: s.label,
4334
+ run: () => onPhraseState?.(phrase.id, s.id)
4335
+ }));
4336
+ const commands = [...marks.length > 0 ? [{
4337
+ group: "Mark as",
4338
+ items: marks
4339
+ }] : [], ...phrase.state ? [{
4340
+ id: "clear",
4341
+ label: "Clear mark",
4342
+ run: () => onPhraseState?.(phrase.id, null)
4343
+ }] : []];
4115
4344
  return /* @__PURE__ */ jsxs("div", {
4116
4345
  "data-phrase": phrase.id,
4117
4346
  "data-active": active ? "" : void 0,
4118
4347
  "aria-current": active ? "true" : void 0,
4348
+ onPointerEnter: () => onHover(true),
4119
4349
  className: cn("flex items-start gap-2 border-l-2 border-transparent px-3 py-2", active && "border-primary bg-accent"),
4120
- children: [play, /* @__PURE__ */ jsxs("div", {
4121
- className: "min-w-0 flex-1",
4122
- children: [/* @__PURE__ */ jsxs("div", {
4123
- className: "flex items-baseline gap-2",
4124
- children: [phrase.speaker && /* @__PURE__ */ jsx("span", {
4125
- className: "type-label text-muted-foreground",
4126
- children: phrase.speaker
4127
- }), /* @__PURE__ */ jsx(Button$1, {
4350
+ children: [
4351
+ play,
4352
+ /* @__PURE__ */ jsxs("div", {
4353
+ className: "min-w-0 flex-1",
4354
+ children: [/* @__PURE__ */ jsxs("div", {
4355
+ className: "flex flex-wrap items-baseline gap-2",
4356
+ children: [
4357
+ phrase.speaker && /* @__PURE__ */ jsx("span", {
4358
+ className: "type-label text-muted-foreground",
4359
+ children: phrase.speaker
4360
+ }),
4361
+ /* @__PURE__ */ jsx(Button$1, {
4362
+ onPress: () => onSeek(phrase.start, { phraseId: phrase.id }),
4363
+ className: "rounded-control type-caption tabular-nums text-muted-foreground hover:text-foreground",
4364
+ "aria-label": `Play from ${format.runningTime(phrase.start)}`,
4365
+ children: format.runningTime(phrase.start)
4366
+ }),
4367
+ doubtful && /* @__PURE__ */ jsx(Status, {
4368
+ tone: "warning",
4369
+ children: "Doubtful"
4370
+ }),
4371
+ phrase.state && /* @__PURE__ */ jsx(Status, {
4372
+ tone: phrase.state.tone,
4373
+ children: phrase.state.label
4374
+ })
4375
+ ]
4376
+ }), edit ? /* @__PURE__ */ jsxs("div", {
4377
+ className: "mt-1 grid gap-2",
4378
+ children: [/* @__PURE__ */ jsx(Textarea, {
4379
+ autoFocus: true,
4380
+ "aria-label": `Edit the phrase at ${format.runningTime(phrase.start)}`,
4381
+ value: edit.text,
4382
+ onChange: (e) => edit.change(e.target.value),
4383
+ onKeyDown: (e) => {
4384
+ e.stopPropagation();
4385
+ if (e.key === "Escape") edit.done(false);
4386
+ else if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) edit.done(true);
4387
+ },
4388
+ className: "min-h-16"
4389
+ }), /* @__PURE__ */ jsxs("div", {
4390
+ className: "flex gap-2",
4391
+ children: [/* @__PURE__ */ jsx(Button, {
4392
+ size: "sm",
4393
+ variant: "default",
4394
+ onPress: () => edit.done(true),
4395
+ children: "Save"
4396
+ }), /* @__PURE__ */ jsx(Button, {
4397
+ size: "sm",
4398
+ variant: "ghost",
4399
+ onPress: () => edit.done(false),
4400
+ children: "Cancel"
4401
+ })]
4402
+ })]
4403
+ }) : alt !== null ? /* @__PURE__ */ jsx(Button$1, {
4128
4404
  onPress: () => onSeek(phrase.start, { phraseId: phrase.id }),
4129
- className: "rounded-control type-caption tabular-nums text-muted-foreground hover:text-foreground",
4130
- "aria-label": `Play from ${format.runningTime(phrase.start)}`,
4131
- children: format.runningTime(phrase.start)
4405
+ className: cn("rounded-control text-left type-body", active && "font-medium underline decoration-2 underline-offset-4"),
4406
+ children: alt
4407
+ }) : /* @__PURE__ */ jsx("p", {
4408
+ className: "type-body",
4409
+ children: phrase.words.map((w, i) => /* @__PURE__ */ jsxs(React.Fragment, { children: [i > 0 && " ", /* @__PURE__ */ jsxs(Button$1, {
4410
+ "aria-current": i === word ? "true" : void 0,
4411
+ "data-doubtful": isDoubtful(w, doubtfulBelow) ? "" : void 0,
4412
+ onPress: () => onSeek(w.start, {
4413
+ phraseId: phrase.id,
4414
+ wordIndex: i
4415
+ }),
4416
+ className: cn("rounded-control hover:bg-muted", isDoubtful(w, doubtfulBelow) && "underline decoration-dotted decoration-2 underline-offset-4", i === word && "font-medium underline decoration-2 underline-offset-4"),
4417
+ children: [w.text, isDoubtful(w, doubtfulBelow) && /* @__PURE__ */ jsx(VisuallyHidden, { children: " (doubtful)" })]
4418
+ })] }, i))
4132
4419
  })]
4133
- }), alt !== null ? /* @__PURE__ */ jsx(Button$1, {
4134
- onPress: () => onSeek(phrase.start, { phraseId: phrase.id }),
4135
- className: cn("rounded-control text-left type-body", active && "font-medium underline decoration-2 underline-offset-4"),
4136
- children: alt
4137
- }) : /* @__PURE__ */ jsx("p", {
4138
- className: "type-body",
4139
- children: phrase.words.map((w, i) => /* @__PURE__ */ jsxs(React.Fragment, { children: [i > 0 && " ", /* @__PURE__ */ jsx(Button$1, {
4140
- "aria-current": i === word ? "true" : void 0,
4141
- onPress: () => onSeek(w.start, {
4142
- phraseId: phrase.id,
4143
- wordIndex: i
4420
+ }),
4421
+ (commands.length > 0 || actions) && !edit && /* @__PURE__ */ jsxs("div", {
4422
+ className: "flex shrink-0 items-center gap-1",
4423
+ children: [commands.length > 0 && /* @__PURE__ */ jsx(Menu, {
4424
+ label: `Mark the phrase at ${format.runningTime(phrase.start)}`,
4425
+ trigger: /* @__PURE__ */ jsx(IconButton, {
4426
+ icon: Ellipsis,
4427
+ label: `Mark the phrase at ${format.runningTime(phrase.start)}`,
4428
+ size: "sm"
4144
4429
  }),
4145
- className: cn("rounded-control hover:bg-muted", i === word && "font-medium underline decoration-2 underline-offset-4"),
4146
- children: w.text
4147
- })] }, i))
4148
- })]
4149
- })]
4430
+ items: commands
4431
+ }), actions]
4432
+ })
4433
+ ]
4150
4434
  });
4151
4435
  }
4152
4436
  // src/lib/waveform.ts
@@ -8003,6 +8287,98 @@ function frameBoxToShares(rect, v, frame) {
8003
8287
  }
8004
8288
  // src/components/compare-parts.tsx
8005
8289
  var VIEWPORT_HEIGHT = "max(16rem, calc(100svh - 14rem))";
8290
+ /** The tallest each row of frames may be so that all of `chrome` and `rows` rows fit in `space` pixels. Pure, so it is tested without a layout. */
8291
+ function fitFrames({ space, chrome, rows, min = 120 }) {
8292
+ return Math.max(min, Math.floor((space - chrome) / Math.max(1, rows)));
8293
+ }
8294
+ /** Frame cap for what the caller asked for: a measured height for `"fit"` and in full screen (whatever the caller passed, so the frame fills what the controls leave), the guess for `"viewport"`, the caller's own length otherwise. */
8295
+ function frameCap(maxHeight, fit, full) {
8296
+ if ((maxHeight === "fit" || full) && fit !== null) return `${fit}px`;
8297
+ return maxHeight === "viewport" || maxHeight === "fit" ? VIEWPORT_HEIGHT : maxHeight;
8298
+ }
8299
+ /**
8300
+ * How tall each frame may be for the pair and everything around it to fit the window (issue #229), measured, not
8301
+ * guessed. In the page: the window's height from the top of `root` (as the page is at its top), less what `root` draws
8302
+ * besides its frames (toolbar, captions, footer, legend: the bottom of its last child, not its height, which a stretched
8303
+ * full-screen section would inflate), less what follows it (later siblings of it and of its ancestors, then `reserve` for
8304
+ * padding and gaps the caller knows). In full screen: the window from the top of `root`, nothing after. Divided by the
8305
+ * rows of frames (side by side is one row; below `sm` it is two) and floored at `MIN_FIT`. Frames are found by
8306
+ * `data-viewport-frame`, so an app never queries for them. Null until measured, or when `enabled` is false.
8307
+ */
8308
+ function useFitHeight(root, { enabled, full, reserve = 0 }) {
8309
+ const [fit, setFit] = React.useState(null);
8310
+ React.useLayoutEffect(() => {
8311
+ if (!enabled) {
8312
+ setFit(null);
8313
+ return;
8314
+ }
8315
+ const el = root.current;
8316
+ if (!el) return;
8317
+ const measure = () => {
8318
+ const frames = [...el.querySelectorAll("[data-viewport-frame]")].map((f) => f.getBoundingClientRect());
8319
+ if (!frames.length) return;
8320
+ const top = el.getBoundingClientRect().top;
8321
+ const rows = [];
8322
+ for (const r of frames) {
8323
+ const row = rows.find((x) => Math.abs(x.top - r.top) < 2);
8324
+ if (row) row.height = Math.max(row.height, r.height);
8325
+ else rows.push({
8326
+ top: r.top,
8327
+ height: r.height
8328
+ });
8329
+ }
8330
+ const chrome = Math.max(el.lastElementChild?.getBoundingClientRect().bottom ?? 0, ...frames.map((r) => r.bottom)) - top - rows.reduce((sum, r) => sum + r.height, 0);
8331
+ const windowHeight = document.documentElement.clientHeight;
8332
+ let space;
8333
+ if (full) {
8334
+ const pad = el.parentElement ? parseFloat(getComputedStyle(el.parentElement).paddingBottom) || 0 : 0;
8335
+ space = windowHeight - top - pad;
8336
+ } else {
8337
+ let after = 0;
8338
+ for (let n = el; n && n !== document.body; n = n.parentElement) for (let sib = n.nextElementSibling; sib; sib = sib.nextElementSibling) {
8339
+ const position = getComputedStyle(sib).position;
8340
+ if (position !== "fixed" && position !== "absolute") after += sib.getBoundingClientRect().height;
8341
+ }
8342
+ space = windowHeight - (top + window.scrollY) - after - reserve;
8343
+ }
8344
+ const next = fitFrames({
8345
+ space,
8346
+ chrome,
8347
+ rows: rows.length
8348
+ });
8349
+ setFit((was) => was !== null && Math.abs(was - next) <= 1 ? was : next);
8350
+ };
8351
+ let frame = 0;
8352
+ const schedule = () => {
8353
+ cancelAnimationFrame(frame);
8354
+ frame = requestAnimationFrame(measure);
8355
+ };
8356
+ measure();
8357
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
8358
+ observer?.observe(el);
8359
+ observer?.observe(document.body);
8360
+ const changes = new MutationObserver(schedule);
8361
+ changes.observe(el, {
8362
+ childList: true,
8363
+ subtree: true
8364
+ });
8365
+ window.addEventListener("resize", schedule);
8366
+ document.addEventListener("fullscreenchange", schedule);
8367
+ return () => {
8368
+ cancelAnimationFrame(frame);
8369
+ observer?.disconnect();
8370
+ changes.disconnect();
8371
+ window.removeEventListener("resize", schedule);
8372
+ document.removeEventListener("fullscreenchange", schedule);
8373
+ };
8374
+ }, [
8375
+ root,
8376
+ enabled,
8377
+ full,
8378
+ reserve
8379
+ ]);
8380
+ return fit;
8381
+ }
8006
8382
  /** 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. */
8007
8383
  function makePicker(a, b, onPick, words) {
8008
8384
  const choose = words?.choose ?? ((label) => `Click to choose ${label}`);
@@ -8089,7 +8465,7 @@ function Picture({ c, blind, missing, onNatural, imgRef, pixelated }) {
8089
8465
  style: pixelated ? { imageRendering: "pixelated" } : void 0,
8090
8466
  onLoad: (e) => {
8091
8467
  setState("ready");
8092
- onNatural?.(e.currentTarget.naturalWidth, e.currentTarget.naturalHeight);
8468
+ if (e.currentTarget.naturalWidth && e.currentTarget.naturalHeight) onNatural?.(e.currentTarget.naturalWidth, e.currentTarget.naturalHeight);
8093
8469
  },
8094
8470
  onError: () => setState("failed"),
8095
8471
  className: "absolute inset-0 size-full object-contain"
@@ -8439,6 +8815,7 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
8439
8815
  return /* @__PURE__ */ jsxs("div", {
8440
8816
  ref,
8441
8817
  role: "group",
8818
+ "data-viewport-frame": "",
8442
8819
  "aria-label": label,
8443
8820
  "aria-roledescription": "zoomable picture",
8444
8821
  tabIndex: 0,
@@ -8750,7 +9127,7 @@ var ALL_MODES = [
8750
9127
  "difference"
8751
9128
  ];
8752
9129
  /** Two pictures to judge, side by side or laid over each other, zoomed and panned together, and full screen. */
8753
- 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 }) {
9130
+ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, regions, onPick, pick = true, pickWords, keys = true, extraShortcuts = [], footer, maxHeight, reserve, cannotCompare = "Could not read these pictures to compare their pixels.", readPixels, defaultDifference = "brightness", className }) {
8754
9131
  const { viewport, setViewport } = useViewport();
8755
9132
  const [full, setFull] = React.useState(false);
8756
9133
  const pairKey = `${a.media.src}|${b.media.src}`;
@@ -8766,6 +9143,12 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
8766
9143
  const frameRef = React.useRef(null);
8767
9144
  const imgRef = React.useRef(null);
8768
9145
  const aspect = natural ? natural[0] / natural[1] : 3 / 2;
9146
+ const sectionRef = React.useRef(null);
9147
+ const fit = useFitHeight(sectionRef, {
9148
+ enabled: maxHeight === "fit" || full,
9149
+ full,
9150
+ reserve
9151
+ });
8769
9152
  const rg = useRegions({
8770
9153
  regions,
8771
9154
  viewport,
@@ -8817,7 +9200,7 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
8817
9200
  onBox: rg.add,
8818
9201
  outline: rg.peek,
8819
9202
  aspect,
8820
- maxHeight: maxHeight === "viewport" ? VIEWPORT_HEIGHT : maxHeight
9203
+ maxHeight: frameCap(maxHeight, fit, full)
8821
9204
  };
8822
9205
  let body;
8823
9206
  if (mode === "side") body = /* @__PURE__ */ jsx("div", {
@@ -8949,6 +9332,7 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
8949
9332
  onActiveChange: setFull,
8950
9333
  className,
8951
9334
  children: /* @__PURE__ */ jsxs("section", {
9335
+ ref: sectionRef,
8952
9336
  "aria-label": label,
8953
9337
  className: cn("grid gap-3", full && "min-h-0 flex-1 content-start overflow-auto"),
8954
9338
  children: [
@@ -10249,7 +10633,7 @@ var MODE_LABEL = {
10249
10633
  blink: "Blink"
10250
10634
  };
10251
10635
  /** Two videos to judge by eye on one clock: side by side, swipe, fade or blink, zoomed together, with matched sound and full screen. */
10252
- 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 }) {
10636
+ 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, reserve, keys = true, extraShortcuts = [], footer, className }) {
10253
10637
  const clock = useVideoClock({
10254
10638
  fps: a.media.fps ?? 30,
10255
10639
  loop: loopProp,
@@ -10269,6 +10653,12 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
10269
10653
  const frameWidth = useWidth(frameRef);
10270
10654
  const { wanted, failed } = clock;
10271
10655
  const aspect = a.media.width / a.media.height;
10656
+ const sectionRef = React.useRef(null);
10657
+ const fit = useFitHeight(sectionRef, {
10658
+ enabled: maxHeight === "fit" || full,
10659
+ full,
10660
+ reserve
10661
+ });
10272
10662
  const natural = [a.media.width, a.media.height];
10273
10663
  const frameHeight = frameWidth / aspect;
10274
10664
  const sharpFor = (c) => {
@@ -10312,7 +10702,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
10312
10702
  onBox: wanted ? void 0 : rg.add,
10313
10703
  outline: rg.peek,
10314
10704
  aspect,
10315
- maxHeight: maxHeight === "viewport" ? VIEWPORT_HEIGHT : maxHeight
10705
+ maxHeight: frameCap(maxHeight, fit, full)
10316
10706
  };
10317
10707
  const shortcuts = [
10318
10708
  ...extraShortcuts,
@@ -10412,6 +10802,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
10412
10802
  onActiveChange: setFull,
10413
10803
  className,
10414
10804
  children: /* @__PURE__ */ jsxs("section", {
10805
+ ref: sectionRef,
10415
10806
  "aria-label": label,
10416
10807
  className: cn("grid gap-3", full && "min-h-0 flex-1 content-start overflow-auto"),
10417
10808
  children: [
@@ -12871,6 +13262,7 @@ function Node$1({ node }) {
12871
13262
  const branch = c.isBranch ? c.isBranch(node) : true;
12872
13263
  const open = branch && c.expanded.isOpen(key);
12873
13264
  const name = c.nodeLabel(node);
13265
+ const because = c.choices?.implied.has(key) ? c.choices.because(key).map((k) => c.nodes.has(k) ? c.nodeLabel(c.nodes.get(k)) : k) : [];
12874
13266
  return /* @__PURE__ */ jsxs(TreeItem, {
12875
13267
  id: key,
12876
13268
  textValue: name,
@@ -12882,6 +13274,10 @@ function Node$1({ node }) {
12882
13274
  style: { paddingInlineStart: `${(level - 1) * 1.25 + .25}rem` },
12883
13275
  "data-selected": isSelected || void 0,
12884
13276
  children: [
13277
+ c.choices && /* @__PURE__ */ jsx(TableSelectionCheckbox, {
13278
+ label: `Choose ${name}`,
13279
+ mixed: c.stateOf(key) === "mixed"
13280
+ }),
12885
13281
  branch ? /* @__PURE__ */ jsx(Button$1, {
12886
13282
  slot: "chevron",
12887
13283
  className: "grid size-6 shrink-0 place-items-center rounded-control text-muted-foreground",
@@ -12908,6 +13304,21 @@ function Node$1({ node }) {
12908
13304
  level,
12909
13305
  branch
12910
13306
  }) : name
13307
+ }),
13308
+ because.length > 0 && /* @__PURE__ */ jsxs("span", {
13309
+ className: "flex max-w-[50%] shrink-0 items-center gap-1 truncate type-caption text-muted-foreground",
13310
+ title: `Included because of ${because.join(", ")}`,
13311
+ children: [/* @__PURE__ */ jsx(Lock, {
13312
+ "aria-hidden": true,
13313
+ className: "size-3 shrink-0"
13314
+ }), /* @__PURE__ */ jsxs("span", {
13315
+ className: "truncate",
13316
+ children: [
13317
+ "Included because of ",
13318
+ because.slice(0, 2).join(", "),
13319
+ because.length > 2 ? ` and ${because.length - 2} more` : ""
13320
+ ]
13321
+ })]
12911
13322
  })
12912
13323
  ]
12913
13324
  }) }), open ? /* @__PURE__ */ jsx(Children, { node }) : branch && /* @__PURE__ */ jsx(ClosedChild, { id: `${key}${NOTE}closed` })]
@@ -12929,6 +13340,10 @@ function Children({ node }) {
12929
13340
  const c = useCtx();
12930
13341
  const key = c.nodeKey(node);
12931
13342
  const load = c.useChildren(node);
13343
+ const ready = load.status === "ready" ? load.data : void 0;
13344
+ React.useEffect(() => {
13345
+ if (ready) c.settle(key, ready);
13346
+ }, [ready]);
12932
13347
  if (load.status === "loading") return /* @__PURE__ */ jsx(TreeItem, {
12933
13348
  id: `${key}${NOTE}loading`,
12934
13349
  textValue: "Loading",
@@ -12993,23 +13408,68 @@ function Children({ node }) {
12993
13408
  })]
12994
13409
  }) })
12995
13410
  }, "empty");
13411
+ c.childKeys.set(key, load.data.map(c.nodeKey));
12996
13412
  return /* @__PURE__ */ jsx(Nodes, { nodes: load.data });
12997
13413
  }
12998
13414
  /** 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. */
12999
- function Tree({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderNode, selected, onSelect, expanded, loadingRow, emptyRow, height = "24rem", className }) {
13415
+ function Tree({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderNode, selected, onSelect, choices, expanded, loadingRow, emptyRow, height = "24rem", className }) {
13000
13416
  const nodes = React.useRef(/* @__PURE__ */ new Map()).current;
13417
+ const childKeys = React.useRef(/* @__PURE__ */ new Map()).current;
13418
+ const below = (key) => (childKeys.get(key) ?? []).flatMap((k) => [k, ...below(k)]);
13419
+ const stateOf = (key) => {
13420
+ const all = choices?.selected;
13421
+ const own = all?.has(key) ?? false;
13422
+ const ds = below(key);
13423
+ if (ds.length === 0) return own ? "on" : "off";
13424
+ const chosen = ds.filter((k) => all?.has(k)).length;
13425
+ if (chosen === ds.length) return "on";
13426
+ return chosen === 0 && !own ? "off" : "mixed";
13427
+ };
13428
+ const awaiting = React.useRef(/* @__PURE__ */ new Set()).current;
13429
+ const latest = React.useRef({
13430
+ expanded,
13431
+ choices
13432
+ });
13433
+ latest.current = {
13434
+ expanded,
13435
+ choices
13436
+ };
13437
+ const opening = React.useRef(/* @__PURE__ */ new Set()).current;
13438
+ const open = (keys) => {
13439
+ for (const k of keys) opening.add(k);
13440
+ latest.current.expanded.onChange(/* @__PURE__ */ new Set([...latest.current.expanded.expanded, ...opening]));
13441
+ };
13442
+ const unread = (key) => {
13443
+ const node = nodes.get(key);
13444
+ return node !== void 0 && (isBranch ? isBranch(node) : true) && !childKeys.has(key);
13445
+ };
13446
+ const tick = (keys) => {
13447
+ const toOpen = keys.filter(unread);
13448
+ for (const k of toOpen) awaiting.add(k);
13449
+ if (toOpen.length) open(toOpen);
13450
+ };
13451
+ const settle = (key, kids) => {
13452
+ opening.delete(key);
13453
+ if (!awaiting.delete(key) || !latest.current.choices) return;
13454
+ const keys = kids.map(nodeKey);
13455
+ for (const kid of kids) nodes.set(nodeKey(kid), kid);
13456
+ latest.current.choices.add(keys);
13457
+ tick(keys);
13458
+ };
13001
13459
  const ctx = {
13002
13460
  useChildren,
13003
13461
  nodeKey,
13004
13462
  nodeLabel,
13005
13463
  isBranch,
13006
13464
  renderNode,
13007
- selected,
13008
- onSelect,
13009
13465
  expanded,
13010
13466
  loadingRow,
13011
13467
  emptyRow,
13012
- nodes
13468
+ nodes,
13469
+ childKeys,
13470
+ choices,
13471
+ stateOf,
13472
+ settle
13013
13473
  };
13014
13474
  if (roots.status === "loading") return /* @__PURE__ */ jsx("div", {
13015
13475
  role: "status",
@@ -13050,26 +13510,55 @@ function Tree({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderN
13050
13510
  if (first === void 0 || isNote(String(first))) return;
13051
13511
  const key = String(first);
13052
13512
  const node = nodes.get(key);
13053
- if (node !== void 0) onSelect(key, node);
13513
+ if (node !== void 0) onSelect?.(key, node);
13514
+ };
13515
+ const displayKeys = choices ? [.../* @__PURE__ */ new Set([...choices.selected, ...nodes.keys()])].filter((k) => stateOf(k) === "on" || choices.selected.has(k) && !nodes.has(k)) : [];
13516
+ const shown = () => {
13517
+ const walk = (keys) => keys.flatMap((k) => expanded.isOpen(k) && childKeys.has(k) ? [k, ...walk(childKeys.get(k))] : [k]);
13518
+ return walk(roots.data.map(nodeKey));
13519
+ };
13520
+ const chooseMany = (keys) => {
13521
+ if (!choices) return;
13522
+ const wanted = new Set(choices.selected);
13523
+ if (keys === "all") {
13524
+ const rows = shown().flatMap((k) => [k, ...below(k)]);
13525
+ for (const x of rows) wanted.add(x);
13526
+ choices.onChange(wanted);
13527
+ tick(rows);
13528
+ return;
13529
+ }
13530
+ const display = new Set(displayKeys);
13531
+ const next = new Set([...keys].map(String).filter((k) => !isNote(k)));
13532
+ for (const k of /* @__PURE__ */ new Set([...next, ...display])) {
13533
+ if (next.has(k) === display.has(k)) continue;
13534
+ const under = [k, ...below(k)];
13535
+ for (const x of under) if (next.has(k)) wanted.add(x);
13536
+ else {
13537
+ wanted.delete(x);
13538
+ awaiting.delete(x);
13539
+ }
13540
+ if (next.has(k)) tick(under);
13541
+ }
13542
+ choices.onChange(wanted);
13054
13543
  };
13055
13544
  const tree = /* @__PURE__ */ jsx(Tree$1, {
13056
13545
  "aria-label": label,
13057
- selectionMode: "single",
13058
- disallowEmptySelection: true,
13059
- selectedKeys: selected === null ? [] : [selected],
13060
- onSelectionChange: choose,
13546
+ selectionMode: choices ? "multiple" : "single",
13547
+ disallowEmptySelection: !choices,
13548
+ selectedKeys: choices ? displayKeys : selected === null ? [] : [selected],
13549
+ onSelectionChange: choices ? chooseMany : choose,
13061
13550
  expandedKeys: expanded.expanded,
13062
13551
  onExpandedChange: (keys) => expanded.onChange(new Set([...keys].map(String).filter((k) => !isNote(k)))),
13063
13552
  renderEmptyState: () => /* @__PURE__ */ jsx("p", {
13064
13553
  className: "p-3 type-body-sm text-muted-foreground",
13065
13554
  children: emptyRow
13066
13555
  }),
13067
- className: cn("min-w-0 overflow-y-auto outline-none", className),
13556
+ className: cn("min-w-0 overflow-y-auto outline-none", !choices && className),
13068
13557
  style: { maxHeight: height },
13069
13558
  "data-strata-scroll": "",
13070
13559
  children: /* @__PURE__ */ jsx(Nodes, { nodes: roots.data })
13071
13560
  });
13072
- return /* @__PURE__ */ jsx(Context.Provider, {
13561
+ const body = /* @__PURE__ */ jsx(Context.Provider, {
13073
13562
  value: ctx,
13074
13563
  children: /* @__PURE__ */ jsx(Virtualizer, {
13075
13564
  layout: ListLayout,
@@ -13077,6 +13566,32 @@ function Tree({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderN
13077
13566
  children: tree
13078
13567
  })
13079
13568
  });
13569
+ if (!choices) return body;
13570
+ return /* @__PURE__ */ jsxs("div", {
13571
+ className: cn("grid min-w-0 gap-2", className),
13572
+ children: [
13573
+ /* @__PURE__ */ jsxs("div", {
13574
+ className: "flex items-center gap-2",
13575
+ children: [/* @__PURE__ */ jsx(Button, {
13576
+ size: "sm",
13577
+ variant: "ghost",
13578
+ onPress: () => chooseMany("all"),
13579
+ children: "Select all shown"
13580
+ }), choices.count > 0 && /* @__PURE__ */ jsx(Button, {
13581
+ size: "sm",
13582
+ variant: "ghost",
13583
+ onPress: choices.clear,
13584
+ children: "Clear"
13585
+ })]
13586
+ }),
13587
+ body,
13588
+ /* @__PURE__ */ jsx("p", {
13589
+ role: "status",
13590
+ className: "sr-only",
13591
+ children: choices.note
13592
+ })
13593
+ ]
13594
+ });
13080
13595
  }
13081
13596
  // src/components/folder-picker.tsx
13082
13597
  var SEP = "/";
@@ -13540,6 +14055,6 @@ function MarkableText({ label, ids, marks, kinds, onMark, clearKeys = [], onCare
13540
14055
  ]
13541
14056
  });
13542
14057
  }
13543
- 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, SpanActions, 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, useMediaSpans, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, useWorkspaceState, valueAt, wordAt, zoomAt };
14058
+ 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, SecretField, SeekBar, SelectableGrid, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, 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, isDoubtful, isReservedChord, isTypingTarget, joinMediaGroup, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveRect, noOverlap, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, phraseDoubtful, 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, useChoices, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useLeaveGuard, useLoad, useMediaElement, useMediaSpans, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, useWorkspaceState, valueAt, wordAt, zoomAt };
13544
14059
 
13545
14060
  //# sourceMappingURL=index.js.map