canvas-recorder-lib 0.7.3 → 0.8.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.
@@ -97,19 +97,18 @@ let isRecording = false;
97
97
  * When the canvas is smaller than the viewport, centers it instead.
98
98
  */
99
99
  function clampPan(canvasCssWidth, canvasCssHeight, px, py) {
100
- const viewportWidth = viewport.clientWidth;
101
- const viewportHeight = viewport.clientHeight;
102
- if (canvasCssWidth <= viewportWidth) {
103
- return [
104
- Math.round((viewportWidth - canvasCssWidth) / 2),
105
- Math.round((viewportHeight - canvasCssHeight) / 2),
106
- ];
107
- }
100
+ // Each direction on its own: a portrait video at 100% can fit across but not down.
108
101
  return [
109
- Math.max(viewportWidth - canvasCssWidth, Math.min(0, px)),
110
- Math.max(viewportHeight - canvasCssHeight, Math.min(0, py)),
102
+ clampPanAxis(canvasCssWidth, viewport.clientWidth, px),
103
+ clampPanAxis(canvasCssHeight, viewport.clientHeight, py),
111
104
  ];
112
105
  }
106
+ /** Centered if the canvas fits this way, otherwise no gap at either edge. */
107
+ function clampPanAxis(canvasSize, viewportSize, pan) {
108
+ return canvasSize <= viewportSize
109
+ ? Math.round((viewportSize - canvasSize) / 2)
110
+ : Math.max(viewportSize - canvasSize, Math.min(0, pan));
111
+ }
113
112
  /**
114
113
  * Resizes the canvas to match zoom and repositions it via left/top.
115
114
  * zoom = 1.0 → 3840×2160 physical pixels, displayed at 1920×1080 CSS px on Retina.
@@ -141,6 +140,8 @@ function applyZoom(zoom, px = panX, py = panY) {
141
140
  [panX, panY] = clampPan(cssW, cssH, px, py);
142
141
  canvas.style.left = `${panX}px`;
143
142
  canvas.style.top = `${panY}px`;
143
+ // The hand cursor, only when there's something to drag into view.
144
+ canvas.classList.toggle("pannable", cssW > viewport.clientWidth || cssH > viewport.clientHeight);
144
145
  }
145
146
  /** Fits the 16:9 canvas into the viewport at pixel-perfect resolution. */
146
147
  function zoomToFit() {
@@ -165,6 +166,7 @@ function zoomToFit() {
165
166
  canvas.style.height = `${cssH}px`;
166
167
  canvas.style.left = `${Math.round((vpW - cssW) / 2)}px`;
167
168
  canvas.style.top = `${Math.round((vpH - cssH) / 2)}px`;
169
+ canvas.classList.remove("pannable");
168
170
  // Immediately redraw so the canvas clear doesn't show as a gray flash.
169
171
  showFrame(playheadInVideoMs(), true);
170
172
  }
@@ -374,10 +376,10 @@ function checkVideosLocalFiles() {
374
376
  * input (pointermove, etc.).
375
377
  */
376
378
  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);
379
+ // While playing or saving, the timeline and 📖 Text keep the play head on screen.
380
+ const following = !live || playCheckBox.checked;
381
+ timelineDisplay.setPlayMs(timeInMs - rootStartMs, following);
382
+ transcriptView?.update(timeInMs - rootStartMs, following);
381
383
  for (const update of goToButtonUpdaters)
382
384
  update();
383
385
  editorPanelsTimeChanged();
@@ -1119,6 +1121,8 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration, pixe
1119
1121
  canvas.style.top = "50%";
1120
1122
  canvas.style.transform = "translate(-50%, -50%)";
1121
1123
  canvas.style.transformOrigin = "";
1124
+ // No panning while saving. The finally block puts the zoom back, and this with it.
1125
+ canvas.classList.remove("pannable");
1122
1126
  // `output` is created inside the try block below, but we need to reach it
1123
1127
  // from the catch block too, so we can still finalize (and thus flush)
1124
1128
  // whatever got encoded before the error.
@@ -1172,6 +1176,7 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration, pixe
1172
1176
  const startTime = performance.now();
1173
1177
  await output.start();
1174
1178
  infoDiv.innerHTML = "Recording in progress...";
1179
+ showTranscriptViewForSave();
1175
1180
  const frameDuration = 1000 / FPS;
1176
1181
  // Offline loop: draw + push frames (not limited to realtime)
1177
1182
  let frameNumber = 0;
@@ -1284,6 +1289,7 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration, pixe
1284
1289
  applyZoom(currentZoomFactor);
1285
1290
  }
