strata-react 1.3.9 → 1.3.11

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/README.md CHANGED
@@ -175,7 +175,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
175
175
  | Notices and progress | `Alert`, `toast`, `StrataToastRegion`, `useClientWork`, `JobStatus` | Three weights. A `toast` confirms finished work and goes by itself (5 s plus 40 ms a character, 8 s minimum with an action, paused under the pointer or focus, always dismissable); it has no danger tone, because an error a person must act on is an inline `Alert` with its recovery as `action` (`announce` makes it `role="alert"` only when it answers something the person just did). `StrataToastRegion` goes once at the app root. `useClientWork` runs browser work with progress, cancel (aborts its `signal`, ends `cancelled`, never `failed`) and a double-start guard; `JobStatus` shows it exactly as it shows a server job, with `onCancel`, `cancelled` and `onDismiss` |
176
176
  | Media player | `MediaPlayer`, `useMediaElement`, `SPEECH_RATES`, `useMediaSpans`, `SpanActions`, `PlayerNotice`, `SpanStrip` | Play a file or a sequence of chapters without the event glue: the element, its state, Strata's controls (or the browser's own on a touch device, `controls="auto"`), a load error with Try again, `navigator.mediaSession` metadata, the seek bar spanning the whole sequence. `useMediaElement(ref)` alone follows an element drawn with the browser's controls `spans` and `spanKinds` mark stretches (an intro, a recap, a sponsor read) on the seek bar as named ranges in a status role's tone and act on them as playback reaches them: `auto` skips (or mutes, for `action: "mute"`) with "Skipped intro" and Undo, `ask` offers a Skip button over the picture and on the `s` key, `off` only draws; each is acted on once, `onSpan` reports `skipped`, `muted`, `undone` or `played`, and `SeekBar` takes `spans` too. `mediaRef` hands out the player's state and requests (an object ref holds the latest, no render of its own), `overlay` draws the app's own thing over the picture only, and a video keeps a 16:9 (or `aspect`) box before its metadata loads. A video has a Full screen button and the `f` key by default (`fullscreen={false}` removes them); on the picture a click plays or pauses, a double click toggles full screen and the wheel sets the volume while the player has focus. A kind's `colour` names a custom property of the app's theme (`"--seg-sponsor"`) instead of a tone, each range carries `data-kind`, and under the browser's own controls a `SpanStrip` under the picture draws the ranges. `start` begins a first load at a time (an attacher's `startAt`, or a seek once the metadata is in) and says "Picked up at 2:05" with Start over (`resumeWords`); `onProgress` reports the position and the seconds actually played through, each once, a skipped span counted (`useMediaElement` takes it too, with `markWatched`). The HLS attacher starts a `growing` source at its beginning, honours `config.startPosition` and takes `words` for its failures. |
177
177
  | Media playback | `Transport`, `SeekBar`, `TimeReadout`, `VolumeControl`, `RateChoice`, `MediaStage`, `StageGuides`, `transportShortcuts`, `format.timecode` | The controls around anything that plays, wired to a player the app owns (HTML media, Web Audio, a canvas, a data replay). Every control is a named icon button in one toolbar; the play button's name is "Play" or "Pause". `SeekBar` has the formatted time as its accessible value, arrows step 5 s and Page keys 30 s by default, and optional marks. `VolumeControl` shows its percent, and muting remembers the level. `transportShortcuts` is the one list for `useHotkeys` and `KeysLegend` (Space and K, J and L, the arrows by a frame, Home and End). `format.timecode` prints m:ss, m:ss.mmm or m:ss:ff. `MediaStage` fits a picture of any aspect ratio into the pane with a letterbox on the sunken surface role, and takes overlays such as `StageGuides` |
