strata-react 1.3.7 → 1.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import { n as useSharedCursor, r as geo, t as CursorScope } from "./cursor-DDGBP
7
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-By3DSUTs.js";
8
8
  import * as React from "react";
9
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, Link, ListBox, ListBoxItem, ListLayout, ListStateContext, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, Popover as Popover$1, RouterProvider, 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, ChevronDown, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, CloudOff, Columns2, Ellipsis, Eye, EyeOff, FileQuestion, Flag, Folder, FolderOpen, GripVertical, History, ImageOff, Info, KeyRound, LayoutGrid, List, Loader, LoaderCircle, Lock, Maximize, Maximize2, Minimize, Minus, PanelBottomClose, PanelBottomOpen, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen, PanelTopClose, PanelTopOpen, Pause, Pencil, Play, Redo2, RotateCcw, RotateCw, Scan, Search, Send, SkipBack, SkipForward, SlidersHorizontal, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
10
+ import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronDown, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, CircleDashed, Clock, CloudOff, Columns2, Ellipsis, Eye, EyeOff, FileQuestion, Flag, Folder, FolderOpen, GripVertical, History, ImageOff, Info, KeyRound, LayoutGrid, List, Loader, LoaderCircle, Lock, Maximize, Maximize2, Minimize, Minus, PanelBottomClose, PanelBottomOpen, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen, PanelTopClose, PanelTopOpen, Pause, Pencil, Play, Redo2, RotateCcw, RotateCw, Scan, Search, Send, SkipBack, SkipForward, SlidersHorizontal, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
11
11
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
12
  import { Link as Link$1, NavLink, useHref, useNavigate, useSearchParams } from "react-router";
13
13
  import { createSortedRowModel, flexRender, rowSortingFeature, tableFeatures, useTable } from "@tanstack/react-table";
@@ -1800,94 +1800,133 @@ function useJobAction({ start, job, queued, done, jobsHref, jobsLabel = "Show jo
1800
1800
  running: waiting && (running || action.phase === "pending")
1801
1801
  };
1802
1802
  }
