canvas-recorder-lib 0.7.2 → 0.7.3

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.
@@ -1,5 +1,5 @@
1
1
  import "./canvas-recorder.css";
2
- import { assertNonNullable, FIGURE_SPACE, parseFloatX, parseIntX, } from "phil-lib/misc";
2
+ import { assertNonNullable, FIGURE_SPACE, parseFloatX, } from "phil-lib/misc";
3
3
  import { AnimationLoop, getById, querySelector, } from "phil-lib/client-misc";
4
4
  import { Output, StreamTarget, CanvasSource, Mp4OutputFormat, AudioBufferSource, QUALITY_HIGH, } from "mediabunny";
5
5
  import { discreteKeyframes, interpolateColors, interpolateLattices, interpolateNumbers, interpolatePoints, interpolateRects, } from "../src/interpolate.js";
@@ -380,6 +380,7 @@ function showFrame(timeInMs, live) {
380
380
  transcriptView?.update(timeInMs - rootStartMs, playCheckBox.checked);
381
381
  for (const update of goToButtonUpdaters)
382
382
  update();
383
+ editorPanelsTimeChanged();
383
384
  context.reset();
384
385
  context.setTransform(mainTransform());
385
386
  if (live) {
@@ -1571,6 +1572,46 @@ initChapters();
1571
1572
  function currentRoot() {
1572
1573
  return chapterList[select.selectedIndex]?.selectable;
1573
1574
  }
1575
+ /** The name the chapter `<select>` shows. */
1576
+ function chapterName(showable) {
1577
+ return showable.userEditableDescription ?? showable.description;
1578
+ }
1579
+ /** The way down from the top of the video to this chapter. Find it again with {@link findChapter}. */
1580
+ function chapterPath(info) {
1581
+ const path = [];
1582
+ for (let step = info; step.parent; step = step.parent) {
1583
+ const child = step.selectable;
1584
+ const index = step.parent.selectable.children?.findIndex((c) => c.child === child) ??
1585
+ -1;
1586
+ path.push({ index, name: chapterName(child) });
1587
+ }
1588
+ return path.reverse();
1589
+ }
1590
+ /**
1591
+ * Find a chapter again from its {@link chapterPath}, in a tree that may have changed.
1592
+ *
1593
+ * At each step, the child at the same position if it still has the same name, otherwise the
1594
+ * first sibling with that name. If a step can't be found, the deepest chapter found so far.
1595
+ * @returns An index into {@link chapterList}. 0, the whole video, if nothing matched.
1596
+ */
1597
+ function findChapter(path) {
1598
+ let current = toShow;
1599
+ let found = 0;
1600
+ for (const { index, name } of path) {
1601
+ const children = current.children ?? [];
1602
+ const atIndex = children[index]?.child;
1603
+ const next = atIndex && chapterName(atIndex) === name
1604
+ ? atIndex
1605
+ : children.find((c) => chapterName(c.child) === name)?.child;
1606
+ if (!next)
1607
+ break;
1608
+ current = next;
1609
+ const position = chapterList.findIndex((d) => d.selectable === next);
1610
+ if (position >= 0)
1611
+ found = position;
1612
+ }
1613
+ return found;
1614
+ }
1574
1615
  /** When checked, picking another root leaves the play limits alone. */
1575
1616
  const keepLimitsCheckbox = getById("keepLimits", HTMLInputElement);
1576
1617
  /** Says what the play limits are, below the chapter `<select>`. */
@@ -1600,6 +1641,8 @@ const visualEditorAPI = {
1600
1641
  soundtrack.request();
1601
1642
  }
1602
1643
  else if (howMuch === "properties") {
1644
+ // A property changed, so it has to be saved, like any other edit.
1645
+ markDirty();
1603
1646
  updateScheduleEditor(selectedSlideChild ?? selectable);
1604
1647
  }
1605
1648
  else {
@@ -1754,6 +1797,103 @@ const timelineWordsMemo = new WeakMap();
1754
1797
  * Cleared whenever {@link updateScheduleEditor} rebuilds.
1755
1798
  */
1756
1799
  const scheduleEditorRefreshers = [];
1800
+ /**
1801
+ * The panels shown now. Rebuilt by {@link updateScheduleEditor}.
1802
+ * Declared up here because the first schedule editor is built while this module is still loading.
1803
+ */
1804
+ const activePanels = [];
1805
+ /** Where `component` starts, in the Visual Editor's root's time. */
1806
+ function componentStartMs(component) {
1807
+ const root = currentRoot();
1808
+ return root ? (startWithin(root, component) ?? 0) : 0;
1809
+ }
1810
+ /** The playhead in `component`'s own time: what its `show()` gets as `timeInMs`. */
1811
+ function componentTimeMs(component) {
1812
+ return playheadInRootMs() - componentStartMs(component);
1813
+ }
1814
+ /** Show `reason` where `active`'s panel was, and stop calling that panel. */
1815
+ function panelFailed(active, reason) {
1816
+ console.error(reason);
1817
+ active.live = false;
1818
+ const name = active.component.userEditableDescription ?? active.component.description;
1819
+ const line = document.createElement("div");
1820
+ line.style.cssText = "color:#b00;margin-bottom:0.4em";
1821
+ line.textContent = `✗ A panel for "${name}" failed: ${String(reason)}`;
1822
+ active.element.replaceWith(line);
1823
+ active.element = line;
1824
+ }
1825
+ /** Call into a panel, unless it's suspended or broken. A bug in a panel mustn't break the editor. */
1826
+ function callPanel(active, call) {
1827
+ if (!active.live)
1828
+ return;
1829
+ try {
1830
+ call(active.panel);
1831
+ }
1832
+ catch (reason) {
1833
+ panelFailed(active, reason);
1834
+ }
1835
+ }
1836
+ /** Tell each panel it's going away. Called before every rebuild. */
1837
+ function suspendEditorPanels() {
1838
+ for (const active of activePanels.splice(0)) {
1839
+ callPanel(active, (panel) => panel.suspend?.());
1840
+ active.live = false;
1841
+ }
1842
+ }
1843
+ /**
1844
+ * Start `component`'s panels: its own {@link Showable.editorPanel}, then the project's,
1845
+ * from `canvasRecorder.addEditorPanel()`.
1846
+ * @returns The elements to show, in order.
1847
+ */
1848
+ function startEditorPanels(component) {
1849
+ return canvasRecorder.editorPanelsFor(component).map((panel) => {
1850
+ const active = {
1851
+ panel,
1852
+ component,
1853
+ element: document.createElement("div"),
1854
+ live: true,
1855
+ };
1856
+ activePanels.push(active);
1857
+ const api = {
1858
+ getTimeMs: () => componentTimeMs(component),
1859
+ seek(ms) {
1860
+ if (!active.live)
1861
+ return;
1862
+ visualEditorAPI.seek(ms + componentStartMs(component));
1863
+ },
1864
+ propertyChanged(property) {
1865
+ if (!active.live)
1866
+ return;
1867
+ activeRootComponentEditor?.update(component, property);
1868
+ markDirty();
1869
+ // Rebuild so the tables show the new value. That restarts this panel too.
1870
+ updateScheduleEditor(component);
1871
+ },
1872
+ refreshGUI(howMuch) {
1873
+ if (!active.live)
1874
+ return;
1875
+ visualEditorAPI.refreshGUI(howMuch);
1876
+ },
1877
+ };
1878
+ callPanel(active, (panel) => {
1879
+ const element = panel.start(api);
1880
+ if (!(element instanceof HTMLElement)) {
1881
+ throw new Error("start() didn't return an HTMLElement.");
1882
+ }
1883
+ active.element = element;
1884
+ });
1885
+ // Every keystroke in the properties, and every duration change.
1886
+ scheduleEditorRefreshers.push(() => callPanel(active, (panel) => panel.update?.()));
1887
+ return active.element;
1888
+ });
1889
+ }
1890
+ /** The playhead moved. Called from {@link showFrame}. */
1891
+ function editorPanelsTimeChanged() {
1892
+ // A copy: a panel's call may rebuild the list.
1893
+ for (const active of [...activePanels]) {
1894
+ callPanel(active, (panel) => panel.timeChanged?.());
1895
+ }
1896
+ }
1757
1897
  /**
1758
1898
  * The schedules the user switched to **Durations**, as opposed to the
1759
1899
  * default, **Times**. See {@link buildScheduleSection}.
@@ -2075,6 +2215,7 @@ timelineDisplay.onBlockClick = (id) => {
2075
2215
  updateComponentEditor(container);
2076
2216
  updateScheduleEditor(child);
2077
2217
  timelineDisplay.setSelectedId(child);
2218
+ activeRootComponentEditor?.selectionChanged(child);
2078
2219
  return true;
2079
2220
  }
2080
2221
  if (child.children?.length && findIn(child.children, child))
@@ -2408,21 +2549,72 @@ function _updateTimeline(selectable) {
2408
2549
  timelineDisplay.setBlocks(_buildTimelineBlocks(selectable));
2409
2550
  timelineDisplay.setSelectedId(selectedSlideChild ?? undefined);
2410
2551
  }
2552
+ /**
2553
+ * Read from the last session, waiting for the saved tree to load. If the page unloads
2554
+ * first, {@link saveState} saves this again, not the default place the page is showing.
2555
+ */
2556
+ let placeToRestore;
2557
+ function currentPlace() {
2558
+ const root = chapterList[select.selectedIndex];
2559
+ const limits = chapterList.find((d) => d.selectable === limitsShowable);
2560
+ const timeInRootMs = playheadInRootMs();
2561
+ return {
2562
+ rootPath: root ? chapterPath(root) : [],
2563
+ keepLimits: keepLimitsCheckbox.checked,
2564
+ limitsPath: limits ? chapterPath(limits) : null,
2565
+ timeInRootMs: isFinite(timeInRootMs) ? timeInRootMs : null,
2566
+ onSectionEnd: querySelector('input[name="onSectionEnd"]:checked', HTMLInputElement).value,
2567
+ wasPlaying: playCheckBox.checked,
2568
+ };
2569
+ }
2570
+ /** Parse what {@link saveState} wrote. undefined if there's nothing, or it's from an older version. */
2571
+ function parseSavedPlace(json) {
2572
+ if (!json)
2573
+ return undefined;
2574
+ try {
2575
+ const place = JSON.parse(json);
2576
+ return Array.isArray(place?.rootPath) ? place : undefined;
2577
+ }
2578
+ catch {
2579
+ return undefined;
2580
+ }
2581
+ }
2582
+ /**
2583
+ * Go back to the place saved by the last session, in the tree as it is now.
2584
+ * Call this after the saved tree is restored.
2585
+ */
2586
+ function restorePlace(place) {
2587
+ // The saved tree can change which chapters exist, and where they start.
2588
+ initChapters();
2589
+ select.selectedIndex = findChapter(place.rootPath);
2590
+ updateFromSelect();
2591
+ if (place.keepLimits) {
2592
+ keepLimitsCheckbox.checked = true;
2593
+ if (place.limitsPath) {
2594
+ limitsShowable = chapterList[findChapter(place.limitsPath)].selectable;
2595
+ applyLimits();
2596
+ }
2597
+ }
2598
+ if (place.timeInRootMs !== null) {
2599
+ const savedMs = rootStartMs + place.timeInRootMs;
2600
+ loadPlayPositionSeconds(Math.max(sectionStartTime, Math.min(sectionEndTime, savedMs)));
2601
+ }
2602
+ loadPlayPositionRange();
2603
+ // "continue" was removed. A page saved with it pauses instead.
2604
+ const onEnd = document.querySelector(`input[name="onSectionEnd"][value="${place.onSectionEnd}"]`);
2605
+ if (onEnd)
2606
+ onEnd.checked = true;
2607
+ if (place.wasPlaying)
2608
+ playCheckBox.checked = true;
2609
+ }
2411
2610
  /**
2412
2611
  * When someone hits refresh in their browser,
2413
2612
  * or hits save in vs code so vite causes a refresh,
2414
2613
  * restart the user with the same gui settings.
2415
2614
  */
2416
2615
  function saveState() {
2417
- sessionStorage.setItem("index", select.selectedIndex.toString());
2418
- sessionStorage.setItem("keepLimits", keepLimitsCheckbox.checked ? "1" : "0");
2419
- sessionStorage.setItem("limitsIndex", chapterList.findIndex((d) => d.selectable === limitsShowable).toString());
2420
- // From the start of the video, however the field shows it. "" for an empty field.
2421
- const playheadMs = playheadInVideoMs();
2422
- sessionStorage.setItem("timeInSeconds", isFinite(playheadMs) ? (playheadMs / 1000).toString() : "");
2616
+ sessionStorage.setItem("place", JSON.stringify(placeToRestore ?? currentPlace()));
2423
2617
  sessionStorage.setItem("playPositionLocal", playPositionLocal.checked ? "1" : "0");
2424
- sessionStorage.setItem("state", querySelector('input[name="onSectionEnd"]:checked', HTMLInputElement).value);
2425
- sessionStorage.setItem("wasPlaying", playCheckBox.checked ? "1" : "0");
2426
2618
  sessionStorage.setItem("zoomSelect", zoomSelect.value);
2427
2619
  sessionStorage.setItem("panX", panX.toString());
2428
2620
  sessionStorage.setItem("panY", panY.toString());
@@ -5322,6 +5514,7 @@ function buildNameSection(selectable) {
5322
5514
  return section;
5323
5515
  }
5324
5516
  function updateScheduleEditor(selectable) {
5517
+ suspendEditorPanels();
5325
5518
  scheduleEditorFieldset.replaceChildren();
5326
5519
  editingRectKf = null;
5327
5520
  viewingRectKfs.clear();
@@ -5449,11 +5642,7 @@ function updateScheduleEditor(selectable) {
5449
5642
  }
5450
5643
  if (selectable instanceof HandwritingEffectComponent) {
5451
5644
  const handwritingPanel = buildHandwritingPanel(selectable, {
5452
- localTimeMs(owner) {
5453
- const root = currentRoot();
5454
- const ownerStart = root ? (startWithin(root, owner) ?? 0) : 0;
5455
- return playheadInRootMs() - ownerStart;
5456
- },
5645
+ localTimeMs: componentTimeMs,
5457
5646
  progressChanged() {
5458
5647
  activeRootComponentEditor?.update(selectable, selectable.progressSchedule);
5459
5648
  markDirty();
@@ -5465,6 +5654,9 @@ function updateScheduleEditor(selectable) {
5465
5654
  // Every keystroke in Divisions or Progress updates the status.
5466
5655
  scheduleEditorRefreshers.push(handwritingPanel.refresh);
5467
5656
  }
5657
+ // A component's own panels, and the project's: after the library's, so on a Fourier
5658
+ // the library's status comes first.
5659
+ scheduleEditorFieldset.append(...startEditorPanels(selectable));
5468
5660
  for (const info of scalars ?? []) {
5469
5661
  const section = buildScalarSection(info, selectable, (s, i) => activeRootComponentEditor?.update(s, i));
5470
5662
  // Rebuild the Transform Info panel whenever the template string changes.
@@ -6499,6 +6691,12 @@ function applyMarkerDrag(localX, localY, shiftKey = false) {
6499
6691
  if (jsonResult.ok) {
6500
6692
  applyJsonSnapshot(jsonResult.data, true, false);
6501
6693
  }
6694
+ // Now the chapters are the saved tree's, so the last session's place can be found.
6695
+ if (placeToRestore) {
6696
+ const place = placeToRestore;
6697
+ placeToRestore = undefined;
6698
+ restorePlace(place);
6699
+ }
6502
6700
  // Catch the synced files up with whatever was restored, rather than
6503
6701
  // trusting the last session's final write: a write started as the page
6504
6702
  // unloads usually never finishes. (It can't leave a corrupt file, only a
@@ -6532,39 +6730,8 @@ function applyMarkerDrag(localX, localY, shiftKey = false) {
6532
6730
  playPositionLocal.checked = false;
6533
6731
  loadPlayPositionSeconds(playheadMs);
6534
6732
  }
6535
- const index = sessionStorage.getItem("index");
6536
- const timeInSeconds = sessionStorage.getItem("timeInSeconds");
6537
- const state = sessionStorage.getItem("state");
6538
- if (index && timeInSeconds && state) {
6539
- select.selectedIndex = assertNonNullable(parseIntX(index));
6540
- if (select.selectedIndex < 0) {
6541
- // What if you save the state when row 13 is selected, but there are currently
6542
- // only 5 rows available? That's when we get here. Without this change
6543
- // updateFromSelect() would throw an exception.
6544
- select.selectedIndex = 0;
6545
- }
6546
- updateFromSelect();
6547
- if (sessionStorage.getItem("keepLimits") === "1") {
6548
- keepLimitsCheckbox.checked = true;
6549
- const limitsIndex = parseIntX(sessionStorage.getItem("limitsIndex") ?? "");
6550
- const saved = limitsIndex === undefined ? undefined : chapterList[limitsIndex];
6551
- if (saved) {
6552
- limitsShowable = saved.selectable;
6553
- applyLimits();
6554
- }
6555
- }
6556
- const savedMs = parseFloat(timeInSeconds) * 1000;
6557
- const clampedMs = Math.max(sectionStartTime, Math.min(sectionEndTime, savedMs));
6558
- loadPlayPositionSeconds(clampedMs);
6559
- loadPlayPositionRange();
6560
- // "continue" was removed. A page saved with it pauses instead.
6561
- const onEnd = document.querySelector(`input[name="onSectionEnd"][value="${state}"]`);
6562
- if (onEnd)
6563
- onEnd.checked = true;
6564
- if (sessionStorage.getItem("wasPlaying") === "1") {
6565
- playCheckBox.checked = true;
6566
- }
6567
- }
6733
+ // Applied when the saved tree is in: see initFromDB() above.
6734
+ placeToRestore = parseSavedPlace(sessionStorage.getItem("place"));
6568
6735
  if (sessionStorage.getItem("quality") === "Low Power") {
6569
6736
  getById("lowPower", HTMLInputElement).checked = true;
6570
6737
  }