1286
1291
  suspendLiveAnimationLoop = false;
1292
+ endTranscriptViewForSave();
1287
1293
  }
1288
1294
  }
1289
1295
  cancelRecordingButton.addEventListener("click", () => {
@@ -2027,11 +2033,24 @@ function applyLimits() {
2027
2033
  ? `Play “${root.description}” instead: set the play limits to its start and end, and go to its start.`
2028
2034
  : "";
2029
2035
  }
2036
+ /**
2037
+ * Two playhead times this close are the same: {@link playPositionSeconds} shows ⅒ ms.
2038
+ */
2039
+ const PLAYHEAD_TOLERANCE_MS = 0.1;
2040
+ /**
2041
+ * Set when {@link refreshChapters} pulled the playhead back inside a chapter that got shorter.
2042
+ * Durations change on every keystroke, so typing 25000 over 30000 makes the chapter 2 ms long
2043
+ * on the way. If the chapter grows again before the playhead moves, it goes back toward `fromMs`.
2044
+ * Both are in the video's time.
2045
+ */
2046
+ let playheadPulledBack;
2030
2047
  /**
2031
2048
  * Switch the Visual Editor to the root picked in the `<select>`. The play
2032
2049
  * limits follow, unless Keep play limits is checked.
2033
2050
  */
2034
2051
  function updateFromSelect() {
2052
+ // Where the playhead was in another chapter means nothing here.
2053
+ playheadPulledBack = undefined;
2035
2054
  const info = chapterList[select.selectedIndex];
2036
2055
  setRootStartMs(info.start);
2037
2056
  if (keepLimitsCheckbox.checked && limitsShowable) {
@@ -2078,12 +2097,36 @@ playRootBtn.addEventListener("click", () => {
2078
2097
  * playback and the editors alone. When it's gone, this switches roots properly.
2079
2098
  */
2080
2099
  function refreshChapters() {
2100
+ const playheadMs = playheadInVideoMs();
2101
+ // Not moved since the last clamp: aim for where it was before that.
2102
+ if (playheadPulledBack &&
2103
+ Math.abs(playheadMs - playheadPulledBack.toMs) > PLAYHEAD_TOLERANCE_MS) {
2104
+ playheadPulledBack = undefined;
2105
+ }
2106
+ const wantedMs = playheadPulledBack?.fromMs ?? playheadMs;
2107
+ // limitsChapter still has the start and end from before this change.
2108
+ const old = limitsChapter;
2109
+ const wasInside = playheadPulledBack !== undefined ||
2110
+ old === undefined ||
2111
+ (playheadMs >= old.start - PLAYHEAD_TOLERANCE_MS &&
2112
+ playheadMs <= old.end + PLAYHEAD_TOLERANCE_MS);
2081
2113
  if (initChapters()) {
2082
2114
  setRootStartMs(chapterList[select.selectedIndex].start);
2083
2115
  applyLimits();
2084
- // The range clamped itself to the new bounds; show the real position again. The
2085
- // number input stays the source of truth, so a playhead past a shortened end is left
2086
- // for playback to wrap rather than moved here.
2116
+ // A shorter chapter can leave the playhead past its end, showing nothing. Keep it inside
2117
+ // the play limits. sectionEndTime already stops just short of the next chapter's start.
2118
+ // A playhead the user put outside the limits stays there.
2119
+ if (wasInside) {
2120
+ const clampedMs = Math.max(sectionStartTime, Math.min(sectionEndTime, wantedMs));
2121
+ if (Math.abs(clampedMs - playheadMs) > PLAYHEAD_TOLERANCE_MS) {
2122
+ loadPlayPositionSeconds(clampedMs);
2123
+ }
2124
+ playheadPulledBack =
2125
+ clampedMs === wantedMs
2126
+ ? undefined
2127
+ : { fromMs: wantedMs, toMs: clampedMs };
2128
+ }
2129
+ // The range clamped itself to the new bounds; show the real position again.
2087
2130
  loadPlayPositionRange();
2088
2131
  }
2089
2132
  else {
@@ -2117,19 +2160,7 @@ onTranscriptsChange(() => {
2117
2160
  // The transcript as text. It rebuilds itself when the clips or transcripts
2118
2161
  // change, so it needs no calls besides the one in showFrame().
2119
2162
  transcriptView = new TranscriptView({
2120
- clips() {
2121
- const root = currentRoot();
2122
- if (!root)
2123
- return [];
2124
- return soundOwners(root)
2125
- .flatMap(({ owner, startMs }) => (owner.soundClips ?? []).map((clip) => ({
2126
- clip,
2127
- owner,
2128
- startMs: startMs + clip.startMsIntoScene,
2129
- lengthMs: soundClipLengthMs(clip),
2130
- })))
2131
- .sort((a, b) => a.startMs - b.startMs);
2132
- },
2163
+ clips: transcriptViewClips,
2133
2164
  transcript(source) {
2134
2165
  const status = transcriptStatus(source);
2135
2166
  if (!status)
@@ -2163,34 +2194,77 @@ transcriptView = new TranscriptView({
2163
2194
  },
2164
2195
  });
2165
2196
  getById("timelineCanvas", HTMLCanvasElement).after(transcriptView.element);
2166
- {
2167
- const READ_KEY = "transcriptView.on";
2168
- const checkbox = getById("transcriptViewCheckbox", HTMLInputElement);
2169
- const timelineCanvas = getById("timelineCanvas", HTMLCanvasElement);
2170
- const apply = () => {
2171
- transcriptView.hidden = !checkbox.checked;
2172
- // The timeline's CSS sets `display`, which would beat the `hidden` attribute.
2173
- timelineCanvas.style.display = checkbox.checked ? "none" : "";
2174
- if (!checkbox.checked)
2175
- timelineDisplay.redraw();
2176
- };
2197
+ /** The current chapter's sound clips, in order of time, for 📖 Text. */
2198
+ function transcriptViewClips() {
2199
+ const root = currentRoot();
2200
+ if (!root)
2201
+ return [];
2202
+ return soundOwners(root)
2203
+ .flatMap(({ owner, startMs }) => (owner.soundClips ?? []).map((clip) => ({
2204
+ clip,
2205
+ owner,
2206
+ startMs: startMs + clip.startMsIntoScene,
2207
+ lengthMs: soundClipLengthMs(clip),
2208
+ })))
2209
+ .sort((a, b) => a.startMs - b.startMs);
2210
+ }
2211
+ // MARK: 📖 Text checkbox
2212
+ const transcriptViewCheckbox = getById("transcriptViewCheckbox", HTMLInputElement);
2213
+ const TRANSCRIPT_VIEW_KEY = "transcriptView.on";
2214
+ /** Show 📖 Text or the timeline, to match the checkbox. */
2215
+ function applyTranscriptViewCheckbox() {
2216
+ const on = transcriptViewCheckbox.checked;
2217
+ transcriptView.hidden = !on;
2218
+ // The timeline's CSS sets `display`, which would beat the `hidden` attribute.
2219
+ getById("timelineCanvas", HTMLCanvasElement).style.display = on ? "none" : "";
2220
+ if (!on)
2221
+ timelineDisplay.redraw();
2222
+ }
2223
+ /**
2224
+ * True while a save has switched to 📖 Text, and the user hasn't touched the checkbox since.
2225
+ * Then the save switches back when it's done.
2226
+ */
2227
+ let transcriptViewJustForSave = false;
2228
+ /**
2229
+ * A save shows 📖 Text by default, so you can read along while it records.
2230
+ * Only when there's something to read: transcripts are on, and the chapter has sound.
2231
+ */
2232
+ function showTranscriptViewForSave() {
2233
+ if (transcriptViewCheckbox.checked)
2234
+ return;
2235
+ if (!transcriptsEnabled() || transcriptViewClips().length === 0)
2236
+ return;
2237
+ transcriptViewCheckbox.checked = true;
2238
+ transcriptViewJustForSave = true;
2239
+ applyTranscriptViewCheckbox();
2240
+ }
2241
+ /** The save is over. Go back to the timeline, unless the user chose since. */
2242
+ function endTranscriptViewForSave() {
2243
+ if (!transcriptViewJustForSave)
2244
+ return;
2245
+ transcriptViewJustForSave = false;
2246
+ transcriptViewCheckbox.checked = false;
2247
+ applyTranscriptViewCheckbox();
2248
+ }
2249
+ try {
2250
+ transcriptViewCheckbox.checked =
2251
+ localStorage.getItem(TRANSCRIPT_VIEW_KEY) === "true";
2252
+ }
2253
+ catch {
2254
+ // Remembering is only a convenience.
2255
+ }
2256
+ transcriptViewCheckbox.addEventListener("input", () => {
2257
+ // The user's choice, so a save won't change it back, and it's remembered.
2258
+ transcriptViewJustForSave = false;
2177
2259
  try {
2178
- checkbox.checked = localStorage.getItem(READ_KEY) === "true";
2260
+ localStorage.setItem(TRANSCRIPT_VIEW_KEY, String(transcriptViewCheckbox.checked));
2179
2261
  }
2180
2262
  catch {
2181
- // Remembering is only a convenience.
2263
+ // See above.
2182
2264
  }
2183
- checkbox.addEventListener("input", () => {
2184
- try {
2185
- localStorage.setItem(READ_KEY, String(checkbox.checked));
2186
- }
2187
- catch {
2188
- // See above.
2189
- }
2190
- apply();
2191
- });
2192
- apply();
2193
- }
2265
+ applyTranscriptViewCheckbox();
2266
+ });
2267
+ applyTranscriptViewCheckbox();
2194
2268
  timelineDisplay.onSeek = (localMs) => {
2195
2269
  stopAudio();
2196
2270
  loadPlayPositionSeconds(localMs + rootStartMs);
@@ -3411,6 +3485,8 @@ async function initFromDB(unloadBackup) {
3411
3485
  }
3412
3486
  _loadSource = source;
3413
3487
  _baselineTreeJson = currentTreeJson();
3488
+ // The unload backup is in the database now, or older than it. See the end of "Load previous state".
3489
+ sessionStorage.removeItem("pendingScheduleSave");
3414
3490
  canvas.style.visibility = "";
3415
3491
  canvasLoading.style.display = "none";
3416
3492
  const currentSel = currentRoot();
@@ -3517,6 +3593,12 @@ function currentSaveTarget() {
3517
3593
  return selectable.schedules?.length ? selectable : null;
3518
3594
  }
3519
3595
  function saveOnUnload() {
3596
+ // Still starting up: the live tree is the TypeScript defaults, not the user's work.
3597
+ // A backup of it would be newer than the real state, so the next startup would load it,
3598
+ // and everything made in the Visual Editor would disappear. The last session's backup,
3599
+ // if there was one, is still in sessionStorage until initFromDB() has saved it.
3600
+ if (_loadSource === undefined)
3601
+ return;
3520
3602
  // When the history dialog is open the live tree may hold a transient preview from
3521
3603
  // _dialogSelectItem. Back up the pre-dialog state instead, so a preview is never
3522
3604
  // persisted as if the user had accepted it.
@@ -6773,6 +6855,16 @@ function applyMarkerDrag(localX, localY, shiftKey = false) {
6773
6855
  }
6774
6856
  finally {
6775
6857
  sessionStorage.clear();
6858
+ // Keep the unload backup until initFromDB() has saved it. If the page reloads before
6859
+ // then, saveOnUnload() saves nothing, so this is the only copy.
6860
+ if (unloadBackup !== null) {
6861
+ try {
6862
+ sessionStorage.setItem("pendingScheduleSave", unloadBackup);
6863
+ }
6864
+ catch {
6865
+ // It fit a moment ago.
6866
+ }
6867
+ }
6776
6868
  }
6777
6869
  }
6778
6870
  // MARK: User interactions with the canvas.