1803
- // src/components/thumbnail.tsx
1804
- var ratio = (aspect) => typeof aspect === "number" ? String(aspect) : aspect.replace("/", " / ");
1805
- /** A box of fixed aspect ratio for a remote image: a skeleton until it loads, the `missing` words (or a `fallback`) if it cannot, a request only when it nears the screen, and `children` overlaid in its corners. `alt` and `missing` or `fallback` are required. */
1806
- function Thumbnail({ src, alt, missing, aspect = 1, fit = "cover", srcSet, sizes, eager = false, rootMargin = "200px", className, fallback, onLoad, onMissing, children }) {
1807
- const sources = React.useMemo(() => src === null ? [] : typeof src === "string" ? src ? [src] : [] : src.filter(Boolean), [src]);
1808
- const key = sources.length ? `${sources.join("\n")} ${srcSet ?? ""}` : null;
1809
- const [outcome, setOutcome] = React.useState(null);
1810
- const mine = key !== null && outcome?.key === key ? outcome : null;
1811
- const index = mine?.index ?? 0;
1812
- const phase = key === null ? "missing" : mine?.done ?? "loading";
1813
- const current = sources[index];
1814
- const near = useInView({
1815
- active: !eager && sources.length > 0,
1816
- rootMargin,
1817
- once: true,
1818
- unsupported: true
1819
- });
1820
- const requested = eager || near.inView;
1821
- const fail = () => setOutcome(index + 1 < sources.length ? {
1822
- key,
1823
- index: index + 1,
1824
- done: null
1825
- } : {
1826
- key,
1827
- index,
1828
- done: "missing"
1829
- });
1830
- const told = React.useRef(null);
1831
- const tell = React.useRef(onMissing);
1832
- tell.current = onMissing;
1833
- React.useEffect(() => {
1834
- if (phase !== "missing") told.current = null;
1835
- else if (key !== null && told.current !== key) {
1836
- told.current = key;
1837
- tell.current?.();
1838
- }
1839
- }, [key, phase]);
1840
- const name = [alt, missing].filter(Boolean).join(": ");
1841
- return /* @__PURE__ */ jsxs("div", {
1842
- ref: near.ref,
1843
- className: cn("relative overflow-hidden rounded-control bg-muted", className),
1844
- style: { aspectRatio: ratio(aspect) },
1845
- "aria-busy": phase === "loading" || void 0,
1846
- children: [
1847
- phase === "loading" && /* @__PURE__ */ jsx(Skeleton, { className: "absolute inset-0" }),
1848
- key !== null && phase !== "missing" && requested && /* @__PURE__ */ jsx("img", {
1849
- src: current,
1850
- srcSet: index === 0 ? srcSet : void 0,
1851
- sizes,
1852
- alt,
1853
- decoding: "async",
1854
- onLoad: (e) => onLoad?.(e.currentTarget, index) === false ? fail() : setOutcome({
1855
- key,
1856
- index,
1857
- done: "loaded"
1858
- }),
1859
- onError: fail,
1860
- className: cn("absolute inset-0 size-full", fit === "cover" ? "object-cover" : "object-contain", phase === "loading" && "opacity-0")
1861
- }, `${key}#${index}`),
1862
- phase === "missing" && /* @__PURE__ */ jsx("div", {
1863
- ...name ? {
1864
- role: "img",
1865
- "aria-label": name
1866
- } : { "aria-hidden": true },
1867
- className: cn("absolute inset-0 grid", fallback === void 0 && "content-center justify-items-center gap-0.5 p-1 text-center text-muted-foreground"),
1868
- children: fallback === void 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ImageOff, {
1869
- "aria-hidden": true,
1870
- className: "size-4 shrink-0"
1871
- }), /* @__PURE__ */ jsx("span", {
1872
- className: "type-caption text-balance",
1873
- children: missing
1874
- })] }) : /* @__PURE__ */ jsx("div", {
1875
- "aria-hidden": true,
1876
- className: "grid size-full min-h-0 min-w-0",
1877
- children: fallback
1878
- })
1879
- }),
1880
- children
1881
- ]
1803
+ // src/components/workflow-steps.tsx
1804
+ var DEFAULT_WORDS = {
1805
+ done: "Done",
1806
+ approved: "Approved",
1807
+ ready: "Not started",
1808
+ stale: "Out of date",
1809
+ failed: "Failed",
1810
+ waiting: "Needs review",
1811
+ blocked: "Waiting"
1812
+ };
1813
+ var LOOKS$1 = {
1814
+ done: {
1815
+ tone: "success",
1816
+ icon: Check
1817
+ },
1818
+ ready: {
1819
+ tone: "neutral",
1820
+ icon: CircleDashed
1821
+ },
1822
+ stale: {
1823
+ tone: "warning",
1824
+ icon: RotateCcw
1825
+ },
1826
+ failed: {
1827
+ tone: "danger",
1828
+ icon: CircleAlert
1829
+ },
1830
+ waiting: {
1831
+ tone: "info",
1832
+ icon: Eye
1833
+ },
1834
+ blocked: {
1835
+ tone: "neutral",
1836
+ icon: Clock
1837
+ }
1838
+ };
1839
+ function wordOf(stage, words) {
1840
+ const state = stage.state in LOOKS$1 ? stage.state : "blocked";
1841
+ if (state === "done" && stage.gate) return words.approved;
1842
+ return words[state];
1843
+ }
1844
+ function detailOf(stage, now) {
1845
+ const last = stage.last;
1846
+ if (!last || last.status === "cleared") return null;
1847
+ const when = format.ago(last.at, now);
1848
+ if (stage.gate && last.status === "done") return last.by === "auto" ? `Approved automatically ${when}` : `Approved by ${last.by ?? "someone"} ${when}`;
1849
+ const took = last.elapsed_s != null && last.elapsed_s >= 1 ? `, took ${format.runningTime(last.elapsed_s)}` : "";
1850
+ return `${last.status === "failed" ? "Failed" : "Ran"} ${when}${took}`;
1851
+ }
1852
+ function StageAction({ stage, filled, run, labels }) {
1853
+ const action = useAsyncAction(() => run(stage));
1854
+ return /* @__PURE__ */ jsx(AsyncButton, {
1855
+ size: "sm",
1856
+ variant: filled ? "default" : "outline",
1857
+ phase: action.phase,
1858
+ error: action.error,
1859
+ labels,
1860
+ "aria-label": `${labels.idle}: ${stage.title}`,
1861
+ onClick: () => void action.run()
1882
1862
  });
1883
1863
  }
