strata-react 1.0.7 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import { C as readErrorBody, E as typeSteps, S as fieldErrorsOf, T as cn, _ as Textarea, a as toLoad, b as describeActionError, c as ColorSchemeChoice, d as useColorScheme, f as useSystemColorScheme, g as NativeSelect, h as Input, i as staleOf, l as ThemeProvider, m as Field, n as createQueryClient, o as useLoad, p as ChoiceGroup, r as fetchJson, s as COLOR_SCHEME_STORAGE_KEY, t as StrataQueryProvider, u as colorSchemeScript, v as useFieldControl, w as Tooltip, x as describeHttpError, y as HttpError } from "./query-CXlmWmrY.js";
2
2
  import * as React from "react";
3
- import { Autocomplete, Button as Button$1, Checkbox as Checkbox$1, Dialog as Dialog$1, DialogTrigger, Disclosure as Disclosure$1, DisclosurePanel, DropZone, FileTrigger, Header, Heading, I18nProvider, Input as Input$1, Keyboard, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, NumberField as NumberField$1, Popover as Popover$1, SearchField, Separator, Slider as Slider$1, SliderOutput, SliderThumb, SliderTrack, SubmenuTrigger, Switch as Switch$1, Tab, TabList, TabPanel, Tabs as Tabs$1, Text, ToggleButton, ToggleButtonGroup, Toolbar as Toolbar$1, UNSTABLE_Toast, UNSTABLE_ToastContent, UNSTABLE_ToastQueue, UNSTABLE_ToastRegion, useFilter } from "react-aria-components";
3
+ import { Autocomplete, Button as Button$1, Checkbox as Checkbox$1, Dialog as Dialog$1, DialogTrigger, Disclosure as Disclosure$1, DisclosurePanel, DropIndicator, DropZone, FileTrigger, GridList, GridListItem, Header, Heading, I18nProvider, Input as Input$1, Keyboard, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, NumberField as NumberField$1, Popover as Popover$1, SearchField, Separator, Slider as Slider$1, SliderOutput, SliderThumb, SliderTrack, SubmenuTrigger, Switch as Switch$1, Tab, TabList, TabPanel, Tabs as Tabs$1, Text, ToggleButton, ToggleButtonGroup, Toolbar as Toolbar$1, UNSTABLE_Toast, UNSTABLE_ToastContent, UNSTABLE_ToastQueue, UNSTABLE_ToastRegion, useDragAndDrop, useFilter } from "react-aria-components";
4
4
  import { cva } from "class-variance-authority";
5
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
- import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronRight, CircleAlert, CircleCheck, FileQuestion, History, ImageOff, Info, Loader, LoaderCircle, Maximize, Minimize, Minus, RotateCcw, Scan, Search, Trash2, TriangleAlert, Upload, X, ZoomIn, ZoomOut } from "lucide-react";
6
+ import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronRight, CircleAlert, CircleCheck, FileQuestion, GripVertical, History, ImageOff, Info, Loader, LoaderCircle, Maximize, Maximize2, Minimize, Minus, Pause, Play, RotateCcw, Scan, Search, SkipBack, SkipForward, Square, StepBack, StepForward, Trash2, TriangleAlert, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
7
7
  import { Link, NavLink, useSearchParams } from "react-router";
8
8
  import { createSortedRowModel, flexRender, rowSortingFeature, tableFeatures, useTable } from "@tanstack/react-table";
9
9
  import { useVirtualizer } from "@tanstack/react-virtual";
10
+ import { VisuallyHidden, mergeProps, useFocusRing, useSlider, useSliderThumb } from "react-aria";
11
+ import { useSliderState } from "react-stately";
10
12
  import { hashKey, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
11
13
  import pixelmatch from "pixelmatch";
12
14
  // src/lib/format.ts
@@ -138,6 +140,22 @@ function createFormat(locale, options = {}) {
138
140
  const [h, m] = [Math.floor(s / 3600), Math.floor(s % 3600 / 60)];
139
141
  return h > 0 ? `${h}:${two(m)}:${two(s % 60)}` : `${m}:${two(s % 60)}`;
140
142
  },
143
+ /**
144
+ * A position in media as an editor shows it, to a chosen precision: "4:05" (seconds), "4:05.250"
145
+ * (`"ms"`), or "4:05:07" (`"frames"` at `fps`, the last part the frame). Hours appear only from
146
+ * one hour. Floors, never rounds up, so a time never reads ahead of the picture. Unknown
147
+ * (null, negative, not finite) prints the placeholder. Set it in `tabular-nums`.
148
+ */
149
+ timecode: (seconds, { precision = "seconds", fps = 30 } = {}) => {
150
+ if (seconds == null || !Number.isFinite(seconds) || seconds < 0) return missing;
151
+ const whole = Math.floor(seconds);
152
+ const two = (n) => String(n).padStart(2, "0");
153
+ const [h, m] = [Math.floor(whole / 3600), Math.floor(whole % 3600 / 60)];
154
+ const base = h > 0 ? `${h}:${two(m)}:${two(whole % 60)}` : `${m}:${two(whole % 60)}`;
155
+ if (precision === "ms") return `${base}.${String(Math.min(Math.floor((seconds - whole) * 1e3 + 1e-6), 999)).padStart(3, "0")}`;
156
+ if (precision === "frames") return `${base}:${two(Math.min(Math.floor((seconds - whole) * fps + 1e-6), Math.ceil(fps) - 1))}`;
157
+ return base;
158
+ },
141
159
  /** What a missing value prints as: an en dash unless `createFormat`'s `missing` says otherwise. */
142
160
  missing,
143
161
  /** A time of day: `format.clock(at)` is "06:05". */
@@ -2874,6 +2892,1193 @@ function TableSkeleton({ rows = 4, columns = 5 }) {
2874
2892
  }, r))]
2875
2893
  });
2876
2894
  }
