strata-react 1.3.2 → 1.3.3

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 (41) hide show
  1. package/README.md +19 -2
  2. package/UPGRADING.md +4 -0
  3. package/dist/api-types/generate.d.ts +2 -0
  4. package/dist/api-types-cli.js +1 -1
  5. package/dist/api-types.js +1 -1
  6. package/dist/components/field.d.ts +28 -5
  7. package/dist/components/link.d.ts +43 -0
  8. package/dist/components/say-again.d.ts +11 -0
  9. package/dist/components/toggle.d.ts +12 -4
  10. package/dist/{errors-DqezYZgy.js → errors-D99YX4XL.js} +2 -2
  11. package/dist/{errors-DqezYZgy.js.map → errors-D99YX4XL.js.map} +1 -1
  12. package/dist/{field-CTd1l3md.js → field-QCCmWTuY.js} +77 -4
  13. package/dist/field-QCCmWTuY.js.map +1 -0
  14. package/dist/{generate-DCRYZPJs.js → generate-CjTHKJ39.js} +21 -3
  15. package/dist/generate-CjTHKJ39.js.map +1 -0
  16. package/dist/index.d.ts +7 -2
  17. package/dist/index.js +251 -12
  18. package/dist/index.js.map +1 -1
  19. package/dist/lib/base.d.ts +10 -0
  20. package/dist/lib/search-param.d.ts +16 -0
  21. package/dist/lib/speech.d.ts +37 -0
  22. package/dist/map.js +2 -2
  23. package/dist/panorama.js +2 -2
  24. package/dist/query/api.d.ts +23 -0
  25. package/dist/query/index.d.ts +12 -2
  26. package/dist/query/typed-api.d.ts +78 -0
  27. package/dist/{query-CgoGqE0T.js → query-CfonqUzU.js} +12 -6
  28. package/dist/{query-CgoGqE0T.js.map → query-CfonqUzU.js.map} +1 -1
  29. package/dist/testing/index.d.ts +4 -6
  30. package/dist/testing/layout.d.ts +1 -1
  31. package/dist/testing/speech.d.ts +32 -0
  32. package/dist/testing/storage.d.ts +7 -0
  33. package/dist/testing.js +145 -4
  34. package/dist/testing.js.map +1 -1
  35. package/dist/{theme-DB0Km2m2.js → theme-By3DSUTs.js} +2 -2
  36. package/dist/{theme-DB0Km2m2.js.map → theme-By3DSUTs.js.map} +1 -1
  37. package/dist/{value-controls-CiwdvJeH.js → value-controls-B7iNh4WO.js} +3 -3
  38. package/dist/{value-controls-CiwdvJeH.js.map → value-controls-B7iNh4WO.js.map} +1 -1
  39. package/package.json +1 -1
  40. package/dist/field-CTd1l3md.js.map +0 -1
  41. package/dist/generate-DCRYZPJs.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-CjTHKJ39.js","names":[],"sources":["../src/api-types/generate.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\n\n// The types behind `strata-api-types` (strata-react issue #263). A strata app's FastAPI server\n// publishes its routes, the shared contracts (`strata_python.contracts`: Health, Task, Page, ErrorBody…)\n// and its typed settings at `/api/openapi.json`; the TypeScript types follow that schema instead of\n// being written again by hand and drifting. The work of reading OpenAPI is `openapi-typescript`\n// (Jonathan, 2026-11-14: types only, nothing in the app's bundle); this file adds where the schema\n// comes from (a running server, or a file the server's own CLI wrote, so CI needs no server) and what\n// the committed file looks like. It lives behind its own entry (`strata-react/api-types`), like\n// `strata-react/visual`, and `openapi-typescript` is an optional peer, so an app that never runs the\n// command installs nothing and the main entry's peer contract is unchanged.\n//\n// The output is deterministic, so `--check` can compare it with the committed file and fail CI when\n// the Python side moved and the file did not. Nothing about the machine (the URL it was read from, a\n// date) goes into it, for the same reason.\n\n/** The OpenAPI document as the generator takes it: a parsed JSON object. */\nexport type OpenApiDocument = Record<string, unknown>;\n\n/** Reads an OpenAPI document from an `http(s)` URL (a running server) or a JSON file path. */\nexport async function loadSchema(source: string, fetcher: typeof fetch = fetch): Promise<OpenApiDocument> {\n let text: string;\n if (/^https?:\\/\\//i.test(source)) {\n const response = await fetcher(source, { headers: { accept: \"application/json\" } });\n if (!response.ok) throw new Error(`${source} answered ${response.status} ${response.statusText}`);\n text = await response.text();\n } else {\n text = await readFile(source, \"utf8\");\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new Error(`${source} is not JSON. Give the OpenAPI document (/api/openapi.json), not the docs page.`);\n }\n if (!parsed || typeof parsed !== \"object\" || !(\"openapi\" in parsed)) throw new Error(`${source} is JSON but not an OpenAPI document (no \"openapi\" field).`);\n return parsed as OpenApiDocument;\n}\n\nconst header = `/* eslint-disable */\n// Generated by strata-api-types from the app's OpenAPI schema. Do not edit by hand:\n// regenerate with \\`strata-api-types <schema> -o <this file>\\`; CI runs it with --check.\n`;\n\n// Short names for the schemas, so a screen writes \\`Schema<\"Task\">\\` and not the whole path.\nconst footer = `\n/** A named schema of the API: \\`Schema<\"Task\">\\`. */\nexport type Schema<K extends keyof components[\"schemas\"]> = components[\"schemas\"][K];\n`;\n\n/** The URL relative references resolve against: the document's own URL, or its file's location. */\nfunction baseOf(source: string): URL {\n return /^https?:\\/\\//i.test(source) ? new URL(source) : pathToFileURL(resolve(source));\n}\n\n/** The message for a failed `import(\"openapi-typescript\")`: absent, or present but unable to load (issue #293: a TypeScript 7 app was told to install what it had). */\nexport function explainImportFailure(cause: unknown, typescriptMajor: number | undefined = installedTypescriptMajor()): string {\n const text = cause instanceof Error ? cause.message : String(cause);\n const code = (cause as { code?: string } | null)?.code;\n const notFound = (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") && /Cannot find (package|module) 'openapi-typescript'/.test(text);\n if (notFound) {\n return \"strata-api-types needs openapi-typescript: npm install --save-dev openapi-typescript (see \\\"API types from the server\\\" in the README for the TypeScript it wants).\";\n }\n const hint =\n typescriptMajor !== undefined && typescriptMajor >= 7\n ? ` The \\`typescript\\` package installed here is version ${typescriptMajor}, which ships no JavaScript API, and openapi-typescript needs one. Install TypeScript 6's under the name \\`typescript\\` (\"typescript\": \"npm:@typescript/typescript6@~6.0.2\", with TypeScript 7 as another name such as \"typescript7\" for \\`tsc\\`) and keep the \\`overrides\\` entry; see \"API types from the server\" in the README.`\n : \" It is installed but did not load; the cause is above. It needs a `typescript` package with a JavaScript API (TypeScript 5 or 6).\";\n return `strata-api-types could not load openapi-typescript: ${text}.${hint}`;\n}\n\n/** The major version of the `typescript` package an app resolves, or `undefined` when none can be read. */\nfunction installedTypescriptMajor(): number | undefined {\n try {\n const { version } = createRequire(resolve(\"package.json\"))(\"typescript/package.json\") as { version?: string };\n const major = Number.parseInt(version ?? \"\", 10);\n return Number.isNaN(major) ? undefined : major;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The TypeScript types for an OpenAPI document, as the text of the generated file. `source` is where the\n * document was read from (a URL or file path): relative `$ref`s to other files resolve against it.\n */\nexport async function generateApiTypes(schema: OpenApiDocument, source?: string): Promise<string> {\n const mod = await import(\"openapi-typescript\").catch((cause: unknown) => {\n throw new Error(explainImportFailure(cause), { cause });\n });\n const { default: openapiTS, astToString } = mod;\n const ast = await openapiTS(schema as never, source ? { cwd: baseOf(source) } : undefined);\n return `${header}\\n${astToString(ast).trimEnd()}\\n${footer}`;\n}\n"],"mappings":";;;;;;AAuBA,eAAsB,WAAW,QAAgB,UAAwB,OAAiC;CACxG,IAAI;CACJ,IAAI,gBAAgB,KAAK,MAAM,GAAG;EAChC,MAAM,WAAW,MAAM,QAAQ,QAAQ,EAAE,SAAS,EAAE,QAAQ,mBAAmB,EAAE,CAAC;EAClF,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,MAAM,GAAG,OAAO,YAAY,SAAS,OAAO,GAAG,SAAS,YAAY;EAChG,OAAO,MAAM,SAAS,KAAK;CAC7B,OACE,OAAO,MAAM,SAAS,QAAQ,MAAM;CAEtC,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,IAAI;CAC1B,QAAQ;EACN,MAAM,IAAI,MAAM,GAAG,OAAO,gFAAgF;CAC5G;CACA,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,EAAE,aAAa,SAAS,MAAM,IAAI,MAAM,GAAG,OAAO,2DAA2D;CAC1J,OAAO;AACT;AAEA,IAAM,SAAS;;;;AAMf,IAAM,SAAS;;;;;AAMf,SAAS,OAAO,QAAqB;CACnC,OAAO,gBAAgB,KAAK,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI,cAAc,QAAQ,MAAM,CAAC;AACvF;;AAGA,SAAgB,qBAAqB,OAAgB,kBAAsC,yBAAyB,GAAW;CAC7H,MAAM,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAClE,MAAM,OAAQ,OAAoC;CAElD,KADkB,SAAS,0BAA0B,SAAS,uBAAuB,oDAAoD,KAAK,IAAI,GAEhJ,OAAO;CAMT,OAAO,uDAAuD,KAAK,GAHjE,oBAAoB,KAAA,KAAa,mBAAmB,IAChD,yDAAyD,gBAAgB,sUACzE;AAER;;AAGA,SAAS,2BAA+C;CACtD,IAAI;EACF,MAAM,EAAE,YAAY,cAAc,QAAQ,cAAc,CAAC,CAAC,CAAC,yBAAyB;EACpF,MAAM,QAAQ,OAAO,SAAS,WAAW,IAAI,EAAE;EAC/C,OAAO,OAAO,MAAM,KAAK,IAAI,KAAA,IAAY;CAC3C,QAAQ;EACN;CACF;AACF;;;;;AAMA,eAAsB,iBAAiB,QAAyB,QAAkC;CAIhG,MAAM,EAAE,SAAS,WAAW,gBAAgB,MAH1B,OAAO,qBAAqB,CAAC,OAAO,UAAmB;EACvE,MAAM,IAAI,MAAM,qBAAqB,KAAK,GAAG,EAAE,MAAM,CAAC;CACxD,CAAC;CAGD,OAAO,GAAG,OAAO,IAAI,YAAY,MADf,UAAU,QAAiB,SAAS,EAAE,KAAK,OAAO,MAAM,EAAE,IAAI,KAAA,CAAS,CACrD,CAAC,CAAC,QAAQ,EAAE,IAAI;AACtD"}
