fablecut 1.15.0 โ†’ 1.16.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
@@ -735,14 +735,16 @@ const runtime = {
735
735
  clipEls: new Map(), // clipId -> HTMLMediaElement
736
736
  clipGain: new Map(), // clipId -> GainNode
737
737
  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)
738
+ audioBufs: new Map(), // media src -> Promise<AudioBuffer> (waveforms + export mix); by file, so a relinked entry decodes its new one
739
+ wavePeaks: new Map(), // mediaId -> {src, channels: Float32Array[], max: Float32Array} | Float32Array (legacy) | {src, pending}
740
740
  library: {}, // dir -> [{name, rel, src, size}] cached /api/library results
741
741
  customFonts: [], // family names loaded from /library/fonts
742
742
  libraryFontReq: new Set(), // library families claimed by a load pass
743
743
  googleLoaded: new Set(), // loaded from Google Fonts (the font picker lists them)
744
744
  fontReq: new Map(), // font name -> Promise<boolean> (ensureFont)
745
745
  undo: [], redo: [],
746
+ seqUndo: new Map(), // sequence id -> {undo, redo, time, sel}: each sequence keeps its own undo history this session
747
+ seqOpen: null, // the open sequence's id, to notice another one being opened
746
748
  audio: null, // {ctx, master (sum), masterOut (fader), trackBus, recDest, meter?, meterReady?}
747
749
  saveTimer: null, pendingSync: false,
748
750
  sfxPreview: null, // <audio> element for library sound previews
@@ -1195,6 +1197,8 @@ async function connectServer() {
1195
1197
  applyProject(data);
1196
1198
  state.connected = true;
1197
1199
  els.projectName.textContent = project.name + " ยท ๐ŸŸข connected";
1200
+ runtime.projectId = res.headers.get("X-FableCut-Project");
1201
+ if (res.headers.get("X-FableCut-Projects")) initProjectsUi();
1198
1202
  listenSSE();
1199
1203
  fetch("/api/export/ffmpeg").then((r) => r.json())
1200
1204
  .then((j) => { state.ffmpeg = !!j.available; }).catch(() => { });
@@ -1204,6 +1208,7 @@ async function connectServer() {
1204
1208
  state.connected = false;
1205
1209
  els.projectName.textContent = project.name + " ยท โšช local session";
1206
1210
  }
1211
+ initSequencesUi();
1207
1212
  await probeMissingMeta();
1208
1213
  }
1209
1214
  /* Main-profile AVC level by canvas height; Annex-B is required so ffmpeg
@@ -1446,6 +1451,14 @@ function syncExportFrameSel() {
1446
1451
  els.exportFrameSel.innerHTML = html;
1447
1452
  }
1448
1453
  function applyProject(data, opts = {}) {
1454
+ if (state.compCtx && !opts.ctx && SeqLib.activeId(data) !== SeqLib.activeId(state.compCtx.root)) {
1455
+ // another sequence was opened (an agent, another tab): the comp was opened from the old one
1456
+ state.compCtx = null;
1457
+ runtime.undo.length = 0; runtime.redo.length = 0;
1458
+ applyProject(data, { ctx: true });
1459
+ syncCompCrumb();
1460
+ return;
1461
+ }
1449
1462
  if (state.compCtx && !opts.ctx) { // the root changed on disk (an agent, another tab): keep the open comp open
1450
1463
  const x = state.compCtx;
1451
1464
  x.root = data;
@@ -1458,6 +1471,7 @@ function applyProject(data, opts = {}) {
1458
1471
  syncCompCrumb();
1459
1472
  return;
1460
1473
  }
1474
+ if (!state.compCtx) noteOpenSequence(data);
1461
1475
  const wa = normalizeWorkArea(data.inPoint, data.outPoint);
1462
1476
  Object.assign(project, {
1463
1477
  name: data.name || "Untitled Project",
@@ -1478,6 +1492,9 @@ function applyProject(data, opts = {}) {
1478
1492
  outputs: Array.isArray(data.outputs) ? data.outputs.filter((o) => o && typeof o === "object") : null,
1479
1493
  master: normalizeMaster(data.master),
1480
1494
  buses: normalizeBuses(data.buses),
1495
+ // the sequences that aren't open, kept as they are (see sequences.js); the open one is this document
1496
+ sequences: Array.isArray(data.sequences) && data.sequences.length ? data.sequences : null,
1497
+ sequence: Array.isArray(data.sequences) && data.sequences.length ? SeqLib.activeId(data) : null,
1481
1498
  comps: (Array.isArray(data.comps) ? data.comps : []).filter((cp) => cp && cp.id).map((cp) => ({
1482
1499
  ...cp, clips: (cp.clips || []).map((x) => {
1483
1500
  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 +1573,38 @@ function scheduleSave() {
1556
1573
  state.dirtyTimeline = true;
1557
1574
  if (!state.connected) return;
1558
1575
  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);
1576
+ runtime.saveTimer = setTimeout(() => { runtime.saveTimer = null; runtime.saving = saveNow(); }, 400);
1577
+ }
1578
+ async function saveNow() {
1579
+ project.revision++;
1580
+ const body = JSON.stringify(projectJSON(), null, 2);
1581
+ try {
1582
+ const headers = { "Content-Type": "application/json" };
1583
+ if (runtime.projectId) headers["X-FableCut-Project"] = runtime.projectId; // the project this edit belongs to
1584
+ const res = await fetch("/api/project", { method: "PUT", headers, body });
1585
+ if (res.status === 409) {
1586
+ // an external tool saved a newer revision while this change was pending
1587
+ const loaded = await syncFromServer(true);
1588
+ toast("Project was updated externally โ€” your last change may need redoing.");
1589
+ runtime.saveFailed = loaded !== true;
1590
+ return loaded === true; // the newer document on disk is now what this tab shows
1591
+ }
1592
+ runtime.saveFailed = !res.ok;
1593
+ return res.ok;
1594
+ } catch { runtime.saveFailed = true; return false; }
1595
+ }
1596
+ /** Write a pending edit now (and wait for one in flight), e.g. before switching projects.
1597
+ * False when that save did not land. */
1598
+ async function flushSave() {
1599
+ try { await runtime.saving; } catch { }
1600
+ // a pending edit, or one whose last save did not land: send it (again) now
1601
+ if (runtime.saveTimer || runtime.saveFailed) { clearTimeout(runtime.saveTimer); runtime.saveTimer = null; runtime.saving = saveNow(); }
1602
+ try { return (await runtime.saving) !== false; } catch { return false; }
1603
+ }
1604
+ async function flushSaveBeforeSwitch() {
1605
+ if (await flushSave()) return true;
1606
+ toast("Your last change couldn't be saved, so the project stays open. Try again in a moment.");
1607
+ return false;
1572
1608
  }
1573
1609
  /** One clip as saved: only the fields the editor knows (unknown runtime fields stay out). */
1574
1610
  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 +1666,10 @@ function projectJSONHere() {
1630
1666
  const buses = normalizeBuses(project.buses);
1631
1667
  if (buses.length) out.buses = buses;
1632
1668
  if (project.comps && project.comps.length) out.comps = project.comps.map((cp) => ({ ...cp, clips: (cp.clips || []).map(serializeClip) }));
1669
+ if (project.sequences) {
1670
+ out.sequences = project.sequences.map((sq) => (sq.id === project.sequence ? { id: sq.id, name: sq.name } : sq));
1671
+ out.sequence = project.sequence;
1672
+ }
1633
1673
  return out;
1634
1674
  }