2895
+ // src/components/media.tsx
2896
+ var clamp$1 = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
2897
+ var timecode = (t, { precision, fps }) => format.timecode(t, {
2898
+ precision,
2899
+ fps
2900
+ });
2901
+ /** The current and total time, in `tabular-nums`, as `<time>` elements. */
2902
+ function TimeReadout({ time, duration, precision = "seconds", fps = 30, className }) {
2903
+ const total = duration === null ? null : timecode(duration, {
2904
+ precision,
2905
+ fps
2906
+ });
2907
+ return /* @__PURE__ */ jsxs("span", {
2908
+ className: cn("inline-flex items-baseline gap-1 type-body-sm tabular-nums", className),
2909
+ children: [
2910
+ /* @__PURE__ */ jsx("time", {
2911
+ dateTime: `PT${Math.floor(time)}S`,
2912
+ "aria-label": `Position ${timecode(time, {
2913
+ precision,
2914
+ fps
2915
+ })}`,
2916
+ className: "text-foreground",
2917
+ style: total ? { minWidth: `${total.length}ch` } : void 0,
2918
+ children: timecode(time, {
2919
+ precision,
2920
+ fps
2921
+ })
2922
+ }),
2923
+ /* @__PURE__ */ jsx("span", {
2924
+ "aria-hidden": true,
2925
+ className: "text-muted-foreground",
2926
+ children: "/"
2927
+ }),
2928
+ /* @__PURE__ */ jsx("time", {
2929
+ dateTime: duration === null ? void 0 : `PT${Math.floor(duration)}S`,
2930
+ "aria-label": `Length ${total ?? format.missing}`,
2931
+ className: "text-muted-foreground",
2932
+ children: total ?? format.missing
2933
+ })
2934
+ ]
2935
+ });
2936
+ }
2937
+ /** A seek bar: dragged, clicked and moved by keys (arrows `step`, Page keys `bigStep`, Home and End), with its time as the accessible value. */
2938
+ function SeekBar({ time, duration, onSeek, marks = [], buffered, step = 5, bigStep = 30, label = "Seek", precision = "seconds", fps = 30, disabled, className }) {
2939
+ const track = React.useRef(null);
2940
+ const input = React.useRef(null);
2941
+ const frac = duration > 0 ? clamp$1(time / duration, 0, 1) : 0;
2942
+ const seekTo = (t) => onSeek(clamp$1(t, 0, duration));
2943
+ const timeText = React.useMemo(() => {
2944
+ const say = (t) => timecode(t, {
2945
+ precision,
2946
+ fps
2947
+ });
2948
+ return {
2949
+ format: say,
2950
+ formatRange: (a, b) => `${say(a)} to ${say(b)}`,
2951
+ resolvedOptions: () => ({ locale: "en-US" })
2952
+ };
2953
+ }, [precision, fps]);
2954
+ const fine = precision === "frames" ? 1 / fps : precision === "ms" ? .001 : .01;
2955
+ const state = useSliderState({
2956
+ minValue: 0,
2957
+ maxValue: Math.max(duration, fine),
2958
+ step: fine,
2959
+ value: [clamp$1(time, 0, duration)],
2960
+ onChange: ([t]) => seekTo(t),
2961
+ numberFormatter: timeText,
2962
+ isDisabled: disabled
2963
+ });
2964
+ const { groupProps, trackProps } = useSlider({
2965
+ "aria-label": label,
2966
+ isDisabled: disabled
2967
+ }, state, track);
2968
+ const { thumbProps, inputProps } = useSliderThumb({
2969
+ index: 0,
2970
+ trackRef: track,
2971
+ inputRef: input,
2972
+ "aria-label": label,
2973
+ isDisabled: disabled
2974
+ }, state);
2975
+ const { focusProps, isFocusVisible } = useFocusRing();
2976
+ const keys = {
2977
+ ArrowLeft: -step,
2978
+ ArrowDown: -step,
2979
+ ArrowRight: step,
2980
+ ArrowUp: step,
2981
+ PageDown: -bigStep,
2982
+ PageUp: bigStep
2983
+ };
2984
+ const onKeyDownCapture = (e) => {
2985
+ if (disabled) return;
2986
+ if (e.key in keys) seekTo(time + keys[e.key]);
2987
+ else if (e.key === "Home") seekTo(0);
2988
+ else if (e.key === "End") seekTo(duration);
2989
+ else return;
2990
+ e.preventDefault();
2991
+ e.stopPropagation();
2992
+ };
2993
+ return /* @__PURE__ */ jsx("div", {
2994
+ ...groupProps,
2995
+ className: cn("relative flex h-(--control-h) min-w-0 flex-1 items-center", disabled && "cursor-not-allowed opacity-50", className),
2996
+ children: /* @__PURE__ */ jsxs("div", {
2997
+ ...trackProps,
2998
+ ref: track,
2999
+ className: cn("relative flex h-full w-full cursor-pointer touch-none items-center", disabled && "cursor-not-allowed"),
3000
+ children: [
3001
+ /* @__PURE__ */ jsx("span", {
3002
+ "aria-hidden": true,
3003
+ className: "absolute inset-x-0 h-1.5 rounded-pill bg-muted"
3004
+ }),
3005
+ buffered !== void 0 && duration > 0 && /* @__PURE__ */ jsx("span", {
3006
+ "aria-hidden": true,
3007
+ className: "absolute left-0 h-1.5 rounded-pill bg-neutral-4",
3008
+ style: { width: `${clamp$1(buffered / duration, 0, 1) * 100}%` }
3009
+ }),
3010
+ /* @__PURE__ */ jsx("span", {
3011
+ "aria-hidden": true,
3012
+ className: "absolute left-0 h-1.5 rounded-pill bg-primary",
3013
+ style: { width: `${frac * 100}%` }
3014
+ }),
3015
+ duration > 0 && marks.map((m) => /* @__PURE__ */ jsx("button", {
3016
+ type: "button",
3017
+ tabIndex: -1,
3018
+ disabled,
3019
+ title: `${m.label}, ${timecode(m.time, {
3020
+ precision,
3021
+ fps
3022
+ })}`,
3023
+ "aria-label": `${m.label}, ${timecode(m.time, {
3024
+ precision,
3025
+ fps
3026
+ })}`,
3027
+ onPointerDown: (e) => e.stopPropagation(),
3028
+ onMouseDown: (e) => e.stopPropagation(),
3029
+ onClick: () => seekTo(m.time),
3030
+ className: "absolute top-1/2 h-3 w-1 -translate-y-1/2 cursor-pointer rounded-pill bg-foreground",
3031
+ style: { left: `${m.time / duration * 100}%` }
3032
+ }, `${m.time}-${m.label}`)),
3033
+ /* @__PURE__ */ jsx("div", {
3034
+ ...thumbProps,
3035
+ className: cn("absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-pill border-2 border-primary bg-background", isFocusVisible && "outline-2 outline-offset-2 outline-ring"),
3036
+ style: { left: `${frac * 100}%` },
3037
+ children: /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx("input", {
3038
+ ref: input,
3039
+ ...mergeProps(inputProps, focusProps),
3040
+ "aria-labelledby": void 0,
3041
+ onKeyDownCapture
3042
+ }) })
3043
+ })
3044
+ ]
3045
+ })
3046
+ });
3047
+ }
3048
+ /** The transport buttons for a player the app owns. Every control is a named icon button; the play button's name is "Play" or "Pause" from `playing`. Only the buttons whose handler is passed are drawn. */
3049
+ function Transport({ playing, onPlayPause, onStop, onToStart, onToEnd, onStepBack, onStepForward, stepUnit = "frame", children, className }) {
3050
+ return /* @__PURE__ */ jsxs(Toolbar, {
3051
+ label: "Playback",
3052
+ className: cn("gap-2", className),
3053
+ children: [
3054
+ onToStart && /* @__PURE__ */ jsx(IconButton, {
3055
+ icon: SkipBack,
3056
+ label: "Go to start",
3057
+ hint: "Home",
3058
+ onClick: onToStart
3059
+ }),
3060
+ onStepBack && /* @__PURE__ */ jsx(IconButton, {
3061
+ icon: StepBack,
3062
+ label: `Back one ${stepUnit}`,
3063
+ hint: "←",
3064
+ onClick: onStepBack
3065
+ }),
3066
+ /* @__PURE__ */ jsx(IconButton, {
3067
+ icon: playing ? Pause : Play,
3068
+ label: playing ? "Pause" : "Play",
3069
+ hint: "Space",
3070
+ variant: "outline",
3071
+ onClick: onPlayPause
3072
+ }),
3073
+ onStop && /* @__PURE__ */ jsx(IconButton, {
3074
+ icon: Square,
3075
+ label: "Stop",
3076
+ onClick: onStop
3077
+ }),
3078
+ onStepForward && /* @__PURE__ */ jsx(IconButton, {
3079
+ icon: StepForward,
3080
+ label: `Forward one ${stepUnit}`,
3081
+ hint: "→",
3082
+ onClick: onStepForward
3083
+ }),
3084
+ onToEnd && /* @__PURE__ */ jsx(IconButton, {
3085
+ icon: SkipForward,
3086
+ label: "Go to end",
3087
+ hint: "End",
3088
+ onClick: onToEnd
3089
+ }),
3090
+ children
3091
+ ]
3092
+ });
3093
+ }
3094
+ /** 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. */
3095
+ function VolumeControl({ volume, onVolumeChange, max = 100, disabled, className }) {
3096
+ const last = React.useRef(volume > 0 ? volume : 100);
3097
+ if (volume > 0) last.current = volume;
3098
+ const muted = volume === 0;
3099
+ return /* @__PURE__ */ jsxs("div", {
3100
+ className: cn("flex items-center gap-2", className),
3101
+ children: [/* @__PURE__ */ jsx(IconButton, {
3102
+ icon: muted ? VolumeX : Volume2,
3103
+ label: muted ? "Unmute" : "Mute",
3104
+ hint: "M",
3105
+ disabled,
3106
+ onClick: () => onVolumeChange(muted ? last.current : 0)
3107
+ }), /* @__PURE__ */ jsx(Slider, {
3108
+ "aria-label": "Volume",
3109
+ value: volume,
3110
+ onChange: onVolumeChange,
3111
+ min: 0,
3112
+ max,
3113
+ unit: "%",
3114
+ disabled,
3115
+ className: "w-40"
3116
+ })]
3117
+ });
3118
+ }
3119
+ /** A choice of playback speed ("0.5×", "1×", "1.5×") on a native select, named "Playback speed". */
3120
+ function RateChoice({ rate, onRateChange, rates = [
3121
+ .5,
3122
+ 1,
3123
+ 1.25,
3124
+ 1.5,
3125
+ 2
3126
+ ], className }) {
3127
+ return /* @__PURE__ */ jsx(NativeSelect, {
3128
+ "aria-label": "Playback speed",
3129
+ value: String(rate),
3130
+ onChange: (e) => onRateChange(Number(e.target.value)),
3131
+ className: cn("w-auto", className),
3132
+ children: rates.map((r) => /* @__PURE__ */ jsx("option", {
3133
+ value: String(r),
3134
+ children: `${r}×`
3135
+ }, r))
3136
+ });
3137
+ }
3138
+ /**
3139
+ * The shortcuts a player takes, as one list for `useHotkeys` and `KeysLegend`: Space and K play
3140
+ * or pause, J and L go back or forward `jump` seconds, the arrows by `frame` seconds, Home and End
3141
+ * to the ends, M mutes. Pass the player's actions; the labels are the legend's words.
3142
+ */
3143
+ function transportShortcuts({ toggle, seek, time, duration, frame = 1 / 30, jump = 1, toggleMute }) {
3144
+ const to = (t) => () => seek(clamp$1(t, 0, duration));
3145
+ return [
3146
+ {
3147
+ keys: [" ", "k"],
3148
+ label: "Play or pause",
3149
+ run: toggle
3150
+ },
3151
+ {
3152
+ keys: ["j"],
3153
+ label: `Back ${jump} s`,
3154
+ run: to(time - jump),
3155
+ repeat: true
3156
+ },
3157
+ {
3158
+ keys: ["l"],
3159
+ label: `Forward ${jump} s`,
3160
+ run: to(time + jump),
3161
+ repeat: true
3162
+ },
3163
+ {
3164
+ keys: ["ArrowLeft"],
3165
+ label: "Back one frame",
3166
+ run: to(time - frame),
3167
+ repeat: true
3168
+ },
3169
+ {
3170
+ keys: ["ArrowRight"],
3171
+ label: "Forward one frame",
3172
+ run: to(time + frame),
3173
+ repeat: true
3174
+ },
3175
+ {
3176
+ keys: ["Home"],
3177
+ label: "Go to start",
3178
+ run: to(0)
3179
+ },
3180
+ {
3181
+ keys: ["End"],
3182
+ label: "Go to end",
3183
+ run: to(duration)
3184
+ },
3185
+ ...toggleMute ? [{
3186
+ keys: ["m"],
3187
+ label: "Mute",
3188
+ run: toggleMute
3189
+ }] : []
3190
+ ];
3191
+ }
3192
+ /** A frame that fits content of an aspect ratio into the pane, letterboxed on the sunken surface role (light and dark both), with room for the app's overlays. */
3193
+ function MediaStage({ aspect, children, label, className }) {
3194
+ const outer = React.useRef(null);
3195
+ const [box, setBox] = React.useState(null);
3196
+ const ratio = typeof aspect === "number" ? aspect : (() => {
3197
+ const [w, h] = aspect.split("/").map(Number);
3198
+ return w / h;
3199
+ })();
3200
+ React.useEffect(() => {
3201
+ const el = outer.current;
3202
+ if (!el) return;
3203
+ const read = () => setBox({
3204
+ w: el.clientWidth,
3205
+ h: el.clientHeight
3206
+ });
3207
+ read();
3208
+ const ro = new ResizeObserver(read);
3209
+ ro.observe(el);
3210
+ return () => ro.disconnect();
3211
+ }, []);
3212
+ const fit = box && box.w > 0 && box.h > 0 ? box.w / box.h > ratio ? {
3213
+ w: box.h * ratio,
3214
+ h: box.h
3215
+ } : {
3216
+ w: box.w,
3217
+ h: box.w / ratio
3218
+ } : null;
3219
+ return /* @__PURE__ */ jsx("div", {
3220
+ ref: outer,
3221
+ role: "group",
3222
+ "aria-label": label,
3223
+ className: cn("grid min-h-0 min-w-0 place-items-center overflow-hidden bg-surface-sunken", className),
3224
+ children: /* @__PURE__ */ jsx("div", {
3225
+ className: "relative overflow-hidden bg-background",
3226
+ style: fit ? {
3227
+ width: fit.w,
3228
+ height: fit.h
3229
+ } : {
3230
+ width: "100%",
3231
+ aspectRatio: String(ratio)
3232
+ },
3233
+ children
3234
+ })
3235
+ });
3236
+ }
3237
+ /** Guides over a stage: action-safe and title-safe frames (90% and 80%), a centre cross and a rule-of-thirds grid. Drawn as two strokes (light over dark) so they read on any picture. */
3238
+ function StageGuides({ safe, thirds, centre, className }) {
3239
+ const lines = [];
3240
+ if (thirds) lines.push([
3241
+ 100 / 3,
3242
+ 0,
3243
+ 100 / 3,
3244
+ 100
3245
+ ], [
3246
+ 200 / 3,
3247
+ 0,
3248
+ 200 / 3,
3249
+ 100
3250
+ ], [
3251
+ 0,
3252
+ 100 / 3,
3253
+ 100,
3254
+ 100 / 3
3255
+ ], [
3256
+ 0,
3257
+ 200 / 3,
3258
+ 100,
3259
+ 200 / 3
3260
+ ]);
3261
+ if (centre) lines.push([
3262
+ 50,
3263
+ 46,
3264
+ 50,
3265
+ 54
3266
+ ], [
3267
+ 46,
3268
+ 50,
3269
+ 54,
3270
+ 50
3271
+ ]);
3272
+ const rects = safe ? [5, 10] : [];
3273
+ const draw = (cls, w) => /* @__PURE__ */ jsxs("g", {
3274
+ className: cls,
3275
+ strokeWidth: w,
3276
+ fill: "none",
3277
+ vectorEffect: "non-scaling-stroke",
3278
+ children: [lines.map((l, i) => /* @__PURE__ */ jsx("line", {
3279
+ x1: l[0],
3280
+ y1: l[1],
3281
+ x2: l[2],
3282
+ y2: l[3],
3283
+ vectorEffect: "non-scaling-stroke"
3284
+ }, i)), rects.map((m) => /* @__PURE__ */ jsx("rect", {
3285
+ x: m,
3286
+ y: m,
3287
+ width: 100 - 2 * m,
3288
+ height: 100 - 2 * m,
3289
+ vectorEffect: "non-scaling-stroke"
3290
+ }, m))]
3291
+ });
3292
+ return /* @__PURE__ */ jsxs("svg", {
3293
+ "aria-hidden": true,
3294
+ viewBox: "0 0 100 100",
3295
+ preserveAspectRatio: "none",
3296
+ className: cn("pointer-events-none absolute inset-0 size-full", className),
3297
+ children: [draw("stroke-foreground", 3), draw("stroke-background", 1)]
3298
+ });
3299
+ }
3300
+ // src/lib/timeline.ts
3301
+ /** Steps a person would write on a scale, in seconds: 1, 2, 5 and 10 × 10ⁿ below a minute, then 15 s, 30 s, minutes, quarter hours, hours, days. ux-research components.md §3.8: ticks land on values people would write. */
3302
+ var STEPS = [
3303
+ .01,
3304
+ .02,
3305
+ .05,
3306
+ .1,
3307
+ .2,
3308
+ .5,
3309
+ 1,
3310
+ 2,
3311
+ 5,
3312
+ 10,
3313
+ 15,
3314
+ 30,
3315
+ 60,
3316
+ 120,
3317
+ 300,
3318
+ 600,
3319
+ 900,
3320
+ 1800,
3321
+ 3600,
3322
+ 7200,
3323
+ 14400,
3324
+ 21600,
3325
+ 43200,
3326
+ 86400
3327
+ ];
3328
+ /** The smallest step whose ticks are at least `minGapPx` apart at this zoom, so labels thin out instead of colliding. */
3329
+ function tickStep(pxPerUnit, minGapPx = 80) {
3330
+ return STEPS.find((s) => s * pxPerUnit >= minGapPx) ?? STEPS[STEPS.length - 1];
3331
+ }
3332
+ /** Tick times from `from` to `to` inclusive, on multiples of `step`. */
3333
+ function ticksBetween(from, to, step) {
3334
+ const out = [];
3335
+ const first = Math.ceil(from / step - 1e-9);
3336
+ for (let i = first; i * step <= to + 1e-9; i++) out.push(Math.round(i * step * 1e6) / 1e6 || 0);
3337
+ return out;
3338
+ }
3339
+ /** A tick's label: m:ss, h:mm:ss, with tenths or hundredths when the step is under a second. */
3340
+ function tickLabel(time, step) {
3341
+ const decimals = step < .1 ? 2 : step < 1 ? 1 : 0;
3342
+ const whole = Math.floor(time + 1e-9);
3343
+ const h = Math.floor(whole / 3600);
3344
+ const m = Math.floor(whole % 3600 / 60);
3345
+ const s = whole % 60;
3346
+ const two = (n) => String(n).padStart(2, "0");
3347
+ const base = h > 0 ? `${h}:${two(m)}:${two(s)}` : `${m}:${two(s)}`;
3348
+ return decimals ? `${base}.${String(Math.round((time - whole) * 10 ** decimals)).padStart(decimals, "0")}` : base;
3349
+ }
3350
+ function clamp(value, min, max) {
3351
+ return Math.min(Math.max(value, min), max);
3352
+ }
3353
+ /** The point to snap `time` to: the nearest of `points` within `thresholdPx` at this zoom, or `null`. */
3354
+ function snapTo(time, points, pxPerUnit, thresholdPx = 8) {
3355
+ let best = null;
3356
+ for (const p of points) if (Math.abs(p - time) * pxPerUnit <= thresholdPx && (best === null || Math.abs(p - time) < Math.abs(best - time))) best = p;
3357
+ return best === null ? null : {
3358
+ time: best,
3359
+ point: best
3360
+ };
3361
+ }
3362
+ /** Round away float noise from adding steps (0.1 + 0.2). */
3363
+ var tidy = (n) => Math.round(n * 1e6) / 1e6;
3364
+ // src/components/timeline.tsx
3365
+ var HEADER_W = "w-40";
3366
+ var EDGE_PX = 8;
3367
+ var DRAG_THRESHOLD = 3;
3368
+ var defaultFormat = (t) => tickLabel(t, 1);
3369
+ /** Zoom state for a timeline: `zoomIn`, `zoomOut`, and `fit` to a viewport width. Pass `zoom` and `setZoom` as the timeline's `zoom` and `onZoomChange`. */
3370
+ function useTimelineZoom({ initial = 20, min = .5, max = 400 } = {}) {
3371
+ const [zoom, set] = React.useState(initial);
3372
+ const setZoom = React.useCallback((z) => set(clamp(z, min, max)), [min, max]);
3373
+ return {
3374
+ zoom,
3375
+ setZoom,
3376
+ zoomIn: () => setZoom(zoom * 1.5),
3377
+ zoomOut: () => setZoom(zoom / 1.5),
3378
+ /** Zoom so `duration` fills `viewportWidth` pixels. */
3379
+ fit: (viewportWidth, duration) => setZoom(viewportWidth / Math.max(duration, 1e-6))
3380
+ };
3381
+ }
3382
+ /** Zoom in, zoom out and fit, as named icon buttons for a timeline's toolbar. */
3383
+ function TimelineZoomControls({ zoom }) {
3384
+ return /* @__PURE__ */ jsxs("div", {
3385
+ className: "flex items-center gap-1",
3386
+ children: [
3387
+ /* @__PURE__ */ jsx(IconButton, {
3388
+ icon: ZoomOut,
3389
+ label: "Zoom out",
3390
+ hint: "-",
3391
+ onClick: zoom.zoomOut
3392
+ }),
3393
+ /* @__PURE__ */ jsx(IconButton, {
3394
+ icon: ZoomIn,
3395
+ label: "Zoom in",
3396
+ hint: "+",
3397
+ onClick: zoom.zoomIn
3398
+ }),
3399
+ /* @__PURE__ */ jsx(IconButton, {
3400
+ icon: Maximize2,
3401
+ label: "Fit to view",
3402
+ hint: "0",
3403
+ onClick: zoom.fit
3404
+ })
3405
+ ]
3406
+ });
3407
+ }
3408
+ /** A rule that refuses an item overlapping another in its lane, for `validate`: names the item in the way. */
3409
+ function noOverlap(items) {
3410
+ return (id, next) => {
3411
+ const me = items.find((i) => i.id === id);
3412
+ const other = items.find((i) => i.id !== id && i.lane === next.lane && i.start < next.start + next.length - 1e-9 && next.start < i.start + i.length - 1e-9);
3413
+ return other ? `${me?.label ?? "This"} would overlap ${other.label}.` : null;
3414
+ };
3415
+ }
3416
+ /** Items placed on a zoomable time axis in lanes, with a current-time rule and markers. Reports every move, trim, selection and time change; the app applies them. Keyboard-complete, and only the items near the view are rendered. */
3417
+ function Timeline({ label, lanes, items, from = 0, to, zoom, onZoomChange, position, onPositionChange, follow, markers = [], selectedIds, onSelect, onItemChange, onDelete, validate, snapPoints = [], snap = true, step = 1, minLength, renderItem, formatTime = defaultFormat, empty, className }) {
3418
+ const min = minLength ?? step;
3419
+ const scroller = React.useRef(null);
3420
+ const laneRefs = React.useRef(/* @__PURE__ */ new Map());
3421
+ const [view, setView] = React.useState({
3422
+ left: 0,
3423
+ width: 640
3424
+ });
3425
+ const [drag, setDrag] = React.useState(null);
3426
+ const dragRef = React.useRef(null);
3427
+ const [focusId, setFocusId] = React.useState(null);
3428
+ const [said, setSaid] = React.useState("");
3429
+ const refocus = React.useRef(null);
3430
+ const selected = selectedIds ?? /* @__PURE__ */ new Set();
3431
+ const laneIndex = React.useMemo(() => new Map(lanes.map((l, i) => [l.id, i])), [lanes]);
3432
+ const laneLabel = (id) => lanes.find((l) => l.id === id)?.label ?? id;
3433
+ const width = Math.max((to - from) * zoom, 1);
3434
+ const x = (t) => (t - from) * zoom;
3435
+ React.useEffect(() => {
3436
+ const el = scroller.current;
3437
+ if (!el) return;
3438
+ const read = () => setView({
3439
+ left: el.scrollLeft,
3440
+ width: el.clientWidth || 640
3441
+ });
3442
+ read();
3443
+ const ro = new ResizeObserver(read);
3444
+ ro.observe(el);
3445
+ el.addEventListener("scroll", read, { passive: true });
3446
+ return () => {
3447
+ ro.disconnect();
3448
+ el.removeEventListener("scroll", read);
3449
+ };
3450
+ }, []);
3451
+ React.useEffect(() => {
3452
+ const el = scroller.current;
3453
+ if (!follow || position === void 0 || !el) return;
3454
+ const px = x(position);
3455
+ if (px < el.scrollLeft || px > el.scrollLeft + el.clientWidth - 24) el.scrollLeft = Math.max(px - el.clientWidth * .25, 0);
3456
+ }, [
3457
+ follow,
3458
+ position,
3459
+ zoom
3460
+ ]);
3461
+ React.useEffect(() => {
3462
+ const id = refocus.current;
3463
+ if (!id) return;
3464
+ refocus.current = null;
3465
+ const el = scroller.current?.querySelector(`[data-item="${CSS.escape(id)}"]`);
3466
+ if (el && document.activeElement !== el && (!document.activeElement || document.activeElement === document.body || !scroller.current?.contains(document.activeElement))) el.focus();
3467
+ }, [items]);
3468
+ const sorted = React.useMemo(() => {
3469
+ const byLane = /* @__PURE__ */ new Map();
3470
+ for (const l of lanes) byLane.set(l.id, []);
3471
+ for (const i of items) byLane.get(i.lane)?.push(i);
3472
+ for (const list of byLane.values()) list.sort((a, b) => a.start - b.start);
3473
+ return byLane;
3474
+ }, [lanes, items]);
3475
+ const snapTimes = React.useMemo(() => {
3476
+ const pts = [...snapPoints, ...markers.map((m) => m.time)];
3477
+ if (position !== void 0) pts.push(position);
3478
+ return pts;
3479
+ }, [
3480
+ snapPoints,
3481
+ markers,
3482
+ position
3483
+ ]);
3484
+ /** Apply a change: validate, report, and say it. Returns the refusal, if any. */
3485
+ const commit = (item, next) => {
3486
+ const reason = validate?.(item.id, next) ?? null;
3487
+ if (reason) {
3488
+ setSaid(reason);
3489
+ return reason;
3490
+ }
3491
+ refocus.current = item.id;
3492
+ onItemChange?.(item.id, next);
3493
+ const where = next.lane !== item.lane ? `, ${laneLabel(next.lane)}` : "";
3494
+ setSaid(next.start !== item.start && next.length === item.length ? `${item.label} moved to ${formatTime(next.start)}${where}.` : next.lane !== item.lane ? `${item.label} moved to ${laneLabel(next.lane)}.` : `${item.label} now ${formatTime(next.start)} to ${formatTime(next.start + next.length)}.`);
3495
+ return null;
3496
+ };
3497
+ const select = (id, add) => {
3498
+ const next = add ? selected.has(id) ? [...selected].filter((s) => s !== id) : [...selected, id] : [id];
3499
+ onSelect?.(next);
3500
+ };
3501
+ const focusItem = (id) => {
3502
+ setFocusId(id);
3503
+ requestAnimationFrame(() => scroller.current?.querySelector(`[data-item="${CSS.escape(id)}"]`)?.focus());
3504
+ scroller.current?.querySelector(`[data-item="${CSS.escape(id)}"]`)?.focus();
3505
+ const item = items.find((i) => i.id === id);
3506
+ if (item && scroller.current) {
3507
+ const el = scroller.current;
3508
+ if (x(item.start) < el.scrollLeft) el.scrollLeft = x(item.start) - 16;
3509
+ else if (x(item.start + item.length) > el.scrollLeft + el.clientWidth) el.scrollLeft = x(item.start + item.length) - el.clientWidth + 16;
3510
+ }
3511
+ };
3512
+ const onItemKeyDown = (e, item) => {
3513
+ const k = e.key;
3514
+ const big = e.shiftKey ? 10 : 1;
3515
+ const lane = sorted.get(item.lane) ?? [];
3516
+ const idx = lane.findIndex((i) => i.id === item.id);
3517
+ const handled = () => {
3518
+ e.preventDefault();
3519
+ e.stopPropagation();
3520
+ };
3521
+ if (e.ctrlKey || e.metaKey) {
3522
+ if (k === "ArrowLeft" || k === "ArrowRight") {
3523
+ handled();
3524
+ const dir = k === "ArrowLeft" ? -1 : 1;
3525
+ commit(item, {
3526
+ start: clamp(tidy(item.start + dir * step * big), from, to - item.length),
3527
+ length: item.length,
3528
+ lane: item.lane
3529
+ });
3530
+ } else if (k === "ArrowUp" || k === "ArrowDown") {
3531
+ handled();
3532
+ const target = lanes[(laneIndex.get(item.lane) ?? 0) + (k === "ArrowUp" ? -1 : 1)];
3533
+ if (target) commit(item, {
3534
+ start: item.start,
3535
+ length: item.length,
3536
+ lane: target.id
3537
+ });
3538
+ return;
3539
+ }
3540
+ if (k !== "Enter" && k !== " ") return;
3541
+ }
3542
+ if (e.altKey && (k === "ArrowLeft" || k === "ArrowRight")) {
3543
+ handled();
3544
+ const dir = k === "ArrowLeft" ? -1 : 1;
3545
+ if (e.shiftKey) {
3546
+ const start = clamp(tidy(item.start + dir * step), from, item.start + item.length - min);
3547
+ commit(item, {
3548
+ start,
3549
+ length: tidy(item.start + item.length - start),
3550
+ lane: item.lane
3551
+ });
3552
+ } else commit(item, {
3553
+ start: item.start,
3554
+ length: clamp(tidy(item.length + dir * step), min, to - item.start),
3555
+ lane: item.lane
3556
+ });
3557
+ return;
3558
+ }
3559
+ switch (k) {
3560
+ case "ArrowLeft":
3561
+ handled();
3562
+ if (lane[idx - 1]) focusItem(lane[idx - 1].id);
3563
+ break;
3564
+ case "ArrowRight":
3565
+ handled();
3566
+ if (lane[idx + 1]) focusItem(lane[idx + 1].id);
3567
+ break;
3568
+ case "ArrowUp":
3569
+ case "ArrowDown": {
3570
+ handled();
3571
+ const neighbour = lanes[(laneIndex.get(item.lane) ?? 0) + (k === "ArrowUp" ? -1 : 1)];
3572
+ const nearest = (neighbour ? sorted.get(neighbour.id) ?? [] : []).reduce((best, c) => !best || Math.abs(c.start - item.start) < Math.abs(best.start - item.start) ? c : best, null);
3573
+ if (nearest) focusItem(nearest.id);
3574
+ break;
3575
+ }
3576
+ case "Home":
3577
+ handled();
3578
+ if (lane[0]) focusItem(lane[0].id);
3579
+ break;
3580
+ case "End":
3581
+ handled();
3582
+ if (lane.length) focusItem(lane[lane.length - 1].id);
3583
+ break;
3584
+ case "Enter":
3585
+ case " ":
3586
+ handled();
3587
+ select(item.id, e.shiftKey || e.ctrlKey || e.metaKey);
3588
+ break;
3589
+ case "Delete":
3590
+ case "Backspace": if (selected.size && onDelete) {
3591
+ handled();
3592
+ onDelete([...selected]);
3593
+ }
3594
+ }
3595
+ };
3596
+ const begin = (e, item, mode) => {
3597
+ if (e.button !== 0) return;
3598
+ e.stopPropagation();
3599
+ e.currentTarget.setPointerCapture?.(e.pointerId);
3600
+ const d = {
3601
+ id: item.id,
3602
+ mode,
3603
+ originX: e.clientX,
3604
+ origin: item,
3605
+ next: {
3606
+ start: item.start,
3607
+ length: item.length,
3608
+ lane: item.lane
3609
+ },
3610
+ reason: null,
3611
+ guide: null,
3612
+ moved: false
3613
+ };
3614
+ dragRef.current = d;
3615
+ setDrag(d);
3616
+ };
3617
+ const laneAt = (clientY, fallback) => {
3618
+ for (const [id, el] of laneRefs.current) {
3619
+ const r = el.getBoundingClientRect();
3620
+ if (clientY >= r.top && clientY < r.bottom) return id;
3621
+ }
3622
+ return fallback;
3623
+ };
3624
+ const onPointerMove = (e) => {
3625
+ const d = dragRef.current;
3626
+ if (!d) return;
3627
+ const dx = e.clientX - d.originX;
3628
+ if (!d.moved && Math.abs(dx) < DRAG_THRESHOLD && d.mode !== "move") return;
3629
+ const dt = dx / zoom;
3630
+ const o = d.origin;
3631
+ let next = {
3632
+ start: o.start,
3633
+ length: o.length,
3634
+ lane: o.lane
3635
+ };
3636
+ let guide = null;
3637
+ const edges = [...snapTimes, ...items.filter((i) => i.id !== o.id).flatMap((i) => [i.start, i.start + i.length])];
3638
+ const snapped = (t) => {
3639
+ const s = snap ? snapTo(t, edges, zoom) : null;
3640
+ if (s) guide = s.point;
3641
+ return s ? s.time : t;
3642
+ };
3643
+ if (d.mode === "move") {
3644
+ let start = o.start + dt;
3645
+ const a = snap ? snapTo(start, edges, zoom) : null;
3646
+ const b = snap ? snapTo(start + o.length, edges, zoom) : null;
3647
+ if (a && (!b || Math.abs(a.time - start) <= Math.abs(b.time - (start + o.length)))) {
3648
+ start = a.time;
3649
+ guide = a.point;
3650
+ } else if (b) {
3651
+ start = b.time - o.length;
3652
+ guide = b.point;
3653
+ }
3654
+ next = {
3655
+ start: clamp(tidy(start), from, to - o.length),
3656
+ length: o.length,
3657
+ lane: laneAt(e.clientY, o.lane)
3658
+ };
3659
+ } else if (d.mode === "end") next = {
3660
+ start: o.start,
3661
+ length: clamp(tidy(snapped(o.start + o.length + dt) - o.start), min, to - o.start),
3662
+ lane: o.lane
3663
+ };
3664
+ else {
3665
+ const start = clamp(tidy(snapped(o.start + dt)), from, o.start + o.length - min);
3666
+ next = {
3667
+ start,
3668
+ length: tidy(o.start + o.length - start),
3669
+ lane: o.lane
3670
+ };
3671
+ }
3672
+ const moved = d.moved || Math.abs(dx) >= DRAG_THRESHOLD || next.lane !== o.lane;
3673
+ const updated = {
3674
+ ...d,
3675
+ next,
3676
+ guide,
3677
+ moved,
3678
+ reason: moved ? validate?.(o.id, next) ?? null : null
3679
+ };
3680
+ dragRef.current = updated;
3681
+ setDrag(updated);
3682
+ };
3683
+ const onPointerUp = (e) => {
3684
+ const d = dragRef.current;
3685
+ dragRef.current = null;
3686
+ setDrag(null);
3687
+ if (!d) return;
3688
+ e.currentTarget.releasePointerCapture?.(e.pointerId);
3689
+ if (!d.moved) {
3690
+ if (d.mode === "move") select(d.id, e.shiftKey || e.ctrlKey || e.metaKey);
3691
+ return;
3692
+ }
3693
+ if (d.reason) setSaid(d.reason);
3694
+ else commit(d.origin, d.next);
3695
+ };
3696
+ const stepSize = tickStep(zoom);
3697
+ const ticks = React.useMemo(() => ticksBetween(from, to, stepSize), [
3698
+ from,
3699
+ to,
3700
+ stepSize
3701
+ ]);
3702
+ const setPosition = (t) => onPositionChange?.(clamp(tidy(t), from, to));
3703
+ const scrubTrack = React.useRef(null);
3704
+ const scrubInput = React.useRef(null);
3705
+ const spokenTime = React.useMemo(() => ({
3706
+ format: formatTime,
3707
+ formatRange: (a, b) => `${formatTime(a)} to ${formatTime(b)}`,
3708
+ resolvedOptions: () => ({ locale: "en-US" })
3709
+ }), [formatTime]);
3710
+ const scrubState = useSliderState({
3711
+ minValue: from,
3712
+ maxValue: Math.max(to, from + 1e-9),
3713
+ step: .001,
3714
+ value: [clamp(position ?? from, from, to)],
3715
+ onChange: ([t]) => setPosition(t),
3716
+ numberFormatter: spokenTime,
3717
+ isDisabled: position === void 0 || !onPositionChange
3718
+ });
3719
+ const { trackProps: rulerProps } = useSlider({
3720
+ "aria-label": "Current time",
3721
+ isDisabled: position === void 0 || !onPositionChange
3722
+ }, scrubState, scrubTrack);
3723
+ const { thumbProps, inputProps } = useSliderThumb({
3724
+ index: 0,
3725
+ trackRef: scrubTrack,
3726
+ inputRef: scrubInput,
3727
+ "aria-label": "Current time",
3728
+ isDisabled: position === void 0 || !onPositionChange
3729
+ }, scrubState);
3730
+ const { focusProps, isFocusVisible } = useFocusRing();
3731
+ const onSliderKey = (e) => {
3732
+ if (position === void 0) return;
3733
+ const big = e.shiftKey ? 10 : 1;
3734
+ const moves = {
3735
+ ArrowLeft: -step * big,
3736
+ ArrowDown: -step * big,
3737
+ ArrowRight: step * big,
3738
+ ArrowUp: step * big,
3739
+ PageDown: -step * 10,
3740
+ PageUp: step * 10
3741
+ };
3742
+ if (e.key in moves) setPosition(position + moves[e.key]);
3743
+ else if (e.key === "Home") setPosition(from);
3744
+ else if (e.key === "End") setPosition(to);
3745
+ else return;
3746
+ e.preventDefault();
3747
+ e.stopPropagation();
3748
+ };
3749
+ const onKeyDown = (e) => {
3750
+ if (!onZoomChange || e.ctrlKey || e.metaKey || e.altKey) return;
3751
+ if (e.key === "+" || e.key === "=") onZoomChange(zoom * 1.5);
3752
+ else if (e.key === "-") onZoomChange(zoom / 1.5);
3753
+ else if (e.key === "0") onZoomChange(view.width / Math.max(to - from, 1e-6));
3754
+ else return;
3755
+ e.preventDefault();
3756
+ };
3757
+ React.useEffect(() => {
3758
+ const el = scroller.current;
3759
+ if (!el || !onZoomChange) return;
3760
+ const onWheel = (e) => {
3761
+ if (!e.ctrlKey && !e.metaKey) return;
3762
+ e.preventDefault();
3763
+ onZoomChange(e.deltaY < 0 ? zoom * 1.25 : zoom / 1.25);
3764
+ };
3765
+ el.addEventListener("wheel", onWheel, { passive: false });
3766
+ return () => el.removeEventListener("wheel", onWheel);
3767
+ }, [onZoomChange, zoom]);
3768
+ const rovingId = focusId && items.some((i) => i.id === focusId) ? focusId : sorted.get(lanes[0]?.id ?? "")?.[0]?.id ?? items[0]?.id ?? null;
3769
+ const lo = view.left - view.width;
3770
+ const hi = view.left + 2 * view.width;
3771
+ const visible = (i) => i.id === focusId || i.id === rovingId || x(i.start + i.length) >= lo && x(i.start) <= hi;
3772
+ const itemLabel = (i) => `${i.label}, ${formatTime(i.start)} to ${formatTime(i.start + i.length)}, ${laneLabel(i.lane)}`;
3773
+ return /* @__PURE__ */ jsxs("div", {
3774
+ role: "group",
3775
+ "aria-label": label,
3776
+ onKeyDown,
3777
+ className: cn("min-w-0 text-foreground", className),
3778
+ children: [
3779
+ /* @__PURE__ */ jsx("p", {
3780
+ role: "status",
3781
+ className: "sr-only",
3782
+ children: said
3783
+ }),
3784
+ /* @__PURE__ */ jsxs("div", {
3785
+ className: "flex",
3786
+ children: [/* @__PURE__ */ jsxs("div", {
3787
+ className: cn("shrink-0 border-r border-border", HEADER_W),
3788
+ children: [/* @__PURE__ */ jsx("div", {
3789
+ className: "h-8 border-b border-border",
3790
+ "aria-hidden": true
3791
+ }), lanes.map((l) => /* @__PURE__ */ jsxs("div", {
3792
+ className: "flex h-(--control-h) items-center gap-1 border-b border-border px-2 type-label",
3793
+ children: [/* @__PURE__ */ jsx("span", {
3794
+ className: "min-w-0 flex-1 truncate",
3795
+ title: l.label,
3796
+ children: l.label
3797
+ }), l.header]
3798
+ }, l.id))]
3799
+ }), /* @__PURE__ */ jsx("div", {
3800
+ ref: scroller,
3801
+ className: "relative min-w-0 flex-1 overflow-x-auto",
3802
+ children: /* @__PURE__ */ jsxs("div", {
3803
+ className: "relative",
3804
+ style: { width },
3805
+ children: [
3806
+ /* @__PURE__ */ jsxs("div", {
3807
+ ...rulerProps,
3808
+ ref: scrubTrack,
3809
+ className: "relative h-8 touch-none border-b border-border",
3810
+ "data-ruler": true,
3811
+ children: [
3812
+ ticks.map((t) => {
3813
+ const px = x(t);
3814
+ const last = px > width - 40;
3815
+ return /* @__PURE__ */ jsx("span", {
3816
+ "aria-hidden": true,
3817
+ className: "absolute top-0 h-full border-l border-border pl-1 type-caption text-muted-foreground tabular-nums",
3818
+ style: {
3819
+ left: px,
3820
+ transform: last ? "translateX(-100%)" : void 0,
3821
+ borderLeftWidth: last ? 0 : 1,
3822
+ paddingRight: last ? 4 : 0
3823
+ },
3824
+ children: formatTime === defaultFormat ? tickLabel(t, stepSize) : formatTime(t)
3825
+ }, t);
3826
+ }),
3827
+ markers.map((m) => /* @__PURE__ */ jsx("button", {
3828
+ type: "button",
3829
+ "aria-label": `Marker: ${m.label}, ${formatTime(m.time)}`,
3830
+ onPointerDown: (e) => e.stopPropagation(),
3831
+ onMouseDown: (e) => e.stopPropagation(),
3832
+ onClick: () => setPosition(m.time),
3833
+ className: "absolute bottom-0 max-w-32 -translate-x-px truncate rounded-control border-l-2 border-foreground bg-muted px-1 type-caption",
3834
+ style: { left: x(m.time) },
3835
+ children: m.label
3836
+ }, m.id)),
3837
+ position !== void 0 && /* @__PURE__ */ jsxs("div", {
3838
+ ...thumbProps,
3839
+ className: cn("absolute top-0 -ml-2 h-full w-4 cursor-ew-resize", isFocusVisible && "outline-2 outline-offset-2 outline-ring"),
3840
+ style: { left: x(position) },
3841
+ children: [/* @__PURE__ */ jsx("span", {
3842
+ "aria-hidden": true,
3843
+ className: "mx-auto block size-3 rounded-pill bg-primary"
3844
+ }), /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx("input", {
3845
+ ref: scrubInput,
3846
+ ...mergeProps(inputProps, focusProps),
3847
+ "aria-labelledby": void 0,
3848
+ onKeyDownCapture: onSliderKey
3849
+ }) })]
3850
+ })
3851
+ ]
3852
+ }),
3853
+ lanes.length === 0 && /* @__PURE__ */ jsx("div", {
3854
+ className: "p-4",
3855
+ children: empty
3856
+ }),
3857
+ lanes.map((l) => /* @__PURE__ */ jsx("div", {
3858
+ role: "group",
3859
+ "aria-label": l.label,
3860
+ ref: (el) => void (el ? laneRefs.current.set(l.id, el) : laneRefs.current.delete(l.id)),
3861
+ className: "relative h-(--control-h) border-b border-border",
3862
+ children: (sorted.get(l.id) ?? []).filter(visible).map((item) => {
3863
+ const live = drag?.id === item.id && drag.moved ? drag : null;
3864
+ const shown = live ? live.next : item;
3865
+ const laneShift = live ? (laneIndex.get(live.next.lane) ?? 0) - (laneIndex.get(item.lane) ?? 0) : 0;
3866
+ const isSel = selected.has(item.id);
3867
+ const px = x(shown.start);
3868
+ const w = Math.max(shown.length * zoom, 4);
3869
+ return /* @__PURE__ */ jsxs("div", {
3870
+ "data-item": item.id,
3871
+ role: "button",
3872
+ "aria-pressed": isSel,
3873
+ "aria-label": itemLabel(item),
3874
+ tabIndex: item.id === rovingId ? 0 : -1,
3875
+ onFocus: () => setFocusId(item.id),
3876
+ onKeyDown: (e) => onItemKeyDown(e, item),
3877
+ onPointerDown: (e) => begin(e, item, "move"),
3878
+ onPointerMove,
3879
+ onPointerUp,
3880
+ className: cn("absolute top-1 bottom-1 min-w-1 cursor-grab touch-none overflow-hidden rounded-control border border-input border-t-4 bg-background px-1.5 type-caption select-none", isSel && "bg-muted font-medium outline-2 outline-offset-1 outline-primary", live?.reason && "border-dashed border-danger bg-danger-subtle"),
3881
+ style: {
3882
+ left: px,
3883
+ width: w,
3884
+ borderTopColor: item.kind ? kindColour(item.kind, items) : void 0,
3885
+ transform: laneShift ? `translateY(calc(var(--control-h) * ${laneShift}))` : void 0,
3886
+ zIndex: live ? 10 : void 0
3887
+ },
3888
+ children: [
3889
+ renderItem ? renderItem(item, {
3890
+ selected: isSel,
3891
+ width: w
3892
+ }) : /* @__PURE__ */ jsx(DefaultItem, {
3893
+ item,
3894
+ width: w
3895
+ }),
3896
+ /* @__PURE__ */ jsx("span", {
3897
+ "aria-hidden": true,
3898
+ className: "absolute inset-y-0 left-0 cursor-ew-resize touch-none",
3899
+ style: { width: EDGE_PX },
3900
+ onPointerDown: (e) => begin(e, item, "start"),
3901
+ onPointerMove,
3902
+ onPointerUp
3903
+ }),
3904
+ /* @__PURE__ */ jsx("span", {
3905
+ "aria-hidden": true,
3906
+ className: "absolute inset-y-0 right-0 cursor-ew-resize touch-none",
3907
+ style: { width: EDGE_PX },
3908
+ onPointerDown: (e) => begin(e, item, "end"),
3909
+ onPointerMove,
3910
+ onPointerUp
3911
+ })
3912
+ ]
3913
+ }, item.id);
3914
+ })
3915
+ }, l.id)),
3916
+ position !== void 0 && /* @__PURE__ */ jsx("div", {
3917
+ "aria-hidden": true,
3918
+ className: "pointer-events-none absolute top-8 bottom-0 w-0.5 bg-primary",
3919
+ style: { left: x(position) - 1 }
3920
+ }),
3921
+ drag?.moved && drag.guide !== null && /* @__PURE__ */ jsx("div", {
3922
+ "aria-hidden": true,
3923
+ className: "pointer-events-none absolute top-0 bottom-0 w-px bg-foreground",
3924
+ style: { left: x(drag.guide) }
3925
+ })
3926
+ ]
3927
+ })
3928
+ })]
3929
+ }),
3930
+ drag?.moved && /* @__PURE__ */ jsx("p", {
3931
+ "aria-hidden": true,
3932
+ className: "mt-1 flex items-center gap-1.5 type-body-sm tabular-nums text-muted-foreground",
3933
+ children: drag.reason ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Ban, { className: "size-4 shrink-0 text-danger" }), /* @__PURE__ */ jsx("span", {
3934
+ className: "text-danger",
3935
+ children: drag.reason
3936
+ })] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
3937
+ formatTime(drag.next.start),
3938
+ " to ",
3939
+ formatTime(drag.next.start + drag.next.length),
3940
+ ", ",
3941
+ laneLabel(drag.next.lane)
3942
+ ] })
3943
+ })
3944
+ ]
3945
+ });
3946
+ }
3947
+ function kindColour(kind, items) {
3948
+ const kinds = [...new Set(items.map((i) => i.kind).filter(Boolean))];
3949
+ return `var(--chart-${Math.max(kinds.indexOf(kind), 0) % 5 + 1})`;
3950
+ }
3951
+ function DefaultItem({ item, width }) {
3952
+ return /* @__PURE__ */ jsxs("span", {
3953
+ className: "flex h-full min-w-0 items-center gap-1.5",
3954
+ children: [/* @__PURE__ */ jsx("span", {
3955
+ className: "min-w-0 flex-1 truncate",
3956
+ children: item.label
3957
+ }), item.kind && width > 120 && /* @__PURE__ */ jsx("span", {
3958
+ className: "shrink-0 text-muted-foreground",
3959
+ children: item.kind
3960
+ })]
3961
+ });
3962
+ }
3963
+ // src/components/sortable-list.tsx
3964
+ var KIND = "strata-kind/";
3965
+ var ID = "strata-item/id";
3966
+ var LIST = "strata-list/";
3967
+ /** A list that reorders by drag and by keyboard, and takes items from other lists by kind. It reports what was asked and never changes the data itself. */
3968
+ function SortableList({ label, items, getKey, getLabel, children, renderActions, empty, onReorder, onInsert, getKind = () => "item", accepts = [], refuses = {}, selectionMode = "none", selectedKeys, onSelectionChange, className }) {
3969
+ const listId = React.useId();
3970
+ const byKey = React.useMemo(() => new Map(items.map((i) => [getKey(i), i])), [items, getKey]);
3971
+ const [refused, setRefused] = React.useState(null);
3972
+ const root = React.useRef(null);
3973
+ React.useEffect(() => {
3974
+ if (!refused) return;
3975
+ const clear = () => setRefused(null);
3976
+ document.addEventListener("dragend", clear);
3977
+ document.addEventListener("drop", clear);
3978
+ return () => {
3979
+ document.removeEventListener("dragend", clear);
3980
+ document.removeEventListener("drop", clear);
3981
+ };
3982
+ }, [refused]);
3983
+ const toTarget = (t) => t.type === "root" ? {
3984
+ key: null,
3985
+ position: "root"
3986
+ } : {
3987
+ key: String(t.key),
3988
+ position: t.dropPosition
3989
+ };
3990
+ const { dragAndDropHooks } = useDragAndDrop({
3991
+ getItems: (keys) => [...keys].map((k) => {
3992
+ const item = byKey.get(String(k));
3993
+ return {
3994
+ [`${KIND}${item ? getKind(item) : "item"}`]: "",
3995
+ [`${LIST}${listId}`]: "",
3996
+ [ID]: String(k),
3997
+ "text/plain": item ? getLabel(item) : String(k)
3998
+ };
3999
+ }),
4000
+ acceptedDragTypes: "all",
4001
+ getDropOperation: (_target, types) => {
4002
+ if (types.has(`${LIST}${listId}`) || accepts.some((k) => types.has(`${KIND}${k}`))) {
4003
+ setRefused(null);
4004
+ return "move";
4005
+ }
4006
+ const kind = Object.keys(refuses).find((k) => types.has(`${KIND}${k}`));
4007
+ if (kind) setRefused(refuses[kind]);
4008
+ return "cancel";
4009
+ },
4010
+ onReorder: (e) => onReorder([...e.keys].map(String), toTarget(e.target)),
4011
+ onInsert: async (e) => {
4012
+ const ids = (await Promise.all(e.items.filter((i) => i.kind === "text").map((i) => i.getText(ID)))).filter(Boolean);
4013
+ onInsert?.(ids, toTarget(e.target));
4014
+ },
4015
+ onRootDrop: async (e) => {
4016
+ const ids = (await Promise.all(e.items.filter((i) => i.kind === "text").map((i) => i.getText(ID)))).filter(Boolean);
4017
+ onInsert?.(ids, {
4018
+ key: null,
4019
+ position: "root"
4020
+ });
4021
+ },
4022
+ renderDropIndicator: (target) => /* @__PURE__ */ jsx(DropIndicator, {
4023
+ target,
4024
+ className: ({ isDropTarget }) => cn("relative h-0 data-[drop-target]:after:absolute data-[drop-target]:after:inset-x-0 data-[drop-target]:after:-top-px data-[drop-target]:after:h-0.5 data-[drop-target]:after:rounded-pill data-[drop-target]:after:bg-primary", isDropTarget && "z-10")
4025
+ })
4026
+ });
4027
+ return /* @__PURE__ */ jsxs("div", {
4028
+ ref: root,
4029
+ className: cn("min-w-0", className),
4030
+ onDragLeaveCapture: (e) => !e.currentTarget.contains(e.relatedTarget) && setRefused(null),
4031
+ children: [/* @__PURE__ */ jsx(GridList, {
4032
+ "aria-label": label,
4033
+ items: items.map((item) => ({
4034
+ item,
4035
+ id: getKey(item)
4036
+ })),
4037
+ dragAndDropHooks,
4038
+ selectionMode,
4039
+ selectedKeys,
4040
+ onSelectionChange: (keys) => onSelectionChange?.(keys === "all" ? new Set(items.map(getKey)) : new Set([...keys].map(String))),
4041
+ renderEmptyState: ({ isDropTarget }) => /* @__PURE__ */ jsx("div", {
4042
+ className: cn("rounded-surface border border-dashed py-6 text-center", isDropTarget ? "border-solid border-primary bg-muted" : "border-input"),
4043
+ children: isDropTarget ? /* @__PURE__ */ jsx("p", {
4044
+ className: "type-body",
4045
+ children: "Drop here"
4046
+ }) : empty
4047
+ }),
4048
+ className: ({ isDropTarget }) => cn("grid divide-y divide-border border-y border-border", isDropTarget && "outline-2 outline-offset-2 outline-primary"),
4049
+ children: ({ item }) => /* @__PURE__ */ jsxs(GridListItem, {
4050
+ id: getKey(item),
4051
+ textValue: getLabel(item),
4052
+ className: "group relative flex min-h-(--control-h) cursor-default items-center gap-2 py-1 pr-1 pl-1 outline-none data-[focus-visible]:outline-2 data-[focus-visible]:-outline-offset-2 data-[focus-visible]:outline-ring data-[selected]:bg-muted data-[selected]:before:absolute data-[selected]:before:inset-y-1 data-[selected]:before:left-0 data-[selected]:before:w-0.5 data-[selected]:before:rounded-pill data-[selected]:before:bg-primary data-[dragging]:opacity-50",
4053
+ children: [
4054
+ /* @__PURE__ */ jsx(Button$1, {
4055
+ slot: "drag",
4056
+ className: "grid size-(--control-h-sm) shrink-0 cursor-grab place-items-center rounded-control text-muted-foreground hover:bg-muted data-[focus-visible]:outline-2 data-[focus-visible]:outline-ring",
4057
+ children: /* @__PURE__ */ jsx(GripVertical, {
4058
+ "aria-hidden": true,
4059
+ className: "size-4"
4060
+ })
4061
+ }),
4062
+ /* @__PURE__ */ jsx("div", {
4063
+ className: "min-w-0 flex-1",
4064
+ children: children(item)
4065
+ }),
4066
+ renderActions && /* @__PURE__ */ jsx("div", {
4067
+ className: "flex shrink-0 items-center gap-1",
4068
+ children: renderActions(item)
4069
+ })
4070
+ ]
4071
+ })
4072
+ }), refused && /* @__PURE__ */ jsxs("p", {
4073
+ role: "status",
4074
+ className: "mt-2 flex items-start gap-1.5 type-body-sm text-danger",
4075
+ children: [/* @__PURE__ */ jsx(Ban, {
4076
+ "aria-hidden": true,
4077
+ className: "mt-0.5 size-4 shrink-0"
4078
+ }), refused]
4079
+ })]
4080
+ });
4081
+ }
2877
4082
  // src/components/file-intake.tsx