package/dist/index.d.ts CHANGED
@@ -21,7 +21,7 @@ export { Popover, type PopoverProps } from './components/popover';
21
21
  export { Tooltip, type TooltipProps } from './components/tooltip';
22
22
  export { Checkbox, type CheckboxProps, type CheckboxGesture } from './components/checkbox';
23
23
  export { AsyncButton, useAsyncAction, type Phase, type AsyncLabels, type AsyncAction, type AsyncActionOptions, type FieldErrors, } from './components/async-button';
24
- export { Field, Input, Textarea, NativeSelect, ChoiceGroup, type FieldProps, type Choice } from './components/field';
24
+ export { Field, Input, Textarea, NativeSelect, ChoiceGroup, type FieldProps, type Choice, type NativeSelectProps, type ChoiceGroupProps } from './components/field';
25
25
  export { Status, type Tone } from './components/status';
26
26
  export { Metric, MetricStrip, type MetricProps } from './components/metric';
27
27
  export { Meter, crossedThreshold, type MeterProps, type MeterThreshold } from './components/meter';
@@ -75,8 +75,13 @@ export type { ControlSize } from './lib/control';
75
75
  export { useHotkeys, KeysLegend, isTypingTarget, type Shortcut } from './components/hotkeys';
76
76
  export { useActiveItem, ActiveList, type ActiveItem } from './components/active-list';
