@braccato/core 1.21.6 → 2.0.0-beta.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.
Files changed (105) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +202 -600
  3. package/dist/styles/lyrics.css +6 -0
  4. package/dist/util.d.ts +2 -0
  5. package/dist/util.js +4 -0
  6. package/js/element.js +234 -0
  7. package/js/renderer.d.ts +157 -0
  8. package/js/renderer.js +535 -0
  9. package/package.json +22 -17
  10. package/pkg/braccato_core_rs.d.ts +236 -0
  11. package/pkg/braccato_core_rs.js +1735 -0
  12. package/pkg/braccato_core_rs_bg.wasm +0 -0
  13. package/pkg/braccato_core_rs_bg.wasm.d.ts +55 -0
  14. package/dist/LICENSE +0 -21
  15. package/dist/README.md +0 -632
  16. package/dist/element.d.ts +0 -168
  17. package/dist/element.js +0 -730
  18. package/dist/engine/animationConfig.d.ts +0 -84
  19. package/dist/engine/animationConfig.js +0 -95
  20. package/dist/engine/animationDrift.d.ts +0 -11
  21. package/dist/engine/animationDrift.js +0 -43
  22. package/dist/engine/animationTiming.d.ts +0 -27
  23. package/dist/engine/animationTiming.js +0 -145
  24. package/dist/engine/autoScroll.d.ts +0 -24
  25. package/dist/engine/autoScroll.js +0 -103
  26. package/dist/engine/clock.d.ts +0 -29
  27. package/dist/engine/clock.js +0 -70
  28. package/dist/engine/contextSweep.d.ts +0 -10
  29. package/dist/engine/contextSweep.js +0 -102
  30. package/dist/engine/cssValues.d.ts +0 -13
  31. package/dist/engine/cssValues.js +0 -47
  32. package/dist/engine/culling.d.ts +0 -6
  33. package/dist/engine/culling.js +0 -76
  34. package/dist/engine/debugOverlay.d.ts +0 -14
  35. package/dist/engine/debugOverlay.js +0 -58
  36. package/dist/engine/decorationSlides.d.ts +0 -6
  37. package/dist/engine/decorationSlides.js +0 -53
  38. package/dist/engine/elementMotion.d.ts +0 -18
  39. package/dist/engine/elementMotion.js +0 -98
  40. package/dist/engine/glow.d.ts +0 -7
  41. package/dist/engine/glow.js +0 -59
  42. package/dist/engine/instance.d.ts +0 -105
  43. package/dist/engine/instance.js +0 -89
  44. package/dist/engine/instrumentalAnimations.d.ts +0 -7
  45. package/dist/engine/instrumentalAnimations.js +0 -59
  46. package/dist/engine/letterPlans.d.ts +0 -31
  47. package/dist/engine/letterPlans.js +0 -62
  48. package/dist/engine/lineAnimationState.d.ts +0 -10
  49. package/dist/engine/lineAnimationState.js +0 -82
  50. package/dist/engine/lineAnimations.d.ts +0 -5
  51. package/dist/engine/lineAnimations.js +0 -63
  52. package/dist/engine/lineLifecycle.d.ts +0 -12
  53. package/dist/engine/lineLifecycle.js +0 -92
  54. package/dist/engine/lineScroll.d.ts +0 -47
  55. package/dist/engine/lineScroll.js +0 -184
  56. package/dist/engine/lineScrollStyle.d.ts +0 -32
  57. package/dist/engine/lineScrollStyle.js +0 -133
  58. package/dist/engine/liveViews.d.ts +0 -3
  59. package/dist/engine/liveViews.js +0 -5
  60. package/dist/engine/motionCurves.d.ts +0 -19
  61. package/dist/engine/motionCurves.js +0 -85
  62. package/dist/engine/motionPreference.d.ts +0 -1
  63. package/dist/engine/motionPreference.js +0 -1
  64. package/dist/engine/passiveScroll.d.ts +0 -10
  65. package/dist/engine/passiveScroll.js +0 -93
  66. package/dist/engine/renderedLines.d.ts +0 -16
  67. package/dist/engine/renderedLines.js +0 -130
  68. package/dist/engine/scrollViewport.d.ts +0 -36
  69. package/dist/engine/scrollViewport.js +0 -104
  70. package/dist/engine/stageMotion.d.ts +0 -7
  71. package/dist/engine/stageMotion.js +0 -319
  72. package/dist/engine/sweepPlans.d.ts +0 -38
  73. package/dist/engine/sweepPlans.js +0 -66
  74. package/dist/engine/tick.d.ts +0 -16
  75. package/dist/engine/tick.js +0 -270
  76. package/dist/engine/timingLogs.d.ts +0 -7
  77. package/dist/engine/timingLogs.js +0 -81
  78. package/dist/engine/userScroll.d.ts +0 -12
  79. package/dist/engine/userScroll.js +0 -62
  80. package/dist/engine/wavePool.d.ts +0 -7
  81. package/dist/engine/wavePool.js +0 -22
  82. package/dist/engine/wordAnimations.d.ts +0 -5
  83. package/dist/engine/wordAnimations.js +0 -206
  84. package/dist/imageHighlights.d.ts +0 -4
  85. package/dist/imageHighlights.js +0 -34
  86. package/dist/index.d.ts +0 -17
  87. package/dist/index.js +0 -12
  88. package/dist/inject.d.ts +0 -98
  89. package/dist/inject.js +0 -591
  90. package/dist/instrumental.d.ts +0 -11
  91. package/dist/instrumental.js +0 -121
  92. package/dist/language.d.ts +0 -9
  93. package/dist/language.js +0 -47
  94. package/dist/letters.d.ts +0 -2
  95. package/dist/letters.js +0 -25
  96. package/dist/renderer.d.ts +0 -29
  97. package/dist/renderer.js +0 -412
  98. package/dist/seek.d.ts +0 -1
  99. package/dist/seek.js +0 -27
  100. package/dist/stage.d.ts +0 -58
  101. package/dist/stage.js +0 -121
  102. package/dist/types.d.ts +0 -236
  103. package/dist/types.js +0 -1
  104. package/dist/view.d.ts +0 -51
  105. package/dist/view.js +0 -396
