@flycut/timeline-kit 0.0.0-stage → 0.2.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.
Files changed (88) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +227 -2
  3. package/dist/chunks/TimelineEditor-ZMbJ8-ee.js +2051 -0
  4. package/dist/chunks/TimelineEditor-ZMbJ8-ee.js.map +1 -0
  5. package/dist/chunks/index-KK9cAE8q.js +661 -0
  6. package/dist/chunks/index-KK9cAE8q.js.map +1 -0
  7. package/dist/chunks/interactionManager-JoPxZ8st.js +775 -0
  8. package/dist/chunks/interactionManager-JoPxZ8st.js.map +1 -0
  9. package/dist/chunks/otio-6KO_Tfi1.js +510 -0
  10. package/dist/chunks/otio-6KO_Tfi1.js.map +1 -0
  11. package/dist/core.js +1673 -0
  12. package/dist/core.js.map +1 -0
  13. package/dist/index.js +100 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/otio.js +313 -0
  16. package/dist/otio.js.map +1 -0
  17. package/dist/plugins.js +243 -0
  18. package/dist/plugins.js.map +1 -0
  19. package/dist/react.js +259 -0
  20. package/dist/react.js.map +1 -0
  21. package/dist/types/adapters/react/index.d.ts +45 -0
  22. package/dist/types/adapters/vue/index.d.ts +202 -0
  23. package/dist/types/src/adapters/otio.d.ts +7 -0
  24. package/dist/types/src/core-entry.d.ts +8 -0
  25. package/dist/types/src/editor/TimelineEditor.d.ts +96 -0
  26. package/dist/types/src/editor/index.d.ts +2 -0
  27. package/dist/types/src/editor/types.d.ts +30 -0
  28. package/dist/types/src/engine/hitTest.d.ts +23 -0
  29. package/dist/types/src/engine/index.d.ts +7 -0
  30. package/dist/types/src/engine/layout.d.ts +47 -0
  31. package/dist/types/src/engine/magnet.d.ts +46 -0
  32. package/dist/types/src/engine/placement.d.ts +13 -0
  33. package/dist/types/src/engine/snap.d.ts +28 -0
  34. package/dist/types/src/engine/timeScale.d.ts +12 -0
  35. package/dist/types/src/engine/virtualization.d.ts +11 -0
  36. package/dist/types/src/frameworks/slotBridge.d.ts +13 -0
  37. package/dist/types/src/index.d.ts +10 -0
  38. package/dist/types/src/model/demoDocument.d.ts +3 -0
  39. package/dist/types/src/model/index.d.ts +4 -0
  40. package/dist/types/src/model/operations.d.ts +77 -0
  41. package/dist/types/src/model/structuralSharing.d.ts +11 -0
  42. package/dist/types/src/model/types.d.ts +55 -0
  43. package/dist/types/src/otio-core/commands/create.d.ts +6 -0
  44. package/dist/types/src/otio-core/commands/helpers.d.ts +5 -0
  45. package/dist/types/src/otio-core/commands/insert.d.ts +2 -0
  46. package/dist/types/src/otio-core/commands/move.d.ts +2 -0
  47. package/dist/types/src/otio-core/commands/split.d.ts +2 -0
  48. package/dist/types/src/otio-core/commands/trim.d.ts +3 -0
  49. package/dist/types/src/otio-core/flycut-otio-draft.d.ts +239 -0
  50. package/dist/types/src/otio-core/guards.d.ts +5 -0
  51. package/dist/types/src/otio-core/index.d.ts +14 -0
  52. package/dist/types/src/otio-core/media/clipMetadata.d.ts +18 -0
  53. package/dist/types/src/otio-core/media/reference.d.ts +9 -0
  54. package/dist/types/src/otio-core/selectors/clip.d.ts +4 -0
  55. package/dist/types/src/otio-core/selectors/timeline.d.ts +5 -0
  56. package/dist/types/src/otio-core/selectors/track.d.ts +8 -0
  57. package/dist/types/src/otio-core/types.d.ts +61 -0
  58. package/dist/types/src/otio-entry.d.ts +2 -0
  59. package/dist/types/src/plugins/clipDragPlugin.d.ts +2 -0
  60. package/dist/types/src/plugins/clipTrimPlugin.d.ts +2 -0
  61. package/dist/types/src/plugins/externalDropPlugin.d.ts +13 -0
  62. package/dist/types/src/plugins/index.d.ts +17 -0
  63. package/dist/types/src/plugins/interactionManager.d.ts +33 -0
  64. package/dist/types/src/plugins/marqueeSelectPlugin.d.ts +2 -0
  65. package/dist/types/src/plugins/playheadPlugin.d.ts +2 -0
  66. package/dist/types/src/plugins/selectionPlugin.d.ts +2 -0
  67. package/dist/types/src/plugins/shortcutsPlugin.d.ts +7 -0
  68. package/dist/types/src/plugins/snapProviders.d.ts +9 -0
  69. package/dist/types/src/plugins/types.d.ts +110 -0
  70. package/dist/types/src/plugins/wheelPlugin.d.ts +2 -0
  71. package/dist/types/src/plugins-entry.d.ts +1 -0
  72. package/dist/types/src/renderer/domRenderer.d.ts +73 -0
  73. package/dist/types/src/renderer/index.d.ts +6 -0
  74. package/dist/types/src/renderer/ruler.d.ts +18 -0
  75. package/dist/types/src/renderer/styles.d.ts +1 -0
  76. package/dist/types/src/renderer/types.d.ts +65 -0
  77. package/dist/types/src/renderer/ui/icons.d.ts +7 -0
  78. package/dist/types/src/renderer/ui/sidebar.d.ts +14 -0
  79. package/dist/types/src/renderer/ui/toolbar.d.ts +16 -0
  80. package/dist/types/src/store/builtinCommands.d.ts +56 -0
  81. package/dist/types/src/store/commandBus.d.ts +18 -0
  82. package/dist/types/src/store/index.d.ts +4 -0
  83. package/dist/types/src/store/store.d.ts +53 -0
  84. package/dist/types/src/store/types.d.ts +59 -0
  85. package/dist/types/src/utils/trimOffset.d.ts +9 -0
  86. package/dist/vue.js +278 -0
  87. package/dist/vue.js.map +1 -0
  88. package/package.json +111 -4