178
- | Listening and reading | `Waveform`, `TranscriptView`, `PlayWindowButton`, `MediaGroup`; `resamplePeaks`, `peaksFromAudio`, `phraseAt`, `wordAt` | Timed media: a waveform from peaks or a decoded file (one slider, marks by line style, named spans, zoom, a keyboard-made range, a spectrogram underlay); timed text that marks the heard word and plays from any word (modes, speakers, follow and Jump to now, virtualised), with doubtful words (dotted, named, counted, "Only doubtful"), a mark per phrase set from a row menu (`states`, `onPhraseState`), correction in place (Enter or F2, `onEdit`) and a hover and focus card (`renderCard`); `MediaPlayer window` plays one stretch of a file, `MediaGroup` lets one player play at a time, `PlayWindowButton` is a row's play control on a shared element; a review transcript needs no player (`time` and `onSeek` are optional), takes `marking` (words become `MarkableText` marks with ids `wordId(phraseId, index)`, selected across rows that are not mounted) and shows a corrected word (`word.correction`) dotted with the original on hover and `onCorrectionPress` to open it |
178
+ | Listening and reading | `Waveform`, `TranscriptView`, `PlayWindowButton`, `MediaGroup`, `FilmStrip`; `resamplePeaks`, `peaksFromAudio`, `peakGain`, `phraseAt`, `wordAt`, `pickEvenly`, `frameAt` | Timed media: a waveform from peaks or a decoded file (one slider, marks by line style, named spans, zoom, a keyboard-made range, a spectrogram underlay, `normalise` to draw quiet sound to fill the height and say by how much); `FilmStrip` is a row of frames from a stretch of video that fits its width (picked evenly), each with its time, pressing one seeks (`onSeek`, one tab stop with arrow keys), and the frame at `time` inside `span` is ringed; timed text that marks the heard word and plays from any word (modes, speakers, follow and Jump to now, virtualised), with doubtful words (dotted, named, counted, "Only doubtful"), a mark per phrase set from a row menu (`states`, `onPhraseState`), correction in place (Enter or F2, `onEdit`) and a hover and focus card (`renderCard`); `MediaPlayer window` plays one stretch of a file, `MediaGroup` lets one player play at a time, `PlayWindowButton` is a row's play control on a shared element; a review transcript needs no player (`time` and `onSeek` are optional), takes `marking` (words become `MarkableText` marks with ids `wordId(phraseId, index)`, selected across rows that are not mounted) and shows a corrected word (`word.correction`) dotted with the original on hover and `onCorrectionPress` to open it |
179
179
  | Streams | `MediaPlayer attach`/`growing`, `useAttachedSource`, `attachHls` (`strata-react/hls`) | A source the element cannot play is attached by an engine; a source still being made says so, shows what exists as ready, and waits at its end without ending |
180
180
  | 360 | `PanoramaViewer` (`strata-react/panorama`), `project`, `unproject`, `describeView` | A 360 picture or video as a controlled window (yaw, pitch, field of view), drag, wheel, pinch and keys, an overlay in the picture's coordinates, said in words, a flat fallback with no WebGL2 |
181
181
  | Conversation | `Conversation`, `Composer`, `RichText`; `matchEntities`, `parseRichText` | A question-and-answer thread: answers stream, finish or fail in place (Try again), one polite announcement per finished answer, following only while at the bottom (Jump to latest); answers can carry pictures (`images`, labelled, lazy, linked to full size) that stay visible beside the collapsed "looked up"; a composer that sends on Enter and is disabled with its reason while answering (Stop); a safe text subset (bold, code, lists, http links, never HTML) whose known ids, longest first and whole words only, become buttons |
package/UPGRADING.md CHANGED
@@ -12,6 +12,7 @@ time. While the version is 0.x, any release may break.
12
12
  Every PR that changes what an app sees adds a line here (see `CLAUDE.md`, "Changelog").
13
13
 
14
14
  ## 2026-11-24
15
+ - `RateChoice` (the speed in `MediaPlayer`, `VideoClock`, `CompareVideo`, `CompareVideoGrid`) is React Aria's `Select`, not a native select (#324): a test that did `user.selectOptions(getByRole("combobox", { name: "Playback speed" }), "1.5×")` now clicks `getByRole("button", { name: /Playback speed/ })` and then `findByRole("option", { name: "1.5×" })`. Visual baselines with a player move: the control is narrower, so a phone-width player's controls can fit on one row.
15
16
  - `createApi`'s `post`/`put`/`patch` send a `Blob`, bytes, `FormData`, `URLSearchParams` or a stream as it is (a Blob with its own type as Content-Type); before, any body was `JSON.stringify`ed, so such a body arrived as `{}`. `createTypedApi` takes `body` (not `json`) on an operation whose request body has only a non-JSON media type, so a workaround that went round the typed client through `fetchJson` can be deleted.
