@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.
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +89 -0
- package/dist/index.d.ts +580 -0
- package/dist/index.js +1288 -0
- package/dist/index.js.map +1 -0
- package/package.json +52 -3
- package/src/components/AppShell.tsx +141 -0
- package/src/components/FileDrop.tsx +223 -0
- package/src/components/PlaybackBar.tsx +303 -0
- package/src/components/SplitPane.tsx +306 -0
- package/src/components/TreeView.tsx +244 -0
- package/src/components/dropFiles.ts +131 -0
- package/src/components/playhead.ts +158 -0
- package/src/components/splitSize.ts +160 -0
- package/src/components/treeModel.ts +188 -0
- package/src/components/usePlayback.ts +105 -0
- package/src/index.ts +70 -0
- package/src/styles.css +7 -0
|
@@ -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,244 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* A hierarchy you can walk with the keyboard.
|
|
3
|
+
*
|
|
4
|
+
* Built for the navigator column of a studio — a robot cell's frame tree, world → robots →
|
|
5
|
+
* links → rigs → cameras — where the tree is data the app already has, the icons are the
|
|
6
|
+
* app's own, and selection is shared with a viewport that can also pick things. So the tree
|
|
7
|
+
* is data-driven, selection is controlled, and selecting something hidden opens the way to it.
|
|
8
|
+
*
|
|
9
|
+
* Rendered flat: one `treeitem` per visible row, carrying its level, position and set size
|
|
10
|
+
* (the WAI-ARIA tree pattern's "flat" form). The focus ring then belongs to one row rather
|
|
11
|
+
* than to a subtree, and the keyboard contract is a function over the same list the DOM is
|
|
12
|
+
* — see `treeModel.ts`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { ChevronRight } from "lucide-react";
|
|
16
|
+
import { useEffect, useRef, useState } from "react";
|
|
17
|
+
import type { KeyboardEvent, MouseEvent } from "react";
|
|
18
|
+
|
|
19
|
+
import { byDensity, cn, useDensity } from "@vitavision/ui";
|
|
20
|
+
|
|
21
|
+
import {
|
|
22
|
+
type TreeNode,
|
|
23
|
+
type TreeRow,
|
|
24
|
+
ancestorIds,
|
|
25
|
+
parentIds,
|
|
26
|
+
treeKeyAction,
|
|
27
|
+
visibleRows,
|
|
28
|
+
} from "./treeModel";
|
|
29
|
+
|
|
30
|
+
/** Props of `TreeView`. */
|
|
31
|
+
export interface TreeViewProps {
|
|
32
|
+
/** The roots of the tree. */
|
|
33
|
+
nodes: readonly TreeNode[];
|
|
34
|
+
/** The selected node's id, controlled; `null` or absent for none. */
|
|
35
|
+
selectedId?: string | null | undefined;
|
|
36
|
+
/** Called with the node's id (and the node) on click, Enter or Space. Not called for a disabled node. */
|
|
37
|
+
onSelect?: ((id: string, node: TreeNode) => void) | undefined;
|
|
38
|
+
/** The expanded parents' ids, controlled. Pair with `onExpandedChange`. */
|
|
39
|
+
expanded?: readonly string[] | undefined;
|
|
40
|
+
/** The initially expanded parents' ids, when uncontrolled. */
|
|
41
|
+
defaultExpanded?: readonly string[] | undefined;
|
|
42
|
+
/** Start with every parent expanded, when uncontrolled (overrides `defaultExpanded`). */
|
|
43
|
+
defaultExpandAll?: boolean | undefined;
|
|
44
|
+
/** Called with the new set of expanded ids whenever a parent opens or closes. */
|
|
45
|
+
onExpandedChange?: ((expanded: string[]) => void) | undefined;
|
|
46
|
+
/** Names the tree for assistive technology. */
|
|
47
|
+
"aria-label": string;
|
|
48
|
+
/** Merged with the tree's own classes through `cn`. */
|
|
49
|
+
className?: string | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A data-driven tree (the WAI-ARIA tree pattern) with single selection.
|
|
54
|
+
*
|
|
55
|
+
* Keyboard: the tree is one Tab stop (roving `tabindex`). ↓/↑ move between visible rows, →
|
|
56
|
+
* expands a parent or enters it, ← collapses a parent or goes up to its parent, Home/End jump
|
|
57
|
+
* to the ends, Enter/Space select, `*` expands the focused row's siblings, and a letter jumps
|
|
58
|
+
* to the next row starting with it. Clicking a row selects it; clicking its chevron toggles it.
|
|
59
|
+
*
|
|
60
|
+
* Selection is controlled (`selectedId`/`onSelect`). When `selectedId` changes to a node
|
|
61
|
+
* inside a collapsed parent, its ancestors are expanded (through `onExpandedChange` when
|
|
62
|
+
* `expanded` is controlled) and the row is scrolled into view — so a pick in a viewport can
|
|
63
|
+
* drive the tree.
|
|
64
|
+
*
|
|
65
|
+
* Each row is a `treeitem` with `aria-level`, `aria-posinset`, `aria-setsize`,
|
|
66
|
+
* `aria-selected` and, for parents, `aria-expanded`; also `data-selected` and, for parents,
|
|
67
|
+
* `data-state` (`open`/`closed`). Row height follows the density in force.
|
|
68
|
+
*/
|
|
69
|
+
export function TreeView({
|
|
70
|
+
nodes,
|
|
71
|
+
selectedId = null,
|
|
72
|
+
onSelect,
|
|
73
|
+
expanded: controlledExpanded,
|
|
74
|
+
defaultExpanded,
|
|
75
|
+
defaultExpandAll = false,
|
|
76
|
+
onExpandedChange,
|
|
77
|
+
"aria-label": ariaLabel,
|
|
78
|
+
className,
|
|
79
|
+
}: TreeViewProps) {
|
|
80
|
+
const density = useDensity();
|
|
81
|
+
const [internalExpanded, setInternalExpanded] = useState<readonly string[]>(() =>
|
|
82
|
+
defaultExpandAll ? parentIds(nodes) : (defaultExpanded ?? []),
|
|
83
|
+
);
|
|
84
|
+
const expandedIds = controlledExpanded ?? internalExpanded;
|
|
85
|
+
const expandedSet = new Set(expandedIds);
|
|
86
|
+
const rows = visibleRows(nodes, expandedSet);
|
|
87
|
+
const [focusedId, setFocusedId] = useState<string | null>(null);
|
|
88
|
+
const rowElementsRef = useRef(new Map<string, HTMLDivElement>());
|
|
89
|
+
|
|
90
|
+
const setExpanded = (next: readonly string[]) => {
|
|
91
|
+
if (controlledExpanded === undefined) setInternalExpanded(next);
|
|
92
|
+
onExpandedChange?.([...next]);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const toggle = (id: string, open: boolean) => {
|
|
96
|
+
if (open === expandedSet.has(id)) return;
|
|
97
|
+
setExpanded(open ? [...expandedIds, id] : expandedIds.filter((other) => other !== id));
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// Reveal a selection made elsewhere: open its ancestors and bring its row into view.
|
|
101
|
+
const latestRef = useRef({ nodes, expandedIds, setExpanded });
|
|
102
|
+
useEffect(() => {
|
|
103
|
+
latestRef.current = { nodes, expandedIds, setExpanded };
|
|
104
|
+
});
|
|
105
|
+
useEffect(() => {
|
|
106
|
+
if (selectedId === null) return;
|
|
107
|
+
const { nodes: tree, expandedIds: open, setExpanded: update } = latestRef.current;
|
|
108
|
+
const missing = ancestorIds(tree, selectedId).filter((id) => !open.includes(id));
|
|
109
|
+
if (missing.length > 0) update([...open, ...missing]);
|
|
110
|
+
}, [selectedId]);
|
|
111
|
+
useEffect(() => {
|
|
112
|
+
if (selectedId === null) return;
|
|
113
|
+
const element = rowElementsRef.current.get(selectedId);
|
|
114
|
+
// `scrollIntoView` is absent in some test DOMs.
|
|
115
|
+
if (typeof element?.scrollIntoView === "function") element.scrollIntoView({ block: "nearest" });
|
|
116
|
+
}, [selectedId, rows.length]);
|
|
117
|
+
|
|
118
|
+
const isVisible = (id: string | null) => id !== null && rows.some((row) => row.node.id === id);
|
|
119
|
+
const tabStop = isVisible(focusedId) ? focusedId : isVisible(selectedId) ? selectedId : (rows[0]?.node.id ?? null);
|
|
120
|
+
|
|
121
|
+
const focusRow = (id: string) => {
|
|
122
|
+
setFocusedId(id);
|
|
123
|
+
rowElementsRef.current.get(id)?.focus();
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const select = (row: TreeRow) => {
|
|
127
|
+
if (!row.node.disabled) onSelect?.(row.node.id, row.node);
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
|
|
131
|
+
if (event.altKey || event.ctrlKey || event.metaKey) return;
|
|
132
|
+
const id = (event.target as HTMLElement).dataset["treeId"];
|
|
133
|
+
if (id === undefined) return;
|
|
134
|
+
const action = treeKeyAction(rows, id, event.key);
|
|
135
|
+
if (action === null) return;
|
|
136
|
+
event.preventDefault();
|
|
137
|
+
switch (action.type) {
|
|
138
|
+
case "focus":
|
|
139
|
+
focusRow(action.id);
|
|
140
|
+
break;
|
|
141
|
+
case "expand":
|
|
142
|
+
toggle(action.id, true);
|
|
143
|
+
break;
|
|
144
|
+
case "collapse":
|
|
145
|
+
toggle(action.id, false);
|
|
146
|
+
break;
|
|
147
|
+
case "select": {
|
|
148
|
+
const row = rows.find((candidate) => candidate.node.id === action.id);
|
|
149
|
+
if (row) select(row);
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
case "expand-siblings":
|
|
153
|
+
setExpanded([...expandedIds, ...action.ids]);
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const onChevron = (event: MouseEvent, row: TreeRow) => {
|
|
159
|
+
event.stopPropagation();
|
|
160
|
+
toggle(row.node.id, !row.isExpanded);
|
|
161
|
+
focusRow(row.node.id);
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
return (
|
|
165
|
+
<div
|
|
166
|
+
role="tree"
|
|
167
|
+
aria-label={ariaLabel}
|
|
168
|
+
onKeyDown={onKeyDown}
|
|
169
|
+
className={cn("flex flex-col py-1 select-none", className)}
|
|
170
|
+
>
|
|
171
|
+
{rows.map((row) => {
|
|
172
|
+
const { node } = row;
|
|
173
|
+
const selected = node.id === selectedId;
|
|
174
|
+
return (
|
|
175
|
+
<div
|
|
176
|
+
key={node.id}
|
|
177
|
+
ref={(element) => {
|
|
178
|
+
if (element) rowElementsRef.current.set(node.id, element);
|
|
179
|
+
else rowElementsRef.current.delete(node.id);
|
|
180
|
+
}}
|
|
181
|
+
role="treeitem"
|
|
182
|
+
aria-level={row.level}
|
|
183
|
+
aria-posinset={row.posInSet}
|
|
184
|
+
aria-setsize={row.setSize}
|
|
185
|
+
aria-selected={selected}
|
|
186
|
+
aria-expanded={row.isParent ? row.isExpanded : undefined}
|
|
187
|
+
aria-disabled={node.disabled || undefined}
|
|
188
|
+
tabIndex={node.id === tabStop ? 0 : -1}
|
|
189
|
+
data-tree-id={node.id}
|
|
190
|
+
data-selected={selected ? "" : undefined}
|
|
191
|
+
data-state={row.isParent ? (row.isExpanded ? "open" : "closed") : undefined}
|
|
192
|
+
onFocus={(event) => {
|
|
193
|
+
if (event.target === event.currentTarget) setFocusedId(node.id);
|
|
194
|
+
}}
|
|
195
|
+
onClick={() => {
|
|
196
|
+
focusRow(node.id);
|
|
197
|
+
select(row);
|
|
198
|
+
}}
|
|
199
|
+
style={{ paddingLeft: `calc(${row.level - 1} * 0.875rem + 0.25rem)` }}
|
|
200
|
+
className={cn(
|
|
201
|
+
"mx-1 flex shrink-0 cursor-default items-center gap-1.5 rounded-control pr-2 text-fg transition-colors",
|
|
202
|
+
"outline-none focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-signal",
|
|
203
|
+
byDensity(density, "h-7 text-sm", "h-6 text-xs"),
|
|
204
|
+
selected ? "bg-signal/12" : "hover:bg-raised",
|
|
205
|
+
node.disabled && "text-fg-subtle",
|
|
206
|
+
)}
|
|
207
|
+
>
|
|
208
|
+
{row.isParent ? (
|
|
209
|
+
<span
|
|
210
|
+
aria-hidden
|
|
211
|
+
onClick={(event) => onChevron(event, row)}
|
|
212
|
+
className="grid size-4 shrink-0 place-items-center rounded-sm text-fg-subtle hover:text-fg"
|
|
213
|
+
>
|
|
214
|
+
<ChevronRight
|
|
215
|
+
className={cn("size-3.5 transition-transform", row.isExpanded && "rotate-90")}
|
|
216
|
+
/>
|
|
217
|
+
</span>
|
|
218
|
+
) : (
|
|
219
|
+
<span aria-hidden className="size-4 shrink-0" />
|
|
220
|
+
)}
|
|
221
|
+
{node.icon !== undefined && (
|
|
222
|
+
<span
|
|
223
|
+
aria-hidden
|
|
224
|
+
className={cn(
|
|
225
|
+
"grid shrink-0 place-items-center [&>svg]:size-3.5",
|
|
226
|
+
selected ? "text-signal" : "text-fg-muted",
|
|
227
|
+
)}
|
|
228
|
+
>
|
|
229
|
+
{node.icon}
|
|
230
|
+
</span>
|
|
231
|
+
)}
|
|
232
|
+
<span className="min-w-0 flex-1 truncate">{node.label}</span>
|
|
233
|
+
{node.meta !== undefined && (
|
|
234
|
+
// On the selected row's tint both `fg-subtle` and `fg-muted` fall below AA at this size.
|
|
235
|
+
<span className={cn("shrink-0 font-mono text-[11px]", selected ? "text-fg" : "text-fg-subtle")}>
|
|
236
|
+
{node.meta}
|
|
237
|
+
</span>
|
|
238
|
+
)}
|
|
239
|
+
</div>
|
|
240
|
+
);
|
|
241
|
+
})}
|
|
242
|
+
</div>
|
|
243
|
+
);
|
|
244
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* What `FileDrop` does with a drop: which files match `accept`, and what a dropped folder
|
|
3
|
+
* contains.
|
|
4
|
+
*
|
|
5
|
+
* The browser enforces `accept` only in the file picker, and only as a hint; a drop brings
|
|
6
|
+
* whatever was dragged. So the filter is applied here, to both routes. And a dropped folder
|
|
7
|
+
* arrives as a zero-byte "file" unless its entries are walked — which is how a scenario
|
|
8
|
+
* folder (a scene, a scenario, its meshes) is opened in one gesture.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Whether a file matches an `accept` string, as `<input type="file" accept>` reads it:
|
|
13
|
+
* comma-separated extensions (`.json`), MIME types (`application/json`) and MIME wildcards
|
|
14
|
+
* (`image/*`). Matching is case-insensitive.
|
|
15
|
+
*
|
|
16
|
+
* @param file - The file's name and MIME type.
|
|
17
|
+
* @param accept - The accept string; empty or absent accepts everything.
|
|
18
|
+
* @returns Whether the file is accepted.
|
|
19
|
+
*/
|
|
20
|
+
export function acceptsFile(file: { name: string; type: string }, accept: string | undefined): boolean {
|
|
21
|
+
const tokens = (accept ?? "")
|
|
22
|
+
.split(",")
|
|
23
|
+
.map((token) => token.trim().toLowerCase())
|
|
24
|
+
.filter((token) => token !== "");
|
|
25
|
+
if (tokens.length === 0) return true;
|
|
26
|
+
const name = file.name.toLowerCase();
|
|
27
|
+
const type = file.type.toLowerCase();
|
|
28
|
+
return tokens.some((token) => {
|
|
29
|
+
if (token.startsWith(".")) return name.endsWith(token);
|
|
30
|
+
if (token.endsWith("/*")) return type.startsWith(token.slice(0, -1));
|
|
31
|
+
return type === token;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Split files by `accept`.
|
|
37
|
+
*
|
|
38
|
+
* @param files - The candidates.
|
|
39
|
+
* @param accept - The accept string.
|
|
40
|
+
* @returns The accepted files and the rejected ones, each in their original order.
|
|
41
|
+
*/
|
|
42
|
+
export function partitionFiles(
|
|
43
|
+
files: readonly File[],
|
|
44
|
+
accept: string | undefined,
|
|
45
|
+
): { accepted: File[]; rejected: File[] } {
|
|
46
|
+
const accepted: File[] = [];
|
|
47
|
+
const rejected: File[] = [];
|
|
48
|
+
for (const file of files) (acceptsFile(file, accept) ? accepted : rejected).push(file);
|
|
49
|
+
return { accepted, rejected };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Whether a drag carries files (rather than text or a link) — the only drags `FileDrop`
|
|
54
|
+
* reacts to.
|
|
55
|
+
*
|
|
56
|
+
* @param dataTransfer - The drag's data, or `null`.
|
|
57
|
+
* @returns Whether `Files` is among its types.
|
|
58
|
+
*/
|
|
59
|
+
export function carriesFiles(dataTransfer: Pick<DataTransfer, "types"> | null): boolean {
|
|
60
|
+
return dataTransfer !== null && Array.from(dataTransfer.types).includes("Files");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The part of the File and Directory Entries API a drop walk needs (`webkitGetAsEntry`). */
|
|
64
|
+
export interface DropEntry {
|
|
65
|
+
/** A file (`FileSystemFileEntry`). */
|
|
66
|
+
isFile: boolean;
|
|
67
|
+
/** A folder (`FileSystemDirectoryEntry`). */
|
|
68
|
+
isDirectory: boolean;
|
|
69
|
+
/** The entry's own name. */
|
|
70
|
+
name: string;
|
|
71
|
+
/** The entry's path from the drop root, with a leading `/`. */
|
|
72
|
+
fullPath: string;
|
|
73
|
+
/** A file entry's contents, as a `File`. */
|
|
74
|
+
file?: (success: (file: File) => void, failure?: (error: unknown) => void) => void;
|
|
75
|
+
/** A folder entry's reader; `readEntries` yields the children in batches, then an empty one. */
|
|
76
|
+
createReader?: () => {
|
|
77
|
+
readEntries: (success: (entries: DropEntry[]) => void, failure?: (error: unknown) => void) => void;
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Every file in a drop, with dropped folders walked recursively.
|
|
83
|
+
*
|
|
84
|
+
* Files found inside a folder carry `webkitRelativePath` (`scene/meshes/base.glb`), as the
|
|
85
|
+
* files of `<input webkitdirectory>` do, so both routes give the same shape. Where the entries
|
|
86
|
+
* API is missing, the drop's plain file list is returned.
|
|
87
|
+
*
|
|
88
|
+
* @param dataTransfer - The drop's data.
|
|
89
|
+
* @returns The files, in the order the browser listed them.
|
|
90
|
+
*/
|
|
91
|
+
export async function collectDroppedFiles(
|
|
92
|
+
dataTransfer: Pick<DataTransfer, "files" | "items">,
|
|
93
|
+
): Promise<File[]> {
|
|
94
|
+
// Everything is read before the first `await`: a drop's data is emptied once its event
|
|
95
|
+
// handler returns.
|
|
96
|
+
const plain = Array.from(dataTransfer.files);
|
|
97
|
+
const entries = Array.from(dataTransfer.items ?? [])
|
|
98
|
+
.filter((item) => item.kind === "file")
|
|
99
|
+
.map((item) => (typeof item.webkitGetAsEntry === "function" ? (item.webkitGetAsEntry() as DropEntry | null) : null));
|
|
100
|
+
// No folder among them (or no entries API): the plain list is already the answer.
|
|
101
|
+
if (!entries.some((entry) => entry?.isDirectory)) return plain;
|
|
102
|
+
const files: File[] = [];
|
|
103
|
+
for (const entry of entries) if (entry) await walkEntry(entry, files);
|
|
104
|
+
return files;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function walkEntry(entry: DropEntry, out: File[]): Promise<void> {
|
|
108
|
+
if (entry.isFile && entry.file) {
|
|
109
|
+
const read = entry.file.bind(entry);
|
|
110
|
+
const file = await new Promise<File>((resolve, reject) => read(resolve, reject));
|
|
111
|
+
const path = entry.fullPath.replace(/^\//, "");
|
|
112
|
+
out.push(path.includes("/") ? withRelativePath(file, path) : file);
|
|
113
|
+
} else if (entry.isDirectory && entry.createReader) {
|
|
114
|
+
const reader = entry.createReader();
|
|
115
|
+
// `readEntries` returns a directory in batches (100 in Chromium) until an empty one.
|
|
116
|
+
for (;;) {
|
|
117
|
+
const batch = await new Promise<DropEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));
|
|
118
|
+
if (batch.length === 0) break;
|
|
119
|
+
for (const child of batch) await walkEntry(child, out);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The file, carrying `webkitRelativePath` — a read-only accessor on `File.prototype`,
|
|
126
|
+
* shadowed here on the instance.
|
|
127
|
+
*/
|
|
128
|
+
function withRelativePath(file: File, path: string): File {
|
|
129
|
+
Object.defineProperty(file, "webkitRelativePath", { value: path, configurable: true });
|
|
130
|
+
return file;
|
|
131
|
+
}
|