@@ -0,0 +1,2051 @@
1
+ /*!
2
+ * timeline-kit
3
+ * Copyright (c) 2026 timeline-kit authors <x007xyzabc@gmail.com>
4
+ * Dual-licensed: AGPL-3.0-only (see LICENSE) or a commercial license.
5
+ * Commercial licensing: x007xyzabc@gmail.com
6
+ */
7
+ import { i as isOtioTimeline, f as fromOtioTimeline, t as toOtioTimeline } from "./otio-6KO_Tfi1.js";
8
+ import { j as getGridSize, h as frameToSeconds, D as DEFAULT_EDIT_POLICIES, I as InteractionManager, l as getPixelsPerSecond, p as msToPx } from "./interactionManager-JoPxZ8st.js";
9
+ import { computeTimelineLayout, hitTestLayout, computeVisibleRange, filterVisibleClips, TimelineStore, CommandBus, registerBuiltinCommands, cloneDocument } from "../core.js";
10
+ import { d as createDefaultPlugins } from "./index-KK9cAE8q.js";
11
+ function isOtioClip(clip) {
12
+ return typeof clip === "object" && clip !== null && clip.OTIO_SCHEMA === "Clip.1";
13
+ }
14
+ function toMilliseconds(time) {
15
+ if (!time || !time.rate) {
16
+ return 0;
17
+ }
18
+ return time.value / time.rate * 1e3;
19
+ }
20
+ function getTrimOffset(input) {
21
+ if (!input || typeof input !== "object") {
22
+ return { offsetPercent: 0, scalePercent: 100 };
23
+ }
24
+ if (isOtioClip(input)) {
25
+ const clip2 = input;
26
+ const trimStartMs = toMilliseconds(clip2.source_range?.start_time);
27
+ const trimDurationMs = toMilliseconds(clip2.source_range?.duration);
28
+ const availableDurationMs = clip2.media_reference?.OTIO_SCHEMA === "ExternalReference.1" && clip2.media_reference.available_range ? toMilliseconds(clip2.media_reference.available_range.duration) : void 0;
29
+ const tkDurationMs = Number(clip2.metadata?.timelineKit?.durationMs ?? 0) || void 0;
30
+ const totalDuration2 = availableDurationMs ?? tkDurationMs ?? trimDurationMs;
31
+ if (!totalDuration2 || totalDuration2 <= 0) {
32
+ return { offsetPercent: 0, scalePercent: 100 };
33
+ }
34
+ return {
35
+ offsetPercent: trimStartMs / totalDuration2 * 100,
36
+ scalePercent: trimDurationMs / totalDuration2 * 100
37
+ };
38
+ }
39
+ const clip = input;
40
+ if (clip.trim && typeof clip.trim.startMs === "number" && typeof clip.trim.endMs === "number") {
41
+ const totalDuration2 = typeof clip.durationMs === "number" && clip.durationMs > 0 ? clip.durationMs : Math.max(0, (clip.endMs ?? 0) - (clip.startMs ?? 0));
42
+ if (totalDuration2 <= 0) {
43
+ return { offsetPercent: 0, scalePercent: 100 };
44
+ }
45
+ return {
46
+ offsetPercent: clip.trim.startMs / totalDuration2 * 100,
47
+ scalePercent: (clip.trim.endMs - clip.trim.startMs) / totalDuration2 * 100
48
+ };
49
+ }
50
+ if (!clip.trimInfo || !clip.resourceInfo) {
51
+ return { offsetPercent: 0, scalePercent: 100 };
52
+ }
53
+ const { startMs, endMs } = clip.trimInfo;
54
+ const totalDuration = clip.resourceInfo.duration || (clip.end ?? 0) - (clip.start ?? 0);
55
+ if (!totalDuration || totalDuration <= 0) {
56
+ return { offsetPercent: 0, scalePercent: 100 };
57
+ }
58
+ return {
59
+ offsetPercent: startMs / totalDuration * 100,
60
+ scalePercent: (endMs - startMs) / totalDuration * 100
61
+ };
62
+ }
63
+ function formatDurationSeconds(totalSeconds) {
64
+ const clamped = Math.max(0, Math.floor(totalSeconds));
65
+ const hours = Math.floor(clamped / 3600);
66
+ const minutes = Math.floor(clamped % 3600 / 60);
67
+ const seconds = clamped % 60;
68
+ if (hours > 0) {
69
+ return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
70
+ }
71
+ return `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
72
+ }
73
+ function formatMajorLabel(bigIndex, scale) {
74
+ let seconds = bigIndex;
75
+ if (scale < 30) {
76
+ seconds *= 60;
77
+ } else if (scale < 70) {
78
+ seconds *= 10;
79
+ }
80
+ return formatDurationSeconds(seconds);
81
+ }
82
+ function formatMinorLabel(smallIndex, step, scale) {
83
+ if (scale < 70 || scale <= 80) {
84
+ return "";
85
+ }
86
+ const index = (smallIndex % step + step) % step;
87
+ if (index === 0) {
88
+ return "";
89
+ }
90
+ return `${index < 10 ? "0" : ""}${index}f`;
91
+ }
92
+ function drawTimeRuler(context, options) {
93
+ const { startPx, fps, scale, totalFrames, width, height, ratio, palette } = options;
94
+ const safeFps = fps > 0 ? fps : 24;
95
+ const step = scale >= 70 ? Math.max(1, Math.round(safeFps)) : 10;
96
+ const gridSizeS = getGridSize(scale, safeFps);
97
+ const gridSizeB = gridSizeS * step;
98
+ const textSize = 12;
99
+ const textScale = 0.83;
100
+ const lineWidth = 0.5;
101
+ context.setTransform(ratio, 0, 0, ratio, 0, 0);
102
+ context.clearRect(0, 0, width, height);
103
+ context.fillStyle = palette.bgColor;
104
+ context.fillRect(0, 0, width, height);
105
+ context.font = `${textSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;
106
+ context.lineWidth = 1;
107
+ context.textBaseline = "middle";
108
+ context.textAlign = "left";
109
+ if (totalFrames > 0) {
110
+ let fCount = totalFrames;
111
+ if (scale < 30) {
112
+ fCount = fCount / safeFps / 6;
113
+ } else if (scale < 70) {
114
+ fCount = fCount / safeFps;
115
+ }
116
+ const focusStart = lineWidth - startPx;
117
+ const focusWidth = fCount * gridSizeS - lineWidth;
118
+ if (focusWidth > gridSizeS) {
119
+ context.fillStyle = palette.focusColor;
120
+ context.fillRect(focusStart, 0, focusWidth, height * 0.375);
121
+ }
122
+ }
123
+ const startValueB = Math.floor(startPx / gridSizeB) * gridSizeB;
124
+ const startValueS = Math.floor(startPx / gridSizeS) * gridSizeS;
125
+ const endValue = startPx + Math.ceil(width) + gridSizeB;
126
+ context.beginPath();
127
+ context.fillStyle = palette.textColor;
128
+ context.strokeStyle = palette.longColor;
129
+ for (let value = startValueB; value < endValue; value += gridSizeB) {
130
+ const x = value - startPx + lineWidth;
131
+ const bigIndex = Math.round(value / gridSizeB);
132
+ context.moveTo(x, 0);
133
+ context.lineTo(x, height * 0.625);
134
+ if (bigIndex >= 0) {
135
+ context.save();
136
+ context.translate(x + 4, height * 0.55);
137
+ context.scale(textScale, textScale);
138
+ context.fillText(formatMajorLabel(bigIndex, scale), 0, 0);
139
+ context.restore();
140
+ }
141
+ }
142
+ context.stroke();
143
+ context.beginPath();
144
+ context.fillStyle = palette.subTextColor;
145
+ context.strokeStyle = palette.shortColor;
146
+ for (let value = startValueS; value < endValue; value += gridSizeS) {
147
+ const smallIndex = Math.round(value / gridSizeS);
148
+ if (smallIndex < 0) {
149
+ continue;
150
+ }
151
+ const x = value - startPx + lineWidth;
152
+ if (smallIndex % step !== 0) {
153
+ context.moveTo(x, 0);
154
+ context.lineTo(x, height * 0.34);
155
+ }
156
+ const minorText = formatMinorLabel(smallIndex, step, scale);
157
+ if (minorText) {
158
+ context.save();
159
+ context.translate(x + 3, height * 0.55);
160
+ context.scale(textScale, textScale);
161
+ context.fillText(minorText, 0, 0);
162
+ context.restore();
163
+ }
164
+ }
165
+ context.stroke();
166
+ context.setTransform(1, 0, 0, 1, 0, 0);
167
+ }
168
+ const STYLE_ID = "timeline-kit-editor-styles";
169
+ const styles = `
170
+ .tk-timeline-editor{--tk-border:#d1d5db;--tk-border-strong:#64748b;--tk-bg:#ffffff;--tk-panel:#f9fafb;--tk-surface:#ffffff;--tk-track:#e5e7eb;--tk-text:#111827;--tk-muted:#6b7280;--tk-accent:#3b82f6;--tk-danger:#ef4444;--tk-ruler-bg:#e5e7eb;--tk-ruler-text:#374151;--tk-ruler-sub:#6b7280;--tk-ruler-long:#374151;--tk-ruler-short:#6b7280;--tk-ruler-focus:#c4b5fd;position:relative;display:flex;flex-direction:column;width:100%;height:100%;min-width:0;min-height:0;overflow:hidden;user-select:none;outline:none;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:var(--tk-text);background:var(--tk-bg)}
171
+ .tk-timeline-editor[data-theme="dark"]{--tk-border:#2b3442;--tk-border-strong:#60a5fa;--tk-bg:#111827;--tk-panel:#192131;--tk-surface:#0f172a;--tk-track:#1f2937;--tk-text:#e5e7eb;--tk-muted:#94a3b8;--tk-accent:#60a5fa;--tk-danger:#f87171;--tk-ruler-bg:#1f2937;--tk-ruler-text:#e5e7eb;--tk-ruler-sub:#94a3b8;--tk-ruler-long:#cbd5e1;--tk-ruler-short:#94a3b8;--tk-ruler-focus:#312e81}
172
+ .dark .tk-timeline-editor[data-theme="auto"]{--tk-border:#2b3442;--tk-border-strong:#60a5fa;--tk-bg:#111827;--tk-panel:#192131;--tk-surface:#0f172a;--tk-track:#1f2937;--tk-text:#e5e7eb;--tk-muted:#94a3b8;--tk-accent:#60a5fa;--tk-danger:#f87171;--tk-ruler-bg:#1f2937;--tk-ruler-text:#e5e7eb;--tk-ruler-sub:#94a3b8;--tk-ruler-long:#cbd5e1;--tk-ruler-short:#94a3b8;--tk-ruler-focus:#312e81}
173
+ @media (prefers-color-scheme: dark){
174
+ .tk-timeline-editor[data-theme="auto"]{--tk-border:#2b3442;--tk-border-strong:#60a5fa;--tk-bg:#111827;--tk-panel:#192131;--tk-surface:#0f172a;--tk-track:#1f2937;--tk-text:#e5e7eb;--tk-muted:#94a3b8;--tk-accent:#60a5fa;--tk-danger:#f87171;--tk-ruler-bg:#1f2937;--tk-ruler-text:#e5e7eb;--tk-ruler-sub:#94a3b8;--tk-ruler-long:#cbd5e1;--tk-ruler-short:#94a3b8;--tk-ruler-focus:#312e81}
175
+ }
176
+ .tk-timeline-toolbar{flex:0 0 auto;padding:8px 16px 6px;border-bottom:1px solid var(--tk-border);background:var(--tk-bg)}
177
+ .tk-toolbar-shell{display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:32px;flex-wrap:wrap}
178
+ .tk-toolbar-group{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
179
+ .tk-toolbar-button,.tk-zoom-button{appearance:none;border:0;background:transparent;color:var(--tk-muted);font-size:12px;line-height:1;cursor:pointer;padding:6px 8px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center}
180
+ .tk-toolbar-button[data-command="undo"],.tk-toolbar-button[data-command="redo"],.tk-toolbar-button[data-command="split"],.tk-toolbar-button[data-command="delete"],.tk-toolbar-button[data-command="magnet"],.tk-toolbar-button[data-command="fit"]{width:24px;height:24px;padding:0}
181
+ .tk-toolbar-button:hover:not(:disabled),.tk-zoom-button:hover{background:color-mix(in srgb,var(--tk-accent) 14%,transparent);color:var(--tk-accent)}
182
+ .tk-toolbar-button.is-active{color:var(--tk-accent);background:color-mix(in srgb,var(--tk-accent) 22%,transparent)}
183
+ .tk-toolbar-button:disabled{opacity:.4;cursor:not-allowed}
184
+ .tk-toolbar-zoom{display:flex;align-items:center;gap:8px;margin-left:16px;width:min(208px,100%);min-width:120px;height:32px;flex:1 1 180px}
185
+ .tk-zoom-button{padding:0;width:22px;height:22px}
186
+ .tk-zoom-slider{width:100%;accent-color:var(--tk-accent);cursor:pointer}
187
+ .tk-timeline-workspace{position:relative;flex:1 1 auto;min-height:0;display:flex;flex-direction:row;overflow:hidden}
188
+ .tk-timeline-sidebar{flex:0 0 auto;display:flex;flex-direction:column;width:112px;border-right:1px solid var(--tk-border);overflow:hidden;background:var(--tk-surface)}
189
+ .tk-timeline-sidebar-header{flex:0 0 auto;height:20px;background:var(--tk-panel);border-bottom:1px solid var(--tk-border);box-sizing:border-box}
190
+ .tk-timeline-sidebar-body{display:flex;flex:1 1 auto;flex-direction:column;gap:4px;min-height:0;box-sizing:border-box;will-change:transform}
191
+ .tk-track-label{display:flex;flex:0 0 auto;align-items:center;justify-content:center;gap:10px;width:100%;padding:0 6px;background:var(--tk-surface);box-sizing:border-box}
192
+ .tk-track-icon{display:flex;align-items:center;justify-content:center;min-width:20px;min-height:20px}
193
+ .tk-track-controls{display:flex;align-items:center;justify-content:center;gap:6px}
194
+ .tk-track-toggle{appearance:none;border:0;background:transparent;padding:0;width:18px;height:18px;border-radius:4px;color:var(--tk-muted);cursor:pointer;display:flex;align-items:center;justify-content:center}
195
+ .tk-track-toggle:hover{background:var(--tk-track)}
196
+ .tk-track-toggle.is-active{color:var(--tk-accent)}
197
+ .tk-lucide{display:block;flex:none}
198
+ .tk-timeline-main{position:relative;flex:1 1 auto;min-width:0;min-height:0;overflow:hidden;background:var(--tk-surface)}
199
+ .tk-timeline-main-scroller{position:relative;display:flex;flex-direction:column;overflow:auto;height:100%}
200
+ .tk-timeline-ruler{position:sticky;top:0;left:0;right:0;height:20px;flex:0 0 20px;z-index:20;background:var(--tk-ruler-bg);cursor:pointer}
201
+ .tk-ruler-canvas{display:block;width:100%;height:100%}
202
+ .tk-tracks-viewport{position:relative;flex:1 0 auto;min-height:calc(100% - 20px)}
203
+ .tk-tracks{position:relative;display:flex;flex-direction:column;gap:4px;min-height:100%;box-sizing:border-box}
204
+ .tk-empty-state{position:absolute;inset:20px 0 20px 0;display:none;align-items:center;justify-content:center;color:var(--tk-muted);font-size:14px;z-index:2}
205
+ .tk-guideline{position:absolute;display:none;pointer-events:none;z-index:25}
206
+ .tk-guideline-vertical{top:0;bottom:0;width:1px;background:var(--tk-accent)}
207
+ .tk-guideline-horizontal{left:0;right:0;height:2px;background:var(--tk-accent)}
208
+ .tk-drag-preview{position:absolute;display:none;align-items:center;justify-content:center;background:color-mix(in srgb,var(--tk-accent) 18%,transparent);border:2px dashed var(--tk-accent);border-radius:4px;color:var(--tk-accent);font-size:12px;font-weight:700;pointer-events:none;z-index:22;box-sizing:border-box}
209
+ .tk-marquee{position:absolute;display:none;pointer-events:none;z-index:26;border:1px solid var(--tk-accent);background:color-mix(in srgb,var(--tk-accent) 14%,transparent);border-radius:2px;box-sizing:border-box}
210
+ .tk-track-row{position:relative;flex:0 0 auto;background:var(--tk-track);border:2px solid transparent;box-sizing:border-box}
211
+ .tk-track-lane{position:relative;height:100%;box-sizing:border-box}
212
+ .tk-track-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;pointer-events:none;z-index:20}
213
+ .tk-track-overlay.is-locked{background:rgba(254,202,202,.28)}
214
+ .tk-track-overlay.is-hidden{background:rgba(209,213,219,.45)}
215
+ .tk-track-overlay.is-muted{background:rgba(254,240,138,.3)}
216
+ .tk-track-overlay-badge{padding:2px 8px;border-radius:999px;background:color-mix(in srgb,var(--tk-surface) 88%,transparent);font-size:11px;font-weight:600}
217
+ .tk-track-clip{position:absolute;top:0;bottom:0;border-radius:4px;overflow:visible;border:1px solid rgba(255,255,255,.12);cursor:grab;box-sizing:border-box}
218
+ .tk-track-clip-content{height:100%;width:100%;overflow:hidden;border-radius:3px;display:flex;align-items:stretch;justify-content:flex-start}
219
+ .tk-track-clip.is-selected{z-index:15;box-shadow:0 0 0 2px var(--tk-border-strong)}
220
+ .tk-track-clip.is-dragging{z-index:18;cursor:grabbing;opacity:.88}
221
+ .tk-track-clip.is-trimming{z-index:18;cursor:ew-resize;opacity:.95}
222
+ .tk-track-clip-selection-frame{position:absolute;inset:0;border:1px solid transparent;border-radius:3px;z-index:3;pointer-events:none}
223
+ .tk-track-clip.is-selected .tk-track-clip-selection-frame{border-color:var(--tk-border-strong)}
224
+ .tk-track-clip-handle{position:absolute;top:-1px;bottom:-1px;width:8px;z-index:4;opacity:0;transition:opacity .12s ease;display:flex;align-items:center;justify-content:center;border-radius:2px;background:var(--tk-border-strong);color:#f8fafc;font-size:10px;line-height:1}
225
+ .tk-track-clip:hover .tk-track-clip-handle,.tk-track-clip.is-selected .tk-track-clip-handle{opacity:1}
226
+ .tk-track-clip-handle.is-left{left:-8px;cursor:w-resize}
227
+ .tk-track-clip-handle.is-right{right:-8px;cursor:e-resize}
228
+ .tk-media-clip{position:relative;width:100%;height:100%;display:flex;flex-direction:column;overflow:hidden;color:#f8fafc;background:linear-gradient(180deg,rgba(15,23,42,.98),rgba(30,41,59,.94))}
229
+ .tk-media-clip.is-audio{background:linear-gradient(180deg,rgba(6,78,59,.96),rgba(17,94,89,.92))}
230
+ .tk-media-clip-label{flex:0 0 auto;height:18px;line-height:18px;padding:0 8px;font-size:11px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;background:rgba(255,255,255,.06);border-bottom:1px solid rgba(255,255,255,.08)}
231
+ .tk-media-clip-body{position:relative;flex:1 1 auto;min-height:0;display:flex;flex-direction:column;overflow:hidden}
232
+ .tk-media-clip-filmstrip-host{position:relative;flex:1 1 auto;min-height:0;overflow:hidden;background:linear-gradient(180deg,rgba(15,23,42,.36),rgba(15,23,42,.08))}
233
+ .tk-media-clip-canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
234
+ .tk-media-clip-filmstrip{position:relative;display:grid;grid-auto-flow:column;grid-auto-columns:minmax(24px,1fr);gap:1px;flex:1;min-height:0;padding:1px;background:linear-gradient(180deg,rgba(15,23,42,.36),rgba(15,23,42,.08))}
235
+ .tk-media-clip-filmstrip-placeholder{display:block;min-width:0;border-radius:2px;background:linear-gradient(135deg,rgba(148,163,184,.24),rgba(71,85,105,.18))}
236
+ .tk-media-clip-waveform{position:relative;display:flex;align-items:center;justify-content:center;height:14px;min-height:14px;overflow:hidden;padding:0 4px;background:linear-gradient(180deg,rgba(59,130,246,.16),rgba(15,23,42,.14));color:rgba(191,219,254,.95)}
237
+ .tk-media-clip-waveform.is-audio-body{flex:1;height:auto;min-height:0;padding:0;background:linear-gradient(180deg,rgba(34,197,94,.16),rgba(15,23,42,.12));color:rgba(187,247,208,.96)}
238
+ .tk-media-clip-waveform-placeholder{display:block;width:100%;height:1px;border-radius:999px;background:currentColor;opacity:.45}
239
+ .tk-default-clip{width:100%;height:100%;padding:8px 10px;box-sizing:border-box;display:flex;flex-direction:column;justify-content:space-between;background:linear-gradient(135deg,#111827,#374151 52%,#6b7280);color:#fff}
240
+ .tk-default-clip[data-type="text"]{background:linear-gradient(135deg,#701a75,#f5d0fe);color:#3b0764}
241
+ .tk-default-clip[data-type="image"]{background:linear-gradient(135deg,#78350f,#fde68a);color:#451a03}
242
+ .tk-default-clip-title{font-size:12px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
243
+ .tk-default-clip-meta{font-size:10px;opacity:.8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
244
+ .tk-playhead{position:absolute;top:0;bottom:0;width:1px;background:var(--tk-border-strong);z-index:30;pointer-events:none}
245
+ .tk-playhead-handle{position:absolute;top:0;left:0;width:10px;height:12px;background:var(--tk-border-strong);border:1px solid var(--tk-border-strong);transform:translateX(-50%);cursor:ew-resize;pointer-events:auto}
246
+ .tk-timeline-editor:focus-visible{outline:2px solid var(--tk-accent);outline-offset:-2px}
247
+ .tk-toolbar-button:focus-visible,.tk-zoom-button:focus-visible,.tk-zoom-slider:focus-visible,.tk-track-toggle:focus-visible,.tk-playhead-handle:focus-visible{outline:2px solid var(--tk-accent);outline-offset:2px}
248
+ .tk-sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
249
+ .tk-playhead-handle::after{content:'';display:block;width:10px;height:10px;border:5px solid var(--tk-border-strong);position:absolute;top:100%;left:-1px;border-right-color:transparent;border-left-color:transparent;border-bottom-color:transparent;box-sizing:border-box}
250
+ @media (max-width: 900px){
251
+ .tk-timeline-toolbar{padding:8px 12px 6px}
252
+ .tk-toolbar-shell{align-items:flex-start}
253
+ .tk-toolbar-group.is-right{width:100%;justify-content:space-between}
254
+ .tk-toolbar-zoom{margin-left:0}
255
+ .tk-timeline-sidebar{width:76px}
256
+ .tk-track-label{gap:6px;padding:0 4px}
257
+ .tk-track-controls{gap:4px}
258
+ }
259
+ @media (max-width: 640px){
260
+ .tk-timeline-toolbar{padding:8px 10px 6px}
261
+ .tk-toolbar-shell{gap:8px}
262
+ .tk-toolbar-group{gap:6px}
263
+ .tk-toolbar-group.is-right{align-items:center}
264
+ .tk-toolbar-zoom{flex-basis:100%;width:100%}
265
+ }
266
+ `;
267
+ function ensureTimelineStyles(enabled = true) {
268
+ if (!enabled || typeof document === "undefined") {
269
+ return;
270
+ }
271
+ if (document.getElementById(STYLE_ID)) {
272
+ return;
273
+ }
274
+ const style = document.createElement("style");
275
+ style.id = STYLE_ID;
276
+ style.textContent = styles;
277
+ document.head.appendChild(style);
278
+ }
279
+ function isSlotRendererObject(slot) {
280
+ return typeof slot === "object" && slot !== null && typeof slot.mount === "function";
281
+ }
282
+ function applyFnResult(host, content) {
283
+ if (content == null) {
284
+ host.replaceChildren();
285
+ return;
286
+ }
287
+ if (typeof content === "string") {
288
+ host.textContent = content;
289
+ return;
290
+ }
291
+ host.replaceChildren(content);
292
+ }
293
+ function normalizeSlotRenderer(slot) {
294
+ if (isSlotRendererObject(slot)) {
295
+ return slot;
296
+ }
297
+ return {
298
+ mount(host, ctx) {
299
+ applyFnResult(host, slot(ctx));
300
+ return {
301
+ update(nextCtx) {
302
+ applyFnResult(host, slot(nextCtx));
303
+ },
304
+ destroy() {
305
+ host.replaceChildren();
306
+ }
307
+ };
308
+ }
309
+ };
310
+ }
311
+ function createSvgIcon(paths, options = {}) {
312
+ const svgNS = "http://www.w3.org/2000/svg";
313
+ const svg = document.createElementNS(svgNS, "svg");
314
+ const size = options.size ?? 16;
315
+ svg.setAttribute("viewBox", "0 0 24 24");
316
+ svg.setAttribute("width", String(size));
317
+ svg.setAttribute("height", String(size));
318
+ svg.setAttribute("fill", "none");
319
+ svg.setAttribute("stroke", options.color ?? "currentColor");
320
+ svg.setAttribute("stroke-width", "2");
321
+ svg.setAttribute("stroke-linecap", "round");
322
+ svg.setAttribute("stroke-linejoin", "round");
323
+ svg.setAttribute("aria-hidden", "true");
324
+ svg.setAttribute("focusable", "false");
325
+ svg.classList.add("tk-lucide");
326
+ for (const d of paths) {
327
+ const path = document.createElementNS(svgNS, "path");
328
+ path.setAttribute("d", d);
329
+ svg.appendChild(path);
330
+ }
331
+ return svg;
332
+ }
333
+ function createTrackTypeIcon(type) {
334
+ if (type === "audio") {
335
+ return createSvgIcon(["M12 3v18", "M8 8v8", "M16 8v8", "M4 13v-2", "M20 13v-2"], { color: "#2f7d62" });
336
+ }
337
+ if (type === "image") {
338
+ return createSvgIcon(["M5 19h14a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2Z", "m8 11-3 4h10l-4-6-3 4Z", "M9 9h.01"], { color: "#d97706" });
339
+ }
340
+ if (type === "text") {
341
+ return createSvgIcon(["M4 7V4h16v3", "M9 20h6", "M12 4v16"], { color: "#a21caf" });
342
+ }
343
+ return createSvgIcon(["M2 7.5 12 2l10 5.5v9L12 22 2 16.5Z", "M12 22v-9"], { color: "#475569" });
344
+ }
345
+ function createTrackActionIcon(command, active) {
346
+ if (command === "locked") {
347
+ return active ? createSvgIcon(["M7 11V7a5 5 0 0 1 10 0v4", "M5 11h14v10H5z"], { size: 14 }) : createSvgIcon(["M8 11V7a4 4 0 1 1 8 0", "M5 11h14v10H5z"], { size: 14 });
348
+ }
349
+ if (command === "visible") {
350
+ return active ? createSvgIcon(["M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z", "M3 3l18 18"], { size: 14 }) : createSvgIcon(["M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z", "M12 15a3 3 0 1 1 0-6 3 3 0 0 1 0 6Z"], { size: 14 });
351
+ }
352
+ return active ? createSvgIcon(["M11 5 6 9H2v6h4l5 4V5Z", "M22 9l-6 6", "M16 9l6 6"], { size: 14 }) : createSvgIcon(["M11 5 6 9H2v6h4l5 4V5Z", "M15.5 8.5a5 5 0 0 1 0 7"], { size: 14 });
353
+ }
354
+ function createToolbarIcon(id) {
355
+ if (id === "undo") {
356
+ return createSvgIcon(["M9 14 4 9l5-5", "M20 20a8 8 0 0 0-8-8H4"], { size: 16 });
357
+ }
358
+ if (id === "redo") {
359
+ return createSvgIcon(["m15 14 5-5-5-5", "M4 20a8 8 0 0 1 8-8h8"], { size: 16 });
360
+ }
361
+ if (id === "split") {
362
+ return createSvgIcon(["M16 3h5v18h-5", "M8 3H3v18h5", "M12 8v8", "M12 12h0"], { size: 16 });
363
+ }
364
+ if (id === "delete") {
365
+ return createSvgIcon(["M3 6h18", "M8 6V4h8v2", "M19 6l-1 14H6L5 6", "M10 11v6", "M14 11v6"], { size: 16 });
366
+ }
367
+ if (id === "magnetSnap") {
368
+ return createSvgIcon(["M6 15V6a2 2 0 0 1 2-2h3v5", "M18 15V6a2 2 0 0 0-2-2h-3v5", "M6 15a6 6 0 0 0 12 0", "M6 15h4", "M14 15h4"], { size: 16 });
369
+ }
370
+ if (id === "fitToView") {
371
+ return createSvgIcon(["M8 3H5a2 2 0 0 0-2 2v3", "M16 3h3a2 2 0 0 1 2 2v3", "M8 21H5a2 2 0 0 1-2-2v-3", "M16 21h3a2 2 0 0 0 2-2v-3"], { size: 16 });
372
+ }
373
+ if (id === "zoom-in") {
374
+ return createSvgIcon(["M12 5v14", "M5 12h14"], { size: 16 });
375
+ }
376
+ if (id === "zoom-out") {
377
+ return createSvgIcon(["M5 12h14"], { size: 16 });
378
+ }
379
+ return createSvgIcon(["M12 12h0"], { size: 16 });
380
+ }
381
+ class SidebarRenderer {
382
+ sidebarEl;
383
+ headerEl;
384
+ bodyEl;
385
+ mountedRows;
386
+ constructor(sidebarEl, headerEl, bodyEl) {
387
+ this.sidebarEl = sidebarEl;
388
+ this.headerEl = headerEl;
389
+ this.bodyEl = bodyEl;
390
+ this.mountedRows = /* @__PURE__ */ new Map();
391
+ }
392
+ render(layout, trackConfigs, sidebarConfig, showRuler) {
393
+ if (sidebarConfig === false) {
394
+ this.sidebarEl.style.display = "none";
395
+ return;
396
+ }
397
+ this.sidebarEl.style.display = "";
398
+ const resolvedConfig = typeof sidebarConfig === "object" && sidebarConfig !== null ? sidebarConfig : {};
399
+ if (typeof resolvedConfig.width === "number" && resolvedConfig.width > 0) {
400
+ this.sidebarEl.style.width = `${resolvedConfig.width}px`;
401
+ } else {
402
+ this.sidebarEl.style.width = "";
403
+ }
404
+ this.headerEl.style.display = showRuler ? "" : "none";
405
+ this.bodyEl.style.paddingTop = `${layout.contentTop}px`;
406
+ this.bodyEl.style.paddingBottom = `${layout.contentBottom}px`;
407
+ const showActions = resolvedConfig.showTrackActions !== false;
408
+ const activeTrackIds = /* @__PURE__ */ new Set();
409
+ const orderedRows = [];
410
+ for (const trackLayout of layout.tracks) {
411
+ const track = trackLayout.track;
412
+ activeTrackIds.add(track.id);
413
+ const trackConfig = trackConfigs[track.type];
414
+ const ctx = {
415
+ track,
416
+ trackIndex: trackLayout.trackIndex,
417
+ height: trackLayout.height
418
+ };
419
+ let record = this.mountedRows.get(track.id);
420
+ if (!record) {
421
+ const rowEl = document.createElement("div");
422
+ rowEl.className = "tk-track-label";
423
+ const iconHost = document.createElement("div");
424
+ iconHost.className = "tk-track-icon";
425
+ const controlsEl = document.createElement("div");
426
+ controlsEl.className = "tk-track-controls";
427
+ rowEl.append(iconHost, controlsEl);
428
+ record = {
429
+ trackId: track.id,
430
+ rowEl,
431
+ iconHost,
432
+ controlsEl
433
+ };
434
+ this.mountedRows.set(track.id, record);
435
+ }
436
+ record.rowEl.style.height = `${trackLayout.height}px`;
437
+ record.rowEl.dataset.trackIndex = String(trackLayout.trackIndex);
438
+ record.rowEl.dataset.trackId = track.id;
439
+ const nextSlot = trackConfig?.icon;
440
+ if (nextSlot !== record.slotRef) {
441
+ record.slotHandle?.destroy?.();
442
+ record.slotHandle = void 0;
443
+ record.iconHost.replaceChildren();
444
+ record.slotRef = nextSlot;
445
+ if (nextSlot) {
446
+ record.slotHandle = normalizeSlotRenderer(nextSlot).mount(record.iconHost, ctx) ?? void 0;
447
+ } else {
448
+ record.iconHost.appendChild(createTrackTypeIcon(track.type));
449
+ }
450
+ } else if (record.slotRef) {
451
+ record.slotHandle?.update?.(ctx);
452
+ } else if (record.iconHost.childElementCount === 0) {
453
+ record.iconHost.appendChild(createTrackTypeIcon(track.type));
454
+ }
455
+ record.controlsEl.style.display = showActions ? "" : "none";
456
+ if (showActions) {
457
+ this.renderTrackActions(record.controlsEl, trackLayout.trackIndex, track.locked === true, track.visible === false, track.muted === true);
458
+ }
459
+ orderedRows.push(record.rowEl);
460
+ }
461
+ for (const [trackId, record] of this.mountedRows.entries()) {
462
+ if (!activeTrackIds.has(trackId)) {
463
+ record.slotHandle?.destroy?.();
464
+ record.rowEl.remove();
465
+ this.mountedRows.delete(trackId);
466
+ }
467
+ }
468
+ this.bodyEl.replaceChildren(...orderedRows);
469
+ }
470
+ syncScroll(scrollTop) {
471
+ this.bodyEl.style.transform = `translateY(${-scrollTop}px)`;
472
+ }
473
+ syncHeights(trackRowElements) {
474
+ const labels = Array.from(this.bodyEl.children);
475
+ labels.forEach((label, index) => {
476
+ const row = trackRowElements[index];
477
+ if (row && row.offsetHeight > 0) {
478
+ label.style.height = `${row.offsetHeight}px`;
479
+ }
480
+ });
481
+ }
482
+ destroy() {
483
+ for (const record of this.mountedRows.values()) {
484
+ record.slotHandle?.destroy?.();
485
+ }
486
+ this.mountedRows.clear();
487
+ this.bodyEl.replaceChildren();
488
+ }
489
+ renderTrackActions(controlsEl, trackIndex, locked, hidden, muted) {
490
+ const actions = [
491
+ { command: "locked", title: locked ? "解锁" : "锁定", label: "Lock track", active: locked },
492
+ { command: "visible", title: hidden ? "显示" : "隐藏", label: "Hide track", active: hidden },
493
+ { command: "muted", title: muted ? "取消静音" : "静音", label: "Mute track", active: muted }
494
+ ];
495
+ const buttons = actions.map((action) => {
496
+ const button = document.createElement("button");
497
+ button.type = "button";
498
+ button.className = "tk-track-toggle";
499
+ button.dataset.trackCommand = action.command;
500
+ button.dataset.trackIndex = String(trackIndex);
501
+ button.title = action.title;
502
+ button.setAttribute("aria-label", action.label);
503
+ button.setAttribute("aria-pressed", action.active ? "true" : "false");
504
+ if (action.active) {
505
+ button.classList.add("is-active");
506
+ }
507
+ button.appendChild(createTrackActionIcon(action.command, action.active));
508
+ return button;
509
+ });
510
+ controlsEl.replaceChildren(...buttons);
511
+ }
512
+ }
513
+ const DEFAULT_TOOLS = [
514
+ { id: "undo", sort: 1, position: "left", command: "undo", title: "撤销 (Ctrl/Cmd+Z)" },
515
+ { id: "redo", sort: 2, position: "left", command: "redo", title: "重做 (Ctrl+Y / Cmd+Shift+Z)" },
516
+ { id: "split", sort: 3, position: "left", command: "split", title: "分割 (Ctrl/Cmd+B)" },
517
+ { id: "delete", sort: 4, position: "left", command: "delete", title: "删除 (Delete/Backspace)" },
518
+ { id: "magnetSnap", sort: 5, position: "right", command: "magnet", title: "磁吸" },
519
+ { id: "fitToView", sort: 6, position: "right", command: "fit", title: "适应窗口" }
520
+ ];
521
+ function appendToolbarContent(button, content) {
522
+ if (content == null) {
523
+ return;
524
+ }
525
+ if (typeof content === "string") {
526
+ button.textContent = content;
527
+ return;
528
+ }
529
+ button.appendChild(content);
530
+ }
531
+ class ToolbarRenderer {
532
+ host;
533
+ buttons;
534
+ slider;
535
+ lastToolsSignature;
536
+ constructor(host) {
537
+ this.host = host;
538
+ this.buttons = /* @__PURE__ */ new Map();
539
+ this.slider = null;
540
+ this.lastToolsSignature = "";
541
+ }
542
+ render(state, customTools) {
543
+ if (customTools === false) {
544
+ this.host.style.display = "none";
545
+ return;
546
+ }
547
+ this.host.style.display = "";
548
+ const tools = this.resolveTools(Array.isArray(customTools) ? customTools : []);
549
+ const signature = tools.map((tool) => `${tool.id}:${tool.sort}:${tool.position}:${tool.command ?? ""}:${tool.title ?? ""}:${Boolean(tool.render)}`).join("|");
550
+ const context = { snapshot: state };
551
+ if (signature !== this.lastToolsSignature || this.buttons.size === 0) {
552
+ this.rebuild(tools, context);
553
+ this.lastToolsSignature = signature;
554
+ } else {
555
+ this.updateStates(tools, context);
556
+ }
557
+ if (this.slider) {
558
+ this.slider.value = String(state.trackScale);
559
+ }
560
+ }
561
+ destroy() {
562
+ this.buttons.clear();
563
+ this.slider = null;
564
+ this.lastToolsSignature = "";
565
+ this.host.replaceChildren();
566
+ }
567
+ resolveTools(customTools) {
568
+ const configMap = /* @__PURE__ */ new Map();
569
+ for (const tool of DEFAULT_TOOLS) {
570
+ configMap.set(tool.id, tool);
571
+ }
572
+ for (const tool of customTools) {
573
+ configMap.set(tool.id, { ...configMap.get(tool.id), ...tool });
574
+ }
575
+ return Array.from(configMap.values()).sort((a, b) => a.sort - b.sort);
576
+ }
577
+ rebuild(tools, context) {
578
+ this.buttons.clear();
579
+ const shell = document.createElement("div");
580
+ shell.className = "tk-toolbar-shell";
581
+ const left = document.createElement("div");
582
+ left.className = "tk-toolbar-group is-left";
583
+ const right = document.createElement("div");
584
+ right.className = "tk-toolbar-group is-right";
585
+ for (const tool of tools) {
586
+ const button = document.createElement("button");
587
+ button.type = "button";
588
+ button.className = "tk-toolbar-button";
589
+ if (tool.command) {
590
+ button.dataset.command = tool.command;
591
+ }
592
+ if (tool.title) {
593
+ button.title = tool.title;
594
+ button.setAttribute("aria-label", tool.title);
595
+ }
596
+ this.applyButtonState(button, tool, context);
597
+ this.buttons.set(tool.id, button);
598
+ if (tool.position === "left") {
599
+ left.appendChild(button);
600
+ } else {
601
+ right.appendChild(button);
602
+ }
603
+ }
604
+ const zoom = document.createElement("div");
605
+ zoom.className = "tk-toolbar-zoom";
606
+ const minus = document.createElement("button");
607
+ minus.type = "button";
608
+ minus.className = "tk-zoom-button";
609
+ minus.dataset.command = "zoom-out";
610
+ minus.title = "缩小";
611
+ minus.setAttribute("aria-label", "缩小");
612
+ minus.appendChild(createToolbarIcon("zoom-out"));
613
+ const slider = document.createElement("input");
614
+ slider.className = "tk-zoom-slider";
615
+ slider.type = "range";
616
+ slider.min = "0";
617
+ slider.max = "100";
618
+ slider.step = "1";
619
+ slider.value = String(context.snapshot.trackScale);
620
+ slider.dataset.command = "track-scale";
621
+ slider.setAttribute("aria-label", "Zoom");
622
+ this.slider = slider;
623
+ const plus = document.createElement("button");
624
+ plus.type = "button";
625
+ plus.className = "tk-zoom-button";
626
+ plus.dataset.command = "zoom-in";
627
+ plus.title = "放大";
628
+ plus.setAttribute("aria-label", "放大");
629
+ plus.appendChild(createToolbarIcon("zoom-in"));
630
+ zoom.append(minus, slider, plus);
631
+ right.appendChild(zoom);
632
+ shell.append(left, right);
633
+ this.host.replaceChildren(shell);
634
+ }
635
+ updateStates(tools, context) {
636
+ for (const tool of tools) {
637
+ const button = this.buttons.get(tool.id);
638
+ if (!button) {
639
+ continue;
640
+ }
641
+ this.applyButtonState(button, tool, context);
642
+ }
643
+ }
644
+ applyButtonState(button, tool, context) {
645
+ const isDisabled = tool.isDisabled?.(context) ?? (tool.id === "undo" ? !context.snapshot.canUndo : tool.id === "redo" ? !context.snapshot.canRedo : tool.id === "split" || tool.id === "delete" ? context.snapshot.selection.clipId == null : false);
646
+ const isActive = tool.isActive?.(context) ?? (tool.id === "magnetSnap" ? context.snapshot.isMagnetEnabled : false);
647
+ button.disabled = isDisabled;
648
+ button.classList.toggle("is-active", isActive);
649
+ if (tool.isActive !== void 0 || tool.id === "magnetSnap") {
650
+ button.setAttribute("aria-pressed", isActive ? "true" : "false");
651
+ }
652
+ if (tool.render) {
653
+ button.replaceChildren();
654
+ appendToolbarContent(button, tool.render(context));
655
+ } else if (button.childElementCount === 0 && !button.textContent) {
656
+ if (tool.label) {
657
+ button.textContent = tool.label;
658
+ } else {
659
+ button.appendChild(createToolbarIcon(tool.id));
660
+ }
661
+ }
662
+ }
663
+ }
664
+ const TRACK_PADDING_LEFT = 10;
665
+ const TRACK_PADDING_RIGHT = 200;
666
+ const RULER_HEIGHT = 20;
667
+ const MIN_CLIP_WIDTH_PX = 32;
668
+ const SCROLL_REV_THRESHOLD_PX = 100;
669
+ const DEFAULT_ARIA_LABEL = "Timeline";
670
+ function setAttr(el, name, value) {
671
+ if (el.getAttribute(name) !== value) {
672
+ el.setAttribute(name, value);
673
+ }
674
+ }
675
+ function formatTimecode(seconds) {
676
+ const safe = Number.isFinite(seconds) && seconds > 0 ? seconds : 0;
677
+ const minutes = Math.floor(safe / 60);
678
+ const secs = (safe - minutes * 60).toFixed(1).padStart(4, "0");
679
+ return `${minutes}:${secs}`;
680
+ }
681
+ function clipAriaLabel(clip) {
682
+ const start = formatTimecode((Number(clip.startMs) || 0) / 1e3);
683
+ const end = formatTimecode((Number(clip.endMs) || 0) / 1e3);
684
+ return `${clip.name || clip.id}, ${start} – ${end}`;
685
+ }
686
+ function trackAriaLabel(track) {
687
+ const states = [];
688
+ if (track.locked === true) {
689
+ states.push("locked");
690
+ }
691
+ if (track.visible === false) {
692
+ states.push("hidden");
693
+ }
694
+ if (track.muted === true) {
695
+ states.push("muted");
696
+ }
697
+ const name = track.name || track.id;
698
+ return states.length > 0 ? `${name}, ${states.join(", ")}` : name;
699
+ }
700
+ function createFilmstripPlaceholders() {
701
+ return Array.from({ length: 6 }, () => {
702
+ const placeholder = document.createElement("span");
703
+ placeholder.className = "tk-media-clip-filmstrip-placeholder";
704
+ return placeholder;
705
+ });
706
+ }
707
+ class DomTimelineRenderer {
708
+ container;
709
+ refs;
710
+ toolbarRenderer;
711
+ sidebarRenderer;
712
+ mountedClips;
713
+ clipPreviewOverrides;
714
+ overlayState;
715
+ trackConfigs;
716
+ uiConfig;
717
+ mediaProvider;
718
+ layout;
719
+ lastState;
720
+ lastVirtualizedScrollLeft;
721
+ previousUserSelect;
722
+ ariaLabelOverride;
723
+ lastAnnouncedSelection;
724
+ constructor(container, options = {}) {
725
+ this.container = container;
726
+ this.trackConfigs = options.trackConfigs ?? {};
727
+ this.uiConfig = options.ui ?? {};
728
+ this.mediaProvider = options.mediaProvider;
729
+ this.mountedClips = /* @__PURE__ */ new Map();
730
+ this.clipPreviewOverrides = /* @__PURE__ */ new Map();
731
+ this.lastState = null;
732
+ this.lastVirtualizedScrollLeft = 0;
733
+ this.previousUserSelect = "";
734
+ this.ariaLabelOverride = options.ariaLabel;
735
+ this.lastAnnouncedSelection = "";
736
+ this.overlayState = {
737
+ verticalGuidelinePx: null,
738
+ horizontalGuidelinePx: null,
739
+ dragPreview: null,
740
+ marqueeRect: null
741
+ };
742
+ ensureTimelineStyles(options.injectStyles !== false);
743
+ this.refs = this.mountDom(options.theme ?? "auto");
744
+ this.toolbarRenderer = new ToolbarRenderer(this.refs.toolbar);
745
+ this.sidebarRenderer = new SidebarRenderer(
746
+ this.refs.sidebar,
747
+ this.refs.sidebarHeader,
748
+ this.refs.sidebarBody
749
+ );
750
+ this.layout = computeTimelineLayout(
751
+ { fps: 24, tracks: [] },
752
+ { trackScale: 50, trackConfigs: this.trackConfigs }
753
+ );
754
+ }
755
+ getRootElement() {
756
+ return this.refs.root;
757
+ }
758
+ getMainScrollerElement() {
759
+ return this.refs.mainScroller;
760
+ }
761
+ setTrackConfigs(trackConfigs) {
762
+ this.trackConfigs = trackConfigs;
763
+ }
764
+ setUIConfig(uiConfig) {
765
+ this.uiConfig = uiConfig;
766
+ setAttr(this.refs.root, "aria-label", this.resolveAriaLabel());
767
+ }
768
+ resolveAriaLabel() {
769
+ return this.ariaLabelOverride ?? this.uiConfig.ariaLabel ?? DEFAULT_ARIA_LABEL;
770
+ }
771
+ setMediaProvider(provider) {
772
+ this.mediaProvider = provider;
773
+ for (const record of this.mountedClips.values()) {
774
+ record.lastRenderKey = void 0;
775
+ }
776
+ }
777
+ getLayout() {
778
+ return this.layout;
779
+ }
780
+ getViewportMetrics() {
781
+ return {
782
+ scrollLeft: this.refs.mainScroller.scrollLeft,
783
+ scrollTop: this.refs.mainScroller.scrollTop,
784
+ clientWidth: this.refs.mainScroller.clientWidth || 640,
785
+ clientHeight: this.refs.mainScroller.clientHeight || 300,
786
+ trackPaddingLeft: TRACK_PADDING_LEFT
787
+ };
788
+ }
789
+ setScrollLeft(scrollLeft) {
790
+ this.refs.mainScroller.scrollLeft = Math.max(0, scrollLeft);
791
+ this.handleScroll();
792
+ }
793
+ lockUserSelect() {
794
+ if (this.previousUserSelect) {
795
+ return;
796
+ }
797
+ this.previousUserSelect = document.body.style.userSelect;
798
+ document.body.style.userSelect = "none";
799
+ }
800
+ restoreUserSelect() {
801
+ document.body.style.userSelect = this.previousUserSelect;
802
+ this.previousUserSelect = "";
803
+ }
804
+ focusContainer() {
805
+ this.refs.root.focus({ preventScroll: true });
806
+ }
807
+ setOverlay(patch) {
808
+ Object.assign(this.overlayState, patch);
809
+ this.renderOverlay();
810
+ }
811
+ clearOverlay() {
812
+ this.overlayState.verticalGuidelinePx = null;
813
+ this.overlayState.horizontalGuidelinePx = null;
814
+ this.overlayState.dragPreview = null;
815
+ this.overlayState.marqueeRect = null;
816
+ this.renderOverlay();
817
+ }
818
+ setClipPreview(clipId, override) {
819
+ if (override === null) {
820
+ this.clipPreviewOverrides.delete(clipId);
821
+ } else {
822
+ this.clipPreviewOverrides.set(clipId, override);
823
+ }
824
+ this.applyClipPreview(clipId);
825
+ }
826
+ clearAllClipPreviews() {
827
+ const ids = Array.from(this.clipPreviewOverrides.keys());
828
+ this.clipPreviewOverrides.clear();
829
+ for (const clipId of ids) {
830
+ this.applyClipPreview(clipId);
831
+ }
832
+ }
833
+ render(state, dirty) {
834
+ this.lastState = state;
835
+ this.refs.root.dataset.theme = state.theme;
836
+ const fullRender = !dirty;
837
+ if (fullRender) {
838
+ setAttr(this.refs.root, "aria-label", this.resolveAriaLabel());
839
+ }
840
+ const shouldRecomputeLayout = fullRender || dirty.has("tracks") || dirty.has("ruler") || dirty.has("sidebar");
841
+ if (shouldRecomputeLayout) {
842
+ this.layout = computeTimelineLayout(state.document, {
843
+ trackScale: state.trackScale,
844
+ trackConfigs: this.trackConfigs,
845
+ viewportHeight: this.refs.tracksViewport.clientHeight
846
+ });
847
+ }
848
+ const showRuler = this.uiConfig.ruler !== false;
849
+ this.refs.ruler.style.display = showRuler ? "" : "none";
850
+ this.refs.tracksViewport.style.minHeight = showRuler ? "calc(100% - 20px)" : "100%";
851
+ if (fullRender || dirty.has("toolbar")) {
852
+ this.toolbarRenderer.render(state, this.uiConfig.toolbar);
853
+ }
854
+ if (fullRender || dirty.has("sidebar") || dirty.has("tracks")) {
855
+ this.sidebarRenderer.render(this.layout, this.trackConfigs, this.uiConfig.sidebar, showRuler);
856
+ }
857
+ if (showRuler && (fullRender || dirty.has("ruler") || dirty.has("tracks"))) {
858
+ this.renderRuler(state);
859
+ }
860
+ if (fullRender || dirty.has("tracks")) {
861
+ this.renderTracks(state);
862
+ this.lastVirtualizedScrollLeft = this.refs.mainScroller.scrollLeft;
863
+ } else if (dirty.has("selection")) {
864
+ this.renderSelectionOnly(state);
865
+ }
866
+ if (dirty?.has("selection")) {
867
+ this.announceSelection(state);
868
+ }
869
+ if (fullRender || dirty.has("playhead") || dirty.has("tracks") || dirty.has("ruler")) {
870
+ this.positionPlayhead(state);
871
+ }
872
+ if (fullRender || dirty.has("overlay")) {
873
+ this.renderOverlay();
874
+ }
875
+ if (fullRender || dirty.has("sidebar") || dirty.has("tracks")) {
876
+ const rowEls = Array.from(this.refs.tracks.children);
877
+ this.sidebarRenderer.syncHeights(rowEls);
878
+ this.sidebarRenderer.syncScroll(this.refs.mainScroller.scrollTop);
879
+ }
880
+ }
881
+ handleScroll() {
882
+ const scrollTop = this.refs.mainScroller.scrollTop;
883
+ const scrollLeft = this.refs.mainScroller.scrollLeft;
884
+ this.sidebarRenderer.syncScroll(scrollTop);
885
+ if (!this.lastState) {
886
+ return;
887
+ }
888
+ this.positionPlayhead(this.lastState);
889
+ if (this.uiConfig.ruler !== false) {
890
+ this.renderRuler(this.lastState);
891
+ }
892
+ if (Math.abs(scrollLeft - this.lastVirtualizedScrollLeft) >= SCROLL_REV_THRESHOLD_PX) {
893
+ this.renderTracks(this.lastState);
894
+ this.lastVirtualizedScrollLeft = scrollLeft;
895
+ }
896
+ }
897
+ hitTestClientPoint(clientX, clientY, target, doc) {
898
+ const el = target instanceof Element ? target : null;
899
+ const scrollerRect = this.refs.mainScroller.getBoundingClientRect();
900
+ const viewportRect = this.refs.tracksViewport.getBoundingClientRect();
901
+ const hitX = Math.max(
902
+ 0,
903
+ clientX - scrollerRect.left + this.refs.mainScroller.scrollLeft - TRACK_PADDING_LEFT
904
+ );
905
+ const y = clientY - viewportRect.top;
906
+ let zoneHint;
907
+ let hintClipId = null;
908
+ if (el) {
909
+ if (el.closest(".tk-timeline-toolbar")) {
910
+ zoneHint = "toolbar";
911
+ } else if (el.closest(".tk-timeline-sidebar")) {
912
+ zoneHint = "sidebar";
913
+ } else if (el.closest(".tk-playhead-handle")) {
914
+ zoneHint = "playhead";
915
+ } else if (el.closest(".tk-timeline-ruler")) {
916
+ zoneHint = "ruler";
917
+ } else {
918
+ const trimEdge = el.closest("[data-trim-edge]");
919
+ const clipEl = el.closest(".tk-track-clip");
920
+ if (clipEl) {
921
+ hintClipId = clipEl.dataset.clipId ?? null;
922
+ if (trimEdge?.dataset.trimEdge === "start") {
923
+ zoneHint = "trim-start";
924
+ } else if (trimEdge?.dataset.trimEdge === "end") {
925
+ zoneHint = "trim-end";
926
+ } else {
927
+ zoneHint = "clip-body";
928
+ }
929
+ } else if (!el.closest(".tk-timeline-editor")) {
930
+ zoneHint = "outside";
931
+ }
932
+ }
933
+ }
934
+ return hitTestLayout(this.layout, doc, {
935
+ x: hitX,
936
+ y,
937
+ zoneHint,
938
+ hintClipId
939
+ });
940
+ }
941
+ destroy() {
942
+ this.restoreUserSelect();
943
+ for (const record of this.mountedClips.values()) {
944
+ record.slotHandle?.destroy?.();
945
+ record.mediaCleanups.forEach((fn) => fn());
946
+ }
947
+ this.mountedClips.clear();
948
+ this.clipPreviewOverrides.clear();
949
+ this.toolbarRenderer.destroy();
950
+ this.sidebarRenderer.destroy();
951
+ this.container.replaceChildren();
952
+ }
953
+ mountDom(theme) {
954
+ const root = document.createElement("div");
955
+ root.className = "tk-timeline-editor";
956
+ root.tabIndex = 0;
957
+ root.dataset.theme = theme;
958
+ root.setAttribute("role", "application");
959
+ root.setAttribute("aria-label", this.resolveAriaLabel());
960
+ const toolbar = document.createElement("div");
961
+ toolbar.className = "tk-timeline-toolbar";
962
+ const workspace = document.createElement("div");
963
+ workspace.className = "tk-timeline-workspace";
964
+ const sidebar = document.createElement("div");
965
+ sidebar.className = "tk-timeline-sidebar";
966
+ const sidebarHeader = document.createElement("div");
967
+ sidebarHeader.className = "tk-timeline-sidebar-header";
968
+ const sidebarBody = document.createElement("div");
969
+ sidebarBody.className = "tk-timeline-sidebar-body";
970
+ sidebar.append(sidebarHeader, sidebarBody);
971
+ const main = document.createElement("div");
972
+ main.className = "tk-timeline-main";
973
+ const mainScroller = document.createElement("div");
974
+ mainScroller.className = "tk-timeline-main-scroller";
975
+ const ruler = document.createElement("div");
976
+ ruler.className = "tk-timeline-ruler";
977
+ const rulerCanvas = document.createElement("canvas");
978
+ rulerCanvas.className = "tk-ruler-canvas";
979
+ rulerCanvas.setAttribute("aria-hidden", "true");
980
+ ruler.appendChild(rulerCanvas);
981
+ const tracksViewport = document.createElement("div");
982
+ tracksViewport.className = "tk-tracks-viewport";
983
+ const tracks = document.createElement("div");
984
+ tracks.className = "tk-tracks";
985
+ const emptyState = document.createElement("div");
986
+ emptyState.className = "tk-empty-state";
987
+ emptyState.textContent = "暂无轨道数据";
988
+ const preview = document.createElement("div");
989
+ preview.className = "tk-drag-preview";
990
+ preview.textContent = "移动到此处";
991
+ const marquee = document.createElement("div");
992
+ marquee.className = "tk-marquee";
993
+ const verticalGuideline = document.createElement("div");
994
+ verticalGuideline.className = "tk-guideline tk-guideline-vertical";
995
+ const horizontalGuideline = document.createElement("div");
996
+ horizontalGuideline.className = "tk-guideline tk-guideline-horizontal";
997
+ tracksViewport.append(tracks, emptyState, preview, marquee, verticalGuideline, horizontalGuideline);
998
+ mainScroller.append(ruler, tracksViewport);
999
+ const playhead = document.createElement("div");
1000
+ playhead.className = "tk-playhead";
1001
+ const handle = document.createElement("div");
1002
+ handle.className = "tk-playhead-handle";
1003
+ handle.setAttribute("role", "slider");
1004
+ handle.setAttribute("aria-label", "Playhead");
1005
+ handle.tabIndex = 0;
1006
+ playhead.appendChild(handle);
1007
+ const status = document.createElement("div");
1008
+ status.className = "tk-sr-only";
1009
+ status.setAttribute("role", "status");
1010
+ status.setAttribute("aria-live", "polite");
1011
+ main.append(mainScroller, playhead);
1012
+ workspace.append(sidebar, main);
1013
+ root.append(toolbar, workspace, status);
1014
+ this.container.replaceChildren(root);
1015
+ return {
1016
+ root,
1017
+ toolbar,
1018
+ workspace,
1019
+ sidebar,
1020
+ sidebarHeader,
1021
+ sidebarBody,
1022
+ main,
1023
+ mainScroller,
1024
+ ruler,
1025
+ rulerCanvas,
1026
+ tracksViewport,
1027
+ tracks,
1028
+ emptyState,
1029
+ preview,
1030
+ marquee,
1031
+ playhead,
1032
+ playheadHandle: handle,
1033
+ verticalGuideline,
1034
+ horizontalGuideline,
1035
+ status
1036
+ };
1037
+ }
1038
+ resolveIsDark(theme) {
1039
+ if (theme === "dark") {
1040
+ return true;
1041
+ }
1042
+ if (theme === "light") {
1043
+ return false;
1044
+ }
1045
+ if (this.container.closest(".dark") !== null) {
1046
+ return true;
1047
+ }
1048
+ if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
1049
+ return window.matchMedia("(prefers-color-scheme: dark)").matches;
1050
+ }
1051
+ return false;
1052
+ }
1053
+ renderRuler(state) {
1054
+ const dark = this.resolveIsDark(state.theme);
1055
+ const ratio = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
1056
+ const canvas = this.refs.rulerCanvas;
1057
+ const cssWidth = Math.max(Math.ceil(this.refs.mainScroller.clientWidth), 320);
1058
+ const cssHeight = RULER_HEIGHT;
1059
+ canvas.width = Math.round(cssWidth * ratio);
1060
+ canvas.height = Math.round(cssHeight * ratio);
1061
+ canvas.style.width = `${cssWidth}px`;
1062
+ canvas.style.height = `${cssHeight}px`;
1063
+ const context = canvas.getContext("2d");
1064
+ if (!context) {
1065
+ return;
1066
+ }
1067
+ const totalFrames = Math.round(this.layout.totalDurationSec * this.layout.fps);
1068
+ drawTimeRuler(context, {
1069
+ startPx: this.refs.mainScroller.scrollLeft - TRACK_PADDING_LEFT,
1070
+ fps: this.layout.fps,
1071
+ scale: state.trackScale,
1072
+ totalFrames,
1073
+ width: cssWidth,
1074
+ height: cssHeight,
1075
+ ratio,
1076
+ palette: this.rulerPalette(dark)
1077
+ });
1078
+ }
1079
+ rulerPalette(dark) {
1080
+ const style = getComputedStyle(this.refs.root);
1081
+ const color = (name, fallback) => style.getPropertyValue(name).trim() || fallback;
1082
+ return {
1083
+ bgColor: color("--tk-ruler-bg", dark ? "#1f2937" : "#e5e7eb"),
1084
+ longColor: color("--tk-ruler-long", dark ? "#cbd5e1" : "#374151"),
1085
+ shortColor: color("--tk-ruler-short", dark ? "#94a3b8" : "#6b7280"),
1086
+ textColor: color("--tk-ruler-text", dark ? "#e5e7eb" : "#374151"),
1087
+ subTextColor: color("--tk-ruler-sub", dark ? "#94a3b8" : "#6b7280"),
1088
+ focusColor: color("--tk-ruler-focus", dark ? "#312e81" : "#c4b5fd")
1089
+ };
1090
+ }
1091
+ renderTracks(state) {
1092
+ const trackContentWidth = this.layout.totalDurationSec * this.layout.pixelsPerSecond + TRACK_PADDING_LEFT + TRACK_PADDING_RIGHT;
1093
+ const timelineWidth = Math.max(trackContentWidth, this.refs.mainScroller.clientWidth || 640);
1094
+ const visibleRange = computeVisibleRange(
1095
+ this.refs.mainScroller.scrollLeft,
1096
+ this.refs.mainScroller.clientWidth || 640,
1097
+ this.layout.pixelsPerSecond,
1098
+ TRACK_PADDING_LEFT
1099
+ );
1100
+ const alwaysIncludeIds = new Set(state.selection.clipIds);
1101
+ for (const previewId of this.clipPreviewOverrides.keys()) {
1102
+ alwaysIncludeIds.add(previewId);
1103
+ }
1104
+ const visibleClipIds = /* @__PURE__ */ new Set();
1105
+ const rowElements = this.layout.tracks.map(
1106
+ (trackLayout) => this.renderTrackRow(state, trackLayout, timelineWidth, visibleRange, alwaysIncludeIds, visibleClipIds)
1107
+ );
1108
+ this.refs.tracksViewport.style.width = `${timelineWidth}px`;
1109
+ this.refs.tracks.style.width = `${timelineWidth}px`;
1110
+ this.refs.tracks.style.paddingTop = `${this.layout.contentTop}px`;
1111
+ this.refs.tracks.style.paddingBottom = `${this.layout.contentBottom}px`;
1112
+ this.refs.tracks.replaceChildren(...rowElements);
1113
+ this.refs.emptyState.style.display = this.layout.tracks.length === 0 ? "flex" : "none";
1114
+ this.pruneUnmountedClips(visibleClipIds);
1115
+ }
1116
+ renderTrackRow(state, trackLayout, timelineWidth, visibleRange, alwaysIncludeIds, visibleClipIds) {
1117
+ const row = document.createElement("div");
1118
+ row.className = "tk-track-row";
1119
+ row.style.height = `${trackLayout.height}px`;
1120
+ row.style.marginLeft = `${TRACK_PADDING_LEFT}px`;
1121
+ row.style.width = `${Math.max(0, timelineWidth - TRACK_PADDING_LEFT)}px`;
1122
+ row.dataset.trackIndex = String(trackLayout.trackIndex);
1123
+ row.dataset.trackId = trackLayout.track.id;
1124
+ row.setAttribute("role", "group");
1125
+ row.setAttribute("aria-label", trackAriaLabel(trackLayout.track));
1126
+ const lane = document.createElement("div");
1127
+ lane.className = "tk-track-lane";
1128
+ lane.style.width = `${Math.max(0, timelineWidth - TRACK_PADDING_LEFT)}px`;
1129
+ lane.setAttribute("role", "listbox");
1130
+ lane.setAttribute("aria-multiselectable", "true");
1131
+ lane.setAttribute("aria-label", trackLayout.track.name || trackLayout.track.id);
1132
+ const visibleClips = filterVisibleClips(trackLayout.clips, visibleRange, alwaysIncludeIds);
1133
+ for (const clipLayout of visibleClips) {
1134
+ visibleClipIds.add(clipLayout.clip.id);
1135
+ lane.appendChild(this.renderClip(state, clipLayout));
1136
+ }
1137
+ row.appendChild(lane);
1138
+ if (trackLayout.track.locked === true) {
1139
+ row.appendChild(this.renderTrackOverlay("已锁定", "is-locked"));
1140
+ } else if (trackLayout.track.visible === false) {
1141
+ row.appendChild(this.renderTrackOverlay("已隐藏", "is-hidden"));
1142
+ } else if (trackLayout.track.muted === true) {
1143
+ row.appendChild(this.renderTrackOverlay("已静音", "is-muted"));
1144
+ }
1145
+ return row;
1146
+ }
1147
+ renderClip(state, clipLayout) {
1148
+ const clip = clipLayout.clip;
1149
+ const widthPx = Math.max(clipLayout.widthPx, MIN_CLIP_WIDTH_PX);
1150
+ const selectedSet = new Set(state.selection.clipIds);
1151
+ const isSelected = selectedSet.has(clip.id) || state.selection.clipId === clip.id;
1152
+ const trackConfig = this.trackConfigs[clipLayout.type] ?? this.trackConfigs[clipLayout.track.type];
1153
+ const record = this.getOrCreateClipRecord(clip.id);
1154
+ const { clipNode, contentHost } = record;
1155
+ clipNode.className = "tk-track-clip";
1156
+ if (isSelected) {
1157
+ clipNode.classList.add("is-selected");
1158
+ }
1159
+ clipNode.style.left = `${clipLayout.leftPx}px`;
1160
+ clipNode.style.width = `${widthPx}px`;
1161
+ clipNode.style.transform = "";
1162
+ clipNode.dataset.clipId = clip.id;
1163
+ clipNode.dataset.trackIndex = String(clipLayout.trackIndex);
1164
+ clipNode.dataset.clipIndex = String(clipLayout.clipIndex);
1165
+ clipNode.dataset.type = clipLayout.type;
1166
+ setAttr(clipNode, "aria-label", clipAriaLabel(clip));
1167
+ setAttr(clipNode, "aria-selected", isSelected ? "true" : "false");
1168
+ const ctx = {
1169
+ clip,
1170
+ track: clipLayout.track,
1171
+ trackIndex: clipLayout.trackIndex,
1172
+ clipIndex: clipLayout.clipIndex,
1173
+ isSelected,
1174
+ renderHints: state.renderHints,
1175
+ clipWidthPx: widthPx,
1176
+ isVisible: true
1177
+ };
1178
+ const customSlot = trackConfig?.clip;
1179
+ if (customSlot) {
1180
+ if (customSlot !== record.slotRef) {
1181
+ record.slotHandle?.destroy?.();
1182
+ record.mediaCleanups.forEach((fn) => fn());
1183
+ record.mediaCleanups = [];
1184
+ contentHost.replaceChildren();
1185
+ record.slotRef = customSlot;
1186
+ record.slotHandle = normalizeSlotRenderer(customSlot).mount(contentHost, ctx) ?? void 0;
1187
+ } else {
1188
+ record.slotHandle?.update?.(ctx);
1189
+ }
1190
+ } else {
1191
+ if (record.slotRef) {
1192
+ record.slotHandle?.destroy?.();
1193
+ record.slotHandle = void 0;
1194
+ record.slotRef = void 0;
1195
+ record.lastRenderKey = void 0;
1196
+ }
1197
+ this.renderDefaultClipContent(record, ctx);
1198
+ }
1199
+ const previewOverride = this.clipPreviewOverrides.get(clip.id);
1200
+ if (previewOverride) {
1201
+ this.applyPreviewStyleToNode(clipNode, previewOverride, clipLayout.leftPx, widthPx);
1202
+ }
1203
+ return clipNode;
1204
+ }
1205
+ renderDefaultClipContent(record, ctx) {
1206
+ const renderKey = [
1207
+ ctx.clip.type,
1208
+ ctx.clip.name,
1209
+ ctx.clip.resource ?? "",
1210
+ ctx.clip.startMs,
1211
+ ctx.clip.endMs,
1212
+ Math.round(ctx.clipWidthPx),
1213
+ ctx.renderHints.zoomActive ? "1" : "0",
1214
+ ctx.renderHints.settleVersion,
1215
+ this.mediaProvider ? "mp" : "nomp"
1216
+ ].join("|");
1217
+ if (record.lastRenderKey === renderKey) {
1218
+ return;
1219
+ }
1220
+ record.lastRenderKey = renderKey;
1221
+ record.mediaCleanups.forEach((fn) => fn());
1222
+ record.mediaCleanups = [];
1223
+ const { clip } = ctx;
1224
+ const ratio = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
1225
+ if (clip.type === "video" || clip.type === "audio") {
1226
+ const node2 = document.createElement("div");
1227
+ node2.className = `tk-media-clip is-${clip.type}`;
1228
+ const label = document.createElement("div");
1229
+ label.className = "tk-media-clip-label";
1230
+ label.textContent = clip.name;
1231
+ node2.appendChild(label);
1232
+ const body = document.createElement("div");
1233
+ body.className = "tk-media-clip-body";
1234
+ if (clip.type === "video") {
1235
+ if (this.mediaProvider?.renderFilmstrip) {
1236
+ const filmstripHost = document.createElement("div");
1237
+ filmstripHost.className = "tk-media-clip-filmstrip-host";
1238
+ const canvas = document.createElement("canvas");
1239
+ canvas.className = "tk-media-clip-canvas";
1240
+ canvas.dataset.mediaRole = "filmstrip";
1241
+ canvas.setAttribute("aria-hidden", "true");
1242
+ canvas.width = Math.max(1, Math.round(ctx.clipWidthPx * ratio));
1243
+ canvas.height = Math.max(1, Math.round(32 * ratio));
1244
+ filmstripHost.appendChild(canvas);
1245
+ body.appendChild(filmstripHost);
1246
+ const cleanup = this.mediaProvider.renderFilmstrip(canvas, ctx);
1247
+ if (typeof cleanup === "function") {
1248
+ record.mediaCleanups.push(cleanup);
1249
+ }
1250
+ } else {
1251
+ const filmstrip = document.createElement("div");
1252
+ filmstrip.className = "tk-media-clip-filmstrip";
1253
+ filmstrip.append(...createFilmstripPlaceholders());
1254
+ body.appendChild(filmstrip);
1255
+ }
1256
+ }
1257
+ const waveform = document.createElement("div");
1258
+ waveform.className = `tk-media-clip-waveform${clip.type === "audio" ? " is-audio-body" : ""}`;
1259
+ if (this.mediaProvider?.renderWaveform) {
1260
+ const canvas = document.createElement("canvas");
1261
+ canvas.className = "tk-media-clip-canvas";
1262
+ canvas.dataset.mediaRole = "waveform";
1263
+ canvas.setAttribute("aria-hidden", "true");
1264
+ canvas.width = Math.max(1, Math.round(ctx.clipWidthPx * ratio));
1265
+ canvas.height = Math.max(1, Math.round((clip.type === "audio" ? 38 : 14) * ratio));
1266
+ waveform.appendChild(canvas);
1267
+ const cleanup = this.mediaProvider.renderWaveform(canvas, ctx);
1268
+ if (typeof cleanup === "function") {
1269
+ record.mediaCleanups.push(cleanup);
1270
+ }
1271
+ } else {
1272
+ const placeholder = document.createElement("span");
1273
+ placeholder.className = "tk-media-clip-waveform-placeholder";
1274
+ waveform.appendChild(placeholder);
1275
+ }
1276
+ body.appendChild(waveform);
1277
+ node2.appendChild(body);
1278
+ record.contentHost.replaceChildren(node2);
1279
+ return;
1280
+ }
1281
+ const node = document.createElement("div");
1282
+ node.className = "tk-default-clip";
1283
+ node.dataset.type = clip.type;
1284
+ const title = document.createElement("div");
1285
+ title.className = "tk-default-clip-title";
1286
+ title.textContent = clip.name;
1287
+ const meta = document.createElement("div");
1288
+ meta.className = "tk-default-clip-meta";
1289
+ if (clip.trim || clip.durationMs) {
1290
+ const { offsetPercent, scalePercent } = getTrimOffset(clip);
1291
+ meta.textContent = `${clip.resource ?? ""} · trim ${offsetPercent.toFixed(0)}% / ${scalePercent.toFixed(0)}%`;
1292
+ } else {
1293
+ meta.textContent = clip.resource || clip.type;
1294
+ }
1295
+ node.append(title, meta);
1296
+ record.contentHost.replaceChildren(node);
1297
+ }
1298
+ renderSelectionOnly(state) {
1299
+ const selectedSet = new Set(state.selection.clipIds);
1300
+ for (const trackLayout of this.layout.tracks) {
1301
+ for (const clipLayout of trackLayout.clips) {
1302
+ const record = this.mountedClips.get(clipLayout.clip.id);
1303
+ if (!record) {
1304
+ continue;
1305
+ }
1306
+ const isSelected = selectedSet.has(clipLayout.clip.id) || state.selection.clipId === clipLayout.clip.id;
1307
+ record.clipNode.classList.toggle("is-selected", isSelected);
1308
+ setAttr(record.clipNode, "aria-selected", isSelected ? "true" : "false");
1309
+ if (record.slotRef) {
1310
+ record.slotHandle?.update?.({
1311
+ clip: clipLayout.clip,
1312
+ track: clipLayout.track,
1313
+ trackIndex: clipLayout.trackIndex,
1314
+ clipIndex: clipLayout.clipIndex,
1315
+ isSelected,
1316
+ renderHints: state.renderHints,
1317
+ clipWidthPx: Math.max(clipLayout.widthPx, MIN_CLIP_WIDTH_PX),
1318
+ isVisible: true
1319
+ });
1320
+ }
1321
+ }
1322
+ }
1323
+ }
1324
+ positionPlayhead(state) {
1325
+ const currentTimeSec = frameToSeconds(state.currentFrame, this.layout.fps);
1326
+ const offsetPx = currentTimeSec * this.layout.pixelsPerSecond;
1327
+ const scrollLeft = this.refs.mainScroller.scrollLeft;
1328
+ this.refs.playhead.style.left = `${Math.max(0, TRACK_PADDING_LEFT + offsetPx - scrollLeft)}px`;
1329
+ const handle = this.refs.playheadHandle;
1330
+ const totalFrames = Math.round(this.layout.totalDurationSec * this.layout.fps);
1331
+ setAttr(handle, "aria-valuemin", "0");
1332
+ setAttr(handle, "aria-valuemax", String(Math.max(totalFrames, state.currentFrame, 0)));
1333
+ setAttr(handle, "aria-valuenow", String(state.currentFrame));
1334
+ setAttr(handle, "aria-valuetext", formatTimecode(currentTimeSec));
1335
+ }
1336
+ /** Announces the selection through the live region. Called only on the selection channel. */
1337
+ announceSelection(state) {
1338
+ const ids = state.selection.clipIds.length > 0 ? [...state.selection.clipIds] : state.selection.clipId ? [state.selection.clipId] : [];
1339
+ const key = ids.join("\0");
1340
+ if (key === this.lastAnnouncedSelection) {
1341
+ return;
1342
+ }
1343
+ this.lastAnnouncedSelection = key;
1344
+ if (ids.length === 0) {
1345
+ this.refs.status.textContent = "Selection cleared";
1346
+ return;
1347
+ }
1348
+ const wanted = new Set(ids);
1349
+ const names = [];
1350
+ for (const track of state.document.tracks) {
1351
+ for (const clip of track.clips) {
1352
+ if (wanted.has(clip.id)) {
1353
+ names.push(clip.name || clip.id);
1354
+ }
1355
+ }
1356
+ }
1357
+ this.refs.status.textContent = names.length === 1 ? `Selected: ${names[0]}` : `Selected ${ids.length} clips: ${names.join(", ")}`;
1358
+ }
1359
+ renderOverlay() {
1360
+ if (this.overlayState.verticalGuidelinePx == null) {
1361
+ this.refs.verticalGuideline.style.display = "none";
1362
+ } else {
1363
+ this.refs.verticalGuideline.style.left = `${TRACK_PADDING_LEFT + this.overlayState.verticalGuidelinePx}px`;
1364
+ this.refs.verticalGuideline.style.display = "block";
1365
+ }
1366
+ if (this.overlayState.horizontalGuidelinePx == null) {
1367
+ this.refs.horizontalGuideline.style.display = "none";
1368
+ } else {
1369
+ this.refs.horizontalGuideline.style.top = `${this.overlayState.horizontalGuidelinePx}px`;
1370
+ this.refs.horizontalGuideline.style.display = "block";
1371
+ }
1372
+ if (!this.overlayState.dragPreview) {
1373
+ this.refs.preview.style.display = "none";
1374
+ } else {
1375
+ const p = this.overlayState.dragPreview;
1376
+ this.refs.preview.style.left = `${TRACK_PADDING_LEFT + p.leftPx}px`;
1377
+ this.refs.preview.style.top = `${p.topPx + 2}px`;
1378
+ this.refs.preview.style.width = `${p.widthPx}px`;
1379
+ this.refs.preview.style.height = `${Math.max(0, p.heightPx - 4)}px`;
1380
+ this.refs.preview.textContent = p.label ?? "移动到此处";
1381
+ this.refs.preview.style.display = "flex";
1382
+ }
1383
+ if (!this.overlayState.marqueeRect) {
1384
+ this.refs.marquee.style.display = "none";
1385
+ } else {
1386
+ const m = this.overlayState.marqueeRect;
1387
+ this.refs.marquee.style.left = `${TRACK_PADDING_LEFT + m.leftPx}px`;
1388
+ this.refs.marquee.style.top = `${m.topPx}px`;
1389
+ this.refs.marquee.style.width = `${m.widthPx}px`;
1390
+ this.refs.marquee.style.height = `${m.heightPx}px`;
1391
+ this.refs.marquee.style.display = "block";
1392
+ }
1393
+ }
1394
+ applyClipPreview(clipId) {
1395
+ const record = this.mountedClips.get(clipId);
1396
+ if (!record) {
1397
+ return;
1398
+ }
1399
+ const layoutClip = this.findLayoutClip(clipId);
1400
+ const baseLeft = layoutClip?.leftPx ?? 0;
1401
+ const baseWidth = Math.max(layoutClip?.widthPx ?? MIN_CLIP_WIDTH_PX, MIN_CLIP_WIDTH_PX);
1402
+ const override = this.clipPreviewOverrides.get(clipId);
1403
+ if (!override) {
1404
+ record.clipNode.style.left = `${baseLeft}px`;
1405
+ record.clipNode.style.width = `${baseWidth}px`;
1406
+ record.clipNode.style.transform = "";
1407
+ record.clipNode.classList.remove("is-dragging", "is-trimming");
1408
+ return;
1409
+ }
1410
+ this.applyPreviewStyleToNode(record.clipNode, override, baseLeft, baseWidth);
1411
+ }
1412
+ applyPreviewStyleToNode(clipNode, override, baseLeft, baseWidth) {
1413
+ clipNode.style.left = `${override.leftPx ?? baseLeft}px`;
1414
+ clipNode.style.width = `${override.widthPx ?? baseWidth}px`;
1415
+ const tx = override.translateX ?? 0;
1416
+ const ty = override.translateY ?? 0;
1417
+ clipNode.style.transform = tx !== 0 || ty !== 0 ? `translate(${tx}px, ${ty}px)` : "";
1418
+ clipNode.classList.toggle("is-dragging", override.isDragging === true);
1419
+ clipNode.classList.toggle("is-trimming", override.isTrimming === true);
1420
+ }
1421
+ findLayoutClip(clipId) {
1422
+ for (const track of this.layout.tracks) {
1423
+ for (const clip of track.clips) {
1424
+ if (clip.clip.id === clipId) {
1425
+ return clip;
1426
+ }
1427
+ }
1428
+ }
1429
+ return null;
1430
+ }
1431
+ getOrCreateClipRecord(clipId) {
1432
+ const existing = this.mountedClips.get(clipId);
1433
+ if (existing) {
1434
+ return existing;
1435
+ }
1436
+ const clipNode = document.createElement("div");
1437
+ clipNode.className = "tk-track-clip";
1438
+ clipNode.setAttribute("role", "option");
1439
+ const contentHost = document.createElement("div");
1440
+ contentHost.className = "tk-track-clip-content";
1441
+ const selectionFrame = document.createElement("div");
1442
+ selectionFrame.className = "tk-track-clip-selection-frame";
1443
+ const leftHandle = document.createElement("div");
1444
+ leftHandle.className = "tk-track-clip-handle is-left";
1445
+ leftHandle.dataset.trimEdge = "start";
1446
+ leftHandle.textContent = "|";
1447
+ leftHandle.setAttribute("aria-hidden", "true");
1448
+ const rightHandle = document.createElement("div");
1449
+ rightHandle.className = "tk-track-clip-handle is-right";
1450
+ rightHandle.dataset.trimEdge = "end";
1451
+ rightHandle.textContent = "|";
1452
+ rightHandle.setAttribute("aria-hidden", "true");
1453
+ clipNode.append(contentHost, selectionFrame, leftHandle, rightHandle);
1454
+ const record = {
1455
+ clipId,
1456
+ clipNode,
1457
+ contentHost,
1458
+ selectionFrame,
1459
+ leftHandle,
1460
+ rightHandle,
1461
+ mediaCleanups: []
1462
+ };
1463
+ this.mountedClips.set(clipId, record);
1464
+ return record;
1465
+ }
1466
+ pruneUnmountedClips(visibleClipIds) {
1467
+ for (const [clipId, record] of this.mountedClips.entries()) {
1468
+ if (!visibleClipIds.has(clipId)) {
1469
+ record.slotHandle?.destroy?.();
1470
+ record.mediaCleanups.forEach((fn) => fn());
1471
+ record.clipNode.remove();
1472
+ this.mountedClips.delete(clipId);
1473
+ }
1474
+ }
1475
+ }
1476
+ renderTrackOverlay(text, variant) {
1477
+ const overlay = document.createElement("div");
1478
+ overlay.className = `tk-track-overlay ${variant}`;
1479
+ overlay.setAttribute("aria-hidden", "true");
1480
+ const badge = document.createElement("div");
1481
+ badge.className = "tk-track-overlay-badge";
1482
+ badge.textContent = text;
1483
+ overlay.appendChild(badge);
1484
+ return overlay;
1485
+ }
1486
+ }
1487
+ function resolveInitialDocument(options) {
1488
+ const source = options.document ?? options.timeline;
1489
+ let doc;
1490
+ if (!source) {
1491
+ doc = {
1492
+ id: "timeline-kit",
1493
+ name: "Timeline",
1494
+ fps: options.fps ?? 24,
1495
+ tracks: []
1496
+ };
1497
+ } else if (isOtioTimeline(source)) {
1498
+ doc = fromOtioTimeline(source);
1499
+ } else {
1500
+ doc = cloneDocument(source);
1501
+ }
1502
+ if (typeof options.fps === "number" && options.fps > 0 && !options.document && !isOtioTimeline(options.timeline)) {
1503
+ doc.fps = options.fps;
1504
+ } else if (typeof options.fps === "number" && options.fps > 0 && doc.fps <= 0) {
1505
+ doc.fps = options.fps;
1506
+ }
1507
+ return doc;
1508
+ }
1509
+ function resolveUIConfig(options) {
1510
+ const ui = { ...options.ui ?? {} };
1511
+ if (ui.toolbar === void 0 && options.toolsConfigs !== void 0) {
1512
+ ui.toolbar = options.toolsConfigs;
1513
+ }
1514
+ return ui;
1515
+ }
1516
+ const liveEditors = /* @__PURE__ */ new Set();
1517
+ let activeEditor = null;
1518
+ class TimelineEditor extends EventTarget {
1519
+ container;
1520
+ store;
1521
+ commands;
1522
+ renderer;
1523
+ interactions;
1524
+ policies;
1525
+ uiConfig;
1526
+ resizeObserver;
1527
+ destroyed;
1528
+ onPointerDownRef;
1529
+ onFocusInRef;
1530
+ onPointerMoveRef;
1531
+ onPointerUpRef;
1532
+ onPointerCancelRef;
1533
+ onWheelRef;
1534
+ onClickRef;
1535
+ onInputRef;
1536
+ onScrollRef;
1537
+ onDragOverRef;
1538
+ onDragLeaveRef;
1539
+ onDropRef;
1540
+ onKeyDownRef;
1541
+ onKeyUpRef;
1542
+ onWindowResizeRef;
1543
+ unsubscribeStore;
1544
+ unsubscribeAfterCommand;
1545
+ constructor(container, options = {}) {
1546
+ super();
1547
+ this.container = container;
1548
+ this.destroyed = false;
1549
+ this.resizeObserver = null;
1550
+ this.policies = {
1551
+ ...DEFAULT_EDIT_POLICIES,
1552
+ ...options.policies ?? {}
1553
+ };
1554
+ this.uiConfig = resolveUIConfig(options);
1555
+ const initialDoc = resolveInitialDocument(options);
1556
+ this.store = new TimelineStore({
1557
+ document: initialDoc,
1558
+ currentFrame: options.currentFrame,
1559
+ trackScale: options.trackScale,
1560
+ isMagnetEnabled: options.isMagnetEnabled,
1561
+ renderHints: options.renderHints,
1562
+ theme: options.theme ?? "auto",
1563
+ historyMode: options.history ?? "internal"
1564
+ });
1565
+ this.renderer = new DomTimelineRenderer(container, {
1566
+ trackConfigs: options.trackConfigs,
1567
+ ui: this.uiConfig,
1568
+ theme: options.theme ?? "auto",
1569
+ injectStyles: options.injectStyles,
1570
+ mediaProvider: options.mediaProvider
1571
+ });
1572
+ this.commands = new CommandBus({
1573
+ store: this.store,
1574
+ getPolicies: () => this.policies,
1575
+ fitToView: () => this.computeFitToViewScale()
1576
+ });
1577
+ registerBuiltinCommands(this.commands);
1578
+ if (options.onBeforeCommand) {
1579
+ this.commands.addBeforeHook(options.onBeforeCommand);
1580
+ }
1581
+ this.interactions = new InteractionManager({
1582
+ store: this.store,
1583
+ commands: this.commands,
1584
+ renderer: this.renderer,
1585
+ getPolicies: () => this.policies
1586
+ });
1587
+ if (!options.disableDefaultPlugins) {
1588
+ const defaults = createDefaultPlugins({ shortcuts: options.shortcuts });
1589
+ for (const plugin of defaults) {
1590
+ this.interactions.use(plugin);
1591
+ }
1592
+ }
1593
+ if (options.keymap) {
1594
+ for (const [chord, binding] of Object.entries(options.keymap)) {
1595
+ this.interactions.setKeyBinding(chord, binding);
1596
+ }
1597
+ }
1598
+ if (options.plugins) {
1599
+ for (const plugin of options.plugins) {
1600
+ this.interactions.use(plugin);
1601
+ }
1602
+ }
1603
+ this.unsubscribeStore = this.store.subscribe((change) => {
1604
+ this.handleStateChange(change);
1605
+ });
1606
+ this.unsubscribeAfterCommand = this.commands.addAfterHook((command, executed) => {
1607
+ if (executed) {
1608
+ this.emitCommandEvent(command);
1609
+ }
1610
+ });
1611
+ this.onPointerDownRef = (event) => this.onPointerDown(event);
1612
+ this.onPointerMoveRef = (event) => this.onPointerMove(event);
1613
+ this.onPointerUpRef = (event) => this.onPointerUp(event);
1614
+ this.onPointerCancelRef = () => {
1615
+ this.interactions.cancelActiveSession();
1616
+ };
1617
+ this.onWheelRef = (event) => this.onWheel(event);
1618
+ this.onClickRef = (event) => this.onClick(event);
1619
+ this.onInputRef = (event) => this.onInput(event);
1620
+ this.onScrollRef = () => this.renderer.handleScroll();
1621
+ this.onDragOverRef = (event) => this.onDragOver(event);
1622
+ this.onDragLeaveRef = () => this.interactions.handleDragLeave();
1623
+ this.onDropRef = (event) => this.onDrop(event);
1624
+ this.onKeyDownRef = (event) => this.onKeyDown(event);
1625
+ this.onFocusInRef = () => this.markActive();
1626
+ this.onKeyUpRef = (event) => this.onKeyUp(event);
1627
+ this.onWindowResizeRef = () => this.resize();
1628
+ this.renderer.render(this.store.getState());
1629
+ this.bindEvents();
1630
+ }
1631
+ getDocument() {
1632
+ return cloneDocument(this.store.getState().document);
1633
+ }
1634
+ setDocument(doc, options) {
1635
+ this.store.setDocument(doc, { pushHistory: options?.pushHistory ?? false });
1636
+ }
1637
+ getTimeline() {
1638
+ return this.getDocument();
1639
+ }
1640
+ setTimeline(timeline, options) {
1641
+ const doc = isOtioTimeline(timeline) ? fromOtioTimeline(timeline) : timeline;
1642
+ this.store.setDocument(doc, { pushHistory: options?.pushHistory ?? false });
1643
+ }
1644
+ getOtioTimeline() {
1645
+ return toOtioTimeline(this.store.getState().document);
1646
+ }
1647
+ getCurrentFrame() {
1648
+ return this.store.getState().currentFrame;
1649
+ }
1650
+ setCurrentFrame(frame) {
1651
+ this.store.setCurrentFrame(frame);
1652
+ }
1653
+ getTrackScale() {
1654
+ return this.store.getState().trackScale;
1655
+ }
1656
+ setTrackScale(scale, renderHints) {
1657
+ this.store.setTrackScale(scale, renderHints);
1658
+ }
1659
+ fitToView() {
1660
+ const scale = this.computeFitToViewScale();
1661
+ if (scale !== null) {
1662
+ this.store.setTrackScale(scale);
1663
+ }
1664
+ return scale;
1665
+ }
1666
+ scrollToTime(ms) {
1667
+ const state = this.store.getState();
1668
+ const pps = getPixelsPerSecond(state.trackScale, state.document.fps);
1669
+ const targetPx = Math.max(0, msToPx(ms, pps));
1670
+ this.renderer.setScrollLeft(targetPx);
1671
+ }
1672
+ setSelection(selection) {
1673
+ if (selection === null) {
1674
+ this.store.clearSelection();
1675
+ return;
1676
+ }
1677
+ if (typeof selection === "string") {
1678
+ this.store.setSelection([selection], selection);
1679
+ return;
1680
+ }
1681
+ if (Array.isArray(selection)) {
1682
+ this.store.setSelection(selection, selection[0] ?? null);
1683
+ return;
1684
+ }
1685
+ const ids = selection.clipIds ?? (selection.clipId ? [selection.clipId] : []);
1686
+ this.store.setSelection(ids, selection.clipId ?? ids[0] ?? null);
1687
+ }
1688
+ clearSelection() {
1689
+ this.store.clearSelection();
1690
+ }
1691
+ setMagnetEnabled(enabled) {
1692
+ this.commands.execute("magnet:set", { enabled });
1693
+ }
1694
+ setHistoryMode(mode) {
1695
+ this.store.setHistoryMode(mode);
1696
+ }
1697
+ setExternalHistoryState(flags) {
1698
+ this.store.setExternalHistoryState(flags);
1699
+ }
1700
+ setTrackConfigs(trackConfigs) {
1701
+ this.renderer.setTrackConfigs(trackConfigs ?? {});
1702
+ this.renderer.render(this.store.getState(), /* @__PURE__ */ new Set(["tracks", "sidebar", "playhead"]));
1703
+ }
1704
+ setToolsConfigs(toolsConfigs) {
1705
+ this.uiConfig = {
1706
+ ...this.uiConfig,
1707
+ toolbar: toolsConfigs ?? true
1708
+ };
1709
+ this.renderer.setUIConfig(this.uiConfig);
1710
+ this.renderer.render(this.store.getState(), /* @__PURE__ */ new Set(["toolbar"]));
1711
+ }
1712
+ setUI(ui) {
1713
+ this.uiConfig = { ...ui };
1714
+ this.renderer.setUIConfig(this.uiConfig);
1715
+ this.renderer.render(this.store.getState(), /* @__PURE__ */ new Set(["toolbar", "sidebar", "ruler", "tracks", "playhead"]));
1716
+ }
1717
+ setTheme(theme) {
1718
+ this.store.setTheme(theme);
1719
+ }
1720
+ setPolicies(policies) {
1721
+ this.policies = {
1722
+ ...this.policies,
1723
+ ...policies
1724
+ };
1725
+ }
1726
+ setRenderHints(renderHints) {
1727
+ this.store.setRenderHints(renderHints);
1728
+ }
1729
+ setMediaProvider(provider) {
1730
+ this.renderer.setMediaProvider(provider);
1731
+ this.renderer.render(this.store.getState(), /* @__PURE__ */ new Set(["tracks"]));
1732
+ }
1733
+ exec(command, payload) {
1734
+ return this.commands.execute(command, payload);
1735
+ }
1736
+ canExecute(command, payload) {
1737
+ return this.commands.canExecute(command, payload);
1738
+ }
1739
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- public default kept for API compatibility
1740
+ registerCommand(type, spec) {
1741
+ return this.commands.register(type, spec);
1742
+ }
1743
+ onBeforeCommand(hook) {
1744
+ return this.commands.addBeforeHook(hook);
1745
+ }
1746
+ use(plugin) {
1747
+ return this.interactions.use(plugin);
1748
+ }
1749
+ removePlugin(name) {
1750
+ return this.interactions.remove(name);
1751
+ }
1752
+ getState() {
1753
+ return this.store.getState();
1754
+ }
1755
+ getSnapshot() {
1756
+ return this.store.getSnapshot();
1757
+ }
1758
+ subscribe(listener) {
1759
+ return this.store.subscribe(listener);
1760
+ }
1761
+ subscribeSelector(selector, listener, isEqual) {
1762
+ return this.store.subscribeSelector(selector, listener, isEqual);
1763
+ }
1764
+ resize() {
1765
+ if (this.destroyed) {
1766
+ return;
1767
+ }
1768
+ this.renderer.clearOverlay();
1769
+ this.renderer.render(this.store.getState(), /* @__PURE__ */ new Set(["ruler", "tracks", "sidebar", "playhead"]));
1770
+ }
1771
+ destroy() {
1772
+ if (this.destroyed) {
1773
+ return;
1774
+ }
1775
+ this.destroyed = true;
1776
+ this.unbindEvents();
1777
+ this.interactions.destroy();
1778
+ this.unsubscribeStore();
1779
+ this.unsubscribeAfterCommand();
1780
+ this.renderer.destroy();
1781
+ }
1782
+ bindEvents() {
1783
+ const root = this.renderer.getRootElement();
1784
+ const scroller = this.renderer.getMainScrollerElement();
1785
+ root.addEventListener("pointerdown", this.onPointerDownRef);
1786
+ root.addEventListener("focusin", this.onFocusInRef);
1787
+ liveEditors.add(this);
1788
+ root.addEventListener("click", this.onClickRef);
1789
+ root.addEventListener("input", this.onInputRef);
1790
+ root.addEventListener("wheel", this.onWheelRef, { passive: false });
1791
+ root.addEventListener("dragover", this.onDragOverRef);
1792
+ root.addEventListener("dragleave", this.onDragLeaveRef);
1793
+ root.addEventListener("drop", this.onDropRef);
1794
+ scroller.addEventListener("scroll", this.onScrollRef);
1795
+ window.addEventListener("pointermove", this.onPointerMoveRef);
1796
+ window.addEventListener("pointerup", this.onPointerUpRef);
1797
+ window.addEventListener("pointercancel", this.onPointerCancelRef);
1798
+ window.addEventListener("keydown", this.onKeyDownRef);
1799
+ window.addEventListener("keyup", this.onKeyUpRef);
1800
+ window.addEventListener("resize", this.onWindowResizeRef);
1801
+ if (typeof ResizeObserver !== "undefined") {
1802
+ this.resizeObserver = new ResizeObserver(() => {
1803
+ this.resize();
1804
+ });
1805
+ this.resizeObserver.observe(this.container);
1806
+ }
1807
+ }
1808
+ unbindEvents() {
1809
+ const root = this.renderer.getRootElement();
1810
+ const scroller = this.renderer.getMainScrollerElement();
1811
+ root.removeEventListener("pointerdown", this.onPointerDownRef);
1812
+ root.removeEventListener("focusin", this.onFocusInRef);
1813
+ liveEditors.delete(this);
1814
+ if (activeEditor === this) {
1815
+ activeEditor = null;
1816
+ }
1817
+ root.removeEventListener("click", this.onClickRef);
1818
+ root.removeEventListener("input", this.onInputRef);
1819
+ root.removeEventListener("wheel", this.onWheelRef);
1820
+ root.removeEventListener("dragover", this.onDragOverRef);
1821
+ root.removeEventListener("dragleave", this.onDragLeaveRef);
1822
+ root.removeEventListener("drop", this.onDropRef);
1823
+ scroller.removeEventListener("scroll", this.onScrollRef);
1824
+ window.removeEventListener("pointermove", this.onPointerMoveRef);
1825
+ window.removeEventListener("pointerup", this.onPointerUpRef);
1826
+ window.removeEventListener("pointercancel", this.onPointerCancelRef);
1827
+ window.removeEventListener("keydown", this.onKeyDownRef);
1828
+ window.removeEventListener("keyup", this.onKeyUpRef);
1829
+ window.removeEventListener("resize", this.onWindowResizeRef);
1830
+ if (this.resizeObserver) {
1831
+ this.resizeObserver.disconnect();
1832
+ this.resizeObserver = null;
1833
+ }
1834
+ }
1835
+ handleStateChange(change) {
1836
+ if (this.destroyed) {
1837
+ return;
1838
+ }
1839
+ this.renderer.render(change.state, change.dirty);
1840
+ const { state, prevState } = change;
1841
+ if (state.document !== prevState.document) {
1842
+ this.emitStateEvent("documentchange");
1843
+ this.emitStateEvent("timelinechange");
1844
+ }
1845
+ if (state.selection !== prevState.selection) {
1846
+ this.emitStateEvent("selectionchange");
1847
+ }
1848
+ if (state.currentFrame !== prevState.currentFrame) {
1849
+ this.emitStateEvent("currentframechange");
1850
+ }
1851
+ if (state.trackScale !== prevState.trackScale) {
1852
+ this.emitStateEvent("trackscalechange");
1853
+ }
1854
+ if (state.isMagnetEnabled !== prevState.isMagnetEnabled) {
1855
+ this.emitStateEvent("magnetchange");
1856
+ }
1857
+ }
1858
+ emitStateEvent(type) {
1859
+ this.dispatchEvent(new CustomEvent(type, {
1860
+ detail: this.getSnapshot()
1861
+ }));
1862
+ }
1863
+ emitCommandEvent(command) {
1864
+ this.dispatchEvent(new CustomEvent("command", {
1865
+ detail: {
1866
+ command,
1867
+ snapshot: this.getSnapshot()
1868
+ }
1869
+ }));
1870
+ }
1871
+ markActive() {
1872
+ activeEditor = this;
1873
+ }
1874
+ onPointerDown(event) {
1875
+ this.markActive();
1876
+ const doc = this.store.getState().document;
1877
+ const hit = this.renderer.hitTestClientPoint(event.clientX, event.clientY, event.target, doc);
1878
+ this.interactions.handlePointerDown({
1879
+ originalEvent: event,
1880
+ hit,
1881
+ clientX: event.clientX,
1882
+ clientY: event.clientY,
1883
+ shiftKey: event.shiftKey,
1884
+ ctrlKey: event.ctrlKey,
1885
+ metaKey: event.metaKey,
1886
+ altKey: event.altKey,
1887
+ button: event.button
1888
+ });
1889
+ }
1890
+ onPointerMove(event) {
1891
+ if (!this.interactions.hasActiveSession()) {
1892
+ return;
1893
+ }
1894
+ const doc = this.store.getState().document;
1895
+ const hit = this.renderer.hitTestClientPoint(event.clientX, event.clientY, event.target, doc);
1896
+ this.interactions.handlePointerMove({
1897
+ originalEvent: event,
1898
+ hit,
1899
+ clientX: event.clientX,
1900
+ clientY: event.clientY,
1901
+ shiftKey: event.shiftKey,
1902
+ ctrlKey: event.ctrlKey,
1903
+ metaKey: event.metaKey,
1904
+ altKey: event.altKey,
1905
+ button: event.button
1906
+ });
1907
+ }
1908
+ onPointerUp(event) {
1909
+ if (!this.interactions.hasActiveSession()) {
1910
+ return;
1911
+ }
1912
+ const doc = this.store.getState().document;
1913
+ const hit = this.renderer.hitTestClientPoint(event.clientX, event.clientY, event.target, doc);
1914
+ this.interactions.handlePointerUp({
1915
+ originalEvent: event,
1916
+ hit,
1917
+ clientX: event.clientX,
1918
+ clientY: event.clientY,
1919
+ shiftKey: event.shiftKey,
1920
+ ctrlKey: event.ctrlKey,
1921
+ metaKey: event.metaKey,
1922
+ altKey: event.altKey,
1923
+ button: event.button
1924
+ });
1925
+ }
1926
+ onWheel(event) {
1927
+ const doc = this.store.getState().document;
1928
+ const hit = this.renderer.hitTestClientPoint(event.clientX, event.clientY, event.target, doc);
1929
+ this.interactions.handleWheel({
1930
+ originalEvent: event,
1931
+ hit,
1932
+ deltaX: event.deltaX,
1933
+ deltaY: event.deltaY,
1934
+ ctrlKey: event.ctrlKey,
1935
+ metaKey: event.metaKey,
1936
+ shiftKey: event.shiftKey
1937
+ });
1938
+ }
1939
+ onDragOver(event) {
1940
+ const doc = this.store.getState().document;
1941
+ const hit = this.renderer.hitTestClientPoint(event.clientX, event.clientY, event.target, doc);
1942
+ this.interactions.handleDragOver({
1943
+ originalEvent: event,
1944
+ hit,
1945
+ dataTransfer: event.dataTransfer
1946
+ });
1947
+ }
1948
+ onDrop(event) {
1949
+ const doc = this.store.getState().document;
1950
+ const hit = this.renderer.hitTestClientPoint(event.clientX, event.clientY, event.target, doc);
1951
+ this.interactions.handleDrop({
1952
+ originalEvent: event,
1953
+ hit,
1954
+ dataTransfer: event.dataTransfer
1955
+ });
1956
+ }
1957
+ onClick(event) {
1958
+ const target = event.target instanceof Element ? event.target : null;
1959
+ if (!target) {
1960
+ return;
1961
+ }
1962
+ const trackButton = target.closest("[data-track-command]");
1963
+ if (trackButton) {
1964
+ const flag = trackButton.dataset.trackCommand;
1965
+ const trackIndex = Number(trackButton.dataset.trackIndex ?? -1);
1966
+ if (flag && trackIndex >= 0) {
1967
+ this.commands.execute("track:toggle-flag", { trackIndex, flag });
1968
+ this.renderer.focusContainer();
1969
+ }
1970
+ return;
1971
+ }
1972
+ const button = target.closest("[data-command]");
1973
+ if (!button) {
1974
+ return;
1975
+ }
1976
+ const command = button.dataset.command;
1977
+ if (!command) {
1978
+ return;
1979
+ }
1980
+ this.commands.execute(command);
1981
+ this.renderer.focusContainer();
1982
+ }
1983
+ onInput(event) {
1984
+ const target = event.target instanceof HTMLInputElement ? event.target : null;
1985
+ if (!target || target.dataset.command !== "track-scale") {
1986
+ return;
1987
+ }
1988
+ const value = Number(target.value);
1989
+ if (Number.isFinite(value)) {
1990
+ this.commands.execute("scale:set", { scale: value });
1991
+ }
1992
+ }
1993
+ onKeyDown(event) {
1994
+ if (!this.shouldHandleWindowKeyEvent()) {
1995
+ return;
1996
+ }
1997
+ this.interactions.handleKeyDown(event);
1998
+ }
1999
+ onKeyUp(event) {
2000
+ if (!this.shouldHandleWindowKeyEvent()) {
2001
+ return;
2002
+ }
2003
+ this.interactions.handleKeyUp(event);
2004
+ }
2005
+ shouldHandleWindowKeyEvent() {
2006
+ if (this.interactions.hasActiveSession()) {
2007
+ return true;
2008
+ }
2009
+ const root = this.renderer.getRootElement();
2010
+ const active = typeof document !== "undefined" ? document.activeElement : null;
2011
+ if (active && root.contains(active)) {
2012
+ return true;
2013
+ }
2014
+ if (!active || active === document.body || active === document.documentElement) {
2015
+ return activeEditor ? activeEditor === this : liveEditors.size === 1;
2016
+ }
2017
+ return false;
2018
+ }
2019
+ computeFitToViewScale() {
2020
+ const state = this.store.getState();
2021
+ const layout = this.renderer.getLayout();
2022
+ const metrics = this.renderer.getViewportMetrics();
2023
+ const totalDurationMs = Math.max(layout.totalDurationMs, 1);
2024
+ const availableWidth = Math.max(metrics.clientWidth * 0.9, 320);
2025
+ const candidateScales = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0];
2026
+ for (const scale of candidateScales) {
2027
+ const pps = getPixelsPerSecond(scale, state.document.fps);
2028
+ if (msToPx(totalDurationMs, pps) <= availableWidth) {
2029
+ return scale;
2030
+ }
2031
+ }
2032
+ return 0;
2033
+ }
2034
+ }
2035
+ function createTimelineEditor(container, options = {}) {
2036
+ return new TimelineEditor(container, options);
2037
+ }
2038
+ export {
2039
+ DEFAULT_TOOLS as D,
2040
+ SidebarRenderer as S,
2041
+ TimelineEditor as T,
2042
+ DomTimelineRenderer as a,
2043
+ ToolbarRenderer as b,
2044
+ createTimelineEditor as c,
2045
+ drawTimeRuler as d,
2046
+ ensureTimelineStyles as e,
2047
+ getTrimOffset as g,
2048
+ isSlotRendererObject as i,
2049
+ normalizeSlotRenderer as n
2050
+ };
2051
+ //# sourceMappingURL=TimelineEditor-ZMbJ8-ee.js.map