@nodetool-ai/timeline 0.8.13 → 0.8.14

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 (45) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/animation/custom.d.ts.map +1 -1
  3. package/dist/animation/custom.js +7 -9
  4. package/dist/animation/custom.js.map +1 -1
  5. package/dist/automation.d.ts.map +1 -1
  6. package/dist/automation.js +7 -3
  7. package/dist/automation.js.map +1 -1
  8. package/dist/keyframes.d.ts +21 -2
  9. package/dist/keyframes.d.ts.map +1 -1
  10. package/dist/keyframes.js +72 -12
  11. package/dist/keyframes.js.map +1 -1
  12. package/dist/ops/apply.d.ts.map +1 -1
  13. package/dist/ops/apply.js +132 -0
  14. package/dist/ops/apply.js.map +1 -1
  15. package/dist/ops/op.d.ts +3 -2
  16. package/dist/ops/op.d.ts.map +1 -1
  17. package/dist/ops/op.js +4 -0
  18. package/dist/ops/op.js.map +1 -1
  19. package/dist/ops/parse.d.ts.map +1 -1
  20. package/dist/ops/parse.js +16 -0
  21. package/dist/ops/parse.js.map +1 -1
  22. package/dist/paramCurves.d.ts +16 -3
  23. package/dist/paramCurves.d.ts.map +1 -1
  24. package/dist/paramCurves.js +104 -4
  25. package/dist/paramCurves.js.map +1 -1
  26. package/dist/render/sceneModel.d.ts.map +1 -1
  27. package/dist/render/sceneModel.js +13 -0
  28. package/dist/render/sceneModel.js.map +1 -1
  29. package/dist/takes.d.ts.map +1 -1
  30. package/dist/takes.js +39 -20
  31. package/dist/takes.js.map +1 -1
  32. package/dist/testing/ops.d.ts.map +1 -1
  33. package/dist/testing/ops.js +20 -0
  34. package/dist/testing/ops.js.map +1 -1
  35. package/dist/transcriptOps.d.ts +267 -0
  36. package/dist/transcriptOps.d.ts.map +1 -0
  37. package/dist/transcriptOps.js +754 -0
  38. package/dist/transcriptOps.js.map +1 -0
  39. package/dist/trimClip.d.ts.map +1 -1
  40. package/dist/trimClip.js +12 -6
  41. package/dist/trimClip.js.map +1 -1
  42. package/dist/types.d.ts +5 -0
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js.map +1 -1
  45. package/package.json +11 -5