77
77
  export { ThemeProvider, useColorScheme, useSystemColorScheme, ColorSchemeChoice, colorSchemeScript, COLOR_SCHEME_STORAGE_KEY, type ColorScheme, type ColorSchemePreference, type ColorSchemeLabels, type ColorSchemeState, } from './components/theme';
78
- export { StrataQueryProvider, createQueryClient, toLoad, staleOf, useLoad, useInfiniteLoad, useJob, isTaskRunning, apiPage, fetchJson, HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody, type FetchJsonOptions, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type Job, type JobOptions, type More, } from './query';
78
+ export { StrataQueryProvider, createQueryClient, toLoad, staleOf, useLoad, useInfiniteLoad, useJob, isTaskRunning, apiPage, fetchJson, HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody, type FetchJsonOptions, type FetchJsonInit, createApi, createTypedApi, type TypedApi, type Api, type ApiOptions, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type Job, type JobOptions, type More, } from './query';
79
79
  export { describeActionError, fieldErrorsOf } from './lib/errors';
80
+ export { appBase, withBase } from './lib/base';
81
+ export { useSearchParam, type SearchParam, type SearchParamOptions } from './lib/search-param';
82
+ export { speak, stopSpeaking, canSpeak, pickVoice, useSpeech, type SpeakOptions, type Speech, type UseSpeechOptions } from './lib/speech';
83
+ export { SayAgain, type SayAgainProps } from './components/say-again';
84
+ export { ButtonLink, TextLink, type ButtonLinkProps, type TextLinkProps } from './components/link';
80
85
  export { Compare, type CompareProps, type CompareMode, type Candidate, type ImageMedia, type AudioMedia, type TextMedia, type VideoMedia } from './components/compare';