1884
- /** The loading shape of a `Thumbnail`, for a `DataView` skeleton: the same box and aspect ratio, so nothing moves when the list arrives. */
1885
- function ThumbnailSkeleton({ aspect = 1, className }) {
1886
- return /* @__PURE__ */ jsx("div", {
1887
- "aria-hidden": true,
1888
- className: cn("relative overflow-hidden rounded-control bg-muted", className),
1889
- style: { aspectRatio: ratio(aspect) },
1890
- children: /* @__PURE__ */ jsx(Skeleton, { className: "absolute inset-0" })
1864
+ /** A subject's stages through a strata-python pipeline, each with its state as a word, when it last ran, its error, and Approve on a waiting gate or Try again on a failed stage. */
1865
+ function WorkflowSteps({ label, stages, onApprove, onRetry, words, now, className }) {
1866
+ const all = {
1867
+ ...DEFAULT_WORDS,
1868
+ ...words
1869
+ };
1870
+ const firstWaiting = stages.find((s) => s.gate && s.state === "waiting")?.name;
1871
+ return /* @__PURE__ */ jsx("ol", {
1872
+ "aria-label": label,
1873
+ className: cn("grid min-w-0 gap-0 divide-y divide-border", className),
1874
+ children: stages.map((stage) => {
1875
+ const state = stage.state in LOOKS$1 ? stage.state : "blocked";
1876
+ const look = stage.state === "done" && stage.gate ? {
1877
+ tone: "success",
1878
+ icon: Check
1879
+ } : LOOKS$1[state];
1880
+ const detail = detailOf(stage, now);
1881
+ const error = state === "failed" ? stage.last?.error : null;
1882
+ return /* @__PURE__ */ jsxs("li", {
1883
+ className: "grid gap-1 py-3",
1884
+ children: [
1885
+ /* @__PURE__ */ jsxs("div", {
1886
+ className: "flex flex-wrap items-center gap-x-3 gap-y-1",
1887
+ children: [
1888
+ /* @__PURE__ */ jsx("span", {
1889
+ className: "min-w-0 flex-1 type-label text-foreground",
1890
+ children: stage.title
1891
+ }),
1892
+ state === "waiting" && stage.gate && onApprove && /* @__PURE__ */ jsx(StageAction, {
1893
+ stage,
1894
+ filled: stage.name === firstWaiting,
1895
+ run: onApprove,
1896
+ labels: {
1897
+ idle: "Approve",
1898
+ pending: "Approving…",
1899
+ done: "Approved"
1900
+ }
1901
+ }),
1902
+ state === "failed" && onRetry && /* @__PURE__ */ jsx(StageAction, {
1903
+ stage,
1904
+ filled: false,
1905
+ run: onRetry,
1906
+ labels: {
1907
+ idle: "Try again",
1908
+ pending: "Starting…",
1909
+ done: "Started"
1910
+ }
1911
+ }),
1912
+ /* @__PURE__ */ jsx(Status, {
1913
+ tone: look.tone,
1914
+ icon: look.icon,
1915
+ children: wordOf(stage, all)
1916
+ })
1917
+ ]
1918
+ }),
1919
+ detail && /* @__PURE__ */ jsx("p", {
1920
+ className: "type-caption text-muted-foreground",
1921
+ children: detail
1922
+ }),
1923
+ error && /* @__PURE__ */ jsx("p", {
1924
+ className: "type-body-sm text-danger",
1925
+ children: error
1926
+ })
1927
+ ]
1928
+ }, stage.name);
1929
+ })
1891
1930
  });
1892
1931
  }
1893
1932
  // src/lib/choice.ts
@@ -2574,6 +2613,212 @@ function TableSkeleton({ rows = 4, columns = 5 }) {
2574
2613
  }, r))]
2575
2614
  });
2576
2615
  }