1635
1675
  function listenSSE() {
@@ -1637,6 +1677,21 @@ function listenSSE() {
1637
1677
  // Named events: "change" = project/media/library; "profiles" = encoding-profiles.json only
1638
1678
  es.addEventListener("change", () => { noteActivity(); syncFromServer(); scheduleOfflineCheck(); });
1639
1679
  es.addEventListener("proxy", (e) => onProxyEvent(e.data));
1680
+ es.addEventListener("versions", (e) => {
1681
+ let d = {};
1682
+ try { d = JSON.parse(e.data); } catch { }
1683
+ if (!(projectsOpen() && pj.verOf && d.project === pj.verOf)) return;
1684
+ if (pj.busy) { pj.verPending = true; return; } // pjVersionAction refreshes when it is done
1685
+ if (document.querySelector(".ver-rename")) return; // a rename is being typed: it refreshes the list when it ends
1686
+ pjDropDiffs(); // a comparison made before this change no longer holds
1687
+ pjLoadVersions();
1688
+ });
1689
+ es.addEventListener("projects", (e) => {
1690
+ let d = {};
1691
+ try { d = JSON.parse(e.data); } catch { }
1692
+ if (d.active && runtime.projectId && d.active !== runtime.projectId) syncFromServer(true);
1693
+ else if (projectsOpen() && !pj.busy) pjLoad();
1694
+ });
1640
1695
  es.addEventListener("export", (e) => {
1641
1696
  noteActivity();
1642
1697
  try { runExportJob(JSON.parse(e.data)); } catch { }
@@ -1665,19 +1720,40 @@ function listenSSE() {
1665
1720
  e.g. Claude โ€” wrote it). Our own saves land at our exact local revision, so
1666
1721
  they compare equal and are skipped without any timing heuristics. Deferred
1667
1722
  during gestures/exports and re-run when they end (runtime.pendingSync). */
1723
+ /** True when the server's document was loaded (a later caller may rely on it). */
1668
1724
  async function syncFromServer(force) {
1669
- if (state.gesture || state.exporting) { runtime.pendingSync = true; return; }
1725
+ if (state.gesture || state.exporting) { runtime.pendingSync = true; return false; }
1670
1726
  runtime.pendingSync = false;
1671
1727
  if (state.binTab === "templates") fetchSaved("templates").then(() => { if (state.binTab === "templates") renderTemplatesTab(); });
1672
1728
  else if (state.binTab !== "project" && state.binTab !== "shapes") fetchLibrary(state.binTab).then(renderLibrary);
1673
1729
  fetchSaved("presets");
1674
1730
  loadLibraryFonts();
1675
1731
  fetchEncodeProfiles();
1732
+ const seq = runtime.syncSeq = (runtime.syncSeq || 0) + 1;
1676
1733
  try {
1677
1734
  const res = await fetch("/api/project", { cache: "no-store" });
1678
1735
  if (!res.ok) return;
1679
1736
  const data = await res.json();
1737
+ if (seq !== runtime.syncSeq) return; // a newer reload is on its way: this answer may be older than it
1680
1738
  if (!data || !Array.isArray(data.clips)) return;
1739
+ // another project was opened (the dashboard, another tab, an agent)
1740
+ const pid = res.headers.get("X-FableCut-Project");
1741
+ const switched = !!(pid && runtime.projectId && pid !== runtime.projectId);
1742
+ if (pid) runtime.projectId = pid;
1743
+ if (switched) {
1744
+ onProjectSwitched();
1745
+ applyProject(data);
1746
+ { // decoded audio is by file: keep what this project uses, free the rest
1747
+ const srcs = new Set(project.media.map((m) => m.src));
1748
+ for (const src of [...runtime.audioBufs.keys()]) if (!srcs.has(src)) runtime.audioBufs.delete(src);
1749
+ }
1750
+ setTime(0);
1751
+ syncCompCrumb();
1752
+ if (!pj.selfSwitch) toast(`Switched to โ€œ${project.name}โ€`);
1753
+ if (projectsOpen()) pjLoad();
1754
+ await probeMissingMeta();
1755
+ return true;
1756
+ }
1681
1757
  if (!force && (data.revision || 0) === (project.revision || 0)) return; // our own save
1682
1758
  if (runtime.saveTimer) { // unsaved local edit vs. external write: external wins, tell the user
1683
1759
  clearTimeout(runtime.saveTimer); runtime.saveTimer = null;
@@ -1686,8 +1762,14 @@ async function syncFromServer(force) {
1686
1762
  toast("Project was updated externally โ€” your last change may need redoing.");
1687
1763
  }
1688
1764
  applyProject(data);
1765
+ syncCompCrumb(); // the top bar shows the project's name
1766
+ // "Compare with now" was against the document before this change
1767
+ // (always: a comparison still on its way was made against the old document too)
1768
+ if (pj.verOf === runtime.projectId) { const had = pj.verDiff.size; pjDropDiffs(); if (had && projectsOpen()) renderProjectGrid(); }
1689
1769
  await probeMissingMeta();
1770
+ return true;
1690
1771
  } catch { }
1772
+ return false;
1691
1773
  }
1692
1774
  /** Populate a media entry's duration/dimensions (and cache preview assets) by
1693
1775
  * dispatching on kind: svg loads its markup, image loads for width/height,
@@ -1697,7 +1779,9 @@ async function syncFromServer(force) {
1697
1779
  async function loadMediaMetadata(m) {
1698
1780
  if (m.kind === "svg") { await loadSvgMedia(m); return; }
1699
1781
  if (m.kind === "image") {
1782
+ const gen = runtime.projectGen;
1700
1783
  const img = await loadImage(m.src);
1784
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
1701
1785
  runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), img, imgSrc: m.src });
1702
1786
  m.width = img.naturalWidth; m.height = img.naturalHeight;
1703
1787
  return;
@@ -1752,6 +1836,7 @@ function loadImage(src) {
1752
1836
  });
1753
1837
  }
1754
1838
  async function grabThumb(m) {
1839
+ const gen = runtime.projectGen;
1755
1840
  const v = document.createElement("video");
1756
1841
  v.muted = true; v.preload = "auto";
1757
1842
  if (isCrossOriginSrc(m.src)) v.crossOrigin = "anonymous";
@@ -1762,6 +1847,7 @@ async function grabThumb(m) {
1762
1847
  const c = document.createElement("canvas");
1763
1848
  c.width = 160; c.height = 90;
1764
1849
  c.getContext("2d").drawImage(v, 0, 0, 160, 90);
1850
+ if (gen !== runtime.projectGen) { v.src = ""; return; }
1765
1851
  runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), thumb: c.toDataURL("image/jpeg", 0.6) });
1766
1852
  v.src = "";
1767
1853
  renderBin(); state.dirtyTimeline = true;
@@ -1773,20 +1859,24 @@ function getDecodeCtx() {
1773
1859
  return decodeCtx || (decodeCtx = new (window.AudioContext || window.webkitAudioContext)());
1774
1860
  }
1775
1861
  function getAudioBuffer(m) {
1776
- let p = runtime.audioBufs.get(m.id);
1862
+ const src = m.src;
1863
+ let p = runtime.audioBufs.get(src);
1777
1864
  if (!p) {
1778
- p = fetch(m.src).then((r) => r.arrayBuffer())
1865
+ p = fetch(src).then((r) => r.arrayBuffer())
1779
1866
  .then((ab) => getDecodeCtx().decodeAudioData(ab));
1780
- runtime.audioBufs.set(m.id, p);
1781
- p.catch(() => runtime.audioBufs.delete(m.id));
1867
+ runtime.audioBufs.set(src, p);
1868
+ p.catch(() => runtime.audioBufs.delete(src));
1782
1869
  }
1783
1870
  return p;
1784
1871
  }
1785
1872
  function ensureWave(m) {
1786
1873
  // 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
1874
+ if (m.kind !== "audio" && m.kind !== "video") return;
1875
+ const have = runtime.wavePeaks.get(m.id), src = m.src;
1876
+ if (have && (have instanceof Float32Array || have.src === src)) return;
1877
+ runtime.wavePeaks.set(m.id, { src, pending: true });
1789
1878
  getAudioBuffer(m).then((buf) => {
1879
+ if (runtime.wavePeaks.get(m.id)?.src !== src) return; // the entry points at another file now (relink, another project)
1790
1880
  const n = Math.max(1, Math.ceil(buf.duration * WAVE_PEAKS_PER_SEC));
1791
1881
  const step = buf.length / n;
1792
1882
  const channels = [];
@@ -1808,10 +1898,10 @@ function ensureWave(m) {
1808
1898
  for (const p of channels) if (p[i] > mx) mx = p[i];
1809
1899
  max[i] = mx;
1810
1900
  }
1811
- runtime.wavePeaks.set(m.id, { channels, max });
1901
+ runtime.wavePeaks.set(m.id, { src, channels, max });
1812
1902
  if (m.channels == null) m.channels = buf.numberOfChannels;
1813
1903
  state.dirtyTimeline = true;
1814
- }).catch(() => runtime.wavePeaks.delete(m.id));
1904
+ }).catch(() => { if (runtime.wavePeaks.get(m.id)?.src === src) runtime.wavePeaks.delete(m.id); });
1815
1905
  }
1816
1906
  function wavePeaksFor(c) {
1817
1907
  const w = runtime.wavePeaks.get(c.mediaId);
@@ -1846,7 +1936,7 @@ async function importFiles(fileList) {
1846
1936
  ? runtime.importFolderId : null;
1847
1937
  runtime.importFolderId = null;
1848
1938
  let added = 0, skipped = 0;
1849
- const addedMedia = [];
1939
+ const addedMedia = [], gen = runtime.projectGen;
1850
1940
  for (const file of files) {
1851
1941
  const kind = mediaKindFromFile(file);
1852
1942
  if (!kind) { skipped++; continue; }
@@ -1866,6 +1956,7 @@ async function importFiles(fileList) {
1866
1956
  if (kind === "video") grabThumb(m).catch(() => { });
1867
1957
  ensureWave(m);
1868
1958
  } catch { skipped++; continue; }
1959
+ if (gen !== runtime.projectGen) { toast("Import stopped: another project was opened. The uploaded files are in media/"); break; }
1869
1960
  project.media.push(m);
1870
1961
  addedMedia.push(m);
1871
1962
  added++;
@@ -1916,6 +2007,7 @@ async function importFromUrl(url) {
1916
2007
  if (!state.connected) { toast("Import from URL needs the editor server"); return; }
1917
2008
  runtime.importUrlAbort = new AbortController();
1918
2009
  setImportUrlBusy(true);
2010
+ const gen = runtime.projectGen;
1919
2011
  try {
1920
2012
  const res = await fetch("/api/import-url", {
1921
2013
  method: "POST",
@@ -1936,6 +2028,7 @@ async function importFromUrl(url) {
1936
2028
  if (kind === "video") grabThumb(m).catch(() => { });
1937
2029
  ensureWave(m);
1938
2030
  } catch { /* browser will retry via probeMissingMeta */ }
2031
+ if (gen !== runtime.projectGen) throw new Error("another project was opened โ€” the file is in media/");
1939
2032
  project.media.push(m);
1940
2033
  renderBin(); scheduleSave();
1941
2034
  closeImportUrl();
@@ -2202,6 +2295,7 @@ function usageDoc() {
2202
2295
  return {
2203
2296
  media: project.media,
2204
2297
  clips: state.compCtx.root.clips || [],
2298
+ sequences: state.compCtx.root.sequences, sequence: state.compCtx.root.sequence,
2205
2299
  comps: (project.comps || []).map((c) => (c.id === id ? { ...c, clips: project.clips } : c)),
2206
2300
  };
2207
2301
  }
@@ -2354,7 +2448,9 @@ function newCollection(name, mediaIds) {
2354
2448
  return col;
2355
2449
  }
2356
2450
  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; }
2451
+ 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; }
2452
+ const elsewhere = SeqLib.others(seqRoot()).find((sq) => (sq.clips || []).some((c) => c.mediaId === m.id));
2453
+ if (elsewhere) { toast(`It's used in the sequence โ€œ${elsewhere.name}โ€ โ€” remove its clips there first`); return; }
2358
2454
  pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media })); // undo brings the media back too
2359
2455
  project.media = project.media.filter((x) => x.id !== m.id);
2360
2456
  project.clips = project.clips.filter((c) => c.mediaId !== m.id);