16
17
  - `SayAgain` inside a `ClipsProvider` takes the recordings of `text` and the provider's `lang` itself; one given `parts` or `lang` is unchanged, and outside a provider nothing changes.
17
18
 
@@ -0,0 +1,35 @@
1
+ import { AspectRatio } from './thumbnail';
2
+ import * as React from "react";
3
+ /** One frame: its time in seconds and its picture (`null` when there is none). */
4
+ export type FilmFrame = {
5
+ time: number;
6
+ src: string | null;
7
+ };
8
+ /** The film strip's props. */
9
+ export type FilmStripProps = {
10
+ /** Names the strip: "Frames of scene 3". */
11
+ label: string;
12
+ /** The frames, in time order. More than fit are thinned evenly. */
13
+ frames: readonly FilmFrame[];
14
+ /** The stretch the strip stands for, seconds: `time` inside it marks the frame being watched. Default the first frame's time to the last's. */
15
+ span?: readonly [number, number];
16
+ /** The playhead, seconds. */
17
+ time?: number;
18
+ /** A frame was pressed: play from its time. Makes the frames buttons. */
19
+ onSeek?: (time: number) => void;
20
+ /** Width over height of each frame. Default 4/3. */
21
+ aspect?: AspectRatio;
22
+ /** The narrowest a frame is drawn, px: sets how many fit. Default 96. */
23
+ frameWidth?: number;
24
+ /** The words for a frame with no picture. Default "No picture". */
25
+ missing?: string;
26
+ /** The verb of a frame's button. Default "Play from", as "Play from 1:20". */
27
+ seekVerb?: string;
28
+ className?: string;
29
+ };
30
+ /** `n` of `items` spread evenly from the first to the last (all of them when there are no more than `n`). */
31
+ export declare function pickEvenly<T>(items: readonly T[], n: number): T[];
32
+ /** The index of the frame showing `time`: the last at or before it, or -1 outside `span`. */
33
+ export declare function frameAt(frames: readonly FilmFrame[], time: number | undefined, span: readonly [number, number]): number;
34
+ /** A row of frames from a stretch of video that fits its width, each with its time; pressing one seeks when `onSeek` is given, and the frame at `time` is marked. */
35
+ export declare function FilmStrip({ label, frames, span, time, onSeek, aspect, frameWidth, missing, seekVerb, className }: FilmStripProps): React.JSX.Element;
@@ -99,7 +99,7 @@ export type VolumeControlProps = {
99
99
  };
100
100
  /** A mute button and a volume slider with its value in percent. Muting sets the volume to 0 and remembers the level; unmuting puts it back. Moving the slider from 0 unmutes. */
101
101
  export declare function VolumeControl({ volume, onVolumeChange, max, disabled, className }: VolumeControlProps): React.JSX.Element;