2878
4083
  /** The picker as a button. `children` is its visible name ("Add files"); `accept` narrows what the dialog shows. */
2879
4084
  function FileButton({ accept, multiple = false, onFiles, icon: Icon, children, ...props }) {
@@ -3803,7 +5008,7 @@ function fitTicks(ticks, scale, widthOf, gap = 12) {
3803
5008
  return sorted.slice(0, 1);
3804
5009
  }
3805
5010
  /** One measured series, drawn in real pixels, with the peak and current readings labelled on the chart and every reading in a screen-reader table. Optional plan, threshold band and `colourScale`. */
3806
- function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, formatX, formatY, xTicks, yMin, yMax, colour = "var(--chart-1)", colourScale, colourScaleLabel, height = 280, className }) {
5011
+ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, formatX, formatY, xTicks, yMin, yMax, colour = "var(--chart-1)", colourScale, colourScaleLabel, current, formatCurrent, readout, onPick, area, height = 280, className }) {
3807
5012
  const [ref, width] = useWidth();
3808
5013
  const gradientId = `heat-${React.useId().replace(/[^\w-]/g, "")}`;
3809
5014
  const all = [...series, ...planned ?? []];
@@ -3828,7 +5033,13 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
3828
5033
  const half = xLabelWidth(t) / 2;
3829
5034
  return Math.min(Math.max(sx(t), half), Math.max(half, width - half));
3830
5035
  };
