canvas-recorder-lib 0.8.3 → 0.8.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.
Files changed (242) hide show
  1. package/README.md +10 -2
  2. package/dev/canvas-recorder.css +14 -0
  3. package/dev/canvas-recorder.ts +379 -45
  4. package/dev/color-picker.ts +13 -0
  5. package/dev/component-picker.ts +60 -11
  6. package/dev/font-widgets.ts +2 -2
  7. package/dev/format-editor.ts +3 -1
  8. package/dev/fourier-panel.ts +7 -3
  9. package/dev/handwriting-panel.ts +7 -7
  10. package/dev/multi-text-dialog.ts +28 -15
  11. package/dev/player-body.ts +75 -30
  12. package/dev/schedule-helpers.ts +10 -3
  13. package/dev/static-image-panel.ts +4 -4
  14. package/dev/subtitles.ts +170 -0
  15. package/dev/synced-file.ts +34 -0
  16. package/dev/timeline-display.ts +1 -1
  17. package/dev/transcript-align.ts +4 -1
  18. package/dev/transcript-editor.ts +1187 -0
  19. package/dev/transcript-export.ts +90 -0
  20. package/dev/transcript-view.ts +8 -5
  21. package/dev/transcripts.ts +140 -15
  22. package/dev/video-clip-panel.ts +4 -4
  23. package/dist/dev/canvas-recorder.css +14 -0
  24. package/dist/dev/canvas-recorder.js +304 -39
  25. package/dist/dev/canvas-recorder.js.map +1 -1
  26. package/dist/dev/color-picker.d.ts.map +1 -1
  27. package/dist/dev/color-picker.js +15 -0
  28. package/dist/dev/color-picker.js.map +1 -1
  29. package/dist/dev/component-picker.d.ts +2 -1
  30. package/dist/dev/component-picker.d.ts.map +1 -1
  31. package/dist/dev/component-picker.js +56 -11
  32. package/dist/dev/component-picker.js.map +1 -1
  33. package/dist/dev/font-widgets.d.ts +2 -2
  34. package/dist/dev/font-widgets.d.ts.map +1 -1
  35. package/dist/dev/font-widgets.js.map +1 -1
  36. package/dist/dev/format-editor.d.ts.map +1 -1
  37. package/dist/dev/format-editor.js +3 -1
  38. package/dist/dev/format-editor.js.map +1 -1
  39. package/dist/dev/fourier-panel.d.ts.map +1 -1
  40. package/dist/dev/fourier-panel.js +4 -3
  41. package/dist/dev/fourier-panel.js.map +1 -1
  42. package/dist/dev/handwriting-panel.d.ts +4 -4
  43. package/dist/dev/handwriting-panel.d.ts.map +1 -1
  44. package/dist/dev/handwriting-panel.js.map +1 -1
  45. package/dist/dev/multi-text-dialog.d.ts.map +1 -1
  46. package/dist/dev/multi-text-dialog.js +23 -12
  47. package/dist/dev/multi-text-dialog.js.map +1 -1
  48. package/dist/dev/player-body.d.ts +1 -1
  49. package/dist/dev/player-body.d.ts.map +1 -1
  50. package/dist/dev/player-body.js +75 -30
  51. package/dist/dev/player-body.js.map +1 -1
  52. package/dist/dev/schedule-helpers.d.ts.map +1 -1
  53. package/dist/dev/schedule-helpers.js +4 -2
  54. package/dist/dev/schedule-helpers.js.map +1 -1
  55. package/dist/dev/static-image-panel.d.ts +3 -3
  56. package/dist/dev/static-image-panel.d.ts.map +1 -1
  57. package/dist/dev/subtitles.d.ts +36 -0
  58. package/dist/dev/subtitles.d.ts.map +1 -0
  59. package/dist/dev/subtitles.js +135 -0
  60. package/dist/dev/subtitles.js.map +1 -0
  61. package/dist/dev/synced-file.d.ts +14 -0
  62. package/dist/dev/synced-file.d.ts.map +1 -1
  63. package/dist/dev/synced-file.js +22 -0
  64. package/dist/dev/synced-file.js.map +1 -1
  65. package/dist/dev/timeline-display.d.ts +5 -0
  66. package/dist/dev/timeline-display.d.ts.map +1 -1
  67. package/dist/dev/timeline-display.js +1 -1
  68. package/dist/dev/timeline-display.js.map +1 -1
  69. package/dist/dev/transcript-align.d.ts +3 -1
  70. package/dist/dev/transcript-align.d.ts.map +1 -1
  71. package/dist/dev/transcript-align.js +2 -0
  72. package/dist/dev/transcript-align.js.map +1 -1
  73. package/dist/dev/transcript-editor.d.ts +36 -0
  74. package/dist/dev/transcript-editor.d.ts.map +1 -0
  75. package/dist/dev/transcript-editor.js +948 -0
  76. package/dist/dev/transcript-editor.js.map +1 -0
  77. package/dist/dev/transcript-export.d.ts +21 -0
  78. package/dist/dev/transcript-export.d.ts.map +1 -1
  79. package/dist/dev/transcript-export.js +65 -0
  80. package/dist/dev/transcript-export.js.map +1 -1
  81. package/dist/dev/transcript-view.d.ts +2 -0
  82. package/dist/dev/transcript-view.d.ts.map +1 -1
  83. package/dist/dev/transcript-view.js +1 -1
  84. package/dist/dev/transcript-view.js.map +1 -1
  85. package/dist/dev/transcripts.d.ts +18 -1
  86. package/dist/dev/transcripts.d.ts.map +1 -1
  87. package/dist/dev/transcripts.js +102 -12
  88. package/dist/dev/transcripts.js.map +1 -1
  89. package/dist/dev/video-clip-panel.d.ts +3 -3
  90. package/dist/dev/video-clip-panel.d.ts.map +1 -1
  91. package/dist/lib/index.d.ts +1 -0
  92. package/dist/lib/index.d.ts.map +1 -1
  93. package/dist/lib/index.js +1 -0
  94. package/dist/lib/index.js.map +1 -1
  95. package/dist/src/glib/line-font.d.ts +6 -0
  96. package/dist/src/glib/line-font.d.ts.map +1 -1
  97. package/dist/src/glib/line-font.js +9 -0
  98. package/dist/src/glib/line-font.js.map +1 -1
  99. package/dist/src/glib/path-shape.d.ts +16 -0
  100. package/dist/src/glib/path-shape.d.ts.map +1 -1
  101. package/dist/src/glib/path-shape.js +23 -0
  102. package/dist/src/glib/path-shape.js.map +1 -1
  103. package/dist/src/glib/transforms.d.ts +9 -0
  104. package/dist/src/glib/transforms.d.ts.map +1 -1
  105. package/dist/src/glib/transforms.js +7 -4
  106. package/dist/src/glib/transforms.js.map +1 -1
  107. package/dist/src/interpolate.d.ts +17 -10
  108. package/dist/src/interpolate.d.ts.map +1 -1
  109. package/dist/src/interpolate.js +1 -17
  110. package/dist/src/interpolate.js.map +1 -1
  111. package/dist/src/morph-animation.js +1 -1
  112. package/dist/src/morph-animation.js.map +1 -1
  113. package/dist/src/peano-fourier/fourier-shared.d.ts.map +1 -1
  114. package/dist/src/peano-fourier/fourier-shared.js +4 -2
  115. package/dist/src/peano-fourier/fourier-shared.js.map +1 -1
  116. package/dist/src/schedule-helper.d.ts +50 -28
  117. package/dist/src/schedule-helper.d.ts.map +1 -1
  118. package/dist/src/schedule-helper.js +22 -0
  119. package/dist/src/schedule-helper.js.map +1 -1
  120. package/dist/src/showable.d.ts +57 -10
  121. package/dist/src/showable.d.ts.map +1 -1
  122. package/dist/src/showable.js +19 -0
  123. package/dist/src/showable.js.map +1 -1
  124. package/dist/src/slide-components/arrow.d.ts +4 -4
  125. package/dist/src/slide-components/arrow.d.ts.map +1 -1
  126. package/dist/src/slide-components/cross-fade-transition.d.ts +2 -1
  127. package/dist/src/slide-components/cross-fade-transition.d.ts.map +1 -1
  128. package/dist/src/slide-components/cross-fade-transition.js +2 -1
  129. package/dist/src/slide-components/cross-fade-transition.js.map +1 -1
  130. package/dist/src/slide-components/duration-agnostic.d.ts +3 -2
  131. package/dist/src/slide-components/duration-agnostic.d.ts.map +1 -1
  132. package/dist/src/slide-components/duration-agnostic.js +4 -2
  133. package/dist/src/slide-components/duration-agnostic.js.map +1 -1
  134. package/dist/src/slide-components/fixed-duration.d.ts +3 -1
  135. package/dist/src/slide-components/fixed-duration.d.ts.map +1 -1
  136. package/dist/src/slide-components/fixed-duration.js +4 -2
  137. package/dist/src/slide-components/fixed-duration.js.map +1 -1
  138. package/dist/src/slide-components/fourier.d.ts +19 -12
  139. package/dist/src/slide-components/fourier.d.ts.map +1 -1
  140. package/dist/src/slide-components/fourier.js +70 -22
  141. package/dist/src/slide-components/fourier.js.map +1 -1
  142. package/dist/src/slide-components/function-graph.d.ts +4 -3
  143. package/dist/src/slide-components/function-graph.d.ts.map +1 -1
  144. package/dist/src/slide-components/function-graph.js +6 -2
  145. package/dist/src/slide-components/function-graph.js.map +1 -1
  146. package/dist/src/slide-components/halftone-shadow.d.ts +8 -7
  147. package/dist/src/slide-components/halftone-shadow.d.ts.map +1 -1
  148. package/dist/src/slide-components/halftone-shadow.js +2 -1
  149. package/dist/src/slide-components/halftone-shadow.js.map +1 -1
  150. package/dist/src/slide-components/handwriting-effect.d.ts +8 -6
  151. package/dist/src/slide-components/handwriting-effect.d.ts.map +1 -1
  152. package/dist/src/slide-components/handwriting-effect.js +4 -2
  153. package/dist/src/slide-components/handwriting-effect.js.map +1 -1
  154. package/dist/src/slide-components/hold.d.ts +4 -2
  155. package/dist/src/slide-components/hold.d.ts.map +1 -1
  156. package/dist/src/slide-components/hold.js +4 -2
  157. package/dist/src/slide-components/hold.js.map +1 -1
  158. package/dist/src/slide-components/image.d.ts +7 -7
  159. package/dist/src/slide-components/image.d.ts.map +1 -1
  160. package/dist/src/slide-components/image.js +4 -2
  161. package/dist/src/slide-components/image.js.map +1 -1
  162. package/dist/src/slide-components/in-parallel.d.ts +6 -3
  163. package/dist/src/slide-components/in-parallel.d.ts.map +1 -1
  164. package/dist/src/slide-components/in-parallel.js +12 -2
  165. package/dist/src/slide-components/in-parallel.js.map +1 -1
  166. package/dist/src/slide-components/in-series.d.ts +2 -1
  167. package/dist/src/slide-components/in-series.d.ts.map +1 -1
  168. package/dist/src/slide-components/in-series.js +2 -1
  169. package/dist/src/slide-components/in-series.js.map +1 -1
  170. package/dist/src/slide-components/live-duration.d.ts +3 -1
  171. package/dist/src/slide-components/live-duration.d.ts.map +1 -1
  172. package/dist/src/slide-components/live-duration.js +4 -2
  173. package/dist/src/slide-components/live-duration.js.map +1 -1
  174. package/dist/src/slide-components/multi-text.d.ts +39 -26
  175. package/dist/src/slide-components/multi-text.d.ts.map +1 -1
  176. package/dist/src/slide-components/multi-text.js +44 -29
  177. package/dist/src/slide-components/multi-text.js.map +1 -1
  178. package/dist/src/slide-components/rectangle.d.ts +5 -4
  179. package/dist/src/slide-components/rectangle.d.ts.map +1 -1
  180. package/dist/src/slide-components/rectangle.js +2 -1
  181. package/dist/src/slide-components/rectangle.js.map +1 -1
  182. package/dist/src/slide-components/registry.d.ts +5 -0
  183. package/dist/src/slide-components/registry.d.ts.map +1 -1
  184. package/dist/src/slide-components/registry.js +28 -27
  185. package/dist/src/slide-components/registry.js.map +1 -1
  186. package/dist/src/slide-components/show-error.d.ts.map +1 -1
  187. package/dist/src/slide-components/show-error.js +3 -2
  188. package/dist/src/slide-components/show-error.js.map +1 -1
  189. package/dist/src/slide-components/simple-text.d.ts +11 -10
  190. package/dist/src/slide-components/simple-text.d.ts.map +1 -1
  191. package/dist/src/slide-components/simple-text.js +5 -3
  192. package/dist/src/slide-components/simple-text.js.map +1 -1
  193. package/dist/src/slide-components/slide-component.d.ts +14 -13
  194. package/dist/src/slide-components/slide-component.d.ts.map +1 -1
  195. package/dist/src/slide-components/slide-component.js +2 -1
  196. package/dist/src/slide-components/slide-component.js.map +1 -1
  197. package/dist/src/slide-components/slide-left.d.ts +2 -1
  198. package/dist/src/slide-components/slide-left.d.ts.map +1 -1
  199. package/dist/src/slide-components/slide-left.js +2 -1
  200. package/dist/src/slide-components/slide-left.js.map +1 -1
  201. package/dist/src/slide-components/text-effect.d.ts +9 -1
  202. package/dist/src/slide-components/text-effect.d.ts.map +1 -1
  203. package/dist/src/slide-components/text-effect.js.map +1 -1
  204. package/dist/src/slide-components/traditional-text.d.ts +8 -8
  205. package/dist/src/slide-components/traditional-text.d.ts.map +1 -1
  206. package/dist/src/slide-components/video-clip.d.ts +4 -3
  207. package/dist/src/slide-components/video-clip.d.ts.map +1 -1
  208. package/dist/src/slide-components/video-clip.js +2 -1
  209. package/dist/src/slide-components/video-clip.js.map +1 -1
  210. package/lib/index.ts +1 -0
  211. package/package.json +2 -2
  212. package/src/glib/line-font.ts +9 -0
  213. package/src/glib/path-shape.ts +35 -0
  214. package/src/glib/transforms.ts +7 -4
  215. package/src/interpolate.ts +18 -27
  216. package/src/morph-animation.ts +1 -1
  217. package/src/peano-fourier/fourier-shared.ts +4 -2
  218. package/src/schedule-helper.ts +50 -28
  219. package/src/showable.ts +79 -10
  220. package/src/slide-components/arrow.ts +4 -4
  221. package/src/slide-components/cross-fade-transition.ts +9 -2
  222. package/src/slide-components/duration-agnostic.ts +4 -3
  223. package/src/slide-components/fixed-duration.ts +4 -2
  224. package/src/slide-components/fourier.ts +89 -32
  225. package/src/slide-components/function-graph.ts +7 -3
  226. package/src/slide-components/halftone-shadow.ts +9 -7
  227. package/src/slide-components/handwriting-effect.ts +8 -6
  228. package/src/slide-components/hold.ts +18 -4
  229. package/src/slide-components/image.ts +9 -7
  230. package/src/slide-components/in-parallel.ts +16 -1
  231. package/src/slide-components/in-series.ts +3 -1
  232. package/src/slide-components/live-duration.ts +4 -2
  233. package/src/slide-components/multi-text.ts +71 -44
  234. package/src/slide-components/rectangle.ts +6 -4
  235. package/src/slide-components/registry.ts +33 -27
  236. package/src/slide-components/show-error.ts +4 -2
  237. package/src/slide-components/simple-text.ts +22 -12
  238. package/src/slide-components/slide-component.ts +15 -13
  239. package/src/slide-components/slide-left.ts +9 -2
  240. package/src/slide-components/text-effect.ts +9 -0
  241. package/src/slide-components/traditional-text.ts +8 -8
  242. package/src/slide-components/video-clip.ts +5 -3
