canvas-recorder-lib 0.7.2 → 0.7.4

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";
@@ -374,12 +374,13 @@ function checkVideosLocalFiles() {
374
374
  * input (pointermove, etc.).
375
375
  */
376
376
  function showFrame(timeInMs, live) {
377
- // While playing, the timeline keeps the play head on screen.
378
- timelineDisplay.setPlayMs(timeInMs - rootStartMs, live && playCheckBox.checked);
379
- if (live)
380
- transcriptView?.update(timeInMs - rootStartMs, playCheckBox.checked);
377
+ // While playing or saving, the timeline and 📖 Text keep the play head on screen.
378
+ const following = !live || playCheckBox.checked;
379
+ timelineDisplay.setPlayMs(timeInMs - rootStartMs, following);
380
+ transcriptView?.update(timeInMs - rootStartMs, following);
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) {
@@ -1171,6 +1172,7 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration, pixe
1171
1172
  const startTime = performance.now();
1172
1173
  await output.start();
1173
1174
  infoDiv.innerHTML = "Recording in progress...";
1175
+ showTranscriptViewForSave();
1174
1176
  const frameDuration = 1000 / FPS;
1175
1177
  // Offline loop: draw + push frames (not limited to realtime)
1176
1178
  let frameNumber = 0;
@@ -1283,6 +1285,7 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration, pixe
1283
1285
  applyZoom(currentZoomFactor);
1284
1286
  }
1285
1287
  suspendLiveAnimationLoop = false;
1288
+ endTranscriptViewForSave();
1286
1289
  }
1287
1290
  }