3831
- const shownXTicks = fitTicks(xTicks, xLabelAt, xLabelWidth);
5036
+ const shownXTicks = React.useMemo(() => fitTicks(xTicks, xLabelAt, xLabelWidth), [
5037
+ xTicks,
5038
+ width,
5039
+ xMin,
5040
+ xMax,
5041
+ formatX
5042
+ ]);
3832
5043
  const path = (pts) => pts.map((p, i) => `${i ? "L" : "M"}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join("");
3833
5044
  const last = series[series.length - 1];
3834
5045
  const peak = series.reduce((a, b) => b.y > a.y ? b : a, series[0]);
@@ -3836,115 +5047,296 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
3836
5047
  /** The colour a value lands on: the highest stop at or below it. Used for the labelled points. */
3837
5048
  const colourAt = (y) => stops.length ? [...stops].reverse().find((s) => s.at <= y)?.colour ?? stops[0].colour : colour;
3838
5049
  const stroke = stops.length ? `url(#${gradientId})` : colour;
5050
+ const plot = React.useMemo(() => /* @__PURE__ */ jsxs(Fragment, { children: [
5051
+ stops.length > 0 && /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("linearGradient", {
5052
+ id: gradientId,
5053
+ gradientUnits: "userSpaceOnUse",
5054
+ x1: 0,
5055
+ x2: 0,
5056
+ y1: sy(y.min),
5057
+ y2: sy(y.max),
5058
+ children: stops.map((s) => /* @__PURE__ */ jsx("stop", {
5059
+ offset: Math.min(1, Math.max(0, (s.at - y.min) / (y.max - y.min))),
5060
+ stopColor: s.colour
5061
+ }, s.at))
5062
+ }) }),
5063
+ band && band.below > y.min && /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("rect", {
5064
+ x: pad.left,
5065
+ y: sy(Math.min(band.below, y.max)),
5066
+ width: w,
5067
+ height: sy(y.min) - sy(Math.min(band.below, y.max)),
5068
+ fill: "var(--success-subtle)"
5069
+ }), /* @__PURE__ */ jsx("text", {
5070
+ x: pad.left + 8,
5071
+ y: sy(Math.min(band.below, y.max)) + 16,
5072
+ className: "fill-success type-caption",
5073
+ children: band.label
5074
+ })] }),
5075
+ y.ticks.map((t) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
5076
+ x1: pad.left,
5077
+ x2: pad.left + w,
5078
+ y1: sy(t),
5079
+ y2: sy(t),
5080
+ stroke: "var(--border)",
5081
+ strokeWidth: 1
5082
+ }), /* @__PURE__ */ jsx("text", {
5083
+ x: pad.left - 8,
5084
+ y: sy(t),
5085
+ dy: "0.32em",
5086
+ textAnchor: "end",
5087
+ className: "fill-muted-foreground type-caption tabular-nums",
5088
+ children: formatY(t)
5089
+ })] }, t)),
5090
+ shownXTicks.map((t) => /* @__PURE__ */ jsx("text", {
5091
+ x: xLabelAt(t),
5092
+ y: height - 8,
5093
+ textAnchor: "middle",
5094
+ className: "fill-muted-foreground type-caption tabular-nums",
5095
+ children: formatX(t)
5096
+ }, t)),
5097
+ planned && /* @__PURE__ */ jsx("path", {
5098
+ d: path(planned),
5099
+ fill: "none",
5100
+ stroke: "var(--muted-foreground)",
5101
+ strokeWidth: 1.5,
5102
+ strokeDasharray: "4 4"
5103
+ }),
5104
+ area && series.length > 1 && /* @__PURE__ */ jsx("path", {
5105
+ d: `${path(series)}L${sx(series[series.length - 1].x).toFixed(1)},${sy(y.min).toFixed(1)}L${sx(series[0].x).toFixed(1)},${sy(y.min).toFixed(1)}Z`,
5106
+ fill: colour,
5107
+ fillOpacity: .12,
5108
+ stroke: "none"
5109
+ }),
5110
+ /* @__PURE__ */ jsx("path", {
5111
+ d: path(series),
5112
+ fill: "none",
5113
+ stroke,
5114
+ strokeWidth: stops.length ? 2.5 : 2,
5115
+ strokeLinejoin: "round",
5116
+ strokeLinecap: "round"
5117
+ }),
5118
+ /* @__PURE__ */ jsx("circle", {
5119
+ cx: sx(peak.x),
5120
+ cy: sy(peak.y),
5121
+ r: 3,
5122
+ fill: colourAt(peak.y)
5123
+ }),
5124
+ /* @__PURE__ */ jsxs("text", {
5125
+ x: sx(peak.x) + 8,
5126
+ y: sy(peak.y) - 8,
5127
+ className: "fill-foreground type-caption tabular-nums",
5128
+ children: [formatY(peak.y), " peak"]
5129
+ }),
5130
+ /* @__PURE__ */ jsx("line", {
5131
+ x1: sx(last.x),
5132
+ x2: sx(last.x),
5133
+ y1: pad.top,
5134
+ y2: pad.top + h,
5135
+ stroke: "var(--foreground)",
5136
+ strokeWidth: 1
5137
+ }),
5138
+ /* @__PURE__ */ jsx("circle", {
5139
+ cx: sx(last.x),
5140
+ cy: sy(last.y),
5141
+ r: 3.5,
5142
+ fill: colourAt(last.y)
5143
+ }),
5144
+ /* @__PURE__ */ jsxs("text", {
5145
+ x: sx(last.x) - 8,
5146
+ y: sy(last.y) - 10,
5147
+ textAnchor: "end",
5148
+ className: "fill-foreground type-label tabular-nums",
5149
+ children: [formatY(last.y), " now"]
5150
+ })
5151
+ ] }), [
5152
+ width,
5153
+ height,
5154
+ series,
5155
+ planned,
5156
+ band,
5157
+ xTicks,
5158
+ yMin,
5159
+ yMax,
5160
+ colour,
5161
+ colourScale,
5162
+ formatX,
5163
+ formatY,
5164
+ area
5165
+ ]);
5166
+ const tableEl = React.useMemo(() => /* @__PURE__ */ jsx("div", {
5167
+ className: "sr-only",
5168
+ children: /* @__PURE__ */ jsxs("table", { children: [
5169
+ /* @__PURE__ */ jsx("caption", { children: label }),
5170
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
5171
+ scope: "col",
5172
+ children: "Time"
5173
+ }), /* @__PURE__ */ jsx("th", {
5174
+ scope: "col",
5175
+ children: seriesLabel
5176
+ })] }) }),
5177
+ /* @__PURE__ */ jsx("tbody", { children: series.map((p) => /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("td", { children: formatX(p.x) }), /* @__PURE__ */ jsx("td", { children: formatY(p.y) })] }, p.x)) })
5178
+ ] })
5179
+ }), [
5180
+ label,
5181
+ seriesLabel,
5182
+ series,
5183
+ formatX,
5184
+ formatY
5185
+ ]);
5186
+ const sorted = React.useMemo(() => [...series].sort((p, q) => p.x - q.x), [series]);
5187
+ const interactive = Boolean(readout || onPick);
5188
+ const [hover, setHover] = React.useState(null);
5189
+ const [kbd, setKbd] = React.useState(null);
5190
+ const [focused, setFocused] = React.useState(false);
5191
+ const readoutText = (pt) => typeof readout === "function" ? readout(pt) : `${formatX(pt.x)}: ${formatY(pt.y)}`;
5192
+ const nearest = (px) => {
5193
+ const target = xMin + (px - pad.left) / (w || 1) * (xMax - xMin || 1);
5194
+ let best = 0;
5195
+ for (let i = 1; i < sorted.length; i++) if (Math.abs(sorted[i].x - target) < Math.abs(sorted[best].x - target)) best = i;
5196
+ return best;
5197
+ };
5198
+ /** The value of the line at x, read between the two readings either side (flat beyond the ends). */
5199
+ const yAt = (x) => {
5200
+ if (!sorted.length) return 0;
5201
+ if (x <= sorted[0].x) return sorted[0].y;
5202
+ for (let i = 1; i < sorted.length; i++) if (x <= sorted[i].x) {
5203
+ const [p0, p1] = [sorted[i - 1], sorted[i]];
5204
+ return p0.y + (p1.y - p0.y) * (x - p0.x) / (p1.x - p0.x || 1);
5205
+ }
5206
+ return sorted[sorted.length - 1].y;
5207
+ };
5208
+ const currentAt = current === void 0 ? null : {
5209
+ x: Math.min(Math.max(current, xMin), xMax),
5210
+ y: yAt(current)
5211
+ };
5212
+ const fallbackIdx = sorted.length ? currentAt ? nearest(sx(currentAt.x)) : sorted.length - 1 : 0;
5213
+ const heldIdx = kbd === null ? fallbackIdx : Math.min(kbd, Math.max(sorted.length - 1, 0));
5214
+ const selectedIdx = hover === null ? heldIdx : Math.min(hover, Math.max(sorted.length - 1, 0));
5215
+ const active = (hover !== null || focused) && sorted.length ? sorted[selectedIdx] : null;
5216
+ const onKey = (e) => {
5217
+ const at = selectedIdx;
5218
+ let next = at;
5219
+ if (e.key === "ArrowRight" || e.key === "ArrowUp") next = Math.min(at + 1, sorted.length - 1);
5220
+ else if (e.key === "ArrowLeft" || e.key === "ArrowDown") next = Math.max(at - 1, 0);
5221
+ else if (e.key === "Home") next = 0;
5222
+ else if (e.key === "End") next = sorted.length - 1;
5223
+ else if ((e.key === "Enter" || e.key === " ") && onPick) {
5224
+ e.preventDefault();
5225
+ onPick(sorted[at].x);
5226
+ return;
5227
+ } else return;
5228
+ e.preventDefault();
5229
+ setHover(null);
5230
+ setKbd(next);
5231
+ };
5232
+ const flip = (px, text) => px + labelWidth(text) + 16 > width ? {
5233
+ x: px - 8,
5234
+ anchor: "end"
5235
+ } : {
5236
+ x: px + 8,
5237
+ anchor: "start"
5238
+ };
3839
5239
  return /* @__PURE__ */ jsxs("figure", {
3840
5240
  className: cn("grid min-w-0 gap-2", className),
3841
5241
  children: [
3842
- /* @__PURE__ */ jsx("div", {
5242
+ /* @__PURE__ */ jsxs("div", {
3843
5243
  ref,
3844
- className: "min-w-0",
3845
- children: width > 0 && /* @__PURE__ */ jsxs("svg", {
5244
+ className: "relative min-w-0",
5245
+ children: [width > 0 && /* @__PURE__ */ jsxs("svg", {
3846
5246
  width,
3847
5247
  height,
3848
5248
  role: "img",
3849
5249
  "aria-label": label,
3850
5250
  className: "block overflow-visible",
3851
5251
  children: [
3852
- stops.length > 0 && /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("linearGradient", {
3853
- id: gradientId,
3854
- gradientUnits: "userSpaceOnUse",
3855
- x1: 0,
3856
- x2: 0,
3857
- y1: sy(y.min),
3858
- y2: sy(y.max),
3859
- children: stops.map((s) => /* @__PURE__ */ jsx("stop", {
3860
- offset: Math.min(1, Math.max(0, (s.at - y.min) / (y.max - y.min))),
3861
- stopColor: s.colour
3862
- }, s.at))
3863
- }) }),
3864
- band && band.below > y.min && /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("rect", {
3865
- x: pad.left,
3866
- y: sy(Math.min(band.below, y.max)),
3867
- width: w,
3868
- height: sy(y.min) - sy(Math.min(band.below, y.max)),
3869
- fill: "var(--success-subtle)"
3870
- }), /* @__PURE__ */ jsx("text", {
3871
- x: pad.left + 8,
3872
- y: sy(Math.min(band.below, y.max)) + 16,
3873
- className: "fill-success type-caption",
3874
- children: band.label
3875
- })] }),
3876
- y.ticks.map((t) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
3877
- x1: pad.left,
3878
- x2: pad.left + w,
3879
- y1: sy(t),
3880
- y2: sy(t),
3881
- stroke: "var(--border)",
3882
- strokeWidth: 1
3883
- }), /* @__PURE__ */ jsx("text", {
3884
- x: pad.left - 8,
3885
- y: sy(t),
3886
- dy: "0.32em",
3887
- textAnchor: "end",
3888
- className: "fill-muted-foreground type-caption tabular-nums",
3889
- children: formatY(t)
3890
- })] }, t)),
3891
- shownXTicks.map((t) => /* @__PURE__ */ jsx("text", {
3892
- x: xLabelAt(t),
3893
- y: height - 8,
3894
- textAnchor: "middle",
3895
- className: "fill-muted-foreground type-caption tabular-nums",
3896
- children: formatX(t)
3897
- }, t)),
3898
- planned && /* @__PURE__ */ jsx("path", {
3899
- d: path(planned),
3900
- fill: "none",
3901
- stroke: "var(--muted-foreground)",
3902
- strokeWidth: 1.5,
3903
- strokeDasharray: "4 4"
3904
- }),
3905
- /* @__PURE__ */ jsx("path", {
3906
- d: path(series),
3907
- fill: "none",
3908
- stroke,
3909
- strokeWidth: stops.length ? 2.5 : 2,
3910
- strokeLinejoin: "round",
3911
- strokeLinecap: "round"
3912
- }),
3913
- /* @__PURE__ */ jsx("circle", {
3914
- cx: sx(peak.x),
3915
- cy: sy(peak.y),
3916
- r: 3,
3917
- fill: colourAt(peak.y)
3918
- }),
3919
- /* @__PURE__ */ jsxs("text", {
3920
- x: sx(peak.x) + 8,
3921
- y: sy(peak.y) - 8,
3922
- className: "fill-foreground type-caption tabular-nums",
3923
- children: [formatY(peak.y), " peak"]
3924
- }),
3925
- /* @__PURE__ */ jsx("line", {
3926
- x1: sx(last.x),
3927
- x2: sx(last.x),
3928
- y1: pad.top,
3929
- y2: pad.top + h,
3930
- stroke: "var(--foreground)",
3931
- strokeWidth: 1
3932
- }),
3933
- /* @__PURE__ */ jsx("circle", {
3934
- cx: sx(last.x),
3935
- cy: sy(last.y),
3936
- r: 3.5,
3937
- fill: colourAt(last.y)
5252
+ plot,
5253
+ currentAt && /* @__PURE__ */ jsxs("g", {
5254
+ "aria-hidden": true,
5255
+ children: [
5256
+ /* @__PURE__ */ jsx("line", {
5257
+ x1: sx(currentAt.x),
5258
+ x2: sx(currentAt.x),
5259
+ y1: pad.top,
5260
+ y2: pad.top + h,
5261
+ stroke: "var(--primary)",
5262
+ strokeWidth: 1.5
5263
+ }),
5264
+ /* @__PURE__ */ jsx("circle", {
5265
+ cx: sx(currentAt.x),
5266
+ cy: sy(currentAt.y),
5267
+ r: 4,
5268
+ fill: "var(--background)",
5269
+ stroke: "var(--primary)",
5270
+ strokeWidth: 2
5271
+ }),
5272
+ (() => {
5273
+ const text = formatCurrent ? formatCurrent(currentAt) : `${formatX(currentAt.x)}: ${formatY(currentAt.y)}`;
5274
+ const at = flip(sx(currentAt.x), text);
5275
+ return /* @__PURE__ */ jsx("text", {
5276
+ x: at.x,
5277
+ y: pad.top + 12,
5278
+ textAnchor: at.anchor,
5279
+ className: "fill-foreground type-caption tabular-nums",
5280
+ children: text
5281
+ });
5282
+ })()
5283
+ ]
3938
5284
  }),
3939
- /* @__PURE__ */ jsxs("text", {
3940
- x: sx(last.x) - 8,
3941
- y: sy(last.y) - 10,
3942
- textAnchor: "end",
3943
- className: "fill-foreground type-label tabular-nums",
3944
- children: [formatY(last.y), " now"]
5285
+ active && /* @__PURE__ */ jsxs("g", {
5286
+ "aria-hidden": true,
5287
+ children: [
5288
+ /* @__PURE__ */ jsx("line", {
5289
+ x1: sx(active.x),
5290
+ x2: sx(active.x),
5291
+ y1: pad.top,
5292
+ y2: pad.top + h,
5293
+ stroke: "var(--muted-foreground)",
5294
+ strokeWidth: 1,
5295
+ strokeDasharray: "2 3"
5296
+ }),
5297
+ /* @__PURE__ */ jsx("circle", {
5298
+ cx: sx(active.x),
5299
+ cy: sy(active.y),
5300
+ r: 4,
5301
+ fill: "var(--foreground)"
5302
+ }),
5303
+ (() => {
5304
+ const text = readoutText(active);
5305
+ const at = flip(sx(active.x), text);
5306
+ return /* @__PURE__ */ jsx("text", {
5307
+ x: at.x,
5308
+ y: sy(active.y) - 10,
5309
+ textAnchor: at.anchor,
5310
+ className: "fill-foreground type-label tabular-nums",
5311
+ paintOrder: "stroke",
5312
+ stroke: "var(--background)",
5313
+ strokeWidth: 3,
5314
+ children: text
5315
+ });
5316
+ })()
5317
+ ]
3945
5318
  })
3946
5319
  ]
3947
- })
5320
+ }), width > 0 && interactive && sorted.length > 0 && /* @__PURE__ */ jsx(ReadingSlider, {
5321
+ label: `${label}: read values`,
5322
+ sorted,
5323
+ selected: selectedIdx,
5324
+ text: readoutText,
5325
+ onSelect: (i) => {
5326
+ setHover(null);
5327
+ setKbd(i);
5328
+ },
5329
+ onPick,
5330
+ onKeyDownCapture: onKey,
5331
+ onHover: (px) => setHover(px === null ? null : nearest(px)),
5332
+ onFocusChange: setFocused,
5333
+ box: {
5334
+ left: pad.left,
5335
+ top: pad.top,
5336
+ width: w,
5337
+ height: h
5338
+ }
5339
+ })]
3948
5340
  }),
