strata-react 1.3.2 → 1.3.4

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 (46) hide show
  1. package/README.md +20 -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/recorder.d.ts +73 -0
  9. package/dist/components/say-again.d.ts +11 -0
  10. package/dist/components/toggle.d.ts +12 -4
  11. package/dist/{errors-DqezYZgy.js → errors-D99YX4XL.js} +2 -2
  12. package/dist/{errors-DqezYZgy.js.map → errors-D99YX4XL.js.map} +1 -1
  13. package/dist/{field-CTd1l3md.js → field-QCCmWTuY.js} +77 -4
  14. package/dist/field-QCCmWTuY.js.map +1 -0
  15. package/dist/{generate-DCRYZPJs.js → generate-CjTHKJ39.js} +21 -3
  16. package/dist/generate-CjTHKJ39.js.map +1 -0
  17. package/dist/index.d.ts +10 -2
  18. package/dist/index.js +447 -15
  19. package/dist/index.js.map +1 -1
  20. package/dist/lib/base.d.ts +10 -0
  21. package/dist/lib/microphone.d.ts +24 -0
  22. package/dist/lib/recording.d.ts +16 -0
  23. package/dist/lib/search-param.d.ts +16 -0
  24. package/dist/lib/speech.d.ts +37 -0
  25. package/dist/map.js +2 -2
  26. package/dist/{query-CgoGqE0T.js → microphone-BZXMKTCM.js} +84 -7
  27. package/dist/microphone-BZXMKTCM.js.map +1 -0
  28. package/dist/panorama.js +2 -2
  29. package/dist/query/api.d.ts +23 -0
  30. package/dist/query/index.d.ts +12 -2
  31. package/dist/query/typed-api.d.ts +78 -0
  32. package/dist/testing/index.d.ts +10 -8
  33. package/dist/testing/layout.d.ts +1 -1
  34. package/dist/testing/microphone.d.ts +20 -0
  35. package/dist/testing/speech.d.ts +32 -0
  36. package/dist/testing/storage.d.ts +7 -0
  37. package/dist/testing.js +175 -8
  38. package/dist/testing.js.map +1 -1
  39. package/dist/{theme-DB0Km2m2.js → theme-By3DSUTs.js} +2 -2
  40. package/dist/{theme-DB0Km2m2.js.map → theme-By3DSUTs.js.map} +1 -1
  41. package/dist/{value-controls-CiwdvJeH.js → value-controls-B7iNh4WO.js} +3 -3
  42. package/dist/{value-controls-CiwdvJeH.js.map → value-controls-B7iNh4WO.js.map} +1 -1
  43. package/package.json +1 -1
  44. package/dist/field-CTd1l3md.js.map +0 -1
  45. package/dist/generate-DCRYZPJs.js.map +0 -1
  46. package/dist/query-CgoGqE0T.js.map +0 -1
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 useMicrophone, c as fetchJson, d as useLoad, f as StrataToastRegion, h as overlaySurface, i as explainMicrophoneError, l as staleOf, m as toastTimeout, n as MicrophoneError, o as StrataQueryProvider, p as toast, r as browserMicrophone, s as createQueryClient, t as MicrophoneContext, u as toLoad } from "./microphone-BZXMKTCM.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,
@@ -1159,7 +1177,7 @@ function LoadError({ message, retry, className }) {
1159
1177
  }
1160
1178
  var defaultError = (failure) => /* @__PURE__ */ jsx(LoadError, { ...failure });
1161
1179
  /** Every view of remote data: renders `skeleton` while loading, an alert with Try again on error, `empty` when `isEmpty`, else `children(data)`, under a `StaleNotice` when a refresh failed. The skeleton and empty state are required. */
