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.
package/README.md CHANGED
@@ -222,6 +222,19 @@ For a new project, take the next number and add it here.
222
222
  When the editor loads saved changes, it rebuilds those children from the registry, so a `description` from your constructor comes back as the registry's default.
223
223
  `userEditableDescription` is saved with the rest, and the diff file uses it to match each child with its TypeScript.
224
224
 
225
+ ### Your own panels in the Visual Editor
226
+
227
+ A panel is your own HTML, shown with a component's properties, bottom right, whenever that component is selected.
228
+ It can read the playhead in the component's own time, move it, and change the component's properties.
229
+ See `EditorPanel` in `src/showable.ts`, and the showcase's "Editor Panels" slide (`test-project/src/showcase/editor-panel.ts`).
230
+
231
+ - **On your own component:** give it an `editorPanel`.
232
+ - **On any component, including the library's:** `canvasRecorder.addEditorPanel((component) => …)` returns a panel for the components you choose, and `undefined` for the rest.
233
+ The showcase gives every Fourier a list of its terms this way.
234
+ - **After changing a property, call `propertyChanged()`.** That saves it, like any other edit, and rebuilds the tables.
235
+ - **Anything worth keeping goes in a property.** The panel object lasts as long as its component, but not across a reload.
236
+ - **Touch the DOM only in `start()` and later,** never while a module loads.
237
+
225
238
  ### Recording a program that has its own state
226
239
 
227
240
  Most of canvas-recorder's components draw any time you ask, in any order.
@@ -4,7 +4,6 @@ import {
4
4
  assertNonNullable,
5
5
  FIGURE_SPACE,
6
6
  parseFloatX,
7
- parseIntX,
8
7
  ReadOnlyRect,
9
8
  } from "phil-lib/misc";