3949
5341
  /* @__PURE__ */ jsxs("figcaption", {
3950
5342
  className: "flex flex-wrap gap-x-5 gap-y-1 type-caption text-muted-foreground",
@@ -4001,23 +5393,76 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
4001
5393
  }), plannedLabel]
4002
5394
  })]
4003
5395
  }),
4004
- /* @__PURE__ */ jsx("div", {
4005
- className: "sr-only",
4006
- children: /* @__PURE__ */ jsxs("table", { children: [
4007
- /* @__PURE__ */ jsx("caption", { children: label }),
4008
- /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
4009
- scope: "col",
4010
- children: "Time"
4011
- }), /* @__PURE__ */ jsx("th", {
4012
- scope: "col",
4013
- children: seriesLabel
4014
- })] }) }),
4015
- /* @__PURE__ */ jsx("tbody", { children: series.map((p) => /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("td", { children: formatX(p.x) }), /* @__PURE__ */ jsx("td", { children: formatY(p.y) })] }, p.x)) })
4016
- ] })
4017
- })
5396
+ tableEl
4018
5397
  ]
4019
5398
  });
4020
5399
  }
5400
+ /** The slider over the plot: React Aria's hooks, snapped to the readings, with the reading as its spoken value. */
5401
+ function ReadingSlider({ label, sorted, selected, text, onSelect, onPick, onKeyDownCapture, onHover, onFocusChange, box }) {
5402
+ const track = React.useRef(null);
5403
+ const input = React.useRef(null);
5404
+ const lo = sorted[0].x;
5405
+ const hi = Math.max(sorted[sorted.length - 1].x, lo + 1e-9);
5406
+ const indexAt = (x) => {
5407
+ let best = 0;
5408
+ for (let i = 1; i < sorted.length; i++) if (Math.abs(sorted[i].x - x) < Math.abs(sorted[best].x - x)) best = i;
5409
+ return best;
5410
+ };
5411
+ const spoken = React.useMemo(() => {
5412
+ const say = (x) => text(sorted[indexAt(x)]);
5413
+ return {
5414
+ format: say,
5415
+ formatRange: (a, b) => `${say(a)} to ${say(b)}`,
5416
+ resolvedOptions: () => ({ locale: "en-US" })
5417
+ };
5418
+ }, [sorted, text]);
5419
+ const state = useSliderState({
5420
+ minValue: lo,
5421
+ maxValue: hi,
5422
+ step: (hi - lo) / 1e4,
5423
+ value: [sorted[selected].x],
5424
+ onChange: ([x]) => onSelect(indexAt(x)),
5425
+ onChangeEnd: ([x]) => onPick?.(sorted[indexAt(x)].x),
5426
+ numberFormatter: spoken
5427
+ });
5428
+ const { groupProps, trackProps } = useSlider({ "aria-label": label }, state, track);
5429
+ const { thumbProps, inputProps } = useSliderThumb({
5430
+ index: 0,
5431
+ trackRef: track,
5432
+ inputRef: input,
5433
+ "aria-label": label
5434
+ }, state);
5435
+ const { focusProps, isFocusVisible } = useFocusRing();
5436
+ return /* @__PURE__ */ jsx("div", {
5437
+ ...groupProps,
5438
+ className: "absolute",
5439
+ style: box,
5440
+ children: /* @__PURE__ */ jsx("div", {
5441
+ ...trackProps,
5442
+ ref: track,
5443
+ onPointerMove: (e) => onHover(e.clientX - e.currentTarget.getBoundingClientRect().left + box.left),
5444
+ onPointerLeave: () => onHover(null),
5445
+ className: cn("relative size-full cursor-crosshair touch-none", isFocusVisible && "outline-2 outline-offset-2 outline-ring"),
5446
+ children: /* @__PURE__ */ jsx("div", {
5447
+ ...thumbProps,
5448
+ className: "absolute inset-y-0 w-0",
5449
+ style: { left: `${state.getThumbPercent(0) * 100}%` },
5450
+ children: /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx("input", {
5451
+ ref: input,
5452
+ ...mergeProps(inputProps, focusProps, {
5453
+ onFocus: () => onFocusChange(true),
5454
+ onBlur: () => onFocusChange(false)
5455
+ }),
5456
+ "aria-labelledby": void 0,
5457
+ onKeyDownCapture: (e) => {
5458
+ onKeyDownCapture(e);
5459
+ if (e.defaultPrevented) e.stopPropagation();
5460
+ }
5461
+ }) })
5462
+ })
5463
+ })
5464
+ });
5465
+ }
4021
5466
  // src/components/page-header.tsx