1162
- function DataView({ state, isEmpty, skeleton, empty, children, staleNotice = (stale) => /* @__PURE__ */ jsx(StaleNotice, { stale }), error = defaultError, className }) {
1180
+ function DataView$1({ state, isEmpty, skeleton, empty, children, staleNotice = (stale) => /* @__PURE__ */ jsx(StaleNotice, { stale }), error = defaultError, className }) {
1163
1181
  return /* @__PURE__ */ jsxs("div", {
1164
1182
  className: cn("min-w-0", className),
1165
1183
  "aria-busy": state.status === "loading" || void 0,
@@ -9585,7 +9603,7 @@ function InfiniteList({ state, label, children, skeleton, empty, moreLabel, more
9585
9603
  ruled
9586
9604
  })
9587
9605
  });
9588
- return /* @__PURE__ */ jsx(DataView, {
9606
+ return /* @__PURE__ */ jsx(DataView$1, {
9589
9607
  state,
9590
9608
  isEmpty: (items) => items.length === 0 && !more.hasMore,
9591
9609
  skeleton,
@@ -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,350 @@ 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/lib/recording.ts
11349
+ /** The quietest level a speech meter draws, in dBFS: below it is silence for speech. */
11350
+ var LEVEL_FLOOR_DB = -60;
11351
+ /** Joins chunks of samples into one buffer, in order. */
11352
+ function joinSamples(chunks) {
11353
+ const out = new Float32Array(chunks.reduce((n, c) => n + c.length, 0));
11354
+ let at = 0;
11355
+ for (const c of chunks) {
11356
+ out.set(c, at);
11357
+ at += c.length;
11358
+ }
11359
+ return out;
11360
+ }
11361
+ /** A mono 16-bit PCM WAV of `samples` (-1 to 1; beyond full scale is clipped). */
11362
+ function encodeWav(samples, sampleRate) {
11363
+ const bytes = samples.length * 2;
11364
+ const view = new DataView(new ArrayBuffer(44 + bytes));
11365
+ const text = (at, s) => {
11366
+ for (let i = 0; i < s.length; i++) view.setUint8(at + i, s.charCodeAt(i));
11367
+ };
11368
+ text(0, "RIFF");
11369
+ view.setUint32(4, 36 + bytes, true);
11370
+ text(8, "WAVE");
11371
+ text(12, "fmt ");
11372
+ view.setUint32(16, 16, true);
11373
+ view.setUint16(20, 1, true);
11374
+ view.setUint16(22, 1, true);
11375
+ view.setUint32(24, sampleRate, true);
11376
+ view.setUint32(28, sampleRate * 2, true);
11377
+ view.setUint16(32, 2, true);
11378
+ view.setUint16(34, 16, true);
11379
+ text(36, "data");
11380
+ view.setUint32(40, bytes, true);
11381
+ for (let i = 0; i < samples.length; i++) {
11382
+ const s = Math.max(-1, Math.min(1, samples[i]));
11383
+ view.setInt16(44 + i * 2, s < 0 ? s * 32768 : s * 32767, true);
11384
+ }
11385
+ return new Blob([view.buffer], { type: "audio/wav" });
11386
+ }
11387
+ /** The highest sample in dBFS, never below `LEVEL_FLOOR_DB` (silence reads as the floor, not minus infinity). */
11388
+ function peakDb(samples) {
11389
+ let peak = 0;
11390
+ for (let i = 0; i < samples.length; i++) peak = Math.max(peak, Math.abs(samples[i]));
11391
+ return peak > 0 ? Math.max(-60, 20 * Math.log10(peak)) : -60;
11392
+ }
11393
+ /** Judges a take by its peak (dBFS). */
11394
+ function speechLevel(peak) {
11395
+ if (peak >= -1) return {
11396
+ tone: "danger",
11397
+ word: "Too loud",
11398
+ advice: "It may have clipped. Move back from the microphone or turn its gain down."
11399
+ };
11400
+ if (peak < -30) return {
11401
+ tone: "warning",
11402
+ word: "Too quiet",
11403
+ advice: "Move closer to the microphone or turn its gain up."
11404
+ };
11405
+ return {
11406
+ tone: "success",
11407
+ word: "Good level",
11408
+ advice: "The level suits speech."
11409
+ };
11410
+ }
11411
+ // src/components/recorder.tsx
11412
+ /** Records one take at a time from the microphone, with its live level, as a lossless WAV. */
11413
+ function useRecorder({ maxSeconds, microphone }) {
11414
+ const fromContext = useMicrophone();
11415
+ const device = microphone ?? fromContext;
11416
+ const [state, setState] = React.useState({ phase: "idle" });
11417
+ const stream = React.useRef(null);
11418
+ const chunks = React.useRef([]);
11419
+ const resolveStop = React.useRef(null);
11420
+ const limit = React.useRef(maxSeconds);
11421
+ limit.current = maxSeconds;
11422
+ const mounted = React.useRef(true);
11423
+ const stop = React.useCallback(() => {
11424
+ const s = stream.current;
11425
+ if (!s) return;
11426
+ stream.current = null;
11427
+ s.close();
11428
+ const samples = joinSamples(chunks.current);
11429
+ chunks.current = [];
11430
+ setState({ phase: "idle" });
11431
+ resolveStop.current?.({
11432
+ samples,
11433
+ sampleRate: s.sampleRate,
11434
+ wav: encodeWav(samples, s.sampleRate),
11435
+ seconds: samples.length / s.sampleRate,
11436
+ peak: peakDb(samples),
11437
+ device: s.device
11438
+ });
11439
+ resolveStop.current = null;
11440
+ }, []);
11441
+ const start = React.useCallback(async () => {
11442
+ if (stream.current || resolveStop.current) return null;
11443
+ setState({ phase: "opening" });
11444
+ chunks.current = [];
11445
+ let recent = [];
11446
+ let frames = 0;
11447
+ const done = new Promise((resolve) => {
11448
+ resolveStop.current = resolve;
11449
+ });
11450
+ let opened;
11451
+ try {
11452
+ opened = await device.open((chunk) => {
11453
+ const s = stream.current;
11454
+ if (!s) return;
11455
+ const room = Math.round(limit.current * s.sampleRate) - frames;
11456
+ const kept = chunk.length > room ? chunk.subarray(0, Math.max(0, room)) : chunk;
11457
+ chunks.current.push(kept);
11458
+ frames += kept.length;
11459
+ recent = [...recent.slice(-4), peakDb(kept)];
11460
+ setState({
11461
+ phase: "recording",
11462
+ seconds: frames / s.sampleRate,
11463
+ level: Math.max(...recent)
11464
+ });
11465
+ if (kept.length < chunk.length || frames >= limit.current * s.sampleRate) stop();
11466
+ });
11467
+ } catch (e) {
11468
+ resolveStop.current = null;
11469
+ setState({
11470
+ phase: "failed",
11471
+ reason: e instanceof MicrophoneError ? e.message : `The microphone could not be opened (${String(e)}).`
11472
+ });
11473
+ return null;
11474
+ }
11475
+ if (!mounted.current) {
11476
+ opened.close();
11477
+ resolveStop.current = null;
11478
+ return null;
11479
+ }
11480
+ stream.current = opened;
11481
+ setState((now) => now.phase === "opening" ? {
11482
+ phase: "recording",
11483
+ seconds: 0,
11484
+ level: -60
11485
+ } : now);
11486
+ return done;
11487
+ }, [device, stop]);
11488
+ React.useEffect(() => {
11489
+ mounted.current = true;
11490
+ return () => {
11491
+ mounted.current = false;
11492
+ stream.current?.close();
11493
+ stream.current = null;
11494
+ };
11495
+ }, []);
11496
+ return {
11497
+ state,
11498
+ start,
11499
+ stop,
11500
+ recording: state.phase === "recording" || state.phase === "opening"
11501
+ };
11502
+ }
11503
+ /** `InputLevel`'s "Too loud" notch: -3 dBFS on the meter's `LEVEL_FLOOR_DB`..0 scale. */
11504
+ var inputLevelThresholds = [{
11505
+ at: -57 / -60,
11506
+ tone: "danger",
11507
+ label: "Too loud"
11508
+ }];
11509
+ /** The microphone's live level while a take records: a peak meter in dBFS with a "Too loud" notch, and the take's running time. */
11510
+ function InputLevel({ level, seconds, maxSeconds, label = "Input level", className }) {
11511
+ const db = Math.min(0, Math.max(-60, level));
11512
+ return /* @__PURE__ */ jsx(Meter, {
11513
+ label,
11514
+ value: db - -60,
11515
+ max: 60,
11516
+ thresholds: inputLevelThresholds,
11517
+ valueText: `${format.integer(Math.round(db) || 0)}\u00a0dBFS`,
11518
+ detail: `Recording ${format.runningTime(seconds)} of at most ${format.runningTime(maxSeconds)}`,
11519
+ className
11520
+ });
11521
+ }
11522
+ /** How a finished take's level reads for speech: a status word, the peak, and what to do about it. */
11523
+ function TakeLevel({ peak, lead, className }) {
11524
+ const verdict = speechLevel(peak);
11525
+ const figure = `peak ${format.integer(Math.round(peak) || 0)}\u00a0dBFS`;
11526
+ return /* @__PURE__ */ jsxs("p", {
11527
+ className: cn("flex items-baseline gap-2 type-body-sm", className),
11528
+ children: [/* @__PURE__ */ jsx(Status, {
11529
+ tone: verdict.tone,
11530
+ children: verdict.word
11531
+ }), /* @__PURE__ */ jsxs("span", {
11532
+ className: "min-w-0 flex-1",
11533
+ children: [
11534
+ lead ? `${lead}, ${figure}` : figure.charAt(0).toUpperCase() + figure.slice(1),
11535
+ ". ",
11536
+ verdict.advice
11537
+ ]
11538
+ })]
11539
+ });
11540
+ }
11541
+ // src/components/link.tsx
11542
+ function useTarget(target, newTab) {
11543
+ const navigate = useNavigate();
11544
+ return {
11545
+ provide: (node) => /* @__PURE__ */ jsx(RouterProvider, {
11546
+ navigate: (to) => void navigate(to),
11547
+ useHref,
11548
+ children: node
11549
+ }),
11550
+ props: {
11551
+ href: target.to ?? target.href,
11552
+ download: target.href === void 0 ? void 0 : target.download,
11553
+ target: newTab ? "_blank" : void 0,
11554
+ rel: newTab || target.href !== void 0 ? "noreferrer" : void 0
11555
+ }
11556
+ };
11557
+ }
11558
+ /**
11559
+ * 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).
11560
+ */
11561
+ function ButtonLink(all) {
11562
+ const { to, href, download, newTab, variant, size, icon: Icon, className, children, ...rest } = all;
11563
+ const { provide, props } = useTarget({
11564
+ to,
11565
+ href,
11566
+ download
11567
+ }, newTab);
11568
+ return provide(/* @__PURE__ */ jsxs(Link, {
11569
+ ...rest,
11570
+ ...props,
11571
+ "data-variant": variant ?? "outline",
11572
+ className: cn(buttonVariants({
11573
+ variant,
11574
+ size
11575
+ }), "no-underline", className),
11576
+ children: [Icon && /* @__PURE__ */ jsx(Icon, { "aria-hidden": true }), typeof children === "string" ? /* @__PURE__ */ jsx("span", {
11577
+ className: "min-w-0 truncate",
11578
+ children
11579
+ }) : children]
11580
+ }));
11581
+ }
11582
+ /**
11583
+ * 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.
11584
+ */
11585
+ function TextLink(all) {
11586
+ const { to, href, download, newTab, icon: Icon, className, children, ...rest } = all;
11587
+ const { provide, props } = useTarget({
11588
+ to,
11589
+ href,
11590
+ download
11591
+ }, newTab);
11592
+ return provide(/* @__PURE__ */ jsxs(Link, {
11593
+ ...rest,
11594
+ ...props,
11595
+ 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),
11596
+ children: [Icon && /* @__PURE__ */ jsx(Icon, { "aria-hidden": true }), children]
11597
+ }));
11598
+ }
11167
11599
  // src/lib/image-diff.ts
11168
11600
  /** The longest side, in pixels, a picture is compared at. */
11169
11601
  var MAX_SIDE = 2048;
@@ -11823,7 +12255,7 @@ function PairJudge({ pair, skeleton, empty, onAnswer, pending, progress, flagRea
11823
12255
  className: "type-body-sm text-muted-foreground",
11824
12256
  children: progress
11825
12257
  }),
11826
- /* @__PURE__ */ jsx(DataView, {
12258
+ /* @__PURE__ */ jsx(DataView$1, {
11827
12259
  state: pair,
11828
12260
  isEmpty: (p) => p === null,
11829
12261
  skeleton,
@@ -16783,6 +17215,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
16783
17215
  ]
16784
17216
  });
16785
17217
  }
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 };
17218
+ 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, 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, canSpeak, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createApi, createFormat, 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, 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, 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, usePlayerWarnings, useRecorder, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
16787
17219
 
16788
17220
  //# sourceMappingURL=index.js.map