reifyui 0.9.0 → 0.10.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.
@@ -1,46 +1,58 @@
1
- // A timeline: lanes of clips against a ruler, with a playhead.
1
+ // A timeline you can edit: lanes of clips against a ruler, with a playhead, trim handles, split,
2
+ // and drag to reorder.
2
3
  //
3
4
  // ONE NUMBER IS THE COORDINATE SYSTEM. `pps` — pixels per second — converts time to x everywhere:
4
- // the ruler's ticks, a clip's width, the playhead's position, the scrub gesture's inverse. Two
5
- // places computing the same conversion is how a ruler and the blocks under it come to disagree,
6
- // which is the one thing a timeline cannot do and still be read.
5
+ // the ruler's ticks, a clip's width, the playhead, every gesture's inverse. Two places computing
6
+ // that conversion is how a ruler and the blocks under it come to disagree, which is the one thing
7
+ // a timeline cannot do and still be read.
7
8
  //
8
- // WHAT THIS COMPONENT KNOWS NOTHING ABOUT: video, audio, files, agents, or where a clip came
9
- // from. It takes lanes of {start, duration} and draws them. Everything product-specific — what a
10
- // clip means, what its artwork is, whether removing one is allowed — arrives as data or a
11
- // callback. That is what lets the same component hold a film's cut, a job's phases, or a
12
- // conversation's turns.
9
+ // THE HOST OWNS THE DOCUMENT. Every gesture ends in a callback carrying SECONDS — onTrim, onSplit,
10
+ // onMoveClip, onDeleteClip — and nothing here mutates anything. That is what lets the same
11
+ // component drive a film's cut, a job's phases or a conversation's turns: it knows about time and
12
+ // blocks and nothing about what a block means. It also puts undo where the document is.
13
13
  //
14
14
  // TIME THAT IS NOT KNOWN IS NOT DRAWN AS TIME. A clip whose duration is null gets a fixed
15
- // placeholder width and a hatched fill, never a guessed length: the whole value of drawing to
16
- // scale is that the width is a measurement, and one invented width poisons every reading of the
17
- // ruler above it.
15
+ // placeholder width and a hatched fill, never a guessed length — a width here is a measurement,
16
+ // and one invented width makes every reading of the ruler above it worthless. Such a clip also
17
+ // gets no trim handles: there is nothing to trim against a length nobody knows.
18
+ //
19
+ // ARTWORK IS ONE REAL FRAME, REPEATED. A filmstrip in a desktop editor shows successive frames
20
+ // pulled from the file. There is no frame-extraction service behind this component, so it tiles
21
+ // the ONE poster it was given at a fixed tile size rather than inventing distinct frames —
22
+ // visibly the same image, which is honest about what is known, and still reads as a strip.
18
23
  import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
19
24
 
20
25
  export const TL_MIN_PPS = 4;
21
- export const TL_MAX_PPS = 240;
26
+ export const TL_MAX_PPS = 400;
22
27
  export const TL_DEFAULT_PPS = 26;
23
28
  /** The sticky lane-label gutter. Lanes start at this x. */
24
- export const TL_HEAD_W = 76;
25
- /** Width for a clip whose duration nobody has measured yet. */
29
+ export const TL_HEAD_W = 84;
30
+ /** Snap magnetism in screen px. Alt bypasses it, the convention everywhere. */
31
+ export const TL_SNAP_PX = 6;
32
+ /** Nothing may be trimmed shorter than this. */
33
+ export const TL_MIN_CLIP_S = 0.1;
34
+ /** Pointer travel below which a press is a click, not a drag. */
35
+ const CLICK_SLOP = 3;
36
+
37
+ const LANE_H = 56;
38
+ const CLIP_INSET = 4;
26
39
  const UNKNOWN_W = 46;
27
- const MIN_CLIP_W = 26;
28
- const LANE_H = 48;
40
+ const MIN_CLIP_W = 18;
29
41
 
30
42
  const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
31
43
 
32
- /* ── ruler maths (pure) ─────────────────────────────────────────────────────────────────────── */
44
+ /* ── ruler + label maths (pure) ─────────────────────────────────────────────────────────────── */
33
45
 
34
46
  const TICK_STEPS = [0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600];
35
47
 
36
- /** The smallest step whose labels stay ~64px apart at this zoom, so ticks thin out as you zoom
37
- * out instead of collapsing into a grey bar. */
48
+ /** The smallest step whose labels stay ~64px apart, so ticks thin out as you zoom out instead of
49
+ * collapsing into a grey bar. */
38
50
  export function majorTickStep(pps) {
39
51
  for (const s of TICK_STEPS) if (s * pps >= 64) return s;
40
52
  return TICK_STEPS[TICK_STEPS.length - 1];
41
53
  }
