@vitavision/workbench 0.0.0-bootstrap.0 → 0.1.0

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,306 @@
1
+ /*
2
+ * Two panes and the divider between them.
3
+ *
4
+ * A studio screen is a handful of permanent surfaces — a tree, a viewport, an inspector, a
5
+ * timeline — whose relative size is the user's decision, not the layout's. The divider is
6
+ * therefore a real control: draggable, operable from the keyboard (the WAI-ARIA
7
+ * window-splitter pattern), announced with its position, and remembered across reloads
8
+ * when asked to be.
9
+ *
10
+ * One pane carries the size and the other takes the rest, so nesting composes: the rest of
11
+ * one split is simply another split. `AppShell` builds its side panels exactly that way.
12
+ */
13
+
14
+ import { useCallback, useId, useRef, useState } from "react";
15
+ import type {
16
+ CSSProperties,
17
+ KeyboardEvent,
18
+ PointerEvent as ReactPointerEvent,
19
+ ReactNode,
20
+ } from "react";
21
+
22
+ import { cn, focusRing } from "@vitavision/ui";
23
+
24
+ import {
25
+ type PaneSize,
26
+ type SizedPane,
27
+ type SplitOrientation,
28
+ clampSize,
29
+ readStoredSize,
30
+ resolveLimits,
31
+ resolveSize,
32
+ splitKeyAction,
33
+ writeStoredSize,
34
+ } from "./splitSize";
35
+
36
+ /** Props of `SplitPane`. */
37
+ export interface SplitPaneProps {
38
+ /**
39
+ * The two panes, in reading order (left then right, or top then bottom). Exactly two;
40
+ * nest another `SplitPane` in either for more.
41
+ */
42
+ children: readonly [ReactNode, ReactNode];
43
+ /**
44
+ * `horizontal` (the default) lays the panes side by side with a vertical divider;
45
+ * `vertical` stacks them with a horizontal one.
46
+ */
47
+ orientation?: SplitOrientation | undefined;
48
+ /** Which pane carries the size; the other takes the rest. Defaults to `start`. */
49
+ sizedPane?: SizedPane | undefined;
50
+ /** The sized pane's size in pixels, controlled. Pair with `onSizeChange`. */
51
+ size?: number | undefined;
52
+ /** The initial size when uncontrolled: pixels or a percentage. Defaults to `"50%"`. */
53
+ defaultSize?: PaneSize | undefined;
54
+ /** Called with the new size in pixels on every drag move and key press (0 when collapsed). */
55
+ onSizeChange?: ((size: number) => void) | undefined;
56
+ /** The sized pane's smallest open size: pixels or a percentage. Defaults to 0. */
57
+ minSize?: PaneSize | undefined;
58
+ /** The sized pane's largest size: pixels or a percentage. Defaults to `"100%"`. */
59
+ maxSize?: PaneSize | undefined;
60
+ /**
61
+ * Lets the sized pane close: dragging it below half its minimum snaps it shut, and Enter
62
+ * on the divider collapses it or restores the last open size.
63
+ */
64
+ collapsible?: boolean | undefined;
65
+ /** How far one arrow-key press moves the divider, in pixels (four times with Shift). Defaults to 16. */
66
+ step?: number | undefined;
67
+ /**
68
+ * Remember the size under this `localStorage` key, and start from it. Uncontrolled only:
69
+ * a controlled split's size is the caller's to keep.
70
+ */
71
+ storageKey?: string | undefined;
72
+ /** Names the divider for assistive technology. Defaults to "Resize panes". */
73
+ "aria-label"?: string | undefined;
74
+ /** Merged with the split's own classes through `cn`. */
75
+ className?: string | undefined;
76
+ }
77
+
78
+ /**
79
+ * Two panes with a draggable, keyboard-operable divider between them.
80
+ *
81
+ * The divider is a `role="separator"` focusable control carrying `aria-valuenow` (the sized
82
+ * pane's size in pixels), `aria-valuemin`/`aria-valuemax` and `aria-controls` (the sized
83
+ * pane). Arrow keys along the axis move it by `step` (Shift: four steps), Home/End give the
84
+ * sized pane its minimum/maximum, Enter collapses or restores a `collapsible` pane. Dragging
85
+ * uses pointer capture, so the drag survives the pointer leaving the divider.
86
+ *
87
+ * Fills its container (`h-full w-full`), so it nests. State is exposed as `data-orientation`
88
+ * on the root, `data-dragging` on the root and the divider while a drag is in progress, and
89
+ * `data-collapsed` on the root and the sized pane while it is closed.
90
+ */
91
+ export function SplitPane({
92
+ children,
93
+ orientation = "horizontal",
94
+ sizedPane = "start",
95
+ size: controlledSize,
96
+ defaultSize = "50%",
97
+ onSizeChange,
98
+ minSize = 0,
99
+ maxSize = "100%",
100
+ collapsible = false,
101
+ step = 16,
102
+ storageKey,
103
+ "aria-label": ariaLabel = "Resize panes",
104
+ className,
105
+ }: SplitPaneProps) {
106
+ const paneId = useId();
107
+ const horizontal = orientation === "horizontal";
108
+ const [length, setLength] = useState<number | null>(null);
109
+ const [internalSize, setInternalSize] = useState<number | null>(null);
110
+ const [dragging, setDragging] = useState(false);
111
+ const rootRef = useRef<HTMLDivElement | null>(null);
112
+ // The drag in progress: where it started, and the size it has reached. The reached size is
113
+ // kept here, not read back from state, because a pointer move's update is rendered at
114
+ // continuous priority and may not have landed when the pointer is released.
115
+ const dragRef = useRef<{ origin: number; start: number; length: number; reached: number } | null>(null);
116
+ const lastOpenRef = useRef<number | null>(null);
117
+
118
+ const limits = length === null ? null : resolveLimits(length, minSize, maxSize, collapsible);
119
+ const size =
120
+ controlledSize ??
121
+ internalSize ??
122
+ (length === null || limits === null ? null : clampSize(resolveSize(defaultSize, length), limits));
123
+ const collapsed = size === 0;
124
+ const controlled = controlledSize !== undefined;
125
+
126
+ /*
127
+ * Measure the split along its axis — synchronously on attach, so the first paint has the
128
+ * limits, then on every resize — and pick up a remembered size. A callback ref rather than
129
+ * an effect: the subscription lives exactly as long as the element.
130
+ */
131
+ const attach = useCallback(
132
+ (element: HTMLDivElement | null) => {
133
+ rootRef.current = element;
134
+ if (!element) return;
135
+ const measure = () => {
136
+ const rect = element.getBoundingClientRect();
137
+ setLength(horizontal ? rect.width : rect.height);
138
+ };
139
+ measure();
140
+ if (storageKey !== undefined && !controlled) {
141
+ const stored = readStoredSize(storageKey);
142
+ if (stored !== null) setInternalSize(stored);
143
+ }
144
+ if (typeof ResizeObserver === "undefined") return;
145
+ const observer = new ResizeObserver(measure);
146
+ observer.observe(element);
147
+ return () => observer.disconnect();
148
+ },
149
+ [horizontal, storageKey, controlled],
150
+ );
151
+
152
+ /** The live length and limits, measured now (a drag or a key press must not use stale ones). */
153
+ const measureNow = () => {
154
+ const element = rootRef.current;
155
+ const rect = element?.getBoundingClientRect();
156
+ const now = rect ? (horizontal ? rect.width : rect.height) : (length ?? 0);
157
+ return { length: now, limits: resolveLimits(now, minSize, maxSize, collapsible) };
158
+ };
159
+
160
+ /** Take a new size: state, the caller, and (on `commit`) storage. `changed` defaults to a comparison with the rendered size. */
161
+ const apply = (next: number, commit: boolean, changed = next !== size) => {
162
+ if (next > 0) lastOpenRef.current = next;
163
+ if (!controlled) setInternalSize(next);
164
+ if (changed) onSizeChange?.(next);
165
+ if (commit && storageKey !== undefined && !controlled) {
166
+ writeStoredSize(storageKey, next);
167
+ }
168
+ };
169
+
170
+ const coordinate = (event: ReactPointerEvent) => (horizontal ? event.clientX : event.clientY);
171
+
172
+ const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
173
+ if (event.button !== 0) return;
174
+ event.preventDefault();
175
+ const { length: now } = measureNow();
176
+ const current = size ?? 0;
177
+ dragRef.current = { origin: coordinate(event), start: current, length: now, reached: current };
178
+ event.currentTarget.setPointerCapture(event.pointerId);
179
+ event.currentTarget.focus();
180
+ setDragging(true);
181
+ };
182
+
183
+ const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
184
+ const drag = dragRef.current;
185
+ if (drag === null) return;
186
+ const delta = (coordinate(event) - drag.origin) * (sizedPane === "start" ? 1 : -1);
187
+ const next = clampSize(drag.start + delta, resolveLimits(drag.length, minSize, maxSize, collapsible));
188
+ if (next === drag.reached) return;
189
+ drag.reached = next;
190
+ // Compared with the drag's own last size above: the rendered one may lag behind.
191
+ apply(next, false, true);
192
+ };
193
+
194
+ const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
195
+ const drag = dragRef.current;
196
+ if (drag === null) return;
197
+ dragRef.current = null;
198
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
199
+ event.currentTarget.releasePointerCapture(event.pointerId);
200
+ }
201
+ setDragging(false);
202
+ if (drag.reached > 0) lastOpenRef.current = drag.reached;
203
+ if (storageKey !== undefined && !controlled) writeStoredSize(storageKey, drag.reached);
204
+ };
205
+
206
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
207
+ const { limits: now } = measureNow();
208
+ const current = size ?? 0;
209
+ const action = splitKeyAction(event.key, event.shiftKey, current, {
210
+ orientation,
211
+ sizedPane,
212
+ step,
213
+ limits: now,
214
+ });
215
+ if (action === null) return;
216
+ event.preventDefault();
217
+ if (action.type === "resize") {
218
+ apply(action.size, true);
219
+ } else if (current > 0) {
220
+ lastOpenRef.current = current;
221
+ apply(0, true);
222
+ } else {
223
+ apply(clampSize(lastOpenRef.current ?? now.min, { ...now, collapsible: false }), true);
224
+ }
225
+ };
226
+
227
+ // Before the first measurement (and on the server) the pane is sized by CSS alone, from
228
+ // the default; afterwards by the measured size. The limits stay in CSS too, so a window
229
+ // resize never pushes the pane outside them between two measurements.
230
+ const basis =
231
+ size !== null ? `${size}px` : typeof defaultSize === "number" ? `${defaultSize}px` : defaultSize;
232
+ const cssSize = (value: PaneSize) => (typeof value === "number" ? `${value}px` : value);
233
+ const sizedStyle: CSSProperties = {
234
+ flex: `0 0 ${basis}`,
235
+ ...(collapsed
236
+ ? {}
237
+ : horizontal
238
+ ? { minWidth: cssSize(minSize), maxWidth: cssSize(maxSize) }
239
+ : { minHeight: cssSize(minSize), maxHeight: cssSize(maxSize) }),
240
+ };
241
+
242
+ const [first, second] = children;
243
+ const paneClasses = "relative min-h-0 min-w-0 overflow-hidden";
244
+ const sized = (
245
+ <div
246
+ id={paneId}
247
+ style={sizedStyle}
248
+ className={paneClasses}
249
+ data-collapsed={collapsed ? "" : undefined}
250
+ // A closed pane keeps its content mounted (a tree keeps its expansion), but nothing in
251
+ // it may take focus or be read out.
252
+ inert={collapsed}
253
+ >
254
+ {sizedPane === "start" ? first : second}
255
+ </div>
256
+ );
257
+ const rest = (
258
+ <div className={cn(paneClasses, "flex-1 basis-0")}>{sizedPane === "start" ? second : first}</div>
259
+ );
260
+
261
+ return (
262
+ <div
263
+ ref={attach}
264
+ data-orientation={orientation}
265
+ data-dragging={dragging ? "" : undefined}
266
+ data-collapsed={collapsed ? "" : undefined}
267
+ className={cn(
268
+ "flex h-full min-h-0 w-full min-w-0",
269
+ horizontal ? "flex-row" : "flex-col",
270
+ dragging && (horizontal ? "cursor-col-resize select-none" : "cursor-row-resize select-none"),
271
+ className,
272
+ )}
273
+ >
274
+ {sizedPane === "start" ? sized : rest}
275
+ <div
276
+ role="separator"
277
+ tabIndex={0}
278
+ aria-label={ariaLabel}
279
+ // The separator's own orientation is across the split: side-by-side panes are divided
280
+ // by a vertical line.
281
+ aria-orientation={horizontal ? "vertical" : "horizontal"}
282
+ aria-controls={paneId}
283
+ aria-valuenow={size === null ? undefined : Math.round(size)}
284
+ aria-valuemin={limits === null ? undefined : collapsible ? 0 : Math.round(limits.min)}
285
+ aria-valuemax={limits === null ? undefined : Math.round(limits.max)}
286
+ data-dragging={dragging ? "" : undefined}
287
+ onPointerDown={onPointerDown}
288
+ onPointerMove={onPointerMove}
289
+ onPointerUp={endDrag}
290
+ onPointerCancel={endDrag}
291
+ onKeyDown={onKeyDown}
292
+ className={cn(
293
+ // A 1px rule with a wider invisible hit area on either side of it.
294
+ "relative z-10 shrink-0 touch-none bg-line transition-colors",
295
+ "before:absolute before:content-['']",
296
+ horizontal
297
+ ? "w-px cursor-col-resize before:inset-y-0 before:-right-1 before:-left-1"
298
+ : "h-px cursor-row-resize before:inset-x-0 before:-top-1 before:-bottom-1",
299
+ "hover:bg-signal data-dragging:bg-signal",
300
+ focusRing,
301
+ )}
302
+ />
303
+ {sizedPane === "start" ? rest : sized}
304
+ </div>
305
+ );
306
+ }
@@ -0,0 +1,149 @@
1
+ /*
2
+ * Where `toast()` shows up.
3
+ *
4
+ * Toasts are for news that does not need an answer — a file loaded, a bake finished, a
5
+ * worker failed in the background. Anything that must be acknowledged is a `Dialog`, and
6
+ * anything tied to one control is that control's `Field` error. So a toast never carries an
7
+ * action beyond dismissing it, it goes away by itself, and it holds still while someone is
8
+ * reading it (pointer over the stack, or focus inside it).
9
+ *
10
+ * The tones reuse the `Callout` vocabulary — the accent for a fact, the verdict colours for
11
+ * success, caveat and failure — on an opaque `overlay` surface, since a toast floats over
12
+ * whatever the viewport is drawing.
13
+ */
14
+
15
+ import { CircleCheck, CircleX, Info, TriangleAlert, X } from "lucide-react";
16
+ import { useEffect, useRef, useState, useSyncExternalStore } from "react";
17
+ import type { FocusEvent } from "react";
18
+
19
+ import { cn, focusRing } from "@vitavision/ui";
20
+
21
+ import { defaultToastStore, type ToastRecord, type ToastStore, type ToastTone } from "./toastStore";
22
+
23
+ const TONE: Record<ToastTone, { border: string; icon: string; Icon: typeof Info }> = {
24
+ info: { border: "border-signal/30", icon: "text-signal", Icon: Info },
25
+ success: { border: "border-normal/30", icon: "text-normal", Icon: CircleCheck },
26
+ warn: { border: "border-warn/30", icon: "text-warn", Icon: TriangleAlert },
27
+ error: { border: "border-defect/30", icon: "text-defect", Icon: CircleX },
28
+ };
29
+
30
+ const NO_TOASTS: readonly ToastRecord[] = [];
31
+
32
+ /** Props of `Toaster`. */
33
+ export interface ToasterProps {
34
+ /** The store to show. Defaults to the one behind `toast()`. */
35
+ store?: ToastStore | undefined;
36
+ /** How many toasts are shown at once; older ones wait. Defaults to 5. */
37
+ limit?: number | undefined;
38
+ /** Merged with the stack's own classes through `cn` (it is fixed to the bottom-right corner). */
39
+ className?: string | undefined;
40
+ }
41
+
42
+ /**
43
+ * The stack of notifications raised with `toast()`. Mount it once, near the root.
44
+ *
45
+ * Fixed to the bottom-right corner, newest at the bottom. Each toast dismisses itself after
46
+ * its `duration`; the countdown pauses while the pointer is over the stack or focus is inside
47
+ * it. A `section` landmark ("Notifications") holding a polite live region, so new toasts are
48
+ * announced; an `error` toast is a `role="alert"`, announced at once. Each toast carries
49
+ * `data-tone` and a "Dismiss" button.
50
+ */
51
+ export function Toaster({ store = defaultToastStore, limit = 5, className }: ToasterProps) {
52
+ const toasts = useSyncExternalStore(store.subscribe, store.getSnapshot, () => NO_TOASTS);
53
+ const [hovered, setHovered] = useState(false);
54
+ const [focused, setFocused] = useState(false);
55
+ const shown = toasts.slice(-Math.max(1, limit));
56
+
57
+ const onBlur = (event: FocusEvent<HTMLElement>) => {
58
+ if (!event.currentTarget.contains(event.relatedTarget)) setFocused(false);
59
+ };
60
+
61
+ return (
62
+ <section
63
+ aria-label="Notifications"
64
+ onPointerEnter={() => setHovered(true)}
65
+ onPointerLeave={() => setHovered(false)}
66
+ onFocus={() => setFocused(true)}
67
+ onBlur={onBlur}
68
+ className={cn(
69
+ "pointer-events-none fixed right-4 bottom-4 z-50 w-80 max-w-[calc(100vw-2rem)]",
70
+ className,
71
+ )}
72
+ >
73
+ <ol aria-live="polite" className="flex flex-col gap-2">
74
+ {shown.map((record) => (
75
+ <ToastItem
76
+ key={record.id}
77
+ record={record}
78
+ paused={hovered || focused}
79
+ onDismiss={() => store.dismiss(record.id)}
80
+ />
81
+ ))}
82
+ </ol>
83
+ </section>
84
+ );
85
+ }
86
+
87
+ function ToastItem({
88
+ record,
89
+ paused,
90
+ onDismiss,
91
+ }: {
92
+ record: ToastRecord;
93
+ paused: boolean;
94
+ onDismiss: () => void;
95
+ }) {
96
+ const { border, icon, Icon } = TONE[record.tone];
97
+ // What is left of the countdown, carried across pauses; restarted when the toast is
98
+ // replaced in place (a new record under the same id).
99
+ const remainingRef = useRef({ record, ms: record.duration });
100
+ const dismissRef = useRef(onDismiss);
101
+ useEffect(() => {
102
+ dismissRef.current = onDismiss;
103
+ });
104
+
105
+ useEffect(() => {
106
+ if (remainingRef.current.record !== record) remainingRef.current = { record, ms: record.duration };
107
+ if (paused || !Number.isFinite(remainingRef.current.ms)) return;
108
+ const started = Date.now();
109
+ const timer = setTimeout(() => dismissRef.current(), remainingRef.current.ms);
110
+ return () => {
111
+ clearTimeout(timer);
112
+ remainingRef.current.ms = Math.max(0, remainingRef.current.ms - (Date.now() - started));
113
+ };
114
+ }, [paused, record]);
115
+
116
+ return (
117
+ // The `alert` role sits on the toast inside the list item, not on the `<li>`: an item with
118
+ // another role is no longer a list item, and the list would be malformed.
119
+ <li className="pointer-events-auto">
120
+ <div
121
+ role={record.tone === "error" ? "alert" : undefined}
122
+ data-tone={record.tone}
123
+ className={cn(
124
+ "flex items-start gap-2.5 rounded-panel border bg-overlay px-3 py-2.5 text-sm leading-snug shadow-lg shadow-black/25",
125
+ "transition-[opacity,translate] duration-200 starting:translate-y-2 starting:opacity-0",
126
+ border,
127
+ )}
128
+ >
129
+ <Icon className={cn("mt-0.5 size-4 shrink-0", icon)} aria-hidden />
130
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
131
+ <p className="font-medium text-fg">{record.title}</p>
132
+ {record.description && <p className="text-fg-muted">{record.description}</p>}
133
+ </div>
134
+ <button
135
+ type="button"
136
+ aria-label="Dismiss"
137
+ title="Dismiss"
138
+ onClick={onDismiss}
139
+ className={cn(
140
+ "-mr-1 grid size-6 shrink-0 place-items-center rounded-control text-fg-subtle transition-colors hover:bg-raised hover:text-fg",
141
+ focusRing,
142
+ )}
143
+ >
144
+ <X className="size-3.5" aria-hidden />
145
+ </button>
146
+ </div>
147
+ </li>
148
+ );
149
+ }