4022
5467
  /** The top of an Operate screen: a noun title, its scope, the main action, and the finding (the one fact in today's data that most needs attention). */
4023
5468
  function PageHeader({ title, scope, actions, finding, as: Heading = "h1" }) {
@@ -5558,6 +7003,6 @@ function CompareGrid({ label, items, blind, missing, actions, columns = 3, keys
5558
7003
  })
5559
7004
  });
5560
7005
  }
5561
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareGrid, CompositionBar, ContextMenu, DEFAULT_TOLERANCE, DataTable, DataView, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, LineChart, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, Popover, PropertyList, PropertyRow, RowAction, SelectableGrid, SideNav, Skeleton, Slider, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, UndoBar, ViewportFrame, VirtualList, actualPixelsScale, buttonVariants, canFullscreen, clampViewport, cn, colorSchemeScript, commandShortcut, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, detectPlatform, differences, fetchJson, fieldErrorsOf, format, formatChord, isReservedChord, isTypingTarget, labelOf, matchesAccept, matchesChord, parseChord, parseSort, readErrorBody, readPixels, resample, serialiseSort, staleOf, toDate, toLoad, toast, toastTimeout, typeSteps, useActiveItem, useAsyncAction, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHotkeys, useInView, useInfiniteLoad, useJob, useLoad, useSelection, useSystemColorScheme, useUndoable, useViewport, zoomAt };
7006
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareGrid, CompositionBar, ContextMenu, DEFAULT_TOLERANCE, DataTable, DataView, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, LineChart, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, Popover, PropertyList, PropertyRow, RateChoice, RowAction, SeekBar, SelectableGrid, SideNav, Skeleton, Slider, SortableList, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, Transport, UndoBar, ViewportFrame, VirtualList, VolumeControl, actualPixelsScale, buttonVariants, canFullscreen, clampViewport, cn, colorSchemeScript, commandShortcut, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, detectPlatform, differences, fetchJson, fieldErrorsOf, format, formatChord, isReservedChord, isTypingTarget, labelOf, matchesAccept, matchesChord, noOverlap, parseChord, parseSort, readErrorBody, readPixels, resample, serialiseSort, staleOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toast, toastTimeout, transportShortcuts, typeSteps, useActiveItem, useAsyncAction, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHotkeys, useInView, useInfiniteLoad, useJob, useLoad, useSelection, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, zoomAt };
5562
7007
 
5563
7008
  //# sourceMappingURL=index.js.map