81
86
  export { ViewportFrame, useViewport, type ViewportFrameProps, type ViewportState } from './components/viewport';
82
87
  export { FullscreenFrame, canFullscreen, type FullscreenFrameProps } from './components/fullscreen-frame';
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
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-CTd1l3md.js";
1
+ import { a as Textarea, c as useSearchParam, d as cn, f as typeSteps, i as NativeSelect, l as Tooltip, n as Field, o as useFieldControl, r as Input, s as controlHeight, t as ChoiceGroup, u as KeyText } from "./field-QCCmWTuY.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 { 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-CiwdvJeH.js";
4
- import { a as fieldErrorsOf, c as IconButton, d as isDev, i as errorPayload, l as RowAction, n as describeActionError, o as readErrorBody, r as describeHttpError, s as Button, t as HttpError, u as buttonVariants } from "./errors-DqezYZgy.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-CgoGqE0T.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-B7iNh4WO.js";
4
+ import { a as fieldErrorsOf, c as IconButton, d as isDev, i as errorPayload, l as RowAction, n as describeActionError, o as readErrorBody, r as describeHttpError, s as Button, t as HttpError, u as buttonVariants } from "./errors-D99YX4XL.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-CfonqUzU.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-DB0Km2m2.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-By3DSUTs.js";
8
8
  import * as React from "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, 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";
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
10
  import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronDown, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, 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
- import { Link, NavLink, useHref, useNavigate, useSearchParams } from "react-router";
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";
14
14
  import { VisuallyHidden, mergeProps, useDrag, useDrop, useFocusRing, useMove, useSlider, useSliderThumb } from "react-aria";
15
15
  import { LayoutInfo, Rect, Size, useSliderState } from "react-stately";
@@ -484,7 +484,25 @@ function Toggle({ label, icon, iconOnly = false, pressed, defaultPressed, onChan
484
484
  }) : button;
485
485
  }
486
486
  /** A single-choice set of toggle buttons for 2 to 7 short options that switch a view. One is always chosen; arrow keys move between them. */