42
54
 
43
- /** m:ss, with tenths only when the step is sub-second — a label finer than the tick is noise. */
55
+ /** m:ss, with tenths only when the step is sub-second — a label finer than its tick is noise. */
44
56
  export function tickLabel(t, step = 1) {
45
57
  const m = Math.floor(t / 60);
46
58
  const s = t - m * 60;
@@ -51,8 +63,7 @@ export function tickLabel(t, step = 1) {
51
63
  return frac > 0 ? `${base}.${frac}` : base;
52
64
  }
53
65
 
54
- /** m:ss for a duration. Returns '' for anything unmeasured, never '0:00' — a zero that means
55
- * "unknown" is the lie this component exists to avoid. */
66
+ /** m:ss for a duration, and '' for anything unmeasured — never '0:00' for an unknown. */
56
67
  export function durationLabel(seconds) {
57
68
  if (!Number.isFinite(seconds) || seconds < 0) return '';
58
69
  const m = Math.floor(seconds / 60);
@@ -60,39 +71,62 @@ export function durationLabel(seconds) {
60
71
  return `${m}:${String(s).padStart(2, '0')}`;
61
72
  }
62
73
 
63
- /** Where each clip sits when a lane is a sequence rather than a set of placed items: each clip
64
- * starts where the last one ended. Unmeasured clips advance by their drawn width so the lane
65
- * stays honest about what follows them. */
74
+ /** Precise enough to trim against: m:ss.t */
75
+ function exactLabel(seconds) {
76
+ if (!Number.isFinite(seconds)) return '—';
77
+ const m = Math.floor(Math.max(0, seconds) / 60);
78
+ const s = Math.max(0, seconds) - m * 60;
79
+ return `${m}:${s < 10 ? '0' : ''}${s.toFixed(1)}`;
80
+ }
81
+
82
+ /** Where each clip sits. A sequential lane runs its clips end to end (a cut); a placed lane puts
83
+ * each at its own `start`. An unmeasured clip advances by its drawn width, so what follows it
84
+ * stays honest about being approximate. */
66
85
  function layout(clips, pps, sequential) {
67
86
  let cursor = 0;
68
- return clips.map((c) => {
87
+ return clips.map((c, i) => {
69
88
  const known = Number.isFinite(c.duration);
70
89
  const w = known ? Math.max(MIN_CLIP_W, c.duration * pps) : UNKNOWN_W;
71
- const x = sequential ? cursor * pps : (c.start || 0) * pps;
90
+ const t0 = sequential ? cursor : (c.start || 0);
72
91
  if (sequential) cursor += known ? c.duration : UNKNOWN_W / pps;
73
- return { clip: c, x, w, known };
92
+ return { clip: c, i, t0, x: t0 * pps, w, known };
74
93
  });
75
94
  }
76
95
 
96
+ /** The nearest snap target within `tol` seconds, or the raw value. */
97
+ function snapTo(t, targets, tol) {
98
+ let best = null;
99
+ let bestD = tol;
100
+ for (const s of targets) {
101
+ const d = Math.abs(s - t);
102
+ if (d <= bestD) { bestD = d; best = s; }
103
+ }
104
+ return best === null ? { value: t, guide: null } : { value: best, guide: best };
105
+ }
106
+
77
107
  /* ── the component ──────────────────────────────────────────────────────────────────────────── */
78
108
 
79
109
  export function Timeline({
80
110
  tracks = [],
81
- /** Seconds. Drives the playhead; pass it from whatever is playing. */
82
111
  currentTime = 0,
83
- /** Called with a time in seconds when the ruler or lane background is scrubbed. */
84
112
  onSeek,
85
113
  onSelectClip,
86
114
  selectedClipId = null,
87
- /** Rendered at the right of each clip on hover — e.g. remove, reorder. (clip, index) => node */
88
- clipActions,
89
- /** Rendered after the last clip of a lane, e.g. an add button. (track) => node */
115
+ /** (clip, edge:'start'|'end', newDurationSeconds, track). Fires once, on release. */
116
+ onTrim,
117
+ /** (clip, atSecondsFromClipStart, track). */
118
+ onSplit,
119
+ /** Sequential lane: (clip, toIndex, track). Placed lane: (clip, newStartSeconds, track). */
120
+ onMoveClip,
121
+ onDeleteClip,
90
122
  laneAppend,
91
123
  zoomStorageKey = null,
124
+ snapStorageKey = null,
92
125
  emptyLabel = 'Nothing here yet.',
93
126
  className = '',
94
127
  }) {
95
128
  const scroller = useRef(null);
129
+ const innerRef = useRef(null);
96
130
  const [pps, setPps] = useState(() => {
97
131
  if (zoomStorageKey && typeof window !== 'undefined') {
98
132
  const n = parseFloat(window.localStorage.getItem(zoomStorageKey) || '');
@@ -100,25 +134,35 @@ export function Timeline({
100
134
  }
101
135
  return TL_DEFAULT_PPS;
102
136
  });
103
- // Anchoring: keep the time under the pointer (or the viewport centre) still while zooming, so
104
- // zoom feels like moving a lens rather than being teleported.
137
+ const [snapping, setSnapping] = useState(() => (
138
+ snapStorageKey && typeof window !== 'undefined'
139
+ ? window.localStorage.getItem(snapStorageKey) !== '0' : true));
140
+ /** The gesture in flight. A ref because pointer handlers must see it synchronously. */
141
+ const gesture = useRef(null);
142
+ /** What the gesture is doing right now: live preview geometry + annotation. */
143
+ const [drag, setDrag] = useState(null);
105
144
  const anchor = useRef(null);
106
145
 
107
146
  const rows = useMemo(
108
- () => tracks.map((t) => ({ ...t, laid: layout(t.clips || [], pps, t.sequential !== false) })),
147
+ () => tracks.map((t) => ({ ...t, sequential: t.sequential !== false,
148
+ laid: layout(t.clips || [], pps, t.sequential !== false) })),
109
149
  [tracks, pps]);
110
150
 
111
151
  const contentSeconds = useMemo(() => {
112
152
  let end = 0;
113
- for (const t of rows) {
114
- for (const { clip, x, w } of t.laid) {
115
- void clip;
116
- end = Math.max(end, (x + w) / pps);
117
- }
118
- }
153
+ for (const t of rows) for (const l of t.laid) end = Math.max(end, l.t0 + l.w / pps);
119
154
  return end;
120
155
  }, [rows, pps]);
121
156
 
157
+ /** Every clip edge, zero, and the playhead: what a drag snaps to. */
158
+ const snapTimes = useMemo(() => {
159
+ const out = [0, currentTime];
160
+ for (const t of rows) for (const l of t.laid) { out.push(l.t0); out.push(l.t0 + l.w / pps); }
161
+ return out;
162
+ }, [rows, pps, currentTime]);
163
+
164
+ /* ── zoom ─────────────────────────────────────────────────────────────────────────────────── */
165
+
122
166
  const setZoom = useCallback((next, clientX) => {
123
167
  const v = clamp(next, TL_MIN_PPS, TL_MAX_PPS);
124
168
  const el = scroller.current;
@@ -133,6 +177,30 @@ export function Timeline({
133
177
  }
134
178
  }, [pps, zoomStorageKey]);
135
179
 
180
+ const fitPps = useCallback((seconds) => {
181
+ const el = scroller.current;
182
+ if (!el || !(seconds > 0)) return null;
183
+ const room = el.clientWidth - TL_HEAD_W - 56;
184
+ return room > 0 ? clamp(room / seconds, TL_MIN_PPS, TL_MAX_PPS) : null;
185
+ }, []);
186
+
187
+ const fit = useCallback(() => {
188
+ const v = fitPps(contentSeconds);
189
+ if (v !== null) { setPps(v); if (scroller.current) scroller.current.scrollLeft = 0; }
190
+ }, [fitPps, contentSeconds]);
191
+
192
+ // Fit ONCE, when there is first something to fit: a one-second clip at a fixed default is a
193
+ // sliver that reads as a broken control. Once, not on every change — re-fitting under someone
194
+ // who just zoomed is the control fighting them. A stored zoom wins; they chose it.
195
+ const fitted = useRef(false);
196
+ useLayoutEffect(() => {
197
+ if (fitted.current || !(contentSeconds > 0)) return;
198
+ if (zoomStorageKey && typeof window !== 'undefined'
199
+ && window.localStorage.getItem(zoomStorageKey)) { fitted.current = true; return; }
200
+ const v = fitPps(contentSeconds);
201
+ if (v !== null) { fitted.current = true; setPps(v); }
202
+ }, [contentSeconds, fitPps, zoomStorageKey]);
203
+
136
204
  useLayoutEffect(() => {
137
205
  const a = anchor.current;
138
206
  if (!a || !scroller.current) return;
@@ -140,7 +208,6 @@ export function Timeline({
140
208
  scroller.current.scrollLeft = Math.max(0, TL_HEAD_W + a.t * pps - a.vx);
141
209
  }, [pps]);
142
210
 
143
- // Cmd/Ctrl+wheel and trackpad pinch zoom around the pointer, the way every editor does.
144
211
  useEffect(() => {
145
212
  const el = scroller.current;
146
213
  if (!el) return undefined;
@@ -154,53 +221,169 @@ export function Timeline({
154
221
  }, [pps, setZoom]);
155
222
 
156
223
  const timeAt = useCallback((clientX) => {
157
- const el = scroller.current;
224
+ const el = innerRef.current;
158
225
  if (!el) return 0;
159
- const rect = el.getBoundingClientRect();
160
- return Math.max(0, (el.scrollLeft + (clientX - rect.left) - TL_HEAD_W) / pps);
226
+ return Math.max(0, (clientX - el.getBoundingClientRect().left - TL_HEAD_W) / pps);
161
227
  }, [pps]);
162
228
 
163
- // Scrubbing: press anywhere on the ruler and drag. Pointer capture means the gesture survives
164
- // leaving the element, which is what makes a drag feel attached to the cursor.
165
- const onScrub = useCallback((e) => {
166
- if (!onSeek) return;
167
- e.currentTarget.setPointerCapture?.(e.pointerId);
168
- onSeek(timeAt(e.clientX));
169
- const move = (ev) => onSeek(timeAt(ev.clientX));
229
+ /* ── gestures ─────────────────────────────────────────────────────────────────────────────── */
230
+
231
+ /** ONE pointer pipeline for scrub, trim and move. They differ in what they compute, not in how
232
+ * the press, the movement threshold, the listeners and the release are handled. Writing that
233
+ * three times is how one of them ends up without its cleanup and leaves the document mid-edit
234
+ * when the pointer goes up outside the window. */
235
+ const beginGesture = useCallback((e, spec) => {
236
+ e.preventDefault();
237
+ e.stopPropagation();
238
+ gesture.current = { ...spec, startX: e.clientX, active: false, value: null };
239
+ const move = (ev) => {
240
+ const cur = gesture.current;
241
+ if (!cur) return;
242
+ if (!cur.active && Math.abs(ev.clientX - cur.startX) < CLICK_SLOP) return;
243
+ cur.active = true;
244
+ let t = timeAt(ev.clientX);
245
+ let guide = null;
246
+ if (snapping && !ev.altKey && cur.kind !== 'scrub') {
247
+ const r = snapTo(t, cur.snapTimes || snapTimes, TL_SNAP_PX / pps);
248
+ t = r.value; guide = r.guide;
249
+ }
250
+ cur.value = t;
251
+ if (cur.kind === 'scrub') onSeek?.(t);
252
+ else setDrag(cur.preview ? { ...cur.preview(t), guide } : { guide });
253
+ };
170
254
  const up = () => {
171
255
  window.removeEventListener('pointermove', move);
172
256
  window.removeEventListener('pointerup', up);
257
+ document.body.classList.remove('rui-tl-gesturing');
258
+ const cur = gesture.current;
259
+ gesture.current = null;
260
+ setDrag(null);
261
+ if (cur?.active && cur.value !== null) cur.commit?.(cur.value);
262
+ else cur?.click?.();
173
263
  };
264
+ document.body.classList.add('rui-tl-gesturing');
174
265
  window.addEventListener('pointermove', move);
175
266
  window.addEventListener('pointerup', up);
176
- }, [onSeek, timeAt]);
267
+ }, [timeAt, snapping, snapTimes, pps, onSeek]);
268
+
269
+ const onScrub = useCallback((e) => {
270
+ if (!onSeek) return;
271
+ onSeek(timeAt(e.clientX));
272
+ beginGesture(e, { kind: 'scrub' });
273
+ }, [onSeek, timeAt, beginGesture]);
274
+
275
+ /* ── split ────────────────────────────────────────────────────────────────────────────────── */
276
+
277
+ /** The clip the playhead is inside, far enough in that both halves would be legal. */
278
+ const splitTarget = useMemo(() => {
279
+ if (!onSplit) return null;
280
+ for (const track of rows) {
281
+ for (const l of track.laid) {
282
+ if (!l.known) continue;
283
+ if (currentTime > l.t0 + TL_MIN_CLIP_S && currentTime < l.t0 + l.clip.duration - TL_MIN_CLIP_S) {
284
+ return { track, l };
285
+ }
286
+ }
287
+ }
288
+ return null;
289
+ }, [rows, currentTime, onSplit]);
290
+
291
+ const doSplit = useCallback(() => {
292
+ if (!splitTarget) return;
293
+ onSplit(splitTarget.l.clip, currentTime - splitTarget.l.t0, splitTarget.track);
294
+ }, [splitTarget, currentTime, onSplit]);
295
+
296
+ const selected = useMemo(() => {
297
+ for (const track of rows) for (const l of track.laid) {
298
+ if (l.clip.id === selectedClipId) return { track, l };
299
+ }
300
+ return null;
301
+ }, [rows, selectedClipId]);
177
302
 
178
303
  const onKeyDown = useCallback((e) => {
304
+ const tag = e.target?.tagName;
305
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target?.isContentEditable) return;
179
306
  if (e.key === '+' || e.key === '=') { e.preventDefault(); setZoom(pps * 1.35); }
180
- if (e.key === '-' || e.key === '_') { e.preventDefault(); setZoom(pps / 1.35); }
181
- }, [pps, setZoom]);
307
+ else if (e.key === '-' || e.key === '_') { e.preventDefault(); setZoom(pps / 1.35); }
308
+ else if (e.key === 'b' || e.key === 'B') { e.preventDefault(); doSplit(); }
309
+ else if ((e.key === 'Delete' || e.key === 'Backspace') && selected && onDeleteClip) {
310
+ e.preventDefault(); onDeleteClip(selected.l.clip, selected.track);
311
+ }
312
+ }, [pps, setZoom, doSplit, selected, onDeleteClip]);
313
+
314
+ const toggleSnap = useCallback(() => {
315
+ setSnapping((v) => {
316
+ const next = !v;
317
+ if (snapStorageKey && typeof window !== 'undefined') {
318
+ try { window.localStorage.setItem(snapStorageKey, next ? '1' : '0'); } catch { /* ignore */ }
319
+ }
320
+ return next;
321
+ });
322
+ }, [snapStorageKey]);
323
+
324
+ /* ── render ───────────────────────────────────────────────────────────────────────────────── */
182
325
 
183
326
  const major = majorTickStep(pps);
184
327
  const minor = major / 5;
185
- const laneW = Math.max(contentSeconds * pps + 120, 240);
328
+ const laneW = Math.max(contentSeconds * pps + 140, 320);
186
329
  const ticks = [];
187
330
  for (let t = 0; t <= contentSeconds + major; t += major) ticks.push(t);
188
331
 
189
332
  return (
190
- <div className={`rui-tl ${className}`} onKeyDown={onKeyDown} tabIndex={-1}>
333
+ <div className={`rui-tl ${className}`} onKeyDown={onKeyDown} tabIndex={0}>
334
+ {/* ── toolbar ─────────────────────────────────────────────────────────────────────────
335
+ The timeline's commands live in a bar, not in a pill floating over the lanes: chrome
336
+ hovering in the corner of the content reads as debris. Every disabled control says WHY,
337
+ because one that is off without a reason looks broken. */}
338
+ <div className="rui-tl-bar">
339
+ {onSplit && (
340
+ <button type="button" className="rui-tl-btn" onClick={doSplit} disabled={!splitTarget}
341
+ title={splitTarget ? 'Split at the playhead (B)'
342
+ : 'Move the playhead inside a clip to split it'}>
343
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
344
+ strokeWidth="2" strokeLinecap="round" aria-hidden="true">
345
+ <circle cx="6" cy="6" r="3" /><circle cx="6" cy="18" r="3" />
346
+ <line x1="20" y1="4" x2="8.12" y2="15.88" />
347
+ <line x1="14.47" y1="14.48" x2="20" y2="20" />
348
+ <line x1="8.12" y1="8.12" x2="12" y2="12" />
349
+ </svg>
350
+ <span>Split</span>
351
+ </button>
352
+ )}
353
+ {onDeleteClip && (
354
+ <button type="button" className="rui-tl-btn" disabled={!selected}
355
+ onClick={() => selected && onDeleteClip(selected.l.clip, selected.track)}
356
+ title={selected ? 'Remove the selected clip' : 'Select a clip to remove it'}>
357
+ Remove
358
+ </button>
359
+ )}
360
+ <button type="button" className={`rui-tl-btn${snapping ? ' is-on' : ''}`}
361
+ onClick={toggleSnap} aria-pressed={snapping}
362
+ title="Snap to clip edges and the playhead. Hold Alt while dragging to bypass.">
363
+ Snap
364
+ </button>
365
+ <span className="rui-tl-time" aria-label="Playhead position">{exactLabel(currentTime)}</span>
366
+ <span className="rui-tl-spacer" />
367
+ <button type="button" className="rui-tl-btn rui-tl-icon" onClick={() => setZoom(pps / 1.35)}
368
+ disabled={pps <= TL_MIN_PPS + 1e-6} aria-label="Zoom out" title="Zoom out (−)">−</button>
369
+ <button type="button" className="rui-tl-btn rui-tl-icon" onClick={() => setZoom(pps * 1.35)}
370
+ disabled={pps >= TL_MAX_PPS - 1e-6} aria-label="Zoom in" title="Zoom in (+)">+</button>
371
+ <button type="button" className="rui-tl-btn" onClick={fit} disabled={!(contentSeconds > 0)}
372
+ title="Fit the whole timeline in the panel">Fit</button>
373
+ </div>
374
+
191
375
  <div className="rui-tl-scroll" ref={scroller}>
192
- <div className="rui-tl-inner" style={{ width: TL_HEAD_W + laneW }}>
376
+ <div className="rui-tl-inner" ref={innerRef} style={{ width: TL_HEAD_W + laneW }}>
193
377
 
194
- {/* ── ruler ────────────────────────────────────────────────────────────────────── */}
378
+ {/* ── ruler ──────────────────────────────────────────────────────────────────────── */}
195
379
  <div className="rui-tl-row rui-tl-rulerrow">
196
380
  <div className="rui-tl-head rui-tl-rulerhead" aria-hidden="true" />
197
381
  <div
198
382
  className="rui-tl-ruler"
199
383
  style={{
200
384
  width: laneW,
201
- // Minor ticks are a repeating background rather than elements: at 600 s and a
202
- // fine zoom that is thousands of nodes, and they carry no information a stripe
203
- // does not.
385
+ // Minor ticks are a repeating background, not elements: ten minutes at a fine zoom
386
+ // is thousands of nodes carrying no information a stripe does not.
204
387
  backgroundImage:
205
388
  'linear-gradient(90deg, var(--uic-line, #DDDFE6) 0 1px, transparent 1px),'
206
389
  + 'linear-gradient(90deg, var(--uic-line-soft, #EFF1F4) 0 1px, transparent 1px)',
@@ -209,8 +392,7 @@ export function Timeline({
209
392
  onPointerDown={onScrub}
210
393
  role={onSeek ? 'slider' : undefined}
211
394
  aria-label={onSeek ? 'Playhead' : undefined}
212
- aria-valuemin={0}
213
- aria-valuemax={Math.round(contentSeconds)}
395
+ aria-valuemin={0} aria-valuemax={Math.round(contentSeconds)}
214
396
  aria-valuenow={Math.round(currentTime)}
215
397
  tabIndex={onSeek ? 0 : undefined}
216
398
  onKeyDown={onSeek ? (e) => {
@@ -227,7 +409,7 @@ export function Timeline({
227
409
  </div>
228
410
  </div>
229
411
 
230
- {/* ── lanes ────────────────────────────────────────────────────────────────────── */}
412
+ {/* ── lanes ──────────────────────────────────────────────────────────────────────── */}
231
413
  {rows.length === 0 && <p className="rui-tl-empty">{emptyLabel}</p>}
232
414
 
233
415
  {rows.map((track) => (
@@ -241,36 +423,21 @@ export function Timeline({
241
423
  {track.laid.length === 0 && track.emptyLabel && (
242
424
  <p className="rui-tl-laneempty">{track.emptyLabel}</p>
243
425
  )}
244
- {track.laid.map(({ clip, x, w, known }, i) => (
245
- <article
246
- key={clip.id ?? i}
247
- className={'rui-tl-clip'
248
- + (clip.state ? ` is-${clip.state}` : '')
249
- + (known ? '' : ' is-unmeasured')
250
- + (selectedClipId === clip.id ? ' is-selected' : '')}
251
- style={{ left: x, width: w, ...(clip.accent ? { '--rui-tl-accent': clip.accent } : null) }}
252
- title={clip.title || clip.label}
253
- tabIndex={0}
254
- onClick={() => onSelectClip?.(clip, i)}
255
- onKeyDown={(e) => {
256
- if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onSelectClip?.(clip, i); }
257
- }}
258
- >
259
- {clip.poster
260
- ? <img className="rui-tl-poster" src={clip.poster} alt="" loading="lazy" />
261
- : <span className="rui-tl-blank" aria-hidden="true">{clip.glyph}</span>}
262
- {clip.badge && <span className="rui-tl-badge">{clip.badge}</span>}
263
- {/* A duration only when one was measured. See durationLabel. */}
264
- {known && w > 44 && (
265
- <span className="rui-tl-dur">{durationLabel(clip.duration)}</span>
266
- )}
267
- {clip.label && w > 96 && <span className="rui-tl-name">{clip.label}</span>}
268
- {clipActions && <span className="rui-tl-acts">{clipActions(clip, i)}</span>}
269
- </article>
426
+ {track.laid.map((l) => (
427
+ <Clip
428
+ key={l.clip.id ?? l.i}
429
+ l={l} track={track} pps={pps}
430
+ selected={selectedClipId === l.clip.id}
431
+ drag={drag}
432
+ onSelect={() => onSelectClip?.(l.clip, l.i)}
433
+ beginGesture={beginGesture}
434
+ onTrim={onTrim} onMoveClip={onMoveClip}
435
+ snapTimes={snapTimes}
436
+ />
270
437
  ))}
271
438
  {laneAppend && (
272
439
  <span className="rui-tl-append"
273
- style={{ left: track.laid.reduce((n, l) => Math.max(n, l.x + l.w), 0) + 4 }}>
440
+ style={{ left: track.laid.reduce((n, x) => Math.max(n, x.x + x.w), 0) + 6 }}>
274
441
  {laneAppend(track)}
275
442
  </span>
276
443
  )}
@@ -278,23 +445,133 @@ export function Timeline({
278
445
  </div>
279
446
  ))}
280
447
 
281
- {/* ── playhead ─────────────────────────────────────────────────────────────────────
282
- Drawn last so it sits above the lanes, and only when there is a time to show. */}
283
- {Number.isFinite(currentTime) && contentSeconds > 0 && (
448
+ {/* A snap guide, drawn only while a gesture is actually locked onto something. */}
449
+ {drag?.guide != null && (
450
+ <div className="rui-tl-guide" style={{ left: TL_HEAD_W + drag.guide * pps }}
451
+ aria-hidden="true" />
452
+ )}
453
+
454
+ {Number.isFinite(currentTime) && (
284
455
  <div className="rui-tl-playhead" style={{ left: TL_HEAD_W + currentTime * pps }}
285
456
  aria-hidden="true">
286
457
  <span className="rui-tl-playhead-grip" />
287
458
  </div>
288
459
  )}
289
- </div>
290
- </div>
291
460
 
292
- <div className="rui-tl-zoom">
293
- <button type="button" className="rui-tl-zoombtn" aria-label="Zoom out"
294
- onClick={() => setZoom(pps / 1.35)} disabled={pps <= TL_MIN_PPS + 1e-6}>−</button>
295
- <button type="button" className="rui-tl-zoombtn" aria-label="Zoom in"
296
- onClick={() => setZoom(pps * 1.35)} disabled={pps >= TL_MAX_PPS - 1e-6}>+</button>
461
+ {/* Numbers where the gesture is, so a trim is read off the clip and not off the ruler. */}
462
+ {drag?.annotation && (
463
+ <div className="rui-tl-annot" style={{ left: TL_HEAD_W + (drag.annotAt || 0) * pps }}>
464
+ {drag.annotation}
465
+ </div>
466
+ )}
467
+ </div>
297
468
  </div>
298
469
  </div>
299
470
  );
300
471
  }
472
+
473
+ /* ── one clip ───────────────────────────────────────────────────────────────────────────────── */
474
+
475
+ function Clip({ l, track, pps, selected, drag, onSelect, beginGesture, onTrim, onMoveClip,
476
+ snapTimes }) {
477
+ const { clip, x, w, known, t0, i } = l;
478
+ const live = drag?.clipId === clip.id ? drag : null;
479
+ const width = live?.width ?? w;
480
+ const left = live?.left ?? x;
481
+
482
+ // A FIXED tile size, so zooming changes how many frames you see rather than stretching one.
483
+ // That is the filmstrip convention; see the note at the top on these being one frame repeated.
484
+ const tileW = Math.round((LANE_H - CLIP_INSET * 2) * (16 / 9));
485
+
486
+ const startTrim = (e, edge) => {
487
+ if (!onTrim || !known) return;
488
+ beginGesture(e, {
489
+ kind: 'trim',
490
+ snapTimes,
491
+ preview: (t) => {
492
+ const dur = edge === 'end'
493
+ ? clamp(t - t0, TL_MIN_CLIP_S, clip.duration)
494
+ : clamp((t0 + clip.duration) - t, TL_MIN_CLIP_S, clip.duration);
495
+ const nextW = dur * pps;
496
+ const nextLeft = edge === 'end' ? x : x + (w - nextW);
497
+ return { clipId: clip.id, width: nextW, left: nextLeft,
498
+ annotation: `${exactLabel(dur)} · ${edge === 'end' ? 'out' : 'in'}`,
499
+ annotAt: (nextLeft + nextW) / pps };
500
+ },
501
+ commit: (t) => {
502
+ const dur = edge === 'end'
503
+ ? clamp(t - t0, TL_MIN_CLIP_S, clip.duration)
504
+ : clamp((t0 + clip.duration) - t, TL_MIN_CLIP_S, clip.duration);
505
+ if (Math.abs(dur - clip.duration) > 1e-3) onTrim(clip, edge, dur, track);
506
+ },
507
+ });
508
+ };
509
+
510
+ const startMove = (e) => {
511
+ if (!onMoveClip) { onSelect(); return; }
512
+ const half = (known ? clip.duration : 0) / 2;
513
+ beginGesture(e, {
514
+ kind: 'move',
515
+ snapTimes,
516
+ preview: (t) => {
517
+ const at = Math.max(0, t - half);
518
+ return { clipId: clip.id, left: at * pps, annotation: exactLabel(at), annotAt: at };
519
+ },
520
+ commit: (t) => {
521
+ const at = Math.max(0, t - half);
522
+ if (track.sequential) {
523
+ // On a cut, POSITION MEANS ORDER. Which slot the clip's centre landed in is the answer,
524
+ // and reordering is what the host is asked for — "move this to 4.2s" is not a thing a
525
+ // magnetic track can honour, and pretending otherwise puts the drawing and the document
526
+ // out of step the moment it re-renders.
527
+ let idx = 0;
528
+ for (const other of track.laid) {
529
+ if (other.clip.id === clip.id) continue;
530
+ if (at + half > other.t0 + (other.w / pps) / 2) idx += 1;
531
+ }
532
+ if (idx !== i) onMoveClip(clip, idx, track);
533
+ } else if (Math.abs(at - t0) > 1e-3) {
534
+ onMoveClip(clip, at, track);
535
+ }
536
+ },
537
+ click: onSelect,
538
+ });
539
+ };
540
+
541
+ return (
542
+ <article
543
+ className={'rui-tl-clip'
544
+ + (clip.state ? ` is-${clip.state}` : '')
545
+ + (known ? '' : ' is-unmeasured')
546
+ + (selected ? ' is-selected' : '')
547
+ + (live ? ' is-live' : '')}
548
+ style={{ left, width, ...(clip.accent ? { '--rui-tl-accent': clip.accent } : null) }}
549
+ title={clip.title || clip.label}
550
+ tabIndex={0}
551
+ onPointerDown={startMove}
552
+ onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onSelect(); } }}
553
+ >
554
+ {clip.poster
555
+ ? <span className="rui-tl-strip" style={{
556
+ backgroundImage: `url("${String(clip.poster).replace(/"/g, '\\"')}")`,
557
+ backgroundSize: `${tileW}px 100%`,
558
+ }} />
559
+ : <span className="rui-tl-blank" aria-hidden="true">{clip.glyph}</span>}
560
+
561
+ {clip.badge && <span className="rui-tl-badge">{clip.badge}</span>}
562
+ {known && width > 46 && <span className="rui-tl-dur">{durationLabel(clip.duration)}</span>}
563
+ {clip.label && width > 104 && <span className="rui-tl-name">{clip.label}</span>}
564
+
565
+ {/* Trim handles, only on a measured clip: there is nothing to trim against a length nobody
566
+ knows, and offering the gesture anyway would conjure a duration out of a drag. */}
567
+ {onTrim && known && (
568
+ <>
569
+ <span className="rui-tl-trim l" onPointerDown={(e) => startTrim(e, 'start')}
570
+ role="separator" aria-label={`Trim the start of ${clip.label || 'this clip'}`} />
571
+ <span className="rui-tl-trim r" onPointerDown={(e) => startTrim(e, 'end')}
572
+ role="separator" aria-label={`Trim the end of ${clip.label || 'this clip'}`} />
573
+ </>
574
+ )}
575
+ </article>
576
+ );
577
+ }