@@ -0,0 +1,754 @@
1
+ /**
2
+ * transcriptOps — the clip↔text projection and the pure edits behind it.
3
+ *
4
+ * Descript's core trick is that the transcript is an editable *index* over the
5
+ * media, not a separate document. Here that means the timeline's **clips are
6
+ * the single source of truth** and the transcript is *projected* from the
7
+ * word-level captions the clips carry. `buildTranscriptDoc` walks the
8
+ * transcript-bearing clips in timeline order and emits word tokens with
9
+ * absolute timings; every text operation maps back to a clip cut / move /
10
+ * relabel and commits through `TimelineStore.setTranscriptAndClips` so one user
11
+ * action lands as one coherent edit (and one undo entry).
12
+ *
13
+ * Word timings are clip-local (relative to `clip.startMs`), so splitting,
14
+ * moving, or re-flowing a clip never rewrites the words — they travel with the
15
+ * clip and stay valid against its new position.
16
+ *
17
+ * Nothing here touches the DOM, the network, or any store — it is trivially
18
+ * unit-testable, mirroring `sceneModel`.
19
+ */
20
+ import { createTimeOrderedUuid, makeClip } from "./defaults.js";
21
+ import { isGroupClip } from "./group.js";
22
+ import { sourceRate } from "./sourceRate.js";
23
+ import { splitClip } from "./splitClip.js";
24
+ /** Beat length used before a line's voiceover has been generated/probed. */
25
+ export const PLACEHOLDER_BEAT_MS = 3000;
26
+ // ── Clip classification ──────────────────────────────────────────────────────
27
+ /** The clip is a generated voiceover beat (TTS), voiced or still a draft. */
28
+ export function isVoiceoverBeat(clip) {
29
+ return clip.bindingKind === "text-to-audio";
30
+ }
31
+ /** The clip carries transcribed words. */
32
+ export function hasWords(clip) {
33
+ return (clip.caption?.words?.length ?? 0) > 0;
34
+ }
35
+ /**
36
+ * A clip belongs to the transcript when it carries a caption (words, or an
37
+ * imported clip awaiting transcription) or is a voiceover beat awaiting
38
+ * generation. Plain media with no caption (background music, B-roll dragged
39
+ * straight onto a track) is excluded.
40
+ */
41
+ export function isTranscriptClip(clip) {
42
+ return clip.caption !== undefined || isVoiceoverBeat(clip);
43
+ }
44
+ // ── Projection ───────────────────────────────────────────────────────────────
45
+ /**
46
+ * Non-lexical disfluencies that filler-word removal targets by default. Kept
47
+ * conservative (clear non-words only) so removal never eats meaningful speech;
48
+ * context-dependent fillers like "like" / "so" / "you know" are deliberately
49
+ * excluded.
50
+ */
51
+ const FILLER_WORDS = new Set([
52
+ "um",
53
+ "umm",
54
+ "uh",
55
+ "uhh",
56
+ "uhm",
57
+ "erm",
58
+ "er",
59
+ "eh",
60
+ "ah",
61
+ "hmm",
62
+ "mhm",
63
+ "mm",
64
+ "uh-huh",
65
+ "mm-hmm"
66
+ ]);
67
+ /** Normalize a token for filler matching: lowercase, trim trailing punctuation. */
68
+ function normalizeToken(text) {
69
+ return text.toLowerCase().replace(/[.,!?;:]+$/, "").trim();
70
+ }
71
+ /** Whether a word reads as a filler ("um", "uh", …). */
72
+ export function isFillerWord(text) {
73
+ return FILLER_WORDS.has(normalizeToken(text));
74
+ }
75
+ /** A word's effective kind: its explicit kind, else filler-or-word by lexicon. */
76
+ function normalizeKind(word) {
77
+ return word.kind ?? (isFillerWord(word.word) ? "filler" : "word");
78
+ }
79
+ /** Order transcript clips by timeline position, with a stable id tie-break. */
80
+ function byTimeline(a, b) {
81
+ return a.startMs - b.startMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
82
+ }
83
+ /** The paragraph a clip belongs to — its `paragraphId`, or itself when unset. */
84
+ function paragraphKey(clip) {
85
+ return clip.paragraphId ?? clip.id;
86
+ }
87
+ /** End of the last clip of any kind — the transcript's covered length. */
88
+ function maxEnd(clips) {
89
+ return clips.reduce((max, c) => Math.max(max, c.startMs + c.durationMs), 0);
90
+ }
91
+ function buildSegment(id, members) {
92
+ const tokens = [];
93
+ for (const clip of members) {
94
+ const offset = clip.startMs;
95
+ (clip.caption?.words ?? []).forEach((word, wordIndex) => {
96
+ tokens.push({
97
+ clipId: clip.id,
98
+ wordIndex,
99
+ text: word.word,
100
+ startMs: offset + word.startMs,
101
+ endMs: offset + word.endMs,
102
+ kind: normalizeKind(word),
103
+ confidence: word.confidence
104
+ });
105
+ });
106
+ }
107
+ const first = members[0];
108
+ const last = members[members.length - 1];
109
+ // A draft is an un-voiced authored beat; an imported clip awaiting
110
+ // transcription is not a draft (it has no prompt to edit).
111
+ const isDraft = members.length === 1 &&
112
+ tokens.length === 0 &&
113
+ first.sourceType !== "imported";
114
+ return {
115
+ id,
116
+ clipIds: members.map((c) => c.id),
117
+ kind: first.sourceType === "imported" ? "imported" : "generated",
118
+ speaker: first.speaker,
119
+ startMs: first.startMs,
120
+ endMs: last.startMs + last.durationMs,
121
+ isDraft,
122
+ draftText: isDraft ? (first.prompt ?? "") : "",
123
+ status: members.some((c) => c.status === "failed") ? "failed" : first.status,
124
+ tokens
125
+ };
126
+ }
127
+ /**
128
+ * `buildTranscriptDoc` runs per store publish from three consumers
129
+ * (`ScriptLane`, `TranscriptPanel`, `TranscriptEditor`'s `SyncPlugin`) and its
130
+ * own recursive callers (`fillerRanges`, `reconcileTranscript`). Clips arrays
131
+ * are never mutated in place (every mutation in this module and in
132
+ * `TimelineStore` replaces the array), so the same array reference always
133
+ * projects to the same doc — safe to memoize by identity. A `WeakMap` lets
134
+ * both the array and its cached doc be collected together once the array is
135
+ * no longer referenced.
136
+ */
137
+ const transcriptDocCache = new WeakMap();
138
+ /**
139
+ * Project the editable transcript from the timeline's clips. Consecutive clips
140
+ * sharing a `paragraphId` collapse into one paragraph (segment); each word
141
+ * becomes an absolute-timed token tagged with its source clip. The result is
142
+ * the read model the editor renders and the map a click-to-seek / select /
143
+ * delete uses to translate text positions back to the timeline.
144
+ */
145
+ export function buildTranscriptDoc(clips) {
146
+ const cached = transcriptDocCache.get(clips);
147
+ if (cached)
148
+ return cached;
149
+ const sorted = clips.filter(isTranscriptClip).sort(byTimeline);
150
+ const segments = [];
151
+ // A paragraphId can recur in more than one non-contiguous group (a clip
152
+ // with a different paragraphId lands between two pieces of the same
153
+ // paragraph) — track how many groups each key has produced so far and
154
+ // disambiguate every group after the first, keeping ids unique doc-wide.
155
+ const occurrences = new Map();
156
+ let i = 0;
157
+ while (i < sorted.length) {
158
+ const key = paragraphKey(sorted[i]);
159
+ const members = [];
160
+ while (i < sorted.length && paragraphKey(sorted[i]) === key) {
161
+ members.push(sorted[i]);
162
+ i += 1;
163
+ }
164
+ const occurrence = occurrences.get(key) ?? 0;
165
+ occurrences.set(key, occurrence + 1);
166
+ const id = occurrence === 0 ? key : `${key}#${occurrence}`;
167
+ segments.push(buildSegment(id, members));
168
+ }
169
+ const doc = { segments, durationMs: maxEnd(sorted) };
170
+ transcriptDocCache.set(clips, doc);
171
+ return doc;
172
+ }
173
+ // ── Layout ───────────────────────────────────────────────────────────────────
174
+ function beatLength(clip) {
175
+ return clip.durationMs > 0 ? clip.durationMs : PLACEHOLDER_BEAT_MS;
176
+ }
177
+ /** Length a transcript clip takes in the layout: a beat's placeholder until voiced. */
178
+ function layoutLength(clip) {
179
+ return isVoiceoverBeat(clip) ? beatLength(clip) : clip.durationMs;
180
+ }
181
+ /** End of the last transcript clip — where the next paragraph is appended. */
182
+ export function transcriptEndMs(clips) {
183
+ return maxEnd(clips.filter(isTranscriptClip));
184
+ }
185
+ /**
186
+ * The audio track a new voiceover paragraph lands on: the track already
187
+ * carrying the voiceover (its last transcript audio clip), else an audio track
188
+ * named "Voiceover", else the first audio track. A linked cut puts its shot
189
+ * audio on the first audio track, so "first audio track" alone would drop a
190
+ * recording or a new line among the shots' sound.
191
+ */
192
+ export function voiceoverTrackId(clips, tracks) {
193
+ const audioTracks = tracks.filter((t) => t.type === "audio");
194
+ const audioIds = new Set(audioTracks.map((t) => t.id));
195
+ const voiced = clips
196
+ .filter((c) => isTranscriptClip(c) && audioIds.has(c.trackId))
197
+ .sort(byTimeline);
198
+ // Without a voiceover, only an empty audio track will do: a new beat on the
199
+ // music track would sit on top of the music.
200
+ const used = new Set(clips.map((c) => c.trackId));
201
+ return (voiced[voiced.length - 1]?.trackId ??
202
+ audioTracks.find((t) => t.name === "Voiceover")?.id ??
203
+ audioTracks.find((t) => !used.has(t.id))?.id);
204
+ }
205
+ /**
206
+ * Re-lay the transcript after a beat changed length or the paragraphs were
207
+ * reordered. Transcript clips (voiceover beats and imported recordings with
208
+ * captions) form one sequence in timeline order, or in `orderedClipIds` order
209
+ * when given. Each clip keeps the offset it has from the end of the clip
210
+ * before it, so pauses, a recording placed between two beats, and lines parked
211
+ * inside their shots all stay where they are; when a clip grows or shrinks,
212
+ * everything after it moves by the difference. A draft beat with no length
213
+ * takes `PLACEHOLDER_BEAT_MS`. Words are clip-local so they need no rewrite.
214
+ * Clips outside the transcript (B-roll, music, shots) keep their positions.
215
+ *
216
+ * `previousDurations` gives the length a clip had when the current offsets
217
+ * were laid out, for a caller that already wrote the new length (voicing
218
+ * probes the real duration before it re-lays the beats).
219
+ *
220
+ * `durationMs` is the end of the last clip of *any* kind, so imported media
221
+ * extending past the voiceover still counts toward the sequence length.
222
+ */
223
+ export function reflowGenerated(clips, orderedClipIds, previousDurations) {
224
+ const timeOrder = clips.filter(isTranscriptClip).sort(byTimeline);
225
+ const offsets = new Map();
226
+ let previousEnd = 0;
227
+ for (const clip of timeOrder) {
228
+ offsets.set(clip.id, clip.startMs - previousEnd);
229
+ previousEnd =
230
+ clip.startMs + (previousDurations?.get(clip.id) ?? clip.durationMs);
231
+ }
232
+ let ordered;
233
+ if (orderedClipIds) {
234
+ const byId = new Map(timeOrder.map((c) => [c.id, c]));
235
+ ordered = orderedClipIds
236
+ .map((id) => byId.get(id))
237
+ .filter((c) => c !== undefined);
238
+ const orderedSet = new Set(orderedClipIds);
239
+ for (const clip of timeOrder) {
240
+ if (!orderedSet.has(clip.id))
241
+ ordered.push(clip);
242
+ }
243
+ }
244
+ else {
245
+ ordered = timeOrder;
246
+ }
247
+ const patched = new Map();
248
+ let cursor = 0;
249
+ let lastStart = 0;
250
+ for (const clip of ordered) {
251
+ const startMs = Math.max(0, lastStart, cursor + (offsets.get(clip.id) ?? 0));
252
+ const durationMs = layoutLength(clip);
253
+ if (clip.startMs !== startMs || clip.durationMs !== durationMs) {
254
+ patched.set(clip.id, { ...clip, startMs, durationMs });
255
+ }
256
+ lastStart = startMs;
257
+ cursor = startMs + durationMs;
258
+ }
259
+ const nextClips = patched.size
260
+ ? clips.map((c) => patched.get(c.id) ?? c)
261
+ : clips;
262
+ return { clips: nextClips, durationMs: maxEnd(nextClips) };
263
+ }
264
+ /**
265
+ * Resolve a word selection (two endpoints, in any order) against a projected
266
+ * document to the absolute time span it covers and the tokens within it.
267
+ * Returns null when either endpoint is no longer present (e.g. after an edit).
268
+ */
269
+ export function resolveSelectionRange(doc, anchor, focus) {
270
+ const flat = doc.segments.flatMap((s) => s.tokens);
271
+ const findIndex = (ref) => flat.findIndex((t) => t.clipId === ref.clipId && t.wordIndex === ref.wordIndex);
272
+ const a = findIndex(anchor);
273
+ const b = findIndex(focus);
274
+ if (a === -1 || b === -1)
275
+ return null;
276
+ const [lo, hi] = a <= b ? [a, b] : [b, a];
277
+ const tokens = flat.slice(lo, hi + 1);
278
+ return {
279
+ startMs: tokens[0].startMs,
280
+ endMs: tokens[tokens.length - 1].endMs,
281
+ tokens
282
+ };
283
+ }
284
+ /**
285
+ * Whether [startMs, endMs) covers any word of a locked clip. A transcript
286
+ * deletion over such a word is refused outright: cutting around the locked
287
+ * clip would still ripple every other track while the word stays put.
288
+ */
289
+ function overlapsLockedWords(clips, startMs, endMs, locks) {
290
+ const locked = locks.lockedClipIds;
291
+ if (!locked || locked.size === 0)
292
+ return false;
293
+ return clips.some((clip) => locked.has(clip.id) &&
294
+ (clip.caption?.words ?? []).some((w) => clip.startMs + w.startMs < endMs && clip.startMs + w.endMs > startMs));
295
+ }
296
+ /** Whether `clip` can be cut by `splitClip` (a time remap refuses a cut). */
297
+ function isCuttable(clip) {
298
+ return clip.timeRemap === undefined;
299
+ }
300
+ /**
301
+ * The head remnant of `clip`, keeping clip-local [0, lengthMs). Built with
302
+ * `splitClip` so fades, transitions, animations and captions follow the same
303
+ * rules as a timeline cut. The head keeps the original id.
304
+ */
305
+ function headRemnant(clip, lengthMs) {
306
+ const [head] = splitClip(clip, clip.startMs + lengthMs);
307
+ return { ...head, id: clip.id };
308
+ }
309
+ /** The tail remnant of `clip`, keeping clip-local [fromMs, dur), placed at `startMs`. */
310
+ function tailRemnant(clip, fromMs, startMs) {
311
+ const [, tail] = splitClip(clip, clip.startMs + fromMs);
312
+ return { ...tail, startMs };
313
+ }
314
+ /**
315
+ * Relinks the remnants on one side of a cut: one fresh `linkId` per original
316
+ * link group, so the head halves of a linked pair stay linked to each other but
317
+ * not to the tail halves (mirrors the store's link-aware split). Unlinked
318
+ * clips pass through.
319
+ */
320
+ function sideRelinker() {
321
+ const byGroup = new Map();
322
+ return (clip) => {
323
+ if (clip.linkId === undefined)
324
+ return clip;
325
+ let linkId = byGroup.get(clip.linkId);
326
+ if (linkId === undefined) {
327
+ linkId = createTimeOrderedUuid();
328
+ byGroup.set(clip.linkId, linkId);
329
+ }
330
+ return { ...clip, linkId };
331
+ };
332
+ }
333
+ /**
334
+ * Ripple-delete the absolute time span [startMs, endMs) across every track:
335
+ * clips fully inside are dropped, clips overlapping an edge are trimmed (their
336
+ * words partitioned and the tail's rebased), and everything after shifts left
337
+ * by the span length so the gap closes — the "editing text = editing media"
338
+ * core. B-roll on other tracks ripples too, keeping the composition in sync.
339
+ * A track with a locked clip at or after the cut, or a time-remapped clip over
340
+ * it, stays as it is. Groups shrink to what is left of their window.
341
+ */
342
+ export function rippleDeleteRange(clips, startMs, endMs, locks = {}) {
343
+ if (endMs <= startMs || overlapsLockedWords(clips, startMs, endMs, locks)) {
344
+ return { clips, durationMs: maxEnd(clips) };
345
+ }
346
+ const span = endMs - startMs;
347
+ // Where a time before the cut, inside it or after it lands once it is removed.
348
+ const shifted = (t) => t <= startMs ? t : t >= endMs ? t - span : startMs;
349
+ // A track keeps every clip where it is when one of its clips cannot follow
350
+ // the cut: a locked clip at or after it, or a time-remapped clip that
351
+ // overlaps it (splitClip refuses a remap). Shifting the other clips on that
352
+ // track would move them onto the one that stays.
353
+ const heldTracks = new Set();
354
+ for (const clip of clips) {
355
+ const cStart = clip.startMs;
356
+ const cEnd = clip.startMs + clip.durationMs;
357
+ if (cEnd <= startMs)
358
+ continue;
359
+ if (locks.lockedClipIds?.has(clip.id) ||
360
+ (!isCuttable(clip) && cStart < endMs)) {
361
+ heldTracks.add(clip.trackId);
362
+ }
363
+ }
364
+ const next = [];
365
+ const removedGroups = new Map();
366
+ const relinkHead = sideRelinker();
367
+ const relinkTail = sideRelinker();
368
+ for (const clip of clips) {
369
+ const cStart = clip.startMs;
370
+ const cEnd = clip.startMs + clip.durationMs;
371
+ if (cEnd <= startMs || heldTracks.has(clip.trackId)) {
372
+ next.push(clip); // entirely before the cut, or on a held track: never cut or moved
373
+ continue;
374
+ }
375
+ if (cStart >= endMs) {
376
+ next.push({ ...clip, startMs: cStart - span }); // entirely after → ripple
377
+ continue;
378
+ }
379
+ if (isGroupClip(clip)) {
380
+ // A group is a transform parent, not media: it spans what is left of
381
+ // its window. A group inside the cut goes, and its children move to its
382
+ // parent.
383
+ const from = shifted(cStart);
384
+ const to = shifted(cEnd);
385
+ if (to > from) {
386
+ next.push({ ...clip, startMs: from, durationMs: to - from });
387
+ }
388
+ else {
389
+ removedGroups.set(clip.id, clip.parentId);
390
+ }
391
+ continue;
392
+ }
393
+ // Overlaps the cut: keep the head before it and the tail after it.
394
+ const headLen = Math.max(0, startMs - cStart);
395
+ const tailFromLocal = Math.min(clip.durationMs, endMs - cStart);
396
+ if (headLen > 0)
397
+ next.push(relinkHead(headRemnant(clip, headLen)));
398
+ if (clip.durationMs - tailFromLocal > 0) {
399
+ next.push(relinkTail(tailRemnant(clip, tailFromLocal, startMs)));
400
+ }
401
+ // Neither remnant → the clip was fully covered and is dropped.
402
+ }
403
+ const reparented = removedGroups.size === 0
404
+ ? next
405
+ : next.map((clip) => {
406
+ if (clip.parentId === undefined || !removedGroups.has(clip.parentId)) {
407
+ return clip;
408
+ }
409
+ let parent = clip.parentId;
410
+ // Bounded: a parent cycle among removed groups must not loop.
411
+ for (let step = 0; step <= removedGroups.size && parent !== undefined && removedGroups.has(parent); step++) {
412
+ parent = removedGroups.get(parent);
413
+ }
414
+ if (parent !== undefined && removedGroups.has(parent))
415
+ parent = undefined;
416
+ const { parentId: _removed, ...rest } = clip;
417
+ return parent ? { ...rest, parentId: parent } : rest;
418
+ });
419
+ return { clips: reparented, durationMs: maxEnd(reparented) };
420
+ }
421
+ /**
422
+ * Change a single word's text without touching its timing or media — Descript's
423
+ * "correct the transcript without changing the audio": you are fixing the
424
+ * label, not the timestamped media behind it.
425
+ */
426
+ export function relabelWord(clips, clipId, wordIndex, text) {
427
+ const target = clips.find((c) => c.id === clipId);
428
+ // Nothing to relabel (clip gone, no caption, out-of-range index, or the
429
+ // text is already what's stored) → return the same array so the commit is a
430
+ // no-op and avoids a needless full-array allocation + re-render.
431
+ if (!target ||
432
+ !target.caption ||
433
+ wordIndex < 0 ||
434
+ wordIndex >= target.caption.words.length ||
435
+ target.caption.words[wordIndex].word === text) {
436
+ return clips;
437
+ }
438
+ return clips.map((c) => {
439
+ if (c.id !== clipId || !c.caption)
440
+ return c;
441
+ const words = c.caption.words.map((w, i) => i === wordIndex ? { ...w, word: text } : w);
442
+ return { ...c, caption: { ...c.caption, words } };
443
+ });
444
+ }
445
+ /** Absolute time spans of every filler word in the projected transcript. */
446
+ function fillerRanges(clips) {
447
+ return buildTranscriptDoc(clips)
448
+ .segments.flatMap((s) => s.tokens)
449
+ .filter((t) => t.kind === "filler")
450
+ .map((t) => ({ startMs: t.startMs, endMs: t.endMs }));
451
+ }
452
+ /**
453
+ * Ripple-cut every filler word ("um", "uh", …) in one pass. Ranges are removed
454
+ * right-to-left so each deletion leaves the earlier (left) ranges' absolute
455
+ * times valid — the bulk version of {@link rippleDeleteRange}.
456
+ */
457
+ export function removeFillers(clips, locks = {}) {
458
+ const ranges = fillerRanges(clips).sort((a, b) => b.startMs - a.startMs);
459
+ let result = clips;
460
+ let durationMs = maxEnd(clips);
461
+ for (const range of ranges) {
462
+ const out = rippleDeleteRange(result, range.startMs, range.endMs, locks);
463
+ result = out.clips;
464
+ durationMs = out.durationMs;
465
+ }
466
+ return { clips: result, durationMs };
467
+ }
468
+ /** Identity of a word as seeded: its source position, text and timing. */
469
+ function seededTokenKey(tok) {
470
+ return `${tok.clipId}:${tok.wordIndex}:${tok.startMs}-${tok.endMs}:${tok.text}`;
471
+ }
472
+ /** Snapshot the words and drafts an editor seeded from `clips` shows. */
473
+ export function snapshotSeededTranscript(clips) {
474
+ return {
475
+ tokenKeys: new Set(buildTranscriptDoc(clips)
476
+ .segments.flatMap((s) => s.tokens)
477
+ .map(seededTokenKey)),
478
+ draftIds: new Set(clips.filter(isDraftBeat).map((c) => c.id))
479
+ };
480
+ }
481
+ /**
482
+ * Reconcile a freeform edit of the transcript text back onto the clips. Given
483
+ * the words that survived the edit (each still tagged with its source word and
484
+ * carrying its possibly-edited text), this:
485
+ * 1. relabels surviving words whose text changed (label only — no media move,
486
+ * matching Descript's "fix the transcript without changing the audio"),
487
+ * 2. ripple-cuts the words that were deleted from the text (right-to-left so
488
+ * the earlier ranges stay valid as the later ones are removed).
489
+ * New text typed between words is folded into the adjacent word upstream (so it
490
+ * arrives here as a relabel); authoring brand-new audio stays an explicit
491
+ * "add line" → voice action.
492
+ *
493
+ * With `seededTokenKeys`, only words the editor was seeded with are relabeled
494
+ * or cut; words that appeared or changed since seeding are left alone.
495
+ */
496
+ export function reconcileTranscript(clips, survivors, locks = {}, seededTokenKeys) {
497
+ const doc = buildTranscriptDoc(clips);
498
+ const tokens = doc.segments.flatMap((s) => s.tokens);
499
+ const isSeeded = (tok) => !seededTokenKeys || seededTokenKeys.has(seededTokenKey(tok));
500
+ const key = (clipId, wordIndex) => `${clipId}:${wordIndex}`;
501
+ const survivingText = new Map(survivors.map((s) => [key(s.clipId, s.wordIndex), s.text]));
502
+ // 1. Relabels (geometry unchanged, so token times stay valid for step 2).
503
+ let next = clips;
504
+ for (const tok of tokens) {
505
+ const edited = survivingText.get(key(tok.clipId, tok.wordIndex));
506
+ if (edited === undefined || !isSeeded(tok))
507
+ continue;
508
+ const trimmed = edited.trim();
509
+ if (trimmed && trimmed !== tok.text) {
510
+ next = relabelWord(next, tok.clipId, tok.wordIndex, trimmed);
511
+ }
512
+ }
513
+ // 2. Ripple-cut removed words, latest first. Adjacent removed words become
514
+ // one span so the silence between them goes too, instead of surviving as a
515
+ // tiny clip fragment.
516
+ const spans = [];
517
+ let previousRemoved = false;
518
+ for (const tok of tokens) {
519
+ const isRemoved = isSeeded(tok) && !survivingText.has(key(tok.clipId, tok.wordIndex));
520
+ if (isRemoved) {
521
+ const last = spans[spans.length - 1];
522
+ if (previousRemoved && last && last.clipId === tok.clipId) {
523
+ last.startMs = Math.min(last.startMs, tok.startMs);
524
+ last.endMs = Math.max(last.endMs, tok.endMs);
525
+ }
526
+ else {
527
+ spans.push({
528
+ clipId: tok.clipId,
529
+ startMs: tok.startMs,
530
+ endMs: tok.endMs
531
+ });
532
+ }
533
+ }
534
+ previousRemoved = isRemoved;
535
+ }
536
+ const removed = spans.sort((a, b) => b.startMs - a.startMs);
537
+ let durationMs = doc.durationMs;
538
+ for (const range of removed) {
539
+ const out = rippleDeleteRange(next, range.startMs, range.endMs, locks);
540
+ next = out.clips;
541
+ durationMs = out.durationMs;
542
+ }
543
+ return { clips: next, durationMs };
544
+ }
545
+ /** Whether a clip is an un-voiced authored beat (a draft awaiting voicing). */
546
+ function isDraftBeat(clip) {
547
+ return isVoiceoverBeat(clip) && !hasWords(clip);
548
+ }
549
+ /**
550
+ * Close the gaps left by removed draft beats: voiceover beats on the same
551
+ * track that start at or after a removed draft's end shift left by its length.
552
+ * Every other clip, and every gap the edit did not create, stays put.
553
+ */
554
+ function removeDraftBeats(clips, removedIds) {
555
+ const gone = clips
556
+ .filter((c) => removedIds.has(c.id))
557
+ .sort((a, b) => b.startMs - a.startMs);
558
+ let next = clips.filter((c) => !removedIds.has(c.id));
559
+ for (const draft of gone) {
560
+ const end = draft.startMs + draft.durationMs;
561
+ next = next.map((c) => isVoiceoverBeat(c) && c.trackId === draft.trackId && c.startMs >= end
562
+ ? { ...c, startMs: c.startMs - draft.durationMs }
563
+ : c);
564
+ }
565
+ return next;
566
+ }
567
+ /**
568
+ * Apply a whole freeform edit to the clips in one transform: reconcile voiced
569
+ * words (relabel + ripple-cut), update existing draft prompts, drop drafts
570
+ * whose text was deleted (closing only their gaps), and append draft beats for
571
+ * newly-typed lines after the last paragraph. Beats the edit did not add or remove
572
+ * keep their starts and the gaps between them. Returns the same array when
573
+ * nothing changed. With `seeded`, only words and drafts the editor was seeded
574
+ * with can be cut or removed.
575
+ */
576
+ export function applyEditorEdits(clips, edits, audioTrackId, locks = {}, seeded) {
577
+ let next = reconcileTranscript(clips, edits.survivors, locks, seeded?.tokenKeys).clips;
578
+ // Existing drafts: write back the edited prompt.
579
+ const updateById = new Map(edits.draftUpdates.map((d) => [d.clipId, d.text.trim()]));
580
+ const promptChanged = (c) => updateById.has(c.id) && (c.prompt ?? "") !== updateById.get(c.id);
581
+ if (next.some(promptChanged)) {
582
+ next = next.map((c) => promptChanged(c) ? { ...c, prompt: updateById.get(c.id) } : c);
583
+ }
584
+ // Drafts whose text was deleted entirely are removed.
585
+ const kept = new Set(edits.draftUpdates.map((d) => d.clipId));
586
+ const removed = new Set(clips
587
+ .filter(isDraftBeat)
588
+ .map((c) => c.id)
589
+ .filter((id) => !kept.has(id) && (!seeded || seeded.draftIds.has(id))));
590
+ if (removed.size > 0)
591
+ next = removeDraftBeats(next, removed);
592
+ // Newly-typed lines become draft beats to voice.
593
+ for (const text of edits.newDraftTexts) {
594
+ const trimmed = text.trim();
595
+ if (!trimmed)
596
+ continue;
597
+ const id = createTimeOrderedUuid();
598
+ next = [
599
+ ...next,
600
+ makeClip({
601
+ id,
602
+ paragraphId: id,
603
+ name: trimmed.slice(0, 40),
604
+ trackId: audioTrackId,
605
+ startMs: transcriptEndMs(next),
606
+ durationMs: PLACEHOLDER_BEAT_MS,
607
+ mediaType: "audio",
608
+ sourceType: "generated",
609
+ bindingKind: "text-to-audio",
610
+ prompt: trimmed,
611
+ status: "draft"
612
+ })
613
+ ];
614
+ }
615
+ return { clips: next, durationMs: maxEnd(next) };
616
+ }
617
+ /** The middle slice of `clip` (clip-local [loMs, hiMs)), placed at `blockMs`. */
618
+ function midRemnant(clip, loMs, hiMs, blockMs) {
619
+ const rate = sourceRate(clip);
620
+ const inPointMs = clip.inPointMs ?? 0;
621
+ const words = (clip.caption?.words ?? [])
622
+ .filter((w) => w.startMs >= loMs && w.endMs <= hiMs)
623
+ .map((w) => ({ ...w, startMs: w.startMs - loMs, endMs: w.endMs - loMs }));
624
+ return {
625
+ ...clip,
626
+ id: createTimeOrderedUuid(),
627
+ startMs: blockMs,
628
+ durationMs: hiMs - loMs,
629
+ // Both cut points are source-space, `loMs`/`hiMs` timeline-ms in (mirrors
630
+ // splitClip's `cutPointMs`).
631
+ inPointMs: inPointMs + loMs * rate,
632
+ outPointMs: inPointMs + hiMs * rate,
633
+ caption: clip.caption ? { ...clip.caption, words } : undefined
634
+ };
635
+ }
636
+ /**
637
+ * Ripple-delete [startMs, endMs) like {@link rippleDeleteRange}, but also return
638
+ * the removed media as a 0-based block of clips — the "cut" half of a move.
639
+ */
640
+ export function cutWordRange(clips, startMs, endMs, locks = {}) {
641
+ if (endMs <= startMs || overlapsLockedWords(clips, startMs, endMs, locks)) {
642
+ return { clips, durationMs: maxEnd(clips), extracted: [] };
643
+ }
644
+ const extracted = [];
645
+ for (const clip of clips) {
646
+ const cStart = clip.startMs;
647
+ const cEnd = clip.startMs + clip.durationMs;
648
+ const lo = Math.max(cStart, startMs);
649
+ const hi = Math.min(cEnd, endMs);
650
+ if (hi <= lo || locks.lockedClipIds?.has(clip.id) || !isCuttable(clip)) {
651
+ continue;
652
+ }
653
+ extracted.push(midRemnant(clip, lo - cStart, hi - cStart, lo - startMs));
654
+ }
655
+ extracted.sort(byTimeline);
656
+ const removed = rippleDeleteRange(clips, startMs, endMs, locks);
657
+ return { clips: removed.clips, durationMs: removed.durationMs, extracted };
658
+ }
659
+ /**
660
+ * Ripple-insert a 0-based `block` of clips at `targetMs`: clips at or after the
661
+ * target shift right by the block length (splitting any clip straddling it),
662
+ * then the block is placed at the target. The paste half of a move.
663
+ */
664
+ export function pasteClipsAt(clips, targetMs, block, locks = {}) {
665
+ if (block.length === 0)
666
+ return { clips, durationMs: maxEnd(clips) };
667
+ const blockLen = block.reduce((m, c) => Math.max(m, c.startMs + c.durationMs), 0);
668
+ const next = [];
669
+ const relinkHead = sideRelinker();
670
+ const relinkTail = sideRelinker();
671
+ for (const clip of clips) {
672
+ const cStart = clip.startMs;
673
+ const cEnd = clip.startMs + clip.durationMs;
674
+ if (cEnd <= targetMs || locks.lockedClipIds?.has(clip.id)) {
675
+ next.push(clip);
676
+ }
677
+ else if (cStart >= targetMs) {
678
+ next.push({ ...clip, startMs: cStart + blockLen });
679
+ }
680
+ else if (!isCuttable(clip)) {
681
+ next.push(clip);
682
+ }
683
+ else {
684
+ const headLen = targetMs - cStart;
685
+ next.push(relinkHead(headRemnant(clip, headLen)));
686
+ next.push(relinkTail(tailRemnant(clip, headLen, targetMs + blockLen)));
687
+ }
688
+ }
689
+ for (const b of block) {
690
+ next.push({ ...b, id: createTimeOrderedUuid(), startMs: b.startMs + targetMs });
691
+ }
692
+ return { clips: next, durationMs: maxEnd(next) };
693
+ }
694
+ // ── Migration: legacy line/caption-clip model → clip-sourced captions ─────────
695
+ /**
696
+ * One-time, idempotent migration from the legacy transcript model (a
697
+ * `TranscriptLine[]` binding a voiceover audio clip + a separate caption clip)
698
+ * to the clip-sourced model (words carried directly by the voiceover clip).
699
+ *
700
+ * For each line: fold the bound caption clip's words onto the voiceover audio
701
+ * clip and drop the now-redundant caption clip. A line that was typed but never
702
+ * voiced (no audio clip) becomes a draft voiceover beat on `audioTrackId` so
703
+ * its text survives. Run only when `transcript` is non-empty; callers clear the
704
+ * `transcript` field afterwards since clips are now the source of truth.
705
+ */
706
+ export function migrateTranscriptToClips(transcript, clips, audioTrackId) {
707
+ if (transcript.length === 0)
708
+ return clips;
709
+ const byId = new Map(clips.map((c) => [c.id, c]));
710
+ const patched = new Map();
711
+ const removeIds = new Set();
712
+ const created = [];
713
+ for (const line of transcript) {
714
+ const bound = line.clipIds
715
+ .map((id) => byId.get(id))
716
+ .filter((c) => c !== undefined);
717
+ const audio = bound.find((c) => c.mediaType === "audio");
718
+ // Exclude the audio clip itself: if it already carries the caption it
719
+ // must not be treated as the redundant caption clip and removed.
720
+ const caption = bound.find((c) => c !== audio && c.caption !== undefined);
721
+ if (audio) {
722
+ const base = patched.get(audio.id) ?? audio;
723
+ patched.set(audio.id, {
724
+ ...base,
725
+ caption: hasWords(base) ? base.caption : caption?.caption ?? base.caption,
726
+ prompt: base.prompt || line.text,
727
+ paragraphId: base.paragraphId ?? base.id
728
+ });
729
+ if (caption)
730
+ removeIds.add(caption.id);
731
+ }
732
+ else if (line.text.trim()) {
733
+ const id = createTimeOrderedUuid();
734
+ created.push(makeClip({
735
+ id,
736
+ paragraphId: id,
737
+ name: line.text.slice(0, 40).trim() || "Voiceover",
738
+ trackId: audioTrackId,
739
+ startMs: line.beatStartMs,
740
+ durationMs: PLACEHOLDER_BEAT_MS,
741
+ mediaType: "audio",
742
+ sourceType: "generated",
743
+ bindingKind: "text-to-audio",
744
+ prompt: line.text,
745
+ status: "draft"
746
+ }));
747
+ }
748
+ }
749
+ const next = clips
750
+ .filter((c) => !removeIds.has(c.id))
751
+ .map((c) => patched.get(c.id) ?? c);
752
+ return [...next, ...created];
753
+ }
754
+ //# sourceMappingURL=transcriptOps.js.map