487
- function ToggleGroup({ label, options, value, onChange, size = "default", className }) {
487
+ function ToggleGroup(props) {
488
+ return props.param === void 0 ? /* @__PURE__ */ jsx(ToggleGroupView, { ...props }) : /* @__PURE__ */ jsx(ParamToggleGroup, { ...props });
489
+ }
490
+ function ParamToggleGroup({ param, options, onChange, ...props }) {
491
+ const [value, setValue] = useSearchParam(param, {
492
+ default: options[0]?.value ?? "",
493
+ parse: (raw) => options.some((o) => o.value === raw)
494
+ });
495
+ return /* @__PURE__ */ jsx(ToggleGroupView, {
496
+ ...props,
497
+ options,
498
+ value,
499
+ onChange: (next) => {
500
+ setValue(next);
501
+ onChange?.(next);
502
+ }
503
+ });
504
+ }
505
+ function ToggleGroupView({ label, options, value, onChange, size = "default", className }) {
488
506
  return /* @__PURE__ */ jsx(ToggleButtonGroup, {
489
507
  "aria-label": label,
490
508
  selectionMode: "single",
@@ -1104,7 +1122,7 @@ function LinkCard({ title, description, marks, as: Heading = "h3", className, ..
1104
1122
  }), /* @__PURE__ */ jsx(ArrowUpRight, {
1105
1123
  "aria-hidden": true,
1106
1124
  className: "mt-0.5 size-4 shrink-0 text-muted-foreground"
1107
- })] }) : /* @__PURE__ */ jsx(Link, {
1125
+ })] }) : /* @__PURE__ */ jsx(Link$1, {
1108
1126
  to: destination.to,
1109
1127
  "aria-describedby": describedBy,
1110
1128
  className: linkClass,
@@ -10773,7 +10791,7 @@ function AppShell({ product, nav, navLabel = "Main", topBar, children, className
10773
10791
  className: "border-b border-border md:border-r md:border-b-0",
10774
10792
  children: /* @__PURE__ */ jsxs("div", {
10775
10793
  className: "flex items-center gap-4 px-4 py-3 md:block md:px-3 md:py-4",
10776
- children: [/* @__PURE__ */ jsx(Link, {
10794
+ children: [/* @__PURE__ */ jsx(Link$1, {
10777
10795
  to: "/",
10778
10796
  className: "shrink-0 rounded-control px-2 type-heading text-foreground no-underline",
10779
10797
  children: product
@@ -10827,7 +10845,7 @@ function Breadcrumb({ items }) {
10827
10845
  const last = i === items.length - 1;
10828
10846
  return /* @__PURE__ */ jsxs("li", {
10829
10847
  className: "flex items-center gap-2",
10830
- children: [item.to && !last ? /* @__PURE__ */ jsx(Link, {
10848
+ children: [item.to && !last ? /* @__PURE__ */ jsx(Link$1, {
10831
10849
  to: item.to,
10832
10850
  className: "text-muted-foreground underline hover:text-foreground",
10833
10851
  children: item.label
@@ -10997,6 +11015,76 @@ function ActiveList({ label, active, empty, children, className }) {
10997
11015
  })
10998
11016
  });
10999
11017
  }
11018
+ // src/lib/base.ts
11019
+ /**
11020
+ * Where the app is mounted: the path of the page's `<base href>` without its trailing slash, `""` at the root or where there is no base (SSR, a plain page).
11021
+ * Give it to React Router as `createBrowserRouter(routes, { basename: appBase() || "/" })`.
11022
+ */
11023
+ function appBase(doc = typeof document === "undefined" ? void 0 : document) {
11024
+ if (!doc?.querySelector("base[href]")) return "";
11025
+ return new URL(".", doc.baseURI).pathname.replace(/\/$/, "");
11026
+ }
11027
+ /**
11028
+ * Puts the app's base in front of a root-relative path (`/api/learners` becomes `/proxy/api/learners` behind a proxy).
11029
+ * Anything else (a relative path, a full URL, a protocol-relative `//host`) is returned as it is. Use it for every `fetch`, `<img src>` and download link the app builds; in-app links are router paths and need none.
11030
+ */
11031
+ function withBase(path, base = appBase()) {
11032
+ return path.startsWith("/") && !path.startsWith("//") ? base + path : path;
11033
+ }
11034
+ // src/query/api.ts
11035
+ /**
11036
+ * 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 })`.
11038
+ */
11039
+ function createApi({ base, ...options } = {}) {
11040
+ const url = (path) => withBase(path, base ?? appBase());
11041
+ const send = (method, path, body, init) => fetchJson(url(path), {
11042
+ ...init,
11043
+ method,
11044
+ ...body === void 0 ? {} : { json: body }
11045
+ }, options);
11046
+ return {
11047
+ url,
11048
+ get: (path, init) => send("GET", path, void 0, init),
11049
+ post: (path, body, init) => send("POST", path, body, init),
11050
+ put: (path, body, init) => send("PUT", path, body, init),
11051
+ patch: (path, body, init) => send("PATCH", path, body, init),
11052
+ delete: (path, init) => send("DELETE", path, void 0, init)
11053
+ };
11054
+ }
11055
+ // src/query/typed-api.ts
11056
+ function fill(path, values, query) {
11057
+ const filled = path.replace(/\{([^}]+)\}/g, (_, name) => {
11058
+ const value = values?.[name];
11059
+ if (value === void 0 || value === null) throw new Error(`strata-react: the path ${path} needs "${name}" in \`path\``);
11060
+ return encodeURIComponent(String(value));
11061
+ });
11062
+ const search = new URLSearchParams();
11063
+ for (const [key, value] of Object.entries(query ?? {})) for (const item of Array.isArray(value) ? value : [value]) if (item !== void 0 && item !== null) search.append(key, String(item));
11064
+ const text = search.toString();
11065
+ return text ? `${filled}${filled.includes("?") ? "&" : "?"}${text}` : filled;
11066
+ }
11067
+ /**
11068
+ * `createApi` typed by the server's schema: `const api = createTypedApi<paths>()`, then `api.post("/api/learners", { json: { nickname } })` and
11069
+ * `api.get("/api/learners/{id}", { path: { id } })`; the path, `path` and `query` values, `json` and the answer are checked, and `{id}` is filled and escaped.
11070
+ */
11071
+ function createTypedApi(options = {}) {
11072
+ const api = createApi(options);
11073
+ const call = (method) => (path, request) => {
11074
+ const { path: values, query, json, ...init } = request ?? {};
11075
+ const target = fill(path, values, query);
11076
+ const rest = init;
11077
+ return method === "get" ? api.get(target, rest) : method === "delete" ? api.delete(target, rest) : api[method](target, json, rest);
11078
+ };
11079
+ return {
11080
+ url: api.url,
11081
+ get: call("get"),
11082
+ post: call("post"),
11083
+ put: call("put"),
11084
+ patch: call("patch"),
11085
+ delete: call("delete")
11086
+ };
11087
+ }
11000
11088
  // src/query/infinite.ts
11001
11089
  /** `useInfiniteQuery` for cursor-paged data, returned as an `InfiniteLoad<T>` for `InfiniteList` (or `DataView`). */
11002
11090
  function useInfiniteLoad({ queryKey, queryFn, items, itemKey, hasMore = () => false, nextCursor, cursorAfter = itemKey, isRemoved, describeError = describeHttpError, enabled, staleTime }) {
@@ -11164,6 +11252,157 @@ function useJob({ isRunning, every = 2e3, invalidates = [], describeError, ...op
11164
11252
  function isTaskRunning(task, finished) {
11165
11253
  return !(Array.isArray(finished) ? finished.includes(task.state) : finished.has(task.state));
11166
11254
  }
11255
+ // src/lib/speech.ts
11256
+ /** Whether this browser can say text aloud. */
11257
+ function canSpeak() {
11258
+ return typeof window !== "undefined" && "speechSynthesis" in window && typeof SpeechSynthesisUtterance !== "undefined";
11259
+ }
11260
+ /** The voice that fits a language: exact match, else the same base language, else none (the browser then uses its default for `lang`). */
11261
+ function pickVoice(voices, lang) {
11262
+ if (!lang) return void 0;
11263
+ const wanted = lang.toLowerCase().replace("_", "-");
11264
+ const base = wanted.split("-")[0];
11265
+ return voices.find((v) => v.lang.toLowerCase().replace("_", "-") === wanted) ?? voices.find((v) => v.lang.toLowerCase().replace("_", "-").split("-")[0] === base);
11266
+ }
11267
+ /** Says `text` aloud now, cancelling what is still being said. Does nothing where there is no speech. Returns whether it was handed to the browser. */
11268
+ function speak(text, { lang, rate = .9, onEnd } = {}) {
11269
+ if (!canSpeak() || !text.trim()) return false;
11270
+ const synth = window.speechSynthesis;
11271
+ synth.cancel();
11272
+ const utterance = new SpeechSynthesisUtterance(text);
11273
+ if (lang) utterance.lang = lang;
11274
+ utterance.rate = rate;
11275
+ const voice = pickVoice(synth.getVoices(), lang);
11276
+ if (voice) utterance.voice = voice;
11277
+ if (onEnd) {
11278
+ utterance.onend = onEnd;
11279
+ utterance.onerror = onEnd;
11280
+ }
11281
+ synth.speak(utterance);
11282
+ return true;
11283
+ }
11284
+ /** Stops whatever is being said. */
11285
+ function stopSpeaking() {
11286
+ if (canSpeak()) window.speechSynthesis.cancel();
11287
+ }
11288
+ /**
11289
+ * Speech for a screen: `const { say, supported } = useSpeech({ lang })`. Waits for voices that load late (`voiceschanged`), cancels on unmount so a
11290
+ * prompt does not keep talking after its screen is gone, and does nothing where there is no speech or the person muted it.
11291
+ */
11292
+ function useSpeech({ lang, rate, muted = false } = {}) {
11293
+ const supported = canSpeak() && !muted;
11294
+ const [speaking, setSpeaking] = React.useState(false);
11295
+ const [, setVoicesVersion] = React.useState(0);
11296
+ React.useEffect(() => {
11297
+ if (!canSpeak()) return;
11298
+ const synth = window.speechSynthesis;
11299
+ const onVoices = () => setVoicesVersion((n) => n + 1);
11300
+ synth.addEventListener?.("voiceschanged", onVoices);
11301
+ return () => {
11302
+ synth.removeEventListener?.("voiceschanged", onVoices);
11303
+ synth.cancel();
11304
+ };
11305
+ }, []);
11306
+ React.useEffect(() => {
11307
+ if (muted) {
11308
+ stopSpeaking();
11309
+ setSpeaking(false);
11310
+ }
11311
+ }, [muted]);
11312
+ return {
11313
+ supported,
11314
+ speaking,
11315
+ say: React.useCallback((text) => {
11316
+ if (!supported) return false;
11317
+ const spoken = speak(text, {
11318
+ lang,
11319
+ rate,
11320
+ onEnd: () => setSpeaking(false)
11321
+ });
11322
+ setSpeaking(spoken);
11323
+ return spoken;
11324
+ }, [
11325
+ supported,
11326
+ lang,
11327
+ rate
11328
+ ]),
11329
+ stop: React.useCallback(() => {
11330
+ stopSpeaking();
11331
+ setSpeaking(false);
11332
+ }, [])
11333
+ };
11334
+ }
11335
+ // src/components/say-again.tsx
11336
+ /** An icon button that says one sentence aloud with the browser's voice; hidden where there is no speech or it is muted. */
11337
+ function SayAgain({ text, verb = "Say", className, ...options }) {
11338
+ const { say, supported, speaking } = useSpeech(options);
11339
+ if (!supported) return null;
11340
+ return /* @__PURE__ */ jsx(IconButton, {
11341
+ icon: Volume2,
11342
+ label: `${verb}: ${text}`,
11343
+ "aria-pressed": speaking || void 0,
11344
+ onPress: () => say(text),
11345
+ className
11346
+ });
11347
+ }
11348
+ // src/components/link.tsx
11349
+ function useTarget(target, newTab) {
11350
+ const navigate = useNavigate();
11351
+ return {
11352
+ provide: (node) => /* @__PURE__ */ jsx(RouterProvider, {
11353
+ navigate: (to) => void navigate(to),
11354
+ useHref,
11355
+ children: node
11356
+ }),
11357
+ props: {
11358
+ href: target.to ?? target.href,
11359
+ download: target.href === void 0 ? void 0 : target.download,
11360
+ target: newTab ? "_blank" : void 0,
11361
+ rel: newTab || target.href !== void 0 ? "noreferrer" : void 0
11362
+ }
11363
+ };
11364
+ }
11365
+ /**
11366
+ * A link drawn as a `Button` (React Router `to`, or `href` for a download or another site): the same variants and heights, `variant="default"` is the filled one and counts for the one-filled-button rule (`data-variant` is set).
11367
+ */
11368
+ function ButtonLink(all) {
11369
+ const { to, href, download, newTab, variant, size, icon: Icon, className, children, ...rest } = all;
11370
+ const { provide, props } = useTarget({
11371
+ to,
11372
+ href,
11373
+ download
11374
+ }, newTab);
11375
+ return provide(/* @__PURE__ */ jsxs(Link, {
11376
+ ...rest,
11377
+ ...props,
11378
+ "data-variant": variant ?? "outline",
11379
+ className: cn(buttonVariants({
11380
+ variant,
11381
+ size
11382
+ }), "no-underline", className),
11383
+ children: [Icon && /* @__PURE__ */ jsx(Icon, { "aria-hidden": true }), typeof children === "string" ? /* @__PURE__ */ jsx("span", {
11384
+ className: "min-w-0 truncate",
11385
+ children
11386
+ }) : children]
11387
+ }));
11388
+ }
11389
+ /**
11390
+ * The house in-app link: accent ink, underlined, for a sentence, a table cell or an empty state's next step. `to` for a route, `href` for a file or another site.
11391
+ */
11392
+ function TextLink(all) {
11393
+ const { to, href, download, newTab, icon: Icon, className, children, ...rest } = all;
11394
+ const { provide, props } = useTarget({
11395
+ to,
11396
+ href,
11397
+ download
11398
+ }, newTab);
11399
+ return provide(/* @__PURE__ */ jsxs(Link, {
11400
+ ...rest,
11401
+ ...props,
11402
+ className: cn("inline-flex items-center gap-1 rounded-control text-primary-11 underline underline-offset-4 transition-state hover:text-primary-12 [&_svg]:size-4 [&_svg]:shrink-0", className),
11403
+ children: [Icon && /* @__PURE__ */ jsx(Icon, { "aria-hidden": true }), children]
11404
+ }));
11405
+ }
11167
11406
  // src/lib/image-diff.ts
11168
11407
  /** The longest side, in pixels, a picture is compared at. */
11169
11408
  var MAX_SIDE = 2048;
@@ -16783,6 +17022,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
16783
17022
  ]
16784
17023
  });
16785
17024
  }
16786
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, 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, Density, Dialog, Disclosure, Done, DragSource, 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, PlaceBoard, PlayWindowButton, PlayerNotice, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, STRATA_DRAG_TYPE, SaveStatus, SecretField, SeekBar, SelectableGrid, SelectableGridSkeleton, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, SpanStrip, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, 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, boxViewport, buttonVariants, canFullscreen, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, errorPayload, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, isDoubtful, isReservedChord, isTaskRunning, isTypingTarget, jobProgressText, joinMediaGroup, joinRects, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, splitRect, staleOf, stepId, stepOnGrid, 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, usePlayerWarnings, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, wordAt, wordId, zoomAt, zoomToBox };
17025
+ 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, Density, Dialog, Disclosure, Done, DragSource, 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, 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, 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, buttonVariants, canFullscreen, canSpeak, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createApi, createFormat, createQueryClient, createTypedApi, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, errorPayload, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, isDoubtful, isReservedChord, isTaskRunning, isTypingTarget, jobProgressText, joinMediaGroup, joinRects, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickVoice, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, speak, splitRect, staleOf, stepId, stepOnGrid, stopSpeaking, 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, usePlayerWarnings, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
16787
17026
 
16788
17027
  //# sourceMappingURL=index.js.map