@vitavision/workbench 0.0.0-bootstrap.0 → 0.1.1

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.
@@ -0,0 +1,223 @@
1
+ /*
2
+ * Opening local files: by dropping them, or through the picker.
3
+ *
4
+ * Both routes are always offered. A drop target alone is invisible to a keyboard and to
5
+ * anyone who does not know it is there; a picker alone makes a folder of scenario files a
6
+ * dozen clicks. The picker is a real `<button>`, so the component is operable without a
7
+ * pointer.
8
+ */
9
+
10
+ import { FolderOpen } from "lucide-react";
11
+ import { useEffect, useRef, useState } from "react";
12
+ import type { ChangeEvent, DragEvent, ReactNode } from "react";
13
+
14
+ import { Button, cn } from "@vitavision/ui";
15
+
16
+ import { carriesFiles, collectDroppedFiles, partitionFiles } from "./dropFiles";
17
+
18
+ /** Props of `FileDrop`. */
19
+ export interface FileDropProps {
20
+ /** Called with the accepted files of a drop or a pick (never with an empty list). */
21
+ onFiles: (files: File[]) => void;
22
+ /** Called with the files a drop or a pick brought that `accept` turned away. */
23
+ onReject?: ((files: File[]) => void) | undefined;
24
+ /**
25
+ * Which files to take, as `<input accept>`: extensions (`.json`), MIME types and MIME
26
+ * wildcards (`image/*`), comma-separated. Applied to drops as well as the picker. Default: all.
27
+ */
28
+ accept?: string | undefined;
29
+ /** Take several files at once. Defaults to true; when false only the first accepted file is passed. */
30
+ multiple?: boolean | undefined;
31
+ /**
32
+ * The picker chooses a folder (`webkitdirectory`) instead of files. Dropped folders are
33
+ * walked either way; files found in a folder carry `webkitRelativePath`.
34
+ */
35
+ directory?: boolean | undefined;
36
+ /**
37
+ * Take drops anywhere in the window, showing a full-window overlay while files are dragged
38
+ * over it; the component itself then renders only the picker button (for a header). Without
39
+ * it, the component is an inline drop zone.
40
+ */
41
+ overlay?: boolean | undefined;
42
+ /** Refuses drops and blocks the picker. */
43
+ disabled?: boolean | undefined;
44
+ /** The picker button's label. Defaults to "Open files…" (or "Open folder…" with `directory`). */
45
+ buttonLabel?: string | undefined;
46
+ /** The overlay's message. Defaults to "Drop to open". */
47
+ overlayMessage?: ReactNode;
48
+ /** The inline zone's message, before the button. Defaults to "Drop files here, or". */
49
+ children?: ReactNode;
50
+ /** Merged with the zone's (or, with `overlay`, the button's) own classes through `cn`. */
51
+ className?: string | undefined;
52
+ }
53
+
54
+ /**
55
+ * A drop target plus an "Open files…" button over a hidden `<input type="file">`.
56
+ *
57
+ * Inline (the default) it is a dashed zone with a message and the button, carrying
58
+ * `data-dragging` while files are dragged over it. With `overlay` it renders only the button
59
+ * and takes drops anywhere in the window, showing a full-window overlay (`aria-hidden`: the
60
+ * button is the accessible route) while a drag carrying files is over the window. Only drags
61
+ * that carry files are reacted to; text and links pass through.
62
+ *
63
+ * Files are filtered by `accept` on both routes (the browser applies it to neither drops nor,
64
+ * reliably, the picker); the rest go to `onReject`. A dropped folder is walked recursively.
65
+ */
66
+ export function FileDrop({
67
+ onFiles,
68
+ onReject,
69
+ accept,
70
+ multiple = true,
71
+ directory = false,
72
+ overlay = false,
73
+ disabled = false,
74
+ buttonLabel,
75
+ overlayMessage = "Drop to open",
76
+ children = "Drop files here, or",
77
+ className,
78
+ }: FileDropProps) {
79
+ const inputRef = useRef<HTMLInputElement | null>(null);
80
+ const depthRef = useRef(0);
81
+ const [dragging, setDragging] = useState(false);
82
+ const label = buttonLabel ?? (directory ? "Open folder…" : "Open files…");
83
+
84
+ const deliver = (files: readonly File[]) => {
85
+ const { accepted, rejected } = partitionFiles(files, accept);
86
+ if (accepted.length > 0) onFiles(multiple ? accepted : accepted.slice(0, 1));
87
+ if (rejected.length > 0) onReject?.(rejected);
88
+ };
89
+ const deliverRef = useRef(deliver);
90
+ useEffect(() => {
91
+ deliverRef.current = deliver;
92
+ });
93
+
94
+ // The window-wide target. `dragenter`/`dragleave` fire for every element crossed, so the
95
+ // overlay's visibility is a depth count rather than the last event seen.
96
+ useEffect(() => {
97
+ if (!overlay || disabled) return;
98
+ const onEnter = (event: globalThis.DragEvent) => {
99
+ if (!carriesFiles(event.dataTransfer)) return;
100
+ depthRef.current += 1;
101
+ setDragging(true);
102
+ };
103
+ const onLeave = (event: globalThis.DragEvent) => {
104
+ if (!carriesFiles(event.dataTransfer)) return;
105
+ depthRef.current = Math.max(0, depthRef.current - 1);
106
+ if (depthRef.current === 0) setDragging(false);
107
+ };
108
+ const onOver = (event: globalThis.DragEvent) => {
109
+ if (!carriesFiles(event.dataTransfer)) return;
110
+ event.preventDefault();
111
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
112
+ };
113
+ const onDrop = (event: globalThis.DragEvent) => {
114
+ if (!event.dataTransfer || !carriesFiles(event.dataTransfer)) return;
115
+ event.preventDefault();
116
+ depthRef.current = 0;
117
+ setDragging(false);
118
+ void collectDroppedFiles(event.dataTransfer).then((files) => deliverRef.current(files));
119
+ };
120
+ window.addEventListener("dragenter", onEnter);
121
+ window.addEventListener("dragleave", onLeave);
122
+ window.addEventListener("dragover", onOver);
123
+ window.addEventListener("drop", onDrop);
124
+ return () => {
125
+ window.removeEventListener("dragenter", onEnter);
126
+ window.removeEventListener("dragleave", onLeave);
127
+ window.removeEventListener("dragover", onOver);
128
+ window.removeEventListener("drop", onDrop);
129
+ depthRef.current = 0;
130
+ };
131
+ }, [overlay, disabled]);
132
+
133
+ const onPick = (event: ChangeEvent<HTMLInputElement>) => {
134
+ const files = Array.from(event.currentTarget.files ?? []);
135
+ // Cleared so that choosing the same file again is still a change.
136
+ event.currentTarget.value = "";
137
+ if (files.length > 0) deliver(files);
138
+ };
139
+
140
+ const picker = (
141
+ <>
142
+ <input
143
+ ref={(element) => {
144
+ inputRef.current = element;
145
+ if (element) element.webkitdirectory = directory;
146
+ }}
147
+ type="file"
148
+ hidden
149
+ tabIndex={-1}
150
+ accept={accept}
151
+ multiple={multiple || directory}
152
+ disabled={disabled}
153
+ onChange={onPick}
154
+ />
155
+ <Button
156
+ icon={<FolderOpen />}
157
+ disabled={disabled}
158
+ onClick={() => inputRef.current?.click()}
159
+ className={overlay ? className : undefined}
160
+ >
161
+ {label}
162
+ </Button>
163
+ </>
164
+ );
165
+
166
+ if (overlay) {
167
+ return (
168
+ <>
169
+ {picker}
170
+ {dragging && (
171
+ <div
172
+ aria-hidden
173
+ data-dragging=""
174
+ className="pointer-events-none fixed inset-0 z-50 grid place-items-center bg-ground/80 p-8 backdrop-blur-sm"
175
+ >
176
+ <div className="rounded-panel border-2 border-dashed border-signal bg-surface px-10 py-8 text-sm font-medium text-fg shadow-lg">
177
+ {overlayMessage}
178
+ </div>
179
+ </div>
180
+ )}
181
+ </>
182
+ );
183
+ }
184
+
185
+ const zoneDrag = (event: DragEvent<HTMLDivElement>, change: 1 | -1 | 0) => {
186
+ if (disabled || !carriesFiles(event.dataTransfer)) return;
187
+ event.preventDefault();
188
+ if (change === 0) {
189
+ event.dataTransfer.dropEffect = "copy";
190
+ return;
191
+ }
192
+ depthRef.current = Math.max(0, depthRef.current + change);
193
+ setDragging(depthRef.current > 0);
194
+ };
195
+
196
+ return (
197
+ <div
198
+ data-dragging={dragging ? "" : undefined}
199
+ data-disabled={disabled ? "" : undefined}
200
+ onDragEnter={(event) => zoneDrag(event, 1)}
201
+ onDragLeave={(event) => zoneDrag(event, -1)}
202
+ onDragOver={(event) => zoneDrag(event, 0)}
203
+ onDrop={(event) => {
204
+ if (disabled || !carriesFiles(event.dataTransfer)) return;
205
+ event.preventDefault();
206
+ depthRef.current = 0;
207
+ setDragging(false);
208
+ void collectDroppedFiles(event.dataTransfer).then(deliver);
209
+ }}
210
+ className={cn(
211
+ "flex flex-col items-center justify-center gap-3 rounded-panel border-2 border-dashed border-line-strong px-6 py-8 text-center text-sm text-fg-muted transition-colors",
212
+ "data-dragging:border-signal data-dragging:bg-signal/8 data-dragging:text-fg",
213
+ // Not `opacity-50`: the message would fall below AA. The disabled button and the quieter
214
+ // border say it instead.
215
+ "data-disabled:border-line",
216
+ className,
217
+ )}
218
+ >
219
+ <p>{children}</p>
220
+ {picker}
221
+ </div>
222
+ );
223
+ }
@@ -0,0 +1,303 @@
1
+ /*
2
+ * The transport for a sampled timeline.
3
+ *
4
+ * Playback state splits by how often it changes. Whether it is playing, how fast, and
5
+ * whether it loops change when someone clicks — ordinary controlled props. Where it is
6
+ * changes every frame — so that is a `Playhead` store the bar subscribes to itself, and a
7
+ * playing timeline re-renders this bar and nothing else in the app.
8
+ *
9
+ * The bar is chrome over a viewport, like the image stage's toolbar: one row, icon buttons
10
+ * named for what they do, the time in mono so it does not jitter as digits change.
11
+ */
12
+
13
+ import {
14
+ ChevronFirst,
15
+ ChevronLast,
16
+ Pause,
17
+ Play,
18
+ Repeat,
19
+ SkipBack,
20
+ SkipForward,
21
+ StepBack,
22
+ StepForward,
23
+ } from "lucide-react";
24
+ import type { ComponentPropsWithRef, KeyboardEvent, ReactNode } from "react";
25
+
26
+ import { type MeasureTone, Select, Slider, byDensity, cn, focusRing, toneColor, useDensity } from "@vitavision/ui";
27
+
28
+ import { formatSeconds, type Playhead } from "./playhead";
29
+ import { usePlayhead, usePlayheadTimeline } from "./usePlayback";
30
+
31
+ /** A point of interest on the timeline — a capture, an event — drawn as a tick on the scrubber. */
32
+ export interface PlaybackMarker {
33
+ /** The sample the marker sits on. */
34
+ index: number;
35
+ /** What happens there; names the tick for assistive technology and its tooltip. */
36
+ label?: string | undefined;
37
+ /** The tick's colour. Defaults to `signal`. */
38
+ tone?: MeasureTone | undefined;
39
+ }
40
+
41
+ /** The speeds offered by default. */
42
+ export const DEFAULT_SPEEDS: readonly number[] = [0.25, 0.5, 1, 2, 4];
43
+
44
+ /** Props of `PlaybackBar`. */
45
+ export interface PlaybackBarProps {
46
+ /** Where playback is. The bar subscribes to it; seeking writes to it. */
47
+ playhead: Playhead;
48
+ /** Whether playback is running, controlled. */
49
+ playing: boolean;
50
+ /** Called with the requested playing state (the play/pause button, Space). */
51
+ onPlayingChange: (playing: boolean) => void;
52
+ /** The playback rate, controlled. Defaults to 1. */
53
+ speed?: number | undefined;
54
+ /** Called with the chosen rate. Without it the speed selector is not shown. */
55
+ onSpeedChange?: ((speed: number) => void) | undefined;
56
+ /** The rates the selector offers. Defaults to 0.25×, 0.5×, 1×, 2×, 4×. */
57
+ speeds?: readonly number[] | undefined;
58
+ /** Whether playback wraps at the end, controlled. */
59
+ loop?: boolean | undefined;
60
+ /** Called with the new loop state. Without it the loop toggle is not shown. */
61
+ onLoopChange?: ((loop: boolean) => void) | undefined;
62
+ /** Ticks on the scrubber, each a click target that seeks to it. */
63
+ markers?: readonly PlaybackMarker[] | undefined;
64
+ /** Called after a marker tick is clicked (the playhead has already moved to it). */
65
+ onMarkerSelect?: ((marker: PlaybackMarker) => void) | undefined;
66
+ /** Formats `t = k · dt` in seconds for the readout. Defaults to `"1.234 s"`. */
67
+ formatTime?: ((seconds: number) => string) | undefined;
68
+ /** Names the bar (a `toolbar`). Defaults to "Playback". */
69
+ "aria-label"?: string | undefined;
70
+ /** Merged with the bar's own classes through `cn`. */
71
+ className?: string | undefined;
72
+ }
73
+
74
+ /**
75
+ * The transport for a sampled timeline: jump to start, previous marker, step back,
76
+ * play/pause, step forward, next marker, jump to end; a scrubber over the samples with the
77
+ * markers as ticks; the time `t = k · dt`; the speed; loop.
78
+ *
79
+ * `playing`, `speed` and `loop` are controlled props. The position is the `playhead` store,
80
+ * which the bar subscribes to itself — so during playback only the bar re-renders. Drive the
81
+ * store with `usePlaybackClock`, and read `playhead.get()` in a render loop.
82
+ *
83
+ * A `role="toolbar"`. Keyboard, while focus is inside it: the scrubber is a slider (←/→ one
84
+ * sample, PageUp/PageDown ten, Home/End); on the buttons, ←/→ step one sample; Space
85
+ * toggles playback anywhere in the bar except on a button, where it presses the button. The
86
+ * root carries `data-playing` while playing and `data-empty` when the timeline has no samples.
87
+ */
88
+ export function PlaybackBar({
89
+ playhead,
90
+ playing,
91
+ onPlayingChange,
92
+ speed = 1,
93
+ onSpeedChange,
94
+ speeds = DEFAULT_SPEEDS,
95
+ loop = false,
96
+ onLoopChange,
97
+ markers = [],
98
+ onMarkerSelect,
99
+ formatTime = formatSeconds,
100
+ "aria-label": ariaLabel = "Playback",
101
+ className,
102
+ }: PlaybackBarProps) {
103
+ const density = useDensity();
104
+ const index = usePlayhead(playhead);
105
+ const { count, dt } = usePlayheadTimeline(playhead);
106
+ const last = Math.max(0, count - 1);
107
+ const empty = count === 0;
108
+
109
+ const sorted = [...markers].filter((m) => m.index >= 0 && m.index <= last).sort((a, b) => a.index - b.index);
110
+ const previousMarker = sorted.filter((m) => m.index < index).at(-1);
111
+ const nextMarker = sorted.find((m) => m.index > index);
112
+
113
+ const seek = (k: number) => playhead.set(k);
114
+
115
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
116
+ const target = event.target as HTMLElement;
117
+ const onButton = target.tagName === "BUTTON";
118
+ if (event.key === " " && !onButton && target.getAttribute("role") !== "combobox") {
119
+ event.preventDefault();
120
+ if (!empty) onPlayingChange(!playing);
121
+ } else if (onButton && (event.key === "ArrowLeft" || event.key === "ArrowRight")) {
122
+ event.preventDefault();
123
+ seek(index + (event.key === "ArrowRight" ? 1 : -1));
124
+ }
125
+ };
126
+
127
+ return (
128
+ <div
129
+ role="toolbar"
130
+ aria-label={ariaLabel}
131
+ data-playing={playing ? "" : undefined}
132
+ data-empty={empty ? "" : undefined}
133
+ onKeyDown={onKeyDown}
134
+ className={cn(
135
+ "flex w-full min-w-0 items-center bg-surface",
136
+ byDensity(density, "gap-3 px-3 py-2", "gap-2 px-2 py-1"),
137
+ className,
138
+ )}
139
+ >
140
+ <div className="flex shrink-0 items-center gap-0.5">
141
+ <BarButton label="Jump to start" onClick={() => seek(0)} disabled={empty || index === 0}>
142
+ <ChevronFirst className="size-4" aria-hidden />
143
+ </BarButton>
144
+ <BarButton
145
+ label="Previous marker"
146
+ onClick={() => previousMarker && seek(previousMarker.index)}
147
+ disabled={previousMarker === undefined}
148
+ >
149
+ <SkipBack className="size-4" aria-hidden />
150
+ </BarButton>
151
+ <BarButton label="Step back" onClick={() => seek(index - 1)} disabled={empty || index === 0}>
152
+ <StepBack className="size-4" aria-hidden />
153
+ </BarButton>
154
+ <BarButton
155
+ label={playing ? "Pause" : "Play"}
156
+ onClick={() => onPlayingChange(!playing)}
157
+ disabled={empty}
158
+ className="text-fg"
159
+ >
160
+ {playing ? <Pause className="size-4" aria-hidden /> : <Play className="size-4" aria-hidden />}
161
+ </BarButton>
162
+ <BarButton label="Step forward" onClick={() => seek(index + 1)} disabled={empty || index >= last}>
163
+ <StepForward className="size-4" aria-hidden />
164
+ </BarButton>
165
+ <BarButton
166
+ label="Next marker"
167
+ onClick={() => nextMarker && seek(nextMarker.index)}
168
+ disabled={nextMarker === undefined}
169
+ >
170
+ <SkipForward className="size-4" aria-hidden />
171
+ </BarButton>
172
+ <BarButton label="Jump to end" onClick={() => seek(last)} disabled={empty || index >= last}>
173
+ <ChevronLast className="size-4" aria-hidden />
174
+ </BarButton>
175
+ </div>
176
+
177
+ <div className="relative flex min-w-24 flex-1 flex-col justify-center">
178
+ {sorted.length > 0 && (
179
+ // The ticks sit on a rail above the track, positioned as Radix positions the thumb:
180
+ // its centre travels from half a thumb (7 px) in from either end.
181
+ <div className="relative h-2.5">
182
+ {sorted.map((marker) => (
183
+ <MarkerTick
184
+ key={`${marker.index}:${marker.label ?? ""}`}
185
+ marker={marker}
186
+ fraction={last === 0 ? 0 : marker.index / last}
187
+ time={formatTime(marker.index * dt)}
188
+ active={marker.index === index}
189
+ onClick={() => {
190
+ seek(marker.index);
191
+ onMarkerSelect?.(marker);
192
+ }}
193
+ />
194
+ ))}
195
+ </div>
196
+ )}
197
+ <Slider
198
+ value={index}
199
+ onValueChange={seek}
200
+ min={0}
201
+ max={last}
202
+ step={1}
203
+ disabled={empty}
204
+ aria-label="Playback position"
205
+ />
206
+ </div>
207
+
208
+ {/* Not an <output>: that is a live region, and this changes every frame. */}
209
+ <span className="shrink-0 font-mono text-xs whitespace-nowrap text-fg tabular-nums">
210
+ <span className="text-fg-subtle">t = </span>
211
+ {formatTime(index * dt)}
212
+ <span className="ml-2 text-fg-subtle">
213
+ {empty ? "–" : index}/{last}
214
+ </span>
215
+ </span>
216
+
217
+ {onSpeedChange && (
218
+ <Select
219
+ value={String(speed)}
220
+ onValueChange={(value) => value !== "" && onSpeedChange(Number(value))}
221
+ options={speeds.map((s) => ({ value: String(s), label: `${s}×` }))}
222
+ aria-label="Playback speed"
223
+ className={cn("w-20 shrink-0 font-mono", byDensity(density, "h-8", "h-7"))}
224
+ />
225
+ )}
226
+
227
+ {onLoopChange && (
228
+ <BarButton label="Loop" pressed={loop} onClick={() => onLoopChange(!loop)}>
229
+ <Repeat className="size-4" aria-hidden />
230
+ </BarButton>
231
+ )}
232
+ </div>
233
+ );
234
+ }
235
+
236
+ function MarkerTick({
237
+ marker,
238
+ fraction,
239
+ time,
240
+ active,
241
+ onClick,
242
+ }: {
243
+ marker: PlaybackMarker;
244
+ fraction: number;
245
+ time: string;
246
+ active: boolean;
247
+ onClick: () => void;
248
+ }) {
249
+ const name = marker.label ? `${marker.label} (${time})` : `Marker at ${time}`;
250
+ return (
251
+ <button
252
+ type="button"
253
+ // The previous/next-marker buttons are the keyboard's way to the markers; one tab stop
254
+ // per tick would bury the rest of the bar behind a long capture list.
255
+ tabIndex={-1}
256
+ title={name}
257
+ aria-label={name}
258
+ data-active={active ? "" : undefined}
259
+ onClick={onClick}
260
+ style={{ left: `calc(7px + ${fraction} * (100% - 14px))` }}
261
+ className="group absolute top-0 flex h-full w-2.5 -translate-x-1/2 cursor-pointer justify-center"
262
+ >
263
+ <span
264
+ aria-hidden
265
+ className="h-full w-0.5 rounded-full opacity-70 transition-opacity group-hover:opacity-100 group-data-active:w-1 group-data-active:opacity-100"
266
+ style={{ backgroundColor: toneColor(marker.tone) }}
267
+ />
268
+ </button>
269
+ );
270
+ }
271
+
272
+ /** Props of the bar's icon button. */
273
+ interface BarButtonProps
274
+ extends Omit<ComponentPropsWithRef<"button">, "type" | "title" | "aria-label" | "aria-pressed" | "children"> {
275
+ label: string;
276
+ pressed?: boolean | undefined;
277
+ children: ReactNode;
278
+ }
279
+
280
+ /** An icon button in the style of `@vitavision/stage2d`'s `StageButton`, sized by density. */
281
+ function BarButton({ label, pressed, className, children, ...props }: BarButtonProps) {
282
+ const density = useDensity();
283
+ return (
284
+ <button
285
+ {...props}
286
+ type="button"
287
+ title={label}
288
+ aria-label={label}
289
+ aria-pressed={pressed}
290
+ data-state={pressed === undefined ? undefined : pressed ? "on" : "off"}
291
+ className={cn(
292
+ "grid place-items-center rounded-control text-fg-muted transition-colors",
293
+ byDensity(density, "size-8", "size-7"),
294
+ "hover:bg-raised hover:text-fg disabled:pointer-events-none disabled:opacity-40",
295
+ pressed && "bg-signal/15 text-signal",
296
+ focusRing,
297
+ className,
298
+ )}
299
+ >
300
+ {children}
301
+ </button>
302
+ );
303
+ }