package/dist/element.js DELETED
@@ -1,730 +0,0 @@
1
- // A custom element over the renderer, so a page mounts synchronized lyrics by writing a tag rather
2
- // than a facade. Importing this file registers two element names, which is why it is an entry point
3
- // of its own: a consumer that only wants the renderer must not pay for a registration it never
4
- // asked for, and this extension mounts the renderer itself.
5
- //
6
- // Light DOM, deliberately, rather than the shadow root the component this replaces used. Themes
7
- // select on the class names in `constants.ts` at document level, `@property` registrations do not
8
- // apply to a stylesheet inside a shadow root, and the extension and a third party should be running
9
- // the same code. The theme handed to `theme` is adopted into the element's own document by
10
- // `setTheme`; the module's stylesheets are the consumer's to load, the way any package's CSS is.
11
- import { createLyricsRenderer } from "./renderer.js";
12
- // -- Names --------------------------------------------
13
- const TAG_NAME = "braccato-lyrics";
14
- // What this extension would publish the same component under. A constructor may only be registered
15
- // once, so the second name costs a subclass.
16
- const ALIAS_TAG_NAME = "better-lyrics";
17
- // Attributes are read, never written back. Reflecting `current-time` would put the playback clock in
18
- // the DOM sixty times a second, and one attribute reflecting while the others do not is worse than
19
- // none of them doing it.
20
- const CURRENT_TIME_ATTRIBUTE = "current-time";
21
- const LAYOUT_ATTRIBUTE = "layout";
22
- const PLAYING_ATTRIBUTE = "playing";
23
- const SOURCE_ATTRIBUTE = "source";
24
- const THEME_ATTRIBUTE = "theme";
25
- // -- Following a media element --------------------------------------------
26
- // Every moment the clock moved, changed speed or stopped while no frame of this element's was
27
- // looking. Each one means the same thing here, so they share a handler. `play` and `pause` are the
28
- // loop's start and stop. `seeking` moves the view as a scrub happens, since the position is already
29
- // the requested one by the time it fires, and `seeked` corrects it to where the media element
30
- // actually landed, which is not always the same number. `ratechange` retakes the reading with the
31
- // rate it will be carried at.
32
- //
33
- // The rest are deliberately not listened to, because the frame loop covers them by asking the media
34
- // element whether its clock is still going rather than trusting that something said so. `ended` is
35
- // covered by the `pause` a non-looping media element fires first and by that same question.
36
- // `emptied` says the resource went away rather than that the clock moved, and leaves the media
37
- // element paused at zero for the next frame to report; the README describes the one gap, which is
38
- // `emptied` while already paused. `error` is the one that would otherwise spin, and `isClockRunning`
39
- // below is what stops it. `waiting` and `stalled` are what the carry cap is for: both say the clock
40
- // stopped advancing without stopping. `loadedmetadata` carries nothing this element reads, and
41
- // `timeupdate` is a coarser copy of the frame loop while playing and of the seek events while not.
42
- const MEDIA_CLOCK_EVENTS = ["play", "pause", "seeking", "seeked", "ratechange"];
43
- // How far past its last reading the media clock may be carried, in milliseconds of frame time
44
- // rather than of song time. `currentTime` is only as fresh as the media element chose to make it,
45
- // which for video is once per presented frame, so a view rendering the raw reading steps where the
46
- // song runs. The gap to fill is spaced in frame time whatever the playback rate is, which is why
47
- // the ceiling is measured there; the README says what that costs at a rate above 1x.
48
- const MAX_CLOCK_CARRY_MS = 100;
49
- // The names the component this replaces dispatched, kept so its consumers port by changing an
50
- // import. `braccato:word-click` is not among them: the renderer tells its host a seek happened and
51
- // nothing more, so telling a word seek from a line seek here would mean this file re-deriving the
52
- // module's own click branch off the DOM. The README says what to listen for instead.
53
- const LINE_CLICK_EVENT = "braccato:line-click";
54
- const LYRICS_LOADED_EVENT = "braccato:lyrics-loaded";
55
- const SCROLL_STATE_EVENT = "braccato:scroll-state";
56
- const STAGE_LAYOUT_EVENT = "braccato:stage-layout";
57
- const ERROR_EVENT = "braccato:error";
58
- const NO_BROWSING_CONTEXT_MESSAGE = "This element is in a document with no window, so there is nothing to build lyrics against";
59
- const THEME_DISAGREEMENT_MESSAGE = "Another lyrics element in this document was given a different theme, and the module's theme settings are shared, so both views render against whichever theme was applied last";
60
- const UNSYNCED_STAGE_MESSAGE = "A stage places lines by their time and these lyrics have none, so the stage shows nothing";
61
- const MISSING_STAGE_STYLESHEET_MESSAGE = "The stage container is still in the document flow, so @braccato/core/styles/stage.css is not loaded and every line stacks where it was built";
62
- const NON_MEDIA_SOURCE_MESSAGE = "The source given is not a media element in this element's document, so the lyrics have no clock to follow";
63
- // -- The views a document is rendering --------------------------------------------
64
- // Membership means rendering, so an element that threw on the way up or has been disconnected is
65
- // not in here and is not one of the views a theme has to agree with.
66
- const renderingElementsByDocument = new WeakMap();
67
- // -- Helpers --------------------------------------------
68
- function toError(thrown) {
69
- return thrown instanceof Error ? thrown : new Error(String(thrown), { cause: thrown });
70
- }
71
- function unresolvedSourceMessage(selector) {
72
- return `The source selector "${selector}" does not name a media element in this element's document, so the lyrics have no clock to follow`;
73
- }
74
- /**
75
- * Whether the media element's clock is still going. A fatal decode or network failure mid-song sets
76
- * `error` and fires one, and leaves `paused` alone: nothing runs the pause steps, so a loop that
77
- * only asked about `paused` would spin against a stopped clock for the life of the element.
78
- */
79
- function isClockRunning(media) {
80
- return !media.paused && media.error === null;
81
- }
82
- /**
83
- * Registers a name only if it is free. A page that loads this module twice would otherwise throw out
84
- * of an import and take the rest of that script with it, and the second registration could not have
85
- * won anyway. Silently, because there is no consumer to tell at module scope: the README says what
86
- * two copies on one page costs.
87
- */
88
- function defineOnce(tagName, elementConstructor) {
89
- if (customElements.get(tagName) !== undefined)
90
- return;
91
- customElements.define(tagName, elementConstructor);
92
- }
93
- // -- The element --------------------------------------------
94
- /**
95
- * Mounts a lyrics view into itself. The renderer is built when the element is connected and
96
- * destroyed when it is disconnected, so an element that is moved around the page rebuilds rather
97
- * than going quiet, and every property may be written before either has happened.
98
- *
99
- * `dir` is not among the properties, and that is the point: `HTMLElement` already reflects it, the
100
- * lines this module builds carry `dir="auto"` and resolve their own direction from their text, and a
101
- * property here would be a second opinion about a question the platform has already answered.
102
- */
103
- export class BraccatoLyricsElement extends HTMLElement {
104
- static observedAttributes = [
105
- CURRENT_TIME_ATTRIBUTE,
106
- LAYOUT_ATTRIBUTE,
107
- PLAYING_ATTRIBUTE,
108
- SOURCE_ATTRIBUTE,
109
- THEME_ATTRIBUTE,
110
- ];
111
- #renderer = null;
112
- // The document this element registered itself in, rather than whatever it is in now: adopting an
113
- // element into another document changes `ownerDocument` under the callback that has to take it
114
- // back out of the first one.
115
- #renderingDocument = null;
116
- #missingBrowsingContext = false;
117
- // Null until a consumer gives lyrics, which is not the same as being given none: an element that
118
- // was never given any leaves whatever it is mounted over alone.
119
- #lyrics = null;
120
- #lyricsOptions = {};
121
- #currentTimeS = 0;
122
- #playing = false;
123
- #tickOptions = {};
124
- #theme = "";
125
- #hostOverrides = {};
126
- #layout = "scroll";
127
- // The song the stage last reported on, so a theme that rebuilds the same lines stays quiet.
128
- #stageReportedLyrics = null;
129
- #source = null;
130
- // Non-null exactly while the element is listening to a media element, so there is no state where
131
- // one is remembered and its listeners are not.
132
- #media = null;
133
- // The last reading of the media clock, the frame it was taken on, and the rate it was taken at.
134
- // Null means the next frame takes a new one, which is what a seek or a rate change leaves behind.
135
- #clockAnchor = null;
136
- #frameHandle = null;
137
- // The window the pending frame was scheduled against rather than whatever the element is in now:
138
- // adopting an element into another document would leave the cancellation aimed at the wrong one.
139
- #frameWindow = null;
140
- // -- Properties --------------------------------------------
141
- /**
142
- * The song. An empty array clears the view, so a consumer between songs has a way to say so.
143
- */
144
- get lyrics() {
145
- return this.#lyrics;
146
- }
147
- set lyrics(lyrics) {
148
- this.#lyrics = lyrics;
149
- this.#applyLyrics();
150
- }
151
- /**
152
- * How the lines are built, beyond the lines themselves: whether a loader is still covering the
153
- * view, and whether these lyrics are a "not found" placeholder rather than a song. The second one
154
- * is what keeps passive scrolling off a one line message it would otherwise drift for the length
155
- * of the song.
156
- *
157
- * Read by the next build rather than causing one, so a consumer writes it beside `lyrics` rather
158
- * than instead of it, and writing both renders once.
159
- */
160
- get lyricsOptions() {
161
- return this.#lyricsOptions;
162
- }
163
- set lyricsOptions(options) {
164
- this.#lyricsOptions = options;
165
- }
166
- /**
167
- * The media element the lyrics follow, as a CSS selector resolved in this element's own document
168
- * or as the element itself. Setting it binds and null unbinds, and while it is bound the element
169
- * reads the clock rather than being told it: `currentTime` and `playing` become what it reports.
170
- *
171
- * Bound only while connected, the way the renderer is built only while connected, and a selector
172
- * is resolved again every time it is written and every time the element connects.
173
- */
174
- get source() {
175
- return this.#source;
176
- }
177
- set source(source) {
178
- this.#source = source;
179
- this.#bindSource();
180
- }
181
- /**
182
- * The media element `source` resolved to. Null whenever nothing is being followed, which is the
183
- * answer for a selector that matched nothing and for an element that is not connected.
184
- */
185
- get mediaElement() {
186
- return this.#media;
187
- }
188
- /**
189
- * Playback position in seconds, not milliseconds: the module ticks in seconds, and converting here
190
- * would leave the element and the renderer underneath it disagreeing about what a number means.
191
- * Writing it renders the view again, so whoever owns the clock drives the lyrics by writing this.
192
- *
193
- * While a media element is bound it is the one that owns the clock, so a write is dropped and this
194
- * keeps reporting what the binding last read. Dropped rather than reported: a consumer who left
195
- * their own frame loop running would otherwise be told about it sixty times a second.
196
- */
197
- get currentTime() {
198
- return this.#currentTimeS;
199
- }
200
- set currentTime(currentTimeS) {
201
- if (this.#media !== null)
202
- return;
203
- this.#currentTimeS = currentTimeS;
204
- this.#tick();
205
- }
206
- /** An output rather than an input while a media element is bound, exactly as `currentTime` is. */
207
- get playing() {
208
- return this.#playing;
209
- }
210
- set playing(playing) {
211
- if (this.#media !== null)
212
- return;
213
- this.#playing = playing;
214
- this.#tick();
215
- }
216
- /**
217
- * The rest of a tick: the user offsets the clock is matched against, whether passive scrolling is
218
- * switched on for unsynced lyrics, and the timestamp of the player snapshot the clock came from.
219
- *
220
- * That last one matters beyond this element. The playback clock the module compares a tick
221
- * against is module scope, so an element sharing a realm with another view has to be given the
222
- * same snapshot timestamps that view is, or every tick reads as a jump away from the other one.
223
- *
224
- * Read by the next tick rather than causing one, so a consumer that writes these and the clock on
225
- * the same frame renders the view once rather than twice.
226
- */
227
- get tickOptions() {
228
- return this.#tickOptions;
229
- }
230
- set tickOptions(options) {
231
- this.#tickOptions = options;
232
- }
233
- /**
234
- * A compiled stylesheet. Its `blyrics-*` comments configure the module and the sheet itself goes
235
- * into this element's document. An empty one puts every setting back to its default, and is
236
- * applied like any other: the settings are module scope, so an element that applied nothing would
237
- * render against whatever the last theme in that bundle left behind. What that costs is that
238
- * connecting an element nobody gave a theme empties the theme element already in its document.
239
- */
240
- get theme() {
241
- return this.#theme;
242
- }
243
- set theme(css) {
244
- this.#theme = css;
245
- this.#applyTheme();
246
- }
247
- /**
248
- * Overrides for anything the renderer asks of its surroundings. Every member has a default, so a
249
- * consumer with nothing to say leaves this alone. Writing it while connected rebuilds the view:
250
- * the renderer is handed its host once, when it is created.
251
- */
252
- get host() {
253
- return this.#hostOverrides;
254
- }
255
- set host(overrides) {
256
- this.#hostOverrides = overrides;
257
- if (this.#renderer === null)
258
- return;
259
- this.#destroyRenderer();
260
- this.#build();
261
- }
262
- /**
263
- * `"stage"` shows only the lines being sung, for subtitles over a video, and fills the nearest
264
- * positioned ancestor. Anything else scrolls. Writing it while connected rebuilds the view: the
265
- * renderer is handed its layout once, when it is created.
266
- */
267
- get layout() {
268
- return this.#layout;
269
- }
270
- set layout(layout) {
271
- const next = layout === "stage" ? "stage" : "scroll";
272
- if (next === this.#layout)
273
- return;
274
- this.#layout = next;
275
- if (this.#renderer === null)
276
- return;
277
- this.#destroyRenderer();
278
- this.#build();
279
- }
280
- /**
281
- * The renderer underneath, for a consumer who outgrows the element. Null while disconnected, and a
282
- * different one after every reconnection.
283
- */
284
- get renderer() {
285
- return this.#renderer;
286
- }
287
- /**
288
- * What the element is doing, asked rather than listened for. `theme-conflict` is the one that says
289
- * the view is on the screen but not necessarily the way it was asked for: the theme settings are
290
- * module scope, so a document with two elements holding different themes renders both against
291
- * whichever was applied last.
292
- *
293
- * A `source` that named nothing to follow is deliberately not one of these. The element is still
294
- * rendering, and a status saying otherwise would trade one true answer for another. What a
295
- * consumer who was not listening for the error reads instead is `mediaElement`, which is null
296
- * while `source` still holds the selector it could not resolve.
297
- */
298
- get status() {
299
- if (this.#renderer === null)
300
- return this.#missingBrowsingContext ? "no-browsing-context" : "idle";
301
- if (this.#isUnsyncedOnStage(this.#renderer))
302
- return "unsynced-on-stage";
303
- return this.#disagreeingPeers().length > 0 ? "theme-conflict" : "rendering";
304
- }
305
- // -- Lifecycle --------------------------------------------
306
- connectedCallback() {
307
- // A page that set a property before this module loaded set it on the instance, where it shadows
308
- // the accessor above for the rest of that element's life unless it is run through it again.
309
- this.#upgradeProperty("lyricsOptions");
310
- this.#upgradeProperty("lyrics");
311
- this.#upgradeProperty("tickOptions");
312
- this.#upgradeProperty("currentTime");
313
- this.#upgradeProperty("playing");
314
- this.#upgradeProperty("theme");
315
- this.#upgradeProperty("host");
316
- this.#upgradeProperty("layout");
317
- this.#upgradeProperty("source");
318
- this.#build();
319
- // After the view exists, so a build that threw on the way up leaves no listener on a media
320
- // element and no frame queued for a view that was never there.
321
- this.#bindSource();
322
- }
323
- disconnectedCallback() {
324
- const peers = this.#peers();
325
- this.#unbindMedia();
326
- this.#destroyRenderer();
327
- this.#missingBrowsingContext = false;
328
- // Destroying a renderer takes the theme element with it when that renderer is the one that
329
- // created it, so whatever is still rendering in that document writes its own theme back in.
330
- for (const peer of peers) {
331
- peer.#applyTheme();
332
- }
333
- }
334
- attributeChangedCallback(name, _oldValue, newValue) {
335
- if (name === CURRENT_TIME_ATTRIBUTE) {
336
- const currentTimeS = Number.parseFloat(newValue ?? "");
337
- // A half written attribute must not send the lyrics back to the top of the song.
338
- if (!Number.isNaN(currentTimeS))
339
- this.currentTime = currentTimeS;
340
- return;
341
- }
342
- if (name === LAYOUT_ATTRIBUTE) {
343
- this.layout = newValue === "stage" ? "stage" : "scroll";
344
- return;
345
- }
346
- if (name === PLAYING_ATTRIBUTE) {
347
- this.playing = newValue !== null;
348
- return;
349
- }
350
- if (name === SOURCE_ATTRIBUTE) {
351
- this.source = newValue;
352
- return;
353
- }
354
- if (name === THEME_ATTRIBUTE) {
355
- this.theme = newValue ?? "";
356
- }
357
- }
358
- // -- Building --------------------------------------------
359
- /**
360
- * A throw from inside the module while the view is being built is the one thing `braccato:error`
361
- * deliberately does not cover. Nothing here catches it, so it comes out of `connectedCallback` and
362
- * the page reports it as an uncaught error with the stack it happened on, which is worth more to
363
- * whoever has to fix it than an event carrying the same error second hand.
364
- */
365
- #build() {
366
- if (this.#renderer !== null)
367
- return;
368
- const view = this.ownerDocument.defaultView;
369
- this.#missingBrowsingContext = view === null;
370
- if (view === null) {
371
- this.#emitError("connect", new Error(NO_BROWSING_CONTEXT_MESSAGE));
372
- return;
373
- }
374
- this.#renderer = createLyricsRenderer({
375
- document: this.ownerDocument,
376
- window: view,
377
- mount: this,
378
- host: this.#hostForRenderer(),
379
- layout: this.#layout,
380
- });
381
- // After the renderer exists and never before, so that a build which threw on the way up leaves
382
- // nothing behind claiming to be one of the document's views.
383
- this.#joinDocument();
384
- this.#applyTheme();
385
- this.#applyLyrics();
386
- }
387
- #destroyRenderer() {
388
- this.#renderer?.destroy();
389
- this.#renderer = null;
390
- this.#stageReportedLyrics = null;
391
- this.#leaveDocument();
392
- }
393
- /**
394
- * The consumer's host with the two members the events are read off wrapped rather than replaced,
395
- * so a consumer who wrote one is still called and the event fires either way.
396
- */
397
- #hostForRenderer() {
398
- const overrides = this.#hostOverrides;
399
- return {
400
- ...overrides,
401
- seek: timeS => {
402
- overrides.seek?.(timeS);
403
- // A bound media element is the player, so a click on a line reaches it here rather than
404
- // through a consumer who would otherwise have to write the other half of their own binding.
405
- // Before the event, so a listener reading the media element back sees where the click sent
406
- // it.
407
- if (this.#media !== null)
408
- this.#media.currentTime = timeS;
409
- this.#emit(LINE_CLICK_EVENT, { timeS });
410
- },
411
- setResumeAffordanceVisible: visible => {
412
- overrides.setResumeAffordanceVisible?.(visible);
413
- this.#emit(SCROLL_STATE_EVENT, { userScrolling: visible });
414
- },
415
- onStageLayout: box => {
416
- overrides.onStageLayout?.(box);
417
- this.#emit(STAGE_LAYOUT_EVENT, { box });
418
- },
419
- };
420
- }
421
- #applyLyrics() {
422
- const renderer = this.#renderer;
423
- const lyrics = this.#lyrics;
424
- if (renderer === null || lyrics === null)
425
- return;
426
- try {
427
- if (lyrics.length === 0) {
428
- renderer.clear();
429
- }
430
- else {
431
- renderer.setLyrics(lyrics, this.#lyricsOptions);
432
- }
433
- }
434
- catch (thrown) {
435
- this.#emitError("lyrics", toError(thrown));
436
- return;
437
- }
438
- this.#emit(LYRICS_LOADED_EVENT, {
439
- lineCount: renderer.lines.length,
440
- syncType: renderer.syncType,
441
- });
442
- this.#reportStageProblems(renderer);
443
- // So the new lines are where the song is rather than at the top until the clock next moves.
444
- this.#tick();
445
- }
446
- #isUnsyncedOnStage(renderer) {
447
- return this.#layout === "stage" && renderer.lines.length > 0 && renderer.syncType === "none";
448
- }
449
- /** Both leave an empty or broken stage behind with nothing thrown, so nobody would hear of them. */
450
- #reportStageProblems(renderer) {
451
- const container = renderer.container;
452
- const view = this.ownerDocument.defaultView;
453
- if (this.#layout !== "stage" || container === null || view === null)
454
- return;
455
- if (this.#lyrics === this.#stageReportedLyrics)
456
- return;
457
- this.#stageReportedLyrics = this.#lyrics;
458
- if (this.#isUnsyncedOnStage(renderer))
459
- this.#emitError("layout", new Error(UNSYNCED_STAGE_MESSAGE));
460
- // A frame later, so a stylesheet that lands just after the build is not reported as missing.
461
- view.requestAnimationFrame(() => {
462
- if (this.#renderer !== renderer || renderer.container !== container)
463
- return;
464
- if (view.getComputedStyle(container).position === "absolute")
465
- return;
466
- this.#emitError("layout", new Error(MISSING_STAGE_STYLESHEET_MESSAGE));
467
- });
468
- }
469
- #applyTheme() {
470
- const renderer = this.#renderer;
471
- if (renderer === null)
472
- return;
473
- let needsLyricRebuild = false;
474
- try {
475
- needsLyricRebuild = renderer.setTheme(this.#theme);
476
- }
477
- catch (thrown) {
478
- this.#emitError("theme", toError(thrown));
479
- return;
480
- }
481
- this.#reportThemeDisagreement();
482
- // Only when there are lines to rebuild. A theme applied while the view is being built is applied
483
- // before the lyrics are, and the build itself is what puts them there.
484
- if (needsLyricRebuild && renderer.container !== null)
485
- this.#applyLyrics();
486
- }
487
- #tick() {
488
- const renderer = this.#renderer;
489
- // A view with nothing built reports a missing container to the host on every tick, and a
490
- // consumer whose clock runs before the lyrics arrive is the ordinary case rather than a fault.
491
- if (renderer === null || renderer.container === null)
492
- return;
493
- // The rate a bound media element is playing at is the element's to report, the same way the
494
- // clock is, so it overrides what the consumer wrote for exactly as long as the binding lasts.
495
- const boundRate = this.#media === null ? undefined : this.#media.playbackRate;
496
- // The play state last, so a consumer writing plain JavaScript cannot answer that question twice.
497
- renderer.tick(this.#currentTimeS, {
498
- ...this.#tickOptions,
499
- ...(boundRate === undefined ? {} : { playbackRate: boundRate }),
500
- isPlaying: this.#playing,
501
- });
502
- }
503
- #upgradeProperty(name) {
504
- // Written through the class rather than `this`: TypeScript refuses an indexed write to a
505
- // polymorphic `this`, since a subclass may have narrowed the accessor it would land on.
506
- const element = this;
507
- if (!Object.hasOwn(element, name))
508
- return;
509
- const value = element[name];
510
- Reflect.deleteProperty(element, name);
511
- element[name] = value;
512
- }
513
- // -- Following a media element --------------------------------------------
514
- /**
515
- * Binds whatever `source` names now, unbinding first, so one call is also how the element moves
516
- * from one media element to another and leaves nothing behind on the first.
517
- *
518
- * Bound only while there is a view to drive. A disconnected element holds no renderer, and a
519
- * clock feeding nothing is a listener and a frame that nobody asked for.
520
- */
521
- #bindSource() {
522
- this.#unbindMedia();
523
- if (this.#renderer === null)
524
- return;
525
- const media = this.#resolveSource();
526
- if (media === null)
527
- return;
528
- this.#media = media;
529
- for (const type of MEDIA_CLOCK_EVENTS) {
530
- media.addEventListener(type, this.#handleMediaClockEvent);
531
- }
532
- // Read now rather than waited for: a media element that was already playing when it was bound
533
- // has no `play` event left to fire.
534
- this.#driveFromMedia();
535
- this.#syncFrameLoop();
536
- }
537
- #unbindMedia() {
538
- this.#cancelFrame();
539
- const media = this.#media;
540
- this.#media = null;
541
- this.#clockAnchor = null;
542
- if (media === null)
543
- return;
544
- for (const type of MEDIA_CLOCK_EVENTS) {
545
- media.removeEventListener(type, this.#handleMediaClockEvent);
546
- }
547
- }
548
- #resolveSource() {
549
- const source = this.#source;
550
- if (source === null)
551
- return null;
552
- // The element's own realm rather than this one, so a source belonging to another document is
553
- // judged against that document's constructor rather than against a foreign one it can never be.
554
- const view = this.ownerDocument.defaultView;
555
- // Held to the same test as a selector's answer. A consumer writing plain JavaScript can hand
556
- // this property anything, and something with the two listener methods binds without complaint
557
- // and then feeds `undefined` to every tick for the length of the song.
558
- if (typeof source !== "string") {
559
- if (view !== null && source instanceof view.HTMLMediaElement)
560
- return source;
561
- this.#emitError("source", new Error(NON_MEDIA_SOURCE_MESSAGE));
562
- return null;
563
- }
564
- let matched;
565
- try {
566
- matched = this.ownerDocument.querySelector(source);
567
- }
568
- catch (thrown) {
569
- // A string that is not a selector throws, and a property setter is not where a consumer
570
- // expects to catch that.
571
- this.#emitError("source", toError(thrown));
572
- return null;
573
- }
574
- if (view === null || !(matched instanceof view.HTMLMediaElement)) {
575
- this.#emitError("source", new Error(unresolvedSourceMessage(source)));
576
- return null;
577
- }
578
- return matched;
579
- }
580
- // One handler for all of them, because what each event means to this element is the same thing:
581
- // the clock moved, changed speed or stopped, and the reading being carried forward is stale.
582
- #handleMediaClockEvent = () => {
583
- this.#driveFromMedia();
584
- this.#syncFrameLoop();
585
- };
586
- #driveFromMedia() {
587
- const media = this.#media;
588
- if (media === null)
589
- return;
590
- this.#clockAnchor = null;
591
- this.#drive(media.currentTime, isClockRunning(media));
592
- }
593
- #drive(currentTimeS, playing) {
594
- this.#currentTimeS = currentTimeS;
595
- this.#playing = playing;
596
- this.#tick();
597
- }
598
- /**
599
- * A frame runs only while a bound clock is running against a view, so a stopped one costs
600
- * nothing. The view is a term of that rather than an assumption: `connectedCallback` orders its
601
- * build before its bind so a build that threw leaves no loop behind, and a `host` rewrite whose
602
- * rebuild throws is the one road left to a live binding with no renderer under it.
603
- */
604
- #syncFrameLoop() {
605
- if (this.#renderer !== null && this.#media !== null && this.#playing) {
606
- this.#scheduleFrame();
607
- return;
608
- }
609
- this.#cancelFrame();
610
- }
611
- #scheduleFrame() {
612
- if (this.#frameHandle !== null)
613
- return;
614
- const view = this.ownerDocument.defaultView;
615
- if (view === null)
616
- return;
617
- this.#frameWindow = view;
618
- this.#frameHandle = view.requestAnimationFrame(this.#renderFrame);
619
- }
620
- #cancelFrame() {
621
- if (this.#frameHandle === null)
622
- return;
623
- this.#frameWindow?.cancelAnimationFrame(this.#frameHandle);
624
- this.#frameHandle = null;
625
- this.#frameWindow = null;
626
- }
627
- #renderFrame = (frameTimeMs) => {
628
- this.#frameHandle = null;
629
- this.#frameWindow = null;
630
- const media = this.#media;
631
- if (media === null)
632
- return;
633
- // The loop asks rather than trusting the pause event, so a clock that stopped without one, at
634
- // the end of a song, when its resource went away or when the stream feeding it failed, still
635
- // stops the frames.
636
- if (isClockRunning(media)) {
637
- this.#drive(this.#carriedClock(media, frameTimeMs), true);
638
- }
639
- else {
640
- this.#driveFromMedia();
641
- }
642
- this.#syncFrameLoop();
643
- };
644
- /**
645
- * Where the song is on this frame. A reading the media element has not refreshed is carried
646
- * forward at the rate it was taken at, which is what keeps a binding honest at any playback rate
647
- * rather than only at 1x, and what turns a clock that only updates once per presented frame into
648
- * one the lyrics can run against.
649
- */
650
- #carriedClock(media, frameTimeMs) {
651
- const mediaTimeS = media.currentTime;
652
- const anchor = this.#clockAnchor;
653
- if (anchor === null || anchor.mediaTimeS !== mediaTimeS) {
654
- this.#clockAnchor = { mediaTimeS, frameTimeMs, rate: media.playbackRate };
655
- return mediaTimeS;
656
- }
657
- const carriedMs = Math.min(Math.max(frameTimeMs - anchor.frameTimeMs, 0), MAX_CLOCK_CARRY_MS);
658
- return anchor.mediaTimeS + (carriedMs * anchor.rate) / 1000;
659
- }
660
- // -- More than one view in a document --------------------------------------------
661
- /**
662
- * The module's theme settings are module scope, so two views in one realm render against whichever
663
- * theme either of them was applied last, and two in one document write the same theme element as
664
- * well. Two views handed the same theme are not affected by any of that and render correctly, so
665
- * that is the line: a second element builds, and what is reported is the disagreement rather than
666
- * the company.
667
- *
668
- * Both sides are told, because the element that diverged is not the one that is now rendering
669
- * against a theme it never asked for.
670
- */
671
- #reportThemeDisagreement() {
672
- const disagreeing = this.#disagreeingPeers();
673
- if (disagreeing.length === 0)
674
- return;
675
- const error = new Error(THEME_DISAGREEMENT_MESSAGE);
676
- this.#emitError("conflict", error);
677
- for (const peer of disagreeing) {
678
- peer.#emitError("conflict", error);
679
- }
680
- }
681
- #peers() {
682
- const elementDocument = this.#renderingDocument;
683
- if (elementDocument === null)
684
- return [];
685
- const rendering = renderingElementsByDocument.get(elementDocument);
686
- if (rendering === undefined)
687
- return [];
688
- return [...rendering].filter(element => element !== this);
689
- }
690
- #disagreeingPeers() {
691
- return this.#peers().filter(element => element.#theme !== this.#theme);
692
- }
693
- #joinDocument() {
694
- const elementDocument = this.ownerDocument;
695
- const rendering = renderingElementsByDocument.get(elementDocument) ?? new Set();
696
- renderingElementsByDocument.set(elementDocument, rendering);
697
- rendering.add(this);
698
- this.#renderingDocument = elementDocument;
699
- }
700
- #leaveDocument() {
701
- const elementDocument = this.#renderingDocument;
702
- if (elementDocument === null)
703
- return;
704
- this.#renderingDocument = null;
705
- renderingElementsByDocument.get(elementDocument)?.delete(this);
706
- }
707
- // -- Events --------------------------------------------
708
- #emit(type, detail) {
709
- // The element's own realm rather than this one, and the global as a last resort: an element in a
710
- // document with no window still has an error to report about exactly that.
711
- const EventConstructor = this.ownerDocument.defaultView?.CustomEvent ?? CustomEvent;
712
- // Composed so an element a consumer put inside their own shadow root still reaches their
713
- // listener; the element builds no shadow root of its own.
714
- this.dispatchEvent(new EventConstructor(type, { detail, bubbles: true, composed: true }));
715
- }
716
- #emitError(phase, error) {
717
- // A microtask later rather than where it happened. `connectedCallback` runs before any listener
718
- // a page could have added, and for an element the parser built it runs before any script at all,
719
- // so an error reported from a build is one nobody could ever have heard. `status` is the answer
720
- // for a consumer that was not listening even then.
721
- queueMicrotask(() => {
722
- this.#emit(ERROR_EVENT, { phase, error });
723
- });
724
- }
725
- }
726
- // -- Registration --------------------------------------------
727
- class BetterLyricsElement extends BraccatoLyricsElement {
728
- }
729
- defineOnce(TAG_NAME, BraccatoLyricsElement);
730
- defineOnce(ALIAS_TAG_NAME, BetterLyricsElement);