@@ -0,0 +1,1187 @@
1
+ import { WORD_FLAG_COLORS } from "./timeline-display.ts";
2
+ import { type TranscriptWord, wordFlag } from "./transcript-align.ts";
3
+
4
+ /**
5
+ * ✎ Edit Transcript: fix the words of one sound file's transcript, and their times.
6
+ *
7
+ * The file is shown in rows, like the timeline: the sound's waveform, with each word under
8
+ * it. The words alternate between two lanes, so a short word still has room for its label.
9
+ *
10
+ * Every change is made right away, and the timeline, 📖 Text and the subtitles follow.
11
+ * Revert puts back the words as they were when the dialog opened. See "Dialogs with live
12
+ * changes" in CLAUDE.md, and "Transcript Editor" in development-plans/saturday-afternoon.md.
13
+ */
14
+
15
+ /** What the dialog needs from the Visual Editor. It never reaches into canvas-recorder.ts directly. */
16
+ export type TranscriptEditorHooks = {
17
+ /** The sound file's URL. */
18
+ readonly source: string;
19
+ /** The file's words right now, or undefined if its transcript isn't ready. */
20
+ readonly words: () => readonly TranscriptWord[] | undefined;
21
+ /** Replace the file's words. Everything that shows the transcript follows. */
22
+ readonly setWords: (words: readonly TranscriptWord[]) => void;
23
+ /** The file's sound, decoded, or null if it isn't ready. */
24
+ readonly audio: () => AudioBuffer | null;
25
+ /** The parts of the file the video plays, in the file's time. The rest is shaded. */
26
+ readonly used: readonly { readonly fromMs: number; readonly toMs: number }[];
27
+ /** Start with the word at this time selected, in the file's time. */
28
+ readonly startAtMs: number;
29
+ /** Stop the video, so two things don't play at once. */
30
+ readonly pausePlayer: () => void;
31
+ /** The dialog closed. */
32
+ readonly closed: () => void;
33
+ };
34
+
35
+ // MARK: Sizes and colors
36
+
37
+ /** In CSS px. */
38
+ const WAVE_HEIGHT = 56;
39
+ const LANE_HEIGHT = 18;
40
+ const ROW_HEIGHT = WAVE_HEIGHT + 2 * LANE_HEIGHT;
41
+ const ROW_GAP = 8;
42
+ /** How close to an edge of the selected word a click grabs it, in CSS px. */
43
+ const EDGE_GRAB_PX = 6;
44
+ /** No word is shorter than this. */
45
+ const MIN_WORD_MS = 20;
46
+ /** A new word's length, when there's room. */
47
+ const NEW_WORD_MS = 400;
48
+ const FONT = "12px sans-serif";
49
+
50
+ const SELECTED_COLOR = "#1a73e8";
51
+ const EDITED_COLOR = "#2e7d32";
52
+ const PLAIN_COLOR = "#555";
53
+
54
+ // MARK: Words
55
+
56
+ /** How a word is labeled. Speech Whisper left out is in [brackets], as everywhere else. */
57
+ function labelOf(word: TranscriptWord): string {
58
+ if (word.text.trim() === "") return "␣";
59
+ return word.timing === "letters" ? `[${word.text}]` : word.text;
60
+ }
61
+
62
+ /** `word` with new times. Its cut points stay outside it. */
63
+ function retimed(
64
+ word: TranscriptWord,
65
+ startMs: number,
66
+ endMs: number,
67
+ ): TranscriptWord {
68
+ return {
69
+ ...word,
70
+ startMs,
71
+ endMs,
72
+ cutBeforeMs: Math.min(word.cutBeforeMs, startMs),
73
+ cutAfterMs: Math.max(word.cutAfterMs, endMs),
74
+ timing: "edited",
75
+ };
76
+ }
77
+
78
+ /** A word nobody heard: typed into a gap. */
79
+ function newWord(startMs: number, endMs: number): TranscriptWord {
80
+ return {
81
+ text: "",
82
+ startMs,
83
+ endMs,
84
+ cutBeforeMs: startMs,
85
+ cutAfterMs: endMs,
86
+ timing: "edited",
87
+ confidence: 1,
88
+ heard: "",
89
+ };
90
+ }
91
+
92
+ /** One word into several, sharing its time in proportion to their lengths. */
93
+ function splitWord(
94
+ word: TranscriptWord,
95
+ parts: readonly string[],
96
+ ): TranscriptWord[] {
97
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
98
+ const spanMs = word.endMs - word.startMs;
99
+ let startMs = word.startMs;
100
+ return parts.map((text, k) => {
101
+ const last = k === parts.length - 1;
102
+ const endMs = last
103
+ ? word.endMs
104
+ : startMs + (spanMs * text.length) / Math.max(1, total);
105
+ const piece: TranscriptWord = {
106
+ ...word,
107
+ text,
108
+ startMs,
109
+ endMs,
110
+ cutBeforeMs: k === 0 ? word.cutBeforeMs : startMs,
111
+ cutAfterMs: last ? word.cutAfterMs : endMs,
112
+ timing: "edited",
113
+ heard: k === 0 ? word.heard : "",
114
+ };
115
+ startMs = endMs;
116
+ return piece;
117
+ });
118
+ }
119
+
120
+ /** 83 456 ms → "1:23.5" */
121
+ function formatTime(ms: number): string {
122
+ const tenths = Math.round(Math.max(0, ms) / 100);
123
+ const minutes = Math.floor(tenths / 600);
124
+ const seconds = (tenths % 600) / 10;
125
+ return `${minutes}:${seconds.toFixed(1).padStart(4, "0")}`;
126
+ }
127
+
128
+ /** `text`, cut short with "…" to fit in `width` px, or "" if not even that fits. */
129
+ function fitText(
130
+ context: CanvasRenderingContext2D,
131
+ text: string,
132
+ width: number,
133
+ ): string {
134
+ if (context.measureText(text).width <= width) return text;
135
+ for (let length = text.length - 1; length > 0; length--) {
136
+ const shorter = text.slice(0, length) + "…";
137
+ if (context.measureText(shorter).width <= width) return shorter;
138
+ }
139
+ return "";
140
+ }
141
+
142
+ // MARK: The dialog
143
+
144
+ /** Open the editor. Does nothing if the transcript isn't ready. */
145
+ export function openTranscriptEditor(hooks: TranscriptEditorHooks): void {
146
+ const original = hooks.words();
147
+ if (!original) return;
148
+ let words: TranscriptWord[] = [...original];
149
+ /** Index into {@link words}. */
150
+ let selected: number | undefined;
151
+ /** Where ▶ Play starts when no word is selected, in the file's time. */
152
+ let cursorMs = hooks.startAtMs;
153
+ /** How much of the file each row shows. */
154
+ let rowMs = 4000;
155
+ /** The text box changed since this word was selected, so it needs {@link commitText}. */
156
+ let textTouched = false;
157
+ const used = [...hooks.used].sort((a, b) => a.fromMs - b.fromMs);
158
+ const measure = document.createElement("canvas").getContext("2d")!;
159
+ measure.font = FONT;
160
+
161
+ const totalMs = () => {
162
+ const audio = hooks.audio();
163
+ return Math.max(
164
+ audio ? audio.duration * 1000 : 0,
165
+ words.at(-1)?.endMs ?? 0,
166
+ 1000,
167
+ );
168
+ };
169
+
170
+ // MARK: Layout
171
+
172
+ const element = <K extends keyof HTMLElementTagNameMap>(
173
+ tag: K,
174
+ css = "",
175
+ text = "",
176
+ ): HTMLElementTagNameMap[K] => {
177
+ const result = document.createElement(tag);
178
+ result.style.cssText = css;
179
+ result.textContent = text;
180
+ return result;
181
+ };
182
+ const button = (label: string, title: string, action: () => void) => {
183
+ const result = element("button", "", label);
184
+ result.type = "button";
185
+ result.title = title;
186
+ result.addEventListener("click", action);
187
+ return result;
188
+ };
189
+
190
+ const dialog = element(
191
+ "dialog",
192
+ "width:min(96vw,1800px);max-width:none;height:90vh;max-height:none;padding:0;border:1px solid #999;display:flex;flex-direction:column;overflow:hidden",
193
+ );
194
+
195
+ const top = element(
196
+ "div",
197
+ "padding:0.5em 0.8em;background:#f4f4f4;border-bottom:1px solid #ccc;flex-shrink:0",
198
+ );
199
+ const fileName = decodeURIComponent(
200
+ hooks.source.split("/").pop() ?? hooks.source,
201
+ );
202
+ const heading = element(
203
+ "h3",
204
+ "margin:0 0 0.2em 0",
205
+ `✎ Transcript: ${fileName}`,
206
+ );
207
+ const hint = element(
208
+ "div",
209
+ "font-size:0.85em;color:#555",
210
+ "Click a word to hear it. Double-click it, or press Enter, to type a fix: a space makes two words, and an empty word is deleted. " +
211
+ "Drag the blue edges to change when it's said. Double-click an empty spot to add a word. " +
212
+ "↑ ↓ move between words, Enter in the text goes to the next one, Space or ⌥Space plays. The darker sound isn't used in this video.",
213
+ );
214
+
215
+ const toolbar = element(
216
+ "div",
217
+ "display:flex;gap:0.5em;align-items:center;flex-wrap:wrap;margin-top:0.4em",
218
+ );
219
+ const rowSelect = element("select");
220
+ for (const seconds of [2, 4, 8, 16, 32]) {
221
+ const option = element("option", "", `${seconds} s`);
222
+ option.value = String(seconds * 1000);
223
+ rowSelect.append(option);
224
+ }
225
+ rowSelect.value = String(rowMs);
226
+ rowSelect.title =
227
+ "How much sound each row shows. Less gives words more room.";
228
+ const rowLabel = element("label", "", "Each row: ");
229
+ rowLabel.append(rowSelect);
230
+ const playBtn = button(
231
+ "▶ Play",
232
+ "Play from the selected word, or from where you clicked, until you stop it. ⌥Space.",
233
+ () => togglePlay(),
234
+ );
235
+ const nextFlaggedBtn = button(
236
+ "Next flagged ⏭",
237
+ "Go to the next red or orange word, and play it.",
238
+ () => goToNextFlagged(),
239
+ );
240
+ const counts = element("span", "font-size:0.85em;color:#555");
241
+ toolbar.append(rowLabel, playBtn, nextFlaggedBtn, counts);
242
+
243
+ const wordBar = element(
244
+ "div",
245
+ "display:flex;gap:0.4em;align-items:center;flex-wrap:wrap;margin-top:0.4em",
246
+ );
247
+ const previousBtn = button("↑", "The previous word (↑).", () => step(-1));
248
+ const nextBtn = button("↓", "The next word (↓).", () => step(1));
249
+ const textInput = element("input", "width:16em");
250
+ textInput.type = "text";
251
+ textInput.placeholder = "type the word";
252
+ textInput.title =
253
+ "What was said. A space makes two words. Empty deletes the word.";
254
+ const secondsInput = (title: string) => {
255
+ const input = element("input", "width:6em");
256
+ input.type = "number";
257
+ input.step = "0.01";
258
+ input.min = "0";
259
+ input.title = title;
260
+ return input;
261
+ };
262
+ const startInput = secondsInput(
263
+ "When the word starts, in seconds from the start of the file.",
264
+ );
265
+ const endInput = secondsInput(
266
+ "When the word ends, in seconds from the start of the file.",
267
+ );
268
+ const playWordBtn = button("▶ Word", "Hear the selected word.", () =>
269
+ playWord(),
270
+ );
271
+ const okBtn = button(
272
+ "✓ OK",
273
+ "This word is right as it is: clear its flag, and go to the next flagged word.",
274
+ () => markOk(),
275
+ );
276
+ const addBtn = button(
277
+ "+ After",
278
+ "Add a word after this one, in the gap if there is one, or else in the second half of this word.",
279
+ () => addAfter(),
280
+ );
281
+ const mergeBtn = button(
282
+ "Merge →",
283
+ "Join this word and the next into one word, with no space. Then fix the text.",
284
+ () => mergeWithNext(),
285
+ );
286
+ const deleteBtn = button("🗑 Delete", "Delete this word.", () =>
287
+ deleteSelected(),
288
+ );
289
+ wordBar.append(
290
+ previousBtn,
291
+ nextBtn,
292
+ element("span", "", "Word:"),
293
+ textInput,
294
+ element("span", "", "Start:"),
295
+ startInput,
296
+ element("span", "", "End:"),
297
+ endInput,
298
+ playWordBtn,
299
+ okBtn,
300
+ addBtn,
301
+ mergeBtn,
302
+ deleteBtn,
303
+ );
304
+ const info = element(
305
+ "div",
306
+ "font-size:0.85em;color:#a06000;min-height:1.2em;margin-top:0.3em",
307
+ );
308
+ top.append(heading, hint, toolbar, wordBar, info);
309
+
310
+ const list = element(
311
+ "div",
312
+ "flex:1;overflow-y:auto;padding:0.5em 0.8em;background:#fff;outline:none",
313
+ );
314
+ // Focusable, so the keys work after a click on the words. See the keydown handler.
315
+ list.tabIndex = -1;
316
+
317
+ const bottom = element(
318
+ "div",
319
+ "display:flex;gap:0.5em;align-items:center;padding:0.5em 0.8em;background:#f4f4f4;border-top:1px solid #ccc;flex-shrink:0",
320
+ );
321
+ const status = element(
322
+ "div",
323
+ "flex:1;font-size:0.85em;color:#555",
324
+ "Every change is made right away. The timeline, 📖 Text and the subtitles follow.",
325
+ );
326
+ const revertBtn = button(
327
+ "Revert",
328
+ "Put back every word the way it was when this opened.",
329
+ () => revert(),
330
+ );
331
+ revertBtn.disabled = true;
332
+ const doneBtn = button(
333
+ "Done",
334
+ "Close. Every change has already been made.",
335
+ () => dialog.close(),
336
+ );
337
+ bottom.append(status, revertBtn, doneBtn);
338
+ dialog.append(top, list, bottom);
339
+
340
+ /** A line that follows the sound while it plays. */
341
+ const playhead = element(
342
+ "div",
343
+ `position:absolute;top:0;width:2px;height:${ROW_HEIGHT}px;background:#e00;pointer-events:none;z-index:1`,
344
+ );
345
+
346
+ // MARK: Rows
347
+
348
+ /**
349
+ * A row's canvases exist only while it's on screen, or nearly. A long file has hundreds
350
+ * of rows, too many canvases to keep.
351
+ */
352
+ type LiveRow = {
353
+ readonly wave: HTMLCanvasElement;
354
+ readonly overlay: HTMLCanvasElement;
355
+ /** In CSS px. */
356
+ readonly width: number;
357
+ };
358
+ let holders: HTMLDivElement[] = [];
359
+ const live = new Map<number, LiveRow>();
360
+ let observer: IntersectionObserver | undefined;
361
+
362
+ const newCanvas = (width: number, height: number) => {
363
+ const canvas = element(
364
+ "canvas",
365
+ `position:absolute;left:0;top:0;width:${width}px;height:${height}px`,
366
+ );
367
+ const dpr = devicePixelRatio || 1;
368
+ canvas.width = Math.round(width * dpr);
369
+ canvas.height = Math.round(height * dpr);
370
+ return canvas;
371
+ };
372
+
373
+ const context = (canvas: HTMLCanvasElement, width: number) => {
374
+ const result = canvas.getContext("2d")!;
375
+ const scale = canvas.width / width;
376
+ result.setTransform(scale, 0, 0, scale, 0, 0);
377
+ return result;
378
+ };
379
+
380
+ function buildRows(): void {
381
+ observer?.disconnect();
382
+ live.clear();
383
+ holders = [];
384
+ const count = Math.max(1, Math.ceil(totalMs() / rowMs));
385
+ const rows: HTMLDivElement[] = [];
386
+ for (let r = 0; r < count; r++) {
387
+ const row = element(
388
+ "div",
389
+ `display:flex;gap:0.5em;height:${ROW_HEIGHT}px;margin-bottom:${ROW_GAP}px`,
390
+ );
391
+ const label = element(
392
+ "div",
393
+ "width:3.5em;flex-shrink:0;font:12px monospace;color:#555;text-align:right",
394
+ formatTime(r * rowMs),
395
+ );
396
+ const holder = element(
397
+ "div",
398
+ `position:relative;flex:1;min-width:0;height:${ROW_HEIGHT}px;background:#eee`,
399
+ );
400
+ holder.dataset.row = String(r);
401
+ row.append(label, holder);
402
+ rows.push(row);
403
+ holders.push(holder);
404
+ }
405
+ list.replaceChildren(...rows);
406
+ observer = new IntersectionObserver(
407
+ (entries) => {
408
+ for (const entry of entries) {
409
+ const r = Number((entry.target as HTMLElement).dataset.row);
410
+ if (entry.isIntersecting) mount(r);
411
+ else unmount(r);
412
+ }
413
+ },
414
+ { root: list, rootMargin: "400px 0px" },
415
+ );
416
+ for (const holder of holders) observer.observe(holder);
417
+ }
418
+
419
+ function mount(r: number): void {
420
+ const holder = holders[r];
421
+ if (!holder || live.has(r)) return;
422
+ const width = holder.clientWidth;
423
+ if (width <= 0) return;
424
+ const wave = newCanvas(width, WAVE_HEIGHT);
425
+ const overlay = newCanvas(width, ROW_HEIGHT);
426
+ overlay.addEventListener("pointerdown", (event) => onPointerDown(event, r));
427
+ overlay.addEventListener("pointermove", (event) => onPointerMove(event, r));
428
+ overlay.addEventListener("pointerup", endDrag);
429
+ overlay.addEventListener("pointercancel", endDrag);
430
+ overlay.addEventListener("dblclick", (event) => onDoubleClick(event, r));
431
+ holder.append(wave, overlay);
432
+ live.set(r, { wave, overlay, width });
433
+ drawWave(r);
434
+ drawOverlay(r);
435
+ }
436
+
437
+ function unmount(r: number): void {
438
+ const row = live.get(r);
439
+ if (!row) return;
440
+ row.wave.remove();
441
+ row.overlay.remove();
442
+ live.delete(r);
443
+ }
444
+
445
+ /** Min / max bars, one per pixel column, like the timeline. */
446
+ function drawWave(r: number): void {
447
+ const row = live.get(r);
448
+ if (!row) return;
449
+ const { wave, width } = row;
450
+ const ctx = context(wave, width);
451
+ ctx.fillStyle = "#3aab3a";
452
+ ctx.fillRect(0, 0, width, WAVE_HEIGHT);
453
+ const audio = hooks.audio();
454
+ if (!audio) {
455
+ ctx.font = `italic ${FONT}`;
456
+ ctx.fillStyle = "#fff";
457
+ ctx.textBaseline = "middle";
458
+ ctx.fillText(
459
+ "The sound isn't loaded, so there's nothing to show or play.",
460
+ 6,
461
+ WAVE_HEIGHT / 2,
462
+ );
463
+ return;
464
+ }
465
+ const data = audio.getChannelData(0);
466
+ const samplesPerMs = audio.sampleRate / 1000;
467
+ const fromMs = r * rowMs;
468
+ const middle = WAVE_HEIGHT / 2;
469
+ const half = WAVE_HEIGHT / 2 - 1;
470
+ ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
471
+ for (let px = 0; px < width; px++) {
472
+ const from = Math.floor((fromMs + (px / width) * rowMs) * samplesPerMs);
473
+ if (from >= data.length) break;
474
+ const to = Math.min(
475
+ data.length,
476
+ Math.max(
477
+ from + 1,
478
+ Math.floor((fromMs + ((px + 1) / width) * rowMs) * samplesPerMs),
479
+ ),
480
+ );
481
+ let low = data[from]!;
482
+ let high = low;
483
+ for (let i = from + 1; i < to; i++) {
484
+ const v = data[i]!;
485
+ if (v < low) low = v;
486
+ else if (v > high) high = v;
487
+ }
488
+ ctx.fillRect(
489
+ px,
490
+ middle - high * half,
491
+ 1,
492
+ Math.max(1, (high - low) * half),
493
+ );
494
+ }
495
+ }
496
+
497
+ /** Everything over the waveform: the shading, the words, the selection. */
498
+ function drawOverlay(r: number): void {
499
+ const row = live.get(r);
500
+ if (!row) return;
501
+ const { overlay, width } = row;
502
+ const ctx = context(overlay, width);
503
+ ctx.clearRect(0, 0, width, ROW_HEIGHT);
504
+ const fromMs = r * rowMs;
505
+ const toMs = fromMs + rowMs;
506
+ const x = (ms: number) => ((ms - fromMs) / rowMs) * width;
507
+
508
+ // The parts of the file this video doesn't play.
509
+ ctx.fillStyle = "rgba(0, 0, 0, 0.45)";
510
+ let shadeFrom = fromMs;
511
+ for (const range of used) {
512
+ if (range.toMs <= shadeFrom) continue;
513
+ if (range.fromMs >= toMs) break;
514
+ if (range.fromMs > shadeFrom) {
515
+ ctx.fillRect(
516
+ x(shadeFrom),
517
+ 0,
518
+ x(range.fromMs) - x(shadeFrom),
519
+ WAVE_HEIGHT,
520
+ );
521
+ }
522
+ shadeFrom = range.toMs;
523
+ }
524
+ if (shadeFrom < toMs) {
525
+ ctx.fillRect(x(shadeFrom), 0, width - x(shadeFrom), WAVE_HEIGHT);
526
+ }
527
+
528
+ ctx.fillStyle = "#2a2a2a";
529
+ ctx.fillRect(0, WAVE_HEIGHT, width, 2 * LANE_HEIGHT);
530
+
531
+ ctx.font = FONT;
532
+ ctx.textBaseline = "middle";
533
+ for (let i = firstWordEndingAfter(fromMs); i < words.length; i++) {
534
+ const word = words[i]!;
535
+ if (word.startMs >= toMs) break;
536
+ const x0 = x(word.startMs);
537
+ const x1 = x(word.endMs);
538
+ const top = WAVE_HEIGHT + (i % 2) * LANE_HEIGHT;
539
+ const flag = wordFlag(word);
540
+ // Where each word starts, on the sound.
541
+ ctx.fillStyle = "rgba(255, 255, 255, 0.6)";
542
+ ctx.fillRect(Math.round(x0), 0, 1, WAVE_HEIGHT);
543
+ ctx.fillStyle =
544
+ i === selected
545
+ ? SELECTED_COLOR
546
+ : flag
547
+ ? WORD_FLAG_COLORS[flag]
548
+ : word.timing === "edited"
549
+ ? EDITED_COLOR
550
+ : PLAIN_COLOR;
551
+ ctx.fillRect(x0, top + 1, Math.max(2, x1 - x0), LANE_HEIGHT - 2);
552
+ // The label can run past its word, up to the next word in the same lane.
553
+ const nextInLane = words[i + 2];
554
+ const limit = Math.min(width, nextInLane ? x(nextInLane.startMs) : width);
555
+ const textX = Math.max(x0, 0) + 3;
556
+ const text = fitText(ctx, labelOf(word), limit - 3 - textX);
557
+ if (text) {
558
+ ctx.fillStyle = "#fff";
559
+ ctx.fillText(text, textX, top + LANE_HEIGHT / 2);
560
+ }
561
+ }
562
+
563
+ const chosen = selected === undefined ? undefined : words[selected];
564
+ if (chosen && chosen.endMs > fromMs && chosen.startMs < toMs) {
565
+ const x0 = x(chosen.startMs);
566
+ const x1 = x(chosen.endMs);
567
+ ctx.fillStyle = "rgba(26, 115, 232, 0.3)";
568
+ ctx.fillRect(x0, 0, x1 - x0, WAVE_HEIGHT);
569
+ // The edges, with handles to drag.
570
+ ctx.fillStyle = SELECTED_COLOR;
571
+ for (const edge of [x0, x1]) {
572
+ ctx.fillRect(edge - 1, 0, 2, ROW_HEIGHT);
573
+ ctx.fillRect(edge - 4, WAVE_HEIGHT / 2 - 9, 8, 18);
574
+ }
575
+ } else if (
576
+ selected === undefined &&
577
+ cursorMs >= fromMs &&
578
+ cursorMs < toMs
579
+ ) {
580
+ ctx.fillStyle = "#ffd400";
581
+ ctx.fillRect(x(cursorMs) - 1, 0, 2, ROW_HEIGHT);
582
+ }
583
+ }
584
+
585
+ function drawAllOverlays(): void {
586
+ for (const r of live.keys()) drawOverlay(r);
587
+ }
588
+
589
+ /** The first word that ends after `ms`, or words.length. */
590
+ function firstWordEndingAfter(ms: number): number {
591
+ let low = 0;
592
+ let high = words.length;
593
+ while (low < high) {
594
+ const middle = (low + high) >> 1;
595
+ if (words[middle]!.endMs > ms) high = middle;
596
+ else low = middle + 1;
597
+ }
598
+ return low;
599
+ }
600
+
601
+ /** Bring the row holding `ms` into view. */
602
+ function reveal(ms: number, block: ScrollLogicalPosition = "nearest"): void {
603
+ const holder = holders[Math.floor(ms / rowMs)];
604
+ holder?.parentElement?.scrollIntoView({ block });
605
+ }
606
+
607
+ // MARK: Changes
608
+
609
+ /** Make a change, everywhere at once. */
610
+ function apply(newWords: TranscriptWord[]): void {
611
+ words = newWords;
612
+ hooks.setWords(words);
613
+ revertBtn.disabled = false;
614
+ drawAllOverlays();
615
+ showCounts();
616
+ }
617
+
618
+ function replaceWord(index: number, word: TranscriptWord): void {
619
+ apply(words.toSpliced(index, 1, word));
620
+ }
621
+
622
+ /**
623
+ * Finish typing in the text box: a space makes several words, and nothing deletes the
624
+ * word. Call before anything that moves the selection.
625
+ * @returns The index of the word after the one that was typed in.
626
+ */
627
+ function commitText(): number | undefined {
628
+ if (selected === undefined) return undefined;
629
+ const index = selected;
630
+ if (!textTouched) return index + 1;
631
+ textTouched = false;
632
+ const word = words[index];
633
+ if (!word) return undefined;
634
+ const parts = word.text.trim().split(/\s+/).filter(Boolean);
635
+ if (parts.length === 0) {
636
+ selected = undefined;
637
+ apply(words.toSpliced(index, 1));
638
+ return index;
639
+ }
640
+ if (parts.length === 1) {
641
+ if (parts[0] !== word.text)
642
+ replaceWord(index, { ...word, text: parts[0]! });
643
+ return index + 1;
644
+ }
645
+ apply(words.toSpliced(index, 1, ...splitWord(word, parts)));
646
+ return index + parts.length;
647
+ }
648
+
649
+ function select(index: number | undefined, focusText = false): void {
650
+ selected =
651
+ index === undefined || words.length === 0
652
+ ? undefined
653
+ : Math.max(0, Math.min(words.length - 1, index));
654
+ textTouched = false;
655
+ showSelected();
656
+ drawAllOverlays();
657
+ if (selected !== undefined) {
658
+ reveal(words[selected]!.startMs);
659
+ if (focusText) {
660
+ textInput.focus();
661
+ textInput.select();
662
+ }
663
+ }
664
+ }
665
+
666
+ /** Move the selection by `delta` words, and play the new one. */
667
+ function step(delta: 1 | -1, focusText = true): void {
668
+ const after = commitText();
669
+ if (selected === undefined && after === undefined) {
670
+ select(firstWordEndingAfter(cursorMs), focusText);
671
+ } else {
672
+ select(delta > 0 ? after : (selected ?? after ?? 0) - 1, focusText);
673
+ }
674
+ playWord();
675
+ }
676
+
677
+ function retimeSelected(startMs: number, endMs: number): void {
678
+ if (selected === undefined) return;
679
+ const word = words[selected]!;
680
+ const previous = words[selected - 1];
681
+ const next = words[selected + 1];
682
+ // Never past a neighbor, unless it was already there.
683
+ const earliest = previous ? Math.min(previous.endMs, word.startMs) : 0;
684
+ const latest = next
685
+ ? Math.max(next.startMs, word.endMs)
686
+ : Math.max(totalMs(), word.endMs);
687
+ const start = Math.round(
688
+ Math.max(earliest, Math.min(startMs, endMs - MIN_WORD_MS)),
689
+ );
690
+ const end = Math.round(
691
+ Math.min(latest, Math.max(endMs, start + MIN_WORD_MS)),
692
+ );
693
+ replaceWord(selected, retimed(word, start, end));
694
+ }
695
+
696
+ function markOk(): void {
697
+ const after = commitText();
698
+ if (selected !== undefined) {
699
+ replaceWord(selected, { ...words[selected]!, timing: "edited" });
700
+ }
701
+ goToNextFlagged(after);
702
+ }
703
+
704
+ function deleteSelected(): void {
705
+ if (selected === undefined) return;
706
+ const index = selected;
707
+ selected = undefined;
708
+ apply(words.toSpliced(index, 1));
709
+ select(Math.min(index, words.length - 1));
710
+ }
711
+
712
+ function addAfter(): void {
713
+ const after = commitText();
714
+ if (selected === undefined || after === undefined) return;
715
+ const index = after - 1;
716
+ const word = words[index]!;
717
+ const next = words[index + 1];
718
+ const gapEnd = next ? next.startMs : totalMs();
719
+ if (gapEnd - word.endMs >= 100) {
720
+ const added = newWord(
721
+ word.endMs,
722
+ Math.min(gapEnd, word.endMs + NEW_WORD_MS),
723
+ );
724
+ apply(words.toSpliced(index + 1, 0, added));
725
+ } else {
726
+ // No room: take the second half of this word.
727
+ const middle = Math.round((word.startMs + word.endMs) / 2);
728
+ const added = newWord(middle, word.endMs);
729
+ apply(
730
+ words.toSpliced(index, 1, retimed(word, word.startMs, middle), added),
731
+ );
732
+ }
733
+ select(index + 1, true);
734
+ }
735
+
736
+ /** A new word where someone double-clicked, if there's room. */
737
+ function addAt(ms: number): void {
738
+ commitText();
739
+ const index = firstWordEndingAfter(ms);
740
+ const previous = words[index - 1];
741
+ const next = words[index];
742
+ if (next && next.startMs <= ms) return; // On a word, not in a gap.
743
+ const startMs = Math.round(Math.max(ms, previous?.endMs ?? 0));
744
+ const endMs = Math.round(
745
+ Math.min(startMs + NEW_WORD_MS, next ? next.startMs : totalMs()),
746
+ );
747
+ if (endMs - startMs < MIN_WORD_MS) return;
748
+ apply(words.toSpliced(index, 0, newWord(startMs, endMs)));
749
+ select(index, true);
750
+ }
751
+
752
+ function mergeWithNext(): void {
753
+ commitText();
754
+ if (selected === undefined) return;
755
+ const index = selected;
756
+ const word = words[index]!;
757
+ const next = words[index + 1];
758
+ if (!next) return;
759
+ const merged: TranscriptWord = {
760
+ ...word,
761
+ text: word.text.trim() + next.text.trim(),
762
+ endMs: Math.max(word.endMs, next.endMs),
763
+ cutAfterMs: Math.max(word.cutAfterMs, next.cutAfterMs),
764
+ timing: "edited",
765
+ confidence: Math.min(word.confidence, next.confidence),
766
+ heard: [word.heard, next.heard].filter(Boolean).join(" "),
767
+ };
768
+ apply(words.toSpliced(index, 2, merged));
769
+ select(index, true);
770
+ }
771
+
772
+ function goToNextFlagged(from?: number): void {
773
+ const start = from ?? (selected ?? firstWordEndingAfter(cursorMs) - 1) + 1;
774
+ for (let k = 0; k < words.length; k++) {
775
+ const index = (start + k) % words.length;
776
+ if (wordFlag(words[index]!)) {
777
+ select(index, true);
778
+ reveal(words[index]!.startMs, "center");
779
+ playWord();
780
+ info.textContent =
781
+ (index < start ? "Back at the start. " : "") + info.textContent;
782
+ return;
783
+ }
784
+ }
785
+ info.textContent = "No flagged words left.";
786
+ }
787
+
788
+ function revert(): void {
789
+ stop();
790
+ selected = undefined;
791
+ textTouched = false;
792
+ apply([...original!]);
793
+ revertBtn.disabled = true;
794
+ showSelected();
795
+ }
796
+
797
+ // MARK: The selected word
798
+
799
+ const seconds = (ms: number) => String(Math.round(ms) / 1000);
800
+
801
+ function showSelected(): void {
802
+ const word = selected === undefined ? undefined : words[selected];
803
+ for (const control of [
804
+ textInput,
805
+ startInput,
806
+ endInput,
807
+ playWordBtn,
808
+ okBtn,
809
+ addBtn,
810
+ mergeBtn,
811
+ deleteBtn,
812
+ ]) {
813
+ control.disabled = !word;
814
+ }
815
+ mergeBtn.disabled = !word || selected === words.length - 1;
816
+ if (!word) {
817
+ textInput.value = "";
818
+ startInput.value = "";
819
+ endInput.value = "";
820
+ info.textContent = words.length
821
+ ? "Click a word to select it."
822
+ : "No words yet. Double-click an empty spot to add one.";
823
+ return;
824
+ }
825
+ textInput.value = word.text;
826
+ startInput.value = seconds(word.startMs);
827
+ endInput.value = seconds(word.endMs);
828
+ const flag = wordFlag(word);
829
+ const notes: string[] = [];
830
+ if (flag === "left out") {
831
+ notes.push(
832
+ "Speech Whisper left out: probably a repeat, a false start or an um. " +
833
+ "It's not in the subtitles unless you fix it or press ✓ OK. Delete it if it's just noise.",
834
+ );
835
+ } else if (flag === "doubtful") {
836
+ notes.push(
837
+ word.heard
838
+ ? `The letter model heard “${word.heard}”. Worth a listen.`
839
+ : "The letter model heard nothing here. Worth a listen.",
840
+ );
841
+ } else if (word.timing === "edited") {
842
+ notes.push("Edited.");
843
+ }
844
+ if (word.timing !== "edited") {
845
+ notes.push(`${Math.round(word.confidence * 100)}% sure.`);
846
+ }
847
+ info.textContent = notes.join(" ");
848
+ }
849
+
850
+ function showCounts(): void {
851
+ const flagged = words.filter((word) => wordFlag(word)).length;
852
+ const edited = words.filter((word) => word.timing === "edited").length;
853
+ counts.textContent = `${words.length} words · ${flagged} flagged · ${edited} edited`;
854
+ }
855
+
856
+ textInput.addEventListener("input", () => {
857
+ if (selected === undefined) return;
858
+ textTouched = true;
859
+ replaceWord(selected, {
860
+ ...words[selected]!,
861
+ text: textInput.value,
862
+ timing: "edited",
863
+ });
864
+ });
865
+ // Clicking elsewhere finishes the word, so a space there makes two words right away.
866
+ textInput.addEventListener("blur", () => {
867
+ if (!textTouched) return;
868
+ commitText();
869
+ showSelected();
870
+ });
871
+
872
+ const onSecondsInput = () => {
873
+ if (selected === undefined) return;
874
+ const word = words[selected]!;
875
+ const start = startInput.valueAsNumber * 1000;
876
+ const end = endInput.valueAsNumber * 1000;
877
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return;
878
+ if (start === word.startMs && end === word.endMs) return;
879
+ retimeSelected(start, end);
880
+ };
881
+ startInput.addEventListener("input", onSecondsInput);
882
+ endInput.addEventListener("input", onSecondsInput);
883
+ // While typing, a number can be out of range for a moment. Afterwards, show what was used.
884
+ for (const input of [startInput, endInput]) {
885
+ input.addEventListener("blur", () => showSelected());
886
+ }
887
+
888
+ // MARK: Mouse
889
+
890
+ let drag:
891
+ | { readonly edge: "start" | "end"; readonly overlay: HTMLCanvasElement }
892
+ | undefined;
893
+
894
+ const where = (event: PointerEvent | MouseEvent, r: number) => {
895
+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
896
+ const x = event.clientX - rect.left;
897
+ return {
898
+ x,
899
+ y: event.clientY - rect.top,
900
+ width: rect.width,
901
+ ms: r * rowMs + (x / rect.width) * rowMs,
902
+ };
903
+ };
904
+
905
+ /** The edge of the selected word under `x`, if any: the closer one. */
906
+ function edgeAt(r: number, x: number, width: number) {
907
+ const word = selected === undefined ? undefined : words[selected];
908
+ if (!word) return undefined;
909
+ const toX = (ms: number) => ((ms - r * rowMs) / rowMs) * width;
910
+ const start = Math.abs(toX(word.startMs) - x);
911
+ const end = Math.abs(toX(word.endMs) - x);
912
+ if (Math.min(start, end) > EDGE_GRAB_PX) return undefined;
913
+ return start <= end ? "start" : "end";
914
+ }
915
+
916
+ /**
917
+ * The word under the mouse. Over the sound, the word being said. Over the words, the word
918
+ * or its label.
919
+ */
920
+ function wordAt(r: number, x: number, y: number, width: number, ms: number) {
921
+ if (y < WAVE_HEIGHT) {
922
+ const index = firstWordEndingAfter(ms);
923
+ const word = words[index];
924
+ return word && word.startMs <= ms ? index : undefined;
925
+ }
926
+ const lane = y < WAVE_HEIGHT + LANE_HEIGHT ? 0 : 1;
927
+ const toX = (t: number) => ((t - r * rowMs) / rowMs) * width;
928
+ // The last word in this lane that starts before the mouse.
929
+ let index = firstWordEndingAfter(ms);
930
+ while (
931
+ index >= 0 &&
932
+ (index % 2 !== lane || (words[index]?.startMs ?? Infinity) > ms)
933
+ ) {
934
+ index--;
935
+ }
936
+ const word = words[index];
937
+ if (!word) return undefined;
938
+ const right = Math.max(
939
+ toX(word.endMs),
940
+ Math.max(toX(word.startMs), 0) +
941
+ 3 +
942
+ measure.measureText(labelOf(word)).width,
943
+ );
944
+ return x <= right ? index : undefined;
945
+ }
946
+
947
+ function onPointerDown(event: PointerEvent, r: number): void {
948
+ if (event.button !== 0) return;
949
+ event.preventDefault();
950
+ // Out of the text box, which finishes the word there, so Space plays and Enter edits.
951
+ list.focus({ preventScroll: true });
952
+ const { x, y, width } = where(event, r);
953
+ const edge = edgeAt(r, x, width);
954
+ if (edge) {
955
+ const overlay = event.currentTarget as HTMLCanvasElement;
956
+ overlay.setPointerCapture(event.pointerId);
957
+ drag = { edge, overlay };
958
+ return;
959
+ }
960
+ commitText();
961
+ const { ms } = where(event, r);
962
+ const index = wordAt(r, x, y, width, ms);
963
+ if (index === undefined) {
964
+ stop();
965
+ cursorMs = ms;
966
+ select(undefined);
967
+ } else {
968
+ select(index);
969
+ playWord();
970
+ }
971
+ }
972
+
973
+ function onPointerMove(event: PointerEvent, r: number): void {
974
+ const { x, y, width, ms } = where(event, r);
975
+ const overlay = event.currentTarget as HTMLCanvasElement;
976
+ if (!drag) {
977
+ overlay.style.cursor = edgeAt(r, x, width)
978
+ ? "ew-resize"
979
+ : wordAt(r, x, y, width, ms) === undefined
980
+ ? "default"
981
+ : "pointer";
982
+ return;
983
+ }
984
+ if (selected === undefined) return;
985
+ const word = words[selected]!;
986
+ if (drag.edge === "start") retimeSelected(ms, word.endMs);
987
+ else retimeSelected(word.startMs, ms);
988
+ showSelected();
989
+ }
990
+
991
+ function endDrag(event: PointerEvent): void {
992
+ if (!drag) return;
993
+ drag.overlay.releasePointerCapture(event.pointerId);
994
+ drag = undefined;
995
+ playWord();
996
+ }
997
+
998
+ function onDoubleClick(event: MouseEvent, r: number): void {
999
+ const { x, y, width, ms } = where(event, r);
1000
+ if (edgeAt(r, x, width)) return;
1001
+ if (wordAt(r, x, y, width, ms) === undefined) {
1002
+ addAt(ms);
1003
+ } else {
1004
+ textInput.focus();
1005
+ textInput.select();
1006
+ }
1007
+ }
1008
+
1009
+ // MARK: Sound
1010
+
1011
+ let audioContext: AudioContext | undefined;
1012
+ let playing:
1013
+ | {
1014
+ readonly node: AudioBufferSourceNode;
1015
+ readonly fromMs: number;
1016
+ readonly startedAt: number;
1017
+ /** Scroll to keep up with it. */
1018
+ readonly follow: boolean;
1019
+ }
1020
+ | undefined;
1021
+
1022
+ function play(fromMs: number, toMs: number, follow: boolean): void {
1023
+ stop();
1024
+ const audio = hooks.audio();
1025
+ if (!audio) return;
1026
+ hooks.pausePlayer();
1027
+ audioContext ??= new AudioContext();
1028
+ void audioContext.resume();
1029
+ const node = audioContext.createBufferSource();
1030
+ node.buffer = audio;
1031
+ node.connect(audioContext.destination);
1032
+ const from = Math.max(0, fromMs);
1033
+ if (Number.isFinite(toMs)) {
1034
+ node.start(0, from / 1000, Math.max(0.01, (toMs - from) / 1000));
1035
+ } else {
1036
+ node.start(0, from / 1000);
1037
+ }
1038
+ const current = {
1039
+ node,
1040
+ fromMs: from,
1041
+ startedAt: audioContext.currentTime,
1042
+ follow,
1043
+ };
1044
+ playing = current;
1045
+ node.addEventListener("ended", () => {
1046
+ if (playing === current) stop();
1047
+ });
1048
+ playBtn.textContent = "■ Stop";
1049
+ requestAnimationFrame(movePlayhead);
1050
+ }
1051
+
1052
+ function stop(): void {
1053
+ if (!playing) return;
1054
+ const { node } = playing;
1055
+ playing = undefined;
1056
+ try {
1057
+ node.stop();
1058
+ } catch {
1059
+ // It already ended.
1060
+ }
1061
+ playhead.remove();
1062
+ playBtn.textContent = "▶ Play";
1063
+ }
1064
+
1065
+ function movePlayhead(): void {
1066
+ if (!playing || !audioContext) return;
1067
+ const ms =
1068
+ playing.fromMs + (audioContext.currentTime - playing.startedAt) * 1000;
1069
+ const r = Math.floor(ms / rowMs);
1070
+ const holder = holders[r];
1071
+ if (holder) {
1072
+ if (playhead.parentElement !== holder) {
1073
+ holder.append(playhead);
1074
+ if (playing.follow) reveal(ms);
1075
+ }
1076
+ playhead.style.left = `${((ms - r * rowMs) / rowMs) * holder.clientWidth - 1}px`;
1077
+ }
1078
+ requestAnimationFrame(movePlayhead);
1079
+ }
1080
+
1081
+ function playWord(): void {
1082
+ const word = selected === undefined ? undefined : words[selected];
1083
+ if (word) play(word.cutBeforeMs, word.cutAfterMs, false);
1084
+ }
1085
+
1086
+ function togglePlay(): void {
1087
+ if (playing) {
1088
+ stop();
1089
+ return;
1090
+ }
1091
+ const word = selected === undefined ? undefined : words[selected];
1092
+ play(word ? word.cutBeforeMs : cursorMs, Infinity, true);
1093
+ }
1094
+
1095
+ // MARK: Keys
1096
+
1097
+ dialog.addEventListener("keydown", (event) => {
1098
+ // The player's own hot keys (⌥Space, ⌥←, Cmd+Z…) mustn't act behind the dialog.
1099
+ event.stopPropagation();
1100
+ const target = event.target;
1101
+ const inText = target === textInput;
1102
+ const inField =
1103
+ target instanceof HTMLInputElement || target instanceof HTMLSelectElement;
1104
+ /**
1105
+ * The word is selected in the text box, as it is after ↑, ↓ or Enter, and nothing typed
1106
+ * yet. Then Space plays, rather than replacing the word with a space.
1107
+ */
1108
+ const untouchedText =
1109
+ inText &&
1110
+ textInput.value !== "" &&
1111
+ textInput.selectionStart === 0 &&
1112
+ textInput.selectionEnd === textInput.value.length;
1113
+ if (event.code === "Space" && (event.altKey || !inField || untouchedText)) {
1114
+ event.preventDefault();
1115
+ togglePlay();
1116
+ } else if (
1117
+ event.key === "Enter" &&
1118
+ !inField &&
1119
+ !(target instanceof HTMLButtonElement) &&
1120
+ selected !== undefined
1121
+ ) {
1122
+ event.preventDefault();
1123
+ textInput.focus();
1124
+ textInput.select();
1125
+ } else if (
1126
+ (event.key === "ArrowDown" || event.key === "ArrowUp") &&
1127
+ (inText || !inField)
1128
+ ) {
1129
+ event.preventDefault();
1130
+ step(event.key === "ArrowDown" ? 1 : -1);
1131
+ } else if (event.key === "Enter" && inText) {
1132
+ event.preventDefault();
1133
+ step(1);
1134
+ } else if (
1135
+ (event.key === "Delete" || event.key === "Backspace") &&
1136
+ !inField
1137
+ ) {
1138
+ event.preventDefault();
1139
+ deleteSelected();
1140
+ }
1141
+ });
1142
+ dialog.addEventListener("keypress", (event) => event.stopPropagation());
1143
+
1144
+ // MARK: Open and close
1145
+
1146
+ rowSelect.addEventListener("input", () => {
1147
+ const keep = selected === undefined ? cursorMs : words[selected]!.startMs;
1148
+ rowMs = Number(rowSelect.value);
1149
+ stop();
1150
+ buildRows();
1151
+ reveal(keep, "center");
1152
+ });
1153
+
1154
+ // The rows' canvases are as wide as the dialog was. Start over when that changes.
1155
+ let lastWidth = 0;
1156
+ const resizeObserver = new ResizeObserver(() => {
1157
+ const width = list.clientWidth;
1158
+ if (width === lastWidth) return;
1159
+ lastWidth = width;
1160
+ for (const r of [...live.keys()]) unmount(r);
1161
+ observer?.disconnect();
1162
+ for (const holder of holders) observer?.observe(holder);
1163
+ });
1164
+
1165
+ // Escape, as well as Done. Every change is already made, so closing is always safe.
1166
+ dialog.addEventListener("close", () => {
1167
+ commitText();
1168
+ stop();
1169
+ void audioContext?.close();
1170
+ observer?.disconnect();
1171
+ resizeObserver.disconnect();
1172
+ dialog.remove();
1173
+ hooks.closed();
1174
+ });
1175
+
1176
+ document.body.append(dialog);
1177
+ dialog.showModal();
1178
+ // Not the first control, which showModal() picks, so the keys work right away.
1179
+ list.focus({ preventScroll: true });
1180
+ buildRows();
1181
+ lastWidth = list.clientWidth;
1182
+ resizeObserver.observe(list);
1183
+ showCounts();
1184
+ const first = firstWordEndingAfter(hooks.startAtMs);
1185
+ select(first < words.length ? first : undefined);
1186
+ reveal(words[selected ?? -1]?.startMs ?? cursorMs, "center");
1187
+ }