10
9
  import {
@@ -22,6 +21,8 @@ import {
22
21
  QUALITY_HIGH,
23
22
  } from "mediabunny";
24
23
  import {
24
+ EditorPanel,
25
+ EditorPanelAPI,
25
26
  RootComponentEditor,
26
27
  SerializedScalar,
27
28
  SerializedSchedule,
@@ -529,6 +530,7 @@ function showFrame(timeInMs: number, live: boolean) {
529
530
  if (live)
530
531
  transcriptView?.update(timeInMs - rootStartMs, playCheckBox.checked);
531
532
  for (const update of goToButtonUpdaters) update();
533
+ editorPanelsTimeChanged();
532
534
  context.reset();
533
535
  context.setTransform(mainTransform());
534
536
  if (live) {
@@ -1885,6 +1887,59 @@ function currentRoot(): Showable | undefined {
1885
1887
  return chapterList[select.selectedIndex]?.selectable;
1886
1888
  }
1887
1889
 
1890
+ // MARK: Chapter paths
1891
+
1892
+ /**
1893
+ * One step down the tree: the child's position among its parent's children, and its name.
1894
+ *
1895
+ * A chapter's row in the `<select>` changes whenever the tree above it changes shape, e.g.
1896
+ * when saved state adds components to an earlier scene. A path of these doesn't.
1897
+ */
1898
+ type ChapterPathStep = { readonly index: number; readonly name: string };
1899
+
1900
+ /** The name the chapter `<select>` shows. */
1901
+ function chapterName(showable: Showable): string {
1902
+ return showable.userEditableDescription ?? showable.description;
1903
+ }
1904
+
1905
+ /** The way down from the top of the video to this chapter. Find it again with {@link findChapter}. */
1906
+ function chapterPath(info: ShowableTree): ChapterPathStep[] {
1907
+ const path: ChapterPathStep[] = [];
1908
+ for (let step = info; step.parent; step = step.parent) {
1909
+ const child = step.selectable;
1910
+ const index =
1911
+ step.parent.selectable.children?.findIndex((c) => c.child === child) ??
1912
+ -1;
1913
+ path.push({ index, name: chapterName(child) });
1914
+ }
1915
+ return path.reverse();
1916
+ }
1917
+
1918
+ /**
1919
+ * Find a chapter again from its {@link chapterPath}, in a tree that may have changed.
1920
+ *
1921
+ * At each step, the child at the same position if it still has the same name, otherwise the
1922
+ * first sibling with that name. If a step can't be found, the deepest chapter found so far.
1923
+ * @returns An index into {@link chapterList}. 0, the whole video, if nothing matched.
1924
+ */
1925
+ function findChapter(path: readonly ChapterPathStep[]): number {
1926
+ let current: Showable = toShow;
1927
+ let found = 0;
1928
+ for (const { index, name } of path) {
1929
+ const children = current.children ?? [];
1930
+ const atIndex = children[index]?.child;
1931
+ const next =
1932
+ atIndex && chapterName(atIndex) === name
1933
+ ? atIndex
1934
+ : children.find((c) => chapterName(c.child) === name)?.child;
1935
+ if (!next) break;
1936
+ current = next;
1937
+ const position = chapterList.findIndex((d) => d.selectable === next);
1938
+ if (position >= 0) found = position;
1939
+ }
1940
+ return found;
1941
+ }
1942
+
1888
1943
  /** When checked, picking another root leaves the play limits alone. */
1889
1944
  const keepLimitsCheckbox = getById("keepLimits", HTMLInputElement);
1890
1945
  /** Says what the play limits are, below the chapter `<select>`. */
@@ -1920,6 +1975,8 @@ const visualEditorAPI: VisualEditorAPI = {
1920
1975
  if (howMuch === "sound") {
1921
1976
  soundtrack.request();
1922
1977
  } else if (howMuch === "properties") {
1978
+ // A property changed, so it has to be saved, like any other edit.
1979
+ markDirty();
1923
1980
  updateScheduleEditor(selectedSlideChild ?? selectable);
1924
1981
  } else {
1925
1982
  // "structure"
@@ -2146,6 +2203,124 @@ const timelineWordsMemo = new WeakMap<
2146
2203
  */
2147
2204
  const scheduleEditorRefreshers: Array<() => void> = [];
2148
2205
 
2206
+ // MARK: Editor panels
2207
+
2208
+ /** One {@link EditorPanel} shown with the selected component's properties. */
2209
+ type ActivePanel = {
2210
+ readonly panel: EditorPanel;
2211
+ readonly component: Showable;
2212
+ /** What's shown: the panel's element, or an error in its place. */
2213
+ element: HTMLElement;
2214
+ /** False once suspended or broken. Then the panel isn't called again, and its API does nothing. */
2215
+ live: boolean;
2216
+ };
2217
+
2218
+ /**
2219
+ * The panels shown now. Rebuilt by {@link updateScheduleEditor}.
2220
+ * Declared up here because the first schedule editor is built while this module is still loading.
2221
+ */
2222
+ const activePanels: ActivePanel[] = [];
2223
+
2224
+ /** Where `component` starts, in the Visual Editor's root's time. */
2225
+ function componentStartMs(component: Showable): number {
2226
+ const root = currentRoot();
2227
+ return root ? (startWithin(root, component) ?? 0) : 0;
2228
+ }
2229
+
2230
+ /** The playhead in `component`'s own time: what its `show()` gets as `timeInMs`. */
2231
+ function componentTimeMs(component: Showable): number {
2232
+ return playheadInRootMs() - componentStartMs(component);
2233
+ }
2234
+
2235
+ /** Show `reason` where `active`'s panel was, and stop calling that panel. */
2236
+ function panelFailed(active: ActivePanel, reason: unknown): void {
2237
+ console.error(reason);
2238
+ active.live = false;
2239
+ const name =
2240
+ active.component.userEditableDescription ?? active.component.description;
2241
+ const line = document.createElement("div");
2242
+ line.style.cssText = "color:#b00;margin-bottom:0.4em";
2243
+ line.textContent = `✗ A panel for "${name}" failed: ${String(reason)}`;
2244
+ active.element.replaceWith(line);
2245
+ active.element = line;
2246
+ }
2247
+
2248
+ /** Call into a panel, unless it's suspended or broken. A bug in a panel mustn't break the editor. */
2249
+ function callPanel(
2250
+ active: ActivePanel,
2251
+ call: (panel: EditorPanel) => void,
2252
+ ): void {
2253
+ if (!active.live) return;
2254
+ try {
2255
+ call(active.panel);
2256
+ } catch (reason) {
2257
+ panelFailed(active, reason);
2258
+ }
2259
+ }
2260
+
2261
+ /** Tell each panel it's going away. Called before every rebuild. */
2262
+ function suspendEditorPanels(): void {
2263
+ for (const active of activePanels.splice(0)) {
2264
+ callPanel(active, (panel) => panel.suspend?.());
2265
+ active.live = false;
2266
+ }
2267
+ }
2268
+
2269
+ /**
2270
+ * Start `component`'s panels: its own {@link Showable.editorPanel}, then the project's,
2271
+ * from `canvasRecorder.addEditorPanel()`.
2272
+ * @returns The elements to show, in order.
2273
+ */
2274
+ function startEditorPanels(component: Showable): HTMLElement[] {
2275
+ return canvasRecorder.editorPanelsFor(component).map((panel) => {
2276
+ const active: ActivePanel = {
2277
+ panel,
2278
+ component,
2279
+ element: document.createElement("div"),
2280
+ live: true,
2281
+ };
2282
+ activePanels.push(active);
2283
+ const api: EditorPanelAPI = {
2284
+ getTimeMs: () => componentTimeMs(component),
2285
+ seek(ms) {
2286
+ if (!active.live) return;
2287
+ visualEditorAPI.seek(ms + componentStartMs(component));
2288
+ },
2289
+ propertyChanged(property) {
2290
+ if (!active.live) return;
2291
+ activeRootComponentEditor?.update(component, property);
2292
+ markDirty();
2293
+ // Rebuild so the tables show the new value. That restarts this panel too.
2294
+ updateScheduleEditor(component);
2295
+ },
2296
+ refreshGUI(howMuch) {
2297
+ if (!active.live) return;
2298
+ visualEditorAPI.refreshGUI(howMuch);
2299
+ },
2300
+ };
2301
+ callPanel(active, (panel) => {
2302
+ const element = panel.start(api);
2303
+ if (!(element instanceof HTMLElement)) {
2304
+ throw new Error("start() didn't return an HTMLElement.");
2305
+ }
2306
+ active.element = element;
2307
+ });
2308
+ // Every keystroke in the properties, and every duration change.
2309
+ scheduleEditorRefreshers.push(() =>
2310
+ callPanel(active, (panel) => panel.update?.()),
2311
+ );
2312
+ return active.element;
2313
+ });
2314
+ }
2315
+
2316
+ /** The playhead moved. Called from {@link showFrame}. */
2317
+ function editorPanelsTimeChanged(): void {
2318
+ // A copy: a panel's call may rebuild the list.
2319
+ for (const active of [...activePanels]) {
2320
+ callPanel(active, (panel) => panel.timeChanged?.());
2321
+ }
2322
+ }
2323
+
2149
2324
  /**
2150
2325
  * The schedules the user switched to **Durations**, as opposed to the
2151
2326
  * default, **Times**. See {@link buildScheduleSection}.
@@ -2474,6 +2649,7 @@ timelineDisplay.onBlockClick = (id) => {
2474
2649
  updateComponentEditor(container);
2475
2650
  updateScheduleEditor(child);
2476
2651
  timelineDisplay.setSelectedId(child);
2652
+ activeRootComponentEditor?.selectionChanged(child);
2477
2653
  return true;
2478
2654
  }
2479
2655
  if (child.children?.length && findIn(child.children, child)) return true;
@@ -2837,33 +3013,103 @@ function _updateTimeline(selectable: Showable): void {
2837
3013
  timelineDisplay.setSelectedId(selectedSlideChild ?? undefined);
2838
3014
  }
2839
3015
 
3016
+ /**
3017
+ * Where the user was in the video: the chapter, the play limits, the playhead, and whether
3018
+ * it was playing. {@link saveState} keeps it across a reload.
3019
+ *
3020
+ * Which chapters exist, and where they start, depends on the saved tree, and that's restored
3021
+ * asynchronously, by `initFromDB()`. So this is put back after that, by {@link restorePlace}.
3022
+ */
3023
+ type SavedPlace = {
3024
+ readonly rootPath: readonly ChapterPathStep[];
3025
+ readonly keepLimits: boolean;
3026
+ readonly limitsPath: readonly ChapterPathStep[] | null;
3027
+ /** From the start of the root, so it stays put if an earlier chapter changes length. null for an empty field. */
3028
+ readonly timeInRootMs: number | null;
3029
+ /** The "on section end" radio button's value. */
3030
+ readonly onSectionEnd: string;
3031
+ readonly wasPlaying: boolean;
3032
+ };
3033
+
3034
+ /**
3035
+ * Read from the last session, waiting for the saved tree to load. If the page unloads
3036
+ * first, {@link saveState} saves this again, not the default place the page is showing.
3037
+ */
3038
+ let placeToRestore: SavedPlace | undefined;
3039
+
3040
+ function currentPlace(): SavedPlace {
3041
+ const root = chapterList[select.selectedIndex];
3042
+ const limits = chapterList.find((d) => d.selectable === limitsShowable);
3043
+ const timeInRootMs = playheadInRootMs();
3044
+ return {
3045
+ rootPath: root ? chapterPath(root) : [],
3046
+ keepLimits: keepLimitsCheckbox.checked,
3047
+ limitsPath: limits ? chapterPath(limits) : null,
3048
+ timeInRootMs: isFinite(timeInRootMs) ? timeInRootMs : null,
3049
+ onSectionEnd: querySelector(
3050
+ 'input[name="onSectionEnd"]:checked',
3051
+ HTMLInputElement,
3052
+ ).value,
3053
+ wasPlaying: playCheckBox.checked,
3054
+ };
3055
+ }
3056
+
3057
+ /** Parse what {@link saveState} wrote. undefined if there's nothing, or it's from an older version. */
3058
+ function parseSavedPlace(json: string | null): SavedPlace | undefined {
3059
+ if (!json) return undefined;
3060
+ try {
3061
+ const place = JSON.parse(json) as SavedPlace;
3062
+ return Array.isArray(place?.rootPath) ? place : undefined;
3063
+ } catch {
3064
+ return undefined;
3065
+ }
3066
+ }
3067
+
3068
+ /**
3069
+ * Go back to the place saved by the last session, in the tree as it is now.
3070
+ * Call this after the saved tree is restored.
3071
+ */
3072
+ function restorePlace(place: SavedPlace): void {
3073
+ // The saved tree can change which chapters exist, and where they start.
3074
+ initChapters();
3075
+ select.selectedIndex = findChapter(place.rootPath);
3076
+ updateFromSelect();
3077
+ if (place.keepLimits) {
3078
+ keepLimitsCheckbox.checked = true;
3079
+ if (place.limitsPath) {
3080
+ limitsShowable = chapterList[findChapter(place.limitsPath)].selectable;
3081
+ applyLimits();
3082
+ }
3083
+ }
3084
+ if (place.timeInRootMs !== null) {
3085
+ const savedMs = rootStartMs + place.timeInRootMs;
3086
+ loadPlayPositionSeconds(
3087
+ Math.max(sectionStartTime, Math.min(sectionEndTime, savedMs)),
3088
+ );
3089
+ }
3090
+ loadPlayPositionRange();
3091
+ // "continue" was removed. A page saved with it pauses instead.
3092
+ const onEnd = document.querySelector<HTMLInputElement>(
3093
+ `input[name="onSectionEnd"][value="${place.onSectionEnd}"]`,
3094
+ );
3095
+ if (onEnd) onEnd.checked = true;
3096
+ if (place.wasPlaying) playCheckBox.checked = true;
3097
+ }
3098
+
2840
3099
  /**
2841
3100
  * When someone hits refresh in their browser,
2842
3101
  * or hits save in vs code so vite causes a refresh,
2843
3102
  * restart the user with the same gui settings.
2844
3103
  */
2845
3104
  function saveState() {
2846
- sessionStorage.setItem("index", select.selectedIndex.toString());
2847
- sessionStorage.setItem("keepLimits", keepLimitsCheckbox.checked ? "1" : "0");
2848
- sessionStorage.setItem(
2849
- "limitsIndex",
2850
- chapterList.findIndex((d) => d.selectable === limitsShowable).toString(),
2851
- );
2852
- // From the start of the video, however the field shows it. "" for an empty field.
2853
- const playheadMs = playheadInVideoMs();
2854
3105
  sessionStorage.setItem(
2855
- "timeInSeconds",
2856
- isFinite(playheadMs) ? (playheadMs / 1000).toString() : "",
3106
+ "place",
3107
+ JSON.stringify(placeToRestore ?? currentPlace()),
2857
3108
  );
2858
3109
  sessionStorage.setItem(
2859
3110
  "playPositionLocal",
2860
3111
  playPositionLocal.checked ? "1" : "0",
2861
3112
  );
2862
- sessionStorage.setItem(
2863
- "state",
2864
- querySelector('input[name="onSectionEnd"]:checked', HTMLInputElement).value,
2865
- );
2866
- sessionStorage.setItem("wasPlaying", playCheckBox.checked ? "1" : "0");
2867
3113
  sessionStorage.setItem("zoomSelect", zoomSelect.value);
2868
3114
  sessionStorage.setItem("panX", panX.toString());
2869
3115
  sessionStorage.setItem("panY", panY.toString());
@@ -6228,6 +6474,7 @@ function buildNameSection(selectable: Showable): HTMLElement {
6228
6474
  }
6229
6475
 
6230
6476
  function updateScheduleEditor(selectable: Showable) {
6477
+ suspendEditorPanels();
6231
6478
  scheduleEditorFieldset.replaceChildren();
6232
6479
  editingRectKf = null;
6233
6480
  viewingRectKfs.clear();
@@ -6374,11 +6621,7 @@ function updateScheduleEditor(selectable: Showable) {
6374
6621
  }
6375
6622
  if (selectable instanceof HandwritingEffectComponent) {
6376
6623
  const handwritingPanel = buildHandwritingPanel(selectable, {
6377
- localTimeMs(owner) {
6378
- const root = currentRoot();
6379
- const ownerStart = root ? (startWithin(root, owner) ?? 0) : 0;
6380
- return playheadInRootMs() - ownerStart;
6381
- },
6624
+ localTimeMs: componentTimeMs,
6382
6625
  progressChanged() {
6383
6626
  activeRootComponentEditor?.update(
6384
6627
  selectable,
@@ -6393,6 +6636,9 @@ function updateScheduleEditor(selectable: Showable) {
6393
6636
  // Every keystroke in Divisions or Progress updates the status.
6394
6637
  scheduleEditorRefreshers.push(handwritingPanel.refresh);
6395
6638
  }
6639
+ // A component's own panels, and the project's: after the library's, so on a Fourier
6640
+ // the library's status comes first.
6641
+ scheduleEditorFieldset.append(...startEditorPanels(selectable));
6396
6642
 
6397
6643
  for (const info of scalars ?? []) {
6398
6644
  const section = buildScalarSection(info, selectable, (s, i) =>
@@ -7552,6 +7798,12 @@ function applyMarkerDrag(localX: number, localY: number, shiftKey = false) {
7552
7798
  if (jsonResult.ok) {
7553
7799
  applyJsonSnapshot(jsonResult.data, true, false);
7554
7800
  }
7801
+ // Now the chapters are the saved tree's, so the last session's place can be found.
7802
+ if (placeToRestore) {
7803
+ const place = placeToRestore;
7804
+ placeToRestore = undefined;
7805
+ restorePlace(place);
7806
+ }
7555
7807
  // Catch the synced files up with whatever was restored, rather than
7556
7808
  // trusting the last session's final write: a write started as the page
7557
7809
  // unloads usually never finishes. (It can't leave a corrupt file, only a
@@ -7591,46 +7843,8 @@ function applyMarkerDrag(localX: number, localY: number, shiftKey = false) {
7591
7843
  playPositionLocal.checked = false;
7592
7844
  loadPlayPositionSeconds(playheadMs);
7593
7845
  }
7594
- const index = sessionStorage.getItem("index");
7595
- const timeInSeconds = sessionStorage.getItem("timeInSeconds");
7596
- const state = sessionStorage.getItem("state");
7597
- if (index && timeInSeconds && state) {
7598
- select.selectedIndex = assertNonNullable(parseIntX(index));
7599
- if (select.selectedIndex < 0) {
7600
- // What if you save the state when row 13 is selected, but there are currently
7601
- // only 5 rows available? That's when we get here. Without this change
7602
- // updateFromSelect() would throw an exception.
7603
- select.selectedIndex = 0;
7604
- }
7605
- updateFromSelect();
7606
- if (sessionStorage.getItem("keepLimits") === "1") {
7607
- keepLimitsCheckbox.checked = true;
7608
- const limitsIndex = parseIntX(
7609
- sessionStorage.getItem("limitsIndex") ?? "",
7610
- );
7611
- const saved =
7612
- limitsIndex === undefined ? undefined : chapterList[limitsIndex];
7613
- if (saved) {
7614
- limitsShowable = saved.selectable;
7615
- applyLimits();
7616
- }
7617
- }
7618
- const savedMs = parseFloat(timeInSeconds) * 1000;
7619
- const clampedMs = Math.max(
7620
- sectionStartTime,
7621
- Math.min(sectionEndTime, savedMs),
7622
- );
7623
- loadPlayPositionSeconds(clampedMs);
7624
- loadPlayPositionRange();
7625
- // "continue" was removed. A page saved with it pauses instead.
7626
- const onEnd = document.querySelector<HTMLInputElement>(
7627
- `input[name="onSectionEnd"][value="${state}"]`,
7628
- );
7629
- if (onEnd) onEnd.checked = true;
7630
- if (sessionStorage.getItem("wasPlaying") === "1") {
7631
- playCheckBox.checked = true;
7632
- }
7633
- }
7846
+ // Applied when the saved tree is in: see initFromDB() above.
7847
+ placeToRestore = parseSavedPlace(sessionStorage.getItem("place"));
7634
7848
  if (sessionStorage.getItem("quality") === "Low Power") {
7635
7849
  getById("lowPower", HTMLInputElement).checked = true;
7636
7850
  }