@@ -2508,13 +2604,14 @@ function showMediaInstances(m, x, y) {
2508
2604
  for (const p of list) {
2509
2605
  const b = document.createElement("button");
2510
2606
  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>`;
2607
+ 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
2608
  b.addEventListener("click", () => { goToPlacement(p); });
2513
2609
  pop.appendChild(b);
2514
2610
  }
2515
2611
  showPopover(pop, x, y);
2516
2612
  }
2517
2613
  function goToPlacement(p) {
2614
+ if (p.sequence && !openSequence(p.sequence)) return;
2518
2615
  const here = compCtxId();
2519
2616
  if (p.comp !== here) {
2520
2617
  if (state.compCtx) exitComp(state.compCtx.path.length);
@@ -2614,7 +2711,7 @@ function reloadMediaSource(m, oldSrc) {
2614
2711
  /** Point a media entry at another file. mode "relink" (same footage) or "replace" (a new file). */
2615
2712
  async function setMediaSource(m, src, mode, name) {
2616
2713
  const oldSrc = m.src, oldDur = m.duration;
2617
- pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media }));
2714
+ pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media, seqClips: otherSequenceClips() }));
2618
2715
  m.src = src;
2619
2716
  for (const k of MediaLib.INFO_KEYS) delete m[k];
2620
2717
  if (mode === "replace") {
@@ -2642,6 +2739,7 @@ async function setMediaSource(m, src, mode, name) {
2642
2739
  fit(project.clips);
2643
2740
  for (const comp of project.comps || []) fit(comp.clips);
2644
2741
  if (state.compCtx) fit(state.compCtx.root.clips);
2742
+ for (const sq of SeqLib.others(seqRoot())) fit(sq.clips);
2645
2743
  runtime.compGen = (runtime.compGen || 0) + 1;
2646
2744
  if (trimmed) msg += ` โ€” ${trimmed} clip edge${trimmed === 1 ? "" : "s"} trimmed to fit`;
2647
2745
  if (m.kind === "video") for (const c of project.clips) if (c.mediaId === m.id && c.kind === "video") reconcileAudioChannels(c);
@@ -3013,7 +3111,7 @@ function mediaForLibraryItem(f) {
3013
3111
  return m;
3014
3112
  }
3015
3113
  async function addLibraryItem(f, trackId, at) {
3016
- const m = mediaForLibraryItem(f);
3114
+ const m = mediaForLibraryItem(f), gen = runtime.projectGen;
3017
3115
  if (!m) { toast("Unsupported file type: " + f.name); return; }
3018
3116
  if ((m.kind === "audio" || m.kind === "video") && (m.duration == null || isNaN(m.duration))) {
3019
3117
  try { await loadMediaMetadata(m); } catch { }
@@ -3026,6 +3124,7 @@ async function addLibraryItem(f, trackId, at) {
3026
3124
  if (m.kind === "image" && !runtime.mediaAux.get(m.id)?.img) {
3027
3125
  try { await loadMediaMetadata(m); } catch { }
3028
3126
  }
3127
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
3029
3128
  addClipFromMedia(m, trackId, at);
3030
3129
  }
3031
3130
  function toggleSfxPreview(f, btn) {
@@ -3103,6 +3202,600 @@ function setBinTab(tab) {
3103
3202
  else if (!isProj) fetchLibrary(tab).then(renderLibrary);
3104
3203
  }
3105
3204
 
3205
+ /* โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• PROJECTS (dashboard) โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• */
3206
+ /* Several projects in one data folder (projects.js on the server). The open one
3207
+ is always ./project.json, so everything else in the editor is unchanged; the
3208
+ dashboard lists the others and switches between them. A switch shows up in
3209
+ syncFromServer as a new X-FableCut-Project id, wherever it came from (this
3210
+ tab, another tab, an agent): undo, the open comp and the Source monitor
3211
+ belong to the old project and are reset there. */
3212
+ const pj = {
3213
+ view: "active", // active | archived
3214
+ mode: "detail", // detail | new
3215
+ sel: null, list: [], templates: [], tpl: "landscape-1080",
3216
+ sort: "opened", search: "", busy: false, selfSwitch: false,
3217
+ verOf: null, versions: [], verDiff: new Map(), // the versions view: whose, its list, open comparisons
3218
+ verDiffGen: 0, verPending: false, // bumped when comparisons are dropped ยท a list refresh waiting for a busy action
3219
+ };
3220
+ const pjFmtDur = (s) => {
3221
+ if (!(s > 0)) return "0:00";
3222
+ const m = Math.floor(s / 60), r = Math.floor(s % 60);
3223
+ return m >= 60 ? `${Math.floor(m / 60)}:${String(m % 60).padStart(2, "0")}:${String(r).padStart(2, "0")}` : `${m}:${String(r).padStart(2, "0")}`;
3224
+ };
3225
+ function pjAgo(iso) {
3226
+ if (!iso) return "never";
3227
+ const s = (Date.now() - new Date(iso).getTime()) / 1000;
3228
+ if (!(s >= 0)) return new Date(iso).toLocaleDateString();
3229
+ if (s < 60) return "just now";
3230
+ if (s < 3600) return `${Math.floor(s / 60)} min ago`;
3231
+ if (s < 86400) return `${Math.floor(s / 3600)} h ago`;
3232
+ if (s < 86400 * 7) return `${Math.floor(s / 86400)} d ago`;
3233
+ return new Date(iso).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
3234
+ }
3235
+ const pjFps = (f) => (f ? `${+(+f).toFixed(3)} fps` : "");
3236
+ async function pjPost(body) {
3237
+ try {
3238
+ const res = await fetch("/api/projects", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
3239
+ const out = await res.json().catch(() => ({}));
3240
+ if (!res.ok) { toast(out.error || `Projects: request failed (${res.status})`); return null; }
3241
+ return out;
3242
+ } catch { toast("Projects: the editor server did not answer"); return null; }
3243
+ }
3244
+ /* The program monitor's picture, small, as the open project's card thumbnail. */
3245
+ async function pjSnapThumb() {
3246
+ const id = runtime.projectId, cv = els.preview;
3247
+ if (!id || !cv || !cv.width || !cv.height) return;
3248
+ try {
3249
+ const w = 360, h = Math.max(1, Math.round(w * cv.height / cv.width));
3250
+ const c = document.createElement("canvas");
3251
+ c.width = w; c.height = h;
3252
+ c.getContext("2d").drawImage(cv, 0, 0, w, h);
3253
+ const blob = await new Promise((r) => c.toBlob(r, "image/jpeg", 0.74));
3254
+ if (blob) await fetch("/api/projects/thumb?id=" + encodeURIComponent(id), { method: "PUT", body: blob });
3255
+ } catch { }
3256
+ }
3257
+ async function pjLoad() {
3258
+ try {
3259
+ const res = await fetch("/api/projects?archived=" + (pj.view === "archived" ? "only" : "exclude"), { cache: "no-store" });
3260
+ if (!res.ok) throw new Error();
3261
+ const data = await res.json();
3262
+ pj.list = data.projects || [];
3263
+ pj.templates = data.templates || [];
3264
+ // syncFromServer owns runtime.projectId: it resets undo, comp and Source on a switch.
3265
+ // On first use the list has just given the shown project.json its id: adopt it, if
3266
+ // project.json is still the document this tab shows.
3267
+ if (data.active && !runtime.projectId) {
3268
+ const r = await fetch("/api/project", { cache: "no-store" }).catch(() => null);
3269
+ const doc = r && r.ok ? await r.json().catch(() => null) : null;
3270
+ const ids = (d) => JSON.stringify([d.name, d.revision || 0, (d.clips || []).map((c) => c.id), (d.media || []).map((m) => m.id)]);
3271
+ const shown = projectJSON();
3272
+ if (doc && r.headers.get("X-FableCut-Project") === data.active && ids(doc) === ids(shown)) runtime.projectId = data.active;
3273
+ else { runtime.projectId = "?"; syncFromServer(true); } // not what this tab shows: load it as a switch
3274
+ } else if (data.active && data.active !== runtime.projectId) syncFromServer(true);
3275
+ if (!pj.list.some((p) => p.id === pj.sel)) pj.sel = (pj.list.find((p) => p.active) || pj.list[0] || {}).id || null;
3276
+ } catch { pj.list = []; toast("Projects: couldn't read the project list"); }
3277
+ renderProjects();
3278
+ }
3279
+ async function openProjects() {
3280
+ const ov = $("projectsOverlay");
3281
+ if (!ov || !state.connected) return;
3282
+ pj.mode = "detail"; pj.view = "active"; pj.sel = runtime.projectId;
3283
+ pj.verOf = null; pjDropDiffs(); // a versions list left open last time may be out of date
3284
+ ov.classList.remove("hidden");
3285
+ $("projectsDialog")?.focus();
3286
+ renderProjects(); // the shell at once; cards once the list is in
3287
+ await flushSave();
3288
+ await pjSnapThumb();
3289
+ await pjLoad();
3290
+ }
3291
+ function closeProjects() {
3292
+ $("projectsOverlay")?.classList.add("hidden");
3293
+ $("btnProjectsDash")?.focus();
3294
+ }
3295
+ const projectsOpen = () => !!$("projectsOverlay") && !$("projectsOverlay").classList.contains("hidden");
3296
+ function pjVisible() {
3297
+ const q = pj.search.trim().toLowerCase();
3298
+ const words = q ? q.split(/\s+/) : [];
3299
+ const hit = (p, w) => w.startsWith("#")
3300
+ ? (p.tags || []).some((t) => t.toLowerCase().includes(w.slice(1)))
3301
+ : [p.name, p.notes, ...(p.tags || [])].some((s) => String(s || "").toLowerCase().includes(w));
3302
+ const out = pj.list.filter((p) => words.every((w) => hit(p, w)));
3303
+ const key = { opened: (p) => p.opened || p.modified || "", modified: (p) => p.modified || "", created: (p) => p.created || "" }[pj.sort];
3304
+ if (key) out.sort((a, b) => String(key(b)).localeCompare(String(key(a))));
3305
+ else out.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }));
3306
+ return out;
3307
+ }
3308
+ function pjThumbHtml(p, big) {
3309
+ const ar = p.width > 0 && p.height > 0 ? `${p.width} / ${p.height}` : "16 / 9";
3310
+ const inner = p.thumb
3311
+ ? `<img src="/api/projects/thumb?id=${encodeURIComponent(p.id)}&v=${p.thumb}" alt="" loading="lazy" draggable="false">`
3312
+ : `<span>${p.width ? `${p.width}ร—${p.height}` : "?"}</span>`;
3313
+ return `<div class="pj-thumb${big ? " big" : ""}"><div class="pj-frame" style="aspect-ratio:${ar}">${inner}</div></div>`;
3314
+ }
3315
+ function renderProjects() {
3316
+ renderProjectGrid();
3317
+ renderProjectSide();
3318
+ }
3319
+ function renderProjectSide() {
3320
+ const side = $("pjSide");
3321
+ if (side) side.innerHTML = pj.mode === "new" ? pjNewHtml() : pjDetailHtml(pj.list.find((p) => p.id === pj.sel));
3322
+ $("pjNewBtn")?.classList.toggle("on", pj.mode === "new");
3323
+ }
3324
+ function renderProjectGrid() {
3325
+ const grid = $("pjGrid");
3326
+ if (!grid) return;
3327
+ for (const b of document.querySelectorAll("[data-pj-view]")) b.classList.toggle("on", b.dataset.pjView === pj.view);
3328
+ grid.classList.toggle("versions", !!pj.verOf);
3329
+ if (pj.verOf) { grid.innerHTML = pjVersionsHtml(); return; }
3330
+ const rows = pjVisible();
3331
+ grid.innerHTML = rows.length ? rows.map((p) => `
3332
+ <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"}">
3333
+ ${pjThumbHtml(p)}
3334
+ <span class="pj-card-name">${escapeHtml(p.name)}${p.active ? ` <span class="pj-badge">Open</span>` : ""}</span>
3335
+ <span class="pj-card-meta">${p.unreadable ? "file unreadable" : `${p.width}ร—${p.height} ยท ${pjFps(p.fps)} ยท ${pjFmtDur(p.duration)}`}</span>
3336
+ <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>
3337
+ </button>`).join("")
3338
+ : `<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>`;
3339
+ }
3340
+ function pjDetailHtml(p) {
3341
+ if (!p) return `<p class="dim">Pick a project to see its details.</p>`;
3342
+ const fact = (k, v) => `<dt>${k}</dt><dd>${v}</dd>`;
3343
+ const tpl = p.template && pj.templates.find((t) => t.id === p.template);
3344
+ return `${pjThumbHtml(p, true)}
3345
+ <label class="pj-field"><span>Name</span><input type="text" id="pjName" value="${escapeHtml(p.name)}" maxlength="120" spellcheck="false"></label>
3346
+ <dl class="pj-facts">
3347
+ ${fact("Canvas", p.unreadable ? "โ€”" : `${p.width}ร—${p.height} ยท ${pjFps(p.fps)}`)}
3348
+ ${fact("Length", `${pjFmtDur(p.duration)} ยท ${p.clips} clip${p.clips === 1 ? "" : "s"} ยท ${p.media} media`)}
3349
+ ${fact("Modified", pjAgo(p.modified))}
3350
+ ${fact("Opened", p.active ? "open now" : pjAgo(p.opened))}
3351
+ ${fact("Created", pjAgo(p.created))}
3352
+ ${tpl ? fact("Template", escapeHtml(tpl.name)) : ""}
3353
+ </dl>
3354
+ <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>
3355
+ <label class="pj-field"><span>Tags</span><input type="text" id="pjTags" value="${escapeHtml((p.tags || []).join(", "))}" placeholder="client, reel, draft" spellcheck="false"></label>
3356
+ <div class="pj-actions">
3357
+ ${p.archived
3358
+ ? `<button type="button" class="btn primary" data-pj-act="unarchive">Unarchive</button>
3359
+ <button type="button" class="btn danger-ghost" data-pj-act="delete" title="Deletes the project file. Its media stay in media/.">Deleteโ€ฆ</button>`
3360
+ : `<button type="button" class="btn primary" data-pj-act="open"${p.active ? " disabled" : ""}>${p.active ? "Currently open" : "Open"}</button>
3361
+ <button type="button" class="btn" data-pj-act="duplicate" title="A copy of the whole project (the footage is shared, not copied)">Duplicate</button>
3362
+ <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>
3363
+ <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>`}
3364
+ </div>
3365
+ <div class="pj-actions">
3366
+ <button type="button" class="btn" data-pj-act="versions" title="Saved versions of this project: compare, restore, mark the final cut">Versionsโ€ฆ</button>
3367
+ <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>
3368
+ </div>
3369
+ <div class="pj-inline hidden" id="pjTplRow">
3370
+ <input type="text" id="pjTplName" value="${escapeHtml(p.name)}" maxlength="120" aria-label="Template name" spellcheck="false">
3371
+ <button type="button" class="btn primary" data-pj-act="template-save">Save template</button>
3372
+ </div>`;
3373
+ }
3374
+ function pjNewHtml() {
3375
+ const tpls = pj.templates;
3376
+ if (!tpls.some((t) => t.id === pj.tpl)) pj.tpl = "landscape-1080";
3377
+ const t = tpls.find((x) => x.id === pj.tpl) || { fps: 30 };
3378
+ const shape = (x) => {
3379
+ const k = 22 / Math.max(x.width || 16, x.height || 9);
3380
+ return `<i class="pj-shape" style="width:${Math.round((x.width || 16) * k)}px;height:${Math.round((x.height || 9) * k)}px"></i>`;
3381
+ };
3382
+ const row = (x) => `<button type="button" class="pj-tpl${x.id === pj.tpl ? " on" : ""}" data-pj-tpl="${escapeHtml(x.id)}">
3383
+ ${shape(x)}<span class="pj-tpl-name">${escapeHtml(x.name)}</span>
3384
+ <span class="pj-tpl-meta dim">${x.width}ร—${x.height}${x.builtin ? "" : ` ยท ${x.clips} clip${x.clips === 1 ? "" : "s"}`}</span>
3385
+ ${x.builtin ? "" : `<span class="pj-tpl-del" data-pj-tpldel="${escapeHtml(x.id)}" role="button" tabindex="0" title="Delete this template">โœ•</span>`}
3386
+ </button>`;
3387
+ const saved = tpls.filter((x) => !x.builtin);
3388
+ return `<h3>New project</h3>
3389
+ <label class="pj-field"><span>Name</span><input type="text" id="pjNewName" value="Untitled Project" maxlength="120" spellcheck="false"></label>
3390
+ <div class="pj-field"><span>Start from</span>
3391
+ <div class="pj-tpls">${tpls.filter((x) => x.builtin).map(row).join("")}</div>
3392
+ ${saved.length ? `<span class="pj-sub">Saved templates</span><div class="pj-tpls">${saved.map(row).join("")}</div>` : ""}
3393
+ </div>
3394
+ <label class="pj-field"><span>Frame rate</span><select id="pjNewFps">
3395
+ <option value="">${t.fps ? `${+(+t.fps).toFixed(3)} fps (template)` : "Template's"}</option>
3396
+ ${[23.976, 24, 25, 29.97, 30, 50, 59.94, 60].map((f) => `<option value="${f}">${f} fps</option>`).join("")}
3397
+ </select></label>
3398
+ <div class="pj-actions">
3399
+ <button type="button" class="btn" data-pj-act="new-cancel">Cancel</button>
3400
+ <button type="button" class="btn primary" data-pj-act="new-create">Create and open</button>
3401
+ </div>`;
3402
+ }
3403
+ async function pjOpenProject(id) {
3404
+ const p = pj.list.find((x) => x.id === id);
3405
+ if (!p || p.active || pj.busy) return;
3406
+ if (state.exporting) { toast("Wait for the export to finish before switching projects"); return; }
3407
+ pj.busy = true;
3408
+ try {
3409
+ if (!(await flushSaveBeforeSwitch())) return;
3410
+ await pjSnapThumb();
3411
+ pj.selfSwitch = true;
3412
+ const out = await pjPost({ action: "open", id });
3413
+ if (!out) return;
3414
+ closeProjects();
3415
+ if (await syncFromServer(true)) toast(`Opened โ€œ${out.project?.name || p.name}โ€`);
3416
+ 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.`);
3417
+ } finally { pj.busy = false; pj.selfSwitch = false; }
3418
+ }
3419
+ async function pjBusy(fn) {
3420
+ pj.busy = true;
3421
+ try { return await fn(); } finally { pj.busy = false; }
3422
+ }
3423
+ async function pjAction(act, btn) {
3424
+ const p = pj.list.find((x) => x.id === pj.sel);
3425
+ if (act === "new-cancel") { pj.mode = "detail"; renderProjects(); return; }
3426
+ if (act === "new-create") {
3427
+ if (pj.busy) return;
3428
+ if (state.exporting) { toast("Wait for the export to finish before switching projects"); return; }
3429
+ const name = ($("pjNewName")?.value || "").trim() || "Untitled Project";
3430
+ const fps = $("pjNewFps")?.value;
3431
+ pj.busy = true;
3432
+ try {
3433
+ if (!(await flushSaveBeforeSwitch())) return;
3434
+ await pjSnapThumb();
3435
+ pj.selfSwitch = true;
3436
+ const out = await pjPost({ action: "new", name, template: pj.tpl, fps: fps ? +fps : undefined, open: true });
3437
+ if (!out) return;
3438
+ closeProjects();
3439
+ if (await syncFromServer(true)) toast(`Created โ€œ${name}โ€`);
3440
+ else toast(`โ€œ${name}โ€ was created and opened, but this tab couldn't load it yet. It will reload when the editor server answers.`);
3441
+ } finally { pj.busy = false; pj.selfSwitch = false; }
3442
+ return;
3443
+ }
3444
+ if (!p) return;
3445
+ if (act === "open") { pjOpenProject(p.id); return; }
3446
+ if (act === "template") { $("pjTplRow")?.classList.toggle("hidden"); $("pjTplName")?.select(); return; }
3447
+ if (act === "versions") { pj.verOf = p.id; pj.versions = []; pjDropDiffs(); renderProjectGrid(); pjLoadVersions(); return; }
3448
+ if (pj.busy) return; // one request at a time: a second click must not duplicate twice
3449
+ if (act === "template-save") {
3450
+ const out = await pjBusy(() => pjPost({ action: "save_template", id: p.id, name: $("pjTplName")?.value || p.name }));
3451
+ if (out) { toast(`Saved template โ€œ${out.template.name}โ€ โ€” pick it under + New project`); await pjLoad(); }
3452
+ return;
3453
+ }
3454
+ if (act === "delete") {
3455
+ if (btn.dataset.armed !== "1") {
3456
+ btn.dataset.armed = "1"; btn.textContent = "Click again to delete";
3457
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Deleteโ€ฆ"; } }, 3000);
3458
+ return;
3459
+ }
3460
+ const out = await pjBusy(() => pjPost({ action: "delete", id: p.id }));
3461
+ if (out) { toast(`Deleted โ€œ${p.name}โ€`); pj.sel = null; await pjLoad(); }
3462
+ return;
3463
+ }
3464
+ const out = await pjBusy(() => pjPost({ action: act, id: p.id }));
3465
+ if (!out) return;
3466
+ if (act === "duplicate") { pj.sel = out.id; toast(`Duplicated as โ€œ${out.project.name}โ€`); }
3467
+ if (act === "archive") toast(`Archived โ€œ${p.name}โ€ โ€” it's under Archived`);
3468
+ if (act === "unarchive") toast(`โ€œ${p.name}โ€ is back in Projects`);
3469
+ await pjLoad();
3470
+ }
3471
+ async function pjSaveField(field) {
3472
+ const p = pj.list.find((x) => x.id === pj.sel);
3473
+ if (!p) return;
3474
+ const el = $({ name: "pjName", notes: "pjNotes", tags: "pjTags" }[field]);
3475
+ if (!el) return;
3476
+ const v = el.value;
3477
+ if (field === "name" && (!v.trim() || v.trim() === p.name)) { if (!v.trim()) el.value = p.name; return; }
3478
+ if (field === "notes" && v === (p.notes || "")) return;
3479
+ if (field === "tags" && v === (p.tags || []).join(", ")) return;
3480
+ const out = await pjPost({ action: "update", id: p.id, [field]: field === "name" ? v.trim() : v });
3481
+ if (!out) return;
3482
+ Object.assign(p, out.project);
3483
+ if (field === "tags") el.value = (out.project.tags || []).join(", ");
3484
+ if (field === "name") renderProjectGrid();
3485
+ }
3486
+ async function pjImport(file) {
3487
+ let doc;
3488
+ try { doc = JSON.parse((await file.text()).replace(/^๏ปฟ/, "")); }
3489
+ catch { toast(`${file.name} isn't JSON`); return; }
3490
+ const name = doc && doc.name && doc.name !== "Untitled Project" ? doc.name : file.name.replace(/\.json$/i, "");
3491
+ const out = await pjPost({ action: "import", project: doc, name });
3492
+ if (!out) return;
3493
+ pj.view = "active"; pj.mode = "detail"; pj.sel = out.id;
3494
+ toast(`Imported โ€œ${out.project.name}โ€ โ€” its media must be in media/ (Relink finds moved files)`);
3495
+ await pjLoad();
3496
+ }
3497
+ /* Versions of one project (history.js on the server), shown in the dashboard's
3498
+ main area in place of the cards. Restoring never loses anything: the server
3499
+ saves what was there as a version first. */
3500
+ const VER_KIND = { manual: "", auto: "Auto", agent: "Agent", restore: "Before restore" };
3501
+ /** Drop the open comparisons, and any still on their way: they were against an older state. */
3502
+ function pjDropDiffs() { pj.verDiff.clear(); pj.verDiffGen++; }
3503
+ async function pjLoadVersions() {
3504
+ const id = pj.verOf;
3505
+ if (!id) return;
3506
+ const seq = pj.verSeq = (pj.verSeq || 0) + 1;
3507
+ // only the newest request for the project still shown may change the list
3508
+ const current = () => seq === pj.verSeq && pj.verOf === id;
3509
+ try {
3510
+ const res = await fetch("/api/versions?project=" + encodeURIComponent(id), { cache: "no-store" });
3511
+ const data = await res.json();
3512
+ if (!res.ok) throw new Error(data.error);
3513
+ if (!current()) return;
3514
+ pj.versions = data.versions || [];
3515
+ } catch (e) {
3516
+ if (!current()) return;
3517
+ pj.versions = []; toast("Versions: " + (e.message || "couldn't read them"));
3518
+ }
3519
+ // what is being typed in Save version survives the repaint
3520
+ const draft = { name: $("verName")?.value, note: $("verNote")?.value, focus: document.activeElement?.id };
3521
+ renderProjectGrid();
3522
+ if (draft.name != null && $("verName")) $("verName").value = draft.name;
3523
+ if (draft.note != null && $("verNote")) $("verNote").value = draft.note;
3524
+ if ((draft.focus === "verName" || draft.focus === "verNote") && $(draft.focus)) $(draft.focus).focus();
3525
+ }
3526
+ function pjVersionsHtml() {
3527
+ const p = pj.list.find((x) => x.id === pj.verOf) || { name: "Project" };
3528
+ const rows = pj.versions.map((v) => {
3529
+ const diff = pj.verDiff.get(v.v);
3530
+ return `<div class="ver-row${v.final ? " final" : ""}" data-ver="${v.v}">
3531
+ <div class="ver-main">
3532
+ <span class="ver-num">v${v.v}</span>
3533
+ <span class="ver-name" title="${escapeHtml(v.name)}">${escapeHtml(v.name)}</span>
3534
+ ${v.final ? `<span class="ver-badge final">Final</span>` : ""}
3535
+ ${VER_KIND[v.kind] ? `<span class="ver-badge">${VER_KIND[v.kind]}</span>` : ""}
3536
+ <span class="ver-meta dim">${pjAgo(v.created)} ยท ${pjFmtDur(v.duration)} ยท ${v.clips} clip${v.clips === 1 ? "" : "s"}</span>
3537
+ </div>
3538
+ ${v.note ? `<div class="ver-note">${escapeHtml(v.note)}</div>` : ""}
3539
+ ${diff ? `<ul class="ver-diff">${diff.length ? diff.map((l) => `<li>${escapeHtml(l)}</li>`).join("") : "<li>Same as now.</li>"}</ul>` : ""}
3540
+ <div class="ver-actions">
3541
+ <button type="button" class="btn tiny" data-ver-act="diff">${diff ? "Hide changes" : "Compare with now"}</button>
3542
+ <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>
3543
+ <button type="button" class="btn tiny" data-ver-act="final">${v.final ? "Unmark final" : "Mark final"}</button>
3544
+ <button type="button" class="btn tiny" data-ver-act="rename">Rename</button>
3545
+ <a class="btn tiny" href="/api/versions/file?project=${encodeURIComponent(pj.verOf)}&version=${v.v}" download>Download</a>
3546
+ <button type="button" class="btn tiny danger-ghost" data-ver-act="delete"${v.final ? ` disabled title="Unmark it as final first"` : ""}>Deleteโ€ฆ</button>
3547
+ </div>
3548
+ </div>`;
3549
+ }).join("");
3550
+ return `<div class="ver-view">
3551
+ <div class="ver-head">
3552
+ <button type="button" class="btn tiny" data-ver-act="back">โ† All projects</button>
3553
+ <h3>Versions of ${escapeHtml(p.name)}</h3>
3554
+ </div>
3555
+ <div class="ver-save">
3556
+ <input type="text" id="verName" maxlength="120" placeholder="Name (optional), e.g. Client cut" spellcheck="false" aria-label="Version name">
3557
+ <input type="text" id="verNote" maxlength="2000" placeholder="Note (optional)" aria-label="Version note">
3558
+ <button type="button" class="btn primary" data-ver-act="save">Save version</button>
3559
+ </div>
3560
+ <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>
3561
+ ${rows || `<div class="pj-empty dim">No versions yet. Save one to have a point to come back to.</div>`}
3562
+ </div>`;
3563
+ }
3564
+ async function pjVersionAction(act, btn) {
3565
+ if (act === "back") { pj.verOf = null; pjDropDiffs(); renderProjects(); return; }
3566
+ if (pj.busy) return;
3567
+ // busy from before the first await, so a second click can't start the same action again
3568
+ if (act === "rename") return pjVersionRun(act, btn);
3569
+ pj.verPending = false;
3570
+ await pjBusy(() => pjVersionRun(act, btn));
3571
+ if (pj.verPending && pj.verOf) { pj.verPending = false; pjDropDiffs(); pjLoadVersions(); } // changed elsewhere meanwhile
3572
+ }
3573
+ async function pjVersionRun(act, btn) {
3574
+ const p = pj.list.find((x) => x.id === pj.verOf);
3575
+ if (!p) return;
3576
+ const row = btn.closest("[data-ver]"), v = row ? +row.dataset.ver : null;
3577
+ const post = (body) => fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ project: p.id, ...body }) })
3578
+ .then(async (r) => { const out = await r.json().catch(() => ({})); if (!r.ok) { toast(out.error || "Versions: request failed"); return null; } return out; })
3579
+ .catch(() => { toast("Versions: the editor server did not answer"); return null; });
3580
+ if (act === "save") {
3581
+ if (p.active && !(await flushSaveForVersion("no version was made"))) return;
3582
+ const out = await post({ action: "save", name: $("verName")?.value, note: $("verNote")?.value });
3583
+ if (out) {
3584
+ toast(`Saved v${out.version.v} โ€œ${out.version.name}โ€`);
3585
+ for (const id of ["verName", "verNote"]) if ($(id)) $(id).value = ""; // saved: not a draft any more
3586
+ await pjLoadVersions();
3587
+ }
3588
+ return;
3589
+ }
3590
+ if (act === "diff") {
3591
+ if (pj.verDiff.has(v)) { pj.verDiff.delete(v); renderProjectGrid(); return; }
3592
+ // compare with what is on screen, or not at all
3593
+ if (p.active && !(await flushSaveForVersion("the comparison would miss it"))) return;
3594
+ const gen = pj.verDiffGen, of = pj.verOf;
3595
+ const out = await post({ action: "diff", version: v });
3596
+ if (out && gen === pj.verDiffGen && of === pj.verOf) { pj.verDiff.set(v, out.lines); renderProjectGrid(); }
3597
+ return;
3598
+ }
3599
+ if (act === "restore") {
3600
+ if (btn.dataset.armed !== "1") {
3601
+ btn.dataset.armed = "1"; btn.textContent = "Click again to restore";
3602
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Restoreโ€ฆ"; } }, 3000);
3603
+ return;
3604
+ }
3605
+ if (p.active && state.exporting) { toast("Wait for the export to finish before restoring"); return; }
3606
+ if (p.active && !(await flushSaveForVersion("nothing was restored"))) return;
3607
+ const out = await post({ action: "restore", version: v });
3608
+ if (!out) return;
3609
+ if (p.active) {
3610
+ // the undo steps describe the document before the restore
3611
+ runtime.undo.length = 0; runtime.redo.length = 0;
3612
+ await syncFromServer(true);
3613
+ }
3614
+ pjDropDiffs();
3615
+ toast(`Restored v${out.restored.v}. What was there is kept as v${out.saved.v}`);
3616
+ await pjLoad(); // the card and details show the restored project
3617
+ await pjLoadVersions();
3618
+ return;
3619
+ }
3620
+ if (act === "final") {
3621
+ const e = pj.versions.find((x) => x.v === v);
3622
+ const out = await post({ action: "update", version: v, final: !e?.final });
3623
+ if (out) await pjLoadVersions();
3624
+ return;
3625
+ }
3626
+ if (act === "rename") {
3627
+ const name = row.querySelector(".ver-name");
3628
+ if (!name || name.querySelector("input")) return;
3629
+ const e = pj.versions.find((x) => x.v === v);
3630
+ name.innerHTML = `<input type="text" class="ver-rename" maxlength="120" value="${escapeHtml(e?.name || "")}" spellcheck="false" aria-label="Version name">`;
3631
+ const inp = name.querySelector("input");
3632
+ inp.focus(); inp.select();
3633
+ const done = async (keep) => {
3634
+ if (inp.dataset.done) return;
3635
+ inp.dataset.done = "1";
3636
+ const val = inp.value.trim();
3637
+ if (keep && val && val !== e?.name) await post({ action: "update", version: v, name: val });
3638
+ await pjLoadVersions();
3639
+ };
3640
+ // Enter / Esc reach it through the dashboard's key handler (initProjectsUi): they blur it
3641
+ inp.addEventListener("blur", () => done(!inp.dataset.cancel));
3642
+ return;
3643
+ }
3644
+ if (act === "delete") {
3645
+ if (btn.dataset.armed !== "1") {
3646
+ btn.dataset.armed = "1"; btn.textContent = "Click again to delete";
3647
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Deleteโ€ฆ"; } }, 3000);
3648
+ return;
3649
+ }
3650
+ const out = await post({ action: "delete", version: v });
3651
+ if (out) { pj.verDiff.delete(v); await pjLoadVersions(); }
3652
+ }
3653
+ }
3654
+ /* Ctrl/Cmd+S: keep the open project as it is now. */
3655
+ let versionSaving = false;
3656
+ async function saveVersionNow() {
3657
+ if (versionSaving) return; // one at a time
3658
+ versionSaving = true;
3659
+ try {
3660
+ const project = runtime.projectId; // another tab may open another project meanwhile
3661
+ if (!(await flushSaveForVersion("no version was made"))) return;
3662
+ const res = await fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "save", ...(project && project !== "?" ? { project } : {}) }) });
3663
+ const out = await res.json().catch(() => ({}));
3664
+ if (!res.ok) { toast(out.error || "Couldn't save a version"); return; }
3665
+ toast(`Saved v${out.version.v} โ€œ${out.version.name}โ€ ยท Projects โ†’ Versions to go back to it`);
3666
+ } catch { toast("Couldn't save a version: the editor server did not answer"); }
3667
+ finally { versionSaving = false; }
3668
+ }
3669
+ /** Write the open project's pending edit before a version action; false (with a toast) when it didn't land. */
3670
+ async function flushSaveForVersion(skipped) {
3671
+ if (await flushSave()) return true;
3672
+ toast(`Your last change couldn't be saved, so ${skipped}. Try again in a moment.`);
3673
+ return false;
3674
+ }
3675
+ /* Called by syncFromServer when ./project.json is now another project. */
3676
+ function onProjectSwitched() {
3677
+ runtime.projectGen = (runtime.projectGen || 0) + 1; // loads started before now no longer write the caches
3678
+ // queued exports carry the old project's settings and names: they don't render this one
3679
+ const queued = exportQueue.length;
3680
+ for (let i = exportQueue.length - 1; i >= 0; i--)
3681
+ if (["pending", "failed", "cancelled"].includes(exportQueue[i].status)) exportQueue.splice(i, 1); // Retry would render this project
3682
+ if (exportQueue.length !== queued) { renderQueue(); toast("Queued exports of the previous project were removed"); }
3683
+ if (runtime.saveTimer) { clearTimeout(runtime.saveTimer); runtime.saveTimer = null; } // an edit of the old project
3684
+ runtime.saveFailed = false;
3685
+ runtime.undo.length = 0; runtime.redo.length = 0;
3686
+ runtime.seqUndo.clear(); runtime.seqOpen = null;
3687
+ state.compCtx = null;
3688
+ clearSource();
3689
+ setSelection([]);
3690
+ // players, pictures, waveforms and proxy states are keyed by media / clip id, which a
3691
+ // duplicate or a template shares with a different file: rebuild them for this project
3692
+ pause();
3693
+ for (const id of [...runtime.clipEls.keys()]) releaseClipEl(id);
3694
+ runtime.mediaAux.clear();
3695
+ runtime.wavePeaks.clear();
3696
+ proxyStatus.clear();
3697
+ }
3698
+ function initProjectsUi() {
3699
+ const ov = $("projectsOverlay"), btn = $("btnProjectsDash");
3700
+ if (!ov || !btn || ov.dataset.wired) return;
3701
+ ov.dataset.wired = "1";
3702
+ btn.classList.remove("hidden");
3703
+ btn.addEventListener("click", openProjects);
3704
+ els.projectName?.classList.add("clickable");
3705
+ els.projectName?.setAttribute("title", "Projects");
3706
+ els.projectName?.addEventListener("click", openProjects);
3707
+ $("pjClose").addEventListener("click", closeProjects);
3708
+ ov.addEventListener("click", (e) => { if (e.target === ov) closeProjects(); });
3709
+ // capture on window: wherever focus is while the dashboard is up, the editor's shortcuts stay out of it
3710
+ window.addEventListener("keydown", (e) => {
3711
+ if (!projectsOpen()) return;
3712
+ e.stopPropagation();
3713
+ if ((e.ctrlKey || e.metaKey) && (e.key === "o" || e.key === "O")) {
3714
+ e.preventDefault(); closeProjects(); // not the browser's Open File dialog
3715
+ } else if ((e.ctrlKey || e.metaKey) && (e.key === "s" || e.key === "S")) {
3716
+ e.preventDefault(); // not the browser's Save Page dialog
3717
+ if (!e.repeat) saveVersionNow().then(() => { if (pj.verOf) pjLoadVersions(); }); // holding the keys makes one
3718
+ } else if (e.target.classList?.contains("ver-rename") && (e.key === "Enter" || e.key === "Escape")) {
3719
+ e.preventDefault();
3720
+ if (e.key === "Escape") e.target.dataset.cancel = "1";
3721
+ e.target.blur();
3722
+ } else if (e.key === "Enter" && (e.target.id === "verName" || e.target.id === "verNote")) {
3723
+ e.preventDefault(); pjVersionAction("save", e.target);
3724
+ } else if (e.key === "Escape") {
3725
+ e.preventDefault();
3726
+ if (pj.mode === "new") { pj.mode = "detail"; renderProjects(); }
3727
+ else if (pj.verOf) { pj.verOf = null; pjDropDiffs(); renderProjects(); }
3728
+ else closeProjects();
3729
+ } else if ((e.key === "Enter" || e.key === " ") && e.target.dataset?.pjTpldel) {
3730
+ e.preventDefault(); e.target.click();
3731
+ } else if (e.key === "Enter" && e.target.dataset?.pj) {
3732
+ e.preventDefault(); pjOpenProject(e.target.dataset.pj);
3733
+ } else if (e.key === "Enter" && e.target.id === "pjNewName") {
3734
+ e.preventDefault(); pjAction("new-create");
3735
+ } else if (e.key === "Enter" && (e.target.id === "pjName" || e.target.id === "pjTags")) {
3736
+ e.preventDefault(); e.target.blur();
3737
+ } else if (e.key === "Enter" && e.target.id === "pjTplName") {
3738
+ e.preventDefault(); pjAction("template-save");
3739
+ }
3740
+ }, true);
3741
+ for (const b of ov.querySelectorAll("[data-pj-view]")) b.addEventListener("click", () => {
3742
+ if (pj.view === b.dataset.pjView && pj.mode === "detail") return;
3743
+ pj.view = b.dataset.pjView; pj.mode = "detail"; pj.verOf = null; pj.list = []; renderProjects(); pjLoad();
3744
+ });
3745
+ $("pjNewBtn").addEventListener("click", () => {
3746
+ pj.mode = pj.mode === "new" ? "detail" : "new";
3747
+ renderProjects();
3748
+ if (pj.mode === "new") $("pjNewName")?.select();
3749
+ });
3750
+ $("pjSearch").addEventListener("input", (e) => { pj.search = e.target.value; renderProjectGrid(); });
3751
+ $("pjSort").addEventListener("change", (e) => { pj.sort = e.target.value; renderProjectGrid(); });
3752
+ $("pjImportFile").addEventListener("change", (e) => { const f = e.target.files?.[0]; e.target.value = ""; if (f) pjImport(f); });
3753
+ $("pjGrid").addEventListener("click", (e) => {
3754
+ const vact = e.target.closest("[data-ver-act]");
3755
+ if (vact) { if (!vact.disabled) pjVersionAction(vact.dataset.verAct, vact); return; }
3756
+ const card = e.target.closest("[data-pj]");
3757
+ if (!card) return;
3758
+ // only the selection changes: re-rendering the cards would swallow a double-click
3759
+ pj.sel = card.dataset.pj; pj.mode = "detail";
3760
+ for (const c of $("pjGrid").querySelectorAll(".pj-card")) c.classList.toggle("sel", c === card);
3761
+ renderProjectSide();
3762
+ });
3763
+ $("pjGrid").addEventListener("dblclick", (e) => { const card = e.target.closest("[data-pj]"); if (card && pj.view === "active") pjOpenProject(card.dataset.pj); });
3764
+ const side = $("pjSide");
3765
+ side.addEventListener("click", async (e) => {
3766
+ const bk = e.target.closest("[data-pj-backup]");
3767
+ if (bk && !bk.dataset.flushed) {
3768
+ // the open project: write its pending edit, then download
3769
+ e.preventDefault();
3770
+ if (!(await flushSaveForVersion("the backup would miss it"))) return;
3771
+ bk.dataset.flushed = "1"; bk.click(); delete bk.dataset.flushed;
3772
+ return;
3773
+ }
3774
+ const del = e.target.closest("[data-pj-tpldel]");
3775
+ if (del) {
3776
+ e.stopPropagation();
3777
+ if (del.dataset.armed !== "1") { del.dataset.armed = "1"; del.textContent = "Delete?"; setTimeout(() => { if (del.isConnected) { del.dataset.armed = ""; del.textContent = "โœ•"; } }, 3000); return; }
3778
+ const out = await pjPost({ action: "delete_template", template: del.dataset.pjTpldel });
3779
+ if (out) { if (pj.tpl === del.dataset.pjTpldel) pj.tpl = "landscape-1080"; await pjLoad(); }
3780
+ return;
3781
+ }
3782
+ const tpl = e.target.closest("[data-pj-tpl]");
3783
+ if (tpl) {
3784
+ const keepName = $("pjNewName")?.value;
3785
+ pj.tpl = tpl.dataset.pjTpl; renderProjects();
3786
+ if (keepName != null && $("pjNewName")) $("pjNewName").value = keepName;
3787
+ return;
3788
+ }
3789
+ const act = e.target.closest("[data-pj-act]");
3790
+ if (act && !act.disabled) pjAction(act.dataset.pjAct, act);
3791
+ });
3792
+ side.addEventListener("focusout", (e) => {
3793
+ if (e.target.id === "pjName") pjSaveField("name");
3794
+ else if (e.target.id === "pjNotes") pjSaveField("notes");
3795
+ else if (e.target.id === "pjTags") pjSaveField("tags");
3796
+ });
3797
+ }
3798
+
3106
3799
  /* โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• EDIT OPERATIONS โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• */