1288
1291
  cancelRecordingButton.addEventListener("click", () => {
@@ -1571,6 +1574,46 @@ initChapters();
1571
1574
  function currentRoot() {
1572
1575
  return chapterList[select.selectedIndex]?.selectable;
1573
1576
  }
1577
+ /** The name the chapter `<select>` shows. */
1578
+ function chapterName(showable) {
1579
+ return showable.userEditableDescription ?? showable.description;
1580
+ }
1581
+ /** The way down from the top of the video to this chapter. Find it again with {@link findChapter}. */
1582
+ function chapterPath(info) {
1583
+ const path = [];
1584
+ for (let step = info; step.parent; step = step.parent) {
1585
+ const child = step.selectable;
1586
+ const index = step.parent.selectable.children?.findIndex((c) => c.child === child) ??
1587
+ -1;
1588
+ path.push({ index, name: chapterName(child) });
1589
+ }
1590
+ return path.reverse();
1591
+ }
1592
+ /**
1593
+ * Find a chapter again from its {@link chapterPath}, in a tree that may have changed.
1594
+ *
1595
+ * At each step, the child at the same position if it still has the same name, otherwise the
1596
+ * first sibling with that name. If a step can't be found, the deepest chapter found so far.
1597
+ * @returns An index into {@link chapterList}. 0, the whole video, if nothing matched.
1598
+ */
1599
+ function findChapter(path) {
1600
+ let current = toShow;
1601
+ let found = 0;
1602
+ for (const { index, name } of path) {
1603
+ const children = current.children ?? [];
1604
+ const atIndex = children[index]?.child;
1605
+ const next = atIndex && chapterName(atIndex) === name
1606
+ ? atIndex
1607
+ : children.find((c) => chapterName(c.child) === name)?.child;
1608
+ if (!next)
1609
+ break;
1610
+ current = next;
1611
+ const position = chapterList.findIndex((d) => d.selectable === next);
1612
+ if (position >= 0)
1613
+ found = position;
1614
+ }
1615
+ return found;
1616
+ }
1574
1617
  /** When checked, picking another root leaves the play limits alone. */
1575
1618
  const keepLimitsCheckbox = getById("keepLimits", HTMLInputElement);
1576
1619
  /** Says what the play limits are, below the chapter `<select>`. */
@@ -1600,6 +1643,8 @@ const visualEditorAPI = {
1600
1643
  soundtrack.request();
1601
1644
  }
1602
1645
  else if (howMuch === "properties") {
1646
+ // A property changed, so it has to be saved, like any other edit.
1647
+ markDirty();
1603
1648
  updateScheduleEditor(selectedSlideChild ?? selectable);
1604
1649
  }
1605
1650
  else {
@@ -1754,6 +1799,103 @@ const timelineWordsMemo = new WeakMap();
1754
1799
  * Cleared whenever {@link updateScheduleEditor} rebuilds.
1755
1800
  */
1756
1801
  const scheduleEditorRefreshers = [];
1802
+ /**
1803
+ * The panels shown now. Rebuilt by {@link updateScheduleEditor}.
1804
+ * Declared up here because the first schedule editor is built while this module is still loading.
1805
+ */
1806
+ const activePanels = [];
1807
+ /** Where `component` starts, in the Visual Editor's root's time. */
1808
+ function componentStartMs(component) {
1809
+ const root = currentRoot();
1810
+ return root ? (startWithin(root, component) ?? 0) : 0;
1811
+ }
1812
+ /** The playhead in `component`'s own time: what its `show()` gets as `timeInMs`. */
1813
+ function componentTimeMs(component) {
1814
+ return playheadInRootMs() - componentStartMs(component);
1815
+ }
1816
+ /** Show `reason` where `active`'s panel was, and stop calling that panel. */
1817
+ function panelFailed(active, reason) {
1818
+ console.error(reason);
1819
+ active.live = false;
1820
+ const name = active.component.userEditableDescription ?? active.component.description;
1821
+ const line = document.createElement("div");
1822
+ line.style.cssText = "color:#b00;margin-bottom:0.4em";
1823
+ line.textContent = `✗ A panel for "${name}" failed: ${String(reason)}`;
1824
+ active.element.replaceWith(line);
1825
+ active.element = line;
1826
+ }
1827
+ /** Call into a panel, unless it's suspended or broken. A bug in a panel mustn't break the editor. */
1828
+ function callPanel(active, call) {
1829
+ if (!active.live)
1830
+ return;
1831
+ try {
1832
+ call(active.panel);
1833
+ }
1834
+ catch (reason) {
1835
+ panelFailed(active, reason);
1836
+ }
1837
+ }
1838
+ /** Tell each panel it's going away. Called before every rebuild. */
1839
+ function suspendEditorPanels() {
1840
+ for (const active of activePanels.splice(0)) {
1841
+ callPanel(active, (panel) => panel.suspend?.());
1842
+ active.live = false;
1843
+ }
1844
+ }
1845
+ /**
1846
+ * Start `component`'s panels: its own {@link Showable.editorPanel}, then the project's,
1847
+ * from `canvasRecorder.addEditorPanel()`.
1848
+ * @returns The elements to show, in order.
1849
+ */
1850
+ function startEditorPanels(component) {
1851
+ return canvasRecorder.editorPanelsFor(component).map((panel) => {
1852
+ const active = {
1853
+ panel,
1854
+ component,
1855
+ element: document.createElement("div"),
1856
+ live: true,
1857
+ };
1858
+ activePanels.push(active);
1859
+ const api = {
1860
+ getTimeMs: () => componentTimeMs(component),
1861
+ seek(ms) {
1862
+ if (!active.live)
1863
+ return;
1864
+ visualEditorAPI.seek(ms + componentStartMs(component));
1865
+ },
1866
+ propertyChanged(property) {
1867
+ if (!active.live)
1868
+ return;
1869
+ activeRootComponentEditor?.update(component, property);
1870
+ markDirty();
1871
+ // Rebuild so the tables show the new value. That restarts this panel too.
1872
+ updateScheduleEditor(component);
1873
+ },
1874
+ refreshGUI(howMuch) {
1875
+ if (!active.live)
1876
+ return;
1877
+ visualEditorAPI.refreshGUI(howMuch);
1878
+ },
1879
+ };
1880
+ callPanel(active, (panel) => {
1881
+ const element = panel.start(api);
1882
+ if (!(element instanceof HTMLElement)) {
1883
+ throw new Error("start() didn't return an HTMLElement.");
1884
+ }
1885
+ active.element = element;
1886
+ });
1887
+ // Every keystroke in the properties, and every duration change.
1888
+ scheduleEditorRefreshers.push(() => callPanel(active, (panel) => panel.update?.()));
1889
+ return active.element;
1890
+ });
1891
+ }
1892
+ /** The playhead moved. Called from {@link showFrame}. */
1893
+ function editorPanelsTimeChanged() {
1894
+ // A copy: a panel's call may rebuild the list.
1895
+ for (const active of [...activePanels]) {
1896
+ callPanel(active, (panel) => panel.timeChanged?.());
1897
+ }
1898
+ }
1757
1899
  /**
1758
1900
  * The schedules the user switched to **Durations**, as opposed to the
1759
1901
  * default, **Times**. See {@link buildScheduleSection}.
@@ -1977,19 +2119,7 @@ onTranscriptsChange(() => {
1977
2119
  // The transcript as text. It rebuilds itself when the clips or transcripts
1978
2120
  // change, so it needs no calls besides the one in showFrame().
1979
2121
  transcriptView = new TranscriptView({
1980
- clips() {
1981
- const root = currentRoot();
1982
- if (!root)
1983
- return [];
1984
- return soundOwners(root)
1985
- .flatMap(({ owner, startMs }) => (owner.soundClips ?? []).map((clip) => ({
1986
- clip,
1987
- owner,
1988
- startMs: startMs + clip.startMsIntoScene,
1989
- lengthMs: soundClipLengthMs(clip),
1990
- })))
1991
- .sort((a, b) => a.startMs - b.startMs);
1992
- },
2122
+ clips: transcriptViewClips,
1993
2123
  transcript(source) {
1994
2124
  const status = transcriptStatus(source);
1995
2125
  if (!status)
@@ -2023,34 +2153,77 @@ transcriptView = new TranscriptView({
2023
2153
  },
2024
2154
  });
2025
2155
  getById("timelineCanvas", HTMLCanvasElement).after(transcriptView.element);
2026
- {
2027
- const READ_KEY = "transcriptView.on";
2028
- const checkbox = getById("transcriptViewCheckbox", HTMLInputElement);
2029
- const timelineCanvas = getById("timelineCanvas", HTMLCanvasElement);
2030
- const apply = () => {
2031
- transcriptView.hidden = !checkbox.checked;
2032
- // The timeline's CSS sets `display`, which would beat the `hidden` attribute.
2033
- timelineCanvas.style.display = checkbox.checked ? "none" : "";
2034
- if (!checkbox.checked)
2035
- timelineDisplay.redraw();
2036
- };
2156
+ /** The current chapter's sound clips, in order of time, for 📖 Text. */
2157
+ function transcriptViewClips() {
2158
+ const root = currentRoot();
2159
+ if (!root)
2160
+ return [];
2161
+ return soundOwners(root)
2162
+ .flatMap(({ owner, startMs }) => (owner.soundClips ?? []).map((clip) => ({
2163
+ clip,
2164
+ owner,
2165
+ startMs: startMs + clip.startMsIntoScene,
2166
+ lengthMs: soundClipLengthMs(clip),
2167
+ })))
2168
+ .sort((a, b) => a.startMs - b.startMs);
2169
+ }
2170
+ // MARK: 📖 Text checkbox
2171
+ const transcriptViewCheckbox = getById("transcriptViewCheckbox", HTMLInputElement);
2172
+ const TRANSCRIPT_VIEW_KEY = "transcriptView.on";
2173
+ /** Show 📖 Text or the timeline, to match the checkbox. */
2174
+ function applyTranscriptViewCheckbox() {
2175
+ const on = transcriptViewCheckbox.checked;
2176
+ transcriptView.hidden = !on;
2177
+ // The timeline's CSS sets `display`, which would beat the `hidden` attribute.
2178
+ getById("timelineCanvas", HTMLCanvasElement).style.display = on ? "none" : "";
2179
+ if (!on)
2180
+ timelineDisplay.redraw();
2181
+ }
2182
+ /**
2183
+ * True while a save has switched to 📖 Text, and the user hasn't touched the checkbox since.
2184
+ * Then the save switches back when it's done.
2185
+ */
2186
+ let transcriptViewJustForSave = false;
2187
+ /**
2188
+ * A save shows 📖 Text by default, so you can read along while it records.
2189
+ * Only when there's something to read: transcripts are on, and the chapter has sound.
2190
+ */
2191
+ function showTranscriptViewForSave() {
2192
+ if (transcriptViewCheckbox.checked)
2193
+ return;
2194
+ if (!transcriptsEnabled() || transcriptViewClips().length === 0)
2195
+ return;
2196
+ transcriptViewCheckbox.checked = true;
2197
+ transcriptViewJustForSave = true;
2198
+ applyTranscriptViewCheckbox();
2199
+ }
2200
+ /** The save is over. Go back to the timeline, unless the user chose since. */
2201
+ function endTranscriptViewForSave() {
2202
+ if (!transcriptViewJustForSave)
2203
+ return;
2204
+ transcriptViewJustForSave = false;
2205
+ transcriptViewCheckbox.checked = false;
2206
+ applyTranscriptViewCheckbox();
2207
+ }
2208
+ try {
2209
+ transcriptViewCheckbox.checked =
2210
+ localStorage.getItem(TRANSCRIPT_VIEW_KEY) === "true";
2211
+ }
2212
+ catch {
2213
+ // Remembering is only a convenience.
2214
+ }
2215
+ transcriptViewCheckbox.addEventListener("input", () => {
2216
+ // The user's choice, so a save won't change it back, and it's remembered.
2217
+ transcriptViewJustForSave = false;
2037
2218
  try {
2038
- checkbox.checked = localStorage.getItem(READ_KEY) === "true";
2219
+ localStorage.setItem(TRANSCRIPT_VIEW_KEY, String(transcriptViewCheckbox.checked));
2039
2220
  }
2040
2221
  catch {
2041
- // Remembering is only a convenience.
2222
+ // See above.
2042
2223
  }
2043
- checkbox.addEventListener("input", () => {
2044
- try {
2045
- localStorage.setItem(READ_KEY, String(checkbox.checked));
2046
- }
2047
- catch {
2048
- // See above.
2049
- }
2050
- apply();
2051
- });
2052
- apply();
2053
- }
2224
+ applyTranscriptViewCheckbox();
2225
+ });
2226
+ applyTranscriptViewCheckbox();
2054
2227
  timelineDisplay.onSeek = (localMs) => {
2055
2228
  stopAudio();
2056
2229
  loadPlayPositionSeconds(localMs + rootStartMs);
@@ -2075,6 +2248,7 @@ timelineDisplay.onBlockClick = (id) => {
2075
2248
  updateComponentEditor(container);
2076
2249
  updateScheduleEditor(child);
2077
2250
  timelineDisplay.setSelectedId(child);
2251
+ activeRootComponentEditor?.selectionChanged(child);
2078
2252
  return true;
2079
2253
  }
2080
2254
  if (child.children?.length && findIn(child.children, child))
@@ -2408,21 +2582,72 @@ function _updateTimeline(selectable) {
2408
2582
  timelineDisplay.setBlocks(_buildTimelineBlocks(selectable));
2409
2583
  timelineDisplay.setSelectedId(selectedSlideChild ?? undefined);
2410
2584
  }
2585
+ /**
2586
+ * Read from the last session, waiting for the saved tree to load. If the page unloads
2587
+ * first, {@link saveState} saves this again, not the default place the page is showing.
2588
+ */
2589
+ let placeToRestore;
2590
+ function currentPlace() {
2591
+ const root = chapterList[select.selectedIndex];
2592
+ const limits = chapterList.find((d) => d.selectable === limitsShowable);
2593
+ const timeInRootMs = playheadInRootMs();
2594
+ return {
2595
+ rootPath: root ? chapterPath(root) : [],
2596
+ keepLimits: keepLimitsCheckbox.checked,
2597
+ limitsPath: limits ? chapterPath(limits) : null,
2598
+ timeInRootMs: isFinite(timeInRootMs) ? timeInRootMs : null,
2599
+ onSectionEnd: querySelector('input[name="onSectionEnd"]:checked', HTMLInputElement).value,
2600
+ wasPlaying: playCheckBox.checked,
2601
+ };
2602
+ }
2603
+ /** Parse what {@link saveState} wrote. undefined if there's nothing, or it's from an older version. */
2604
+ function parseSavedPlace(json) {
2605
+ if (!json)
2606
+ return undefined;
2607
+ try {
2608
+ const place = JSON.parse(json);
2609
+ return Array.isArray(place?.rootPath) ? place : undefined;
2610
+ }
2611
+ catch {
2612
+ return undefined;
2613
+ }
2614
+ }
2615
+ /**
2616
+ * Go back to the place saved by the last session, in the tree as it is now.
2617
+ * Call this after the saved tree is restored.
2618
+ */
2619
+ function restorePlace(place) {
2620
+ // The saved tree can change which chapters exist, and where they start.
2621
+ initChapters();
2622
+ select.selectedIndex = findChapter(place.rootPath);
2623
+ updateFromSelect();
2624
+ if (place.keepLimits) {
2625
+ keepLimitsCheckbox.checked = true;
2626
+ if (place.limitsPath) {
2627
+ limitsShowable = chapterList[findChapter(place.limitsPath)].selectable;
2628
+ applyLimits();
2629
+ }
2630
+ }
2631
+ if (place.timeInRootMs !== null) {
2632
+ const savedMs = rootStartMs + place.timeInRootMs;
2633
+ loadPlayPositionSeconds(Math.max(sectionStartTime, Math.min(sectionEndTime, savedMs)));
2634
+ }
2635
+ loadPlayPositionRange();
2636
+ // "continue" was removed. A page saved with it pauses instead.
2637
+ const onEnd = document.querySelector(`input[name="onSectionEnd"][value="${place.onSectionEnd}"]`);
2638
+ if (onEnd)
2639
+ onEnd.checked = true;
2640
+ if (place.wasPlaying)
2641
+ playCheckBox.checked = true;
2642
+ }
2411
2643
  /**
2412
2644
  * When someone hits refresh in their browser,
2413
2645
  * or hits save in vs code so vite causes a refresh,
2414
2646
  * restart the user with the same gui settings.
2415
2647
  */
2416
2648
  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() : "");
2649
+ sessionStorage.setItem("place", JSON.stringify(placeToRestore ?? currentPlace()));
2423
2650
  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
2651
  sessionStorage.setItem("zoomSelect", zoomSelect.value);
2427
2652
  sessionStorage.setItem("panX", panX.toString());
2428
2653
  sessionStorage.setItem("panY", panY.toString());
@@ -3219,6 +3444,8 @@ async function initFromDB(unloadBackup) {
3219
3444
  }
3220
3445
  _loadSource = source;
3221
3446
  _baselineTreeJson = currentTreeJson();
3447
+ // The unload backup is in the database now, or older than it. See the end of "Load previous state".
3448
+ sessionStorage.removeItem("pendingScheduleSave");
3222
3449
  canvas.style.visibility = "";
3223
3450
  canvasLoading.style.display = "none";
3224
3451
  const currentSel = currentRoot();
@@ -3325,6 +3552,12 @@ function currentSaveTarget() {
3325
3552
  return selectable.schedules?.length ? selectable : null;
3326
3553
  }
3327
3554
  function saveOnUnload() {
3555
+ // Still starting up: the live tree is the TypeScript defaults, not the user's work.
3556
+ // A backup of it would be newer than the real state, so the next startup would load it,
3557
+ // and everything made in the Visual Editor would disappear. The last session's backup,
3558
+ // if there was one, is still in sessionStorage until initFromDB() has saved it.
3559
+ if (_loadSource === undefined)
3560
+ return;
3328
3561
  // When the history dialog is open the live tree may hold a transient preview from
3329
3562
  // _dialogSelectItem. Back up the pre-dialog state instead, so a preview is never
3330
3563
  // persisted as if the user had accepted it.
@@ -5322,6 +5555,7 @@ function buildNameSection(selectable) {
5322
5555
  return section;
5323
5556
  }
5324
5557
  function updateScheduleEditor(selectable) {
5558
+ suspendEditorPanels();
5325
5559
  scheduleEditorFieldset.replaceChildren();
5326
5560
  editingRectKf = null;
5327
5561
  viewingRectKfs.clear();
@@ -5449,11 +5683,7 @@ function updateScheduleEditor(selectable) {
5449
5683
  }
5450
5684
  if (selectable instanceof HandwritingEffectComponent) {
5451
5685
  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
- },
5686
+ localTimeMs: componentTimeMs,
5457
5687
  progressChanged() {
5458
5688
  activeRootComponentEditor?.update(selectable, selectable.progressSchedule);
5459
5689
  markDirty();
@@ -5465,6 +5695,9 @@ function updateScheduleEditor(selectable) {
5465
5695
  // Every keystroke in Divisions or Progress updates the status.
5466
5696
  scheduleEditorRefreshers.push(handwritingPanel.refresh);
5467
5697
  }
5698
+ // A component's own panels, and the project's: after the library's, so on a Fourier
5699
+ // the library's status comes first.
5700
+ scheduleEditorFieldset.append(...startEditorPanels(selectable));
5468
5701
  for (const info of scalars ?? []) {
5469
5702
  const section = buildScalarSection(info, selectable, (s, i) => activeRootComponentEditor?.update(s, i));
5470
5703
  // Rebuild the Transform Info panel whenever the template string changes.
@@ -6499,6 +6732,12 @@ function applyMarkerDrag(localX, localY, shiftKey = false) {
6499
6732
  if (jsonResult.ok) {
6500
6733
  applyJsonSnapshot(jsonResult.data, true, false);
6501
6734
  }
6735
+ // Now the chapters are the saved tree's, so the last session's place can be found.
6736
+ if (placeToRestore) {
6737
+ const place = placeToRestore;
6738
+ placeToRestore = undefined;
6739
+ restorePlace(place);
6740
+ }
6502
6741
  // Catch the synced files up with whatever was restored, rather than
6503
6742
  // trusting the last session's final write: a write started as the page
6504
6743
  // unloads usually never finishes. (It can't leave a corrupt file, only a
@@ -6532,39 +6771,8 @@ function applyMarkerDrag(localX, localY, shiftKey = false) {
6532
6771
  playPositionLocal.checked = false;
6533
6772
  loadPlayPositionSeconds(playheadMs);
6534
6773
  }
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
- }
6774
+ // Applied when the saved tree is in: see initFromDB() above.
6775
+ placeToRestore = parseSavedPlace(sessionStorage.getItem("place"));
6568
6776
  if (sessionStorage.getItem("quality") === "Low Power") {
6569
6777
  getById("lowPower", HTMLInputElement).checked = true;
6570
6778
  }
@@ -6606,6 +6814,16 @@ function applyMarkerDrag(localX, localY, shiftKey = false) {
6606
6814
  }
6607
6815
  finally {
6608
6816
  sessionStorage.clear();
6817
+ // Keep the unload backup until initFromDB() has saved it. If the page reloads before
6818
+ // then, saveOnUnload() saves nothing, so this is the only copy.
6819
+ if (unloadBackup !== null) {
6820
+ try {
6821
+ sessionStorage.setItem("pendingScheduleSave", unloadBackup);
6822
+ }
6823
+ catch {
6824
+ // It fit a moment ago.
6825
+ }
6826
+ }
6609
6827
  }
6610
6828
  }
6611
6829
  // MARK: User interactions with the canvas.