@bendyline/squisq-editor-react 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/index.d.ts +757 -20
  2. package/dist/index.js +16910 -6844
  3. package/dist/index.js.map +1 -1
  4. package/package.json +4 -4
  5. package/src/BlockCardView.tsx +121 -0
  6. package/src/BlockPreviewPanel.tsx +69 -0
  7. package/src/BlockPropertiesPopover.tsx +191 -0
  8. package/src/EditorContext.tsx +143 -0
  9. package/src/EditorShell.tsx +200 -120
  10. package/src/FolderView.tsx +131 -0
  11. package/src/Icon.tsx +26 -0
  12. package/src/ImageEditor.tsx +69 -22
  13. package/src/OutlinePanel.tsx +38 -3
  14. package/src/PlainHtmlPreview.tsx +30 -3
  15. package/src/PreviewControls.tsx +180 -8
  16. package/src/RawEditor.tsx +216 -29
  17. package/src/RecorderEntry.tsx +9 -16
  18. package/src/TemplateAnnotation.ts +44 -0
  19. package/src/TemplatePicker.tsx +329 -54
  20. package/src/ThemeCustomizerPanel.tsx +30 -336
  21. package/src/ThemePicker.tsx +112 -3
  22. package/src/TimelineBlockPreview.tsx +37 -0
  23. package/src/TimelineTrack.tsx +671 -0
  24. package/src/Toolbar.tsx +528 -174
  25. package/src/Tooltip.tsx +22 -4
  26. package/src/TransitionPicker.tsx +351 -0
  27. package/src/VersionHistoryPanel.tsx +61 -31
  28. package/src/ViewMenuPanel.tsx +17 -14
  29. package/src/WysiwygEditor.tsx +161 -65
  30. package/src/__tests__/blockProperties.test.ts +92 -0
  31. package/src/__tests__/blockRange.test.ts +105 -0
  32. package/src/__tests__/buildPreviewDocTransition.test.ts +73 -0
  33. package/src/__tests__/createShapeLayer.test.ts +46 -0
  34. package/src/__tests__/drawingShapeRoundTrip.test.ts +49 -0
  35. package/src/__tests__/embeddedMedia.test.ts +48 -0
  36. package/src/__tests__/headingTransition.test.ts +138 -0
  37. package/src/__tests__/layoutChildRoundTrip.test.ts +71 -0
  38. package/src/__tests__/plainHtmlPreview.test.tsx +10 -8
  39. package/src/__tests__/recorderMediaInsert.test.ts +86 -0
  40. package/src/__tests__/templateAnnotationRoundTrip.test.ts +18 -0
  41. package/src/__tests__/templatePickerMetadata.test.ts +32 -0
  42. package/src/__tests__/timelineSource.test.ts +134 -0
  43. package/src/__tests__/tiptapBridge.test.ts +92 -0
  44. package/src/__tests__/tiptapBridgeConformance.test.ts +47 -0
  45. package/src/__tests__/tooltip.test.tsx +72 -0
  46. package/src/__tests__/transitionCatalog.test.ts +64 -0
  47. package/src/__tests__/useBlockNavigator.test.tsx +67 -0
  48. package/src/__tests__/useMediaRecorder.test.ts +24 -0
  49. package/src/__tests__/useTimelineClock.test.ts +21 -0
  50. package/src/blockProperties.ts +88 -0
  51. package/src/blockRange.ts +132 -0
  52. package/src/buildPreviewDoc.ts +98 -9
  53. package/src/customTemplates/AddBin.tsx +126 -0
  54. package/src/customTemplates/CustomLayoutManager.tsx +233 -0
  55. package/src/customTemplates/CustomTemplateContext.tsx +182 -0
  56. package/src/customTemplates/LayerToolbar.tsx +580 -0
  57. package/src/customTemplates/ShapeGlyph.tsx +47 -0
  58. package/src/customTemplates/TemplateDesigner.tsx +430 -0
  59. package/src/customTemplates/__tests__/library.test.ts +88 -0
  60. package/src/customTemplates/__tests__/normalizePositions.test.ts +109 -0
  61. package/src/customTemplates/__tests__/shapeDefs.test.ts +49 -0
  62. package/src/customTemplates/__tests__/useMemoryLayerAdapter.test.ts +95 -0
  63. package/src/customTemplates/designer.css +673 -0
  64. package/src/customTemplates/index.ts +31 -0
  65. package/src/customTemplates/library.ts +97 -0
  66. package/src/customTemplates/normalizePositions.ts +75 -0
  67. package/src/customTemplates/shapeDefs.ts +131 -0
  68. package/src/customTemplates/thumbnail.tsx +63 -0
  69. package/src/customTemplates/tokenDefs.ts +60 -0
  70. package/src/customTemplates/useDocCustomTemplates.ts +52 -0
  71. package/src/customTemplates/useMemoryLayerAdapter.ts +123 -0
  72. package/src/customThemes/CustomThemeContext.tsx +179 -0
  73. package/src/customThemes/CustomThemeDialog.tsx +286 -0
  74. package/src/customThemes/__tests__/CustomThemeContext.test.tsx +64 -0
  75. package/src/customThemes/__tests__/CustomThemeDialog.test.tsx +47 -0
  76. package/src/customThemes/__tests__/customThemeLibrary.test.ts +51 -0
  77. package/src/customThemes/customThemeLibrary.ts +97 -0
  78. package/src/customThemes/index.ts +31 -0
  79. package/src/customThemes/themeControls.tsx +229 -0
  80. package/src/customThemes/themeDraft.ts +272 -0
  81. package/src/customThemes/useDocCustomThemes.ts +49 -0
  82. package/src/diagram/DiagramCanvas.tsx +240 -0
  83. package/src/diagram/DiagramExtension.ts +209 -0
  84. package/src/diagram/DiagramMaximizedOverlay.tsx +46 -0
  85. package/src/diagram/DiagramWidget.tsx +270 -0
  86. package/src/diagram/diagramCommands.ts +604 -0
  87. package/src/diagram/diagramConstants.ts +17 -0
  88. package/src/diagram/useDiagramData.ts +126 -0
  89. package/src/embeddedMedia.ts +78 -0
  90. package/src/frontmatter.ts +29 -0
  91. package/src/headingTransition.ts +231 -0
  92. package/src/imageEditor/CanvasSurface.tsx +383 -88
  93. package/src/imageEditor/PropertiesPanel.tsx +47 -1
  94. package/src/imageEditor/Toolbar.tsx +229 -16
  95. package/src/imageEditor/createShapeLayer.ts +280 -0
  96. package/src/imageEditor/icons.tsx +34 -114
  97. package/src/imageEditor/image-editor.css +54 -5
  98. package/src/imageEditor/state.ts +23 -3
  99. package/src/index.ts +77 -0
  100. package/src/recorder/RecorderModal.tsx +120 -53
  101. package/src/recorder/RecorderPanel.tsx +2 -26
  102. package/src/recorder/hooks/useMediaRecorder.ts +17 -2
  103. package/src/recorder/insertMediaBlock.ts +30 -0
  104. package/src/resolveBlockVisual.ts +33 -0
  105. package/src/scene/Scene.tsx +540 -0
  106. package/src/scene/SceneBlockExtension.ts +198 -0
  107. package/src/scene/SceneBlockToolbar.tsx +201 -0
  108. package/src/scene/SceneBlockWidget.tsx +434 -0
  109. package/src/scene/ScenePropsBar.tsx +85 -0
  110. package/src/scene/SceneSelection.tsx +107 -0
  111. package/src/scene/SceneViewport.tsx +102 -0
  112. package/src/scene/ShapePalette.tsx +181 -0
  113. package/src/scene/__tests__/DiagramAdapter.test.ts +56 -0
  114. package/src/scene/__tests__/bezierEdit.test.ts +85 -0
  115. package/src/scene/__tests__/blockLayers.test.ts +57 -0
  116. package/src/scene/__tests__/shapeLayers.test.ts +106 -0
  117. package/src/scene/__tests__/useSceneHitTest.test.ts +90 -0
  118. package/src/scene/__tests__/useScenePanZoom.test.ts +103 -0
  119. package/src/scene/adapters/DiagramAdapter.ts +168 -0
  120. package/src/scene/adapters/DrawingAdapter.ts +415 -0
  121. package/src/scene/adapters/LayoutAdapter.ts +310 -0
  122. package/src/scene/adapters/blockLayers.ts +159 -0
  123. package/src/scene/commands/SceneCommand.ts +70 -0
  124. package/src/scene/commands/drawingCommands.ts +318 -0
  125. package/src/scene/commands/layoutCommands.ts +301 -0
  126. package/src/scene/hooks/useSceneHitTest.ts +105 -0
  127. package/src/scene/hooks/useScenePanZoom.ts +147 -0
  128. package/src/scene/hooks/useSceneSelection.ts +62 -0
  129. package/src/scene/index.ts +95 -0
  130. package/src/scene/layers/DiagramEdges.tsx +127 -0
  131. package/src/scene/layers/edgeGeometry.ts +77 -0
  132. package/src/scene/layers/nodeCard.tsx +145 -0
  133. package/src/scene/layers/renderLayer.tsx +70 -0
  134. package/src/scene/layers/shapeLayers.ts +201 -0
  135. package/src/scene/paths/bezierEdit.ts +208 -0
  136. package/src/scene/scene.css +649 -0
  137. package/src/scene/text/SceneTextOverlay.tsx +161 -0
  138. package/src/scene/text/sceneTextChannel.ts +40 -0
  139. package/src/scene/text/sceneTextConfig.ts +27 -0
  140. package/src/scene/text/sceneTiptap.ts +36 -0
  141. package/src/scene/text/useSceneTextEditing.ts +39 -0
  142. package/src/scene/tools/ConnectTool.ts +111 -0
  143. package/src/scene/tools/DrawingConnectTool.ts +161 -0
  144. package/src/scene/tools/PathTool.ts +158 -0
  145. package/src/scene/tools/PlaceTool.ts +47 -0
  146. package/src/scene/tools/SceneTool.ts +75 -0
  147. package/src/scene/tools/SelectTool.ts +284 -0
  148. package/src/scene/tools/ShapeTool.ts +144 -0
  149. package/src/scene/tools/TextTool.ts +72 -0
  150. package/src/scene/tools/TokenTool.ts +95 -0
  151. package/src/scene/tools/createDrawShapeTool.ts +82 -0
  152. package/src/styles/diagram.css +183 -0
  153. package/src/styles/editor.css +1615 -203
  154. package/src/styles/folder-view.css +210 -0
  155. package/src/styles/image-edit-affordance.css +2 -2
  156. package/src/styles/index.css +4 -0
  157. package/src/timelineSource.ts +244 -0
  158. package/src/tiptapBridge.ts +115 -34
  159. package/src/tooltipPlacement.ts +13 -0
  160. package/src/transitionCatalog.ts +159 -0
  161. package/src/types/monaco-shims.d.ts +10 -0
  162. package/src/useBlockNavigator.ts +153 -0
  163. package/src/useMonacoLoader.ts +105 -0
  164. package/src/useTimelineClock.ts +76 -0
  165. package/src/utils/dropUtils.ts +1 -1