3107
3800
  /* Undo entries are {clips, markers} snapshots. Drag gestures still push a bare
3108
3801
  clips array (taken at pointerdown) โ€” restoring one leaves markers alone. */
@@ -3116,8 +3809,20 @@ function pushUndo(snap = undoSnapshot()) {
3116
3809
  if (runtime.undo.length > 100) runtime.undo.shift();
3117
3810
  runtime.redo.length = 0;
3118
3811
  }
3812
+ /** Does this undo step hold other sequences' clips (a top-level seqClips)? Parsed only when the text could say so. */
3813
+ function hasSeqClips(json) {
3814
+ if (typeof json !== "string" || !json.includes('"seqClips":')) return false;
3815
+ try { const snap = JSON.parse(json); return !!snap && typeof snap === "object" && !Array.isArray(snap) && Object.hasOwn(snap, "seqClips"); }
3816
+ catch { return false; }
3817
+ }
3818
+ /** The clips of the sequences that aren't open, by id โ€” for the undo of an edit that reaches into them. */
3819
+ function otherSequenceClips() { return Object.fromEntries(SeqLib.others(seqRoot()).map((sq) => [sq.id, sq.clips || []])); }
3119
3820
  function restoreSnapshot(json) {
3120
3821
  const snap = JSON.parse(json);
3822
+ if (snap && snap.seqClips) {
3823
+ const open = SeqLib.activeId(seqRoot());
3824
+ for (const [id, clips] of Object.entries(snap.seqClips)) { const sq = SeqLib.find(seqRoot(), id); if (sq && id !== open) sq.clips = clips; }
3825
+ }
3121
3826
  if (Array.isArray(snap)) project.clips = snap;
3122
3827
  else {
3123
3828
  project.clips = snap.clips; project.markers = snap.markers; if (snap.comps) project.comps = snap.comps;
@@ -3135,7 +3840,8 @@ function restoreSnapshot(json) {
3135
3840
  * (removing, relinking or replacing media), so redo puts it back too. */
3136
3841
  function counterSnapshot(snap) {
3137
3842
  if (!snap.includes('"media":')) return undoSnapshot();
3138
- return JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media });
3843
+ return JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media,
3844
+ ...(hasSeqClips(snap) ? { seqClips: otherSequenceClips() } : {}) });
3139
3845
  }