2616
+ // src/components/jobs-table.tsx
2617
+ var LOOKS = {
2618
+ queued: {
2619
+ tone: "neutral",
2620
+ icon: Clock,
2621
+ word: "Queued"
2622
+ },
2623
+ running: {
2624
+ tone: "info",
2625
+ icon: LoaderCircle,
2626
+ word: "Running"
2627
+ },
2628
+ done: {
2629
+ tone: "success",
2630
+ icon: Check,
2631
+ word: "Done"
2632
+ },
2633
+ failed: {
2634
+ tone: "danger",
2635
+ icon: CircleAlert,
2636
+ word: "Failed"
2637
+ },
2638
+ cancelled: {
2639
+ tone: "neutral",
2640
+ icon: Ban,
2641
+ word: "Cancelled"
2642
+ }
2643
+ };
2644
+ function JobAction({ job, subject, run, labels }) {
2645
+ const action = useAsyncAction(() => run(job));
2646
+ return /* @__PURE__ */ jsx(AsyncButton, {
2647
+ size: "sm",
2648
+ variant: "ghost",
2649
+ className: "-my-1.5",
2650
+ phase: action.phase,
2651
+ error: action.error,
2652
+ labels,
2653
+ "aria-label": `${labels.idle} ${subject}`,
2654
+ onClick: () => void action.run()
2655
+ });
2656
+ }
2657
+ /** A table of the queue's jobs (`GET /api/jobs`): what each is, its state as a word with its progress or error, when it started, and Cancel or Run again where they apply. */
2658
+ function JobsTable({ caption, jobs, describe = (j) => j.kind, onCancel, onRetry, now, className }) {
2659
+ return /* @__PURE__ */ jsx(DataTable, {
2660
+ caption,
2661
+ columns: [
2662
+ {
2663
+ key: "job",
2664
+ header: "Job",
2665
+ cell: (j) => describe(j),
2666
+ value: (j) => describe(j),
2667
+ truncate: true
2668
+ },
2669
+ {
2670
+ key: "state",
2671
+ header: "State",
2672
+ cell: (j) => {
2673
+ const look = LOOKS[j.state] ?? LOOKS.queued;
2674
+ return /* @__PURE__ */ jsx(Status, {
2675
+ tone: look.tone,
2676
+ icon: look.icon,
2677
+ children: look.word
2678
+ });
2679
+ },
2680
+ value: (j) => j.state
2681
+ },
2682
+ {
2683
+ key: "detail",
2684
+ header: "Detail",
2685
+ cell: (j) => j.state === "failed" && j.error ? /* @__PURE__ */ jsx("span", {
2686
+ className: "text-danger",
2687
+ children: j.error
2688
+ }) : j.state === "running" && j.progress?.text ? j.progress.text : /* @__PURE__ */ jsx("span", {
2689
+ className: "text-muted-foreground",
2690
+ children: format.missing
2691
+ }),
2692
+ sort: false,
2693
+ truncate: true
2694
+ },
2695
+ {
2696
+ key: "created",
2697
+ header: "Added",
2698
+ cell: (j) => format.ago(j.created_at, now),
2699
+ value: (j) => new Date(j.created_at)
2700
+ },
2701
+ {
2702
+ key: "actions",
2703
+ header: "Actions",
2704
+ hideHeader: true,
2705
+ sort: false,
2706
+ cell: (j) => (j.state === "queued" || j.state === "running") && onCancel ? /* @__PURE__ */ jsx(JobAction, {
2707
+ job: j,
2708
+ subject: describe(j),
2709
+ run: onCancel,
2710
+ labels: {
2711
+ idle: "Cancel",
2712
+ pending: "Cancelling…",
2713
+ done: "Cancelled"
2714
+ }
2715
+ }) : (j.state === "failed" || j.state === "cancelled") && onRetry ? /* @__PURE__ */ jsx(JobAction, {
2716
+ job: j,
2717
+ subject: describe(j),
2718
+ run: onRetry,
2719
+ labels: {
2720
+ idle: "Run again",
2721
+ pending: "Queuing…",
2722
+ done: "Queued"
2723
+ }
2724
+ }) : null
2725
+ }
2726
+ ],
2727
+ rows: jobs,
2728
+ rowKey: (j) => String(j.id),
2729
+ className: cn(className)
2730
+ });
2731
+ }
2732
+ // src/components/thumbnail.tsx
2733
+ var ratio = (aspect) => typeof aspect === "number" ? String(aspect) : aspect.replace("/", " / ");
2734
+ /** A box of fixed aspect ratio for a remote image: a skeleton until it loads, the `missing` words (or a `fallback`) if it cannot, a request only when it nears the screen, and `children` overlaid in its corners. `alt` and `missing` or `fallback` are required. */
2735
+ function Thumbnail({ src, alt, missing, aspect = 1, fit = "cover", srcSet, sizes, eager = false, rootMargin = "200px", className, fallback, onLoad, onMissing, children }) {
2736
+ const sources = React.useMemo(() => src === null ? [] : typeof src === "string" ? src ? [src] : [] : src.filter(Boolean), [src]);
2737
+ const key = sources.length ? `${sources.join("\n")} ${srcSet ?? ""}` : null;
2738
+ const [outcome, setOutcome] = React.useState(null);
2739
+ const mine = key !== null && outcome?.key === key ? outcome : null;
2740
+ const index = mine?.index ?? 0;
2741
+ const phase = key === null ? "missing" : mine?.done ?? "loading";
2742
+ const current = sources[index];
2743
+ const near = useInView({
2744
+ active: !eager && sources.length > 0,
2745
+ rootMargin,
2746
+ once: true,
2747
+ unsupported: true
2748
+ });
2749
+ const requested = eager || near.inView;
2750
+ const fail = () => setOutcome(index + 1 < sources.length ? {
2751
+ key,
2752
+ index: index + 1,
2753
+ done: null
2754
+ } : {
2755
+ key,
2756
+ index,
2757
+ done: "missing"
2758
+ });
2759
+ const told = React.useRef(null);
2760
+ const tell = React.useRef(onMissing);
2761
+ tell.current = onMissing;
2762
+ React.useEffect(() => {
2763
+ if (phase !== "missing") told.current = null;
2764
+ else if (key !== null && told.current !== key) {
2765
+ told.current = key;
2766
+ tell.current?.();
2767
+ }
2768
+ }, [key, phase]);
2769
+ const name = [alt, missing].filter(Boolean).join(": ");
2770
+ return /* @__PURE__ */ jsxs("div", {
2771
+ ref: near.ref,
2772
+ className: cn("relative overflow-hidden rounded-control bg-muted", className),
2773
+ style: { aspectRatio: ratio(aspect) },
2774
+ "aria-busy": phase === "loading" || void 0,
2775
+ children: [
2776
+ phase === "loading" && /* @__PURE__ */ jsx(Skeleton, { className: "absolute inset-0" }),
2777
+ key !== null && phase !== "missing" && requested && /* @__PURE__ */ jsx("img", {
2778
+ src: current,
2779
+ srcSet: index === 0 ? srcSet : void 0,
2780
+ sizes,
2781
+ alt,
2782
+ decoding: "async",
2783
+ onLoad: (e) => onLoad?.(e.currentTarget, index) === false ? fail() : setOutcome({
2784
+ key,
2785
+ index,
2786
+ done: "loaded"
2787
+ }),
2788
+ onError: fail,
2789
+ className: cn("absolute inset-0 size-full", fit === "cover" ? "object-cover" : "object-contain", phase === "loading" && "opacity-0")
2790
+ }, `${key}#${index}`),
2791
+ phase === "missing" && /* @__PURE__ */ jsx("div", {
2792
+ ...name ? {
2793
+ role: "img",
2794
+ "aria-label": name
2795
+ } : { "aria-hidden": true },
2796
+ className: cn("absolute inset-0 grid", fallback === void 0 && "content-center justify-items-center gap-0.5 p-1 text-center text-muted-foreground"),
2797
+ children: fallback === void 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ImageOff, {
2798
+ "aria-hidden": true,
2799
+ className: "size-4 shrink-0"
2800
+ }), /* @__PURE__ */ jsx("span", {
2801
+ className: "type-caption text-balance",
2802
+ children: missing
2803
+ })] }) : /* @__PURE__ */ jsx("div", {
2804
+ "aria-hidden": true,
2805
+ className: "grid size-full min-h-0 min-w-0",
2806
+ children: fallback
2807
+ })
2808
+ }),
2809
+ children
2810
+ ]
2811
+ });
2812
+ }
2813
+ /** The loading shape of a `Thumbnail`, for a `DataView` skeleton: the same box and aspect ratio, so nothing moves when the list arrives. */
2814
+ function ThumbnailSkeleton({ aspect = 1, className }) {
2815
+ return /* @__PURE__ */ jsx("div", {
2816
+ "aria-hidden": true,
2817
+ className: cn("relative overflow-hidden rounded-control bg-muted", className),
2818
+ style: { aspectRatio: ratio(aspect) },
2819
+ children: /* @__PURE__ */ jsx(Skeleton, { className: "absolute inset-0" })
2820
+ });
2821
+ }
2577
2822
  // src/components/fullscreen-frame.tsx
