@cyca/react-timeline-editor 0.2.4-alpha.5 → 0.2.5-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1572 @@
1
+ import { a as parserTimeToPixel, c as PREFIX, i as parserPixelToTime, n as getScaleCountByRows, o as parserTimeToTransform, r as parserActionsToPositions, s as parserTransformToTime, t as getScaleCountByPixel } from "./deal-data-DH3Lh6kA.mjs";
2
+ import { createElement, useCallback, useEffect, useEffectEvent, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { prefixNames } from "framework-utils";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ import { useDrag } from "@use-gesture/react";
6
+ import { ScrollArea, Slot } from "radix-ui";
7
+ import { useVirtualizer } from "@tanstack/react-virtual";
8
+ import { resize } from "motion";
9
+ //#region src/utils/with-defaults.ts
10
+ function withDefaults(props) {
11
+ let { editorData = [], effects = {}, scale = 1, scaleSplitCount = 10, scaleWidth = 160, startLeft = 20, minScaleCount, maxScaleCount = Infinity, rowHeight = 32, collapsedRowHeight, autoScrollSpeed = 1, autoScrollMaxSpeed = 10 } = props;
12
+ if (scale <= 0) {
13
+ console.error("Error: scale must be greater than 0!");
14
+ scale = 1;
15
+ }
16
+ if (scaleSplitCount <= 0) {
17
+ console.warn("Warning: scaleSplitCount cannot be less than 1!");
18
+ scaleSplitCount = 1;
19
+ }
20
+ if (scaleWidth <= 0) {
21
+ console.warn("Warning: scaleWidth must be greater than 0!");
22
+ scaleWidth = 160;
23
+ }
24
+ if (startLeft < 0) {
25
+ console.warn("Warning: startLeft cannot be less than 0!");
26
+ startLeft = 0;
27
+ }
28
+ if (typeof minScaleCount === "number") {
29
+ minScaleCount = parseInt(minScaleCount + "");
30
+ if (minScaleCount < 1) {
31
+ console.warn("Warning: minScaleCount must be greater than 1!");
32
+ minScaleCount = 20;
33
+ }
34
+ }
35
+ maxScaleCount = maxScaleCount === Infinity ? Infinity : parseInt(maxScaleCount + "");
36
+ if (maxScaleCount < 1) {
37
+ console.warn("Warning: maxScaleCount must be greater than 1!");
38
+ maxScaleCount = 20;
39
+ }
40
+ if (typeof minScaleCount === "number" && maxScaleCount < minScaleCount) {
41
+ console.warn("Warning: maxScaleCount cannot be less than minScaleCount!");
42
+ maxScaleCount = minScaleCount;
43
+ }
44
+ if (rowHeight <= 0) {
45
+ console.warn("Warning: rowHeight must be greater than 0!");
46
+ rowHeight = 32;
47
+ }
48
+ if (typeof collapsedRowHeight !== "undefined" && collapsedRowHeight <= 0) {
49
+ console.warn("Warning: collapsedRowHeight must be greater than 0!");
50
+ collapsedRowHeight = rowHeight;
51
+ }
52
+ if (editorData.some((row) => typeof row.collapsed?.height !== "undefined" && row.collapsed.height <= 0)) {
53
+ console.warn("Warning: collapsed row height must be greater than 0!");
54
+ editorData = editorData.map((row) => typeof row.collapsed?.height !== "undefined" && row.collapsed.height <= 0 ? {
55
+ ...row,
56
+ collapsed: {
57
+ ...row.collapsed,
58
+ height: void 0
59
+ }
60
+ } : row);
61
+ }
62
+ const temp = { ...props };
63
+ delete temp["style"];
64
+ return {
65
+ ...temp,
66
+ editorData,
67
+ effects,
68
+ scale,
69
+ scaleSplitCount,
70
+ scaleWidth,
71
+ startLeft,
72
+ minScaleCount,
73
+ maxScaleCount,
74
+ rowHeight,
75
+ collapsedRowHeight,
76
+ autoScrollSpeed,
77
+ autoScrollMaxSpeed
78
+ };
79
+ }
80
+ //#endregion
81
+ //#region src/utils/deal-class-prefix.ts
82
+ function prefix(...classNames) {
83
+ return prefixNames(`${PREFIX}-`, ...classNames);
84
+ }
85
+ //#endregion
86
+ //#region src/components/edit_area/snap-lines.tsx
87
+ /** Drag auxiliary lines */
88
+ const SnapGuideLines = ({ isMoving, movePositions = [], assistPositions = [] }) => {
89
+ return /* @__PURE__ */ jsx("div", {
90
+ className: prefix("snap-line-container"),
91
+ children: isMoving && movePositions.filter((item) => assistPositions.includes(item)).map((linePos, index) => {
92
+ return /* @__PURE__ */ jsx("div", {
93
+ className: prefix("snap-line"),
94
+ style: { left: linePos }
95
+ }, index);
96
+ })
97
+ });
98
+ };
99
+ //#endregion
100
+ //#region src/components/row_rnd/hooks/use-auto-scroll.ts
101
+ const DEFAULT_SPEED = 1;
102
+ const MAX_SPEED = 10;
103
+ const CRITICAL_SIZE = 10;
104
+ function useAutoScroll(target, autoScrollSpeed = DEFAULT_SPEED, autoScrollMaxSpeed = MAX_SPEED) {
105
+ const leftBoundRef = useRef(Number.MIN_SAFE_INTEGER);
106
+ const rightBoundRef = useRef(Number.MAX_SAFE_INTEGER);
107
+ const speed = useRef(autoScrollSpeed);
108
+ const frame = useRef(void 0);
109
+ const initAutoScroll = () => {
110
+ if (target?.current) {
111
+ const { left, width } = target.current.getBoundingClientRect();
112
+ leftBoundRef.current = left;
113
+ rightBoundRef.current = left + width;
114
+ }
115
+ };
116
+ const dealDragAutoScroll = (e, deltaScroll) => {
117
+ if (e.clientX >= rightBoundRef.current || e.clientX <= leftBoundRef.current) {
118
+ if (frame.current !== void 0) cancelAnimationFrame(frame.current);
119
+ const over = Math.abs(e.clientX >= rightBoundRef.current ? e.clientX - rightBoundRef.current : e.clientX - leftBoundRef.current);
120
+ speed.current = Math.min(Math.max(Math.ceil(over / CRITICAL_SIZE) * autoScrollSpeed, autoScrollSpeed), autoScrollMaxSpeed);
121
+ const delta = (e.clientX >= rightBoundRef.current ? 1 : -1) * speed.current;
122
+ const loop = () => {
123
+ deltaScroll && deltaScroll(delta);
124
+ frame.current = requestAnimationFrame(loop);
125
+ };
126
+ frame.current = requestAnimationFrame(loop);
127
+ return false;
128
+ } else if (frame.current !== void 0) cancelAnimationFrame(frame.current);
129
+ return true;
130
+ };
131
+ const dealResizeAutoScroll = (e, _dir, deltaScroll) => {
132
+ if (e.clientX >= rightBoundRef.current || e.clientX < leftBoundRef.current) {
133
+ if (frame.current !== void 0) cancelAnimationFrame(frame.current);
134
+ const over = Math.abs(e.clientX >= rightBoundRef.current ? e.clientX - rightBoundRef.current : e.clientX - leftBoundRef.current);
135
+ speed.current = Math.min(Math.max(Math.ceil(over / CRITICAL_SIZE) * autoScrollSpeed, autoScrollSpeed), autoScrollMaxSpeed);
136
+ const delta = (e.clientX >= rightBoundRef.current ? 1 : -1) * speed.current;
137
+ const loop = () => {
138
+ deltaScroll && deltaScroll(delta);
139
+ frame.current = requestAnimationFrame(loop);
140
+ };
141
+ frame.current = requestAnimationFrame(loop);
142
+ return false;
143
+ } else if (frame.current !== void 0) cancelAnimationFrame(frame.current);
144
+ return true;
145
+ };
146
+ const stopAutoScroll = () => {
147
+ leftBoundRef.current = Number.MIN_SAFE_INTEGER;
148
+ rightBoundRef.current = Number.MAX_SAFE_INTEGER;
149
+ speed.current = autoScrollSpeed;
150
+ if (frame.current !== void 0) cancelAnimationFrame(frame.current);
151
+ };
152
+ return {
153
+ initAutoScroll,
154
+ dealDragAutoScroll,
155
+ dealResizeAutoScroll,
156
+ stopAutoScroll
157
+ };
158
+ }
159
+ //#endregion
160
+ //#region src/components/row_rnd/interactable.tsx
161
+ /**
162
+ * Helper function to create a GestureEvent from gesture state
163
+ */
164
+ const createGestureEvent = (target, delta, xy, edges, deltaRect) => ({
165
+ target,
166
+ dx: delta[0],
167
+ dy: delta[1],
168
+ clientX: xy[0],
169
+ clientY: xy[1],
170
+ ...edges && { edges },
171
+ ...deltaRect && { deltaRect }
172
+ });
173
+ /**
174
+ * Helper function to check if an event target is a resize handle
175
+ */
176
+ const isResizeHandle = (eventTarget, leftHandle, rightHandle) => {
177
+ if (!eventTarget) return false;
178
+ return eventTarget === leftHandle || eventTarget === rightHandle || (leftHandle?.contains(eventTarget) ?? false) || (rightHandle?.contains(eventTarget) ?? false);
179
+ };
180
+ const Interactable = ({ children, style, draggable, resizable, draggableOptions, resizableOptions, ref }) => {
181
+ const draggableOptionsRef = useRef(void 0);
182
+ const resizableOptionsRef = useRef(void 0);
183
+ const leftResizeHandleRef = useRef(null);
184
+ const rightResizeHandleRef = useRef(null);
185
+ useLayoutEffect(() => {
186
+ draggableOptionsRef.current = draggableOptions;
187
+ resizableOptionsRef.current = resizableOptions;
188
+ if (!ref?.current) return;
189
+ const currentLeftSelector = resizableOptions?.edges?.left;
190
+ const currentRightSelector = resizableOptions?.edges?.right;
191
+ const node = ref.current;
192
+ if (currentLeftSelector) leftResizeHandleRef.current = node.querySelector(currentLeftSelector);
193
+ if (currentRightSelector) rightResizeHandleRef.current = node.querySelector(currentRightSelector);
194
+ }, [
195
+ draggableOptions,
196
+ ref,
197
+ resizableOptions
198
+ ]);
199
+ useDrag(({ active, delta, xy, event, first, last }) => {
200
+ const node = ref?.current;
201
+ if (!node) return;
202
+ if (isResizeHandle(event?.target, leftResizeHandleRef.current, rightResizeHandleRef.current)) return;
203
+ const gestureEvent = createGestureEvent(node, delta, xy);
204
+ if (first) draggableOptionsRef.current?.onstart?.(gestureEvent);
205
+ else if (last) draggableOptionsRef.current?.onend?.(gestureEvent);
206
+ else if (active) draggableOptionsRef.current?.onmove?.(gestureEvent);
207
+ }, {
208
+ enabled: draggable,
209
+ axis: draggableOptions?.lockAxis === "x" ? "x" : void 0,
210
+ pointer: { capture: true },
211
+ target: ref,
212
+ threshold: 0
213
+ });
214
+ useDrag(({ active, delta, xy, first, last }) => {
215
+ const node = ref?.current;
216
+ if (!node) return;
217
+ const gestureEvent = createGestureEvent(node, delta, xy, { left: true }, { left: delta[0] });
218
+ if (first) resizableOptionsRef.current?.onstart?.(gestureEvent);
219
+ else if (last) resizableOptionsRef.current?.onend?.(gestureEvent);
220
+ else if (active) resizableOptionsRef.current?.onmove?.(gestureEvent);
221
+ }, {
222
+ enabled: resizable,
223
+ target: leftResizeHandleRef,
224
+ pointer: { capture: true },
225
+ threshold: 0
226
+ });
227
+ useDrag(({ active, delta, xy, first, last }) => {
228
+ const node = ref?.current;
229
+ if (!node) return;
230
+ const gestureEvent = createGestureEvent(node, delta, xy, { right: true }, { right: delta[0] });
231
+ if (first) resizableOptionsRef.current?.onstart?.(gestureEvent);
232
+ else if (last) resizableOptionsRef.current?.onend?.(gestureEvent);
233
+ else if (active) resizableOptionsRef.current?.onmove?.(gestureEvent);
234
+ }, {
235
+ enabled: resizable,
236
+ target: rightResizeHandleRef,
237
+ pointer: { capture: true },
238
+ threshold: 0
239
+ });
240
+ return /* @__PURE__ */ jsx(Slot.Root, {
241
+ ref,
242
+ style: {
243
+ ...draggable ? { touchAction: "none" } : {},
244
+ ...style
245
+ },
246
+ draggable: false,
247
+ children
248
+ });
249
+ };
250
+ //#endregion
251
+ //#region src/components/row_rnd/row-rnd.tsx
252
+ const parseDatasetValue = (value, defaultValue = 0) => {
253
+ return value ? parseFloat(value) : defaultValue;
254
+ };
255
+ const calculateSnap = (position, snapPositions, snapDistance, minDis = Number.MAX_SAFE_INTEGER) => {
256
+ let snap = position;
257
+ let currentMinDis = minDis;
258
+ for (const item of snapPositions) {
259
+ const itemValue = typeof item === "number" ? item : item.value;
260
+ const dis = Math.abs(itemValue - position);
261
+ if (dis < snapDistance && dis < currentMinDis) {
262
+ snap = itemValue;
263
+ currentMinDis = dis;
264
+ }
265
+ }
266
+ return {
267
+ snap,
268
+ minDis: currentMinDis
269
+ };
270
+ };
271
+ function RowDnd({ children, edges, left, width, start = 20, grid = 1, getBounds = () => ({
272
+ left: Number.MIN_SAFE_INTEGER,
273
+ right: Number.MAX_SAFE_INTEGER
274
+ }), enableResizing = true, enableDragging = true, snapDistance = 8, snapPositions = [], snapOrigin = "leading", onResizeStart, onResize, onResizeEnd, onDragStart, onDragEnd, onDrag, parentRef, autoScroll = true, autoScrollSpeed, autoScrollMaxSpeed, ref }) {
275
+ const interactableRef = useRef(null);
276
+ const deltaX = useRef(0);
277
+ const isSnap = useRef(false);
278
+ const { initAutoScroll, stopAutoScroll, dealDragAutoScroll, dealResizeAutoScroll } = useAutoScroll(parentRef, autoScrollSpeed, autoScrollMaxSpeed);
279
+ const handleUpdateLeft = (left, reset = true) => {
280
+ if (!interactableRef.current) return;
281
+ if (reset) deltaX.current = 0;
282
+ const target = interactableRef.current;
283
+ target.style.setProperty("--translate-x", `${left}px`);
284
+ target.dataset.left = String(left);
285
+ };
286
+ const handleUpdateWidth = (width, reset = true) => {
287
+ if (!interactableRef.current) return;
288
+ if (reset) deltaX.current = 0;
289
+ const target = interactableRef.current;
290
+ target.style.width = `${width}px`;
291
+ target.dataset.width = String(width);
292
+ };
293
+ const handleGetLeft = () => {
294
+ if (!interactableRef.current) return 0;
295
+ return parseDatasetValue(interactableRef.current.dataset.left);
296
+ };
297
+ const handleGetWidth = () => {
298
+ if (!interactableRef.current) return 0;
299
+ return parseDatasetValue(interactableRef.current.dataset.width);
300
+ };
301
+ useEffect(() => {
302
+ if (!interactableRef.current) return;
303
+ const target = interactableRef.current;
304
+ handleUpdateWidth(typeof width === "undefined" ? target.offsetWidth : width, false);
305
+ }, [width]);
306
+ useEffect(() => {
307
+ handleUpdateLeft(left || 0, false);
308
+ }, [left]);
309
+ useImperativeHandle(ref, () => ({
310
+ updateLeft: (left) => handleUpdateLeft(left || 0, false),
311
+ updateWidth: (width) => handleUpdateWidth(width, false),
312
+ getLeft: handleGetLeft,
313
+ getWidth: handleGetWidth
314
+ }));
315
+ const handleMoveStart = () => {
316
+ deltaX.current = 0;
317
+ isSnap.current = false;
318
+ initAutoScroll();
319
+ onDragStart?.();
320
+ };
321
+ const move = (param) => {
322
+ const { preLeft, preWidth, scrollDelta } = param;
323
+ if (scrollDelta) deltaX.current += scrollDelta;
324
+ const distance = isSnap.current ? snapDistance : grid;
325
+ if (Math.abs(deltaX.current) < distance) return;
326
+ let curLeft = preLeft + Math.trunc(deltaX.current / distance) * distance;
327
+ const movingRight = deltaX.current > 0;
328
+ let checkPosition = curLeft;
329
+ if (snapOrigin === "leading") checkPosition = movingRight ? curLeft + preWidth : curLeft;
330
+ else if (snapOrigin === "right") checkPosition = curLeft + preWidth;
331
+ else if (snapOrigin === "center") checkPosition = curLeft + preWidth / 2;
332
+ const { snap: snapPosition } = calculateSnap(checkPosition, snapPositions, snapDistance);
333
+ if (snapPosition !== checkPosition) {
334
+ isSnap.current = true;
335
+ if (snapOrigin === "leading") curLeft = movingRight ? snapPosition - preWidth : snapPosition;
336
+ else if (snapOrigin === "right") curLeft = snapPosition - preWidth;
337
+ else if (snapOrigin === "center") curLeft = snapPosition - preWidth / 2;
338
+ else curLeft = snapPosition;
339
+ } else {
340
+ const offset = curLeft - start;
341
+ if (offset % grid !== 0) curLeft = start + grid * Math.round(offset / grid);
342
+ isSnap.current = false;
343
+ }
344
+ deltaX.current = deltaX.current % distance;
345
+ const bounds = getBounds();
346
+ if (curLeft < bounds.left) curLeft = bounds.left;
347
+ else if (curLeft + preWidth > bounds.right) curLeft = bounds.right - preWidth;
348
+ if (onDrag) {
349
+ if (onDrag({
350
+ lastLeft: preLeft,
351
+ left: curLeft,
352
+ lastWidth: preWidth,
353
+ width: preWidth
354
+ }, scrollDelta) === false) return;
355
+ }
356
+ handleUpdateLeft(curLeft, false);
357
+ };
358
+ const handleMove = (e) => {
359
+ const target = e.target;
360
+ const preLeft = parseDatasetValue(target.dataset.left);
361
+ const preWidth = parseDatasetValue(target.dataset.width);
362
+ deltaX.current += e.dx;
363
+ if (autoScroll && parentRef?.current) {
364
+ const deltaScroll = (delta) => {
365
+ if (!parentRef?.current || !interactableRef.current) return;
366
+ parentRef.current.scrollLeft += delta;
367
+ const currentTarget = interactableRef.current;
368
+ move({
369
+ preLeft: parseDatasetValue(currentTarget.dataset.left),
370
+ preWidth: parseDatasetValue(currentTarget.dataset.width),
371
+ scrollDelta: delta
372
+ });
373
+ };
374
+ if (!dealDragAutoScroll(e, deltaScroll)) return;
375
+ }
376
+ move({
377
+ preLeft,
378
+ preWidth
379
+ });
380
+ };
381
+ const handleMoveStop = (e) => {
382
+ deltaX.current = 0;
383
+ isSnap.current = false;
384
+ stopAutoScroll();
385
+ const target = e.target;
386
+ onDragEnd?.({
387
+ left: parseDatasetValue(target.dataset.left),
388
+ width: parseDatasetValue(target.dataset.width)
389
+ });
390
+ };
391
+ const handleResizeStart = (e) => {
392
+ deltaX.current = 0;
393
+ isSnap.current = false;
394
+ initAutoScroll();
395
+ const dir = e.edges?.right ? "right" : "left";
396
+ onResizeStart?.(dir);
397
+ };
398
+ const resize = (param) => {
399
+ const { dir, preWidth, preLeft, scrollDelta } = param;
400
+ if (scrollDelta) deltaX.current += scrollDelta;
401
+ const distance = isSnap.current ? snapDistance : grid;
402
+ if (Math.abs(deltaX.current) < distance) return;
403
+ const bounds = getBounds();
404
+ if (dir === "left") {
405
+ let curLeft = preLeft + Math.trunc(deltaX.current / distance) * distance;
406
+ const { snap } = calculateSnap(curLeft, snapPositions, snapDistance);
407
+ if (snap !== curLeft) {
408
+ isSnap.current = true;
409
+ curLeft = snap;
410
+ } else {
411
+ const offset = curLeft - start;
412
+ if (offset % grid !== 0) curLeft = start + grid * Math.round(offset / grid);
413
+ isSnap.current = false;
414
+ }
415
+ deltaX.current = deltaX.current % distance;
416
+ if (curLeft < bounds.left) curLeft = bounds.left;
417
+ const tempRight = preLeft + preWidth;
418
+ const curWidth = tempRight - curLeft;
419
+ if (curLeft >= tempRight) return;
420
+ if (onResize) {
421
+ if (onResize("left", {
422
+ lastLeft: preLeft,
423
+ lastWidth: preWidth,
424
+ left: curLeft,
425
+ width: curWidth
426
+ }) === false) return;
427
+ }
428
+ handleUpdateLeft(curLeft, false);
429
+ handleUpdateWidth(curWidth, false);
430
+ } else {
431
+ let curWidth = preWidth + Math.trunc(deltaX.current / distance) * distance;
432
+ const rightEdge = preLeft + curWidth;
433
+ const { snap } = calculateSnap(rightEdge, snapPositions, snapDistance);
434
+ if (snap !== rightEdge) {
435
+ isSnap.current = true;
436
+ curWidth = snap - preLeft;
437
+ } else {
438
+ let tempRight = preLeft + curWidth;
439
+ const offset = tempRight - start;
440
+ if (offset % grid !== 0) {
441
+ tempRight = start + grid * Math.round(offset / grid);
442
+ curWidth = tempRight - preLeft;
443
+ }
444
+ isSnap.current = false;
445
+ }
446
+ deltaX.current = deltaX.current % distance;
447
+ if (preLeft + curWidth > bounds.right) curWidth = bounds.right - preLeft;
448
+ if (curWidth <= 0) return;
449
+ if (onResize) {
450
+ if (onResize("right", {
451
+ lastLeft: preLeft,
452
+ lastWidth: preWidth,
453
+ left: preLeft,
454
+ width: curWidth
455
+ }) === false) return;
456
+ }
457
+ handleUpdateWidth(curWidth, false);
458
+ }
459
+ };
460
+ const handleResize = (e) => {
461
+ const target = e.target;
462
+ const dir = e.edges?.left ? "left" : "right";
463
+ const preLeft = parseDatasetValue(target.dataset.left);
464
+ const preWidth = parseDatasetValue(target.dataset.width);
465
+ deltaX.current += dir === "left" ? e.deltaRect?.left || 0 : e.deltaRect?.right || 0;
466
+ if (autoScroll && parentRef?.current) {
467
+ const deltaScroll = (delta) => {
468
+ if (!parentRef?.current || !interactableRef.current) return;
469
+ parentRef.current.scrollLeft += delta;
470
+ const currentTarget = interactableRef.current;
471
+ resize({
472
+ preLeft: parseDatasetValue(currentTarget.dataset.left),
473
+ preWidth: parseDatasetValue(currentTarget.dataset.width),
474
+ dir,
475
+ scrollDelta: delta
476
+ });
477
+ };
478
+ if (!dealResizeAutoScroll(e, dir, deltaScroll)) return;
479
+ }
480
+ resize({
481
+ preLeft,
482
+ preWidth,
483
+ dir
484
+ });
485
+ };
486
+ const handleResizeStop = (e) => {
487
+ deltaX.current = 0;
488
+ isSnap.current = false;
489
+ stopAutoScroll();
490
+ const target = e.target;
491
+ const dir = e.edges?.right ? "right" : "left";
492
+ onResizeEnd?.(dir, {
493
+ left: parseDatasetValue(target.dataset.left),
494
+ width: parseDatasetValue(target.dataset.width)
495
+ });
496
+ };
497
+ return /* @__PURE__ */ jsx(Interactable, {
498
+ "data-left": left || 0,
499
+ style: {
500
+ "--translate-x": `${left || 0}px`,
501
+ transform: `translateX(var(--translate-x)) scaleX(var(--scale-x,1))`,
502
+ width
503
+ },
504
+ ref: interactableRef,
505
+ draggable: enableDragging,
506
+ resizable: enableResizing,
507
+ draggableOptions: {
508
+ lockAxis: "x",
509
+ onmove: handleMove,
510
+ onstart: handleMoveStart,
511
+ onend: handleMoveStop,
512
+ cursorChecker: () => ""
513
+ },
514
+ resizableOptions: {
515
+ axis: "x",
516
+ invert: "none",
517
+ edges,
518
+ onmove: handleResize,
519
+ onstart: handleResizeStart,
520
+ onend: handleResizeStop
521
+ },
522
+ children
523
+ });
524
+ }
525
+ //#endregion
526
+ //#region src/utils/clsx.ts
527
+ function clsx() {
528
+ let i = 0, tmp, str = "", len = arguments.length;
529
+ for (; i < len; i++) if (tmp = arguments[i]) {
530
+ if (typeof tmp === "string") str += (str && " ") + tmp;
531
+ }
532
+ return str;
533
+ }
534
+ //#endregion
535
+ //#region src/components/edit_area/edit-action.tsx
536
+ const EditAction = ({ editorData, row, rowRenderHeight, action, effects, scale, scaleWidth, scaleSplitCount, startLeft, gridSnap, disableDrag, autoScroll, autoScrollSpeed, autoScrollMaxSpeed, scaleCount, maxScaleCount, setScaleCount, onActionMoveStart, onActionMoving, onActionMoveEnd, onActionResizeStart, onActionResizeEnd, onActionResizing, snapData, setEditorData, onClickAction, onClickActionOnly, onDoubleClickAction, onContextMenuAction, getActionRender, handleTime, scrollContainerRef }) => {
537
+ const rowRnd = useRef(null);
538
+ const isDragWhenClick = useRef(false);
539
+ const { id, maxEnd, minStart, end, start, selected, flexible = true, movable = true, effectId } = action;
540
+ const safeScale = scale ?? 1;
541
+ const safeScaleWidth = scaleWidth ?? 160;
542
+ const safeStartLeft = startLeft ?? 20;
543
+ const safeScaleSplitCount = scaleSplitCount ?? 10;
544
+ const safeMaxScaleCount = maxScaleCount ?? Number.MAX_SAFE_INTEGER;
545
+ const leftLimit = parserTimeToPixel(minStart || 0, {
546
+ startLeft: safeStartLeft,
547
+ scale: safeScale,
548
+ scaleWidth: safeScaleWidth
549
+ });
550
+ const rightLimit = Math.min(safeMaxScaleCount * safeScaleWidth + safeStartLeft, parserTimeToPixel(maxEnd || Number.MAX_VALUE, {
551
+ startLeft: safeStartLeft,
552
+ scale: safeScale,
553
+ scaleWidth: safeScaleWidth
554
+ }));
555
+ const baseTransform = useMemo(() => {
556
+ return parserTimeToTransform({
557
+ start,
558
+ end
559
+ }, {
560
+ startLeft: safeStartLeft,
561
+ scale: safeScale,
562
+ scaleWidth: safeScaleWidth
563
+ });
564
+ }, [
565
+ end,
566
+ start,
567
+ safeStartLeft,
568
+ safeScaleWidth,
569
+ safeScale
570
+ ]);
571
+ const [dragTransform, setDragTransform] = useState(null);
572
+ const transform = dragTransform ?? baseTransform;
573
+ const gridSize = safeScaleWidth / safeScaleSplitCount;
574
+ const classNames = prefix(clsx("action", movable && "action-movable", selected && "action-selected", flexible && "action-flexible", effects[effectId] && `action-effect-${effectId}`));
575
+ /** Calculate scale count */
576
+ const handleScaleCount = (left, width) => {
577
+ const curScaleCount = getScaleCountByPixel(left + width, {
578
+ startLeft: safeStartLeft,
579
+ scaleCount,
580
+ scaleWidth: safeScaleWidth
581
+ });
582
+ if (curScaleCount !== scaleCount) setScaleCount(curScaleCount);
583
+ };
584
+ const handleDragStart = () => {
585
+ onActionMoveStart && onActionMoveStart({
586
+ action,
587
+ row
588
+ });
589
+ };
590
+ const handleDrag = ({ left, width }) => {
591
+ isDragWhenClick.current = true;
592
+ if (onActionMoving) {
593
+ const { start, end } = parserTransformToTime({
594
+ left,
595
+ width
596
+ }, {
597
+ scaleWidth: safeScaleWidth,
598
+ scale: safeScale,
599
+ startLeft: safeStartLeft
600
+ });
601
+ if (onActionMoving({
602
+ action,
603
+ row,
604
+ start,
605
+ end
606
+ }) === false) return false;
607
+ }
608
+ setDragTransform({
609
+ left,
610
+ width
611
+ });
612
+ handleScaleCount(left, width);
613
+ };
614
+ const handleDragEnd = ({ left, width }) => {
615
+ const { start, end } = parserTransformToTime({
616
+ left,
617
+ width
618
+ }, {
619
+ scaleWidth: safeScaleWidth,
620
+ scale: safeScale,
621
+ startLeft: safeStartLeft
622
+ });
623
+ const rowItem = editorData.find((item) => item.id === row.id);
624
+ if (!rowItem) return;
625
+ const actionItem = rowItem.actions.find((item) => item.id === id);
626
+ if (!actionItem) return;
627
+ actionItem.start = start;
628
+ actionItem.end = end;
629
+ setEditorData([...editorData]);
630
+ if (onActionMoveEnd) onActionMoveEnd({
631
+ action: actionItem,
632
+ row,
633
+ start,
634
+ end
635
+ });
636
+ setDragTransform(null);
637
+ };
638
+ const handleResizeStart = (dir) => {
639
+ onActionResizeStart && onActionResizeStart({
640
+ action,
641
+ row,
642
+ dir
643
+ });
644
+ };
645
+ const handleResizing = (dir, { left, width }) => {
646
+ isDragWhenClick.current = true;
647
+ if (onActionResizing) {
648
+ const { start, end } = parserTransformToTime({
649
+ left,
650
+ width
651
+ }, {
652
+ scaleWidth: safeScaleWidth,
653
+ scale: safeScale,
654
+ startLeft: safeStartLeft
655
+ });
656
+ if (onActionResizing({
657
+ action,
658
+ row,
659
+ start,
660
+ end,
661
+ dir
662
+ }) === false) return false;
663
+ }
664
+ setDragTransform({
665
+ left,
666
+ width
667
+ });
668
+ handleScaleCount(left, width);
669
+ };
670
+ const handleResizeEnd = (dir, { left, width }) => {
671
+ const { start, end } = parserTransformToTime({
672
+ left,
673
+ width
674
+ }, {
675
+ scaleWidth: safeScaleWidth,
676
+ scale: safeScale,
677
+ startLeft: safeStartLeft
678
+ });
679
+ const rowItem = editorData.find((item) => item.id === row.id);
680
+ if (!rowItem) return;
681
+ const actionItem = rowItem.actions.find((item) => item.id === id);
682
+ if (!actionItem) return;
683
+ actionItem.start = start;
684
+ actionItem.end = end;
685
+ setEditorData([...editorData]);
686
+ if (onActionResizeEnd) onActionResizeEnd({
687
+ action: actionItem,
688
+ row,
689
+ start,
690
+ end,
691
+ dir
692
+ });
693
+ setDragTransform(null);
694
+ };
695
+ const nowAction = {
696
+ ...action,
697
+ ...parserTransformToTime({
698
+ left: transform.left,
699
+ width: transform.width
700
+ }, {
701
+ startLeft: safeStartLeft,
702
+ scaleWidth: safeScaleWidth,
703
+ scale: safeScale
704
+ })
705
+ };
706
+ const nowRow = {
707
+ ...row,
708
+ actions: [...row.actions]
709
+ };
710
+ if (row.actions.includes(action)) nowRow.actions[row.actions.indexOf(action)] = nowAction;
711
+ return /* @__PURE__ */ jsx(RowDnd, {
712
+ ref: rowRnd,
713
+ parentRef: scrollContainerRef,
714
+ start: safeStartLeft,
715
+ left: transform.left,
716
+ width: transform.width,
717
+ grid: gridSnap && gridSize || 1,
718
+ snapDistance: gridSnap ? Math.max((gridSize || 1) / 2, 8) : 8,
719
+ snapPositions: snapData.assistPositions,
720
+ getBounds: () => {
721
+ return {
722
+ left: leftLimit,
723
+ right: rightLimit
724
+ };
725
+ },
726
+ edges: {
727
+ left: !disableDrag && flexible && `.${prefix("action-left-stretch")}`,
728
+ right: !disableDrag && flexible && `.${prefix("action-right-stretch")}`
729
+ },
730
+ enableDragging: !disableDrag && movable,
731
+ enableResizing: !disableDrag && flexible,
732
+ onDragStart: handleDragStart,
733
+ onDrag: handleDrag,
734
+ onDragEnd: handleDragEnd,
735
+ onResizeStart: handleResizeStart,
736
+ onResize: handleResizing,
737
+ onResizeEnd: handleResizeEnd,
738
+ autoScroll,
739
+ autoScrollSpeed,
740
+ autoScrollMaxSpeed,
741
+ children: /* @__PURE__ */ jsxs("div", {
742
+ onMouseDown: () => {
743
+ isDragWhenClick.current = false;
744
+ },
745
+ onClick: (e) => {
746
+ let time;
747
+ if (onClickAction) {
748
+ time = handleTime(e);
749
+ onClickAction(e, {
750
+ row,
751
+ action,
752
+ time
753
+ });
754
+ }
755
+ if (!isDragWhenClick.current && onClickActionOnly) {
756
+ if (time === void 0) time = handleTime(e);
757
+ onClickActionOnly(e, {
758
+ row,
759
+ action,
760
+ time
761
+ });
762
+ }
763
+ },
764
+ onDoubleClick: (e) => {
765
+ if (onDoubleClickAction) onDoubleClickAction(e, {
766
+ row,
767
+ action,
768
+ time: handleTime(e)
769
+ });
770
+ },
771
+ onContextMenu: (e) => {
772
+ if (onContextMenuAction) onContextMenuAction(e, {
773
+ row,
774
+ action,
775
+ time: handleTime(e)
776
+ });
777
+ },
778
+ className: classNames,
779
+ style: { height: rowRenderHeight },
780
+ children: [
781
+ getActionRender && getActionRender(nowAction, nowRow),
782
+ /* @__PURE__ */ jsx("div", {
783
+ className: clsx(prefix("action-left-stretch")),
784
+ style: {
785
+ touchAction: "none",
786
+ visibility: flexible ? "visible" : "hidden",
787
+ pointerEvents: flexible ? "auto" : "none"
788
+ }
789
+ }),
790
+ /* @__PURE__ */ jsx("div", {
791
+ className: prefix("action-right-stretch"),
792
+ style: {
793
+ touchAction: "none",
794
+ visibility: flexible ? "visible" : "hidden",
795
+ pointerEvents: flexible ? "auto" : "none"
796
+ }
797
+ })
798
+ ]
799
+ })
800
+ });
801
+ };
802
+ //#endregion
803
+ //#region src/components/edit_area/edit-row.tsx
804
+ const EditRow = (props) => {
805
+ const { rowData, rowRenderHeight, isCollapsed = false, style = {}, onClickRow, onDoubleClickRow, onContextMenuRow, scrollContainerRef, startLeft, scale, scaleWidth, unstable_rowActionsOverscan, getEmptyRowRender, getCollapsedRowLabelRender } = props;
806
+ const classNames = ["edit-row"];
807
+ if (rowData?.selected) classNames.push("edit-row-selected");
808
+ const safeScale = scale ?? 1;
809
+ const safeScaleWidth = scaleWidth ?? 160;
810
+ const safeStartLeft = startLeft ?? 20;
811
+ const handleTime = (e) => {
812
+ if (!scrollContainerRef.current) return 0;
813
+ const rect = e.currentTarget.getBoundingClientRect();
814
+ return parserPixelToTime(e.clientX - rect.x, {
815
+ startLeft: safeStartLeft,
816
+ scale: safeScale,
817
+ scaleWidth: safeScaleWidth
818
+ });
819
+ };
820
+ const actions = useMemo(() => (rowData?.actions ? [...rowData.actions] : []).sort((a, b) => a.start - b.start), [rowData]);
821
+ const getItemKey = useCallback((index) => actions[index]?.id ?? index, [actions]);
822
+ const virtualizer = useVirtualizer({
823
+ horizontal: true,
824
+ count: actions.length,
825
+ getItemKey,
826
+ getScrollElement: () => scrollContainerRef.current,
827
+ estimateSize: (index) => {
828
+ if (!actions[index]) return 0;
829
+ let start = index > 0 ? actions[index - 1].end : 0;
830
+ let end = actions[index].end;
831
+ if (start > end) return 0;
832
+ let { width } = parserTimeToTransform({
833
+ start,
834
+ end
835
+ }, {
836
+ startLeft: safeStartLeft,
837
+ scale: safeScale,
838
+ scaleWidth: safeScaleWidth
839
+ });
840
+ return width;
841
+ },
842
+ overscan: unstable_rowActionsOverscan ?? 5
843
+ });
844
+ useEffect(() => virtualizer.measure(), [
845
+ safeScale,
846
+ safeScaleWidth,
847
+ safeStartLeft,
848
+ virtualizer
849
+ ]);
850
+ return /* @__PURE__ */ jsxs("div", {
851
+ className: `${prefix(...classNames)} ${(rowData?.classNames || []).join(" ")}`,
852
+ style,
853
+ onPointerEnter: props.onPointerEnter,
854
+ onPointerLeave: props.onPointerLeave,
855
+ onClick: (e) => {
856
+ if (rowData && onClickRow) onClickRow(e, {
857
+ row: rowData,
858
+ time: handleTime(e)
859
+ });
860
+ },
861
+ onDoubleClick: (e) => {
862
+ if (rowData && onDoubleClickRow) onDoubleClickRow(e, {
863
+ row: rowData,
864
+ time: handleTime(e)
865
+ });
866
+ },
867
+ onContextMenu: (e) => {
868
+ if (rowData && onContextMenuRow) onContextMenuRow(e, {
869
+ row: rowData,
870
+ time: handleTime(e)
871
+ });
872
+ },
873
+ children: [
874
+ rowData && isCollapsed && getCollapsedRowLabelRender && /* @__PURE__ */ jsx("div", {
875
+ className: prefix("collapsed-row-label"),
876
+ "aria-hidden": "true",
877
+ children: getCollapsedRowLabelRender({
878
+ row: rowData,
879
+ height: rowRenderHeight
880
+ })
881
+ }),
882
+ rowData && actions.length === 0 && getEmptyRowRender && /* @__PURE__ */ jsx("div", {
883
+ className: prefix("empty-row"),
884
+ children: getEmptyRowRender({
885
+ row: rowData,
886
+ height: rowRenderHeight
887
+ })
888
+ }),
889
+ rowData && virtualizer.getVirtualItems().map((virtualEntry) => {
890
+ const action = actions[virtualEntry.index];
891
+ if (!action) throw new Error("Action not found");
892
+ return /* @__PURE__ */ jsx(EditAction, {
893
+ ...props,
894
+ handleTime,
895
+ row: rowData,
896
+ rowRenderHeight,
897
+ action
898
+ }, action.id);
899
+ })
900
+ ]
901
+ });
902
+ };
903
+ //#endregion
904
+ //#region src/components/edit_area/hooks/use-snap.ts
905
+ const useSnap = (props) => {
906
+ const [snapData, setSnapData] = useState({
907
+ isMoving: false,
908
+ movePositions: [],
909
+ assistPositions: []
910
+ });
911
+ const activeDragStateRef = useRef(null);
912
+ const snapDataRef = useEffectEvent(() => ({
913
+ ...props,
914
+ snapData
915
+ }));
916
+ useEffect(() => {
917
+ const activeDragState = activeDragStateRef.current;
918
+ const currentProps = snapDataRef();
919
+ if (currentProps.snap && activeDragState && currentProps.snapData.isMoving && currentProps.snapPositions) {
920
+ const assistActionIds = activeDragState.assistActionIds;
921
+ const assistPositions = currentProps.snapPositions.filter((pos) => {
922
+ if (pos.actionId === activeDragState.action.id) return false;
923
+ if (assistActionIds && !assistActionIds.includes(pos.actionId)) return false;
924
+ return true;
925
+ }).map((pos) => pos.value);
926
+ if (!currentProps.hideCursor) {
927
+ const cursorLeft = parserTimeToPixel(currentProps.cursorTime, {
928
+ scaleWidth: currentProps.scaleWidth ?? 160,
929
+ scale: currentProps.scale ?? 1,
930
+ startLeft: currentProps.startLeft ?? 20
931
+ });
932
+ assistPositions.push(cursorLeft);
933
+ }
934
+ setSnapData((pre) => ({
935
+ ...pre,
936
+ assistPositions
937
+ }));
938
+ } else if (!currentProps.snap && currentProps.snapData.isMoving) setSnapData((pre) => ({
939
+ ...pre,
940
+ assistPositions: []
941
+ }));
942
+ }, [props.snap]);
943
+ const handleInitSnap = (data) => {
944
+ const assistActionIds = props.getAssistDragLineActionIds && props.getAssistDragLineActionIds({
945
+ action: data.action,
946
+ row: data.row,
947
+ editorData: props.editorData
948
+ });
949
+ activeDragStateRef.current = {
950
+ action: data.action,
951
+ row: data.row,
952
+ assistActionIds
953
+ };
954
+ if (props.snap && props.snapPositions) {
955
+ const assistPositions = props.snapPositions.filter((pos) => {
956
+ if (pos.actionId === data.action.id) return false;
957
+ if (assistActionIds && !assistActionIds.includes(pos.actionId)) return false;
958
+ return true;
959
+ }).map((pos) => pos.value);
960
+ if (!props.hideCursor) {
961
+ const cursorLeft = parserTimeToPixel(props.cursorTime, {
962
+ scaleWidth: props.scaleWidth ?? 160,
963
+ scale: props.scale ?? 1,
964
+ startLeft: props.startLeft ?? 20
965
+ });
966
+ assistPositions.push(cursorLeft);
967
+ }
968
+ setSnapData({
969
+ isMoving: true,
970
+ movePositions: [],
971
+ assistPositions
972
+ });
973
+ } else setSnapData({
974
+ isMoving: true,
975
+ movePositions: [],
976
+ assistPositions: []
977
+ });
978
+ };
979
+ const handleUpdateSnap = (data) => {
980
+ if (props.snap) {
981
+ const currentScaleWidth = props.scaleWidth ?? 160;
982
+ const currentScale = props.scale ?? 1;
983
+ const currentStartLeft = props.startLeft ?? 20;
984
+ const { left, width } = parserTimeToTransform({
985
+ start: data.start,
986
+ end: data.end
987
+ }, {
988
+ startLeft: currentStartLeft,
989
+ scaleWidth: currentScaleWidth,
990
+ scale: currentScale
991
+ });
992
+ const movePositions = data.dir ? data.dir === "right" ? [left + width] : [left] : [left, left + width];
993
+ setSnapData((pre) => ({
994
+ ...pre,
995
+ movePositions
996
+ }));
997
+ }
998
+ };
999
+ const disposeSnap = () => {
1000
+ activeDragStateRef.current = null;
1001
+ setSnapData({
1002
+ isMoving: false,
1003
+ movePositions: [],
1004
+ assistPositions: []
1005
+ });
1006
+ };
1007
+ return {
1008
+ snapData,
1009
+ handleInitSnap,
1010
+ handleUpdateSnap,
1011
+ disposeSnap
1012
+ };
1013
+ };
1014
+ //#endregion
1015
+ //#region src/utils/row-layout.ts
1016
+ function getTimelineRowPresentation(params) {
1017
+ const layouts = [];
1018
+ let totalHeight = 0;
1019
+ const collapsibleRowIds = new Set(params.editorData.filter((row) => row.collapsed).map((row) => row.id));
1020
+ const defaultExpandedRowIds = params.editorData.filter((row) => row.collapsed?.expandedByDefault).map((row) => row.id);
1021
+ const focusedRowId = (params.lockedRowId && collapsibleRowIds.has(params.lockedRowId) ? params.lockedRowId : null) ?? (params.hoveredRowId && collapsibleRowIds.has(params.hoveredRowId) ? params.hoveredRowId : null) ?? defaultExpandedRowIds[0] ?? null;
1022
+ for (const row of params.editorData) {
1023
+ const expandedHeight = row.rowHeight || params.rowHeight;
1024
+ const collapsedHeight = row.collapsed?.height ?? params.collapsedRowHeight;
1025
+ const isCollapsed = Boolean(row.collapsed && row.id !== focusedRowId);
1026
+ const height = isCollapsed ? collapsedHeight : expandedHeight;
1027
+ layouts.push({
1028
+ row,
1029
+ top: totalHeight,
1030
+ height,
1031
+ isCollapsed
1032
+ });
1033
+ totalHeight += height;
1034
+ }
1035
+ return {
1036
+ layouts,
1037
+ totalHeight,
1038
+ defaultExpandedRowIds
1039
+ };
1040
+ }
1041
+ //#endregion
1042
+ //#region src/components/edit_area/edit-area.tsx
1043
+ const EditArea = ({ ref, ...props }) => {
1044
+ const { snapData, handleInitSnap, handleUpdateSnap, disposeSnap } = useSnap({
1045
+ snap: props.snap,
1046
+ hideCursor: props.hideCursor,
1047
+ cursorTime: props.cursorTime,
1048
+ scaleWidth: props.scaleWidth,
1049
+ scale: props.scale,
1050
+ startLeft: props.startLeft,
1051
+ getAssistDragLineActionIds: props.getAssistDragLineActionIds,
1052
+ editorData: props.editorData,
1053
+ snapPositions: props.snapPositions
1054
+ });
1055
+ const currentScaleWidth = props.scaleWidth ?? 160;
1056
+ const currentStartLeft = props.startLeft ?? 20;
1057
+ const contentWidth = Math.max(props.scaleCount * currentScaleWidth + currentStartLeft, props.timelineWidth);
1058
+ const rows = (() => {
1059
+ let result = [];
1060
+ for (const { row, top, height, isCollapsed } of props.rowLayouts) result.push(/* @__PURE__ */ createElement(EditRow, {
1061
+ ...props,
1062
+ key: row.id,
1063
+ rowData: row,
1064
+ rowRenderHeight: height,
1065
+ isCollapsed,
1066
+ snapData,
1067
+ scrollContainerRef: props.scrollElementRef,
1068
+ style: {
1069
+ position: "absolute",
1070
+ top: 0,
1071
+ left: 0,
1072
+ width: contentWidth,
1073
+ height: `${height}px`,
1074
+ transform: `translateY(${top}px)`
1075
+ },
1076
+ onPointerEnter: () => {
1077
+ if (row.collapsed) props.setHoveredRowId(row.id);
1078
+ },
1079
+ onPointerLeave: () => {
1080
+ props.clearHoveredRowId(row.id);
1081
+ },
1082
+ onActionMoveStart: (data) => {
1083
+ if (row.collapsed) props.setLockedRowId(row.id);
1084
+ handleInitSnap(data);
1085
+ return props.onActionMoveStart && props.onActionMoveStart(data);
1086
+ },
1087
+ onActionResizeStart: (data) => {
1088
+ if (row.collapsed) props.setLockedRowId(row.id);
1089
+ handleInitSnap(data);
1090
+ return props.onActionResizeStart && props.onActionResizeStart(data);
1091
+ },
1092
+ onActionMoving: (data) => {
1093
+ handleUpdateSnap(data);
1094
+ return props.onActionMoving && props.onActionMoving(data);
1095
+ },
1096
+ onActionResizing: (data) => {
1097
+ handleUpdateSnap(data);
1098
+ return props.onActionResizing && props.onActionResizing(data);
1099
+ },
1100
+ onActionResizeEnd: (data) => {
1101
+ props.setLockedRowId(null);
1102
+ disposeSnap();
1103
+ return props.onActionResizeEnd && props.onActionResizeEnd(data);
1104
+ },
1105
+ onActionMoveEnd: (data) => {
1106
+ props.setLockedRowId(null);
1107
+ disposeSnap();
1108
+ return props.onActionMoveEnd && props.onActionMoveEnd(data);
1109
+ }
1110
+ }));
1111
+ return result;
1112
+ })();
1113
+ return /* @__PURE__ */ jsxs("div", {
1114
+ ref,
1115
+ style: {
1116
+ width: contentWidth,
1117
+ height: props.rowLayoutsTotalHeight,
1118
+ position: "relative",
1119
+ backgroundPositionX: `0, ${props.startLeft ?? 20}px`,
1120
+ backgroundSize: `${props.startLeft ?? 20}px, ${props.scaleWidth ?? 160}px`
1121
+ },
1122
+ className: "timeline-editor-edit-area",
1123
+ children: [rows, props.snap && /* @__PURE__ */ jsx(SnapGuideLines, { ...snapData })]
1124
+ });
1125
+ };
1126
+ //#endregion
1127
+ //#region src/components/time_area/time-area.tsx
1128
+ function TimeArea({ scaleSplitCount, scaleWidth, startLeft, scaleCount, maxScaleCount, scale, scrollElementRef, onClickTimeArea, setCursor, getScaleRender }) {
1129
+ const splitCount = scaleSplitCount ?? 1;
1130
+ const width = scaleWidth ?? 160;
1131
+ const left = startLeft ?? 20;
1132
+ /** Whether to show sub-scale marks */
1133
+ const showUnit = (scaleSplitCount ?? 0) > 0;
1134
+ const columnCount = showUnit ? scaleCount * (scaleSplitCount ?? 1) + 1 : scaleCount;
1135
+ const totalWidth = (showUnit ? width / splitCount : width) * (columnCount - 1) + left;
1136
+ const getColumnWidth = (index) => {
1137
+ switch (index) {
1138
+ case 0: return left;
1139
+ default: return showUnit ? width / splitCount : width;
1140
+ }
1141
+ };
1142
+ const virtualizer = useVirtualizer({
1143
+ horizontal: true,
1144
+ count: columnCount,
1145
+ getScrollElement: () => scrollElementRef.current,
1146
+ estimateSize: getColumnWidth,
1147
+ overscan: 10
1148
+ });
1149
+ useEffect(() => virtualizer.measure(), [
1150
+ scale,
1151
+ scaleWidth,
1152
+ startLeft,
1153
+ virtualizer
1154
+ ]);
1155
+ return /* @__PURE__ */ jsx("div", {
1156
+ style: { width: `${totalWidth}px` },
1157
+ className: prefix("time-area"),
1158
+ onClick: (e) => {
1159
+ const leftStart = startLeft ?? 20;
1160
+ const widthValue = scaleWidth ?? 160;
1161
+ const scaleValue = scale ?? 1;
1162
+ const maxCount = maxScaleCount ?? Infinity;
1163
+ const rect = e.currentTarget.getBoundingClientRect();
1164
+ const position = e.clientX - rect.x;
1165
+ const left = Math.max(position, leftStart);
1166
+ if (left > maxCount * widthValue + leftStart) return;
1167
+ const time = parserPixelToTime(left, {
1168
+ startLeft: leftStart,
1169
+ scale: scaleValue,
1170
+ scaleWidth: widthValue
1171
+ });
1172
+ onClickTimeArea && onClickTimeArea(time, e);
1173
+ if (e.defaultPrevented) return;
1174
+ setCursor({ time });
1175
+ },
1176
+ children: virtualizer.getVirtualItems().map((virtualColumn) => {
1177
+ const columnIndex = virtualColumn.index;
1178
+ const splitCount = scaleSplitCount ?? 1;
1179
+ const scaleValue = scale ?? 1;
1180
+ const isShowScale = showUnit ? columnIndex % splitCount === 0 : true;
1181
+ const classNames = [prefix("time-unit"), isShowScale ? prefix("time-unit-big") : prefix("time-unit-small")];
1182
+ const item = (showUnit ? columnIndex / splitCount : columnIndex) * scaleValue;
1183
+ return /* @__PURE__ */ jsx("div", {
1184
+ "data-index": virtualColumn.index,
1185
+ style: {
1186
+ width: `${virtualColumn.size}px`,
1187
+ transform: `translateX(${virtualColumn.start}px)`
1188
+ },
1189
+ className: classNames.join(" "),
1190
+ children: isShowScale && /* @__PURE__ */ jsx("div", {
1191
+ className: prefix("time-unit-scale"),
1192
+ children: getScaleRender?.(item) ?? item
1193
+ })
1194
+ }, virtualColumn.key);
1195
+ })
1196
+ });
1197
+ }
1198
+ //#endregion
1199
+ //#region src/utils/with-hook.tsx
1200
+ function withHooks(hook) {
1201
+ const Component = ({ children, ...params }) => {
1202
+ return children(hook(params));
1203
+ };
1204
+ Component.displayName = `withHooks(${hook.name || "Hook"})`;
1205
+ return Component;
1206
+ }
1207
+ //#endregion
1208
+ //#region src/utils/measured.tsx
1209
+ function useMeasure({ elementRef }) {
1210
+ const [size, setSize] = useState({
1211
+ width: 0,
1212
+ height: 0
1213
+ });
1214
+ useLayoutEffect(() => {
1215
+ if (!elementRef.current) return;
1216
+ resize(elementRef.current, (_el, size) => {
1217
+ setSize({
1218
+ width: size.width,
1219
+ height: size.height
1220
+ });
1221
+ });
1222
+ }, [elementRef]);
1223
+ return size;
1224
+ }
1225
+ withHooks(useMeasure);
1226
+ //#endregion
1227
+ //#region src/components/cursor/cursor.tsx
1228
+ const Cursor = ({ disableDrag, height, cursorTime, setCursor, startLeft, scaleWidth, scale, scaleCount, scaleSplitCount, scrollElementRef, maxScaleCount, onCursorDragStart, onCursorDrag, onCursorDragEnd, cursorSnap, autoScrollSpeed, autoScrollMaxSpeed, snapPositions = [] }) => {
1229
+ const rowRnd = useRef(null);
1230
+ const leftStart = startLeft ?? 20;
1231
+ const width = scaleWidth ?? 160;
1232
+ const scaleValue = scale ?? 1;
1233
+ const activeSnapPositions = !cursorSnap ? [] : snapPositions;
1234
+ useEffect(() => {
1235
+ if (rowRnd.current) {
1236
+ const left = startLeft ?? 20;
1237
+ const width = scaleWidth ?? 160;
1238
+ const scaleValue = scale ?? 1;
1239
+ rowRnd.current.updateLeft(parserTimeToPixel(cursorTime, {
1240
+ startLeft: left,
1241
+ scaleWidth: width,
1242
+ scale: scaleValue
1243
+ }));
1244
+ }
1245
+ }, [
1246
+ cursorTime,
1247
+ startLeft,
1248
+ scaleWidth,
1249
+ scale
1250
+ ]);
1251
+ const maxCount = maxScaleCount ?? Infinity;
1252
+ const showUnit = (scaleSplitCount ?? 0) > 0;
1253
+ const splitCount = scaleSplitCount ?? 1;
1254
+ const columnCount = showUnit ? scaleCount * (scaleSplitCount ?? 1) + 1 : scaleCount;
1255
+ const left = startLeft ?? 20;
1256
+ const totalWidth = (showUnit ? width / splitCount : width) * (columnCount - 1) + left;
1257
+ return /* @__PURE__ */ jsx(RowDnd, {
1258
+ start: leftStart,
1259
+ ref: rowRnd,
1260
+ parentRef: scrollElementRef,
1261
+ getBounds: () => {
1262
+ return {
1263
+ left: 0,
1264
+ right: Math.min(totalWidth, maxCount * width + leftStart - (scrollElementRef.current?.scrollLeft ?? 0))
1265
+ };
1266
+ },
1267
+ autoScroll: true,
1268
+ autoScrollSpeed,
1269
+ autoScrollMaxSpeed,
1270
+ enableDragging: !disableDrag,
1271
+ enableResizing: false,
1272
+ snapPositions: activeSnapPositions,
1273
+ snapDistance: 8,
1274
+ snapOrigin: "left",
1275
+ onDragStart: () => {
1276
+ const time = parserPixelToTime(rowRnd.current?.getLeft() ?? parserTimeToPixel(cursorTime, {
1277
+ startLeft: leftStart,
1278
+ scaleWidth: width,
1279
+ scale: scaleValue
1280
+ }), {
1281
+ startLeft: leftStart,
1282
+ scale: scaleValue,
1283
+ scaleWidth: width
1284
+ });
1285
+ onCursorDragStart && onCursorDragStart(time);
1286
+ },
1287
+ onDragEnd: ({ left }) => {
1288
+ const time = parserPixelToTime(left, {
1289
+ startLeft: leftStart,
1290
+ scale: scaleValue,
1291
+ scaleWidth: width
1292
+ });
1293
+ setCursor({ time });
1294
+ onCursorDragEnd && onCursorDragEnd(time);
1295
+ },
1296
+ onDrag: ({ left }) => {
1297
+ const time = parserPixelToTime(left, {
1298
+ startLeft: leftStart,
1299
+ scale: scaleValue,
1300
+ scaleWidth: width
1301
+ });
1302
+ setCursor({ time });
1303
+ onCursorDrag && onCursorDrag(time);
1304
+ },
1305
+ children: /* @__PURE__ */ jsxs("div", {
1306
+ className: prefix("cursor"),
1307
+ style: { height },
1308
+ children: [/* @__PURE__ */ jsx("svg", {
1309
+ className: prefix("cursor-top"),
1310
+ width: "8",
1311
+ height: "12",
1312
+ viewBox: "0 0 8 12",
1313
+ fill: "none",
1314
+ children: /* @__PURE__ */ jsx("path", {
1315
+ d: "M0 1C0 0.447715 0.447715 0 1 0H7C7.55228 0 8 0.447715 8 1V9.38197C8 9.76074 7.786 10.107 7.44721 10.2764L4.44721 11.7764C4.16569 11.9172 3.83431 11.9172 3.55279 11.7764L0.552786 10.2764C0.214002 10.107 0 9.76074 0 9.38197V1Z",
1316
+ fill: "currentColor"
1317
+ })
1318
+ }), /* @__PURE__ */ jsx("div", { className: prefix("cursor-area") })]
1319
+ })
1320
+ });
1321
+ };
1322
+ //#endregion
1323
+ //#region src/components/scroll-area.tsx
1324
+ function ScrollBar({ className, orientation = "vertical", ...props }) {
1325
+ return /* @__PURE__ */ jsx(ScrollArea.ScrollAreaScrollbar, {
1326
+ "data-slot": "scroll-area-scrollbar",
1327
+ orientation,
1328
+ className,
1329
+ ...props,
1330
+ children: /* @__PURE__ */ jsx(ScrollArea.ScrollAreaThumb, { "data-slot": "scroll-area-thumb" })
1331
+ });
1332
+ }
1333
+ //#endregion
1334
+ //#region src/components/hooks/use-stable-scroll.ts
1335
+ /**
1336
+ * Hook to maintain scroll position stability when scale or scaleWidth changes.
1337
+ * Uses the cursor time as a reference point to keep it visually stable.
1338
+ */
1339
+ function useStableScroll({ scrollElementRef, scale, scaleWidth, startLeft, cursorTimeRef }) {
1340
+ const prevScaleRef = useRef(null);
1341
+ const prevScaleWidthRef = useRef(null);
1342
+ useLayoutEffect(() => {
1343
+ const scrollElement = scrollElementRef.current;
1344
+ if (prevScaleRef.current !== null && prevScaleWidthRef.current !== null && scrollElement && (prevScaleRef.current !== scale || prevScaleWidthRef.current !== scaleWidth)) {
1345
+ const currentScrollLeft = scrollElement.scrollLeft;
1346
+ const cursorTime = cursorTimeRef.current;
1347
+ const oldCursorPixelPosition = parserTimeToPixel(cursorTime, {
1348
+ startLeft,
1349
+ scale: prevScaleRef.current,
1350
+ scaleWidth: prevScaleWidthRef.current
1351
+ });
1352
+ scrollElement.scrollLeft = parserTimeToPixel(cursorTime, {
1353
+ startLeft,
1354
+ scale,
1355
+ scaleWidth
1356
+ }) - (oldCursorPixelPosition - currentScrollLeft);
1357
+ }
1358
+ prevScaleRef.current = scale;
1359
+ prevScaleWidthRef.current = scaleWidth;
1360
+ }, [
1361
+ scale,
1362
+ scaleWidth,
1363
+ startLeft,
1364
+ scrollElementRef,
1365
+ cursorTimeRef
1366
+ ]);
1367
+ }
1368
+ //#endregion
1369
+ //#region src/components/timeline.tsx
1370
+ function Timeline({ ref, ...props }) {
1371
+ const timelineProps = withDefaults(props);
1372
+ const domRef = useRef(null);
1373
+ const warnedDefaultRowsRef = useRef("");
1374
+ const { width, height } = useMeasure({ elementRef: domRef });
1375
+ const [hoveredRowId, setHoveredRowId] = useState(null);
1376
+ const [lockedRowId, setLockedRowId] = useState(null);
1377
+ const editorAreaKey = props.unstable_forceRemountEditorArea ?? 0;
1378
+ const minScaleCount = timelineProps.minScaleCount ?? Math.max(getScaleCountByRows(timelineProps.editorData, {
1379
+ scale: timelineProps.scale,
1380
+ pad: .1
1381
+ }), Math.ceil((width - timelineProps.startLeft) / timelineProps.scaleWidth));
1382
+ const derivedScaleCount = Math.min(timelineProps.maxScaleCount, minScaleCount);
1383
+ const snapPositions = !timelineProps.editorData ? [] : parserActionsToPositions(timelineProps.editorData.flatMap((row) => row.actions), {
1384
+ startLeft: timelineProps.startLeft,
1385
+ scale: timelineProps.scale,
1386
+ scaleWidth: timelineProps.scaleWidth
1387
+ });
1388
+ const [overrideScaleCount, setOverrideScaleCount] = useState(null);
1389
+ useLayoutEffect(() => {
1390
+ setOverrideScaleCount(null);
1391
+ }, [derivedScaleCount]);
1392
+ const scaleCount = overrideScaleCount ?? derivedScaleCount;
1393
+ const rowPresentation = getTimelineRowPresentation({
1394
+ editorData: timelineProps.editorData,
1395
+ rowHeight: timelineProps.rowHeight,
1396
+ collapsedRowHeight: timelineProps.collapsedRowHeight ?? timelineProps.rowHeight,
1397
+ hoveredRowId,
1398
+ lockedRowId
1399
+ });
1400
+ const duplicateDefaultRowsKey = rowPresentation.defaultExpandedRowIds.join("\n");
1401
+ if (rowPresentation.defaultExpandedRowIds.length > 1 && warnedDefaultRowsRef.current !== duplicateDefaultRowsKey) {
1402
+ warnedDefaultRowsRef.current = duplicateDefaultRowsKey;
1403
+ console.warn("Warning: multiple collapsible rows set expandedByDefault. The first row in editorData wins.");
1404
+ }
1405
+ /** Dynamically set scale count - overrides the derived value */
1406
+ const handleSetScaleCount = (value) => {
1407
+ setOverrideScaleCount(Math.min(timelineProps.maxScaleCount, value));
1408
+ };
1409
+ const [cursorTime, setCursorTime] = useState(0);
1410
+ const cursorTimeRef = useRef(0);
1411
+ useStableScroll({
1412
+ scrollElementRef: domRef,
1413
+ scale: timelineProps.scale,
1414
+ scaleWidth: timelineProps.scaleWidth,
1415
+ startLeft: timelineProps.startLeft,
1416
+ cursorTimeRef
1417
+ });
1418
+ /** Handle editor data changes */
1419
+ const handleEditorDataChange = (editorData) => {
1420
+ timelineProps.onChange?.(editorData);
1421
+ };
1422
+ /** Handle cursor */
1423
+ const handleSetCursor = (param) => {
1424
+ let { left, time } = param;
1425
+ if (typeof time !== "undefined") {
1426
+ setCursorTime(time);
1427
+ cursorTimeRef.current = time;
1428
+ return true;
1429
+ }
1430
+ if (typeof left !== "undefined") {
1431
+ setCursorTime(cursorTimeRef.current = parserPixelToTime(left, {
1432
+ startLeft: timelineProps.startLeft,
1433
+ scale: timelineProps.scale,
1434
+ scaleWidth: timelineProps.scaleWidth
1435
+ }));
1436
+ return true;
1437
+ }
1438
+ return false;
1439
+ };
1440
+ const handleScrollToTime = (time, options = {}) => {
1441
+ const element = domRef.current;
1442
+ if (!element) return;
1443
+ const { block = "start", offset = 0, onlyIfNotVisible = false } = options;
1444
+ const target = parserTimeToPixel(time, {
1445
+ startLeft: timelineProps.startLeft,
1446
+ scale: timelineProps.scale,
1447
+ scaleWidth: timelineProps.scaleWidth
1448
+ });
1449
+ const viewportWidth = element.clientWidth;
1450
+ if (onlyIfNotVisible) {
1451
+ const currentScrollLeft = element.scrollLeft;
1452
+ if (target >= currentScrollLeft && target <= currentScrollLeft + viewportWidth) return;
1453
+ }
1454
+ let targetScrollLeft;
1455
+ if (block === "end") targetScrollLeft = target - viewportWidth + offset;
1456
+ else if (block === "center") targetScrollLeft = target - viewportWidth / 2;
1457
+ else targetScrollLeft = target - offset;
1458
+ const maxScrollLeft = Math.max(0, element.scrollWidth - viewportWidth);
1459
+ element.scrollTo({
1460
+ left: Math.min(Math.max(targetScrollLeft, 0), maxScrollLeft),
1461
+ behavior: options.behavior ?? "instant"
1462
+ });
1463
+ };
1464
+ useImperativeHandle(ref, () => ({
1465
+ get target() {
1466
+ return domRef.current;
1467
+ },
1468
+ set time(time) {
1469
+ handleSetCursor({ time });
1470
+ },
1471
+ get time() {
1472
+ return cursorTimeRef.current;
1473
+ },
1474
+ getTime() {
1475
+ return cursorTimeRef.current;
1476
+ },
1477
+ setTime(time) {
1478
+ handleSetCursor({ time });
1479
+ },
1480
+ getTimePixelPosition(time) {
1481
+ return parserTimeToPixel(time ?? cursorTimeRef.current, {
1482
+ startLeft: timelineProps.startLeft,
1483
+ scale: timelineProps.scale,
1484
+ scaleWidth: timelineProps.scaleWidth
1485
+ });
1486
+ },
1487
+ setScrollLeft: (val) => {
1488
+ if (!domRef.current) return;
1489
+ domRef.current.scrollLeft = val;
1490
+ },
1491
+ setScrollTop: (val) => {
1492
+ if (!domRef.current) return;
1493
+ domRef.current.scrollTop = val;
1494
+ },
1495
+ get scrollLeft() {
1496
+ if (!domRef.current) return 0;
1497
+ return domRef.current.scrollLeft;
1498
+ },
1499
+ get scrollTop() {
1500
+ if (!domRef.current) return 0;
1501
+ return domRef.current.scrollTop;
1502
+ },
1503
+ set scrollLeft(val) {
1504
+ if (!domRef.current) return;
1505
+ domRef.current.scrollLeft = val;
1506
+ },
1507
+ set scrollTop(val) {
1508
+ if (!domRef.current) return;
1509
+ domRef.current.scrollTop = val;
1510
+ },
1511
+ scrollToTime: handleScrollToTime
1512
+ }));
1513
+ return /* @__PURE__ */ jsxs(ScrollArea.Root, {
1514
+ style: timelineProps.style,
1515
+ className: `${PREFIX} ${timelineProps.disableDrag ? PREFIX + "-disable" : ""}`,
1516
+ "data-slot": "scroll-area",
1517
+ children: [
1518
+ /* @__PURE__ */ jsxs(ScrollArea.Viewport, {
1519
+ "data-slot": "scroll-area-viewport",
1520
+ ref: domRef,
1521
+ onScroll: (e) => {
1522
+ timelineProps.onScroll?.(e.currentTarget);
1523
+ },
1524
+ children: [
1525
+ /* @__PURE__ */ jsx(TimeArea, {
1526
+ ...timelineProps,
1527
+ setCursor: handleSetCursor,
1528
+ scaleCount,
1529
+ scrollElementRef: domRef
1530
+ }),
1531
+ /* @__PURE__ */ jsx(EditArea, {
1532
+ ...timelineProps,
1533
+ scrollElementRef: domRef,
1534
+ timelineWidth: width,
1535
+ timelineHeight: height,
1536
+ disableDrag: timelineProps.disableDrag,
1537
+ editorData: timelineProps.editorData,
1538
+ cursorTime,
1539
+ scaleCount,
1540
+ setScaleCount: handleSetScaleCount,
1541
+ setEditorData: handleEditorDataChange,
1542
+ snapPositions,
1543
+ rowLayouts: rowPresentation.layouts,
1544
+ rowLayoutsTotalHeight: rowPresentation.totalHeight,
1545
+ setHoveredRowId,
1546
+ clearHoveredRowId: (rowId) => {
1547
+ setHoveredRowId((currentRowId) => currentRowId === rowId ? null : currentRowId);
1548
+ },
1549
+ setLockedRowId
1550
+ }, `__editor_area_${editorAreaKey}__`),
1551
+ !timelineProps.hideCursor && /* @__PURE__ */ jsx(Cursor, {
1552
+ ...timelineProps,
1553
+ timelineWidth: width,
1554
+ height: Math.max(height, rowPresentation.totalHeight + 42),
1555
+ scaleCount,
1556
+ setScaleCount: handleSetScaleCount,
1557
+ setCursor: handleSetCursor,
1558
+ cursorTime,
1559
+ editorData: timelineProps.editorData,
1560
+ scrollElementRef: domRef,
1561
+ snapPositions
1562
+ })
1563
+ ]
1564
+ }),
1565
+ /* @__PURE__ */ jsx(ScrollBar, { orientation: "horizontal" }),
1566
+ /* @__PURE__ */ jsx(ScrollBar, { orientation: "vertical" }),
1567
+ /* @__PURE__ */ jsx(ScrollArea.Corner, {})
1568
+ ]
1569
+ });
1570
+ }
1571
+ //#endregion
1572
+ export { Timeline };