fablecut 1.15.0 → 1.17.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.
package/app.js CHANGED
@@ -73,7 +73,7 @@ const DEFAULT_PROPS = {
73
73
  bold: true, italic: false, weight: 0, align: "center",
74
74
  letterSpacing: 0, lineHeight: 1.2, uppercase: false, textShadow: 12,
75
75
  glow: 0, glowColor: "", // neon glow (glowColor defaults to fill)
76
- textAnim: "none", wordRate: 0.15, direction: "auto",
76
+ textAnim: "none", wordRate: 0.15, direction: "auto", highlightColor: "#ffd166",
77
77
  strokeWidth: 0, strokeColor: "#000000", bgColor: "#000000", bgOpacity: 0,
78
78
  boxW: 0, boxH: 0, // text box (px); 0 = hug content. Resize handles edit these.
79
79
  boxFit: false, // false = wrap at fixed fontSize; true = scale font to fit box
@@ -86,7 +86,7 @@ const ANIMATABLE = ["x", "y", "scale", "rotation", "opacity", "volume", "pan", "
86
86
  const TRANSITIONS = ["none", "fade", "slide-left", "slide-right", "slide-up", "slide-down",
87
87
  "zoom", "wipe", "wipe-right", "wipe-up", "wipe-down", "iris", "spin", "blur", "whip",
88
88
  "glitch", "pop"];
89
- const TEXT_ANIMS = ["none", "typewriter", "word-pop", "word-slide", "karaoke",
89
+ const TEXT_ANIMS = ["none", "typewriter", "word-pop", "word-slide", "karaoke", "highlight",
90
90
  "letter-pop", "wave", "bounce", "shake",
91
91
  "clip-reveal", "zoom-in", "font-cut", "rise-mask"];
92
92
  const BLEND_MODES = self.FableCutMask.BLENDS; // the canvas composite set, shared with the agent (mask.js)
@@ -434,6 +434,8 @@ function showClipCtxMenu(clientX, clientY, c) {
434
434
  item("Crossfade with neighbours", "Shift+D", () => crossfadeSelected(), locked ? "Locked — unlock to change" : null);
435
435
  item("Auto-duck under other tracks", "", () => autoDuckClips(selectedClips()), locked ? "Locked — unlock to change" : null);
436
436
  }
437
+ if (group.some((x) => x.kind === "audio" || x.kind === "video"))
438
+ item("Find silences", "", () => findSilences(selectedClips()));
437
439
  if (selectedClips().some((x) => isVisualClip(x) && x.kind !== "null"))
438
440
  item("Parent to a new null", "", parentSelectionToNull, locked ? "Locked — unlock to change" : null);
439
441
  item("Precompose", "", precomposeSelection, locked ? "Locked — unlock to change" : null);
@@ -550,6 +552,8 @@ const state = {
550
552
  previewRate: 1, // playback speed for PREVIEW only — never affects export
551
553
  selId: null, // primary selection (drives the inspector)
552
554
  selIds: new Set(), // full multi-selection (includes selId)
555
+ silence: null, // silences found (Inspector → Silence): {ids, spans, sig}, shown on the timeline until cut or cleared
556
+ silenceBusy: false, // a Find is listening (the Inspector offers Cancel)
553
557
  trackSize: "l", // s | m | l — timeline track density preset
554
558
  connected: false, exporting: false,
555
559
  rendering: false, // fast (server/ffmpeg) export in progress
@@ -735,14 +739,16 @@ const runtime = {
735
739
  clipEls: new Map(), // clipId -> HTMLMediaElement
736
740
  clipGain: new Map(), // clipId -> GainNode
737
741
  mediaAux: new Map(), // mediaId -> {img?, thumb?, svgText?, svgAnimated?}
738
- audioBufs: new Map(), // mediaId -> Promise<AudioBuffer> (waveforms + export mix)
739
- wavePeaks: new Map(), // mediaId -> {channels: Float32Array[], max: Float32Array} | Float32Array (legacy) | null (pending)
742
+ audioBufs: new Map(), // media src -> Promise<AudioBuffer> (waveforms + export mix); by file, so a relinked entry decodes its new one
743
+ wavePeaks: new Map(), // mediaId -> {src, channels: Float32Array[], max: Float32Array} | Float32Array (legacy) | {src, pending}
740
744
  library: {}, // dir -> [{name, rel, src, size}] cached /api/library results
741
745
  customFonts: [], // family names loaded from /library/fonts
742
746
  libraryFontReq: new Set(), // library families claimed by a load pass
743
747
  googleLoaded: new Set(), // loaded from Google Fonts (the font picker lists them)
744
748
  fontReq: new Map(), // font name -> Promise<boolean> (ensureFont)
745
749
  undo: [], redo: [],
750
+ seqUndo: new Map(), // sequence id -> {undo, redo, time, sel}: each sequence keeps its own undo history this session
751
+ seqOpen: null, // the open sequence's id, to notice another one being opened
746
752
  audio: null, // {ctx, master (sum), masterOut (fader), trackBus, recDest, meter?, meterReady?}
747
753
  saveTimer: null, pendingSync: false,
748
754
  sfxPreview: null, // <audio> element for library sound previews
@@ -791,7 +797,7 @@ const els = {
791
797
  btnInsert: $("btnInsert"), btnReplace: $("btnReplace"),
792
798
  vuMeter: $("vuMeter"),
793
799
  sideTabs: $("sideTabs"),
794
- mixer: $("mixer"), colorPage: $("colorPage"),
800
+ mixer: $("mixer"), colorPage: $("colorPage"), transcriptPage: $("transcriptPage"),
795
801
  exportSetup: $("exportSetup"), engineFast: $("engineFast"), engineRealtime: $("engineRealtime"),
796
802
  exportProfileRow: $("exportProfileRow"),
797
803
  exportProfileSel: $("exportProfileSel"), exportProfileNote: $("exportProfileNote"),
@@ -1195,6 +1201,8 @@ async function connectServer() {
1195
1201
  applyProject(data);
1196
1202
  state.connected = true;
1197
1203
  els.projectName.textContent = project.name + " · 🟢 connected";
1204
+ runtime.projectId = res.headers.get("X-FableCut-Project");
1205
+ if (res.headers.get("X-FableCut-Projects")) initProjectsUi();
1198
1206
  listenSSE();
1199
1207
  fetch("/api/export/ffmpeg").then((r) => r.json())
1200
1208
  .then((j) => { state.ffmpeg = !!j.available; }).catch(() => { });
@@ -1204,6 +1212,7 @@ async function connectServer() {
1204
1212
  state.connected = false;
1205
1213
  els.projectName.textContent = project.name + " · ⚪ local session";
1206
1214
  }
1215
+ initSequencesUi();
1207
1216
  await probeMissingMeta();
1208
1217
  }
1209
1218
  /* Main-profile AVC level by canvas height; Annex-B is required so ffmpeg
@@ -1446,6 +1455,14 @@ function syncExportFrameSel() {
1446
1455
  els.exportFrameSel.innerHTML = html;
1447
1456
  }
1448
1457
  function applyProject(data, opts = {}) {
1458
+ if (state.compCtx && !opts.ctx && SeqLib.activeId(data) !== SeqLib.activeId(state.compCtx.root)) {
1459
+ // another sequence was opened (an agent, another tab): the comp was opened from the old one
1460
+ state.compCtx = null;
1461
+ runtime.undo.length = 0; runtime.redo.length = 0;
1462
+ applyProject(data, { ctx: true });
1463
+ syncCompCrumb();
1464
+ return;
1465
+ }
1449
1466
  if (state.compCtx && !opts.ctx) { // the root changed on disk (an agent, another tab): keep the open comp open
1450
1467
  const x = state.compCtx;
1451
1468
  x.root = data;
@@ -1458,6 +1475,7 @@ function applyProject(data, opts = {}) {
1458
1475
  syncCompCrumb();
1459
1476
  return;
1460
1477
  }
1478
+ if (!state.compCtx) noteOpenSequence(data);
1461
1479
  const wa = normalizeWorkArea(data.inPoint, data.outPoint);
1462
1480
  Object.assign(project, {
1463
1481
  name: data.name || "Untitled Project",
@@ -1478,6 +1496,9 @@ function applyProject(data, opts = {}) {
1478
1496
  outputs: Array.isArray(data.outputs) ? data.outputs.filter((o) => o && typeof o === "object") : null,
1479
1497
  master: normalizeMaster(data.master),
1480
1498
  buses: normalizeBuses(data.buses),
1499
+ // the sequences that aren't open, kept as they are (see sequences.js); the open one is this document
1500
+ sequences: Array.isArray(data.sequences) && data.sequences.length ? data.sequences : null,
1501
+ sequence: Array.isArray(data.sequences) && data.sequences.length ? SeqLib.activeId(data) : null,
1481
1502
  comps: (Array.isArray(data.comps) ? data.comps : []).filter((cp) => cp && cp.id).map((cp) => ({
1482
1503
  ...cp, clips: (cp.clips || []).map((x) => {
1483
1504
  if (x.keyframes) for (const arr of Object.values(x.keyframes)) if (Array.isArray(arr)) arr.sort((a, b) => a.t - b.t);
@@ -1556,19 +1577,38 @@ function scheduleSave() {
1556
1577
  state.dirtyTimeline = true;
1557
1578
  if (!state.connected) return;
1558
1579
  clearTimeout(runtime.saveTimer);
1559
- runtime.saveTimer = setTimeout(async () => {
1560
- runtime.saveTimer = null;
1561
- project.revision++;
1562
- const body = JSON.stringify(projectJSON(), null, 2);
1563
- try {
1564
- const res = await fetch("/api/project", { method: "PUT", headers: { "Content-Type": "application/json" }, body });
1565
- if (res.status === 409) {
1566
- // an external tool saved a newer revision while this change was pending
1567
- await syncFromServer(true);
1568
- toast("Project was updated externally — your last change may need redoing.");
1569
- }
1570
- } catch { }
1571
- }, 400);
1580
+ runtime.saveTimer = setTimeout(() => { runtime.saveTimer = null; runtime.saving = saveNow(); }, 400);
1581
+ }
1582
+ async function saveNow() {
1583
+ project.revision++;
1584
+ const body = JSON.stringify(projectJSON(), null, 2);
1585
+ try {
1586
+ const headers = { "Content-Type": "application/json" };
1587
+ if (runtime.projectId) headers["X-FableCut-Project"] = runtime.projectId; // the project this edit belongs to
1588
+ const res = await fetch("/api/project", { method: "PUT", headers, body });
1589
+ if (res.status === 409) {
1590
+ // an external tool saved a newer revision while this change was pending
1591
+ const loaded = await syncFromServer(true);
1592
+ toast("Project was updated externally — your last change may need redoing.");
1593
+ runtime.saveFailed = loaded !== true;
1594
+ return loaded === true; // the newer document on disk is now what this tab shows
1595
+ }
1596
+ runtime.saveFailed = !res.ok;
1597
+ return res.ok;
1598
+ } catch { runtime.saveFailed = true; return false; }
1599
+ }
1600
+ /** Write a pending edit now (and wait for one in flight), e.g. before switching projects.
1601
+ * False when that save did not land. */
1602
+ async function flushSave() {
1603
+ try { await runtime.saving; } catch { }
1604
+ // a pending edit, or one whose last save did not land: send it (again) now
1605
+ if (runtime.saveTimer || runtime.saveFailed) { clearTimeout(runtime.saveTimer); runtime.saveTimer = null; runtime.saving = saveNow(); }
1606
+ try { return (await runtime.saving) !== false; } catch { return false; }
1607
+ }
1608
+ async function flushSaveBeforeSwitch() {
1609
+ if (await flushSave()) return true;
1610
+ toast("Your last change couldn't be saved, so the project stays open. Try again in a moment.");
1611
+ return false;
1572
1612
  }
1573
1613
  /** One clip as saved: only the fields the editor knows (unknown runtime fields stay out). */
1574
1614
  function serializeClip({ id, mediaId, kind, compId, track, start, in: inn, duration, name, props, keyframes, transitionIn, transitionOut, linkedId, linkGroup, locked, disabled, unlinked, fx, parent }) {
@@ -1630,6 +1670,10 @@ function projectJSONHere() {
1630
1670
  const buses = normalizeBuses(project.buses);
1631
1671
  if (buses.length) out.buses = buses;
1632
1672
  if (project.comps && project.comps.length) out.comps = project.comps.map((cp) => ({ ...cp, clips: (cp.clips || []).map(serializeClip) }));
1673
+ if (project.sequences) {
1674
+ out.sequences = project.sequences.map((sq) => (sq.id === project.sequence ? { id: sq.id, name: sq.name } : sq));
1675
+ out.sequence = project.sequence;
1676
+ }
1633
1677
  return out;
1634
1678
  }
1635
1679
  function listenSSE() {
@@ -1637,6 +1681,22 @@ function listenSSE() {
1637
1681
  // Named events: "change" = project/media/library; "profiles" = encoding-profiles.json only
1638
1682
  es.addEventListener("change", () => { noteActivity(); syncFromServer(); scheduleOfflineCheck(); });
1639
1683
  es.addEventListener("proxy", (e) => onProxyEvent(e.data));
1684
+ es.addEventListener("transcript", (e) => onTranscriptEvent(e.data));
1685
+ es.addEventListener("versions", (e) => {
1686
+ let d = {};
1687
+ try { d = JSON.parse(e.data); } catch { }
1688
+ if (!(projectsOpen() && pj.verOf && d.project === pj.verOf)) return;
1689
+ if (pj.busy) { pj.verPending = true; return; } // pjVersionAction refreshes when it is done
1690
+ if (document.querySelector(".ver-rename")) return; // a rename is being typed: it refreshes the list when it ends
1691
+ pjDropDiffs(); // a comparison made before this change no longer holds
1692
+ pjLoadVersions();
1693
+ });
1694
+ es.addEventListener("projects", (e) => {
1695
+ let d = {};
1696
+ try { d = JSON.parse(e.data); } catch { }
1697
+ if (d.active && runtime.projectId && d.active !== runtime.projectId) syncFromServer(true);
1698
+ else if (projectsOpen() && !pj.busy) pjLoad();
1699
+ });
1640
1700
  es.addEventListener("export", (e) => {
1641
1701
  noteActivity();
1642
1702
  try { runExportJob(JSON.parse(e.data)); } catch { }
@@ -1665,19 +1725,40 @@ function listenSSE() {
1665
1725
  e.g. Claude — wrote it). Our own saves land at our exact local revision, so
1666
1726
  they compare equal and are skipped without any timing heuristics. Deferred
1667
1727
  during gestures/exports and re-run when they end (runtime.pendingSync). */
1728
+ /** True when the server's document was loaded (a later caller may rely on it). */
1668
1729
  async function syncFromServer(force) {
1669
- if (state.gesture || state.exporting) { runtime.pendingSync = true; return; }
1730
+ if (state.gesture || state.exporting) { runtime.pendingSync = true; return false; }
1670
1731
  runtime.pendingSync = false;
1671
1732
  if (state.binTab === "templates") fetchSaved("templates").then(() => { if (state.binTab === "templates") renderTemplatesTab(); });
1672
1733
  else if (state.binTab !== "project" && state.binTab !== "shapes") fetchLibrary(state.binTab).then(renderLibrary);
1673
1734
  fetchSaved("presets");
1674
1735
  loadLibraryFonts();
1675
1736
  fetchEncodeProfiles();
1737
+ const seq = runtime.syncSeq = (runtime.syncSeq || 0) + 1;
1676
1738
  try {
1677
1739
  const res = await fetch("/api/project", { cache: "no-store" });
1678
1740
  if (!res.ok) return;
1679
1741
  const data = await res.json();
1742
+ if (seq !== runtime.syncSeq) return; // a newer reload is on its way: this answer may be older than it
1680
1743
  if (!data || !Array.isArray(data.clips)) return;
1744
+ // another project was opened (the dashboard, another tab, an agent)
1745
+ const pid = res.headers.get("X-FableCut-Project");
1746
+ const switched = !!(pid && runtime.projectId && pid !== runtime.projectId);
1747
+ if (pid) runtime.projectId = pid;
1748
+ if (switched) {
1749
+ onProjectSwitched();
1750
+ applyProject(data);
1751
+ { // decoded audio is by file: keep what this project uses, free the rest
1752
+ const srcs = new Set(project.media.map((m) => m.src));
1753
+ for (const src of [...runtime.audioBufs.keys()]) if (!srcs.has(src)) runtime.audioBufs.delete(src);
1754
+ }
1755
+ setTime(0);
1756
+ syncCompCrumb();
1757
+ if (!pj.selfSwitch) toast(`Switched to “${project.name}”`);
1758
+ if (projectsOpen()) pjLoad();
1759
+ await probeMissingMeta();
1760
+ return true;
1761
+ }
1681
1762
  if (!force && (data.revision || 0) === (project.revision || 0)) return; // our own save
1682
1763
  if (runtime.saveTimer) { // unsaved local edit vs. external write: external wins, tell the user
1683
1764
  clearTimeout(runtime.saveTimer); runtime.saveTimer = null;
@@ -1686,8 +1767,14 @@ async function syncFromServer(force) {
1686
1767
  toast("Project was updated externally — your last change may need redoing.");
1687
1768
  }
1688
1769
  applyProject(data);
1770
+ syncCompCrumb(); // the top bar shows the project's name
1771
+ // "Compare with now" was against the document before this change
1772
+ // (always: a comparison still on its way was made against the old document too)
1773
+ if (pj.verOf === runtime.projectId) { const had = pj.verDiff.size; pjDropDiffs(); if (had && projectsOpen()) renderProjectGrid(); }
1689
1774
  await probeMissingMeta();
1775
+ return true;
1690
1776
  } catch { }
1777
+ return false;
1691
1778
  }
1692
1779
  /** Populate a media entry's duration/dimensions (and cache preview assets) by
1693
1780
  * dispatching on kind: svg loads its markup, image loads for width/height,
@@ -1697,7 +1784,9 @@ async function syncFromServer(force) {
1697
1784
  async function loadMediaMetadata(m) {
1698
1785
  if (m.kind === "svg") { await loadSvgMedia(m); return; }
1699
1786
  if (m.kind === "image") {
1787
+ const gen = runtime.projectGen;
1700
1788
  const img = await loadImage(m.src);
1789
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
1701
1790
  runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), img, imgSrc: m.src });
1702
1791
  m.width = img.naturalWidth; m.height = img.naturalHeight;
1703
1792
  return;
@@ -1752,6 +1841,7 @@ function loadImage(src) {
1752
1841
  });
1753
1842
  }
1754
1843
  async function grabThumb(m) {
1844
+ const gen = runtime.projectGen;
1755
1845
  const v = document.createElement("video");
1756
1846
  v.muted = true; v.preload = "auto";
1757
1847
  if (isCrossOriginSrc(m.src)) v.crossOrigin = "anonymous";
@@ -1762,6 +1852,7 @@ async function grabThumb(m) {
1762
1852
  const c = document.createElement("canvas");
1763
1853
  c.width = 160; c.height = 90;
1764
1854
  c.getContext("2d").drawImage(v, 0, 0, 160, 90);
1855
+ if (gen !== runtime.projectGen) { v.src = ""; return; }
1765
1856
  runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), thumb: c.toDataURL("image/jpeg", 0.6) });
1766
1857
  v.src = "";
1767
1858
  renderBin(); state.dirtyTimeline = true;
@@ -1773,20 +1864,24 @@ function getDecodeCtx() {
1773
1864
  return decodeCtx || (decodeCtx = new (window.AudioContext || window.webkitAudioContext)());
1774
1865
  }
1775
1866
  function getAudioBuffer(m) {
1776
- let p = runtime.audioBufs.get(m.id);
1867
+ const src = m.src;
1868
+ let p = runtime.audioBufs.get(src);
1777
1869
  if (!p) {
1778
- p = fetch(m.src).then((r) => r.arrayBuffer())
1870
+ p = fetch(src).then((r) => r.arrayBuffer())
1779
1871
  .then((ab) => getDecodeCtx().decodeAudioData(ab));
1780
- runtime.audioBufs.set(m.id, p);
1781
- p.catch(() => runtime.audioBufs.delete(m.id));
1872
+ runtime.audioBufs.set(src, p);
1873
+ p.catch(() => runtime.audioBufs.delete(src));
1782
1874
  }
1783
1875
  return p;
1784
1876
  }
1785
1877
  function ensureWave(m) {
1786
1878
  // Also decode peaks from video files when their audio is placed on an A track
1787
- if ((m.kind !== "audio" && m.kind !== "video") || runtime.wavePeaks.has(m.id)) return;
1788
- runtime.wavePeaks.set(m.id, null); // pending
1879
+ if (m.kind !== "audio" && m.kind !== "video") return;
1880
+ const have = runtime.wavePeaks.get(m.id), src = m.src;
1881
+ if (have && (have instanceof Float32Array || have.src === src)) return;
1882
+ runtime.wavePeaks.set(m.id, { src, pending: true });
1789
1883
  getAudioBuffer(m).then((buf) => {
1884
+ if (runtime.wavePeaks.get(m.id)?.src !== src) return; // the entry points at another file now (relink, another project)
1790
1885
  const n = Math.max(1, Math.ceil(buf.duration * WAVE_PEAKS_PER_SEC));
1791
1886
  const step = buf.length / n;
1792
1887
  const channels = [];
@@ -1808,10 +1903,10 @@ function ensureWave(m) {
1808
1903
  for (const p of channels) if (p[i] > mx) mx = p[i];
1809
1904
  max[i] = mx;
1810
1905
  }
1811
- runtime.wavePeaks.set(m.id, { channels, max });
1906
+ runtime.wavePeaks.set(m.id, { src, channels, max });
1812
1907
  if (m.channels == null) m.channels = buf.numberOfChannels;
1813
1908
  state.dirtyTimeline = true;
1814
- }).catch(() => runtime.wavePeaks.delete(m.id));
1909
+ }).catch(() => { if (runtime.wavePeaks.get(m.id)?.src === src) runtime.wavePeaks.delete(m.id); });
1815
1910
  }
1816
1911
  function wavePeaksFor(c) {
1817
1912
  const w = runtime.wavePeaks.get(c.mediaId);
@@ -1846,7 +1941,7 @@ async function importFiles(fileList) {
1846
1941
  ? runtime.importFolderId : null;
1847
1942
  runtime.importFolderId = null;
1848
1943
  let added = 0, skipped = 0;
1849
- const addedMedia = [];
1944
+ const addedMedia = [], gen = runtime.projectGen;
1850
1945
  for (const file of files) {
1851
1946
  const kind = mediaKindFromFile(file);
1852
1947
  if (!kind) { skipped++; continue; }
@@ -1866,6 +1961,7 @@ async function importFiles(fileList) {
1866
1961
  if (kind === "video") grabThumb(m).catch(() => { });
1867
1962
  ensureWave(m);
1868
1963
  } catch { skipped++; continue; }
1964
+ if (gen !== runtime.projectGen) { toast("Import stopped: another project was opened. The uploaded files are in media/"); break; }
1869
1965
  project.media.push(m);
1870
1966
  addedMedia.push(m);
1871
1967
  added++;
@@ -1916,6 +2012,7 @@ async function importFromUrl(url) {
1916
2012
  if (!state.connected) { toast("Import from URL needs the editor server"); return; }
1917
2013
  runtime.importUrlAbort = new AbortController();
1918
2014
  setImportUrlBusy(true);
2015
+ const gen = runtime.projectGen;
1919
2016
  try {
1920
2017
  const res = await fetch("/api/import-url", {
1921
2018
  method: "POST",
@@ -1936,6 +2033,7 @@ async function importFromUrl(url) {
1936
2033
  if (kind === "video") grabThumb(m).catch(() => { });
1937
2034
  ensureWave(m);
1938
2035
  } catch { /* browser will retry via probeMissingMeta */ }
2036
+ if (gen !== runtime.projectGen) throw new Error("another project was opened — the file is in media/");
1939
2037
  project.media.push(m);
1940
2038
  renderBin(); scheduleSave();
1941
2039
  closeImportUrl();
@@ -2202,6 +2300,7 @@ function usageDoc() {
2202
2300
  return {
2203
2301
  media: project.media,
2204
2302
  clips: state.compCtx.root.clips || [],
2303
+ sequences: state.compCtx.root.sequences, sequence: state.compCtx.root.sequence,
2205
2304
  comps: (project.comps || []).map((c) => (c.id === id ? { ...c, clips: project.clips } : c)),
2206
2305
  };
2207
2306
  }
@@ -2354,7 +2453,9 @@ function newCollection(name, mediaIds) {
2354
2453
  return col;
2355
2454
  }
2356
2455
  function removeMediaFromBin(m) {
2357
- if (state.compCtx && (state.compCtx.root.clips || []).some((c) => c.mediaId === m.id)) { toast("It's used on the main timeline — go back to Main to delete it"); return; }
2456
+ if (state.compCtx && (state.compCtx.root.clips || []).some((c) => c.mediaId === m.id)) { toast(`It's used on the timeline of “${openSequenceName()}” — go back to it to delete it`); return; }
2457
+ const elsewhere = SeqLib.others(seqRoot()).find((sq) => (sq.clips || []).some((c) => c.mediaId === m.id));
2458
+ if (elsewhere) { toast(`It's used in the sequence “${elsewhere.name}” — remove its clips there first`); return; }
2358
2459
  pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media })); // undo brings the media back too
2359
2460
  project.media = project.media.filter((x) => x.id !== m.id);
2360
2461
  project.clips = project.clips.filter((c) => c.mediaId !== m.id);
@@ -2508,13 +2609,14 @@ function showMediaInstances(m, x, y) {
2508
2609
  for (const p of list) {
2509
2610
  const b = document.createElement("button");
2510
2611
  b.type = "button"; b.className = "ctx-item";
2511
- b.innerHTML = `<span>${escapeHtml(p.comp ? `▣ ${p.compName}` : "Main")} · ${escapeHtml(p.track)}</span><kbd>${fmt(p.start)} → ${fmt(p.start + p.duration)}</kbd>`;
2612
+ b.innerHTML = `<span>${escapeHtml(p.sequence ? `▤ ${p.sequenceName}` : p.comp ? `▣ ${p.compName}` : openSequenceName())} · ${escapeHtml(p.track)}</span><kbd>${fmt(p.start)} → ${fmt(p.start + p.duration)}</kbd>`;
2512
2613
  b.addEventListener("click", () => { goToPlacement(p); });
2513
2614
  pop.appendChild(b);
2514
2615
  }
2515
2616
  showPopover(pop, x, y);
2516
2617
  }
2517
2618
  function goToPlacement(p) {
2619
+ if (p.sequence && !openSequence(p.sequence)) return;
2518
2620
  const here = compCtxId();
2519
2621
  if (p.comp !== here) {
2520
2622
  if (state.compCtx) exitComp(state.compCtx.path.length);
@@ -2614,7 +2716,7 @@ function reloadMediaSource(m, oldSrc) {
2614
2716
  /** Point a media entry at another file. mode "relink" (same footage) or "replace" (a new file). */
2615
2717
  async function setMediaSource(m, src, mode, name) {
2616
2718
  const oldSrc = m.src, oldDur = m.duration;
2617
- pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media }));
2719
+ pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media, seqClips: otherSequenceClips() }));
2618
2720
  m.src = src;
2619
2721
  for (const k of MediaLib.INFO_KEYS) delete m[k];
2620
2722
  if (mode === "replace") {
@@ -2642,6 +2744,7 @@ async function setMediaSource(m, src, mode, name) {
2642
2744
  fit(project.clips);
2643
2745
  for (const comp of project.comps || []) fit(comp.clips);
2644
2746
  if (state.compCtx) fit(state.compCtx.root.clips);
2747
+ for (const sq of SeqLib.others(seqRoot())) fit(sq.clips);
2645
2748
  runtime.compGen = (runtime.compGen || 0) + 1;
2646
2749
  if (trimmed) msg += ` — ${trimmed} clip edge${trimmed === 1 ? "" : "s"} trimmed to fit`;
2647
2750
  if (m.kind === "video") for (const c of project.clips) if (c.mediaId === m.id && c.kind === "video") reconcileAudioChannels(c);
@@ -3013,7 +3116,7 @@ function mediaForLibraryItem(f) {
3013
3116
  return m;
3014
3117
  }
3015
3118
  async function addLibraryItem(f, trackId, at) {
3016
- const m = mediaForLibraryItem(f);
3119
+ const m = mediaForLibraryItem(f), gen = runtime.projectGen;
3017
3120
  if (!m) { toast("Unsupported file type: " + f.name); return; }
3018
3121
  if ((m.kind === "audio" || m.kind === "video") && (m.duration == null || isNaN(m.duration))) {
3019
3122
  try { await loadMediaMetadata(m); } catch { }
@@ -3026,6 +3129,7 @@ async function addLibraryItem(f, trackId, at) {
3026
3129
  if (m.kind === "image" && !runtime.mediaAux.get(m.id)?.img) {
3027
3130
  try { await loadMediaMetadata(m); } catch { }
3028
3131
  }
3132
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
3029
3133
  addClipFromMedia(m, trackId, at);
3030
3134
  }
3031
3135
  function toggleSfxPreview(f, btn) {
@@ -3103,6 +3207,600 @@ function setBinTab(tab) {
3103
3207
  else if (!isProj) fetchLibrary(tab).then(renderLibrary);
3104
3208
  }
3105
3209
 
3210
+ /* ═══════════════════════════ PROJECTS (dashboard) ═══════════════════════════ */
3211
+ /* Several projects in one data folder (projects.js on the server). The open one
3212
+ is always ./project.json, so everything else in the editor is unchanged; the
3213
+ dashboard lists the others and switches between them. A switch shows up in
3214
+ syncFromServer as a new X-FableCut-Project id, wherever it came from (this
3215
+ tab, another tab, an agent): undo, the open comp and the Source monitor
3216
+ belong to the old project and are reset there. */
3217
+ const pj = {
3218
+ view: "active", // active | archived
3219
+ mode: "detail", // detail | new
3220
+ sel: null, list: [], templates: [], tpl: "landscape-1080",
3221
+ sort: "opened", search: "", busy: false, selfSwitch: false,
3222
+ verOf: null, versions: [], verDiff: new Map(), // the versions view: whose, its list, open comparisons
3223
+ verDiffGen: 0, verPending: false, // bumped when comparisons are dropped · a list refresh waiting for a busy action
3224
+ };
3225
+ const pjFmtDur = (s) => {
3226
+ if (!(s > 0)) return "0:00";
3227
+ const m = Math.floor(s / 60), r = Math.floor(s % 60);
3228
+ return m >= 60 ? `${Math.floor(m / 60)}:${String(m % 60).padStart(2, "0")}:${String(r).padStart(2, "0")}` : `${m}:${String(r).padStart(2, "0")}`;
3229
+ };
3230
+ function pjAgo(iso) {
3231
+ if (!iso) return "never";
3232
+ const s = (Date.now() - new Date(iso).getTime()) / 1000;
3233
+ if (!(s >= 0)) return new Date(iso).toLocaleDateString();
3234
+ if (s < 60) return "just now";
3235
+ if (s < 3600) return `${Math.floor(s / 60)} min ago`;
3236
+ if (s < 86400) return `${Math.floor(s / 3600)} h ago`;
3237
+ if (s < 86400 * 7) return `${Math.floor(s / 86400)} d ago`;
3238
+ return new Date(iso).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
3239
+ }
3240
+ const pjFps = (f) => (f ? `${+(+f).toFixed(3)} fps` : "");
3241
+ async function pjPost(body) {
3242
+ try {
3243
+ const res = await fetch("/api/projects", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
3244
+ const out = await res.json().catch(() => ({}));
3245
+ if (!res.ok) { toast(out.error || `Projects: request failed (${res.status})`); return null; }
3246
+ return out;
3247
+ } catch { toast("Projects: the editor server did not answer"); return null; }
3248
+ }
3249
+ /* The program monitor's picture, small, as the open project's card thumbnail. */
3250
+ async function pjSnapThumb() {
3251
+ const id = runtime.projectId, cv = els.preview;
3252
+ if (!id || !cv || !cv.width || !cv.height) return;
3253
+ try {
3254
+ const w = 360, h = Math.max(1, Math.round(w * cv.height / cv.width));
3255
+ const c = document.createElement("canvas");
3256
+ c.width = w; c.height = h;
3257
+ c.getContext("2d").drawImage(cv, 0, 0, w, h);
3258
+ const blob = await new Promise((r) => c.toBlob(r, "image/jpeg", 0.74));
3259
+ if (blob) await fetch("/api/projects/thumb?id=" + encodeURIComponent(id), { method: "PUT", body: blob });
3260
+ } catch { }
3261
+ }
3262
+ async function pjLoad() {
3263
+ try {
3264
+ const res = await fetch("/api/projects?archived=" + (pj.view === "archived" ? "only" : "exclude"), { cache: "no-store" });
3265
+ if (!res.ok) throw new Error();
3266
+ const data = await res.json();
3267
+ pj.list = data.projects || [];
3268
+ pj.templates = data.templates || [];
3269
+ // syncFromServer owns runtime.projectId: it resets undo, comp and Source on a switch.
3270
+ // On first use the list has just given the shown project.json its id: adopt it, if
3271
+ // project.json is still the document this tab shows.
3272
+ if (data.active && !runtime.projectId) {
3273
+ const r = await fetch("/api/project", { cache: "no-store" }).catch(() => null);
3274
+ const doc = r && r.ok ? await r.json().catch(() => null) : null;
3275
+ const ids = (d) => JSON.stringify([d.name, d.revision || 0, (d.clips || []).map((c) => c.id), (d.media || []).map((m) => m.id)]);
3276
+ const shown = projectJSON();
3277
+ if (doc && r.headers.get("X-FableCut-Project") === data.active && ids(doc) === ids(shown)) runtime.projectId = data.active;
3278
+ else { runtime.projectId = "?"; syncFromServer(true); } // not what this tab shows: load it as a switch
3279
+ } else if (data.active && data.active !== runtime.projectId) syncFromServer(true);
3280
+ if (!pj.list.some((p) => p.id === pj.sel)) pj.sel = (pj.list.find((p) => p.active) || pj.list[0] || {}).id || null;
3281
+ } catch { pj.list = []; toast("Projects: couldn't read the project list"); }
3282
+ renderProjects();
3283
+ }
3284
+ async function openProjects() {
3285
+ const ov = $("projectsOverlay");
3286
+ if (!ov || !state.connected) return;
3287
+ pj.mode = "detail"; pj.view = "active"; pj.sel = runtime.projectId;
3288
+ pj.verOf = null; pjDropDiffs(); // a versions list left open last time may be out of date
3289
+ ov.classList.remove("hidden");
3290
+ $("projectsDialog")?.focus();
3291
+ renderProjects(); // the shell at once; cards once the list is in
3292
+ await flushSave();
3293
+ await pjSnapThumb();
3294
+ await pjLoad();
3295
+ }
3296
+ function closeProjects() {
3297
+ $("projectsOverlay")?.classList.add("hidden");
3298
+ $("btnProjectsDash")?.focus();
3299
+ }
3300
+ const projectsOpen = () => !!$("projectsOverlay") && !$("projectsOverlay").classList.contains("hidden");
3301
+ function pjVisible() {
3302
+ const q = pj.search.trim().toLowerCase();
3303
+ const words = q ? q.split(/\s+/) : [];
3304
+ const hit = (p, w) => w.startsWith("#")
3305
+ ? (p.tags || []).some((t) => t.toLowerCase().includes(w.slice(1)))
3306
+ : [p.name, p.notes, ...(p.tags || [])].some((s) => String(s || "").toLowerCase().includes(w));
3307
+ const out = pj.list.filter((p) => words.every((w) => hit(p, w)));
3308
+ const key = { opened: (p) => p.opened || p.modified || "", modified: (p) => p.modified || "", created: (p) => p.created || "" }[pj.sort];
3309
+ if (key) out.sort((a, b) => String(key(b)).localeCompare(String(key(a))));
3310
+ else out.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }));
3311
+ return out;
3312
+ }
3313
+ function pjThumbHtml(p, big) {
3314
+ const ar = p.width > 0 && p.height > 0 ? `${p.width} / ${p.height}` : "16 / 9";
3315
+ const inner = p.thumb
3316
+ ? `<img src="/api/projects/thumb?id=${encodeURIComponent(p.id)}&v=${p.thumb}" alt="" loading="lazy" draggable="false">`
3317
+ : `<span>${p.width ? `${p.width}×${p.height}` : "?"}</span>`;
3318
+ return `<div class="pj-thumb${big ? " big" : ""}"><div class="pj-frame" style="aspect-ratio:${ar}">${inner}</div></div>`;
3319
+ }
3320
+ function renderProjects() {
3321
+ renderProjectGrid();
3322
+ renderProjectSide();
3323
+ }
3324
+ function renderProjectSide() {
3325
+ const side = $("pjSide");
3326
+ if (side) side.innerHTML = pj.mode === "new" ? pjNewHtml() : pjDetailHtml(pj.list.find((p) => p.id === pj.sel));
3327
+ $("pjNewBtn")?.classList.toggle("on", pj.mode === "new");
3328
+ }
3329
+ function renderProjectGrid() {
3330
+ const grid = $("pjGrid");
3331
+ if (!grid) return;
3332
+ for (const b of document.querySelectorAll("[data-pj-view]")) b.classList.toggle("on", b.dataset.pjView === pj.view);
3333
+ grid.classList.toggle("versions", !!pj.verOf);
3334
+ if (pj.verOf) { grid.innerHTML = pjVersionsHtml(); return; }
3335
+ const rows = pjVisible();
3336
+ grid.innerHTML = rows.length ? rows.map((p) => `
3337
+ <button type="button" class="pj-card${p.id === pj.sel && pj.mode === "detail" ? " sel" : ""}${p.active ? " open" : ""}" data-pj="${escapeHtml(p.id)}" title="${p.active ? "Currently open" : "Double-click to open"}">
3338
+ ${pjThumbHtml(p)}
3339
+ <span class="pj-card-name">${escapeHtml(p.name)}${p.active ? ` <span class="pj-badge">Open</span>` : ""}</span>
3340
+ <span class="pj-card-meta">${p.unreadable ? "file unreadable" : `${p.width}×${p.height} · ${pjFps(p.fps)} · ${pjFmtDur(p.duration)}`}</span>
3341
+ <span class="pj-card-when dim">${pj.sort === "created" ? "Created " + pjAgo(p.created) : pj.sort === "modified" || !p.opened ? "Modified " + pjAgo(p.modified) : "Opened " + pjAgo(p.opened)}</span>
3342
+ </button>`).join("")
3343
+ : `<div class="pj-empty dim">${pj.list.length ? "No project matches the search." : pj.view === "archived" ? "Nothing archived. Archive a project to keep it out of the list without deleting it." : "Loading…"}</div>`;
3344
+ }
3345
+ function pjDetailHtml(p) {
3346
+ if (!p) return `<p class="dim">Pick a project to see its details.</p>`;
3347
+ const fact = (k, v) => `<dt>${k}</dt><dd>${v}</dd>`;
3348
+ const tpl = p.template && pj.templates.find((t) => t.id === p.template);
3349
+ return `${pjThumbHtml(p, true)}
3350
+ <label class="pj-field"><span>Name</span><input type="text" id="pjName" value="${escapeHtml(p.name)}" maxlength="120" spellcheck="false"></label>
3351
+ <dl class="pj-facts">
3352
+ ${fact("Canvas", p.unreadable ? "—" : `${p.width}×${p.height} · ${pjFps(p.fps)}`)}
3353
+ ${fact("Length", `${pjFmtDur(p.duration)} · ${p.clips} clip${p.clips === 1 ? "" : "s"} · ${p.media} media`)}
3354
+ ${fact("Modified", pjAgo(p.modified))}
3355
+ ${fact("Opened", p.active ? "open now" : pjAgo(p.opened))}
3356
+ ${fact("Created", pjAgo(p.created))}
3357
+ ${tpl ? fact("Template", escapeHtml(tpl.name)) : ""}
3358
+ </dl>
3359
+ <label class="pj-field"><span>Notes</span><textarea id="pjNotes" rows="4" maxlength="4000" placeholder="Brief, client, deadline, what's left to do…">${escapeHtml(p.notes || "")}</textarea></label>
3360
+ <label class="pj-field"><span>Tags</span><input type="text" id="pjTags" value="${escapeHtml((p.tags || []).join(", "))}" placeholder="client, reel, draft" spellcheck="false"></label>
3361
+ <div class="pj-actions">
3362
+ ${p.archived
3363
+ ? `<button type="button" class="btn primary" data-pj-act="unarchive">Unarchive</button>
3364
+ <button type="button" class="btn danger-ghost" data-pj-act="delete" title="Deletes the project file. Its media stay in media/.">Delete…</button>`
3365
+ : `<button type="button" class="btn primary" data-pj-act="open"${p.active ? " disabled" : ""}>${p.active ? "Currently open" : "Open"}</button>
3366
+ <button type="button" class="btn" data-pj-act="duplicate" title="A copy of the whole project (the footage is shared, not copied)">Duplicate</button>
3367
+ <button type="button" class="btn" data-pj-act="template" title="Start new projects from this one: its canvas, tracks, clips and media">Save as template</button>
3368
+ <button type="button" class="btn" data-pj-act="archive"${p.active ? ` disabled title="Open another project first"` : ` title="Hide it from the list; nothing is deleted"`}>Archive</button>`}
3369
+ </div>
3370
+ <div class="pj-actions">
3371
+ <button type="button" class="btn" data-pj-act="versions" title="Saved versions of this project: compare, restore, mark the final cut">Versions…</button>
3372
+ <a class="btn" href="/api/projects/backup?id=${encodeURIComponent(p.id)}" download${p.active ? " data-pj-backup" : ""} title="The project and all its versions as one file. Import… restores it">Download backup</a>
3373
+ </div>
3374
+ <div class="pj-inline hidden" id="pjTplRow">
3375
+ <input type="text" id="pjTplName" value="${escapeHtml(p.name)}" maxlength="120" aria-label="Template name" spellcheck="false">
3376
+ <button type="button" class="btn primary" data-pj-act="template-save">Save template</button>
3377
+ </div>`;
3378
+ }
3379
+ function pjNewHtml() {
3380
+ const tpls = pj.templates;
3381
+ if (!tpls.some((t) => t.id === pj.tpl)) pj.tpl = "landscape-1080";
3382
+ const t = tpls.find((x) => x.id === pj.tpl) || { fps: 30 };
3383
+ const shape = (x) => {
3384
+ const k = 22 / Math.max(x.width || 16, x.height || 9);
3385
+ return `<i class="pj-shape" style="width:${Math.round((x.width || 16) * k)}px;height:${Math.round((x.height || 9) * k)}px"></i>`;
3386
+ };
3387
+ const row = (x) => `<button type="button" class="pj-tpl${x.id === pj.tpl ? " on" : ""}" data-pj-tpl="${escapeHtml(x.id)}">
3388
+ ${shape(x)}<span class="pj-tpl-name">${escapeHtml(x.name)}</span>
3389
+ <span class="pj-tpl-meta dim">${x.width}×${x.height}${x.builtin ? "" : ` · ${x.clips} clip${x.clips === 1 ? "" : "s"}`}</span>
3390
+ ${x.builtin ? "" : `<span class="pj-tpl-del" data-pj-tpldel="${escapeHtml(x.id)}" role="button" tabindex="0" title="Delete this template">✕</span>`}
3391
+ </button>`;
3392
+ const saved = tpls.filter((x) => !x.builtin);
3393
+ return `<h3>New project</h3>
3394
+ <label class="pj-field"><span>Name</span><input type="text" id="pjNewName" value="Untitled Project" maxlength="120" spellcheck="false"></label>
3395
+ <div class="pj-field"><span>Start from</span>
3396
+ <div class="pj-tpls">${tpls.filter((x) => x.builtin).map(row).join("")}</div>
3397
+ ${saved.length ? `<span class="pj-sub">Saved templates</span><div class="pj-tpls">${saved.map(row).join("")}</div>` : ""}
3398
+ </div>
3399
+ <label class="pj-field"><span>Frame rate</span><select id="pjNewFps">
3400
+ <option value="">${t.fps ? `${+(+t.fps).toFixed(3)} fps (template)` : "Template's"}</option>
3401
+ ${[23.976, 24, 25, 29.97, 30, 50, 59.94, 60].map((f) => `<option value="${f}">${f} fps</option>`).join("")}
3402
+ </select></label>
3403
+ <div class="pj-actions">
3404
+ <button type="button" class="btn" data-pj-act="new-cancel">Cancel</button>
3405
+ <button type="button" class="btn primary" data-pj-act="new-create">Create and open</button>
3406
+ </div>`;
3407
+ }
3408
+ async function pjOpenProject(id) {
3409
+ const p = pj.list.find((x) => x.id === id);
3410
+ if (!p || p.active || pj.busy) return;
3411
+ if (state.exporting) { toast("Wait for the export to finish before switching projects"); return; }
3412
+ pj.busy = true;
3413
+ try {
3414
+ if (!(await flushSaveBeforeSwitch())) return;
3415
+ await pjSnapThumb();
3416
+ pj.selfSwitch = true;
3417
+ const out = await pjPost({ action: "open", id });
3418
+ if (!out) return;
3419
+ closeProjects();
3420
+ if (await syncFromServer(true)) toast(`Opened “${out.project?.name || p.name}”`);
3421
+ else toast(`“${out.project?.name || p.name}” is open, but this tab couldn't load it yet. It will reload when the editor server answers.`);
3422
+ } finally { pj.busy = false; pj.selfSwitch = false; }
3423
+ }
3424
+ async function pjBusy(fn) {
3425
+ pj.busy = true;
3426
+ try { return await fn(); } finally { pj.busy = false; }
3427
+ }
3428
+ async function pjAction(act, btn) {
3429
+ const p = pj.list.find((x) => x.id === pj.sel);
3430
+ if (act === "new-cancel") { pj.mode = "detail"; renderProjects(); return; }
3431
+ if (act === "new-create") {
3432
+ if (pj.busy) return;
3433
+ if (state.exporting) { toast("Wait for the export to finish before switching projects"); return; }
3434
+ const name = ($("pjNewName")?.value || "").trim() || "Untitled Project";
3435
+ const fps = $("pjNewFps")?.value;
3436
+ pj.busy = true;
3437
+ try {
3438
+ if (!(await flushSaveBeforeSwitch())) return;
3439
+ await pjSnapThumb();
3440
+ pj.selfSwitch = true;
3441
+ const out = await pjPost({ action: "new", name, template: pj.tpl, fps: fps ? +fps : undefined, open: true });
3442
+ if (!out) return;
3443
+ closeProjects();
3444
+ if (await syncFromServer(true)) toast(`Created “${name}”`);
3445
+ else toast(`“${name}” was created and opened, but this tab couldn't load it yet. It will reload when the editor server answers.`);
3446
+ } finally { pj.busy = false; pj.selfSwitch = false; }
3447
+ return;
3448
+ }
3449
+ if (!p) return;
3450
+ if (act === "open") { pjOpenProject(p.id); return; }
3451
+ if (act === "template") { $("pjTplRow")?.classList.toggle("hidden"); $("pjTplName")?.select(); return; }
3452
+ if (act === "versions") { pj.verOf = p.id; pj.versions = []; pjDropDiffs(); renderProjectGrid(); pjLoadVersions(); return; }
3453
+ if (pj.busy) return; // one request at a time: a second click must not duplicate twice
3454
+ if (act === "template-save") {
3455
+ const out = await pjBusy(() => pjPost({ action: "save_template", id: p.id, name: $("pjTplName")?.value || p.name }));
3456
+ if (out) { toast(`Saved template “${out.template.name}” — pick it under + New project`); await pjLoad(); }
3457
+ return;
3458
+ }
3459
+ if (act === "delete") {
3460
+ if (btn.dataset.armed !== "1") {
3461
+ btn.dataset.armed = "1"; btn.textContent = "Click again to delete";
3462
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Delete…"; } }, 3000);
3463
+ return;
3464
+ }
3465
+ const out = await pjBusy(() => pjPost({ action: "delete", id: p.id }));
3466
+ if (out) { toast(`Deleted “${p.name}”`); pj.sel = null; await pjLoad(); }
3467
+ return;
3468
+ }
3469
+ const out = await pjBusy(() => pjPost({ action: act, id: p.id }));
3470
+ if (!out) return;
3471
+ if (act === "duplicate") { pj.sel = out.id; toast(`Duplicated as “${out.project.name}”`); }
3472
+ if (act === "archive") toast(`Archived “${p.name}” — it's under Archived`);
3473
+ if (act === "unarchive") toast(`“${p.name}” is back in Projects`);
3474
+ await pjLoad();
3475
+ }
3476
+ async function pjSaveField(field) {
3477
+ const p = pj.list.find((x) => x.id === pj.sel);
3478
+ if (!p) return;
3479
+ const el = $({ name: "pjName", notes: "pjNotes", tags: "pjTags" }[field]);
3480
+ if (!el) return;
3481
+ const v = el.value;
3482
+ if (field === "name" && (!v.trim() || v.trim() === p.name)) { if (!v.trim()) el.value = p.name; return; }
3483
+ if (field === "notes" && v === (p.notes || "")) return;
3484
+ if (field === "tags" && v === (p.tags || []).join(", ")) return;
3485
+ const out = await pjPost({ action: "update", id: p.id, [field]: field === "name" ? v.trim() : v });
3486
+ if (!out) return;
3487
+ Object.assign(p, out.project);
3488
+ if (field === "tags") el.value = (out.project.tags || []).join(", ");
3489
+ if (field === "name") renderProjectGrid();
3490
+ }
3491
+ async function pjImport(file) {
3492
+ let doc;
3493
+ try { doc = JSON.parse((await file.text()).replace(/^/, "")); }
3494
+ catch { toast(`${file.name} isn't JSON`); return; }
3495
+ const name = doc && doc.name && doc.name !== "Untitled Project" ? doc.name : file.name.replace(/\.json$/i, "");
3496
+ const out = await pjPost({ action: "import", project: doc, name });
3497
+ if (!out) return;
3498
+ pj.view = "active"; pj.mode = "detail"; pj.sel = out.id;
3499
+ toast(`Imported “${out.project.name}” — its media must be in media/ (Relink finds moved files)`);
3500
+ await pjLoad();
3501
+ }
3502
+ /* Versions of one project (history.js on the server), shown in the dashboard's
3503
+ main area in place of the cards. Restoring never loses anything: the server
3504
+ saves what was there as a version first. */
3505
+ const VER_KIND = { manual: "", auto: "Auto", agent: "Agent", restore: "Before restore" };
3506
+ /** Drop the open comparisons, and any still on their way: they were against an older state. */
3507
+ function pjDropDiffs() { pj.verDiff.clear(); pj.verDiffGen++; }
3508
+ async function pjLoadVersions() {
3509
+ const id = pj.verOf;
3510
+ if (!id) return;
3511
+ const seq = pj.verSeq = (pj.verSeq || 0) + 1;
3512
+ // only the newest request for the project still shown may change the list
3513
+ const current = () => seq === pj.verSeq && pj.verOf === id;
3514
+ try {
3515
+ const res = await fetch("/api/versions?project=" + encodeURIComponent(id), { cache: "no-store" });
3516
+ const data = await res.json();
3517
+ if (!res.ok) throw new Error(data.error);
3518
+ if (!current()) return;
3519
+ pj.versions = data.versions || [];
3520
+ } catch (e) {
3521
+ if (!current()) return;
3522
+ pj.versions = []; toast("Versions: " + (e.message || "couldn't read them"));
3523
+ }
3524
+ // what is being typed in Save version survives the repaint
3525
+ const draft = { name: $("verName")?.value, note: $("verNote")?.value, focus: document.activeElement?.id };
3526
+ renderProjectGrid();
3527
+ if (draft.name != null && $("verName")) $("verName").value = draft.name;
3528
+ if (draft.note != null && $("verNote")) $("verNote").value = draft.note;
3529
+ if ((draft.focus === "verName" || draft.focus === "verNote") && $(draft.focus)) $(draft.focus).focus();
3530
+ }
3531
+ function pjVersionsHtml() {
3532
+ const p = pj.list.find((x) => x.id === pj.verOf) || { name: "Project" };
3533
+ const rows = pj.versions.map((v) => {
3534
+ const diff = pj.verDiff.get(v.v);
3535
+ return `<div class="ver-row${v.final ? " final" : ""}" data-ver="${v.v}">
3536
+ <div class="ver-main">
3537
+ <span class="ver-num">v${v.v}</span>
3538
+ <span class="ver-name" title="${escapeHtml(v.name)}">${escapeHtml(v.name)}</span>
3539
+ ${v.final ? `<span class="ver-badge final">Final</span>` : ""}
3540
+ ${VER_KIND[v.kind] ? `<span class="ver-badge">${VER_KIND[v.kind]}</span>` : ""}
3541
+ <span class="ver-meta dim">${pjAgo(v.created)} · ${pjFmtDur(v.duration)} · ${v.clips} clip${v.clips === 1 ? "" : "s"}</span>
3542
+ </div>
3543
+ ${v.note ? `<div class="ver-note">${escapeHtml(v.note)}</div>` : ""}
3544
+ ${diff ? `<ul class="ver-diff">${diff.length ? diff.map((l) => `<li>${escapeHtml(l)}</li>`).join("") : "<li>Same as now.</li>"}</ul>` : ""}
3545
+ <div class="ver-actions">
3546
+ <button type="button" class="btn tiny" data-ver-act="diff">${diff ? "Hide changes" : "Compare with now"}</button>
3547
+ <button type="button" class="btn tiny" data-ver-act="restore" title="Put this version back. What is there now is saved as a version first.">Restore…</button>
3548
+ <button type="button" class="btn tiny" data-ver-act="final">${v.final ? "Unmark final" : "Mark final"}</button>
3549
+ <button type="button" class="btn tiny" data-ver-act="rename">Rename</button>
3550
+ <a class="btn tiny" href="/api/versions/file?project=${encodeURIComponent(pj.verOf)}&version=${v.v}" download>Download</a>
3551
+ <button type="button" class="btn tiny danger-ghost" data-ver-act="delete"${v.final ? ` disabled title="Unmark it as final first"` : ""}>Delete…</button>
3552
+ </div>
3553
+ </div>`;
3554
+ }).join("");
3555
+ return `<div class="ver-view">
3556
+ <div class="ver-head">
3557
+ <button type="button" class="btn tiny" data-ver-act="back">← All projects</button>
3558
+ <h3>Versions of ${escapeHtml(p.name)}</h3>
3559
+ </div>
3560
+ <div class="ver-save">
3561
+ <input type="text" id="verName" maxlength="120" placeholder="Name (optional), e.g. Client cut" spellcheck="false" aria-label="Version name">
3562
+ <input type="text" id="verNote" maxlength="2000" placeholder="Note (optional)" aria-label="Version note">
3563
+ <button type="button" class="btn primary" data-ver-act="save">Save version</button>
3564
+ </div>
3565
+ <p class="dim ver-hint">Versions are also saved on their own every 10 minutes while the project changes, and before an agent edits it.${p.active ? " Ctrl/Cmd+S saves one from anywhere in the editor." : ""}</p>
3566
+ ${rows || `<div class="pj-empty dim">No versions yet. Save one to have a point to come back to.</div>`}
3567
+ </div>`;
3568
+ }
3569
+ async function pjVersionAction(act, btn) {
3570
+ if (act === "back") { pj.verOf = null; pjDropDiffs(); renderProjects(); return; }
3571
+ if (pj.busy) return;
3572
+ // busy from before the first await, so a second click can't start the same action again
3573
+ if (act === "rename") return pjVersionRun(act, btn);
3574
+ pj.verPending = false;
3575
+ await pjBusy(() => pjVersionRun(act, btn));
3576
+ if (pj.verPending && pj.verOf) { pj.verPending = false; pjDropDiffs(); pjLoadVersions(); } // changed elsewhere meanwhile
3577
+ }
3578
+ async function pjVersionRun(act, btn) {
3579
+ const p = pj.list.find((x) => x.id === pj.verOf);
3580
+ if (!p) return;
3581
+ const row = btn.closest("[data-ver]"), v = row ? +row.dataset.ver : null;
3582
+ const post = (body) => fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ project: p.id, ...body }) })
3583
+ .then(async (r) => { const out = await r.json().catch(() => ({})); if (!r.ok) { toast(out.error || "Versions: request failed"); return null; } return out; })
3584
+ .catch(() => { toast("Versions: the editor server did not answer"); return null; });
3585
+ if (act === "save") {
3586
+ if (p.active && !(await flushSaveForVersion("no version was made"))) return;
3587
+ const out = await post({ action: "save", name: $("verName")?.value, note: $("verNote")?.value });
3588
+ if (out) {
3589
+ toast(`Saved v${out.version.v} “${out.version.name}”`);
3590
+ for (const id of ["verName", "verNote"]) if ($(id)) $(id).value = ""; // saved: not a draft any more
3591
+ await pjLoadVersions();
3592
+ }
3593
+ return;
3594
+ }
3595
+ if (act === "diff") {
3596
+ if (pj.verDiff.has(v)) { pj.verDiff.delete(v); renderProjectGrid(); return; }
3597
+ // compare with what is on screen, or not at all
3598
+ if (p.active && !(await flushSaveForVersion("the comparison would miss it"))) return;
3599
+ const gen = pj.verDiffGen, of = pj.verOf;
3600
+ const out = await post({ action: "diff", version: v });
3601
+ if (out && gen === pj.verDiffGen && of === pj.verOf) { pj.verDiff.set(v, out.lines); renderProjectGrid(); }
3602
+ return;
3603
+ }
3604
+ if (act === "restore") {
3605
+ if (btn.dataset.armed !== "1") {
3606
+ btn.dataset.armed = "1"; btn.textContent = "Click again to restore";
3607
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Restore…"; } }, 3000);
3608
+ return;
3609
+ }
3610
+ if (p.active && state.exporting) { toast("Wait for the export to finish before restoring"); return; }
3611
+ if (p.active && !(await flushSaveForVersion("nothing was restored"))) return;
3612
+ const out = await post({ action: "restore", version: v });
3613
+ if (!out) return;
3614
+ if (p.active) {
3615
+ // the undo steps describe the document before the restore
3616
+ runtime.undo.length = 0; runtime.redo.length = 0;
3617
+ await syncFromServer(true);
3618
+ }
3619
+ pjDropDiffs();
3620
+ toast(`Restored v${out.restored.v}. What was there is kept as v${out.saved.v}`);
3621
+ await pjLoad(); // the card and details show the restored project
3622
+ await pjLoadVersions();
3623
+ return;
3624
+ }
3625
+ if (act === "final") {
3626
+ const e = pj.versions.find((x) => x.v === v);
3627
+ const out = await post({ action: "update", version: v, final: !e?.final });
3628
+ if (out) await pjLoadVersions();
3629
+ return;
3630
+ }
3631
+ if (act === "rename") {
3632
+ const name = row.querySelector(".ver-name");
3633
+ if (!name || name.querySelector("input")) return;
3634
+ const e = pj.versions.find((x) => x.v === v);
3635
+ name.innerHTML = `<input type="text" class="ver-rename" maxlength="120" value="${escapeHtml(e?.name || "")}" spellcheck="false" aria-label="Version name">`;
3636
+ const inp = name.querySelector("input");
3637
+ inp.focus(); inp.select();
3638
+ const done = async (keep) => {
3639
+ if (inp.dataset.done) return;
3640
+ inp.dataset.done = "1";
3641
+ const val = inp.value.trim();
3642
+ if (keep && val && val !== e?.name) await post({ action: "update", version: v, name: val });
3643
+ await pjLoadVersions();
3644
+ };
3645
+ // Enter / Esc reach it through the dashboard's key handler (initProjectsUi): they blur it
3646
+ inp.addEventListener("blur", () => done(!inp.dataset.cancel));
3647
+ return;
3648
+ }
3649
+ if (act === "delete") {
3650
+ if (btn.dataset.armed !== "1") {
3651
+ btn.dataset.armed = "1"; btn.textContent = "Click again to delete";
3652
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Delete…"; } }, 3000);
3653
+ return;
3654
+ }
3655
+ const out = await post({ action: "delete", version: v });
3656
+ if (out) { pj.verDiff.delete(v); await pjLoadVersions(); }
3657
+ }
3658
+ }
3659
+ /* Ctrl/Cmd+S: keep the open project as it is now. */
3660
+ let versionSaving = false;
3661
+ async function saveVersionNow() {
3662
+ if (versionSaving) return; // one at a time
3663
+ versionSaving = true;
3664
+ try {
3665
+ const project = runtime.projectId; // another tab may open another project meanwhile
3666
+ if (!(await flushSaveForVersion("no version was made"))) return;
3667
+ const res = await fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "save", ...(project && project !== "?" ? { project } : {}) }) });
3668
+ const out = await res.json().catch(() => ({}));
3669
+ if (!res.ok) { toast(out.error || "Couldn't save a version"); return; }
3670
+ toast(`Saved v${out.version.v} “${out.version.name}” · Projects → Versions to go back to it`);
3671
+ } catch { toast("Couldn't save a version: the editor server did not answer"); }
3672
+ finally { versionSaving = false; }
3673
+ }
3674
+ /** Write the open project's pending edit before a version action; false (with a toast) when it didn't land. */
3675
+ async function flushSaveForVersion(skipped) {
3676
+ if (await flushSave()) return true;
3677
+ toast(`Your last change couldn't be saved, so ${skipped}. Try again in a moment.`);
3678
+ return false;
3679
+ }
3680
+ /* Called by syncFromServer when ./project.json is now another project. */
3681
+ function onProjectSwitched() {
3682
+ runtime.projectGen = (runtime.projectGen || 0) + 1; // loads started before now no longer write the caches
3683
+ // queued exports carry the old project's settings and names: they don't render this one
3684
+ const queued = exportQueue.length;
3685
+ for (let i = exportQueue.length - 1; i >= 0; i--)
3686
+ if (["pending", "failed", "cancelled"].includes(exportQueue[i].status)) exportQueue.splice(i, 1); // Retry would render this project
3687
+ if (exportQueue.length !== queued) { renderQueue(); toast("Queued exports of the previous project were removed"); }
3688
+ if (runtime.saveTimer) { clearTimeout(runtime.saveTimer); runtime.saveTimer = null; } // an edit of the old project
3689
+ runtime.saveFailed = false;
3690
+ runtime.undo.length = 0; runtime.redo.length = 0;
3691
+ runtime.seqUndo.clear(); runtime.seqOpen = null;
3692
+ state.compCtx = null;
3693
+ clearSource();
3694
+ setSelection([]);
3695
+ // players, pictures, waveforms and proxy states are keyed by media / clip id, which a
3696
+ // duplicate or a template shares with a different file: rebuild them for this project
3697
+ pause();
3698
+ for (const id of [...runtime.clipEls.keys()]) releaseClipEl(id);
3699
+ runtime.mediaAux.clear();
3700
+ runtime.wavePeaks.clear();
3701
+ proxyStatus.clear();
3702
+ }
3703
+ function initProjectsUi() {
3704
+ const ov = $("projectsOverlay"), btn = $("btnProjectsDash");
3705
+ if (!ov || !btn || ov.dataset.wired) return;
3706
+ ov.dataset.wired = "1";
3707
+ btn.classList.remove("hidden");
3708
+ btn.addEventListener("click", openProjects);
3709
+ els.projectName?.classList.add("clickable");
3710
+ els.projectName?.setAttribute("title", "Projects");
3711
+ els.projectName?.addEventListener("click", openProjects);
3712
+ $("pjClose").addEventListener("click", closeProjects);
3713
+ ov.addEventListener("click", (e) => { if (e.target === ov) closeProjects(); });
3714
+ // capture on window: wherever focus is while the dashboard is up, the editor's shortcuts stay out of it
3715
+ window.addEventListener("keydown", (e) => {
3716
+ if (!projectsOpen()) return;
3717
+ e.stopPropagation();
3718
+ if ((e.ctrlKey || e.metaKey) && (e.key === "o" || e.key === "O")) {
3719
+ e.preventDefault(); closeProjects(); // not the browser's Open File dialog
3720
+ } else if ((e.ctrlKey || e.metaKey) && (e.key === "s" || e.key === "S")) {
3721
+ e.preventDefault(); // not the browser's Save Page dialog
3722
+ if (!e.repeat) saveVersionNow().then(() => { if (pj.verOf) pjLoadVersions(); }); // holding the keys makes one
3723
+ } else if (e.target.classList?.contains("ver-rename") && (e.key === "Enter" || e.key === "Escape")) {
3724
+ e.preventDefault();
3725
+ if (e.key === "Escape") e.target.dataset.cancel = "1";
3726
+ e.target.blur();
3727
+ } else if (e.key === "Enter" && (e.target.id === "verName" || e.target.id === "verNote")) {
3728
+ e.preventDefault(); pjVersionAction("save", e.target);
3729
+ } else if (e.key === "Escape") {
3730
+ e.preventDefault();
3731
+ if (pj.mode === "new") { pj.mode = "detail"; renderProjects(); }
3732
+ else if (pj.verOf) { pj.verOf = null; pjDropDiffs(); renderProjects(); }
3733
+ else closeProjects();
3734
+ } else if ((e.key === "Enter" || e.key === " ") && e.target.dataset?.pjTpldel) {
3735
+ e.preventDefault(); e.target.click();
3736
+ } else if (e.key === "Enter" && e.target.dataset?.pj) {
3737
+ e.preventDefault(); pjOpenProject(e.target.dataset.pj);
3738
+ } else if (e.key === "Enter" && e.target.id === "pjNewName") {
3739
+ e.preventDefault(); pjAction("new-create");
3740
+ } else if (e.key === "Enter" && (e.target.id === "pjName" || e.target.id === "pjTags")) {
3741
+ e.preventDefault(); e.target.blur();
3742
+ } else if (e.key === "Enter" && e.target.id === "pjTplName") {
3743
+ e.preventDefault(); pjAction("template-save");
3744
+ }
3745
+ }, true);
3746
+ for (const b of ov.querySelectorAll("[data-pj-view]")) b.addEventListener("click", () => {
3747
+ if (pj.view === b.dataset.pjView && pj.mode === "detail") return;
3748
+ pj.view = b.dataset.pjView; pj.mode = "detail"; pj.verOf = null; pj.list = []; renderProjects(); pjLoad();
3749
+ });
3750
+ $("pjNewBtn").addEventListener("click", () => {
3751
+ pj.mode = pj.mode === "new" ? "detail" : "new";
3752
+ renderProjects();
3753
+ if (pj.mode === "new") $("pjNewName")?.select();
3754
+ });
3755
+ $("pjSearch").addEventListener("input", (e) => { pj.search = e.target.value; renderProjectGrid(); });
3756
+ $("pjSort").addEventListener("change", (e) => { pj.sort = e.target.value; renderProjectGrid(); });
3757
+ $("pjImportFile").addEventListener("change", (e) => { const f = e.target.files?.[0]; e.target.value = ""; if (f) pjImport(f); });
3758
+ $("pjGrid").addEventListener("click", (e) => {
3759
+ const vact = e.target.closest("[data-ver-act]");
3760
+ if (vact) { if (!vact.disabled) pjVersionAction(vact.dataset.verAct, vact); return; }
3761
+ const card = e.target.closest("[data-pj]");
3762
+ if (!card) return;
3763
+ // only the selection changes: re-rendering the cards would swallow a double-click
3764
+ pj.sel = card.dataset.pj; pj.mode = "detail";
3765
+ for (const c of $("pjGrid").querySelectorAll(".pj-card")) c.classList.toggle("sel", c === card);
3766
+ renderProjectSide();
3767
+ });
3768
+ $("pjGrid").addEventListener("dblclick", (e) => { const card = e.target.closest("[data-pj]"); if (card && pj.view === "active") pjOpenProject(card.dataset.pj); });
3769
+ const side = $("pjSide");
3770
+ side.addEventListener("click", async (e) => {
3771
+ const bk = e.target.closest("[data-pj-backup]");
3772
+ if (bk && !bk.dataset.flushed) {
3773
+ // the open project: write its pending edit, then download
3774
+ e.preventDefault();
3775
+ if (!(await flushSaveForVersion("the backup would miss it"))) return;
3776
+ bk.dataset.flushed = "1"; bk.click(); delete bk.dataset.flushed;
3777
+ return;
3778
+ }
3779
+ const del = e.target.closest("[data-pj-tpldel]");
3780
+ if (del) {
3781
+ e.stopPropagation();
3782
+ if (del.dataset.armed !== "1") { del.dataset.armed = "1"; del.textContent = "Delete?"; setTimeout(() => { if (del.isConnected) { del.dataset.armed = ""; del.textContent = "✕"; } }, 3000); return; }
3783
+ const out = await pjPost({ action: "delete_template", template: del.dataset.pjTpldel });
3784
+ if (out) { if (pj.tpl === del.dataset.pjTpldel) pj.tpl = "landscape-1080"; await pjLoad(); }
3785
+ return;
3786
+ }
3787
+ const tpl = e.target.closest("[data-pj-tpl]");
3788
+ if (tpl) {
3789
+ const keepName = $("pjNewName")?.value;
3790
+ pj.tpl = tpl.dataset.pjTpl; renderProjects();
3791
+ if (keepName != null && $("pjNewName")) $("pjNewName").value = keepName;
3792
+ return;
3793
+ }
3794
+ const act = e.target.closest("[data-pj-act]");
3795
+ if (act && !act.disabled) pjAction(act.dataset.pjAct, act);
3796
+ });
3797
+ side.addEventListener("focusout", (e) => {
3798
+ if (e.target.id === "pjName") pjSaveField("name");
3799
+ else if (e.target.id === "pjNotes") pjSaveField("notes");
3800
+ else if (e.target.id === "pjTags") pjSaveField("tags");
3801
+ });
3802
+ }
3803
+
3106
3804
  /* ═══════════════════════════ EDIT OPERATIONS ═══════════════════════════ */
3107
3805
  /* Undo entries are {clips, markers} snapshots. Drag gestures still push a bare
3108
3806
  clips array (taken at pointerdown) — restoring one leaves markers alone. */
@@ -3116,8 +3814,20 @@ function pushUndo(snap = undoSnapshot()) {
3116
3814
  if (runtime.undo.length > 100) runtime.undo.shift();
3117
3815
  runtime.redo.length = 0;
3118
3816
  }
3817
+ /** Does this undo step hold other sequences' clips (a top-level seqClips)? Parsed only when the text could say so. */
3818
+ function hasSeqClips(json) {
3819
+ if (typeof json !== "string" || !json.includes('"seqClips":')) return false;
3820
+ try { const snap = JSON.parse(json); return !!snap && typeof snap === "object" && !Array.isArray(snap) && Object.hasOwn(snap, "seqClips"); }
3821
+ catch { return false; }
3822
+ }
3823
+ /** The clips of the sequences that aren't open, by id — for the undo of an edit that reaches into them. */
3824
+ function otherSequenceClips() { return Object.fromEntries(SeqLib.others(seqRoot()).map((sq) => [sq.id, sq.clips || []])); }
3119
3825
  function restoreSnapshot(json) {
3120
3826
  const snap = JSON.parse(json);
3827
+ if (snap && snap.seqClips) {
3828
+ const open = SeqLib.activeId(seqRoot());
3829
+ for (const [id, clips] of Object.entries(snap.seqClips)) { const sq = SeqLib.find(seqRoot(), id); if (sq && id !== open) sq.clips = clips; }
3830
+ }
3121
3831
  if (Array.isArray(snap)) project.clips = snap;
3122
3832
  else {
3123
3833
  project.clips = snap.clips; project.markers = snap.markers; if (snap.comps) project.comps = snap.comps;
@@ -3135,7 +3845,8 @@ function restoreSnapshot(json) {
3135
3845
  * (removing, relinking or replacing media), so redo puts it back too. */
3136
3846
  function counterSnapshot(snap) {
3137
3847
  if (!snap.includes('"media":')) return undoSnapshot();
3138
- return JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media });
3848
+ return JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media,
3849
+ ...(hasSeqClips(snap) ? { seqClips: otherSequenceClips() } : {}) });
3139
3850
  }
3140
3851
  function undo() {
3141
3852
  if (!runtime.undo.length) return;
@@ -4285,9 +4996,29 @@ function rebuildClips() {
4285
4996
  if (hasWave) drawClipWave(div.querySelector(".wave"), c, tr.h);
4286
4997
  }
4287
4998
  paintAudioOverlaps();
4999
+ paintSilences();
4288
5000
  state.dirtyTimeline = false;
4289
5001
  updateWorkArea();
4290
5002
  }
5003
+ /* The silences Find marked: a band on each lane of the clips that were listened to. */
5004
+ function paintSilences() {
5005
+ const s = state.silence;
5006
+ if (!s) return;
5007
+ if (s.sig !== silenceSig()) { state.silence = null; return; } // the timeline moved on: they no longer line up
5008
+ const lanes = new Set(withLinked(project.clips.filter((c) => s.ids.includes(c.id))).map((c) => c.track));
5009
+ for (const id of lanes) {
5010
+ const row = els.tracks.querySelector(`[data-track="${id}"]`);
5011
+ if (!row) continue;
5012
+ for (const sp of s.spans) {
5013
+ const el = document.createElement("div");
5014
+ el.className = "silence-span";
5015
+ el.style.left = (sp.from * state.pps) + "px";
5016
+ el.style.width = Math.max(2, (sp.to - sp.from) * state.pps) + "px";
5017
+ el.title = `Silence ${fmt(sp.from)} → ${fmt(sp.to)} (${(sp.to - sp.from).toFixed(2)} s) · Inspector → Silence → Cut`;
5018
+ row.appendChild(el);
5019
+ }
5020
+ }
5021
+ }
4291
5022
  /* Hatched bands where two+ audio clips share a track (CSS draw, O(n²) per track). */
4292
5023
  function paintAudioOverlaps() {
4293
5024
  const byTrack = new Map();
@@ -5949,6 +6680,22 @@ function renderInspector(lite) {
5949
6680
  ${slider("speed", 0.25, 4, 0.05, p.speed, "×")}
5950
6681
  </div>`;
5951
6682
  }
6683
+ if ((c.kind === "video" || c.kind === "audio") && typeof FableCutSilence !== "undefined") {
6684
+ const so = silenceOptions(), found = state.silence;
6685
+ const num = (k, lo, hi, step, unit, title) => `<span class="insp-ctrls"><input type="number" data-sil="${k}" min="${lo}" max="${hi}" step="${step}" value="${so[k]}" title="${title}" style="max-width:64px"> ${unit}</span>`;
6686
+ html += `<div class="insp-section"><h3>Silence</h3>
6687
+ ${row("Below", num("threshold", -80, -10, 1, "dB", "Quieter than this counts as silence (dBFS). Raise it toward −30 in a noisy room"))}
6688
+ ${row("At least", num("minSilence", 0.1, 10, 0.1, "s", "Shorter pauses are left alone"))}
6689
+ ${row("Keep", num("padding", 0, 2, 0.05, "s beside speech", "Quiet kept before and after each phrase, so words aren't clipped"))}
6690
+ ${row("", state.silenceBusy
6691
+ ? `<span class="insp-ctrls"><span style="opacity:.75">Listening…</span>
6692
+ <button type="button" class="btn tiny" data-sil-clear title="Stop listening">Cancel</button></span>`
6693
+ : `<span class="insp-ctrls"><button type="button" class="btn tiny" data-sil-find title="Listen to the selected clips and mark their silences on the timeline">Find</button>
6694
+ ${found ? `<button type="button" class="btn tiny" data-sil-cut title="Extract every marked silence on the targeted tracks (one undo step)">Cut ${found.spans.length}</button>
6695
+ <button type="button" class="btn tiny" data-sil-clear title="Remove the marks">Clear</button>` : ""}</span>`)}
6696
+ ${found ? `<div class="insp-note">${found.spans.length} silence${found.spans.length === 1 ? "" : "s"}, ${FableCutSilence.total(found.spans).toFixed(1)} s, marked on the timeline. Cut extracts them on the targeted tracks — lock the music bed first to keep it running.</div>` : ""}
6697
+ </div>`;
6698
+ }
5952
6699
  if (c.kind === "audio" && typeof FableCutFx !== "undefined") {
5953
6700
  html += `<div class="insp-section" data-fx-section><h3>Audio effects</h3>${fxEditorHtml(c.fx, playheadOverClip(c) ? state.time - c.start : null)}</div>`;
5954
6701
  }
@@ -6034,7 +6781,11 @@ function renderInspector(lite) {
6034
6781
  ${row("Title style", `<button type="button" class="btn tiny style-picker-btn" data-style-open title="Pick a style — hover to preview it live">${(TITLE_STYLES[c.styleName] || {}).label || "Choose…"} ▾</button>
6035
6782
  <button class="btn tiny" data-action="title-shuffle" title="Random style">Shuffle</button>`)}
6036
6783
  ${row("Animation", `<select data-k="textAnim">${TEXT_ANIMS.map((a) => `<option ${a === p.textAnim ? "selected" : ""}>${a}</option>`).join("")}</select>`, "", "textAnim")}
6037
- ${slider("wordRate", 0.05, 0.6, 0.01, p.wordRate, "s")}
6784
+ ${p.textAnim === "highlight" ? row("Highlight", `<input type="color" data-k="highlightColor" value="${p.highlightColor || "#ffd166"}" title="The colour of the word being said">`, "", "highlightColor") : ""}
6785
+ ${Array.isArray(p.wordTimes) && p.wordTimes.length ? `<div class="insp-note">${p.caption ? "Caption: its" : "Its"} ${p.wordTimes.length} words follow the speech${
6786
+ String(p.text || "").split(/\s+/).filter(Boolean).length === p.wordTimes.length ? ", so Word rate doesn't apply"
6787
+ : " — the text now has another number of words, so they are spread over the clip; Add captions again to re-time them"}.</div>`
6788
+ : slider("wordRate", 0.05, 0.6, 0.01, p.wordRate, "s")}
6038
6789
  </div>`;
6039
6790
  }
6040
6791
  els.inspector.innerHTML = html;
@@ -6160,6 +6911,18 @@ function renderInspector(lite) {
6160
6911
  const sel = selectedClips();
6161
6912
  clearDuck(sel.length ? sel : [c]);
6162
6913
  });
6914
+ els.inspector.querySelectorAll("[data-sil]").forEach((inp) => inp.addEventListener("change", () => {
6915
+ const o = silenceOptions(), [lo, hi] = FableCutSilence.LIMITS[inp.dataset.sil];
6916
+ o[inp.dataset.sil] = clamp(+inp.value || 0, lo, hi);
6917
+ inp.value = o[inp.dataset.sil];
6918
+ try { localStorage.setItem(SILENCE_KEY, JSON.stringify(o)); } catch { }
6919
+ }));
6920
+ els.inspector.querySelector("[data-sil-find]")?.addEventListener("click", () => {
6921
+ const sel = selectedClips();
6922
+ findSilences(sel.length ? sel : [c]);
6923
+ });
6924
+ els.inspector.querySelector("[data-sil-cut]")?.addEventListener("click", cutSilences);
6925
+ els.inspector.querySelector("[data-sil-clear]")?.addEventListener("click", clearSilences);
6163
6926
  els.inspector.querySelector("[data-norm-target]")?.addEventListener("change", (e) => {
6164
6927
  try { localStorage.setItem(NORMALIZE_KEY, e.target.value); } catch { }
6165
6928
  });
@@ -7893,13 +8656,14 @@ function setDuckKeys(c, keys) {
7893
8656
  }
7894
8657
  /** Timeline spans with sound on the voice clips (each measured after its
7895
8658
  * channel routing, scaled by its clip gain and static volume). */
7896
- async function voiceRegions(voices, threshold) {
8659
+ async function voiceRegions(voices, threshold, minLen, heard) {
7897
8660
  const lists = [];
7898
8661
  for (const v of voices) {
7899
8662
  const m = getMedia(v.mediaId);
7900
8663
  if (!m) continue;
7901
8664
  let buf;
7902
8665
  try { buf = await getAudioBuffer(m); } catch { continue; }
8666
+ heard?.add(v.id); // read and measured: its quiet is real quiet, not a file that failed to decode
7903
8667
  const a = clamp(Math.floor(v.in * buf.sampleRate), 0, buf.length);
7904
8668
  const b = clamp(Math.ceil(mediaTimeAt(v, clipEnd(v)) * buf.sampleRate), a, buf.length);
7905
8669
  const src = [];
@@ -7908,9 +8672,663 @@ async function voiceRegions(voices, threshold) {
7908
8672
  lists.push(FableCutDucking.activeRegions(env, {
7909
8673
  t0: v.start, speed: clipSpeed(v), threshold,
7910
8674
  gain: dbToGain(clipGainDb(v)) * clamp(+(v.props?.volume ?? 1), 0, VOL_MAX),
8675
+ ...(minLen != null ? { minLen } : {}),
7911
8676
  }));
7912
8677
  }
7913
- return FableCutDucking.mergeRegions(lists);
8678
+ // silence wants every pause, so nothing is bridged there; ducking bridges short gaps
8679
+ return FableCutDucking.mergeRegions(lists, minLen != null ? 0 : undefined);
8680
+ }
8681
+
8682
+ /* ── Silence (silence.js): find the pauses in speech, mark them on the
8683
+ timeline, cut them out with Extract — the same spans and ops as
8684
+ fablecut_silence. ── */
8685
+ const SILENCE_KEY = "fablecut-silence";
8686
+ function silenceOptions() {
8687
+ try { return FableCutSilence.options(JSON.parse(localStorage.getItem(SILENCE_KEY) || "{}")); }
8688
+ catch { return { ...FableCutSilence.DEFAULTS }; }
8689
+ }
8690
+ /** Each linked group's audio stems, else the clip itself (audio, or a video without stems). */
8691
+ function speechGroups(clips) {
8692
+ const groups = new Map();
8693
+ for (const c of clips) {
8694
+ if (c.kind !== "audio" && c.kind !== "video") continue;
8695
+ const key = c.linkGroup || c.id;
8696
+ if (groups.has(key)) continue;
8697
+ const stems = withLinked([c]).filter((x) => x.kind === "audio");
8698
+ groups.set(key, stems.length ? stems : [c]);
8699
+ }
8700
+ return [...groups.values()];
8701
+ }
8702
+ /** Everything the marks were found from — where each clip sits, its file, speed, level and switches, the
8703
+ * frame rate: marked silences only stand while this is unchanged. */
8704
+ function silenceSig() {
8705
+ return project.fps + "#" + project.clips.map((c) => JSON.stringify([c.id, c.track, c.start, c.in, c.duration, c.mediaId,
8706
+ getMedia(c.mediaId)?.src ?? null, c.linkGroup ?? null, c.props?.speed ?? 1, c.keyframes?.speed ?? null,
8707
+ c.props?.gain ?? 0, c.props?.volume ?? 1, c.props?.audioChannel ?? null, c.props?.channelMode ?? null,
8708
+ clipRenders(c) ? 1 : 0])).join("|");
8709
+ }
8710
+ let silenceGen = 0; // the newest Find: an older one still decoding never replaces its result
8711
+ async function findSilences(clips, opts = silenceOptions()) {
8712
+ if (typeof FableCutSilence === "undefined") { toast("Silence module missing — reload the editor"); return; }
8713
+ // a new Find replaces the old marks whatever it finds, so Cut never acts on another clip's result
8714
+ const gen = ++silenceGen;
8715
+ if (state.silence) { state.silence = null; state.dirtyTimeline = true; renderInspector(); }
8716
+ const all = speechGroups(clips).map((g) => g.filter(clipRenders)).filter((g) => g.length);
8717
+ if (!all.length) { toast("Select a clip with sound to find its silences"); return; }
8718
+ // a speed ramp moves the sound along the timeline unevenly: those clips are left alone
8719
+ const groups = all.filter((g) => !g.some(FableCutSilence.ramped));
8720
+ if (!groups.length) { toast("These clips have a speed ramp — silence removal works on clips at a steady speed"); return; }
8721
+ toast("Listening for silences…");
8722
+ const sig = silenceSig(), heard = new Set();
8723
+ state.silenceBusy = true; // the Inspector shows Listening… with Cancel meanwhile
8724
+ renderInspector();
8725
+ let sound;
8726
+ try { sound = await voiceRegions(groups.flat(), opts.threshold, FableCutSilence.MIN_SOUND, heard); }
8727
+ finally { if (gen === silenceGen) state.silenceBusy = false; }
8728
+ if (gen !== silenceGen) return; // a newer Find took over, or Cancel
8729
+ renderInspector(); // Listening… → Find again, whatever comes next
8730
+ // the timeline moved while it listened: these spans belong to the old one
8731
+ if (silenceSig() !== sig) { toast("The timeline changed while listening — find the silences again"); return; }
8732
+ // a clip whose audio couldn't be read is not silent: leave its time alone
8733
+ const usable = groups.filter((g) => g.every((x) => heard.has(x.id)));
8734
+ if (!usable.length) { toast("Couldn't read the audio of these clips — nothing marked"); return; }
8735
+ const ranges = usable.map((g) => [Math.min(...g.map((x) => x.start)), Math.max(...g.map(clipEnd))]);
8736
+ const spans = FableCutSilence.silentSpans(sound, ranges, { ...opts, fps: project.fps });
8737
+ state.silence = spans.length ? { ids: usable.flat().map((x) => x.id), spans, sig } : null;
8738
+ state.dirtyTimeline = true;
8739
+ renderInspector();
8740
+ toast((spans.length
8741
+ ? `${spans.length} silence${spans.length === 1 ? "" : "s"}, ${FableCutSilence.total(spans).toFixed(1)} s — marked on the timeline`
8742
+ : "No silences that long — try a higher threshold or a shorter minimum") +
8743
+ (usable.length < groups.length ? " · some clips' audio couldn't be read, so their time is left alone" : "") +
8744
+ (groups.length < all.length ? " · clips with a speed ramp are left alone" : ""));
8745
+ }
8746
+ /** Extract every marked silence on the targeted tracks, last first: one undo step. */
8747
+ function cutSilences() {
8748
+ const s = state.silence;
8749
+ // the marks dropped when the timeline changed (the button can outlive them until the Inspector redraws)
8750
+ if (!s) { renderInspector(); toast("The timeline changed — find the silences again"); return; }
8751
+ if (s.sig !== silenceSig()) { state.silence = null; renderInspector(); toast("The timeline changed — find the silences again"); return; }
8752
+ const snap = undoSnapshot();
8753
+ let cut = 0, secs = 0;
8754
+ for (const sp of s.spans.slice().sort((a, b) => b.from - a.from)) {
8755
+ if (!EDIT.liftRange(sp.from, sp.to, true)) { cut++; secs += sp.to - sp.from; }
8756
+ }
8757
+ state.silence = null;
8758
+ if (!cut) { state.dirtyTimeline = true; renderInspector(); toast("Nothing was cut — target the clip's tracks first"); return; }
8759
+ pushUndo(snap);
8760
+ pruneSelection();
8761
+ state.dirtyTimeline = true;
8762
+ scheduleSave();
8763
+ renderInspector();
8764
+ toast(`Cut ${cut} silence${cut === 1 ? "" : "s"} · ${secs.toFixed(1)} s shorter`);
8765
+ }
8766
+
8767
+ /* ── Transcripts (transcribe.js, transcribe-worker.js): speech → words in this
8768
+ browser with Whisper, kept per file by the server (analysis/transcripts/).
8769
+ The Transcript tab shows the timeline's words: click one to go there, select
8770
+ some and press Delete (or Cut) to extract them, find a phrase and cut every
8771
+ time it is said — the same spans and extract ops as fablecut_transcribe. ── */
8772
+ const TRANSCRIBE_KEY = "fablecut-transcribe";
8773
+ const trState = { open: false, built: false, busy: null, sig: "", words: [], sel: null, anchor: null, drag: false, query: "", hits: [], now: -1 };
8774
+ const transcriptCache = new Map(); // src → validated transcript | false (none) | Promise while asking the server
8775
+ let transcriptGen = 0; // bumps whenever a transcript arrives or changes: the tab redraws
8776
+ function transcribeSettings() {
8777
+ let o = {};
8778
+ try { o = JSON.parse(localStorage.getItem(TRANSCRIBE_KEY) || "{}"); } catch { }
8779
+ let model = FableCutTranscribe.DEFAULT_MODEL, language = null, captionStyle = null;
8780
+ try { model = FableCutTranscribe.model(o.model); } catch { }
8781
+ try { language = FableCutTranscribe.language(o.language); } catch { }
8782
+ try { captionStyle = typeof FableCutCaptions !== "undefined" && o.captionStyle ? FableCutCaptions.style(o.captionStyle) : null; } catch { }
8783
+ return { model, language, captionStyle };
8784
+ }
8785
+ function saveTranscribeSettings(patch) {
8786
+ try { localStorage.setItem(TRANSCRIBE_KEY, JSON.stringify({ ...transcribeSettings(), ...patch })); } catch { }
8787
+ }
8788
+ /** The transcript of a file, if it is here already. */
8789
+ function transcriptOf(src) {
8790
+ const d = transcriptCache.get(src);
8791
+ return d && !(d instanceof Promise) ? d : null;
8792
+ }
8793
+ /** Ask the server for a file's transcript (once; `force` asks again). Resolves to it, or false. */
8794
+ function loadTranscript(src, force = false) {
8795
+ const have = transcriptCache.get(src);
8796
+ if (!force && have !== undefined) return have instanceof Promise ? have : Promise.resolve(have);
8797
+ const p = fetch("/api/transcript?src=" + encodeURIComponent(src)).then((r) => (r.ok ? r.json() : null))
8798
+ .then((j) => {
8799
+ let d = false;
8800
+ try { d = j && j.transcript ? FableCutTranscribe.validate(j.transcript) : false; } catch { }
8801
+ if (transcriptCache.get(src) === p) { transcriptCache.set(src, d); transcriptGen++; }
8802
+ return d;
8803
+ })
8804
+ .catch(() => { if (transcriptCache.get(src) === p) transcriptCache.set(src, false); return false; });
8805
+ transcriptCache.set(src, p);
8806
+ return p;
8807
+ }
8808
+ function onTranscriptEvent(data) {
8809
+ let src = null;
8810
+ try { src = JSON.parse(data).src; } catch { }
8811
+ if (!src) return;
8812
+ loadTranscript(src, true).then(() => renderTranscript(true));
8813
+ }
8814
+
8815
+ /* The worker: one at a time, each piece of audio answered in turn. */
8816
+ let trWorker = null, trSeq = 0, trIdleTimer = 0;
8817
+ const trPending = new Map();
8818
+ function transcribeWorker() {
8819
+ if (trWorker) return trWorker;
8820
+ trWorker = new Worker("transcribe-worker.js", { type: "module" });
8821
+ trWorker.onmessage = (e) => {
8822
+ const m = e.data || {};
8823
+ if (m.type === "progress") { onModelProgress(m); return; }
8824
+ const p = trPending.get(m.id);
8825
+ if (!p) return;
8826
+ trPending.delete(m.id);
8827
+ if (m.type === "done") p.resolve(m.chunks || []);
8828
+ else p.reject(new Error(/dynamically imported module|Failed to fetch|NetworkError|Load failed/i.test(m.error || "")
8829
+ ? "couldn't download the speech model — check the internet connection (it is needed the first time)"
8830
+ : m.error || "transcription failed"));
8831
+ };
8832
+ trWorker.onerror = (e) => {
8833
+ for (const p of trPending.values()) p.reject(new Error(e.message || "the speech worker failed to start"));
8834
+ trPending.clear();
8835
+ trWorker = null;
8836
+ };
8837
+ return trWorker;
8838
+ }
8839
+ function stopTranscribeWorker() {
8840
+ if (trWorker) { trWorker.terminate(); trWorker = null; }
8841
+ for (const p of trPending.values()) p.reject(new Error("cancelled"));
8842
+ trPending.clear();
8843
+ }
8844
+ function whisperPiece(pcm, model, language) {
8845
+ return new Promise((resolve, reject) => {
8846
+ const id = ++trSeq;
8847
+ trPending.set(id, { resolve, reject });
8848
+ transcribeWorker().postMessage({ type: "run", id, lib: FableCutTranscribe.LIBRARY, model: FableCutTranscribe.MODELS[model].id, pcm, language }, [pcm.buffer]);
8849
+ });
8850
+ }
8851
+ function onModelProgress(m) {
8852
+ const b = trState.busy;
8853
+ if (!b || !m.file) return;
8854
+ if (m.status === "done") { const f = b.dl.get(m.file); if (f) f.loaded = f.total; }
8855
+ else if (m.total > 0) b.dl.set(m.file, { loaded: m.loaded, total: m.total });
8856
+ b.beat?.();
8857
+ paintTranscribeBusy();
8858
+ }
8859
+ /** A file's sound as Whisper hears it: mono, 16 kHz. */
8860
+ async function speechPcm(m) {
8861
+ const buf = await getAudioBuffer(m);
8862
+ const R = FableCutTranscribe.RATE;
8863
+ const oc = new OfflineAudioContext(1, Math.max(1, Math.ceil(buf.duration * R)), R);
8864
+ const node = oc.createBufferSource();
8865
+ node.buffer = buf;
8866
+ node.connect(oc.destination);
8867
+ node.start();
8868
+ return { pcm: (await oc.startRendering()).getChannelData(0), duration: buf.duration };
8869
+ }
8870
+ /** Transcribe one file and save it on the server. Resolves to {doc, saved}. */
8871
+ async function transcribeFile(src, { model, language, onProgress, cancelled }) {
8872
+ const T = FableCutTranscribe, R = T.RATE;
8873
+ const m = project.media.find((x) => x.src === src) || { src };
8874
+ const { pcm, duration } = await speechPcm(m);
8875
+ const pieces = T.plan(pcm, R), words = [];
8876
+ for (let k = 0; k < pieces.length; k++) {
8877
+ if (cancelled()) throw new Error("cancelled");
8878
+ const [a, b] = pieces[k];
8879
+ if (!T.quiet(pcm, a, b)) words.push(...T.joinChunks(await whisperPiece(pcm.slice(a, b), model, language), a / R, b / R));
8880
+ onProgress((k + 1) / pieces.length);
8881
+ }
8882
+ const doc = T.validate({ src, model, language: language || "auto", duration, created: new Date().toISOString(), words });
8883
+ let saved = false;
8884
+ try { saved = (await fetch("/api/transcript?src=" + encodeURIComponent(src), { method: "POST", body: JSON.stringify(doc) })).ok; } catch { }
8885
+ transcriptCache.set(src, doc);
8886
+ transcriptGen++;
8887
+ return { doc, saved };
8888
+ }
8889
+ /** Transcribe files one after another. `beat(fraction)` hears about progress (an agent's job). */
8890
+ async function transcribeSrcs(srcs, opts = transcribeSettings(), beat = null) {
8891
+ if (trState.busy) throw new Error("this tab is already transcribing — wait for it, or cancel it");
8892
+ const busy = trState.busy = { srcs, i: 0, frac: 0, cancel: false, dl: new Map(), beat: () => beat?.((busy.i + busy.frac) / srcs.length) };
8893
+ const out = { done: [], failed: [], cancelled: false };
8894
+ renderTranscript(true);
8895
+ try {
8896
+ for (let i = 0; i < srcs.length; i++) {
8897
+ busy.i = i; busy.frac = 0;
8898
+ paintTranscribeBusy();
8899
+ busy.beat();
8900
+ try {
8901
+ const r = await transcribeFile(srcs[i], {
8902
+ ...opts, cancelled: () => busy.cancel,
8903
+ onProgress: (f) => { busy.frac = f; paintTranscribeBusy(); busy.beat(); },
8904
+ });
8905
+ out.done.push({ src: srcs[i], words: r.doc.words.length, language: r.doc.language, saved: r.saved });
8906
+ } catch (e) {
8907
+ if (busy.cancel) { out.cancelled = true; break; }
8908
+ out.failed.push({ src: srcs[i], error: String((e && e.message) || e) });
8909
+ }
8910
+ }
8911
+ } finally {
8912
+ trState.busy = null;
8913
+ renderTranscript(true);
8914
+ // the model holds a few hundred MB: let it go after a quiet minute (the browser keeps the download)
8915
+ clearTimeout(trIdleTimer);
8916
+ trIdleTimer = setTimeout(() => { if (!trState.busy) stopTranscribeWorker(); }, 60000);
8917
+ }
8918
+ return out;
8919
+ }
8920
+ function cancelTranscribe() {
8921
+ if (!trState.busy) return;
8922
+ trState.busy.cancel = true;
8923
+ stopTranscribeWorker();
8924
+ }
8925
+
8926
+ /** Each linked group that sounds (its audio stems, else the clip), as on the timeline. */
8927
+ function transcriptGroups() {
8928
+ return speechGroups(project.clips).map((g) => g.filter(clipRenders)).filter((g) => {
8929
+ const m = g.length && getMedia(g[0].mediaId);
8930
+ // a picture with its sound turned off, or a file with no audio stream, has nothing to say
8931
+ return m && m.audioChannels !== 0 && !(g.length === 1 && g[0].kind === "video" && +(g[0].props?.volume ?? 1) === 0);
8932
+ });
8933
+ }
8934
+ /** The timeline's words, every transcribed clip, in time order (transcribe.js layout). */
8935
+ function transcriptWords() {
8936
+ const entries = [];
8937
+ for (const g of transcriptGroups()) {
8938
+ const d = transcriptOf(getMedia(g[0].mediaId).src);
8939
+ if (d) entries.push({ clip: g[0], words: d.words });
8940
+ }
8941
+ return FableCutTranscribe.layout(entries);
8942
+ }
8943
+ /** What Transcribe works on: the selected clips' files, else every file on the timeline without a transcript. */
8944
+ function transcribeTargets() {
8945
+ const groups = transcriptGroups();
8946
+ const picked = new Set();
8947
+ for (const id of state.selIds) {
8948
+ const c = getClip(id);
8949
+ if (c && (c.kind === "video" || c.kind === "audio")) { const m = getMedia(c.mediaId); if (m) picked.add(m.src); }
8950
+ }
8951
+ const srcs = [...new Set(groups.map((g) => getMedia(g[0].mediaId).src))];
8952
+ const sel = srcs.filter((s) => picked.has(s));
8953
+ return sel.length ? { srcs: sel, selected: true } : { srcs: srcs.filter((s) => transcriptCache.get(s) === false), selected: false };
8954
+ }
8955
+ /** What the words' places depend on: the timeline and the transcripts. */
8956
+ function transcriptWordsSig() {
8957
+ return silenceSig() + "|" + transcriptGen;
8958
+ }
8959
+ /** What the tab shows: that, and the clip selection (the Transcribe button follows it). */
8960
+ function transcriptSig() {
8961
+ return transcriptWordsSig() + "|" + [...state.selIds].join(",");
8962
+ }
8963
+
8964
+ function buildTranscriptPage() {
8965
+ const T = FableCutTranscribe, root = els.transcriptPage, set = transcribeSettings();
8966
+ root.innerHTML = `<div class="tr-head">
8967
+ <div class="tr-row">
8968
+ <button type="button" class="btn primary" data-tr-go></button>
8969
+ <select data-tr-model title="Speech model. Base is quick; Small is more accurate and slower. Each downloads once, then stays in this browser">${Object.entries(T.MODELS).map(([k, m]) =>
8970
+ `<option value="${k}" ${k === set.model ? "selected" : ""}>${m.label} · ${m.mb} MB</option>`).join("")}</select>
8971
+ <select data-tr-lang title="The language spoken. Auto-detect works for most; pick it when a clip is short or mixes languages">
8972
+ <option value="auto">Auto-detect</option>${Object.entries(T.LANGUAGES).sort((a, b) => a[1].localeCompare(b[1])).map(([k, n]) =>
8973
+ `<option value="${k}" ${k === set.language ? "selected" : ""}>${n}</option>`).join("")}</select>
8974
+ </div>
8975
+ <div class="tr-busy hidden" data-tr-busy><span data-tr-busy-text></span><span class="tr-bar"><i data-tr-bar></i></span>
8976
+ <button type="button" class="btn tiny" data-tr-cancel title="Stop transcribing (what is done is kept)">Cancel</button></div>
8977
+ <div class="tr-row">
8978
+ <input type="search" data-tr-find placeholder="Find words…" spellcheck="false" title="A word or phrase; case and punctuation don't matter. Enter goes to the next one">
8979
+ <span class="tr-count" data-tr-count></span>
8980
+ <button type="button" class="btn tiny" data-tr-cut-found disabled title="Extract every place it is said, on the targeted tracks (one undo step)">Cut all</button>
8981
+ <button type="button" class="btn tiny" data-tr-copy title="Copy the transcript as text, with timecodes">Copy</button>
8982
+ </div>
8983
+ <div class="tr-row">
8984
+ <span class="tr-lbl">Captions</span>
8985
+ <select data-tr-cap-style title="The look: subtitle on a dark bar, karaoke (words light up as said), highlight (the word being said in colour), word pop (a few big words at a time)">${Object.entries(FableCutCaptions.STYLES).map(([k, st]) =>
8986
+ `<option value="${k}" ${k === (set.captionStyle || FableCutCaptions.DEFAULT_STYLE) ? "selected" : ""}>${st.label}</option>`).join("")}</select>
8987
+ <button type="button" class="btn tiny" data-tr-cap-add title="Make captions from these words, timed word by word, on a video lane above the edit (replaces the captions there; one undo step)">Add captions</button>
8988
+ <button type="button" class="btn tiny" data-tr-cap-file="srt" title="Download the timeline's captions as a SubRip file">SRT</button>
8989
+ <button type="button" class="btn tiny" data-tr-cap-file="vtt" title="Download the timeline's captions as a WebVTT file">VTT</button>
8990
+ <button type="button" class="btn tiny" data-tr-cap-import title="Place the captions of an SRT or WebVTT file">Import…</button>
8991
+ <input type="file" accept=".srt,.vtt,text/vtt,application/x-subrip" data-tr-cap-input hidden>
8992
+ </div>
8993
+ <div class="tr-note">Caption last: a cut through a caption doesn't re-time its words, so add captions again after changing the edit.</div>
8994
+ </div>
8995
+ <div class="tr-body" data-tr-body tabindex="0"></div>
8996
+ <div class="tr-foot hidden" data-tr-foot><span data-tr-sel></span>
8997
+ <button type="button" class="btn tiny" data-tr-cut-sel title="Extract the selected words and the pause after them, on the targeted tracks (Delete)">Cut</button></div>`;
8998
+ const q = (s) => root.querySelector(s);
8999
+ trState.el = { go: q("[data-tr-go]"), busy: q("[data-tr-busy]"), busyText: q("[data-tr-busy-text]"), bar: q("[data-tr-bar]"),
9000
+ find: q("[data-tr-find]"), count: q("[data-tr-count]"), cutFound: q("[data-tr-cut-found]"), body: q("[data-tr-body]"),
9001
+ foot: q("[data-tr-foot]"), selText: q("[data-tr-sel]") };
9002
+ const E = trState.el;
9003
+ E.go.addEventListener("click", transcribeFromTab);
9004
+ q("[data-tr-cancel]").addEventListener("click", cancelTranscribe);
9005
+ q("[data-tr-model]").addEventListener("change", (e) => saveTranscribeSettings({ model: e.target.value }));
9006
+ q("[data-tr-lang]").addEventListener("change", (e) => saveTranscribeSettings({ language: e.target.value === "auto" ? null : e.target.value }));
9007
+ E.find.addEventListener("input", () => { trState.query = E.find.value; findTranscript(); });
9008
+ E.find.addEventListener("keydown", (e) => {
9009
+ if (e.key === "Enter") { e.preventDefault(); nextTranscriptHit(e.shiftKey ? -1 : 1); }
9010
+ if (e.key === "Escape" && E.find.value) { e.stopPropagation(); E.find.value = ""; trState.query = ""; findTranscript(); }
9011
+ });
9012
+ E.cutFound.addEventListener("click", () => {
9013
+ const n = trState.hits.length;
9014
+ if (n) cutTranscriptRuns(trState.hits, `${n} × "${trState.query.trim()}"`);
9015
+ });
9016
+ q("[data-tr-copy]").addEventListener("click", copyTranscript);
9017
+ q("[data-tr-cap-style]").addEventListener("change", (e) => saveTranscribeSettings({ captionStyle: e.target.value }));
9018
+ q("[data-tr-cap-add]").addEventListener("click", () => addCaptionsFromTranscript(q("[data-tr-cap-style]").value));
9019
+ root.querySelectorAll("[data-tr-cap-file]").forEach((b) => b.addEventListener("click", () => downloadCaptions(b.dataset.trCapFile)));
9020
+ const capInput = q("[data-tr-cap-input]");
9021
+ q("[data-tr-cap-import]").addEventListener("click", () => capInput.click());
9022
+ capInput.addEventListener("change", async () => {
9023
+ const f = capInput.files && capInput.files[0];
9024
+ capInput.value = "";
9025
+ if (!f) return;
9026
+ let list;
9027
+ const st = q("[data-tr-cap-style]").value;
9028
+ try { list = FableCutCaptions.parse(await f.text()); } catch (e) { toast(e.message); return; }
9029
+ const m = FableCutCaptions.metrics(st, project.width, project.height);
9030
+ placeCaptions(FableCutCaptions.fit(list, m.chars, m.lines), st, `from ${f.name}`);
9031
+ });
9032
+ q("[data-tr-cut-sel]").addEventListener("click", cutTranscriptSelection);
9033
+ E.body.addEventListener("mousedown", (e) => {
9034
+ const tc = e.target.closest(".tr-tc");
9035
+ if (tc) { goToTranscriptTime(+tc.dataset.t); return; }
9036
+ const w = e.target.closest(".tw");
9037
+ if (!w || e.button !== 0) return;
9038
+ e.preventDefault();
9039
+ E.body.focus({ preventScroll: true });
9040
+ const k = +w.dataset.k;
9041
+ if (e.shiftKey && trState.anchor != null) trState.sel = { i: Math.min(trState.anchor, k), j: Math.max(trState.anchor, k) };
9042
+ else { trState.anchor = k; trState.sel = { i: k, j: k }; goToTranscriptTime(trState.words[k].s); }
9043
+ trState.drag = true;
9044
+ paintTranscriptMarks();
9045
+ });
9046
+ E.body.addEventListener("mouseover", (e) => {
9047
+ if (!trState.drag) return;
9048
+ const w = e.target.closest(".tw");
9049
+ if (!w || trState.anchor == null) return;
9050
+ const k = +w.dataset.k;
9051
+ trState.sel = { i: Math.min(trState.anchor, k), j: Math.max(trState.anchor, k) };
9052
+ paintTranscriptMarks();
9053
+ });
9054
+ window.addEventListener("mouseup", () => { trState.drag = false; });
9055
+ // Delete anywhere in this tab means the words, never the timeline's clips: with none selected it does
9056
+ // nothing; in the Find box it edits the text
9057
+ root.addEventListener("keydown", (e) => {
9058
+ if ((e.key === "Delete" || e.key === "Backspace") && !e.ctrlKey && !e.metaKey && !e.altKey) {
9059
+ e.stopPropagation();
9060
+ if (isTypingTarget(e.target)) return;
9061
+ e.preventDefault();
9062
+ if (trState.sel) cutTranscriptSelection();
9063
+ } else if (e.key === "Escape" && trState.sel && !isTypingTarget(e.target)) {
9064
+ e.preventDefault(); e.stopPropagation();
9065
+ trState.sel = null; trState.anchor = null;
9066
+ paintTranscriptMarks();
9067
+ }
9068
+ });
9069
+ trState.built = true;
9070
+ }
9071
+ function renderTranscript(force = false) {
9072
+ if (!trState.open || !els.transcriptPage) return;
9073
+ if (typeof FableCutTranscribe === "undefined") { els.transcriptPage.innerHTML = `<div class="tr-empty">Transcript module missing — reload the editor.</div>`; return; }
9074
+ if (!trState.built) buildTranscriptPage();
9075
+ const groups = transcriptGroups();
9076
+ for (const g of groups) {
9077
+ const src = getMedia(g[0].mediaId).src;
9078
+ if (!transcriptCache.has(src)) loadTranscript(src).then(() => renderTranscript(true));
9079
+ }
9080
+ paintTranscribeBusy();
9081
+ const sig = transcriptSig();
9082
+ if (!force && sig === trState.sig) return;
9083
+ trState.sig = sig;
9084
+ const T = FableCutTranscribe, E = trState.el;
9085
+ const words = trState.words = transcriptWords();
9086
+ trState.wsig = transcriptWordsSig();
9087
+ const tgt = transcribeTargets();
9088
+ E.go.textContent = tgt.selected ? `Transcribe selected (${tgt.srcs.length})` : tgt.srcs.length ? `Transcribe ${tgt.srcs.length} file${tgt.srcs.length === 1 ? "" : "s"}` : "Transcribe";
9089
+ E.go.disabled = !!trState.busy || !tgt.srcs.length;
9090
+ E.go.title = tgt.srcs.length ? "Turn the speech into words, in this browser (the model downloads once). Select clips to transcribe just those, or again"
9091
+ : groups.length ? "Every file on the timeline has a transcript — select clips to transcribe them again" : "Put clips with speech on the timeline first";
9092
+ const missing = [...new Set(groups.map((g) => getMedia(g[0].mediaId)).filter((m) => transcriptCache.get(m.src) === false).map((m) => m.name || m.src))];
9093
+ let html = "";
9094
+ if (!groups.length) html = `<div class="tr-empty">Put clips with speech on the timeline, then transcribe them here. Speech becomes words in this browser; your audio never leaves it.</div>`;
9095
+ else {
9096
+ if (missing.length) html += `<div class="tr-note">No transcript yet: ${missing.slice(0, 6).map(escapeHtml).join(", ")}${missing.length > 6 ? ` +${missing.length - 6} more` : ""}</div>`;
9097
+ if (!words.length && !missing.length) html += `<div class="tr-empty">${[...transcriptCache.values()].some((v) => v instanceof Promise) ? "Loading…" : "No words in these clips."}</div>`;
9098
+ for (const s of T.segments(words)) {
9099
+ let p = "";
9100
+ for (let k = s.i; k <= s.j; k++) p += (k > s.i ? " " : "") + `<span class="tw" data-k="${k}">${escapeHtml(words[k].w)}</span>`;
9101
+ html += `<p class="tr-seg"><span class="tr-tc" data-t="${s.from}" title="Go to ${fmt(s.from)}">${fmt(s.from)}</span>${p}</p>`;
9102
+ }
9103
+ }
9104
+ E.body.innerHTML = html;
9105
+ trState.now = -1;
9106
+ // the selection stands only while the words are the same ones
9107
+ const key = words.map((x) => x.s + x.w).join("|");
9108
+ if (key !== trState.wordsKey) { trState.sel = null; trState.anchor = null; }
9109
+ trState.wordsKey = key;
9110
+ findTranscript(true);
9111
+ }
9112
+ /** Go to a time from the transcript: the Program monitor shows it, as markers and placements do. */
9113
+ function goToTranscriptTime(t) {
9114
+ if (isSourceMode()) setMonitorMode("program");
9115
+ setTime(t);
9116
+ }
9117
+ function paintTranscribeBusy() {
9118
+ const E = trState.el, b = trState.busy;
9119
+ if (!E) return;
9120
+ E.busy.classList.toggle("hidden", !b);
9121
+ if (!b) return;
9122
+ let loaded = 0, total = 0, downloading = false;
9123
+ for (const f of b.dl.values()) { loaded += f.loaded; total += f.total; if (f.loaded < f.total) downloading = true; }
9124
+ const name = (project.media.find((m) => m.src === b.srcs[b.i])?.name) || b.srcs[b.i].split("/").pop();
9125
+ const frac = downloading && total ? loaded / total : (b.i + b.frac) / b.srcs.length;
9126
+ E.busyText.textContent = downloading
9127
+ ? `Downloading the speech model (once)… ${Math.round(100 * loaded / total)}%`
9128
+ : `Transcribing ${name}${b.srcs.length > 1 ? ` (${b.i + 1} of ${b.srcs.length})` : ""}… ${Math.round(100 * b.frac)}%`;
9129
+ E.bar.style.width = `${Math.round(100 * frac)}%`;
9130
+ }
9131
+ function findTranscript(keepSel = false) {
9132
+ const E = trState.el;
9133
+ if (!E) return;
9134
+ const q = trState.query.trim();
9135
+ trState.hits = q ? FableCutTranscribe.find(trState.words, q) : [];
9136
+ E.count.textContent = q ? `${trState.hits.length} found` : "";
9137
+ E.cutFound.disabled = !trState.hits.length;
9138
+ E.cutFound.textContent = trState.hits.length ? `Cut ${trState.hits.length}` : "Cut all";
9139
+ if (!keepSel) trState.hitAt = -1;
9140
+ paintTranscriptMarks();
9141
+ }
9142
+ function nextTranscriptHit(dir) {
9143
+ const h = trState.hits;
9144
+ if (!h.length) return;
9145
+ trState.hitAt = ((trState.hitAt ?? -1) + dir + h.length) % h.length;
9146
+ const run = h[trState.hitAt];
9147
+ trState.sel = { i: run.i, j: run.j };
9148
+ trState.anchor = run.i;
9149
+ goToTranscriptTime(trState.words[run.i].s);
9150
+ paintTranscriptMarks();
9151
+ trState.el.body.querySelector(`.tw[data-k="${run.i}"]`)?.scrollIntoView({ block: "center" });
9152
+ }
9153
+ function paintTranscriptMarks() {
9154
+ const E = trState.el;
9155
+ if (!E) return;
9156
+ const hit = new Set();
9157
+ for (const r of trState.hits) for (let k = r.i; k <= r.j; k++) hit.add(k);
9158
+ const s = trState.sel;
9159
+ for (const el of E.body.querySelectorAll(".tw")) {
9160
+ const k = +el.dataset.k;
9161
+ el.classList.toggle("hit", hit.has(k));
9162
+ el.classList.toggle("sel", !!s && k >= s.i && k <= s.j);
9163
+ }
9164
+ E.foot.classList.toggle("hidden", !s);
9165
+ if (s) {
9166
+ const w = trState.words;
9167
+ const txt = FableCutTranscribe.text(w, s.i, s.j);
9168
+ E.selText.textContent = `${s.j - s.i + 1} word${s.j === s.i ? "" : "s"} · ${(w[s.j].e - w[s.i].s).toFixed(1)} s · “${txt.length > 60 ? txt.slice(0, 57) + "…" : txt}”`;
9169
+ }
9170
+ }
9171
+ function cutTranscriptSelection() {
9172
+ const s = trState.sel;
9173
+ if (!s) return;
9174
+ cutTranscriptRuns([s], `${s.j - s.i + 1} word${s.j === s.i ? "" : "s"}`);
9175
+ }
9176
+ /** Extract the words of each run (and the pause after them) on the targeted tracks: one undo step. */
9177
+ function cutTranscriptRuns(runs, label) {
9178
+ // the words were placed on the timeline as it was at the last redraw: it may have moved since
9179
+ if (transcriptWordsSig() !== trState.wsig) { renderTranscript(true); toast("The timeline changed — find or select the words again"); return; }
9180
+ const spans = FableCutTranscribe.cutSpans(trState.words, runs, { fps: projectFps() });
9181
+ if (!spans.length) { toast("Too short to cut"); return; }
9182
+ const snap = undoSnapshot();
9183
+ let cut = 0, secs = 0;
9184
+ for (const sp of spans.slice().sort((a, b) => b.from - a.from)) {
9185
+ if (!EDIT.liftRange(sp.from, sp.to, true)) { cut++; secs += sp.to - sp.from; }
9186
+ }
9187
+ if (!cut) { state.dirtyTimeline = true; toast("Nothing was cut — target the clip's tracks first (or unlock them)"); return; }
9188
+ pushUndo(snap);
9189
+ pruneSelection();
9190
+ state.dirtyTimeline = true;
9191
+ scheduleSave();
9192
+ trState.sel = null; trState.anchor = null;
9193
+ renderTranscript(true);
9194
+ toast(`Cut ${label} · ${secs.toFixed(1)} s shorter`);
9195
+ }
9196
+ function copyTranscript() {
9197
+ const lines = FableCutTranscribe.segments(trState.words).map((s) => `[${fmt(s.from)}] ${s.text}`);
9198
+ if (!lines.length) { toast("Nothing to copy yet"); return; }
9199
+ navigator.clipboard.writeText(lines.join("\n")).then(() => toast(`Copied ${lines.length} line${lines.length === 1 ? "" : "s"}`), () => toast("Couldn't copy — the browser refused"));
9200
+ }
9201
+ async function transcribeFromTab() {
9202
+ const { srcs } = transcribeTargets();
9203
+ if (!srcs.length) { toast("Put a clip with speech on the timeline first"); return; }
9204
+ let out;
9205
+ try { out = await transcribeSrcs(srcs); } catch (e) { toast(e.message); return; }
9206
+ const unsaved = out.done.filter((d) => !d.saved).length;
9207
+ const words = out.done.reduce((n, d) => n + d.words, 0);
9208
+ toast(out.cancelled ? `Stopped — ${out.done.length} file${out.done.length === 1 ? "" : "s"} transcribed`
9209
+ : out.failed.length && !out.done.length ? `Couldn't transcribe: ${out.failed[0].error}`
9210
+ : `Transcribed ${out.done.length} file${out.done.length === 1 ? "" : "s"}, ${words} words` +
9211
+ (out.failed.length ? ` · ${out.failed.length} failed (${out.failed[0].error})` : "") +
9212
+ (unsaved ? " · kept for this session only (the server didn't save it)" : ""));
9213
+ }
9214
+ /** The word under the playhead, lit (and kept in view while playing); a redraw when the timeline changes. */
9215
+ let trTickAt = 0;
9216
+ function transcriptTick() {
9217
+ const now = performance.now();
9218
+ if (now - trTickAt > 300) { trTickAt = now; renderTranscript(); }
9219
+ const w = trState.words;
9220
+ let lo = 0, hi = w.length - 1, k = -1;
9221
+ while (lo <= hi) { const m = (lo + hi) >> 1; if (w[m].s <= state.time + 1e-4) { k = m; lo = m + 1; } else hi = m - 1; }
9222
+ if (k >= 0 && state.time > w[k].e + 0.25) k = -1;
9223
+ if (k === trState.now || !trState.el) return;
9224
+ trState.el.body.querySelector(".tw.now")?.classList.remove("now");
9225
+ const el = k >= 0 ? trState.el.body.querySelector(`.tw[data-k="${k}"]`) : null;
9226
+ el?.classList.add("now");
9227
+ if (el && state.playing) el.scrollIntoView({ block: "nearest" });
9228
+ trState.now = k;
9229
+ }
9230
+
9231
+ /* ── Captions (captions.js): the transcript's words become caption clips — text
9232
+ clips with wordTimes, so karaoke / highlight / word pop follow the speech —
9233
+ on a video lane above the edit; subtitle files out and in. The same clips as
9234
+ fablecut_captions. ── */
9235
+ function addCaptionsFromTranscript(styleKey) {
9236
+ const C = FableCutCaptions;
9237
+ if (transcriptWordsSig() !== trState.wsig) renderTranscript(true);
9238
+ const words = trState.words;
9239
+ if (!words.length) { toast("Transcribe the clips first — captions are made from their words"); return; }
9240
+ const m = C.metrics(styleKey, project.width, project.height);
9241
+ placeCaptions(C.cues(words, { chars: m.chars, lines: m.lines, words: m.words, maxDur: m.maxDur, fps: projectFps() }), styleKey, "");
9242
+ }
9243
+ /** Put caption cues on the timeline (replacing the captions there), as one undo step. */
9244
+ function placeCaptions(list, styleKey, from) {
9245
+ const C = FableCutCaptions;
9246
+ if (!list.length) { toast("No captions to add"); return; }
9247
+ const old = project.clips.filter(C.isCaption);
9248
+ if (old.some(isGroupLocked)) { toastLocked(); return; }
9249
+ const span = [list[0].start, list[list.length - 1].end];
9250
+ const lane = C.trackFor(old.length ? project : { ...project, clips: project.clips.filter((c) => !C.isCaption(c)), tracks: serializeTracks() }, span[0], span[1]);
9251
+ if (state.lockedTracks?.has?.(lane.track) || (project.lockedTracks || []).includes(lane.track)) { toast(`${lane.track} is locked — unlock it for the captions`); return; }
9252
+ const snap = undoSnapshot();
9253
+ let track = lane.track;
9254
+ if (lane.add) {
9255
+ const t = addTimelineTrack("video");
9256
+ if (!t) return;
9257
+ track = t.id;
9258
+ }
9259
+ const oldIds = new Set(old.map((c) => c.id));
9260
+ project.clips = project.clips.filter((c) => !oldIds.has(c.id));
9261
+ for (const id of oldIds) state.selIds.delete(id);
9262
+ if (oldIds.has(state.selId)) state.selId = null;
9263
+ for (const cue of list) project.clips.push({ ...C.clip(cue, { style: styleKey, width: project.width, height: project.height, track }), id: "c_" + uid() });
9264
+ pushUndo(snap);
9265
+ pruneSelection();
9266
+ state.dirtyTimeline = true;
9267
+ scheduleSave();
9268
+ renderInspector();
9269
+ toast(`${list.length} caption${list.length === 1 ? "" : "s"} on ${track}${from ? " " + from : ""}${old.length ? ` · replaced ${old.length}` : ""}`);
9270
+ }
9271
+ /** A cut, split or trim that shortens a caption leaves its words timed to the old cut: say so, for a moment. */
9272
+ const capWatch = { durs: null, at: 0, said: 0 };
9273
+ function watchCaptions(now) {
9274
+ if (now - capWatch.at < 500 || typeof FableCutCaptions === "undefined") return;
9275
+ capWatch.at = now;
9276
+ const durs = new Map();
9277
+ for (const c of project.clips) if (FableCutCaptions.isCaption(c)) durs.set(c.id, c.duration);
9278
+ const prev = capWatch.durs;
9279
+ capWatch.durs = durs;
9280
+ if (!prev || now - capWatch.said < 5000) return;
9281
+ for (const [id, d] of durs) {
9282
+ if (prev.has(id) && d < prev.get(id) - 1e-4) {
9283
+ capWatch.said = now;
9284
+ toast("Captions don't re-time when cut — add them again in the Transcript tab once the edit is done");
9285
+ return;
9286
+ }
9287
+ }
9288
+ }
9289
+ function downloadCaptions(kind) {
9290
+ const C = FableCutCaptions, list = C.fromClips(project.clips, [...state.disabledTracks]);
9291
+ if (!list.length) { toast("No captions on the timeline yet — Add captions first"); return; }
9292
+ const blob = new Blob([kind === "vtt" ? C.toVTT(list) : C.toSRT(list)], { type: kind === "vtt" ? "text/vtt" : "application/x-subrip" });
9293
+ const a = document.createElement("a");
9294
+ a.href = URL.createObjectURL(blob);
9295
+ a.download = `${String(project.name || "captions").replace(/[^\w\- ]+/g, "_").trim() || "captions"}.${kind}`;
9296
+ document.body.appendChild(a);
9297
+ a.click();
9298
+ a.remove();
9299
+ setTimeout(() => URL.revokeObjectURL(a.href), 2000);
9300
+ toast(`Saved ${list.length} caption${list.length === 1 ? "" : "s"} as ${a.download}`);
9301
+ }
9302
+ /* fablecut_transcribe: transcribe the job's files in this tab, save them, report. */
9303
+ async function runTranscribeJob(ticket, fail) {
9304
+ const spec = ticket.transcribe || {};
9305
+ if (typeof FableCutTranscribe === "undefined") return fail("the transcript module is missing — reload the editor");
9306
+ if (trState.busy) return fail("this editor tab is already transcribing — wait for it, or cancel it there");
9307
+ const srcs = [], skipped = [];
9308
+ for (const src of spec.srcs || []) {
9309
+ if (!spec.again && await loadTranscript(src, true)) { skipped.push(src); continue; }
9310
+ srcs.push(src);
9311
+ }
9312
+ const report = (body, force) => fetch("/api/export/job/report?id=" + encodeURIComponent(ticket.id), { method: "POST", body: JSON.stringify(body) })
9313
+ .then((r) => r.json()).then((r) => { if (r?.cancel) cancelTranscribe(); }).catch(() => { });
9314
+ if (!srcs.length) return report({ status: "done", result: { done: [], skipped, failed: [] } });
9315
+ let last = 0;
9316
+ const out = await transcribeSrcs(srcs, { model: FableCutTranscribe.model(spec.model), language: spec.language || null }, (f) => {
9317
+ const t = performance.now();
9318
+ if (t - last > 1000) { last = t; report({ progress: f }); }
9319
+ }).catch((e) => ({ done: [], failed: srcs.map((src) => ({ src, error: e.message })) }));
9320
+ for (const d of out.done) if (!d.saved) out.failed.push({ src: d.src, error: "transcribed, but the server didn't save it" });
9321
+ out.done = out.done.filter((d) => d.saved);
9322
+ if (out.cancelled) return report({ status: "failed", error: "cancelled" });
9323
+ if (!out.done.length && out.failed.length) return fail(out.failed.map((f) => `${f.src}: ${f.error}`).join(" · "));
9324
+ return report({ status: "done", result: { done: out.done, skipped, failed: out.failed } });
9325
+ }
9326
+ function clearSilences() {
9327
+ silenceGen++; // a Find still listening doesn't bring the marks back
9328
+ state.silence = null;
9329
+ state.silenceBusy = false;
9330
+ state.dirtyTimeline = true;
9331
+ renderInspector();
7914
9332
  }
7915
9333
  async function autoDuckClips(clips, { under = null, amount = duckAmount(), threshold = -40 } = {}) {
7916
9334
  if (typeof FableCutDucking === "undefined") { toast("Ducking module missing — reload the editor"); return; }
@@ -7997,17 +9415,20 @@ function parseDbInput(s) {
7997
9415
  return Number.isFinite(v) ? clampFaderDb(v) : null;
7998
9416
  }
7999
9417
  function setSideTab(tab) {
8000
- const mixer = tab === "mixer", color = tab === "color";
9418
+ const mixer = tab === "mixer", color = tab === "color", transcript = tab === "transcript";
8001
9419
  mixerState.open = mixer;
8002
9420
  colorState.open = color;
9421
+ trState.open = transcript;
8003
9422
  for (const b of els.sideTabs.querySelectorAll("[data-side]"))
8004
9423
  b.classList.toggle("on", b.dataset.side === tab);
8005
- els.inspector.classList.toggle("hidden", mixer || color);
9424
+ els.inspector.classList.toggle("hidden", mixer || color || transcript);
8006
9425
  els.mixer.classList.toggle("hidden", !mixer);
8007
9426
  els.colorPage.classList.toggle("hidden", !color);
9427
+ els.transcriptPage.classList.toggle("hidden", !transcript);
8008
9428
  try { localStorage.setItem(SIDE_TAB_KEY, tab); } catch { }
8009
9429
  if (mixer) renderMixer();
8010
9430
  else if (color) renderColorPage(true);
9431
+ else if (transcript) renderTranscript(true);
8011
9432
  else renderInspector();
8012
9433
  }
8013
9434
  /** Write a track's fader / pan, push it into the live graph, persist. */
@@ -9355,7 +10776,9 @@ function parseSvgSize(txt) {
9355
10776
  return { width: w || 800, height: h || 600 };
9356
10777
  }
9357
10778
  async function loadSvgMedia(m) {
10779
+ const gen = runtime.projectGen;
9358
10780
  const txt = await (await fetch(m.src)).text();
10781
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
9359
10782
  const { width, height } = parseSvgSize(txt);
9360
10783
  m.width = width; m.height = height;
9361
10784
  const aux = runtime.mediaAux.get(m.id) || {};
@@ -9364,7 +10787,7 @@ async function loadSvgMedia(m) {
9364
10787
  aux.svgFrames = new Map(); // quantized t -> HTMLImageElement (small LRU)
9365
10788
  aux.svgPending = null;
9366
10789
  runtime.mediaAux.set(m.id, aux);
9367
- if (!aux.svgAnimated) aux.img = await rasterizeSvgMarkup(txt);
10790
+ if (!aux.svgAnimated) { const img = await rasterizeSvgMarkup(txt); if (gen === runtime.projectGen) aux.img = img; }
9368
10791
  state.dirtyTimeline = true;
9369
10792
  }
9370
10793
  function svgMarkupAt(aux, t) {
@@ -10222,6 +11645,7 @@ function exitComp(levels = 1) {
10222
11645
  scheduleSave();
10223
11646
  }
10224
11647
  function syncCompCrumb() {
11648
+ syncSequenceButton();
10225
11649
  if (els.projectName) els.projectName.textContent = project.name + (state.connected ? " · 🟢 connected" : " · ⚪ local session");
10226
11650
  const el = document.getElementById("compCrumb");
10227
11651
  if (!el) return;
@@ -10229,13 +11653,203 @@ function syncCompCrumb() {
10229
11653
  el.classList.toggle("hidden", !x);
10230
11654
  if (!x) { el.innerHTML = ""; return; }
10231
11655
  const names = x.path.map((id) => (CompLib.getComp(x.root, id) || { name: id }).name);
10232
- el.innerHTML = `<button type="button" class="btn tiny" data-crumb="${x.path.length}" title="Back to the main timeline">◀ Main</button>` +
11656
+ el.innerHTML = `<button type="button" class="btn tiny" data-crumb="${x.path.length}" title="Back to the timeline">◀ ${escapeHtml(openSequenceName())}</button>` +
10233
11657
  names.map((n, i) => `<span class="crumb-sep">›</span>` + (i < names.length - 1
10234
11658
  ? `<button type="button" class="btn tiny" data-crumb="${x.path.length - 1 - i}">${escapeHtml(n)}</button>`
10235
- : `<b title="You are editing this composition — Esc or ◀ Main goes back">${escapeHtml(n)}</b>`)).join("");
11659
+ : `<b title="You are editing this composition — Esc or ◀ goes back">${escapeHtml(n)}</b>`)).join("");
10236
11660
  for (const b of el.querySelectorAll("[data-crumb]")) b.addEventListener("click", () => exitComp(+b.dataset.crumb));
10237
11661
  }
10238
11662
 
11663
+ /* ═══════════════════════════ SEQUENCES ═══════════════════════════
11664
+ Several timelines in one project (sequences.js). The open one is `project`
11665
+ itself — clips, tracks, canvas, frame rate, mix, delivery — and the others
11666
+ wait in project.sequences. Opening one parks this timeline in its entry and
11667
+ loads the other, like a reload. For the session each sequence keeps its own
11668
+ undo history, playhead and selection. */
11669
+ const SeqLib = self.FableCutSeq;
11670
+ /** The document that holds the sequences (the root while a comp is open). */
11671
+ function seqRoot() { return state.compCtx ? state.compCtx.root : project; }
11672
+ function openSequenceName() { const r = seqRoot(); return (SeqLib.find(r, SeqLib.activeId(r)) || SeqLib.MAIN).name; }
11673
+ /** A document is about to be shown: when it opens another sequence, the undo steps,
11674
+ * playhead and selection go with the one that was open, and the other's come back. */
11675
+ function noteOpenSequence(data) {
11676
+ const next = SeqLib.activeId(data), prev = runtime.seqOpen;
11677
+ runtime.seqOpen = next;
11678
+ runtime.seqBack = null;
11679
+ if (!prev || prev === next) return;
11680
+ // the steps only fit the state they were taken on: its timeline, and the comps and media every sequence
11681
+ // shares (undo puts those back too). An agent or the other sequence may change them meanwhile.
11682
+ // A relink / replace step also holds the other sequences' clips: then those must be as they were too.
11683
+ const here = projectJSONHere();
11684
+ const withOthers = [...runtime.undo, ...runtime.redo].some(hasSeqClips);
11685
+ runtime.seqUndo.set(prev, { undo: runtime.undo.slice(), redo: runtime.redo.slice(), time: state.time, sel: state.selId,
11686
+ fp: seqUndoPrint(here, withOthers), withOthers });
11687
+ const back = runtime.seqUndo.get(next);
11688
+ const fits = back && back.fp === seqUndoPrint(data, back.withOthers);
11689
+ runtime.undo.splice(0, runtime.undo.length, ...(fits ? back.undo : []));
11690
+ runtime.redo.splice(0, runtime.redo.length, ...(fits ? back.redo : []));
11691
+ runtime.seqBack = back || null;
11692
+ }
11693
+ /** What a sequence's undo steps rely on: its timeline, the shared comps and media, and (for relink /
11694
+ * replace steps) the clips of the other sequences — in the saved form, so both sides compare alike. */
11695
+ function seqUndoPrint(d, withOthers) {
11696
+ return JSON.stringify([d.clips || [], d.comps || [], (d.media || []).filter((m) => !m.transient),
11697
+ ...(withOthers ? [SeqLib.others(d).map((sq) => [sq.id, sq.clips || []])] : [])]);
11698
+ }
11699
+ /** Open sequence `id` in the editor. False when it can't be opened now. */
11700
+ function openSequence(id) {
11701
+ if (state.exporting) { toast("Wait for the export to finish before opening another sequence"); return false; }
11702
+ if (state.gesture) return false;
11703
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11704
+ if (SeqLib.activeId(project) === id) return true;
11705
+ if (state.playing) pause();
11706
+ const doc = projectJSONHere();
11707
+ try { SeqLib.open(doc, id); } catch (e) { toast(e.message); return false; }
11708
+ applyProject(doc);
11709
+ const back = runtime.seqBack;
11710
+ runtime.seqBack = null;
11711
+ const sel = back && back.sel && getClip(back.sel);
11712
+ setSelection(sel ? [...withLinked([sel])].map((c) => c.id) : []);
11713
+ setTime(back ? back.time : 0);
11714
+ syncCompCrumb();
11715
+ scheduleSave();
11716
+ return true;
11717
+ }
11718
+ /** Add a sequence ({name?, from?, width?, height?}) and open it. */
11719
+ function newSequence(opts) {
11720
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11721
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11722
+ const doc = projectJSONHere();
11723
+ let s;
11724
+ try { s = SeqLib.add(doc, opts); } catch (e) { toast(e.message); return; }
11725
+ project.sequences = doc.sequences; project.sequence = doc.sequence;
11726
+ if (openSequence(s.id)) toast(`New sequence “${s.name}” · ${s.width}×${s.height}`);
11727
+ else { scheduleSave(); syncCompCrumb(); toast(`New sequence “${s.name}” added — open it from the sequence menu`); }
11728
+ }
11729
+ function renameSequence(id, name) {
11730
+ const r = seqRoot();
11731
+ try { SeqLib.rename(r, id, name); } catch (e) { toast(e.message); return; }
11732
+ if (!r.sequences) { r.sequences = null; r.sequence = null; }
11733
+ syncCompCrumb(); scheduleSave();
11734
+ }
11735
+ /** Delete a sequence — after keeping the project as it is now as a version, when the server is there. */
11736
+ async function deleteSequence(id) {
11737
+ const r = seqRoot(), s = SeqLib.find(r, id);
11738
+ if (!s || SeqLib.entries(r).length < 2) return;
11739
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11740
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11741
+ let kept = null;
11742
+ if (state.connected) {
11743
+ const projectId = runtime.projectId; // the version is of this project, whatever another tab opens meanwhile
11744
+ if (!(await flushSaveForVersion("the sequence was not deleted"))) return;
11745
+ try {
11746
+ const res = await fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" },
11747
+ body: JSON.stringify({ action: "save", name: `Before deleting the sequence “${s.name}”`.slice(0, 120), ...(projectId && projectId !== "?" ? { project: projectId } : {}) }) });
11748
+ if (res.ok) kept = (await res.json()).version;
11749
+ } catch { }
11750
+ // the delete has no undo: without that version it doesn't happen
11751
+ if (!kept) { toast(`Couldn't keep a version of the project, so “${s.name}” was not deleted. Try again in a moment.`); return; }
11752
+ }
11753
+ // the editor may have moved on while the version was saved
11754
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11755
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11756
+ if (!SeqLib.find(project, id) || SeqLib.entries(project).length < 2) return; // deleted or changed meanwhile (another tab, an agent)
11757
+ const wasOpen = SeqLib.activeId(project) === id;
11758
+ const doc = projectJSONHere();
11759
+ try { SeqLib.remove(doc, id); } catch (e) { toast(e.message); return; }
11760
+ if (wasOpen) {
11761
+ applyProject(doc);
11762
+ const back = runtime.seqBack;
11763
+ runtime.seqBack = null;
11764
+ setSelection([]);
11765
+ setTime(back ? back.time : 0);
11766
+ } else { project.sequences = doc.sequences || null; project.sequence = doc.sequence || null; }
11767
+ runtime.seqUndo.delete(id);
11768
+ syncCompCrumb(); scheduleSave();
11769
+ toast(`Deleted the sequence “${s.name}”` + (kept ? ` · it is kept in version v${kept.v} (Projects → Versions)` : ""));
11770
+ }
11771
+ function syncSequenceButton() {
11772
+ const b = $("btnSequences");
11773
+ if (!b) return;
11774
+ const n = SeqLib.entries(seqRoot()).length;
11775
+ b.querySelector(".seq-name").textContent = openSequenceName();
11776
+ b.querySelector(".seq-count").textContent = n > 1 ? String(n) : "";
11777
+ b.title = `Sequence: ${openSequenceName()}${n > 1 ? ` (one of ${n})` : ""} — open another one, or add, duplicate, rename`;
11778
+ }
11779
+ /** The sequence menu: the project's sequences (click one to open it), then what to do with them. */
11780
+ function showSequenceMenu(x, y) {
11781
+ hideTrackCtxMenu();
11782
+ const menu = document.createElement("div");
11783
+ menu.className = "ctx-menu seq-menu";
11784
+ const r = seqRoot(), openId = SeqLib.activeId(r);
11785
+ const rows = SeqLib.list(r), open = rows.find((row) => row.active);
11786
+ const item = (html, run, why, keepOpen) => {
11787
+ const b = document.createElement("button");
11788
+ b.type = "button"; b.className = "ctx-item"; b.innerHTML = html;
11789
+ if (why) { b.disabled = true; b.title = why; } else b.addEventListener("click", () => { if (!keepOpen) hideTrackCtxMenu(); run(b); });
11790
+ menu.appendChild(b);
11791
+ return b;
11792
+ };
11793
+ const sep = () => { const d = document.createElement("div"); d.className = "ctx-sep"; menu.appendChild(d); };
11794
+ for (const row of rows) {
11795
+ // the open one's live numbers are on the timeline (or the root, while a comp is open)
11796
+ const w = row.active ? r.width : row.width, h = row.active ? r.height : row.height;
11797
+ const len = row.active ? (state.compCtx ? row.duration : projDur()) : row.duration;
11798
+ const b = item(`<span class="seq-check">${row.active ? "✓" : ""}</span><span class="seq-row-name">${escapeHtml(row.name)}</span><kbd>${w}×${h} · ${fmt(len)}</kbd>`,
11799
+ () => openSequence(row.id));
11800
+ if (row.active) b.classList.add("on");
11801
+ }
11802
+ sep();
11803
+ item(`<span>New sequence…</span>`, () => promptNewSequence(x, y));
11804
+ item(`<span>Duplicate “${escapeHtml(open.name)}”</span>`, () => newSequence({ from: "open" }));
11805
+ item(`<span>Rename “${escapeHtml(open.name)}”…</span>`, () => promptBinText(x, y, "Sequence name", open.name, (v) => renameSequence(openId, v), { max: 120, ok: "Rename" }));
11806
+ item(`<span>Delete “${escapeHtml(open.name)}”…</span>`, (b) => {
11807
+ if (b.dataset.armed !== "1") { b.dataset.armed = "1"; b.querySelector("span").textContent = "Click again to delete it"; return; }
11808
+ hideTrackCtxMenu();
11809
+ deleteSequence(openId);
11810
+ }, rows.length < 2 ? "A project keeps at least one sequence" : null, true);
11811
+ showPopover(menu, x, y);
11812
+ }
11813
+ /** New sequence: a name, a canvas, and whether it starts empty or as a copy of the open one. */
11814
+ function promptNewSequence(x, y) {
11815
+ const pop = document.createElement("div");
11816
+ pop.className = "ctx-menu bin-pop seq-new";
11817
+ const n = SeqLib.entries(seqRoot()).length + 1;
11818
+ const sizes = [{ label: `Same as “${openSequenceName()}” · ${project.width}×${project.height}`, w: 0, h: 0 }, ...ASPECT_PRESETS];
11819
+ pop.innerHTML = `<label class="bin-pop-label" for="seqNewName">New sequence</label>
11820
+ <input type="text" class="bin-pop-input" id="seqNewName" maxlength="120" spellcheck="false">
11821
+ <label class="bin-pop-label" for="seqNewSize">Canvas</label>
11822
+ <select id="seqNewSize" class="bin-pop-input">${sizes.map((s, i) => `<option value="${i}">${escapeHtml(s.label)}</option>`).join("")}</select>
11823
+ <label class="seq-new-copy"><input type="checkbox" id="seqNewCopy"> Start from a copy of “${escapeHtml(openSequenceName())}”</label>
11824
+ <div class="bin-pop-hint">Media and compositions are shared by every sequence. Each has its own timeline, canvas, frame rate, mix and delivery settings.</div>
11825
+ <div class="bin-pop-btns"><button type="button" class="btn tiny" data-cancel>Cancel</button><button type="button" class="btn tiny accent" data-ok>Create</button></div>`;
11826
+ pop.querySelector("#seqNewName").value = `Sequence ${n}`;
11827
+ const ok = () => {
11828
+ const name = pop.querySelector("#seqNewName").value.trim();
11829
+ const size = sizes[+pop.querySelector("#seqNewSize").value] || sizes[0];
11830
+ const copy = pop.querySelector("#seqNewCopy").checked;
11831
+ hideTrackCtxMenu();
11832
+ newSequence({ name: name || undefined, from: copy ? "open" : "empty", ...(size.w ? { width: size.w, height: size.h } : {}) });
11833
+ };
11834
+ pop.querySelector("[data-ok]").addEventListener("click", ok);
11835
+ pop.querySelector("[data-cancel]").addEventListener("click", () => hideTrackCtxMenu());
11836
+ pop.addEventListener("keydown", (e) => {
11837
+ if (e.key === "Enter" && e.target.tagName !== "SELECT") { e.preventDefault(); ok(); }
11838
+ else if (e.key === "Escape") { e.preventDefault(); hideTrackCtxMenu(); }
11839
+ e.stopPropagation();
11840
+ });
11841
+ showPopover(pop, x, y);
11842
+ const input = pop.querySelector("#seqNewName");
11843
+ input.focus(); input.select();
11844
+ }
11845
+ function initSequencesUi() {
11846
+ const b = $("btnSequences");
11847
+ if (!b || b.dataset.wired) return;
11848
+ b.dataset.wired = "1";
11849
+ b.addEventListener("click", () => { const rc = b.getBoundingClientRect(); showSequenceMenu(rc.left, rc.bottom + 4); });
11850
+ syncSequenceButton();
11851
+ }
11852
+
10239
11853
  /* ── Making comps ── */
10240
11854
  function newCompId() { let id; do id = "comp_" + uid(); while (getComp(id)); return id; }
10241
11855
  /** Precompose the selection: the clips move into a new comp, a comp clip takes their place. */
@@ -11012,8 +12626,10 @@ function drawClipPicture(c, W, H, t, layered) {
11012
12626
  src = getSvgImage(c, t);
11013
12627
  if (src) { sw = src.naturalWidth || src.width; sh = src.naturalHeight || src.height; }
11014
12628
  } else if (c.kind === "video") {
11015
- src = getClipEl(c);
11016
- if (src) { sw = src.videoWidth; sh = src.videoHeight; }
12629
+ const frame = runtime.exportFrames && runtime.exportFrames.get(c.id);
12630
+ src = frame || getClipEl(c);
12631
+ if (frame) { sw = frame.displayWidth; sh = frame.displayHeight; }
12632
+ else if (src) { sw = src.videoWidth; sh = src.videoHeight; }
11017
12633
  } else if (c.kind === "comp") {
11018
12634
  src = renderComp(c, t);
11019
12635
  if (src) { sw = src.width; sh = src.height; }
@@ -12086,6 +13702,7 @@ window.addEventListener("keydown", (e) => {
12086
13702
  return;
12087
13703
  }
12088
13704
  if (!maskUi.clip || (maskUi.sel < 0 && !maskUi.tool)) return;
13705
+ if (els.transcriptPage?.contains(e.target)) return; // keys typed in the Transcript tab are its own
12089
13706
  const tg = e.target;
12090
13707
  if (tg && (tg.tagName === "INPUT" || tg.tagName === "TEXTAREA" || tg.tagName === "SELECT" || tg.isContentEditable)) return;
12091
13708
  const c = getClip(state.selId);
@@ -12758,6 +14375,7 @@ els.preview.addEventListener("dblclick", (e) => {
12758
14375
  shapeUi.pt = -1; scheduleSave(); renderInspector();
12759
14376
  }, true);
12760
14377
  window.addEventListener("keydown", (e) => {
14378
+ if (els.transcriptPage?.contains(e.target)) return; // keys typed in the Transcript tab are its own
12761
14379
  if (e.key === "Escape" && runtime.anchorTool && !shapeUi.sel && !shapeUi.tool) {
12762
14380
  const tg0 = e.target;
12763
14381
  if (!(tg0 && (tg0.tagName === "INPUT" || tg0.tagName === "TEXTAREA" || tg0.tagName === "SELECT"))) {
@@ -12891,12 +14509,13 @@ function drawTextOnPath(c, p, local) {
12891
14509
  return out;
12892
14510
  };
12893
14511
  const words = anim === "word-pop" ? centre("word") : null, lineBox = anim === "zoom-in" ? centre("line") : null;
14512
+ const clk = wordClock(c, p, wi, rate);
12894
14513
  const shown = anim === "typewriter" ? Math.floor(local / (rate / 4)) : Infinity;
12895
14514
  const ease = EASE["ease-out"];
12896
14515
  for (const q of glyphs) {
12897
14516
  if (q.space || q.gi >= shown) continue;
12898
- let d = q.d, scale = 1, alpha = 1, dx = 0, dy = 0, clipL = null, clipR = null, rise = null;
12899
- const uw = clamp((local - q.word * rate) / 0.25, 0, 1); // per word
14517
+ let d = q.d, scale = 1, alpha = 1, dx = 0, dy = 0, clipL = null, clipR = null, rise = null, lit = false;
14518
+ const uw = clamp((local - clk(q.word)[0]) / 0.25, 0, 1); // per word
12900
14519
  const ul = (dur) => clamp((local - q.line * rate) / dur, 0, 1); // per line
12901
14520
  if (anim === "letter-pop") {
12902
14521
  const u = clamp((local - q.ci * rate / 3) / 0.18, 0, 1);
@@ -12914,6 +14533,7 @@ function drawTextOnPath(c, p, local) {
12914
14533
  } else if (anim === "bounce") dy -= Math.abs(Math.sin(local * 3.2 + q.word * 0.9)) * size * 0.18;
12915
14534
  else if (anim === "shake") { dx += Math.sin(local * 31 + q.word * 7.3) * size * 0.035; dy += Math.cos(local * 27 + q.word * 3.1) * size * 0.035; }
12916
14535
  else if (anim === "karaoke") alpha = uw >= 1 ? 1 : 0.3 + uw * 0.7;
14536
+ else if (anim === "highlight") lit = wordIsCurrent(clk, q.word, wi, local);
12917
14537
  else if (anim === "clip-reveal") { // a wipe runs along each line in reading order
12918
14538
  const u = ul(0.5);
12919
14539
  if (u <= 0) continue;
@@ -12952,7 +14572,7 @@ function drawTextOnPath(c, p, local) {
12952
14572
  }
12953
14573
  if (p.glow > 0) { ctx2d.shadowColor = p.glowColor || p.color || "#fff"; ctx2d.shadowBlur = (+p.glow) * size / 40; }
12954
14574
  else if (shadowBlur > 0) { ctx2d.shadowColor = "rgba(0,0,0,.7)"; ctx2d.shadowBlur = shadowBlur; ctx2d.shadowOffsetY = shadowBlur / 3; }
12955
- ctx2d.fillStyle = fill();
14575
+ ctx2d.fillStyle = lit ? p.highlightColor || "#ffd166" : fill();
12956
14576
  ctx2d.fillText(q.g, 0, 0);
12957
14577
  if (p.glow > 0) ctx2d.fillText(q.g, 0, 0);
12958
14578
  ctx2d.globalAlpha = keep;
@@ -13257,7 +14877,24 @@ function letterAnimSegments(line) {
13257
14877
 
13258
14878
  /* ── Text rendering: styling (stroke / background pill) + kinetic animations.
13259
14879
  `local` is clip-local time in seconds. Word timing: word i enters at
13260
- i * wordRate; each entrance animation lasts ~0.25 s. ── */
14880
+ i * wordRate — or, on a caption timed to speech, at its wordTimes start;
14881
+ each entrance animation lasts ~0.25 s. ── */
14882
+ /** Word i's [start, end], seconds from the clip's start: props.wordTimes (a caption timed to speech)
14883
+ * when it has one pair per word; if the text was edited to another word count, spread over the clip;
14884
+ * else one every wordRate seconds. */
14885
+ function wordClock(c, p, n, rate) {
14886
+ const wt = p.wordTimes;
14887
+ if (Array.isArray(wt) && wt.length === n && n) return (i) => [+wt[i]?.[0] || 0, +wt[i]?.[1] || 0];
14888
+ if (Array.isArray(wt) && n) { const step = Math.max(0.05, (+c?.duration || n * rate) / n); return (i) => [i * step, (i + 1) * step]; }
14889
+ return (i) => [i * rate, (i + 1) * rate];
14890
+ }
14891
+ /** Is word i the one being said? From its start to its end (a tenth of a second more, so the
14892
+ * highlight doesn't flicker between words), and never past the next word's start. */
14893
+ function wordIsCurrent(clk, i, n, local) {
14894
+ const [a, b] = clk(i);
14895
+ const until = Math.max(b, a + 0.05) + 0.1;
14896
+ return local >= a && local < (i + 1 < n ? Math.min(clk(i + 1)[0], until) : until);
14897
+ }
13261
14898
  const backOut = (u) => { const c1 = 1.70158, c3 = c1 + 1; const v = u - 1; return 1 + c3 * v * v * v + c1 * v * v; };
13262
14899
  function hexToRgba(hex, a) {
13263
14900
  const n = parseInt(String(hex).replace("#", ""), 16) || 0;
@@ -13451,7 +15088,7 @@ function drawText(c, p, local) {
13451
15088
  g.addColorStop(1, p.color2);
13452
15089
  return g;
13453
15090
  };
13454
- const paint = (str, x, y, alpha = 1, rtl = false) => {
15091
+ const paint = (str, x, y, alpha = 1, rtl = false, fill = null) => {
13455
15092
  if (alpha <= 0) return;
13456
15093
  const keep = ctx2d.globalAlpha;
13457
15094
  const prevDir = ctx2d.direction;
@@ -13468,15 +15105,15 @@ function drawText(c, p, local) {
13468
15105
  if (p.glow > 0) { // neon: colored halo, double-fill for intensity
13469
15106
  ctx2d.shadowColor = p.glowColor || p.color || "#fff";
13470
15107
  ctx2d.shadowBlur = (+p.glow) * size / 40;
13471
- ctx2d.fillStyle = fillFor(y);
15108
+ ctx2d.fillStyle = fill || fillFor(y);
13472
15109
  ctx2d.fillText(str, x, y);
13473
15110
  ctx2d.fillText(str, x, y);
13474
15111
  } else if (shadowBlur > 0) {
13475
15112
  ctx2d.shadowColor = "rgba(0,0,0,.7)"; ctx2d.shadowBlur = shadowBlur; ctx2d.shadowOffsetY = shadowBlur / 3;
13476
- ctx2d.fillStyle = fillFor(y);
15113
+ ctx2d.fillStyle = fill || fillFor(y);
13477
15114
  ctx2d.fillText(str, x, y);
13478
15115
  } else {
13479
- ctx2d.fillStyle = fillFor(y);
15116
+ ctx2d.fillStyle = fill || fillFor(y);
13480
15117
  ctx2d.fillText(str, x, y);
13481
15118
  }
13482
15119
  ctx2d.shadowColor = "transparent"; ctx2d.shadowBlur = 0; ctx2d.shadowOffsetY = 0;
@@ -13605,6 +15242,8 @@ function drawText(c, p, local) {
13605
15242
  }
13606
15243
  // word-based animations: lay words out manually, per-line, honoring alignment + direction
13607
15244
  const spaceW = ctx2d.measureText(" ").width;
15245
+ const nWords = rawLines.reduce((n, ln) => n + ln.split(/\s+/).filter(Boolean).length, 0);
15246
+ const clk = wordClock(c, p, nWords, rate);
13608
15247
  let wi = 0;
13609
15248
  rawLines.forEach((ln, i) => {
13610
15249
  const y = y0 + i * lh;
@@ -13622,8 +15261,16 @@ function drawText(c, p, local) {
13622
15261
  words.forEach((word, j) => {
13623
15262
  const w = widths[j];
13624
15263
  const cx = rtl ? x - w / 2 : x + w / 2;
13625
- const u = clamp((local - wi * rate) / 0.25, 0, 1);
13626
- if (anim === "word-pop") {
15264
+ const u = clamp((local - clk(wi)[0]) / 0.25, 0, 1);
15265
+ if (anim === "highlight") { // every word shown; the one being said lit and lifted a little
15266
+ const on = wordIsCurrent(clk, wi, nWords, local);
15267
+ const s = on ? 1 + 0.03 * backOut(clamp((local - clk(wi)[0]) / 0.15, 0, 1)) : 1;
15268
+ ctx2d.save();
15269
+ ctx2d.translate(cx, y);
15270
+ if (s !== 1) ctx2d.scale(s, s);
15271
+ paint(word, 0, 0, 1, rtl, on ? p.highlightColor || "#ffd166" : null);
15272
+ ctx2d.restore();
15273
+ } else if (anim === "word-pop") {
13627
15274
  if (u > 0) {
13628
15275
  ctx2d.save();
13629
15276
  ctx2d.translate(cx, y);
@@ -13890,6 +15537,8 @@ function loop(ts) {
13890
15537
  }
13891
15538
  }
13892
15539
  if (state.dirtyTimeline) rebuildClips();
15540
+ if (trState.open) transcriptTick();
15541
+ watchCaptions(ts);
13893
15542
  const phX = Math.round(state.time * state.pps);
13894
15543
  if (phX !== playheadPx) {
13895
15544
  playheadPx = phX;
@@ -15000,6 +16649,141 @@ function prefetchExportVideos(t) {
15000
16649
  } catch { }
15001
16650
  }
15002
16651
  }
16652
+ /* ── Export decode: frames straight from WebCodecs ──
16653
+ Seeking <video> per frame is slow and not frame-exact, so export decodes
16654
+ MP4 / MOV clips itself (mp4-demux.js + VideoDecoder). Clips it can't take
16655
+ stay on the <video> path. */
16656
+ const Mp4 = self.FableCutMp4;
16657
+ class ExportFrameSource {
16658
+ static async open(src) {
16659
+ if (typeof VideoDecoder !== "function" || !Mp4) return null;
16660
+ try {
16661
+ const probe = await fetch(src, { headers: { Range: "bytes=0-0" } });
16662
+ if (probe.status !== 206) { try { await probe.body?.cancel(); } catch { } return null; }
16663
+ const size = Number((probe.headers.get("content-range") || "").split("/")[1]);
16664
+ await probe.arrayBuffer();
16665
+ if (!(size > 0)) return null;
16666
+ const read = async (a, b) => {
16667
+ const r = await fetch(src, { headers: { Range: `bytes=${a}-${b - 1}` } });
16668
+ if (r.status !== 206) throw new Error("range request refused");
16669
+ return new Uint8Array(await r.arrayBuffer());
16670
+ };
16671
+ const moov = await Mp4.findMoov(read, size);
16672
+ const mv = moov && Mp4.parseMovie(moov);
16673
+ if (!mv || !mv.samples.length) return null;
16674
+ const cfg = { codec: mv.codec, codedWidth: mv.width, codedHeight: mv.height };
16675
+ if (mv.description) cfg.description = mv.description;
16676
+ if (mv.displayWidth !== mv.width) Object.assign(cfg, { displayAspectWidth: mv.displayWidth, displayAspectHeight: mv.displayHeight });
16677
+ const ok = await VideoDecoder.isConfigSupported(cfg).catch(() => null);
16678
+ return ok && ok.supported ? new ExportFrameSource(read, size, mv, cfg) : null;
16679
+ } catch { return null; }
16680
+ }
16681
+ constructor(read, size, mv, cfg) {
16682
+ Object.assign(this, { read, size, cfg, samples: mv.samples, order: Mp4.presentationOrder(mv.samples) });
16683
+ this.dec = null; this.pos = 0; this.out = []; this.cur = null; this.win = null; this.err = null; this.wake = null;
16684
+ }
16685
+ restart(from) {
16686
+ this.dropQueue();
16687
+ if (this.dec && this.dec.state !== "closed") this.dec.close();
16688
+ this.err = null;
16689
+ this.dec = new VideoDecoder({
16690
+ output: (f) => { this.out.push(f); this.poke(); },
16691
+ error: (e) => { this.err = e; this.poke(); },
16692
+ });
16693
+ this.dec.ondequeue = () => this.poke();
16694
+ this.dec.configure(this.cfg);
16695
+ this.pos = from;
16696
+ }
16697
+ poke() { const w = this.wake; this.wake = null; if (w) w(); }
16698
+ dropQueue() { for (const f of this.out) f.close(); this.out = []; }
16699
+ /** The bytes of one sample, read through a 4 MB window (samples are mostly
16700
+ * contiguous, so one range request covers many frames). */
16701
+ async bytes(s) {
16702
+ const w = this.win;
16703
+ if (!w || s.offset < w.at || s.offset + s.size > w.at + w.data.length) {
16704
+ const end = Math.min(this.size, s.offset + Math.max(s.size, 4 << 20));
16705
+ this.win = { at: s.offset, data: await this.read(s.offset, end) };
16706
+ }
16707
+ const o = s.offset - this.win.at;
16708
+ return this.win.data.subarray(o, o + s.size);
16709
+ }
16710
+ /** The frame a player shows at media time t (a VideoFrame owned by this
16711
+ * source: valid until the next call or close()). */
16712
+ async frameAt(t) {
16713
+ const k = Mp4.frameAt(this.samples, this.order, t), ts = Math.round(this.samples[k].pts * 1e6);
16714
+ if (this.cur && this.cur.timestamp === ts) return this.cur;
16715
+ const sync = Mp4.syncBefore(this.samples, k);
16716
+ const passed = this.out.length > 0 && this.out[0].timestamp > ts;
16717
+ if (!this.dec || this.dec.state === "closed" || (this.cur && this.cur.timestamp > ts)
16718
+ || (k < this.pos && passed) || sync > this.pos) this.restart(sync);
16719
+ const n = this.samples.length;
16720
+ for (;;) {
16721
+ while (this.out.length && this.out[0].timestamp < ts) this.out.shift().close();
16722
+ if (this.out.length) { // the target, or (a frame the decoder dropped) the next one
16723
+ if (this.cur) this.cur.close();
16724
+ this.cur = this.out.shift();
16725
+ return this.cur;
16726
+ }
16727
+ if (this.err) throw this.err;
16728
+ let fed = false;
16729
+ while (this.pos < n && this.dec.decodeQueueSize < 8 && this.out.length < 3) {
16730
+ const s = this.samples[this.pos++];
16731
+ this.dec.decode(new EncodedVideoChunk({
16732
+ type: s.key ? "key" : "delta", timestamp: Math.round(s.pts * 1e6),
16733
+ duration: Math.round(s.dur * 1e6), data: await this.bytes(s),
16734
+ }));
16735
+ fed = true;
16736
+ }
16737
+ if (!fed && this.pos >= n && this.dec.decodeQueueSize === 0) {
16738
+ await this.dec.flush().catch((e) => { this.err = this.err || e; });
16739
+ this.pos = n + 1; // after a flush the decoder needs a sync sample again
16740
+ if (!this.out.length) { if (this.err) throw this.err; return this.cur; }
16741
+ continue;
16742
+ }
16743
+ await new Promise((res) => { this.wake = res; setTimeout(res, 50); });
16744
+ }
16745
+ }
16746
+ close() {
16747
+ this.dropQueue();
16748
+ if (this.cur) { this.cur.close(); this.cur = null; }
16749
+ if (this.dec && this.dec.state !== "closed") this.dec.close();
16750
+ this.dec = null; this.win = null;
16751
+ }
16752
+ }
16753
+ /** Export-time decode state: clip id → source (or null: use the element). */
16754
+ function exportDecodeBegin() {
16755
+ runtime.exportDecode = runtime.noExportDecode ? null : { sources: new Map(), opening: new Map() };
16756
+ runtime.exportFrames = new Map();
16757
+ }
16758
+ function exportDecodeEnd() {
16759
+ const d = runtime.exportDecode;
16760
+ if (d) for (const s of d.sources.values()) s?.close();
16761
+ runtime.exportDecode = null;
16762
+ runtime.exportFrames = null;
16763
+ }
16764
+ /** Decode the frame of video clip c for timeline time t; false when the clip
16765
+ * stays on the <video> path. Frames go to runtime.exportFrames for drawing. */
16766
+ async function exportDecodeFrame(c, t) {
16767
+ const d = runtime.exportDecode;
16768
+ if (!d || c.kind !== "video" || evalProps(c, t).bgRemove) return false;
16769
+ let src = d.sources.get(c.id);
16770
+ if (src === undefined) {
16771
+ const m = getMedia(c.mediaId);
16772
+ if (!m || !m.src) { d.sources.set(c.id, null); return false; }
16773
+ if (!d.opening.has(c.id)) d.opening.set(c.id, ExportFrameSource.open(m.src));
16774
+ src = await d.opening.get(c.id);
16775
+ d.sources.set(c.id, src);
16776
+ }
16777
+ if (!src) return false;
16778
+ try {
16779
+ runtime.exportFrames.set(c.id, await src.frameAt(mediaTimeAt(c, t)));
16780
+ return true;
16781
+ } catch (e) { // a decode error: this clip falls back to its element for the rest of the export
16782
+ console.warn("[FableCut] export decode failed, using the video element:", e && e.message);
16783
+ src.close(); d.sources.set(c.id, null); runtime.exportFrames.delete(c.id);
16784
+ return false;
16785
+ }
16786
+ }
15003
16787
  async function seekVideosTo(t, { queueBusy } = {}) {
15004
16788
  const fps = projectFps();
15005
16789
  const frameMs = 1000 / fps;
@@ -15011,9 +16795,26 @@ async function seekVideosTo(t, { queueBusy } = {}) {
15011
16795
  const keepPlaying = fast && !behind && !queueBusy;
15012
16796
  const waits = [];
15013
16797
  const restoreGain = [];
16798
+ const decoded = new Set();
16799
+ const dec = runtime.exportDecode;
16800
+ if (dec) {
16801
+ const jobs = [];
16802
+ for (const c of mediaClips()) {
16803
+ if (c.kind !== "video" || !clipRenders(c)) continue;
16804
+ if (!activeAt(c, t)) { // export runs forward: past its end, free the clip's decoder
16805
+ const s = dec.sources.get(c.id);
16806
+ if (s && t > c.start + c.duration) { s.close(); dec.sources.delete(c.id); dec.opening.delete(c.id); }
16807
+ runtime.exportFrames.delete(c.id);
16808
+ continue;
16809
+ }
16810
+ jobs.push(exportDecodeFrame(c, t).then((ok) => { if (ok) decoded.add(c.id); }));
16811
+ }
16812
+ await Promise.all(jobs);
16813
+ }
15014
16814
  for (const c of mediaClips()) {
15015
16815
  if (c.kind !== "video") continue;
15016
16816
  if (!clipRenders(c)) continue;
16817
+ if (decoded.has(c.id)) continue;
15017
16818
  const el = getClipEl(c); if (!el) continue;
15018
16819
  if (!activeAt(c, t)) {
15019
16820
  if (!el.paused) el.pause();
@@ -15242,6 +17043,7 @@ async function fastExport(opts = {}) {
15242
17043
  resetExportCanvases();
15243
17044
  await armExportCors();
15244
17045
  await useOriginalPlayers(); // proxies are for editing — export reads the originals
17046
+ exportDecodeBegin();
15245
17047
  // JPEG off the compositor thread: snapshot is sync, encode/upload run ahead
15246
17048
  // under backpressure. Awaiting toBlob every frame was slower than ffmpeg.
15247
17049
  const up = createExportUploader(sessId, {
@@ -15349,6 +17151,7 @@ async function fastExport(opts = {}) {
15349
17151
  } finally {
15350
17152
  exportAbort = null;
15351
17153
  exportFullCanvas = false;
17154
+ exportDecodeEnd();
15352
17155
  restoreExportVideoState();
15353
17156
  endExportWindow();
15354
17157
  state.exporting = false; state.rendering = false;
@@ -15567,6 +17370,7 @@ async function runExportJob(ticket) {
15567
17370
  if (ticket.revision != null && (project.revision || 0) < ticket.revision) await syncFromServer();
15568
17371
  if (ticket.kind === "scopes") return runScopesJob(ticket, fail);
15569
17372
  if (ticket.kind === "track") return runTrackJob(ticket, fail);
17373
+ if (ticket.kind === "transcribe") return runTranscribeJob(ticket, fail);
15570
17374
  if (!state.ffmpeg) {
15571
17375
  const j = await fetch("/api/export/ffmpeg").then((r) => r.json()).catch(() => ({}));
15572
17376
  state.ffmpeg = !!j.available;
@@ -15956,6 +17760,7 @@ async function webCodecsExport() {
15956
17760
  resetExportCanvases();
15957
17761
  await armExportCors();
15958
17762
  await useOriginalPlayers(); // proxies are for editing — export reads the originals
17763
+ exportDecodeBegin();
15959
17764
 
15960
17765
  for (let f = 0; f < frames; f++) {
15961
17766
  if (renderCancelled || signal.aborted) throw new Error("cancelled");
@@ -16011,6 +17816,7 @@ async function webCodecsExport() {
16011
17816
  if (msg !== "cancelled") alert("Export failed: " + msg);
16012
17817
  } finally {
16013
17818
  exportAbort = null;
17819
+ exportDecodeEnd();
16014
17820
  restoreExportVideoState();
16015
17821
  endExportWindow();
16016
17822
  state.exporting = false; state.rendering = false;
@@ -16815,6 +18621,18 @@ window.addEventListener("keydown", (e) => {
16815
18621
  return;
16816
18622
  }
16817
18623
  }
18624
+ // Ctrl/Cmd+S: save a version of the open project (the editor saves every change anyway)
18625
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (k === "s" || k === "S")) {
18626
+ e.preventDefault(); // never the browser's Save Page dialog, and not S (split) either
18627
+ if (!e.repeat && $("btnProjectsDash") && !$("btnProjectsDash").classList.contains("hidden")) saveVersionNow(); // holding the keys makes one
18628
+ return;
18629
+ }
18630
+ // Ctrl/Cmd+O: the Projects dashboard (where the editor server has projects)
18631
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (k === "o" || k === "O") && $("btnProjectsDash") && !$("btnProjectsDash").classList.contains("hidden")) {
18632
+ e.preventDefault();
18633
+ openProjects();
18634
+ return;
18635
+ }
16818
18636
  if (k === "Escape" && els.importUrlOverlay && !els.importUrlOverlay.classList.contains("hidden")) {
16819
18637
  e.preventDefault();
16820
18638
  closeImportUrl();
@@ -16864,7 +18682,7 @@ window.addEventListener("keydown", (e) => {
16864
18682
  e.preventDefault(); // Ctrl/Cmd+L would otherwise focus the address bar
16865
18683
  toggleLinkSelected();
16866
18684
  }
16867
- else if (k === "s" || k === "S") splitAtPlayhead();
18685
+ else if ((k === "s" || k === "S") && !e.ctrlKey && !e.metaKey) splitAtPlayhead();
16868
18686
  else if (k === "," && !e.ctrlKey && !e.metaKey && !e.altKey) {
16869
18687
  e.preventDefault();
16870
18688
  insertSourceAtPlayhead();
@@ -18257,7 +20075,7 @@ for (const b of els.sideTabs.querySelectorAll("[data-side]"))
18257
20075
  b.addEventListener("click", () => setSideTab(b.dataset.side));
18258
20076
  try {
18259
20077
  const side = localStorage.getItem(SIDE_TAB_KEY);
18260
- if (side === "mixer" || side === "color") setSideTab(side);
20078
+ if (side === "mixer" || side === "color" || side === "transcript") setSideTab(side);
18261
20079
  if (localStorage.getItem(WS_KEY) === "color") setWorkspace("color");
18262
20080
  } catch { }
18263
20081
  connectServer().then(() => { loadLibraryFonts(); runExportJobFromUrl(); });