@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.
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +89 -0
- package/dist/index.d.ts +671 -0
- package/dist/index.js +1469 -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/Toaster.tsx +149 -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/toastStore.ts +128 -0
- package/src/components/treeModel.ts +188 -0
- package/src/components/usePlayback.ts +105 -0
- package/src/index.ts +67 -0
- package/src/styles.css +7 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Where playback is, as a store outside React.
|
|
3
|
+
*
|
|
4
|
+
* A sampled timeline plays at display rate, and the things that follow it — a robot's joint
|
|
5
|
+
* angles, a camera frustum, a highlighted capture — are drawn by a render loop, not by
|
|
6
|
+
* React. If the current frame lived in React state, every frame of playback would re-render
|
|
7
|
+
* every component that reads it, including the whole scene graph. So it lives here: a tiny
|
|
8
|
+
* store a render loop reads with `get()` at no cost, and that React components subscribe to
|
|
9
|
+
* (through `usePlayhead`) only where they display it — the playback bar, a time readout.
|
|
10
|
+
*
|
|
11
|
+
* The store holds an integer sample index and nothing else that changes per frame. The
|
|
12
|
+
* sub-sample position real-time playback needs is the clock's business (`advance`,
|
|
13
|
+
* `usePlaybackClock`), not the store's, so a reader never sees a fractional frame.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A sampled timeline's current position: an external store shared by React and render loops.
|
|
18
|
+
*
|
|
19
|
+
* Every function member may be called detached (`const { get } = playhead`), which is how
|
|
20
|
+
* `useSyncExternalStore` and a render loop hold them.
|
|
21
|
+
*/
|
|
22
|
+
export interface Playhead {
|
|
23
|
+
/** The current sample index, an integer in `0 … count − 1` (0 when `count` is 0). Cheap: call it every frame. */
|
|
24
|
+
readonly get: () => number;
|
|
25
|
+
/**
|
|
26
|
+
* Move to sample `k`. Rounded to an integer and clamped to `0 … count − 1`; listeners are
|
|
27
|
+
* notified only if the index changed.
|
|
28
|
+
*/
|
|
29
|
+
readonly set: (k: number) => void;
|
|
30
|
+
/**
|
|
31
|
+
* Be told when the index or the timeline changes.
|
|
32
|
+
*
|
|
33
|
+
* @returns The unsubscribe function.
|
|
34
|
+
*/
|
|
35
|
+
readonly subscribe: (listener: () => void) => () => void;
|
|
36
|
+
/** How many samples the timeline has. */
|
|
37
|
+
readonly count: number;
|
|
38
|
+
/** The time between samples, in seconds. Sample `k` is at `t = k · dt`. */
|
|
39
|
+
readonly dt: number;
|
|
40
|
+
/**
|
|
41
|
+
* Swap in a new timeline — a newly loaded or re-baked scenario — keeping the one store
|
|
42
|
+
* every subscriber already holds. The index is clamped into the new range (not reset:
|
|
43
|
+
* call `set(0)` for that). Listeners are notified if anything changed.
|
|
44
|
+
*/
|
|
45
|
+
readonly setTimeline: (count: number, dt: number) => void;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* A playhead over `count` samples spaced `dt` seconds apart, starting at sample 0.
|
|
50
|
+
*
|
|
51
|
+
* Create one per app (not per render — keep it in a `useState` initialiser or module
|
|
52
|
+
* scope), hand it to `PlaybackBar` and to the render loop, and replace its timeline with
|
|
53
|
+
* `setTimeline` when a new scenario loads.
|
|
54
|
+
*
|
|
55
|
+
* @param count - The number of samples (a non-negative integer).
|
|
56
|
+
* @param dt - Seconds between samples (positive).
|
|
57
|
+
* @returns The store.
|
|
58
|
+
*/
|
|
59
|
+
export function createPlayhead(count: number, dt: number): Playhead {
|
|
60
|
+
let index = 0;
|
|
61
|
+
let timeline = checkTimeline(count, dt);
|
|
62
|
+
const listeners = new Set<() => void>();
|
|
63
|
+
const notify = () => {
|
|
64
|
+
for (const listener of [...listeners]) listener();
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
get: () => index,
|
|
69
|
+
set: (k) => {
|
|
70
|
+
const next = clampIndex(k, timeline.count);
|
|
71
|
+
if (next === index) return;
|
|
72
|
+
index = next;
|
|
73
|
+
notify();
|
|
74
|
+
},
|
|
75
|
+
subscribe: (listener) => {
|
|
76
|
+
listeners.add(listener);
|
|
77
|
+
return () => {
|
|
78
|
+
listeners.delete(listener);
|
|
79
|
+
};
|
|
80
|
+
},
|
|
81
|
+
get count() {
|
|
82
|
+
return timeline.count;
|
|
83
|
+
},
|
|
84
|
+
get dt() {
|
|
85
|
+
return timeline.dt;
|
|
86
|
+
},
|
|
87
|
+
setTimeline: (nextCount, nextDt) => {
|
|
88
|
+
const next = checkTimeline(nextCount, nextDt);
|
|
89
|
+
const nextIndex = clampIndex(index, next.count);
|
|
90
|
+
if (next.count === timeline.count && next.dt === timeline.dt && nextIndex === index) return;
|
|
91
|
+
timeline = next;
|
|
92
|
+
index = nextIndex;
|
|
93
|
+
notify();
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function checkTimeline(count: number, dt: number): { count: number; dt: number } {
|
|
99
|
+
if (!Number.isInteger(count) || count < 0) {
|
|
100
|
+
throw new RangeError(`playhead: count must be a non-negative integer, got ${count}`);
|
|
101
|
+
}
|
|
102
|
+
if (!(dt > 0) || !Number.isFinite(dt)) {
|
|
103
|
+
throw new RangeError(`playhead: dt must be a positive number of seconds, got ${dt}`);
|
|
104
|
+
}
|
|
105
|
+
return { count, dt };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A sample index made legal: rounded, and clamped to `0 … count − 1`.
|
|
110
|
+
*
|
|
111
|
+
* @param k - Any number (`NaN` reads as 0).
|
|
112
|
+
* @param count - The number of samples.
|
|
113
|
+
* @returns The index; 0 when `count` is 0.
|
|
114
|
+
*/
|
|
115
|
+
export function clampIndex(k: number, count: number): number {
|
|
116
|
+
if (count <= 0 || Number.isNaN(k)) return 0;
|
|
117
|
+
return Math.min(count - 1, Math.max(0, Math.round(k)));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The outcome of one clock step: the new fractional position, and whether playback ran off the end. */
|
|
121
|
+
export interface AdvanceResult {
|
|
122
|
+
/** The new position in samples (fractional); the index to show is its floor. */
|
|
123
|
+
position: number;
|
|
124
|
+
/** True when a non-looping timeline reached its last sample on this step. */
|
|
125
|
+
ended: boolean;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* One step of real-time playback, in samples.
|
|
130
|
+
*
|
|
131
|
+
* Each sample is shown for `dt`: a looping timeline has period `count · dt` and wraps from
|
|
132
|
+
* the last sample to the first; a non-looping one stops on the last sample and reports
|
|
133
|
+
* `ended`. The position is fractional so that playback slower than one sample per frame
|
|
134
|
+
* still advances.
|
|
135
|
+
*
|
|
136
|
+
* @param position - The current position in samples (fractional).
|
|
137
|
+
* @param delta - How many samples to advance (elapsed seconds × speed ÷ dt); not negative.
|
|
138
|
+
* @param count - The number of samples.
|
|
139
|
+
* @param loop - Whether to wrap at the end.
|
|
140
|
+
* @returns The new position and whether playback ended.
|
|
141
|
+
*/
|
|
142
|
+
export function advance(position: number, delta: number, count: number, loop: boolean): AdvanceResult {
|
|
143
|
+
if (count <= 1) return { position: 0, ended: !loop };
|
|
144
|
+
const next = position + Math.max(0, delta);
|
|
145
|
+
if (loop) return { position: next % count, ended: false };
|
|
146
|
+
const last = count - 1;
|
|
147
|
+
return next >= last ? { position: last, ended: true } : { position: next, ended: false };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The default time readout: seconds with millisecond resolution, `"1.234 s"`.
|
|
152
|
+
*
|
|
153
|
+
* @param seconds - The time.
|
|
154
|
+
* @returns The formatted time.
|
|
155
|
+
*/
|
|
156
|
+
export function formatSeconds(seconds: number): string {
|
|
157
|
+
return `${seconds.toFixed(3)} s`;
|
|
158
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The arithmetic behind `SplitPane`: resolving sizes given in pixels or percent, clamping a
|
|
3
|
+
* drag or a key press to the pane's limits, and remembering a size across reloads.
|
|
4
|
+
*
|
|
5
|
+
* Kept out of the component so every rule — which key moves the divider which way, where a
|
|
6
|
+
* collapsible pane snaps shut — is tested without a DOM.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A pane size: CSS pixels as a number, or a share of the split's length as a percentage
|
|
11
|
+
* string (`"30%"`).
|
|
12
|
+
*/
|
|
13
|
+
export type PaneSize = number | `${number}%`;
|
|
14
|
+
|
|
15
|
+
/** The limits a `SplitPane`'s sized pane is held to, resolved to pixels. */
|
|
16
|
+
export interface SplitLimits {
|
|
17
|
+
/** The smallest open size, in pixels. */
|
|
18
|
+
min: number;
|
|
19
|
+
/** The largest size, in pixels. */
|
|
20
|
+
max: number;
|
|
21
|
+
/** Whether the pane may close to 0 below `min`. */
|
|
22
|
+
collapsible: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A size in pixels.
|
|
27
|
+
*
|
|
28
|
+
* @param size - Pixels, or a percentage of `length`.
|
|
29
|
+
* @param length - The split's length along its axis, in pixels.
|
|
30
|
+
* @returns The size in pixels (never negative).
|
|
31
|
+
*/
|
|
32
|
+
export function resolveSize(size: PaneSize, length: number): number {
|
|
33
|
+
const px = typeof size === "number" ? size : (Number.parseFloat(size) / 100) * length;
|
|
34
|
+
return Number.isFinite(px) ? Math.max(0, px) : 0;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The limits in pixels for a split of `length`. `max` never exceeds `length`, and `min`
|
|
39
|
+
* never exceeds `max`.
|
|
40
|
+
*
|
|
41
|
+
* @param length - The split's length along its axis, in pixels.
|
|
42
|
+
* @param minSize - The smallest open size. Defaults to 0.
|
|
43
|
+
* @param maxSize - The largest size. Defaults to the whole length.
|
|
44
|
+
* @param collapsible - Whether the pane may close below `minSize`.
|
|
45
|
+
* @returns The resolved limits.
|
|
46
|
+
*/
|
|
47
|
+
export function resolveLimits(
|
|
48
|
+
length: number,
|
|
49
|
+
minSize: PaneSize = 0,
|
|
50
|
+
maxSize: PaneSize = "100%",
|
|
51
|
+
collapsible = false,
|
|
52
|
+
): SplitLimits {
|
|
53
|
+
const max = Math.min(resolveSize(maxSize, length), Math.max(0, length));
|
|
54
|
+
const min = Math.min(resolveSize(minSize, length), max);
|
|
55
|
+
return { min, max, collapsible };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Hold a proposed size to the limits. A collapsible pane dragged below half its minimum
|
|
60
|
+
* snaps shut (0); between half the minimum and the minimum it stays at the minimum.
|
|
61
|
+
*
|
|
62
|
+
* @param size - The proposed size, in pixels.
|
|
63
|
+
* @param limits - The resolved limits.
|
|
64
|
+
* @returns The size to apply, in pixels, rounded to whole pixels.
|
|
65
|
+
*/
|
|
66
|
+
export function clampSize(size: number, limits: SplitLimits): number {
|
|
67
|
+
if (limits.collapsible && size < limits.min / 2) return 0;
|
|
68
|
+
return Math.round(Math.min(limits.max, Math.max(limits.min, size)));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Which way a `SplitPane` lays out its two panes. */
|
|
72
|
+
export type SplitOrientation = "horizontal" | "vertical";
|
|
73
|
+
|
|
74
|
+
/** Which of the two panes carries the explicit size; the other takes the rest. */
|
|
75
|
+
export type SizedPane = "start" | "end";
|
|
76
|
+
|
|
77
|
+
/** What a key press on the divider asks for. */
|
|
78
|
+
export type SplitKeyAction =
|
|
79
|
+
| { type: "resize"; size: number }
|
|
80
|
+
| { type: "toggle-collapse" };
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The divider's keyboard (the WAI-ARIA window-splitter pattern).
|
|
84
|
+
*
|
|
85
|
+
* The arrow keys along the split's axis move the divider the way they point — so the sized
|
|
86
|
+
* pane grows or shrinks depending on which side it is on — by `step`, or four steps with
|
|
87
|
+
* Shift. Home gives the sized pane its minimum, End its maximum, and Enter collapses or
|
|
88
|
+
* restores a collapsible pane.
|
|
89
|
+
*
|
|
90
|
+
* @param key - `KeyboardEvent.key`.
|
|
91
|
+
* @param shift - Whether Shift is held.
|
|
92
|
+
* @param size - The sized pane's current size, in pixels.
|
|
93
|
+
* @param options - The layout, the step in pixels and the resolved limits.
|
|
94
|
+
* @returns The action, or `null` when the key is not the divider's.
|
|
95
|
+
*/
|
|
96
|
+
export function splitKeyAction(
|
|
97
|
+
key: string,
|
|
98
|
+
shift: boolean,
|
|
99
|
+
size: number,
|
|
100
|
+
options: { orientation: SplitOrientation; sizedPane: SizedPane; step: number; limits: SplitLimits },
|
|
101
|
+
): SplitKeyAction | null {
|
|
102
|
+
const { orientation, sizedPane, step, limits } = options;
|
|
103
|
+
const [back, forward] =
|
|
104
|
+
orientation === "horizontal" ? ["ArrowLeft", "ArrowRight"] : ["ArrowUp", "ArrowDown"];
|
|
105
|
+
const grow = sizedPane === "start" ? 1 : -1;
|
|
106
|
+
const delta = shift ? step * 4 : step;
|
|
107
|
+
|
|
108
|
+
switch (key) {
|
|
109
|
+
case forward:
|
|
110
|
+
return { type: "resize", size: clampOpen(size + grow * delta, limits) };
|
|
111
|
+
case back:
|
|
112
|
+
return { type: "resize", size: clampOpen(size - grow * delta, limits) };
|
|
113
|
+
case "Home":
|
|
114
|
+
return { type: "resize", size: Math.round(limits.min) };
|
|
115
|
+
case "End":
|
|
116
|
+
return { type: "resize", size: Math.round(limits.max) };
|
|
117
|
+
case "Enter":
|
|
118
|
+
return limits.collapsible ? { type: "toggle-collapse" } : null;
|
|
119
|
+
default:
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A key step never snaps a pane shut (that is Enter's job): clamp to the open range. */
|
|
125
|
+
function clampOpen(size: number, limits: SplitLimits): number {
|
|
126
|
+
return Math.round(Math.min(limits.max, Math.max(limits.min, size)));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The size stored under `key`, if any.
|
|
131
|
+
*
|
|
132
|
+
* @param key - The `localStorage` key.
|
|
133
|
+
* @returns The stored size in pixels, or `null` when nothing valid is stored or storage
|
|
134
|
+
* cannot be read (private browsing, the server).
|
|
135
|
+
*/
|
|
136
|
+
export function readStoredSize(key: string): number | null {
|
|
137
|
+
try {
|
|
138
|
+
const raw = window.localStorage.getItem(key);
|
|
139
|
+
if (raw === null) return null;
|
|
140
|
+
const value = Number(raw);
|
|
141
|
+
return Number.isFinite(value) && value >= 0 ? value : null;
|
|
142
|
+
} catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Remember a size under `key`. Failures (storage full, disabled, the server) are ignored: a
|
|
149
|
+
* size that is not remembered is not worth an error.
|
|
150
|
+
*
|
|
151
|
+
* @param key - The `localStorage` key.
|
|
152
|
+
* @param size - The size in pixels.
|
|
153
|
+
*/
|
|
154
|
+
export function writeStoredSize(key: string, size: number): void {
|
|
155
|
+
try {
|
|
156
|
+
window.localStorage.setItem(key, String(Math.round(size)));
|
|
157
|
+
} catch {
|
|
158
|
+
// Nothing to do: the size simply is not remembered.
|
|
159
|
+
}
|
|
160
|
+
}
|