2578
2823
  /** Whether this browser can show an element full screen. False in jsdom and on iPhone, where the modal fallback is used. */
2579
2824
  function canFullscreen() {
@@ -11032,16 +11277,17 @@ function withBase(path, base = appBase()) {
11032
11277
  return path.startsWith("/") && !path.startsWith("//") ? base + path : path;
11033
11278
  }
11034
11279
  // src/query/api.ts
11280
+ var isRaw = (body) => typeof Blob !== "undefined" && body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof FormData !== "undefined" && body instanceof FormData || body instanceof URLSearchParams || typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
11035
11281
  /**
11036
11282
  * A small client over `fetchJson` for the app's own server: root-relative paths get the app's base (so it works behind a reverse proxy),
11037
- * and `post`, `put` and `patch` send their body as JSON. `api.post<Learner>("/api/learners", { nickname })`.
11283
+ * and `post`, `put` and `patch` send their body as JSON (a `Blob`, bytes, `FormData` or a stream is sent as it is, with the Blob's own type). `api.post<Learner>("/api/learners", { nickname })`.
11038
11284
  */
11039
11285
  function createApi({ base, ...options } = {}) {
11040
11286
  const url = (path) => withBase(path, base ?? appBase());
11041
11287
  const send = (method, path, body, init) => fetchJson(url(path), {
11042
11288
  ...init,
11043
11289
  method,
11044
- ...body === void 0 ? {} : { json: body }
11290
+ ...body === void 0 ? {} : isRaw(body) ? { body } : { json: body }
11045
11291
  }, options);
11046
11292
  return {
11047
11293
  url,
@@ -11071,10 +11317,10 @@ function fill(path, values, query) {
11071
11317
  function createTypedApi(options = {}) {
11072
11318
  const api = createApi(options);
11073
11319
  const call = (method) => (path, request) => {
11074
- const { path: values, query, json, ...init } = request ?? {};
11320
+ const { path: values, query, json, body, ...init } = request ?? {};
11075
11321
  const target = fill(path, values, query);
11076
11322
  const rest = init;
11077
- return method === "get" ? api.get(target, rest) : method === "delete" ? api.delete(target, rest) : api[method](target, json, rest);
11323
+ return method === "get" ? api.get(target, rest) : method === "delete" ? api.delete(target, rest) : api[method](target, body ?? json, rest);
11078
11324
  };
11079
11325
  return {
11080
11326
  url: api.url,
@@ -11252,6 +11498,18 @@ function useJob({ isRunning, every = 2e3, invalidates = [], describeError, ...op
11252
11498
  function isTaskRunning(task, finished) {
11253
11499
  return !(Array.isArray(finished) ? finished.includes(task.state) : finished.has(task.state));
11254
11500
  }
11501
+ // src/query/workflow.ts
11502
+ /** Whether the queue job advancing a workflow run is still going. `finished` is the generated `FINISHED` (or `["done", "failed", "cancelled"]`). */
11503
+ function isWorkflowRunning(run, finished) {
11504
+ return run.job != null && isTaskRunning(run.job, finished);
11505
+ }
11506
+ /** A subject's `WorkflowRun`: polled while its job runs, its `invalidates` read again once when it ends. */
11507
+ function useWorkflowRun({ finished, ...options }) {
11508
+ return useJob({
11509
+ ...options,
11510
+ isRunning: (run) => isWorkflowRunning(run, finished)
11511
+ });
11512
+ }
11255
11513
  // src/query/outbox.ts
11256
11514
  /** Whether a failure is the server's answer for good (refused) rather than for now (waiting). */
11257
11515
  function isRefusal(error) {
@@ -11271,7 +11529,7 @@ function problemOf(error) {
11271
11529
  }
11272
11530
  return "The server could not be reached.";
11273
11531
  }
11274
- function defaultStorage() {
11532
+ function defaultStorage$1() {
11275
11533
  try {
11276
11534
  const s = window.localStorage;
11277
11535
  const probe = "strata:outbox:probe";
@@ -11288,7 +11546,7 @@ function randomId() {
11288
11546
  /** A queue of writes kept on the device (localStorage) and sent in order when the server can take them; see `useOutbox` and `OutboxStatus`. */
11289
11547
  function createOutbox({ name, send, storage, retryMs = 2e3, maxRetryMs = 6e4 }) {
11290
11548
  const key = `strata:outbox:${name}`;
11291
- const store = storage === void 0 ? defaultStorage() : storage;
11549
+ const store = storage === void 0 ? defaultStorage$1() : storage;
11292
11550
  const post = send ?? ((item) => fetchJson(withBase(item.path, appBase()), {
11293
11551
  method: item.method,
11294
11552
  json: item.json
@@ -11555,6 +11813,104 @@ function OutboxStatus({ outbox, noun, className }) {
11555
11813
  })]
11556
11814
  });
11557
11815
  }
11816
+ // src/query/reserve.ts
11817
+ function defaultStorage() {
11818
+ try {
11819
+ const s = window.localStorage;
11820
+ const probe = "strata:reserve:probe";
11821
+ s.setItem(probe, "1");
11822
+ s.removeItem(probe);
11823
+ return s;
11824
+ } catch {
11825
+ return null;
11826
+ }
11827
+ }
11828
+ /** Items the server made ahead, kept on the device (localStorage) and used once each; see `useReserve`. */
11829
+ function createReserve({ name, size, fetch, sameMake = () => true, storage }) {
11830
+ const prefix = `strata:reserve:${name}:`;
11831
+ const store = storage === void 0 ? defaultStorage() : storage;
11832
+ let persisted = store !== null;
11833
+ const listeners = /* @__PURE__ */ new Set();
11834
+ const inFlight = /* @__PURE__ */ new Set();
11835
+ const latest = /* @__PURE__ */ new Map();
11836
+ const changed = () => {
11837
+ for (const l of listeners) l();
11838
+ };
11839
+ const read = (key) => {
11840
+ if (!persisted || !store) return [];
11841
+ try {
11842
+ const raw = JSON.parse(store.getItem(prefix + key) ?? "null");
11843
+ return Array.isArray(raw) ? raw : [];
11844
+ } catch {
11845
+ return [];
11846
+ }
11847
+ };
11848
+ const write = (key, items) => {
11849
+ if (persisted && store) try {
11850
+ if (items.length) store.setItem(prefix + key, JSON.stringify(items.slice(0, size)));
11851
+ else store.removeItem(prefix + key);
11852
+ } catch {
11853
+ persisted = false;
11854
+ }
11855
+ changed();
11856
+ };
11857
+ return {
11858
+ take(key) {
11859
+ const items = read(key);
11860
+ const [next, ...rest] = items;
11861
+ if (items.length === 0) return void 0;
11862
+ write(key, rest);
11863
+ return next;
11864
+ },
11865
+ async refresh(key, fresh) {
11866
+ latest.set(key, fresh);
11867
+ const current = read(key);
11868
+ const kept = current.filter((item) => sameMake(item, fresh));
11869
+ if (kept.length !== current.length) write(key, kept);
11870
+ if (kept.length * 2 >= size || inFlight.has(key)) return;
11871
+ inFlight.add(key);
11872
+ try {
11873
+ const more = await fetch(key, size - kept.length);
11874
+ const now = read(key);
11875
+ write(key, [...now, ...more.filter((item) => sameMake(item, latest.get(key)))].slice(0, size));
11876
+ } catch {} finally {
11877
+ inFlight.delete(key);
11878
+ }
11879
+ },
11880
+ kept: (key) => read(key).length,
11881
+ get persisted() {
11882
+ return persisted;
11883
+ },
11884
+ seed(key, items) {
11885
+ write(key, items);
11886
+ },
11887
+ clear(key) {
11888
+ if (key !== void 0) return write(key, []);
11889
+ if (persisted && store) try {
11890
+ for (const k of Object.keys(store).filter((k) => k.startsWith(prefix))) store.removeItem(k);
11891
+ } catch {
11892
+ persisted = false;
11893
+ }
11894
+ changed();
11895
+ },
11896
+ subscribe(listener) {
11897
+ listeners.add(listener);
11898
+ return () => listeners.delete(listener);
11899
+ }
11900
+ };
11901
+ }
11902
+ /** How many items `reserve` keeps for `key`, re-rendering as they are taken, topped up or changed by another tab: "6 rounds kept for offline". */
11903
+ function useReserve(reserve, key) {
11904
+ const subscribe = React.useCallback((listener) => {
11905
+ const stop = reserve.subscribe(listener);
11906
+ window.addEventListener("storage", listener);
11907
+ return () => {
11908
+ stop();
11909
+ window.removeEventListener("storage", listener);
11910
+ };
11911
+ }, [reserve]);
11912
+ return React.useSyncExternalStore(subscribe, () => reserve.kept(key), () => 0);
11913
+ }
11558
11914
  // src/lib/speech.ts
11559
11915
  var partsOf = (saying) => (typeof saying === "string" ? [{ text: saying }] : [...saying]).filter((p) => p.text.trim() || p.clip);
11560
11916
  /** The words of what is said, as one sentence: what the browser's voice says when a recording is missing, and the button's name. */
@@ -11697,11 +12053,88 @@ function useSpeech({ lang, rate, muted = false } = {}) {
11697
12053
  }, [])
11698
12054
  };
11699
12055
  }
12056
+ // src/query/clips.tsx
12057
+ /** The query key of the clip list: invalidate it after a recording is kept, `queryClient.invalidateQueries({ queryKey: clipsQueryKey })`. */
12058
+ var clipsQueryKey = ["strata", "clips"];
12059
+ var Context$1 = React.createContext({
12060
+ ready: true,
12061
+ parts: (text) => [{
12062
+ text,
12063
+ clip: null
12064
+ }],
12065
+ say: (text) => speak(text),
12066
+ words: (text) => text
12067
+ });
12068
+ /** Reads the app's clip list once and gives `useClips`, `SayAgain` and `useSayOnShow` each line's recording. Put it in the shell, inside the query provider. */
12069
+ function ClipsProvider({ load, lang, split, describe, queryKey = clipsQueryKey, children }) {
12070
+ const list = useLoad({
12071
+ queryKey,
12072
+ queryFn: load,
12073
+ staleTime: Infinity,
12074
+ networkMode: "always"
12075
+ });
12076
+ const clips = list.status === "ready" ? list.data : void 0;
12077
+ const value = React.useMemo(() => {
12078
+ const parts = (text) => (split ? split(text) : [text]).map((line) => line.trim()).filter(Boolean).map((line) => {
12079
+ const url = clips?.[line];
12080
+ return url ? {
12081
+ text: line,
12082
+ clip: withBase(url, appBase())
12083
+ } : {
12084
+ text: describe?.(line) ?? line,
12085
+ clip: null
12086
+ };
12087
+ });
12088
+ return {
12089
+ ready: list.status !== "loading",
12090
+ lang,
12091
+ parts,
12092
+ say: (text) => speak(parts(text), { lang }),
12093
+ words: (text) => textOf(parts(text))
12094
+ };
12095
+ }, [
12096
+ clips,
12097
+ list.status,
12098
+ lang,
12099
+ split,
12100
+ describe
12101
+ ]);
12102
+ return /* @__PURE__ */ jsx(Context$1.Provider, {
12103
+ value,
12104
+ children
12105
+ });
12106
+ }
12107
+ /** The app's clips: `const { say, parts, words, ready } = useClips()`. The browser's voice alone outside a `ClipsProvider`. */
12108
+ function useClips() {
12109
+ return React.useContext(Context$1);
12110
+ }
12111
+ /**
12112
+ * Says `text` once when it appears and the clips are `ready`, and again when `text` changes; stops it on unmount so a prompt does not talk
12113
+ * after its screen is gone. `useSayOnShow(question.text)`.
12114
+ */
12115
+ function useSayOnShow(text, { muted = false } = {}) {
12116
+ const { ready, say } = useClips();
12117
+ const latest = React.useRef(say);
12118
+ latest.current = say;
12119
+ React.useEffect(() => {
12120
+ if (muted || !ready || !text) return;
12121
+ latest.current(text);
12122
+ return () => stopSpeaking();
12123
+ }, [
12124
+ muted,
12125
+ ready,
12126
+ text
12127
+ ]);
12128
+ }
11700
12129
  // src/components/say-again.tsx
11701
12130
  /** An icon button that says one sentence aloud, from its recordings when given, else with the browser's voice; hidden where neither can be heard or it is muted. */
11702
12131
  function SayAgain({ text, parts, verb = "Say", className, ...options }) {
11703
- const { say, speaking } = useSpeech(options);
11704
- const saying = parts?.length ? parts : text;
12132
+ const clips = useClips();
12133
+ const { say, speaking } = useSpeech({
12134
+ ...options,
12135
+ lang: options.lang ?? clips.lang
12136
+ });
12137
+ const saying = parts?.length ? parts : clips.parts(text);
11705
12138
  if (options.muted || !canSay(saying)) return null;
11706
12139
  return /* @__PURE__ */ jsx(IconButton, {
11707
12140
  icon: Volume2,
@@ -17581,6 +18014,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
17581
18014
  ]
17582
18015
  });
17583
18016
  }
17584
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, ButtonLink, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, ContextMenu, Conversation, CursorScope, DEFAULT_TOLERANCE, DataTable, DataView$1 as DataView, Density, Dialog, Disclosure, Done, DragSource, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, InputLevel, Inspector, InspectorSection, JobStatus, KeysLegend, LEVEL_FLOOR_DB, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MicrophoneContext, MicrophoneError, MissingFile, NBSP, NativeSelect, NumberField, OutboxStatus, PageHeader, PairJudge, PairVote, Pane, PlaceBoard, PlayWindowButton, PlayerNotice, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, STRATA_DRAG_TYPE, SaveStatus, SayAgain, SecretField, SeekBar, SelectableGrid, SelectableGridSkeleton, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, SpanStrip, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, TakeLevel, TextLink, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TileGrid, TileGridSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewOptions, ViewportFrame, VirtualList, VolumeControl, Waveform, Workspace, actualPixelsScale, ancestorsOf, apiPage, appBase, boxViewport, browserMicrophone, buttonVariants, canFullscreen, canPlayClips, canSay, canSpeak, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createApi, createFormat, createOutbox, createQueryClient, createTypedApi, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, encodeWav, errorPayload, explainMicrophoneError, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, inputLevelThresholds, isDoubtful, isRefusal, isReservedChord, isTaskRunning, isTypingTarget, jobProgressText, joinMediaGroup, joinRects, joinSamples, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peakDb, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickVoice, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, speak, speechLevel, splitRect, staleOf, stepId, stepOnGrid, stopSpeaking, textOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, turnRect, turnedSize, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoSave, useBookUrl, useBoxes, useChoices, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, useMicrophone, useOutbox, useOutboxStarted, usePlayerWarnings, useRecorder, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
18017
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, ButtonLink, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, ChoiceGroup, ClipsProvider, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, ContextMenu, Conversation, CursorScope, DEFAULT_TOLERANCE, DataTable, DataView$1 as DataView, Density, Dialog, Disclosure, Done, DragSource, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, InputLevel, Inspector, InspectorSection, JobStatus, JobsTable, KeysLegend, LEVEL_FLOOR_DB, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MicrophoneContext, MicrophoneError, MissingFile, NBSP, NativeSelect, NumberField, OutboxStatus, PageHeader, PairJudge, PairVote, Pane, PlaceBoard, PlayWindowButton, PlayerNotice, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, STRATA_DRAG_TYPE, SaveStatus, SayAgain, SecretField, SeekBar, SelectableGrid, SelectableGridSkeleton, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, SpanStrip, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, TakeLevel, TextLink, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TileGrid, TileGridSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewOptions, ViewportFrame, VirtualList, VolumeControl, Waveform, WorkflowSteps, Workspace, actualPixelsScale, ancestorsOf, apiPage, appBase, boxViewport, browserMicrophone, buttonVariants, canFullscreen, canPlayClips, canSay, canSpeak, clampToRoom, clampViewport, clipsQueryKey, cn, colorSchemeScript, commandShortcut, countMarks, createApi, createFormat, createOutbox, createQueryClient, createReserve, createTypedApi, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, encodeWav, errorPayload, explainMicrophoneError, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, inputLevelThresholds, isDoubtful, isRefusal, isReservedChord, isTaskRunning, isTypingTarget, isWorkflowRunning, jobProgressText, joinMediaGroup, joinRects, joinSamples, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peakDb, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickVoice, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, speak, speechLevel, splitRect, staleOf, stepId, stepOnGrid, stopSpeaking, textOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, turnRect, turnedSize, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoSave, useBookUrl, useBoxes, useChoices, useClientWork, useClips, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, useMicrophone, useOutbox, useOutboxStarted, usePlayerWarnings, useRecorder, useReserve, useSayOnShow, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkflowRun, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
17585
18018
 
17586
18019
  //# sourceMappingURL=index.js.map