102
- /** A choice of playback speed ("0.5×", "1×", "1.5×") on a native select, named "Playback speed". */
102
+ /** A choice of playback speed ("0.5×", "1×", "1.5×"), named "Playback speed": React Aria's Select. */
103
103
  export declare function RateChoice({ rate, onRateChange, rates, className }: {
104
104
  rate: number;
105
105
  onRateChange: (rate: number) => void;
@@ -42,6 +42,11 @@ type Common = {
42
42
  defaultView?: readonly [number, number];
43
43
  /** How many peaks a decoded file is reduced to. Default 2000. */
44
44
  buckets?: number;
45
+ /** Scale the drawing so the loud parts fill the height (a quiet recording, such as a camcorder tape), and say by how much. `true` uses the defaults of `peakGain`; an object sets them. Only the drawing changes. */
46
+ normalise?: boolean | {
47
+ percentile?: number;
48
+ maxGain?: number;
49
+ };
45
50
  /** Turns a decoded file into samples. Default: the browser's `AudioContext.decodeAudioData`. */
46
51
  decode?: (data: ArrayBuffer) => Promise<DecodedAudio>;
47
52
  /** The words of the reading state; defaults say "Reading the waveform". */
@@ -62,5 +67,5 @@ export type WaveformProps = Common & ({
62
67
  peaks?: never;
63
68
  });
64
69
  /** An audio waveform with marks, spans and a playhead: one slider you click, drag or key to seek, zoom, and a range to select. */
65
- export declare function Waveform({ label, peaks, source, duration: given, time, onSeek, marks, spans, underlay, range: controlledRange, onRangeChange, step, bigStep, defaultView, buckets, decode, words, disabled, className }: WaveformProps): React.JSX.Element;
70
+ export declare function Waveform({ label, peaks, source, duration: given, time, onSeek, marks, spans, underlay, range: controlledRange, onRangeChange, step, bigStep, defaultView, buckets, normalise, decode, words, disabled, className }: WaveformProps): React.JSX.Element;
66
71
  export {};
package/dist/index.d.ts CHANGED
@@ -39,13 +39,14 @@ export { useJobAction, type JobAction, type JobActionOptions } from './component
39
39
  export { WorkflowSteps, type WorkflowStepsProps, type WorkflowStage, type StageState, type StageWords } from './components/workflow-steps';
40
40
  export { JobsTable, type JobsTableProps, type JobRow } from './components/jobs-table';
41
41
  export { Thumbnail, ThumbnailSkeleton, type ThumbnailProps, type AspectRatio } from './components/thumbnail';
42
+ export { FilmStrip, pickEvenly, frameAt, type FilmStripProps, type FilmFrame } from './components/film-strip';
42
43
  export { DataTable, TableSkeleton, parseSort, serialiseSort, type CellValue, type Column, type Sort, type DataTableProps, type RowSelection, type RowExpansion, } from './components/data-table';
43
44
  export { MediaPlayer, useMediaElement, useAttachedSource, SPEECH_RATES, type MediaPlayerProps, type MediaElementState, type MediaElementOptions, type MediaWindow, type StreamContext, type StreamAttachment, type SourceAttacher, type MediaProblem, type MediaSource, type MediaSession, type MediaProgress, type ResumeWords } from './components/media-player';
44
45
  export { useMediaSpans, SpanActions, PlayerNotice, type SpanActionsNotice, type MediaSpanData, type SpanKind, type SpanBehaviour, type SpanOutcome, type SpanWords, type MediaSpansState } from './components/media-spans';
45
46
  export { TranscriptView, type TranscriptViewProps, type TranscriptSeek } from './components/transcript-view';
46
47
  export { phraseAt, wordAt, wordId, phraseOfWordId, isDoubtful, phraseDoubtful, type TranscriptGroup, type TranscriptPhrase, type TranscriptPhraseState, type TranscriptWord } from './lib/transcript';
47
48
  export { Waveform, type WaveformProps, type WaveformMark, type WaveformMarkKind, type WaveformSpan, type WaveformTone } from './components/waveform';
48
- export { resamplePeaks, toPeakPair, peaksFromAudio, type WaveformPeaks, type PeakPair, type DecodedAudio } from './lib/waveform';
49
+ export { resamplePeaks, toPeakPair, peaksFromAudio, peakGain, type WaveformPeaks, type PeakPair, type DecodedAudio } from './lib/waveform';
49
50
  export { MediaGroup, PlayWindowButton, joinMediaGroup, type PlayWindowButtonProps } from './components/media-group';
50
51
  export { Transport, TimeReadout, SeekBar, SpanStrip, VolumeControl, RateChoice, MediaStage, StageGuides, transportShortcuts, type TransportProps, type SeekBarProps, type SeekBarSpan, type VolumeControlProps, type Precision } from './components/media';
51
52
  export { Timeline, TimelineZoomControls, useTimelineZoom, noOverlap, type TimelineProps, type TimelineItem, type TimelineLane, type TimelineMarker, type TimelineChange, type TimelineDrop } from './components/timeline';
package/dist/index.js CHANGED
@@ -6,12 +6,12 @@ import { a as useMicrophone, c as fetchJson, d as useLoad, f as StrataToastRegio
6
6
  import { n as useSharedCursor, r as geo, t as CursorScope } from "./cursor-DDGBPiTJ.js";
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
- 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";
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, Select, SelectValue, 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, 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";
14
- import { VisuallyHidden, mergeProps, useDrag, useDrop, useFocusRing, useMove, useSlider, useSliderThumb } from "react-aria";
14
+ import { UNSAFE_PortalProvider, VisuallyHidden, mergeProps, useDrag, useDrop, useFocusRing, useMove, useSlider, useSliderThumb, useUNSAFE_PortalContext } from "react-aria";
15
15
  import { LayoutInfo, Rect, Size, useSliderState } from "react-stately";
16
16
  import { hashKey, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
17
17
  import pixelmatch from "pixelmatch";
@@ -2819,6 +2819,81 @@ function ThumbnailSkeleton({ aspect = 1, className }) {
2819
2819
  children: /* @__PURE__ */ jsx(Skeleton, { className: "absolute inset-0" })
2820
2820
  });
2821
2821
  }
2822
+ // src/components/film-strip.tsx
2823
+ var GAP$1 = 4;
2824
+ /** `n` of `items` spread evenly from the first to the last (all of them when there are no more than `n`). */
2825
+ function pickEvenly(items, n) {
2826
+ if (n <= 0) return [];
2827
+ if (items.length <= n) return [...items];
2828
+ if (n === 1) return [items[Math.floor((items.length - 1) / 2)]];
2829
+ return Array.from({ length: n }, (_, i) => items[Math.round(i * (items.length - 1) / (n - 1))]);
2830
+ }
2831
+ /** The index of the frame showing `time`: the last at or before it, or -1 outside `span`. */
2832
+ function frameAt(frames, time, span) {
2833
+ if (time === void 0 || frames.length === 0 || time < span[0] || time >= span[1]) return -1;
2834
+ let found = 0;
2835
+ for (let i = 0; i < frames.length; i++) if (frames[i].time <= time) found = i;
2836
+ return found;
2837
+ }
2838
+ /** A row of frames from a stretch of video that fits its width, each with its time; pressing one seeks when `onSeek` is given, and the frame at `time` is marked. */
2839
+ function FilmStrip({ label, frames, span, time, onSeek, aspect = "4/3", frameWidth = 96, missing = "No picture", seekVerb = "Play from", className }) {
2840
+ const box = React.useRef(null);
2841
+ const [width, setWidth] = React.useState(0);
2842
+ React.useLayoutEffect(() => {
2843
+ const el = box.current;
2844
+ if (!el) return;
2845
+ const read = () => setWidth(Math.round(el.getBoundingClientRect().width));
2846
+ read();
2847
+ if (typeof ResizeObserver === "undefined") return;
2848
+ const ro = new ResizeObserver(read);
2849
+ ro.observe(el);
2850
+ return () => ro.disconnect();
2851
+ }, []);
2852
+ const shown = pickEvenly(frames, Math.max(1, Math.floor((width + GAP$1) / (frameWidth + GAP$1))));
2853
+ const current = frameAt(shown, time, span ?? [frames[0]?.time ?? 0, frames.length ? frames[frames.length - 1].time + 1e-6 : 0]);
2854
+ const picture = (f, i) => /* @__PURE__ */ jsx(Thumbnail, {
2855
+ src: f.src,
2856
+ alt: onSeek ? "" : `Frame at ${format.runningTime(f.time)}`,
2857
+ missing,
2858
+ aspect,
2859
+ className: cn("w-full", i === current && "ring-2 ring-primary ring-offset-1 ring-offset-background"),
2860
+ children: /* @__PURE__ */ jsx("span", {
2861
+ "aria-hidden": true,
2862
+ className: "absolute bottom-0.5 right-0.5 rounded-control bg-background/80 px-1 type-caption tabular-nums text-foreground",
2863
+ children: format.runningTime(f.time)
2864
+ })
2865
+ });
2866
+ return /* @__PURE__ */ jsx("div", {
2867
+ ref: box,
2868
+ className: cn("min-w-0", className),
2869
+ children: frames.length === 0 ? /* @__PURE__ */ jsx(Thumbnail, {
2870
+ src: null,
2871
+ alt: label,
2872
+ missing,
2873
+ aspect,
2874
+ className: "w-full max-w-24"
2875
+ }) : onSeek ? /* @__PURE__ */ jsx(Toolbar, {
2876
+ label,
2877
+ className: "flex-nowrap gap-1",
2878
+ children: shown.map((f, i) => /* @__PURE__ */ jsx(Button$1, {
2879
+ "aria-label": `${seekVerb} ${format.runningTime(f.time)}`,
2880
+ "aria-current": i === current ? "time" : void 0,
2881
+ onPress: () => onSeek(f.time),
2882
+ className: "min-w-0 flex-1 rounded-control outline-offset-2 transition-state press",
2883
+ children: picture(f, i)
2884
+ }, `${f.time}-${i}`))
2885
+ }) : /* @__PURE__ */ jsx("div", {
2886
+ role: "group",
2887
+ "aria-label": label,
2888
+ className: "flex gap-1",
2889
+ children: shown.map((f, i) => /* @__PURE__ */ jsx("div", {
2890
+ "aria-current": i === current ? "time" : void 0,
2891
+ className: "min-w-0 flex-1",
2892
+ children: picture(f, i)
2893
+ }, `${f.time}-${i}`))
2894
+ })
2895
+ });
2896
+ }
2822
2897
  // src/components/fullscreen-frame.tsx
2823
2898
  /** Whether this browser can show an element full screen. False in jsdom and on iPhone, where the modal fallback is used. */
2824
2899
  function canFullscreen() {
@@ -2860,10 +2935,15 @@ function FullscreenFrame({ label, active, onActiveChange, modal: allowModal = tr
2860
2935
  };
2861
2936
  }, [active, allowModal]);
2862
2937
  const modal = allowModal && active && !native && (!canFullscreen() || refused);
2938
+ const outer = useUNSAFE_PortalContext();
2939
+ const getContainer = React.useCallback(() => native && ref.current ? ref.current : outer.getContainer?.() ?? document.body, [native, outer]);
2863
2940
  const inner = /* @__PURE__ */ jsx("div", {
2864
2941
  ref,
2865
2942
  className: cn(active && "flex h-full min-h-0 flex-col bg-background p-4", className),
2866
- children
2943
+ children: /* @__PURE__ */ jsx(UNSAFE_PortalProvider, {
2944
+ getContainer,
2945
+ children
2946
+ })
2867
2947
  });
2868
2948
  if (!modal) return inner;
2869
2949
  return /* @__PURE__ */ jsx(ModalOverlay, {
@@ -3200,7 +3280,7 @@ function VolumeControl({ volume, onVolumeChange, max = 100, disabled, className
3200
3280
  })]
3201
3281
  });
3202
3282
  }
3203
- /** A choice of playback speed ("0.5×", "1×", "1.5×") on a native select, named "Playback speed". */
3283
+ /** A choice of playback speed ("0.5×", "1×", "1.5×"), named "Playback speed": React Aria's Select. */
3204
3284
  function RateChoice({ rate, onRateChange, rates = [
3205
3285
  .5,
3206
3286
  1,
@@ -3208,15 +3288,34 @@ function RateChoice({ rate, onRateChange, rates = [
3208
3288
  1.5,
3209
3289
  2
3210
3290
  ], className }) {
3211
- return /* @__PURE__ */ jsx(NativeSelect, {
3291
+ return /* @__PURE__ */ jsxs(Select, {
3212
3292
  "aria-label": "Playback speed",
3213
- value: String(rate),
3214
- onChange: (e) => onRateChange(Number(e.target.value)),
3293
+ selectedKey: String(rate),
3294
+ onSelectionChange: (key) => key !== null && onRateChange(Number(key)),
3215
3295
  className: cn("w-auto", className),
3216
- children: rates.map((r) => /* @__PURE__ */ jsx("option", {
3217
- value: String(r),
3218
- children: `${r}×`
3219
- }, r))
3296
+ children: [/* @__PURE__ */ jsxs(Button$1, {
3297
+ className: cn("flex w-full items-center justify-between gap-2 rounded-control border border-input bg-background pr-2 pl-3 type-body text-foreground transition-state", controlHeight.default),
3298
+ children: [/* @__PURE__ */ jsx(SelectValue, { className: "tabular-nums" }), /* @__PURE__ */ jsx(ChevronDown, {
3299
+ "aria-hidden": true,
3300
+ className: "size-4 text-muted-foreground"
3301
+ })]
3302
+ }), /* @__PURE__ */ jsx(Popover$1, {
3303
+ placement: "bottom start",
3304
+ offset: 4,
3305
+ className: cn("layer-overlay min-w-(--trigger-width) p-1", overlaySurface),
3306
+ children: /* @__PURE__ */ jsx(ListBox, {
3307
+ className: "outline-none",
3308
+ children: rates.map((r) => /* @__PURE__ */ jsx(ListBoxItem, {
3309
+ id: String(r),
3310
+ textValue: `${r}×`,
3311
+ className: "flex min-h-(--control-h-sm) cursor-pointer items-center justify-between gap-3 rounded-control px-2 type-body-sm tabular-nums outline-none focus:bg-muted selected:font-medium",
3312
+ children: ({ isSelected }) => /* @__PURE__ */ jsxs(Fragment, { children: [`${r}×`, isSelected && /* @__PURE__ */ jsx(Check, {
3313
+ "aria-hidden": true,
3314
+ className: "size-4"
3315
+ })] })
3316
+ }, r))
3317
+ })
3318
+ })]
3220
3319
  });
3221
3320
  }
3222
3321
  /**
@@ -5660,6 +5759,23 @@ function resamplePeaks(peaks, buckets) {
5660
5759
  };
5661
5760
  }
5662
5761
  /**
5762
+ * How much to scale peaks so the loud parts fill the height: one over the `percentile` of the slices'
5763
+ * largest magnitudes, at most `maxGain` and never below 1. A percentile rather than the loudest slice,
5764
+ * so one thump or click on a quiet recording (a dropped camcorder, a tape splice) does not keep the rest
5765
+ * flat; a ceiling, so a recording that is only hiss is not drawn as if it were speech.
5766
+ */
5767
+ function peakGain(pair, { percentile = .995, maxGain = 16 } = {}) {
5768
+ const n = Math.min(pair.min.length, pair.max.length);
5769
+ if (n === 0) return 1;
5770
+ const stride = Math.max(1, Math.floor(n / 5e4));
5771
+ const loud = [];
5772
+ for (let i = 0; i < n; i += stride) loud.push(Math.max(Math.abs(pair.min[i]), Math.abs(pair.max[i])));
5773
+ loud.sort((a, b) => a - b);
5774
+ const top = loud[Math.min(loud.length - 1, Math.floor(percentile * (loud.length - 1)))];
5775
+ if (!(top > 0)) return 1;
5776
+ return Math.min(Math.max(1 / top, 1), maxGain);
5777
+ }
5778
+ /**
5663
5779
  * Reduces decoded audio to `buckets` peaks over all channels, in chunks, calling `progress` with
5664
5780
  * the buckets done and awaiting between chunks so the page stays responsive and `signal` can stop it.
5665
5781
  */
@@ -5760,7 +5876,7 @@ async function defaultDecode(data) {
5760
5876
  var clamp$2 = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
5761
5877
  var clock = (t) => format.runningTime(t);
5762
5878
  /** An audio waveform with marks, spans and a playhead: one slider you click, drag or key to seek, zoom, and a range to select. */
5763
- function Waveform({ label, peaks, source, duration: given, time, onSeek, marks = [], spans = [], underlay, range: controlledRange, onRangeChange, step = 5, bigStep = 30, defaultView, buckets = 2e3, decode = defaultDecode, words = WORDS, disabled, className }) {
5879
+ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks = [], spans = [], underlay, range: controlledRange, onRangeChange, step = 5, bigStep = 30, defaultView, buckets = 2e3, normalise = false, decode = defaultDecode, words = WORDS, disabled, className }) {
5764
5880
  const work = useClientWork(async ({ signal, progress }) => {
5765
5881
  const data = typeof source === "string" ? await (await fetch(source, { signal })).arrayBuffer() : await source.arrayBuffer();
5766
5882
  progress(0, buckets + 2);
@@ -5789,6 +5905,17 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
5789
5905
  const pair = React.useMemo(() => peaks === void 0 ? null : toPeakPair(peaks), [peaks]) ?? (work.phase === "finished" ? work.result.pair : null);
5790
5906
  const duration = given ?? (work.phase === "finished" ? work.result.duration : 0);
5791
5907
  const ready = pair !== null && duration > 0;
5908
+ const percentile = typeof normalise === "object" ? normalise.percentile : void 0;
5909
+ const maxGain = typeof normalise === "object" ? normalise.maxGain : void 0;
5910
+ const gain = React.useMemo(() => normalise && pair ? peakGain(pair, {
5911
+ percentile,
5912
+ maxGain
5913
+ }) : 1, [
5914
+ normalise,
5915
+ pair,
5916
+ percentile,
5917
+ maxGain
5918
+ ]);
5792
5919
  const [view, setView] = React.useState(defaultView ? [defaultView[0], defaultView[1]] : null);
5793
5920
  const [v0, v1] = view ? clampView(view[0], view[1] - view[0], duration || 1) : [0, duration];
5794
5921
  const zoomed = ready && v1 - v0 < duration - 1e-6;
@@ -5960,8 +6087,8 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
5960
6087
  for (let x = 0; x < width; x += column) {
5961
6088
  const [lo, hi] = peaksBetween(pair, (v0 + x / width * (v1 - v0)) / duration, (v0 + (x + column) / width * (v1 - v0)) / duration);
5962
6089
  if (!Number.isFinite(lo)) continue;
5963
- const top = 50 - clamp$2(hi, -1, 1) * 48;
5964
- const bottom = 50 - clamp$2(lo, -1, 1) * 48;
6090
+ const top = 50 - clamp$2(hi * gain, -1, 1) * 48;
6091
+ const bottom = 50 - clamp$2(lo * gain, -1, 1) * 48;
5965
6092
  d += `M${x + .5} ${top.toFixed(1)}V${Math.max(bottom, top + 1).toFixed(1)}`;
5966
6093
  }
5967
6094
  return d;
@@ -5970,7 +6097,8 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
5970
6097
  width,
5971
6098
  v0,
5972
6099
  v1,
5973
- duration
6100
+ duration,
6101
+ gain
5974
6102
  ]);
5975
6103
  const clipId = React.useId();
5976
6104
  const px = (t) => (t - v0) / span * width;
@@ -5978,7 +6106,8 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
5978
6106
  const thin = visibleMarks.length > width / 8;
5979
6107
  const listedMarks = marks.filter((m) => m.label && (m.listed ?? m.kind !== "beat"));
5980
6108
  const counts = marks.reduce((c, m) => (c[m.kind ?? "mark"] = (c[m.kind ?? "mark"] ?? 0) + 1, c), {});
5981
- const summary = ready ? `${clock(duration)} long${Object.keys(counts).length ? `, ${Object.entries(counts).map(([k, n]) => `${n} ${k}${n === 1 ? "" : "s"}`).join(", ")}` : ""}${spans.length ? `, ${spans.length} span${spans.length === 1 ? "" : "s"}` : ""}${zoomed ? `, showing ${clock(v0)} to ${clock(v1)}` : ""}${range ? `, range ${clock(range[0])} to ${clock(range[1])}` : ""}` : "";
6109
+ const louder = gain >= 1.1 ? `Shown ${gain < 10 ? gain.toFixed(1).replace(/\.0$/, "") : Math.round(gain)}× louder` : null;
6110
+ const summary = ready ? `${clock(duration)} long${Object.keys(counts).length ? `, ${Object.entries(counts).map(([k, n]) => `${n} ${k}${n === 1 ? "" : "s"}`).join(", ")}` : ""}${spans.length ? `, ${spans.length} span${spans.length === 1 ? "" : "s"}` : ""}${zoomed ? `, showing ${clock(v0)} to ${clock(v1)}` : ""}${range ? `, range ${clock(range[0])} to ${clock(range[1])}` : ""}${louder ? `, ${louder.toLowerCase()}` : ""}` : "";
5982
6111
  const summaryId = React.useId();
5983
6112
  return /* @__PURE__ */ jsxs("div", {
5984
6113
  role: "group",
@@ -6140,6 +6269,11 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
6140
6269
  })
6141
6270
  ]
6142
6271
  }),
6272
+ ready && louder && /* @__PURE__ */ jsx("p", {
6273
+ "aria-hidden": true,
6274
+ className: "justify-self-end type-caption text-muted-foreground",
6275
+ children: louder
6276
+ }),
6143
6277
  /* @__PURE__ */ jsxs(VisuallyHidden, { children: [
6144
6278
  /* @__PURE__ */ jsx("p", {
6145
6279
  id: summaryId,
@@ -18014,6 +18148,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
18014
18148
  ]
18015
18149
  });
18016
18150
  }
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 };
18151
+ 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, FilmStrip, 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, frameAt, 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, peakGain, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickEvenly, 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 };
18018
18152
 
18019
18153
  //# sourceMappingURL=index.js.map