3140
3846
  function undo() {
3141
3847
  if (!runtime.undo.length) return;
@@ -9355,7 +10061,9 @@ function parseSvgSize(txt) {
9355
10061
  return { width: w || 800, height: h || 600 };
9356
10062
  }
9357
10063
  async function loadSvgMedia(m) {
10064
+ const gen = runtime.projectGen;
9358
10065
  const txt = await (await fetch(m.src)).text();
10066
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
9359
10067
  const { width, height } = parseSvgSize(txt);
9360
10068
  m.width = width; m.height = height;
9361
10069
  const aux = runtime.mediaAux.get(m.id) || {};
@@ -9364,7 +10072,7 @@ async function loadSvgMedia(m) {
9364
10072
  aux.svgFrames = new Map(); // quantized t -> HTMLImageElement (small LRU)
9365
10073
  aux.svgPending = null;
9366
10074
  runtime.mediaAux.set(m.id, aux);
9367
- if (!aux.svgAnimated) aux.img = await rasterizeSvgMarkup(txt);
10075
+ if (!aux.svgAnimated) { const img = await rasterizeSvgMarkup(txt); if (gen === runtime.projectGen) aux.img = img; }
9368
10076
  state.dirtyTimeline = true;
9369
10077
  }
9370
10078
  function svgMarkupAt(aux, t) {
@@ -10222,6 +10930,7 @@ function exitComp(levels = 1) {
10222
10930
  scheduleSave();
10223
10931
  }
10224
10932
  function syncCompCrumb() {
10933
+ syncSequenceButton();
10225
10934
  if (els.projectName) els.projectName.textContent = project.name + (state.connected ? " ยท ๐ŸŸข connected" : " ยท โšช local session");
10226
10935
  const el = document.getElementById("compCrumb");
10227
10936
  if (!el) return;
@@ -10229,13 +10938,203 @@ function syncCompCrumb() {
10229
10938
  el.classList.toggle("hidden", !x);
10230
10939
  if (!x) { el.innerHTML = ""; return; }
10231
10940
  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>` +
10941
+ el.innerHTML = `<button type="button" class="btn tiny" data-crumb="${x.path.length}" title="Back to the timeline">โ—€ ${escapeHtml(openSequenceName())}</button>` +
10233
10942
  names.map((n, i) => `<span class="crumb-sep">โ€บ</span>` + (i < names.length - 1
10234
10943
  ? `<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("");
10944
+ : `<b title="You are editing this composition โ€” Esc or โ—€ goes back">${escapeHtml(n)}</b>`)).join("");
10236
10945
  for (const b of el.querySelectorAll("[data-crumb]")) b.addEventListener("click", () => exitComp(+b.dataset.crumb));
10237
10946
  }
10238
10947
 
10948
+ /* โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• SEQUENCES โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
10949
+ Several timelines in one project (sequences.js). The open one is `project`
10950
+ itself โ€” clips, tracks, canvas, frame rate, mix, delivery โ€” and the others
10951
+ wait in project.sequences. Opening one parks this timeline in its entry and
10952
+ loads the other, like a reload. For the session each sequence keeps its own
10953
+ undo history, playhead and selection. */
10954
+ const SeqLib = self.FableCutSeq;
10955
+ /** The document that holds the sequences (the root while a comp is open). */
10956
+ function seqRoot() { return state.compCtx ? state.compCtx.root : project; }
10957
+ function openSequenceName() { const r = seqRoot(); return (SeqLib.find(r, SeqLib.activeId(r)) || SeqLib.MAIN).name; }
10958
+ /** A document is about to be shown: when it opens another sequence, the undo steps,
10959
+ * playhead and selection go with the one that was open, and the other's come back. */
10960
+ function noteOpenSequence(data) {
10961
+ const next = SeqLib.activeId(data), prev = runtime.seqOpen;
10962
+ runtime.seqOpen = next;
10963
+ runtime.seqBack = null;
10964
+ if (!prev || prev === next) return;
10965
+ // the steps only fit the state they were taken on: its timeline, and the comps and media every sequence
10966
+ // shares (undo puts those back too). An agent or the other sequence may change them meanwhile.
10967
+ // A relink / replace step also holds the other sequences' clips: then those must be as they were too.
10968
+ const here = projectJSONHere();
10969
+ const withOthers = [...runtime.undo, ...runtime.redo].some(hasSeqClips);
10970
+ runtime.seqUndo.set(prev, { undo: runtime.undo.slice(), redo: runtime.redo.slice(), time: state.time, sel: state.selId,
10971
+ fp: seqUndoPrint(here, withOthers), withOthers });
10972
+ const back = runtime.seqUndo.get(next);
10973
+ const fits = back && back.fp === seqUndoPrint(data, back.withOthers);
10974
+ runtime.undo.splice(0, runtime.undo.length, ...(fits ? back.undo : []));
10975
+ runtime.redo.splice(0, runtime.redo.length, ...(fits ? back.redo : []));
10976
+ runtime.seqBack = back || null;
10977
+ }
10978
+ /** What a sequence's undo steps rely on: its timeline, the shared comps and media, and (for relink /
10979
+ * replace steps) the clips of the other sequences โ€” in the saved form, so both sides compare alike. */
10980
+ function seqUndoPrint(d, withOthers) {
10981
+ return JSON.stringify([d.clips || [], d.comps || [], (d.media || []).filter((m) => !m.transient),
10982
+ ...(withOthers ? [SeqLib.others(d).map((sq) => [sq.id, sq.clips || []])] : [])]);
10983
+ }
10984
+ /** Open sequence `id` in the editor. False when it can't be opened now. */
10985
+ function openSequence(id) {
10986
+ if (state.exporting) { toast("Wait for the export to finish before opening another sequence"); return false; }
10987
+ if (state.gesture) return false;
10988
+ if (state.compCtx) exitComp(state.compCtx.path.length);
10989
+ if (SeqLib.activeId(project) === id) return true;
10990
+ if (state.playing) pause();
10991
+ const doc = projectJSONHere();
10992
+ try { SeqLib.open(doc, id); } catch (e) { toast(e.message); return false; }
10993
+ applyProject(doc);
10994
+ const back = runtime.seqBack;
10995
+ runtime.seqBack = null;
10996
+ const sel = back && back.sel && getClip(back.sel);
10997
+ setSelection(sel ? [...withLinked([sel])].map((c) => c.id) : []);
10998
+ setTime(back ? back.time : 0);
10999
+ syncCompCrumb();
11000
+ scheduleSave();
11001
+ return true;
11002
+ }
11003
+ /** Add a sequence ({name?, from?, width?, height?}) and open it. */
11004
+ function newSequence(opts) {
11005
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11006
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11007
+ const doc = projectJSONHere();
11008
+ let s;
11009
+ try { s = SeqLib.add(doc, opts); } catch (e) { toast(e.message); return; }
11010
+ project.sequences = doc.sequences; project.sequence = doc.sequence;
11011
+ if (openSequence(s.id)) toast(`New sequence โ€œ${s.name}โ€ ยท ${s.width}ร—${s.height}`);
11012
+ else { scheduleSave(); syncCompCrumb(); toast(`New sequence โ€œ${s.name}โ€ added โ€” open it from the sequence menu`); }
11013
+ }
11014
+ function renameSequence(id, name) {
11015
+ const r = seqRoot();
11016
+ try { SeqLib.rename(r, id, name); } catch (e) { toast(e.message); return; }
11017
+ if (!r.sequences) { r.sequences = null; r.sequence = null; }
11018
+ syncCompCrumb(); scheduleSave();
11019
+ }
11020
+ /** Delete a sequence โ€” after keeping the project as it is now as a version, when the server is there. */
11021
+ async function deleteSequence(id) {
11022
+ const r = seqRoot(), s = SeqLib.find(r, id);
11023
+ if (!s || SeqLib.entries(r).length < 2) return;
11024
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11025
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11026
+ let kept = null;
11027
+ if (state.connected) {
11028
+ const projectId = runtime.projectId; // the version is of this project, whatever another tab opens meanwhile
11029
+ if (!(await flushSaveForVersion("the sequence was not deleted"))) return;
11030
+ try {
11031
+ const res = await fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" },
11032
+ body: JSON.stringify({ action: "save", name: `Before deleting the sequence โ€œ${s.name}โ€`.slice(0, 120), ...(projectId && projectId !== "?" ? { project: projectId } : {}) }) });
11033
+ if (res.ok) kept = (await res.json()).version;
11034
+ } catch { }
11035
+ // the delete has no undo: without that version it doesn't happen
11036
+ if (!kept) { toast(`Couldn't keep a version of the project, so โ€œ${s.name}โ€ was not deleted. Try again in a moment.`); return; }
11037
+ }
11038
+ // the editor may have moved on while the version was saved
11039
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11040
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11041
+ if (!SeqLib.find(project, id) || SeqLib.entries(project).length < 2) return; // deleted or changed meanwhile (another tab, an agent)
11042
+ const wasOpen = SeqLib.activeId(project) === id;
11043
+ const doc = projectJSONHere();
11044
+ try { SeqLib.remove(doc, id); } catch (e) { toast(e.message); return; }
11045
+ if (wasOpen) {
11046
+ applyProject(doc);
11047
+ const back = runtime.seqBack;
11048
+ runtime.seqBack = null;
11049
+ setSelection([]);
11050
+ setTime(back ? back.time : 0);
11051
+ } else { project.sequences = doc.sequences || null; project.sequence = doc.sequence || null; }
11052
+ runtime.seqUndo.delete(id);
11053
+ syncCompCrumb(); scheduleSave();
11054
+ toast(`Deleted the sequence โ€œ${s.name}โ€` + (kept ? ` ยท it is kept in version v${kept.v} (Projects โ†’ Versions)` : ""));
11055
+ }
11056
+ function syncSequenceButton() {
11057
+ const b = $("btnSequences");
11058
+ if (!b) return;
11059
+ const n = SeqLib.entries(seqRoot()).length;
11060
+ b.querySelector(".seq-name").textContent = openSequenceName();
11061
+ b.querySelector(".seq-count").textContent = n > 1 ? String(n) : "";
11062
+ b.title = `Sequence: ${openSequenceName()}${n > 1 ? ` (one of ${n})` : ""} โ€” open another one, or add, duplicate, rename`;
11063
+ }
11064
+ /** The sequence menu: the project's sequences (click one to open it), then what to do with them. */
11065
+ function showSequenceMenu(x, y) {
11066
+ hideTrackCtxMenu();
11067
+ const menu = document.createElement("div");
11068
+ menu.className = "ctx-menu seq-menu";
11069
+ const r = seqRoot(), openId = SeqLib.activeId(r);
11070
+ const rows = SeqLib.list(r), open = rows.find((row) => row.active);
11071
+ const item = (html, run, why, keepOpen) => {
11072
+ const b = document.createElement("button");
11073
+ b.type = "button"; b.className = "ctx-item"; b.innerHTML = html;
11074
+ if (why) { b.disabled = true; b.title = why; } else b.addEventListener("click", () => { if (!keepOpen) hideTrackCtxMenu(); run(b); });
11075
+ menu.appendChild(b);
11076
+ return b;
11077
+ };
11078
+ const sep = () => { const d = document.createElement("div"); d.className = "ctx-sep"; menu.appendChild(d); };
11079
+ for (const row of rows) {
11080
+ // the open one's live numbers are on the timeline (or the root, while a comp is open)
11081
+ const w = row.active ? r.width : row.width, h = row.active ? r.height : row.height;
11082
+ const len = row.active ? (state.compCtx ? row.duration : projDur()) : row.duration;
11083
+ 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>`,
11084
+ () => openSequence(row.id));
11085
+ if (row.active) b.classList.add("on");
11086
+ }
11087
+ sep();
11088
+ item(`<span>New sequenceโ€ฆ</span>`, () => promptNewSequence(x, y));
11089
+ item(`<span>Duplicate โ€œ${escapeHtml(open.name)}โ€</span>`, () => newSequence({ from: "open" }));
11090
+ item(`<span>Rename โ€œ${escapeHtml(open.name)}โ€โ€ฆ</span>`, () => promptBinText(x, y, "Sequence name", open.name, (v) => renameSequence(openId, v), { max: 120, ok: "Rename" }));
11091
+ item(`<span>Delete โ€œ${escapeHtml(open.name)}โ€โ€ฆ</span>`, (b) => {
11092
+ if (b.dataset.armed !== "1") { b.dataset.armed = "1"; b.querySelector("span").textContent = "Click again to delete it"; return; }
11093
+ hideTrackCtxMenu();
11094
+ deleteSequence(openId);
11095
+ }, rows.length < 2 ? "A project keeps at least one sequence" : null, true);
11096
+ showPopover(menu, x, y);
11097
+ }
11098
+ /** New sequence: a name, a canvas, and whether it starts empty or as a copy of the open one. */
11099
+ function promptNewSequence(x, y) {
11100
+ const pop = document.createElement("div");
11101
+ pop.className = "ctx-menu bin-pop seq-new";
11102
+ const n = SeqLib.entries(seqRoot()).length + 1;
11103
+ const sizes = [{ label: `Same as โ€œ${openSequenceName()}โ€ ยท ${project.width}ร—${project.height}`, w: 0, h: 0 }, ...ASPECT_PRESETS];
11104
+ pop.innerHTML = `<label class="bin-pop-label" for="seqNewName">New sequence</label>
11105
+ <input type="text" class="bin-pop-input" id="seqNewName" maxlength="120" spellcheck="false">
11106
+ <label class="bin-pop-label" for="seqNewSize">Canvas</label>
11107
+ <select id="seqNewSize" class="bin-pop-input">${sizes.map((s, i) => `<option value="${i}">${escapeHtml(s.label)}</option>`).join("")}</select>
11108
+ <label class="seq-new-copy"><input type="checkbox" id="seqNewCopy"> Start from a copy of โ€œ${escapeHtml(openSequenceName())}โ€</label>
11109
+ <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>
11110
+ <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>`;
11111
+ pop.querySelector("#seqNewName").value = `Sequence ${n}`;
11112
+ const ok = () => {
11113
+ const name = pop.querySelector("#seqNewName").value.trim();
11114
+ const size = sizes[+pop.querySelector("#seqNewSize").value] || sizes[0];
11115
+ const copy = pop.querySelector("#seqNewCopy").checked;
11116
+ hideTrackCtxMenu();
11117
+ newSequence({ name: name || undefined, from: copy ? "open" : "empty", ...(size.w ? { width: size.w, height: size.h } : {}) });
11118
+ };
11119
+ pop.querySelector("[data-ok]").addEventListener("click", ok);
11120
+ pop.querySelector("[data-cancel]").addEventListener("click", () => hideTrackCtxMenu());
11121
+ pop.addEventListener("keydown", (e) => {
11122
+ if (e.key === "Enter" && e.target.tagName !== "SELECT") { e.preventDefault(); ok(); }
11123
+ else if (e.key === "Escape") { e.preventDefault(); hideTrackCtxMenu(); }
11124
+ e.stopPropagation();
11125
+ });
11126
+ showPopover(pop, x, y);
11127
+ const input = pop.querySelector("#seqNewName");
11128
+ input.focus(); input.select();
11129
+ }
11130
+ function initSequencesUi() {
11131
+ const b = $("btnSequences");
11132
+ if (!b || b.dataset.wired) return;
11133
+ b.dataset.wired = "1";
11134
+ b.addEventListener("click", () => { const rc = b.getBoundingClientRect(); showSequenceMenu(rc.left, rc.bottom + 4); });
11135
+ syncSequenceButton();
11136
+ }
11137
+
10239
11138
  /* โ”€โ”€ Making comps โ”€โ”€ */
10240
11139
  function newCompId() { let id; do id = "comp_" + uid(); while (getComp(id)); return id; }
10241
11140
  /** Precompose the selection: the clips move into a new comp, a comp clip takes their place. */
@@ -11012,8 +11911,10 @@ function drawClipPicture(c, W, H, t, layered) {
11012
11911
  src = getSvgImage(c, t);
11013
11912
  if (src) { sw = src.naturalWidth || src.width; sh = src.naturalHeight || src.height; }
11014
11913
  } else if (c.kind === "video") {
11015
- src = getClipEl(c);
11016
- if (src) { sw = src.videoWidth; sh = src.videoHeight; }
11914
+ const frame = runtime.exportFrames && runtime.exportFrames.get(c.id);
11915
+ src = frame || getClipEl(c);
11916
+ if (frame) { sw = frame.displayWidth; sh = frame.displayHeight; }
11917
+ else if (src) { sw = src.videoWidth; sh = src.videoHeight; }
11017
11918
  } else if (c.kind === "comp") {
11018
11919
  src = renderComp(c, t);
11019
11920
  if (src) { sw = src.width; sh = src.height; }
@@ -15000,6 +15901,141 @@ function prefetchExportVideos(t) {
15000
15901
  } catch { }
15001
15902
  }
15002
15903
  }
15904
+ /* โ”€โ”€ Export decode: frames straight from WebCodecs โ”€โ”€
15905
+ Seeking <video> per frame is slow and not frame-exact, so export decodes
15906
+ MP4 / MOV clips itself (mp4-demux.js + VideoDecoder). Clips it can't take
15907
+ stay on the <video> path. */
15908
+ const Mp4 = self.FableCutMp4;
15909
+ class ExportFrameSource {
15910
+ static async open(src) {
15911
+ if (typeof VideoDecoder !== "function" || !Mp4) return null;
15912
+ try {
15913
+ const probe = await fetch(src, { headers: { Range: "bytes=0-0" } });
15914
+ if (probe.status !== 206) { try { await probe.body?.cancel(); } catch { } return null; }
15915
+ const size = Number((probe.headers.get("content-range") || "").split("/")[1]);
15916
+ await probe.arrayBuffer();
15917
+ if (!(size > 0)) return null;
15918
+ const read = async (a, b) => {
15919
+ const r = await fetch(src, { headers: { Range: `bytes=${a}-${b - 1}` } });
15920
+ if (r.status !== 206) throw new Error("range request refused");
15921
+ return new Uint8Array(await r.arrayBuffer());
15922
+ };
15923
+ const moov = await Mp4.findMoov(read, size);
15924
+ const mv = moov && Mp4.parseMovie(moov);
15925
+ if (!mv || !mv.samples.length) return null;
15926
+ const cfg = { codec: mv.codec, codedWidth: mv.width, codedHeight: mv.height };
15927
+ if (mv.description) cfg.description = mv.description;
15928
+ if (mv.displayWidth !== mv.width) Object.assign(cfg, { displayAspectWidth: mv.displayWidth, displayAspectHeight: mv.displayHeight });
15929
+ const ok = await VideoDecoder.isConfigSupported(cfg).catch(() => null);
15930
+ return ok && ok.supported ? new ExportFrameSource(read, size, mv, cfg) : null;
15931
+ } catch { return null; }
15932
+ }
15933
+ constructor(read, size, mv, cfg) {
15934
+ Object.assign(this, { read, size, cfg, samples: mv.samples, order: Mp4.presentationOrder(mv.samples) });
15935
+ this.dec = null; this.pos = 0; this.out = []; this.cur = null; this.win = null; this.err = null; this.wake = null;
15936
+ }
15937
+ restart(from) {
15938
+ this.dropQueue();
15939
+ if (this.dec && this.dec.state !== "closed") this.dec.close();
15940
+ this.err = null;
15941
+ this.dec = new VideoDecoder({
15942
+ output: (f) => { this.out.push(f); this.poke(); },
15943
+ error: (e) => { this.err = e; this.poke(); },
15944
+ });
15945
+ this.dec.ondequeue = () => this.poke();
15946
+ this.dec.configure(this.cfg);
15947
+ this.pos = from;
15948
+ }
15949
+ poke() { const w = this.wake; this.wake = null; if (w) w(); }
15950
+ dropQueue() { for (const f of this.out) f.close(); this.out = []; }
15951
+ /** The bytes of one sample, read through a 4 MB window (samples are mostly
15952
+ * contiguous, so one range request covers many frames). */
15953
+ async bytes(s) {
15954
+ const w = this.win;
15955
+ if (!w || s.offset < w.at || s.offset + s.size > w.at + w.data.length) {
15956
+ const end = Math.min(this.size, s.offset + Math.max(s.size, 4 << 20));
15957
+ this.win = { at: s.offset, data: await this.read(s.offset, end) };
15958
+ }
15959
+ const o = s.offset - this.win.at;
15960
+ return this.win.data.subarray(o, o + s.size);
15961
+ }
15962
+ /** The frame a player shows at media time t (a VideoFrame owned by this
15963
+ * source: valid until the next call or close()). */
15964
+ async frameAt(t) {
15965
+ const k = Mp4.frameAt(this.samples, this.order, t), ts = Math.round(this.samples[k].pts * 1e6);
15966
+ if (this.cur && this.cur.timestamp === ts) return this.cur;
15967
+ const sync = Mp4.syncBefore(this.samples, k);
15968
+ const passed = this.out.length > 0 && this.out[0].timestamp > ts;
15969
+ if (!this.dec || this.dec.state === "closed" || (this.cur && this.cur.timestamp > ts)
15970
+ || (k < this.pos && passed) || sync > this.pos) this.restart(sync);
15971
+ const n = this.samples.length;
15972
+ for (;;) {
15973
+ while (this.out.length && this.out[0].timestamp < ts) this.out.shift().close();
15974
+ if (this.out.length) { // the target, or (a frame the decoder dropped) the next one
15975
+ if (this.cur) this.cur.close();
15976
+ this.cur = this.out.shift();
15977
+ return this.cur;
15978
+ }
15979
+ if (this.err) throw this.err;
15980
+ let fed = false;
15981
+ while (this.pos < n && this.dec.decodeQueueSize < 8 && this.out.length < 3) {
15982
+ const s = this.samples[this.pos++];
15983
+ this.dec.decode(new EncodedVideoChunk({
15984
+ type: s.key ? "key" : "delta", timestamp: Math.round(s.pts * 1e6),
15985
+ duration: Math.round(s.dur * 1e6), data: await this.bytes(s),
15986
+ }));
15987
+ fed = true;
15988
+ }
15989
+ if (!fed && this.pos >= n && this.dec.decodeQueueSize === 0) {
15990
+ await this.dec.flush().catch((e) => { this.err = this.err || e; });
15991
+ this.pos = n + 1; // after a flush the decoder needs a sync sample again
15992
+ if (!this.out.length) { if (this.err) throw this.err; return this.cur; }
15993
+ continue;
15994
+ }
15995
+ await new Promise((res) => { this.wake = res; setTimeout(res, 50); });
15996
+ }
15997
+ }
15998
+ close() {
15999
+ this.dropQueue();
16000
+ if (this.cur) { this.cur.close(); this.cur = null; }
16001
+ if (this.dec && this.dec.state !== "closed") this.dec.close();
16002
+ this.dec = null; this.win = null;
16003
+ }
16004
+ }
16005
+ /** Export-time decode state: clip id โ†’ source (or null: use the element). */
16006
+ function exportDecodeBegin() {
16007
+ runtime.exportDecode = runtime.noExportDecode ? null : { sources: new Map(), opening: new Map() };
16008
+ runtime.exportFrames = new Map();
16009
+ }
16010
+ function exportDecodeEnd() {
16011
+ const d = runtime.exportDecode;
16012
+ if (d) for (const s of d.sources.values()) s?.close();
16013
+ runtime.exportDecode = null;
16014
+ runtime.exportFrames = null;
16015
+ }
16016
+ /** Decode the frame of video clip c for timeline time t; false when the clip
16017
+ * stays on the <video> path. Frames go to runtime.exportFrames for drawing. */
16018
+ async function exportDecodeFrame(c, t) {
16019
+ const d = runtime.exportDecode;
16020
+ if (!d || c.kind !== "video" || evalProps(c, t).bgRemove) return false;
16021
+ let src = d.sources.get(c.id);
16022
+ if (src === undefined) {
16023
+ const m = getMedia(c.mediaId);
16024
+ if (!m || !m.src) { d.sources.set(c.id, null); return false; }
16025
+ if (!d.opening.has(c.id)) d.opening.set(c.id, ExportFrameSource.open(m.src));
16026
+ src = await d.opening.get(c.id);
16027
+ d.sources.set(c.id, src);
16028
+ }
16029
+ if (!src) return false;
16030
+ try {
16031
+ runtime.exportFrames.set(c.id, await src.frameAt(mediaTimeAt(c, t)));
16032
+ return true;
16033
+ } catch (e) { // a decode error: this clip falls back to its element for the rest of the export
16034
+ console.warn("[FableCut] export decode failed, using the video element:", e && e.message);
16035
+ src.close(); d.sources.set(c.id, null); runtime.exportFrames.delete(c.id);
16036
+ return false;
16037
+ }
16038
+ }
15003
16039
  async function seekVideosTo(t, { queueBusy } = {}) {
15004
16040
  const fps = projectFps();
15005
16041
  const frameMs = 1000 / fps;
@@ -15011,9 +16047,26 @@ async function seekVideosTo(t, { queueBusy } = {}) {
15011
16047
  const keepPlaying = fast && !behind && !queueBusy;
15012
16048
  const waits = [];
15013
16049
  const restoreGain = [];
16050
+ const decoded = new Set();
16051
+ const dec = runtime.exportDecode;
16052
+ if (dec) {
16053
+ const jobs = [];
16054
+ for (const c of mediaClips()) {
16055
+ if (c.kind !== "video" || !clipRenders(c)) continue;
16056
+ if (!activeAt(c, t)) { // export runs forward: past its end, free the clip's decoder
16057
+ const s = dec.sources.get(c.id);
16058
+ if (s && t > c.start + c.duration) { s.close(); dec.sources.delete(c.id); dec.opening.delete(c.id); }
16059
+ runtime.exportFrames.delete(c.id);
16060
+ continue;
16061
+ }
16062
+ jobs.push(exportDecodeFrame(c, t).then((ok) => { if (ok) decoded.add(c.id); }));
16063
+ }
16064
+ await Promise.all(jobs);
16065
+ }
15014
16066
  for (const c of mediaClips()) {
15015
16067
  if (c.kind !== "video") continue;
15016
16068
  if (!clipRenders(c)) continue;
16069
+ if (decoded.has(c.id)) continue;
15017
16070
  const el = getClipEl(c); if (!el) continue;
15018
16071
  if (!activeAt(c, t)) {
15019
16072
  if (!el.paused) el.pause();
@@ -15242,6 +16295,7 @@ async function fastExport(opts = {}) {
15242
16295
  resetExportCanvases();
15243
16296
  await armExportCors();
15244
16297
  await useOriginalPlayers(); // proxies are for editing โ€” export reads the originals
16298
+ exportDecodeBegin();
15245
16299
  // JPEG off the compositor thread: snapshot is sync, encode/upload run ahead
15246
16300
  // under backpressure. Awaiting toBlob every frame was slower than ffmpeg.
15247
16301
  const up = createExportUploader(sessId, {
@@ -15349,6 +16403,7 @@ async function fastExport(opts = {}) {
15349
16403
  } finally {
15350
16404
  exportAbort = null;
15351
16405
  exportFullCanvas = false;
16406
+ exportDecodeEnd();
15352
16407
  restoreExportVideoState();
15353
16408
  endExportWindow();
15354
16409
  state.exporting = false; state.rendering = false;
@@ -15956,6 +17011,7 @@ async function webCodecsExport() {
15956
17011
  resetExportCanvases();
15957
17012
  await armExportCors();
15958
17013
  await useOriginalPlayers(); // proxies are for editing โ€” export reads the originals
17014
+ exportDecodeBegin();
15959
17015
 
15960
17016
  for (let f = 0; f < frames; f++) {
15961
17017
  if (renderCancelled || signal.aborted) throw new Error("cancelled");
@@ -16011,6 +17067,7 @@ async function webCodecsExport() {
16011
17067
  if (msg !== "cancelled") alert("Export failed: " + msg);
16012
17068
  } finally {
16013
17069
  exportAbort = null;
17070
+ exportDecodeEnd();
16014
17071
  restoreExportVideoState();
16015
17072
  endExportWindow();
16016
17073
  state.exporting = false; state.rendering = false;
@@ -16815,6 +17872,18 @@ window.addEventListener("keydown", (e) => {
16815
17872
  return;
16816
17873
  }
16817
17874
  }
17875
+ // Ctrl/Cmd+S: save a version of the open project (the editor saves every change anyway)
17876
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (k === "s" || k === "S")) {
17877
+ e.preventDefault(); // never the browser's Save Page dialog, and not S (split) either
17878
+ if (!e.repeat && $("btnProjectsDash") && !$("btnProjectsDash").classList.contains("hidden")) saveVersionNow(); // holding the keys makes one
17879
+ return;
17880
+ }
17881
+ // Ctrl/Cmd+O: the Projects dashboard (where the editor server has projects)
17882
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (k === "o" || k === "O") && $("btnProjectsDash") && !$("btnProjectsDash").classList.contains("hidden")) {
17883
+ e.preventDefault();
17884
+ openProjects();
17885
+ return;
17886
+ }
16818
17887
  if (k === "Escape" && els.importUrlOverlay && !els.importUrlOverlay.classList.contains("hidden")) {
16819
17888
  e.preventDefault();
16820
17889
  closeImportUrl();
@@ -16864,7 +17933,7 @@ window.addEventListener("keydown", (e) => {
16864
17933
  e.preventDefault(); // Ctrl/Cmd+L would otherwise focus the address bar
16865
17934
  toggleLinkSelected();
16866
17935
  }
16867
- else if (k === "s" || k === "S") splitAtPlayhead();
17936
+ else if ((k === "s" || k === "S") && !e.ctrlKey && !e.metaKey) splitAtPlayhead();
16868
17937
  else if (k === "," && !e.ctrlKey && !e.metaKey && !e.altKey) {
16869
17938
  e.preventDefault();
16870
17939
  insertSourceAtPlayhead();