@@ -0,0 +1,671 @@
1
+ /**
2
+ * TimelineTrack
3
+ *
4
+ * Horizontal timeline strip for the Timeline view. Shows every block as a bar
5
+ * (width ∝ duration, x ∝ startTime) with its media clips as sub-bars below.
6
+ * Clicking a block selects it (the editor above follows). Dragging a block's
7
+ * right edge changes its duration; dragging its left edge changes the previous
8
+ * block's duration (the boundary, since startTime is derived). Dragging a media
9
+ * clip moves its `startAt`; dragging the clip's right edge changes its length;
10
+ * double-clicking a clip toggles `spillover`. All edits are written back to the
11
+ * markdown source via {@link timelineSource}.
12
+ */
13
+
14
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
15
+ import type { Block, MediaClip } from '@bendyline/squisq/schemas';
16
+ import {
17
+ resolveMediaSchedule,
18
+ getDocPlaybackDuration,
19
+ VIEWPORT_PRESETS,
20
+ type ScheduledClip,
21
+ } from '@bendyline/squisq/schemas';
22
+ import { flattenBlocks, DEFAULT_THEME } from '@bendyline/squisq/doc';
23
+ import { MediaClipLayer, MediaContext } from '@bendyline/squisq-react';
24
+ import { useEditorContext } from './EditorContext';
25
+ import { usePreviewSettingsOptional } from './PreviewControls';
26
+ import {
27
+ setBlockDurationInSource,
28
+ setMediaClipInSource,
29
+ placeClipInBlock,
30
+ type ClipSpec,
31
+ } from './timelineSource';
32
+ import { collectEmbeddedMedia } from './embeddedMedia';
33
+ import { BlockThumbnail } from './TimelineBlockPreview';
34
+ import { resolveBlockVisual } from './resolveBlockVisual';
35
+ import { useTimelineClock } from './useTimelineClock';
36
+
37
+ /** Viewport the per-bar thumbnails render at. */
38
+ const PREVIEW_VIEWPORT = VIEWPORT_PRESETS.landscape;
39
+
40
+ const DEFAULT_PX_PER_SECOND = 18;
41
+ const ZOOM_MIN = 4;
42
+ const ZOOM_MAX = 160;
43
+ const ZOOM_FACTOR = 1.4;
44
+ const MIN_DURATION = 0.5; // seconds — floor when dragging a block edge
45
+ /** Candidate ruler-tick intervals (seconds); the first wide enough is used. */
46
+ const TICK_STEPS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600];
47
+ /** Minimum pixels between ruler ticks. */
48
+ const TICK_MIN_PX = 64;
49
+
50
+ type DragKind =
51
+ | 'block-right'
52
+ | 'block-left'
53
+ | 'clip-move'
54
+ | 'clip-right'
55
+ | 'embed-move'
56
+ | 'embed-right';
57
+
58
+ interface DragState {
59
+ kind: DragKind;
60
+ startX: number;
61
+ /** Lower bound (seconds) for the dragged value (0 for position drags). */
62
+ floor: number;
63
+ /** Value (seconds) at drag start, added to the pointer delta. */
64
+ previewBase: number;
65
+ /** Live preview value (seconds) shown while dragging. */
66
+ preview: number;
67
+ commit: (seconds: number) => void;
68
+ /** Id of the bar/clip being dragged (for live preview geometry). */
69
+ targetId: string;
70
+ /**
71
+ * For block-edge drags: index of the block whose duration changes. Its bar
72
+ * previews at `preview` and every block after it shifts by the delta so the
73
+ * whole track follows the mouse live.
74
+ */
75
+ pivotIndex?: number;
76
+ /**
77
+ * True after pointer-up: the edit is committed but kept applied so the bar
78
+ * holds its new position while the markdown re-parses (debounced). Cleared
79
+ * once the regenerated `doc` reflects the edit — avoids a snap-back flash.
80
+ */
81
+ committed?: boolean;
82
+ }
83
+
84
+ function headingLine(block: Block): number | undefined {
85
+ return block.sourceHeading?.position?.start.line;
86
+ }
87
+
88
+ export interface TimelineTrackProps {
89
+ height?: number;
90
+ }
91
+
92
+ export function TimelineTrack({ height = 160 }: TimelineTrackProps) {
93
+ const {
94
+ doc,
95
+ markdownSource,
96
+ setMarkdownSource,
97
+ goToBlockByLine,
98
+ activeBlockStartLine,
99
+ mediaProvider,
100
+ } = useEditorContext();
101
+ const [drag, setDrag] = useState<DragState | null>(null);
102
+ const [pxPerSecond, setPxPerSecond] = useState(DEFAULT_PX_PER_SECOND);
103
+ const scrollRef = useRef<HTMLDivElement>(null);
104
+
105
+ const blocks = useMemo(() => (doc ? flattenBlocks(doc.blocks) : []), [doc]);
106
+
107
+ // Tiny slideshow thumbnail for every block, filling its bar. Resolved once
108
+ // per doc/theme so dragging (which re-renders bar geometry each frame)
109
+ // doesn't re-render the SVGs.
110
+ const previewSettings = usePreviewSettingsOptional();
111
+ const previewTheme = previewSettings?.activeTheme ?? DEFAULT_THEME;
112
+ const visualByBlock = useMemo(() => {
113
+ const map = new Map<string, Block>();
114
+ if (doc) {
115
+ for (const b of blocks) {
116
+ const visual = resolveBlockVisual(doc, b, previewTheme, PREVIEW_VIEWPORT);
117
+ if (visual) map.set(b.id, visual);
118
+ }
119
+ }
120
+ return map;
121
+ }, [doc, blocks, previewTheme]);
122
+ const clips = useMemo<ScheduledClip[]>(() => (doc ? resolveMediaSchedule(doc) : []), [doc]);
123
+ const total = useMemo(() => (doc ? getDocPlaybackDuration(doc) : 0), [doc]);
124
+ const width = Math.max(total * pxPerSecond, 200);
125
+
126
+ // Real-time playback clock for the playhead + media. Starting playback also
127
+ // drops any in-progress edit so the playhead drives.
128
+ const { currentTime, isPlaying, play, pause, seek } = useTimelineClock(total);
129
+ const startPlay = useCallback(() => {
130
+ setDrag(null);
131
+ play();
132
+ }, [play]);
133
+
134
+ // Scrubbing the playhead: drag the red bar to seek. Pauses playback while
135
+ // dragging; seeks continuously from the pointer position.
136
+ const [scrubbing, setScrubbing] = useState(false);
137
+ useEffect(() => {
138
+ if (!scrubbing) return;
139
+ const onMove = (e: PointerEvent) => {
140
+ const scroll = scrollRef.current;
141
+ if (!scroll) return;
142
+ const rect = scroll.getBoundingClientRect();
143
+ const x = e.clientX - rect.left + scroll.scrollLeft;
144
+ seek(x / pxPerSecond);
145
+ };
146
+ const onUp = () => setScrubbing(false);
147
+ window.addEventListener('pointermove', onMove);
148
+ window.addEventListener('pointerup', onUp);
149
+ return () => {
150
+ window.removeEventListener('pointermove', onMove);
151
+ window.removeEventListener('pointerup', onUp);
152
+ };
153
+ }, [scrubbing, pxPerSecond, seek]);
154
+
155
+ // Raw clip lookup (keeps clipStart/clipEnd/spillover that the schedule drops)
156
+ // so a clip can be rebuilt verbatim when relocated to another block.
157
+ const rawClipById = useMemo(() => {
158
+ const map = new Map<string, MediaClip>();
159
+ if (doc) {
160
+ for (const b of flattenBlocks(doc.blocks)) for (const m of b.media ?? []) map.set(m.id, m);
161
+ for (const m of doc.documentMedia ?? []) map.set(m.id, m);
162
+ }
163
+ return map;
164
+ }, [doc]);
165
+
166
+ // The heading-bearing block whose [startTime, startTime+duration) contains
167
+ // `time`, clamped to the first/last such block. Used to retarget a dragged
168
+ // clip to whichever block it lands in.
169
+ const blockAtTime = useCallback(
170
+ (time: number): Block | null => {
171
+ const withHeadings = blocks.filter((b) => headingLine(b) != null);
172
+ if (withHeadings.length === 0) return null;
173
+ let found = withHeadings[0];
174
+ for (const b of withHeadings) {
175
+ if (time >= b.startTime) found = b;
176
+ }
177
+ return found;
178
+ },
179
+ [blocks],
180
+ );
181
+
182
+ // While playing, follow the playhead: when it crosses into a new block,
183
+ // select that block so the card editor + bar highlight track playback. Guarded
184
+ // by a ref so we only fire on block boundaries, not every animation frame.
185
+ const followedBlockRef = useRef<string | null>(null);
186
+ useEffect(() => {
187
+ if (!isPlaying) {
188
+ followedBlockRef.current = null;
189
+ return;
190
+ }
191
+ const block = blockAtTime(currentTime);
192
+ if (!block || block.id === followedBlockRef.current) return;
193
+ followedBlockRef.current = block.id;
194
+ const line = headingLine(block);
195
+ if (line != null) goToBlockByLine(line);
196
+ }, [isPlaying, currentTime, blockAtTime, goToBlockByLine]);
197
+
198
+ // Auto-scroll so the playhead stays visible while playing.
199
+ useEffect(() => {
200
+ if (!isPlaying) return;
201
+ const scroll = scrollRef.current;
202
+ if (!scroll) return;
203
+ const x = currentTime * pxPerSecond;
204
+ const left = scroll.scrollLeft;
205
+ const right = left + scroll.clientWidth;
206
+ if (x < left || x > right - 80) {
207
+ scroll.scrollLeft = Math.max(0, x - scroll.clientWidth / 2);
208
+ }
209
+ }, [isPlaying, currentTime, pxPerSecond]);
210
+
211
+ // Move a clip's start to an absolute timeline position. If the new start
212
+ // lands in a different block, the clip's annotation relocates to that block
213
+ // (rebuilt from `spec`); within the same block it's a minimal `startAt` edit.
214
+ // `extraPatch` carries non-position edits (e.g. clipEnd) for the same-block case.
215
+ const moveClipToTime = useCallback(
216
+ (
217
+ sourceLine: number | undefined,
218
+ currentBlockId: string | undefined,
219
+ spec: ClipSpec,
220
+ newAbsStart: number,
221
+ extraPatch?: { clipEnd?: number },
222
+ ) => {
223
+ if (sourceLine == null) return;
224
+ const target = blockAtTime(newAbsStart);
225
+ const targetLine = target ? headingLine(target) : undefined;
226
+ if (target == null || targetLine == null) return;
227
+ const startAt = Math.max(0, newAbsStart - target.startTime);
228
+ if (currentBlockId === target.id) {
229
+ // Same block → in-place edit, preserving any extra params on the line.
230
+ const next = setMediaClipInSource(markdownSource, sourceLine, { startAt, ...extraPatch });
231
+ if (next) setMarkdownSource(next);
232
+ return;
233
+ }
234
+ const next = placeClipInBlock(
235
+ markdownSource,
236
+ sourceLine,
237
+ targetLine,
238
+ extraPatch?.clipEnd != null ? { ...spec, clipEnd: extraPatch.clipEnd } : spec,
239
+ startAt,
240
+ );
241
+ if (next) setMarkdownSource(next);
242
+ },
243
+ [blockAtTime, markdownSource, setMarkdownSource],
244
+ );
245
+
246
+ // Convert a body-embedded media tag into a timed clip annotation at
247
+ // `newAbsStart` (relocating to the landing block). Always writes an
248
+ // annotation, since the embed isn't one yet.
249
+ const placeEmbeddedClip = useCallback(
250
+ (sourceLine: number | undefined, spec: ClipSpec, newAbsStart: number) => {
251
+ if (sourceLine == null) return;
252
+ const target = blockAtTime(newAbsStart);
253
+ const targetLine = target ? headingLine(target) : undefined;
254
+ if (target == null || targetLine == null) return;
255
+ const startAt = Math.max(0, newAbsStart - target.startTime);
256
+ const next = placeClipInBlock(markdownSource, sourceLine, targetLine, spec, startAt);
257
+ if (next) setMarkdownSource(next);
258
+ },
259
+ [blockAtTime, markdownSource, setMarkdownSource],
260
+ );
261
+
262
+ const zoomIn = useCallback(() => setPxPerSecond((s) => Math.min(ZOOM_MAX, s * ZOOM_FACTOR)), []);
263
+ const zoomOut = useCallback(() => setPxPerSecond((s) => Math.max(ZOOM_MIN, s / ZOOM_FACTOR)), []);
264
+
265
+ // Track the visible width so the ruler can draw ticks across the whole
266
+ // viewport, not just up to where the content ends.
267
+ const [viewportWidth, setViewportWidth] = useState(0);
268
+ useEffect(() => {
269
+ const el = scrollRef.current;
270
+ if (!el || typeof ResizeObserver === 'undefined') return;
271
+ const update = () => setViewportWidth(el.clientWidth);
272
+ update();
273
+ const ro = new ResizeObserver(update);
274
+ ro.observe(el);
275
+ return () => ro.disconnect();
276
+ }, []);
277
+
278
+ // Live drag handling on the window so the pointer can leave the bar. The
279
+ // current scale is read from a ref so the handler doesn't re-bind on zoom.
280
+ const scaleRef = useRef(pxPerSecond);
281
+ scaleRef.current = pxPerSecond;
282
+ const dragRef = useRef<DragState | null>(null);
283
+ dragRef.current = drag;
284
+ const isDragging = drag != null && !drag.committed;
285
+ useEffect(() => {
286
+ if (!isDragging) return;
287
+ const onMove = (e: PointerEvent) => {
288
+ const d = dragRef.current;
289
+ if (!d) return;
290
+ const deltaSec = (e.clientX - d.startX) / scaleRef.current;
291
+ setDrag({ ...d, preview: Math.max(d.floor, d.previewBase + deltaSec) });
292
+ };
293
+ const onUp = () => {
294
+ const d = dragRef.current;
295
+ if (!d) return;
296
+ d.commit(d.preview);
297
+ // Keep the preview applied (committed) until the regenerated doc reflects
298
+ // the edit, so the bar doesn't snap back to the old layout for a frame.
299
+ setDrag({ ...d, committed: true });
300
+ // Fallback: if the edit produced identical markdown (no re-parse), drop
301
+ // the committed preview anyway so it can't get stuck.
302
+ window.setTimeout(() => {
303
+ if (dragRef.current?.committed) setDrag(null);
304
+ }, 500);
305
+ };
306
+ window.addEventListener('pointermove', onMove);
307
+ window.addEventListener('pointerup', onUp);
308
+ return () => {
309
+ window.removeEventListener('pointermove', onMove);
310
+ window.removeEventListener('pointerup', onUp);
311
+ };
312
+ }, [isDragging]);
313
+
314
+ // Drop the committed preview once the doc re-parses with the new value.
315
+ useEffect(() => {
316
+ if (dragRef.current?.committed) setDrag(null);
317
+ }, [doc]);
318
+
319
+ const beginDrag = useCallback(
320
+ (
321
+ e: React.PointerEvent,
322
+ kind: DragKind,
323
+ targetId: string,
324
+ base: number,
325
+ commit: (seconds: number) => void,
326
+ opts?: { pivotIndex?: number; floor?: number },
327
+ ) => {
328
+ e.preventDefault();
329
+ e.stopPropagation();
330
+ // Position drags (moving a clip) floor at 0; length drags floor at MIN_DURATION.
331
+ const floor =
332
+ opts?.floor ?? (kind === 'clip-move' || kind === 'embed-move' ? 0 : MIN_DURATION);
333
+ setDrag({
334
+ kind,
335
+ startX: e.clientX,
336
+ floor,
337
+ preview: base,
338
+ previewBase: base,
339
+ commit,
340
+ targetId,
341
+ pivotIndex: opts?.pivotIndex,
342
+ });
343
+ },
344
+ [],
345
+ );
346
+
347
+ if (!doc) return null;
348
+
349
+ // Live layout while a block edge is dragged: the pivot block previews at the
350
+ // new duration and every block after it shifts by the delta, so the track
351
+ // re-lays-out under the mouse instead of snapping on release.
352
+ const blockDrag =
353
+ drag && (drag.kind === 'block-right' || drag.kind === 'block-left') ? drag : null;
354
+ const pivot = blockDrag?.pivotIndex ?? -1;
355
+ const blockDelta = blockDrag ? blockDrag.preview - blockDrag.previewBase : 0;
356
+ const previewLeft = (index: number) =>
357
+ (blocks[index].startTime + (index > pivot ? blockDelta : 0)) * pxPerSecond;
358
+ const previewWidth = (index: number) =>
359
+ Math.max((index === pivot ? blockDrag!.preview : blocks[index].duration) * pxPerSecond, 2);
360
+ const clipShift = (clip: ScheduledClip) => {
361
+ if (!blockDrag || clip.anchor === 'document' || !clip.blockId) return 0;
362
+ const owning = blocks.findIndex((b) => b.id === clip.blockId);
363
+ return owning > pivot ? blockDelta : 0;
364
+ };
365
+
366
+ // Ruler ticks: the smallest interval that keeps labels at least TICK_MIN_PX
367
+ // apart at the current zoom.
368
+ const tickSeconds =
369
+ TICK_STEPS.find((s) => s * pxPerSecond >= TICK_MIN_PX) ?? TICK_STEPS[TICK_STEPS.length - 1];
370
+ // Fill ticks across the whole visible track, continuing past the content end.
371
+ const rulerEnd = Math.max(total, viewportWidth / pxPerSecond);
372
+ const ticks: number[] = [];
373
+ for (let t = 0; t <= rulerEnd + 0.001 && ticks.length < 1000; t += tickSeconds) ticks.push(t);
374
+
375
+ return (
376
+ <div className="squisq-timeline" style={{ height }} data-testid="timeline-track">
377
+ <div className="squisq-timeline-controls">
378
+ <button
379
+ type="button"
380
+ className="squisq-timeline-zoom-button squisq-timeline-play-button"
381
+ onClick={isPlaying ? pause : startPlay}
382
+ aria-label={isPlaying ? 'Pause' : 'Play'}
383
+ data-tooltip={isPlaying ? 'Pause' : 'Play'}
384
+ data-testid="timeline-play"
385
+ >
386
+ {isPlaying ? '❚❚' : '▶'}
387
+ </button>
388
+ <span className="squisq-timeline-time" data-testid="timeline-time">
389
+ {formatClock(currentTime)} / {formatClock(total)}
390
+ </span>
391
+ <button
392
+ type="button"
393
+ className="squisq-timeline-zoom-button"
394
+ onClick={zoomOut}
395
+ disabled={pxPerSecond <= ZOOM_MIN}
396
+ aria-label="Zoom out"
397
+ data-tooltip="Zoom out"
398
+ >
399
+
400
+ </button>
401
+ <button
402
+ type="button"
403
+ className="squisq-timeline-zoom-button"
404
+ onClick={zoomIn}
405
+ disabled={pxPerSecond >= ZOOM_MAX}
406
+ aria-label="Zoom in"
407
+ data-tooltip="Zoom in"
408
+ >
409
+ +
410
+ </button>
411
+ </div>
412
+ <div className="squisq-timeline-scroll" ref={scrollRef}>
413
+ <div className="squisq-timeline-inner" style={{ width }}>
414
+ <div className="squisq-timeline-row squisq-timeline-row--blocks">
415
+ {blocks.map((b, i) => {
416
+ const line = headingLine(b);
417
+ const isActive = line != null && line === activeBlockStartLine;
418
+ const left = previewLeft(i);
419
+ const barWidth = previewWidth(i);
420
+ const prev = i > 0 ? blocks[i - 1] : null;
421
+ return (
422
+ <div
423
+ key={b.id}
424
+ className={`squisq-timeline-block${isActive ? ' squisq-timeline-block--active' : ''}`}
425
+ style={{ left, width: barWidth }}
426
+ title={`${b.title ?? b.id} — ${formatDur(b.duration)}`}
427
+ onClick={() => {
428
+ seek(b.startTime);
429
+ if (line != null) goToBlockByLine(line);
430
+ }}
431
+ >
432
+ {visualByBlock.has(b.id) && (
433
+ <div className="squisq-timeline-block-thumb" aria-hidden>
434
+ <BlockThumbnail
435
+ visual={visualByBlock.get(b.id)!}
436
+ viewport={PREVIEW_VIEWPORT}
437
+ mediaProvider={mediaProvider}
438
+ />
439
+ </div>
440
+ )}
441
+ {prev && headingLine(prev) != null && (
442
+ <span
443
+ className="squisq-timeline-edge squisq-timeline-edge--left"
444
+ onPointerDown={(e) =>
445
+ beginDrag(
446
+ e,
447
+ 'block-left',
448
+ b.id,
449
+ prev.duration,
450
+ (sec) => {
451
+ // Moving the boundary changes the previous block's duration.
452
+ const next = setBlockDurationInSource(
453
+ markdownSource,
454
+ headingLine(prev)!,
455
+ sec,
456
+ );
457
+ if (next) setMarkdownSource(next);
458
+ },
459
+ { pivotIndex: i - 1 },
460
+ )
461
+ }
462
+ />
463
+ )}
464
+ <span className="squisq-timeline-block-label">{b.title ?? b.id}</span>
465
+ {line != null && (
466
+ <span
467
+ className="squisq-timeline-edge squisq-timeline-edge--right"
468
+ onPointerDown={(e) =>
469
+ beginDrag(
470
+ e,
471
+ 'block-right',
472
+ b.id,
473
+ b.duration,
474
+ (sec) => {
475
+ const next = setBlockDurationInSource(markdownSource, line, sec);
476
+ if (next) setMarkdownSource(next);
477
+ },
478
+ { pivotIndex: i },
479
+ )
480
+ }
481
+ />
482
+ )}
483
+ </div>
484
+ );
485
+ })}
486
+ </div>
487
+
488
+ <div className="squisq-timeline-row squisq-timeline-row--media">
489
+ {clips.map((c) => {
490
+ const length = c.absoluteEnd - c.absoluteStart;
491
+ // Live geometry while dragging: follow a block-edge drag's shift,
492
+ // or the clip's own move/resize (drag.preview is an absolute time).
493
+ let left = (c.absoluteStart + clipShift(c)) * pxPerSecond;
494
+ let clipWidth = Math.max(length * pxPerSecond, 4);
495
+ if (drag?.targetId === c.id && drag.kind === 'clip-move') {
496
+ left = drag.preview * pxPerSecond;
497
+ } else if (drag?.targetId === c.id && drag.kind === 'clip-right') {
498
+ clipWidth = Math.max(drag.preview * pxPerSecond, 4);
499
+ }
500
+ const editable = c.sourceLine != null;
501
+ const specOf = (): ClipSpec => {
502
+ const raw = rawClipById.get(c.id);
503
+ return raw
504
+ ? {
505
+ kind: raw.kind,
506
+ src: raw.src,
507
+ clipStart: raw.clipStart,
508
+ clipEnd: raw.clipEnd,
509
+ spillover: raw.spillover,
510
+ }
511
+ : { kind: c.kind, src: c.src, clipStart: c.sourceIn };
512
+ };
513
+ return (
514
+ <div
515
+ key={c.id}
516
+ className={`squisq-timeline-clip squisq-timeline-clip--${c.kind}${
517
+ c.anchor === 'document' ? ' squisq-timeline-clip--document' : ''
518
+ }`}
519
+ style={{ left, width: clipWidth }}
520
+ title={`${c.src} — ${formatDur(length)}${c.anchor === 'document' ? ' (document)' : ''}`}
521
+ onPointerDown={(e) =>
522
+ editable &&
523
+ beginDrag(e, 'clip-move', c.id, c.absoluteStart, (absStart) => {
524
+ if (c.anchor === 'document') {
525
+ const next = setMediaClipInSource(markdownSource, c.sourceLine!, {
526
+ startAt: absStart,
527
+ });
528
+ if (next) setMarkdownSource(next);
529
+ } else {
530
+ moveClipToTime(c.sourceLine, c.blockId, specOf(), absStart);
531
+ }
532
+ })
533
+ }
534
+ onDoubleClick={() => {
535
+ if (c.sourceLine == null) return;
536
+ // Toggle spillover (block clips only).
537
+ const next = setMediaClipInSource(markdownSource, c.sourceLine, {
538
+ spillover: c.anchor === 'block' ? true : null,
539
+ });
540
+ if (next) setMarkdownSource(next);
541
+ }}
542
+ >
543
+ <span className="squisq-timeline-clip-label">{clipName(c.src)}</span>
544
+ {editable && (
545
+ <span
546
+ className="squisq-timeline-edge squisq-timeline-edge--right"
547
+ onPointerDown={(e) =>
548
+ beginDrag(e, 'clip-right', c.id, length, (len) => {
549
+ const next = setMediaClipInSource(markdownSource, c.sourceLine!, {
550
+ clipEnd: (c.sourceIn ?? 0) + len,
551
+ });
552
+ if (next) setMarkdownSource(next);
553
+ })
554
+ }
555
+ />
556
+ )}
557
+ </div>
558
+ );
559
+ })}
560
+
561
+ {/* Media embedded in a block's body (recordings, dropped files):
562
+ snapped to the parent block. Editing one converts it to a timed
563
+ clip annotation and relocates it to wherever it's dragged. */}
564
+ {blocks.flatMap((b, i) =>
565
+ collectEmbeddedMedia(b).map((m, j) => {
566
+ const id = `embed:${b.id}:${j}`;
567
+ const absStart = b.startTime;
568
+ const length = b.duration;
569
+ let left = previewLeft(i);
570
+ let clipWidth = previewWidth(i);
571
+ if (drag?.targetId === id && drag.kind === 'embed-move') {
572
+ left = drag.preview * pxPerSecond;
573
+ } else if (drag?.targetId === id && drag.kind === 'embed-right') {
574
+ clipWidth = Math.max(drag.preview * pxPerSecond, 4);
575
+ }
576
+ const spec: ClipSpec = { kind: m.kind, src: m.src };
577
+ return (
578
+ <div
579
+ key={id}
580
+ className={`squisq-timeline-clip squisq-timeline-clip--${m.kind} squisq-timeline-clip--embedded`}
581
+ style={{ left, width: clipWidth }}
582
+ title={`${m.src} — drag to time / move between blocks`}
583
+ onPointerDown={(e) =>
584
+ m.sourceLine != null &&
585
+ beginDrag(e, 'embed-move', id, absStart, (newAbsStart) => {
586
+ placeEmbeddedClip(m.sourceLine, { ...spec, clipEnd: length }, newAbsStart);
587
+ })
588
+ }
589
+ >
590
+ <span className="squisq-timeline-clip-label">{clipName(m.src)}</span>
591
+ {m.sourceLine != null && (
592
+ <span
593
+ className="squisq-timeline-edge squisq-timeline-edge--right"
594
+ onPointerDown={(e) =>
595
+ beginDrag(e, 'embed-right', id, length, (len) => {
596
+ placeEmbeddedClip(m.sourceLine, { ...spec, clipEnd: len }, absStart);
597
+ })
598
+ }
599
+ />
600
+ )}
601
+ </div>
602
+ );
603
+ }),
604
+ )}
605
+ </div>
606
+
607
+ <div
608
+ className="squisq-timeline-row squisq-timeline-row--ruler"
609
+ onClick={(e) => {
610
+ const rect = e.currentTarget.getBoundingClientRect();
611
+ seek((e.clientX - rect.left) / pxPerSecond);
612
+ }}
613
+ >
614
+ {ticks.map((t) => (
615
+ <div key={t} className="squisq-timeline-tick" style={{ left: t * pxPerSecond }}>
616
+ <span className="squisq-timeline-tick-label">{formatDur(t)}</span>
617
+ </div>
618
+ ))}
619
+ </div>
620
+
621
+ {/* Playhead — vertical line at the current time, over all rows.
622
+ Drag the bar (or its knob) to scrub. */}
623
+ <div
624
+ className="squisq-timeline-playhead"
625
+ style={{ left: currentTime * pxPerSecond }}
626
+ data-testid="timeline-playhead"
627
+ onPointerDown={(e) => {
628
+ e.preventDefault();
629
+ e.stopPropagation();
630
+ pause();
631
+ setScrubbing(true);
632
+ }}
633
+ >
634
+ <div className="squisq-timeline-playhead-knob" />
635
+ </div>
636
+ </div>
637
+ </div>
638
+
639
+ {/* Off-screen host: plays the timed audio clips in sync with the clock. */}
640
+ <div className="squisq-timeline-media-host" aria-hidden>
641
+ <MediaContext.Provider value={mediaProvider ?? null}>
642
+ <MediaClipLayer
643
+ schedule={clips}
644
+ currentTime={currentTime}
645
+ isPlaying={isPlaying}
646
+ basePath="/"
647
+ />
648
+ </MediaContext.Provider>
649
+ </div>
650
+ </div>
651
+ );
652
+ }
653
+
654
+ function formatClock(seconds: number): string {
655
+ const s = Math.max(0, Math.floor(seconds));
656
+ const m = Math.floor(s / 60);
657
+ return `${m}:${String(s % 60).padStart(2, '0')}`;
658
+ }
659
+
660
+ function formatDur(seconds: number): string {
661
+ const s = Math.round(seconds * 10) / 10;
662
+ if (s < 60) return `${s}s`;
663
+ const m = Math.floor(s / 60);
664
+ const rem = Math.round(s - m * 60);
665
+ return `${m}:${String(rem).padStart(2, '0')}`;
666
+ }
667
+
668
+ function clipName(src: string): string {
669
+ const base = src.split('/').pop() ?? src;
670
+ return base;
671
+ }