@braccato/core 1.19.1 → 1.20.1

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 (70) hide show
  1. package/dist/engine/animationConfig.d.ts +88 -0
  2. package/dist/engine/animationConfig.js +98 -0
  3. package/dist/engine/animationDrift.d.ts +11 -0
  4. package/dist/engine/animationDrift.js +43 -0
  5. package/dist/engine/animationTiming.d.ts +25 -0
  6. package/dist/engine/animationTiming.js +119 -0
  7. package/dist/engine/autoScroll.d.ts +24 -0
  8. package/dist/engine/autoScroll.js +103 -0
  9. package/dist/engine/clock.d.ts +29 -0
  10. package/dist/engine/clock.js +70 -0
  11. package/dist/engine/cssValues.d.ts +13 -0
  12. package/dist/engine/cssValues.js +47 -0
  13. package/dist/engine/culling.d.ts +6 -0
  14. package/dist/engine/culling.js +67 -0
  15. package/dist/engine/debugOverlay.d.ts +14 -0
  16. package/dist/engine/debugOverlay.js +58 -0
  17. package/dist/engine/decorationSlides.d.ts +6 -0
  18. package/dist/engine/decorationSlides.js +44 -0
  19. package/dist/engine/glow.d.ts +7 -0
  20. package/dist/engine/glow.js +59 -0
  21. package/dist/engine/highlightKeyframes.d.ts +8 -0
  22. package/dist/engine/highlightKeyframes.js +37 -0
  23. package/dist/engine/instance.d.ts +102 -0
  24. package/dist/engine/instance.js +87 -0
  25. package/dist/engine/instrumentalAnimations.d.ts +7 -0
  26. package/dist/engine/instrumentalAnimations.js +59 -0
  27. package/dist/engine/letterPlans.d.ts +42 -0
  28. package/dist/engine/letterPlans.js +103 -0
  29. package/dist/engine/lineAnimationState.d.ts +10 -0
  30. package/dist/engine/lineAnimationState.js +85 -0
  31. package/dist/engine/lineAnimations.d.ts +5 -0
  32. package/dist/engine/lineAnimations.js +82 -0
  33. package/dist/engine/lineLifecycle.d.ts +12 -0
  34. package/dist/engine/lineLifecycle.js +92 -0
  35. package/dist/engine/lineScroll.d.ts +48 -0
  36. package/dist/engine/lineScroll.js +174 -0
  37. package/dist/engine/lineScrollStyle.d.ts +27 -0
  38. package/dist/engine/lineScrollStyle.js +119 -0
  39. package/dist/engine/liveViews.d.ts +3 -0
  40. package/dist/engine/liveViews.js +5 -0
  41. package/dist/engine/motionPreference.d.ts +1 -0
  42. package/dist/engine/motionPreference.js +1 -0
  43. package/dist/engine/passiveScroll.d.ts +10 -0
  44. package/dist/engine/passiveScroll.js +93 -0
  45. package/dist/engine/renderedLines.d.ts +17 -0
  46. package/dist/engine/renderedLines.js +137 -0
  47. package/dist/engine/scrollViewport.d.ts +36 -0
  48. package/dist/engine/scrollViewport.js +104 -0
  49. package/dist/engine/stageMotion.d.ts +7 -0
  50. package/dist/engine/stageMotion.js +319 -0
  51. package/dist/engine/tick.d.ts +13 -0
  52. package/dist/engine/tick.js +246 -0
  53. package/dist/engine/timingLogs.d.ts +7 -0
  54. package/dist/engine/timingLogs.js +81 -0
  55. package/dist/engine/userScroll.d.ts +12 -0
  56. package/dist/engine/userScroll.js +62 -0
  57. package/dist/engine/wavePool.d.ts +8 -0
  58. package/dist/engine/wavePool.js +22 -0
  59. package/dist/engine/wordAnimations.d.ts +9 -0
  60. package/dist/engine/wordAnimations.js +216 -0
  61. package/dist/index.d.ts +3 -2
  62. package/dist/index.js +2 -1
  63. package/dist/inject.js +40 -22
  64. package/dist/renderer.js +8 -2
  65. package/dist/types.d.ts +1 -1
  66. package/dist/view.d.ts +2 -2
  67. package/dist/view.js +7 -3
  68. package/package.json +2 -2
  69. package/dist/engine.d.ts +0 -471
  70. package/dist/engine.js +0 -3133
package/dist/engine.js DELETED
@@ -1,3133 +0,0 @@
1
- // The animation engine: one instance per rendered view, holding that view's lines, its selection,
2
- // its scroll state and the per frame work that keeps the three in step. `renderer.ts` is what a
3
- // consumer holds; this is what it is holding.
4
- //
5
- // An instance per rendered surface rather than a singleton, because this extension runs two: the
6
- // YouTube Music side panel and the floating window. The two share parsed lyric data and a playback
7
- // clock and nothing else, so anything one view can disagree with another about lives on the
8
- // instance.
9
- //
10
- // The module owns no clock. A tick arrives from outside with the time already on it, which here is
11
- // the interpolated player snapshot behind `blyrics-send-player-time`, and in the floating window a
12
- // second interpolation of that same snapshot. Neither is a media element, which is why the custom
13
- // element can own an animation frame loop over one while nothing under here owns a loop at all.
14
- //
15
- // Two things are module scope rather than instance scope: the set of live instances, and the
16
- // playback clock the last tick wrote. Their unit is a bundle rather than a document, and this
17
- // module is bundled into the isolated world and the page world separately, so those are two clocks
18
- // that never meet. `themeSettings.ts` holds the third thing under that rule.
19
- import { ANIMATING_CLASS, CREDITS_CLASS, CURRENT_LYRICS_CLASS, FOOTER_CLASS, LINE_CLASS, PAUSED_CLASS, ROMANIZED_LYRICS_CLASS, RTL_CLASS, TRANSLATED_LYRICS_CLASS, USER_SCROLLING_CLASS, WORD_STATE_ACTIVE, WORD_STATE_ATTR, WORD_STATE_PAST, WORD_STATE_UPCOMING, } from "./constants.js";
20
- import { INSTRUMENTAL_WAVE_PATH_HIGH, INSTRUMENTAL_WAVE_PATH_LOW } from "./instrumental.js";
21
- import { layoutStage, planStage, queuedStageY, stageTextSpan, } from "./stage.js";
22
- import { registerThemeSetting } from "./themeSettings.js";
23
- import { clamp, getRelativeLayoutBounds, isGecko, positiveModulo, roundedMs, toMs } from "./util.js";
24
- const NO_LYRICS_ELEMENT_LOG = "No lyrics element found on the page, skipping lyrics injection";
25
- const LYRICS_CHECK_INTERVAL_ERROR = "Error in lyrics check interval:";
26
- const PAUSING_LYRICS_SCROLL_LOG = "Pausing Lyrics Autoscroll Due to User Scroll";
27
- const USER_SCROLL_RESUME_DELAY_MS = 25000;
28
- const PASSIVE_USER_SCROLL_RESUME_DELAY_MS = 5000;
29
- const PASSIVE_DRIFT_SCROLL_TOLERANCE_PX = 1;
30
- const LYRIC_ENDING_THRESHOLD_S = registerThemeSetting("blyrics-lyric-ending-threshold-s", 0.5);
31
- const EARLY_SCROLL_CONSIDER = registerThemeSetting("blyrics-early-scroll-consider-s", 0.54);
32
- const TIME_JUMP_THRESHOLD = 0.5;
33
- // Gecko steps media time every ~40ms, so reads lag by a random amount (never lead) that reseeks lines as drift.
34
- const SMOOTH_PLAYBACK_CLOCK = isGecko();
35
- // One Gecko step (~45ms) plus margin: a read further off is a seek or a timer spike, not media lag.
36
- const CLOCK_RESYNC_THRESHOLD_S = 0.06;
37
- const CLOCK_SLEW_PER_S = 0.1;
38
- const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
39
- const SCROLL_PREPARE_LEAD_MS = 120;
40
- const LINE_SCROLL_FALLBACK_DURATION_MS = 750;
41
- const SWIPE_LEAD_RATIO = registerThemeSetting("blyrics-swipe-lead-ratio", 0.1);
42
- const SWIPE_DURATION_RATIO = registerThemeSetting("blyrics-swipe-duration-ratio", 1.6);
43
- const ENABLE_DEBUG_RENDER = registerThemeSetting("blyrics-debug-renderer", false);
44
- const ENABLE_ANIMATION_TIMING_LOGS = registerThemeSetting("blyrics-debug-animation-timing", false);
45
- const ANIMATION_TIMING_LOG_WINDOW_MS = 3000;
46
- const ANIMATION_TIMING_LOG_INTERVAL_MS = 750;
47
- const ANIMATION_TIMING_LOG_THRESHOLD_MS = 30;
48
- const ANIMATION_TIMING_RESET_THRESHOLD_MS = 100;
49
- const ANIMATION_TIMING_ACCUMULATION_DECAY = 1.08;
50
- const ANIMATION_TIMING_ACCUMULATION_WEIGHT = 0.4;
51
- const ANIMATION_TIMING_LEARN_RATE = 0.08;
52
- const ANIMATION_TIMING_LEARN_SAMPLE_LIMIT_MS = 80;
53
- const ANIMATION_TIMING_MAX_LEARNED_OFFSET_MS = 80;
54
- function registerLineScrollStyleSetting(property, defaultValue) {
55
- return [property, registerThemeSetting(property.slice(2), defaultValue)];
56
- }
57
- const LINE_SCROLL_AFTER_FUNCTION = "calc(750ms + log(var(--blyrics-line-scroll-abs-relative-index) + 2, 2.71828) * 80ms + (var(--blyrics-line-scroll-abs-relative-index) + 1) * 20ms)";
58
- const LINE_SCROLL_STYLE_SETTINGS = [
59
- registerLineScrollStyleSetting("--blyrics-line-scroll-duration", LINE_SCROLL_AFTER_FUNCTION),
60
- registerLineScrollStyleSetting("--blyrics-line-scroll-above-duration", "calc(750ms + min(var(--blyrics-line-scroll-abs-relative-index), 6) * 20ms)"),
61
- registerLineScrollStyleSetting("--blyrics-line-scroll-active-duration", ""),
62
- registerLineScrollStyleSetting("--blyrics-line-scroll-below-duration", LINE_SCROLL_AFTER_FUNCTION),
63
- registerLineScrollStyleSetting("--blyrics-line-scroll-timing-function", "var(--blyrics-lyric-scroll-timing-function)"),
64
- registerLineScrollStyleSetting("--blyrics-line-scroll-start-easing", "var(--blyrics-line-scroll-timing-function)"),
65
- registerLineScrollStyleSetting("--blyrics-line-scroll-end-easing", "linear"),
66
- registerLineScrollStyleSetting("--blyrics-line-scroll-above-start-easing", ""),
67
- registerLineScrollStyleSetting("--blyrics-line-scroll-active-start-easing", ""),
68
- registerLineScrollStyleSetting("--blyrics-line-scroll-below-start-easing", ""),
69
- registerLineScrollStyleSetting("--blyrics-line-scroll-above-end-easing", ""),
70
- registerLineScrollStyleSetting("--blyrics-line-scroll-active-end-easing", ""),
71
- registerLineScrollStyleSetting("--blyrics-line-scroll-below-end-easing", ""),
72
- registerLineScrollStyleSetting("--blyrics-line-scroll-translate-y-start", "var(--blyrics-line-scroll-delta-px)"),
73
- registerLineScrollStyleSetting("--blyrics-line-scroll-translate-y-end", "0px"),
74
- registerLineScrollStyleSetting("--blyrics-line-scroll-above-translate-y-start", ""),
75
- registerLineScrollStyleSetting("--blyrics-line-scroll-active-translate-y-start", ""),
76
- registerLineScrollStyleSetting("--blyrics-line-scroll-below-translate-y-start", ""),
77
- registerLineScrollStyleSetting("--blyrics-line-scroll-above-translate-y-end", ""),
78
- registerLineScrollStyleSetting("--blyrics-line-scroll-active-translate-y-end", ""),
79
- registerLineScrollStyleSetting("--blyrics-line-scroll-below-translate-y-end", ""),
80
- ];
81
- // Tracked so the tick can skip the per-line translate write-then-read unless a theme overrides it.
82
- const LINE_SCROLL_TRANSLATE_SETTINGS = LINE_SCROLL_STYLE_SETTINGS.filter(([property]) => property.includes("translate-y")).map(([, setting]) => setting);
83
- const animationTimingLastLogTimes = new WeakMap();
84
- // 0.5 means the selected lyric will be in the middle of the screen, 0 means top, 1 means bottom
85
- const SCROLL_POS_OFFSET_RATIO = registerThemeSetting("blyrics-target-scroll-pos-ratio", 0.37);
86
- const PASSIVE_SCROLL_ENABLED = registerThemeSetting("blyrics-passive-scroll-enabled", true);
87
- const PASSIVE_SECONDS_PER_LINE = registerThemeSetting("blyrics-passive-scroll-seconds-per-line", 3.5);
88
- const PASSIVE_BOTTOM_PAUSE_S = registerThemeSetting("blyrics-passive-scroll-bottom-pause-s", 1.5);
89
- const PASSIVE_RESET_DURATION_S = registerThemeSetting("blyrics-passive-scroll-reset-duration-s", 0.6);
90
- const PASSIVE_TOP_PAUSE_S = registerThemeSetting("blyrics-passive-scroll-top-pause-s", 0.8);
91
- /**
92
- * Stands where a snapshot's wall clock timestamp would be when the time did not come from a live
93
- * player, and so says nothing about how long ago it was sampled.
94
- */
95
- const NO_PLAYER_SNAPSHOT = -1;
96
- /**
97
- * Every instance that has been created and not yet destroyed. Operations that describe the song
98
- * rather than one view are addressed to all of them: nothing outside this module gets to name a
99
- * particular view, so nothing outside it can leave one showing lyrics the others have dropped.
100
- */
101
- const liveEngines = new Set();
102
- /**
103
- * Runs an operation against every live instance. Cheap enough for a scroll or a song change, and
104
- * deliberately not used inside the tick, which runs per frame and per line.
105
- */
106
- export function forEveryLiveView(runOperation) {
107
- for (const engine of liveEngines) {
108
- runOperation(engine);
109
- }
110
- }
111
- export function createAnimationEngineInstance(engineDocument, engineWindow, host, layout = "scroll") {
112
- const reducedMotionQuery = engineWindow.matchMedia(REDUCED_MOTION_QUERY);
113
- const handleReducedMotionChange = () => clearStyleCaches(engine);
114
- const engine = {
115
- document: engineDocument,
116
- window: engineWindow,
117
- host,
118
- lines: [],
119
- lyricsContainer: null,
120
- syncType: "none",
121
- lyricWidth: 0,
122
- lyricHeight: 0,
123
- skipScrolls: 0,
124
- skipScrollsDecayTimes: [],
125
- scrollResumeTime: 0,
126
- scrollPos: -1,
127
- selectedElementIndex: 0,
128
- wasUserScrolling: false,
129
- lastScrollElements: [],
130
- pinnedScrollLine: null,
131
- lastScrollDebugContext: {
132
- activeElms: [],
133
- centers: [],
134
- lyricScrollTime: 0,
135
- },
136
- passiveScrollAccumulatedTime: 0,
137
- passiveLastWallTime: 0,
138
- passiveScrollTop: null,
139
- cachedTabRendererHeight: null,
140
- cachedScrollInsets: NO_SCROLL_INSETS,
141
- cachedFooterItem: null,
142
- cachedCreditsItem: null,
143
- creditsFocused: false,
144
- cachedLineScrollTiming: new Map(),
145
- tabRendererResizeObserver: null,
146
- observedTabRenderer: null,
147
- lineScrollAnimations: [],
148
- lineScrollAnimationToken: 0,
149
- pendingLineScroll: null,
150
- lineScrollElementTokens: new WeakMap(),
151
- visibleWillChangeElements: new Set(),
152
- culledLineElements: new Set(),
153
- waveAnimationPool: [],
154
- lineCullObserver: null,
155
- cachedDurations: new Map(),
156
- cachedCSSValues: new Map(),
157
- cachedAnimationSettings: null,
158
- passiveScrollEnabled: false,
159
- lastTickOptions: null,
160
- playbackRate: 1,
161
- passiveRAFId: null,
162
- pendingLyricsUpdateFrame: null,
163
- learnedAnimationTimingOffsetMs: 0,
164
- animationTimingVisibilityLogUntil: 0,
165
- layout,
166
- stageKey: "",
167
- stageRemeasured: false,
168
- stageHeight: 0,
169
- stageBox: null,
170
- stageMetrics: new Map(),
171
- stageY: new Map(),
172
- stageMoves: new Map(),
173
- stageFades: new Map(),
174
- stageBlurs: new Map(),
175
- stageFontSize: 16,
176
- destroy: () => {
177
- liveEngines.delete(engine);
178
- reducedMotionQuery.removeEventListener("change", handleReducedMotionChange);
179
- engine.tabRendererResizeObserver?.disconnect();
180
- engine.tabRendererResizeObserver = null;
181
- engine.observedTabRenderer = null;
182
- engine.lineCullObserver?.disconnect();
183
- engine.lineCullObserver = null;
184
- stopPassiveScrollLoop(engine);
185
- cancelLyricPositionUpdate(engine);
186
- },
187
- };
188
- reducedMotionQuery.addEventListener("change", handleReducedMotionChange);
189
- liveEngines.add(engine);
190
- return engine;
191
- }
192
- const playbackClock = {
193
- lastTime: 0,
194
- lastPlayState: false,
195
- lastEventCreationTime: NO_PLAYER_SNAPSHOT,
196
- smoothedTime: 0,
197
- smoothedAt: NO_PLAYER_SNAPSHOT,
198
- };
199
- /**
200
- * Forgets the last player snapshot, so the next tick is treated as the first one of a new song
201
- * rather than as a jump away from the previous one.
202
- */
203
- export function resetPlaybackClock() {
204
- playbackClock.lastTime = 0;
205
- playbackClock.lastPlayState = false;
206
- playbackClock.lastEventCreationTime = NO_PLAYER_SNAPSHOT;
207
- playbackClock.smoothedAt = NO_PLAYER_SNAPSHOT;
208
- }
209
- export function smoothedPlaybackTime(previousTime, previousAt, rawTime, now, playbackRate) {
210
- if (previousAt === NO_PLAYER_SNAPSHOT)
211
- return rawTime;
212
- const elapsedS = Math.max(0, now - previousAt) / 1000;
213
- const predictedTime = previousTime + elapsedS * playbackRate;
214
- const errorS = rawTime - predictedTime;
215
- if (errorS >= 0 || Math.abs(errorS) >= CLOCK_RESYNC_THRESHOLD_S)
216
- return rawTime;
217
- return predictedTime + errorS * Math.min(1, elapsedS * CLOCK_SLEW_PER_S);
218
- }
219
- // -- View operations --------------------------
220
- /**
221
- * The user asked for autoscroll back, now.
222
- */
223
- export function resetScrollResume(engine) {
224
- engine.scrollResumeTime = 0;
225
- }
226
- /**
227
- * The user asked for autoscroll back, now. Resuming is a property of playback rather than of one
228
- * view, so every live instance resumes. Published in this shape rather than as the registry walk
229
- * and the per view operation it is built from, so that nothing outside the module gets to name a
230
- * particular view.
231
- */
232
- export function resumeAllAutoscroll() {
233
- forEveryLiveView(resetScrollResume);
234
- }
235
- /**
236
- * The user scrolled this view. Scrolls the engine itself performed are swallowed;
237
- * a real one pauses autoscroll long enough to read where it landed, and offers the way back.
238
- *
239
- * @param isPassive - Whether the lyrics on screen are unsynced, and so are drifting on their own
240
- * rather than following the song. Those resume sooner.
241
- */
242
- export function noteUserScroll(engine, isPassive) {
243
- if (isPassive) {
244
- if (isPassiveDriftScroll(engine))
245
- return;
246
- }
247
- else if (engine.skipScrolls > 0) {
248
- engine.skipScrolls--;
249
- engine.skipScrollsDecayTimes.shift();
250
- return;
251
- }
252
- dropPendingLineScroll(engine);
253
- if (engine.host.isLoaderActive())
254
- return;
255
- if (engine.scrollResumeTime < Date.now()) {
256
- engine.host.log(PAUSING_LYRICS_SCROLL_LOG);
257
- }
258
- engine.scrollResumeTime =
259
- Date.now() + (isPassive ? PASSIVE_USER_SCROLL_RESUME_DELAY_MS : USER_SCROLL_RESUME_DELAY_MS);
260
- engine.wasUserScrolling = true;
261
- engine.host.setResumeAffordanceVisible(true);
262
- engine.lyricsContainer?.classList.add(USER_SCROLLING_CLASS);
263
- }
264
- /**
265
- * Reports whether the container is a different size than the lines were last measured against, and
266
- * clears the scroll cooldown when it is so the caller's re-measurement can scroll immediately. The
267
- * new size is recorded by that re-measurement, not here.
268
- */
269
- export function noteContainerResize(engine, width, height) {
270
- if (width === engine.lyricWidth && height === engine.lyricHeight)
271
- return false;
272
- return true;
273
- }
274
- /**
275
- * Takes the lines this view is showing off the screen, keeping the container they were in, and
276
- * reports whether there was anything there to take.
277
- */
278
- export function clearOnScreenLyrics(engine) {
279
- if (!engine.lyricsContainer)
280
- return false;
281
- engine.lyricsContainer.replaceChildren();
282
- resetStage(engine);
283
- return true;
284
- }
285
- export function hasRenderedLines(engine) {
286
- return engine.lines.length > 0;
287
- }
288
- /**
289
- * The render records this view built. Handing them out is a leak: they carry this view's elements
290
- * and its `Animation` objects, so a caller that rewrites line times or hangs translations off them
291
- * can only ever reach one view. Phase 5 revisits it, when both of those have to reach two.
292
- */
293
- export function getRenderedLines(engine) {
294
- return engine.lines;
295
- }
296
- export function getRenderedSyncType(engine) {
297
- return engine.syncType;
298
- }
299
- /**
300
- * Drops the song this view was rendering: its selection, its pending scroll work, its animations
301
- * and its render records. The records go before the caller clears the DOM, so the elements they
302
- * hold are released along with it.
303
- */
304
- export function clearLyrics(engine) {
305
- engine.scrollPos = -1;
306
- dropPendingLineScroll(engine);
307
- clearLineScrollAnimations(engine);
308
- clearVisibleLyricWillChange(engine);
309
- engine.lineCullObserver?.disconnect();
310
- engine.lineCullObserver = null;
311
- clearOffscreenLineCulling(engine);
312
- for (const line of engine.lines) {
313
- resetLineAnimationState(line);
314
- line.isSelected = false;
315
- }
316
- engine.skipScrollsDecayTimes = [];
317
- engine.lastScrollElements = [];
318
- engine.pinnedScrollLine = null;
319
- engine.lastScrollDebugContext.activeElms = [];
320
- engine.lastScrollDebugContext.centers = [];
321
- engine.passiveScrollAccumulatedTime = 0;
322
- engine.passiveLastWallTime = 0;
323
- engine.passiveScrollTop = null;
324
- stopPassiveScrollLoop(engine);
325
- engine.lines = [];
326
- engine.cachedFooterItem = null;
327
- engine.cachedCreditsItem = null;
328
- engine.creditsFocused = false;
329
- engine.lyricsContainer = null;
330
- engine.waveAnimationPool.length = 0;
331
- resetStage(engine);
332
- }
333
- /**
334
- * How far a scroll still running has carried a line from its place, or zero with none running on it.
335
- */
336
- export function lineScrollOffset(engine, element) {
337
- if (!engine.lineScrollAnimations.some(record => record.lineElement === element))
338
- return 0;
339
- return currentTranslateY(engine, element, 0);
340
- }
341
- /**
342
- * Hands the engine the lines of a song swapped into the view it already holds. A kept line is the
343
- * same record and keeps everything; a dropped line's animations stop and nothing goes on holding it;
344
- * a line built in place of one is handed what the engine held for that one, so the scroll does not
345
- * see a line it has not met and the stage does not fade in a line that was already up.
346
- *
347
- * @param lines - The new song's records, kept ones included, in order
348
- * @param dropped - Records of the song before that the new one no longer has
349
- * @param replaced - Each new record built in place of a dropped one, to the one it replaced
350
- */
351
- export function replaceRenderedLines(engine, lines, dropped, replaced) {
352
- const successors = new Map();
353
- for (const [line, previous] of replaced)
354
- successors.set(previous, line);
355
- const droppedElements = new Set(dropped.map(line => line.lyricElement));
356
- const carry = (line) => successors.get(line) ?? (droppedElements.has(line.lyricElement) ? null : line);
357
- const carryAll = (from) => from.map(carry).filter((line) => line !== null);
358
- // The line being sung is still the line being sung, so a theme keyed on those classes does not dim it
359
- // and bring it back. Its animations are set up again from the new timing on the next tick. Read
360
- // before the dropped lines are let go, which clears their selection.
361
- for (const [line, previous] of replaced) {
362
- line.isScrolled = previous.isScrolled;
363
- line.isSelected = previous.isSelected;
364
- togglePartClass(line, CURRENT_LYRICS_CLASS, previous.lyricElement.classList.contains(CURRENT_LYRICS_CLASS));
365
- togglePartClass(line, ANIMATING_CLASS, previous.lyricElement.classList.contains(ANIMATING_CLASS));
366
- }
367
- // A planned scroll was planned against lines and places this swap is about to change.
368
- dropPendingLineScroll(engine);
369
- for (const record of [...engine.lineScrollAnimations]) {
370
- if (!droppedElements.has(record.lineElement))
371
- continue;
372
- record.animation.cancel();
373
- removeLineScrollAnimation(engine, record);
374
- }
375
- for (const line of dropped) {
376
- resetLineAnimationState(line);
377
- line.isSelected = false;
378
- engine.visibleWillChangeElements.delete(line.lyricElement);
379
- engine.culledLineElements.delete(line.lyricElement);
380
- }
381
- engine.lastScrollElements = carryAll(engine.lastScrollElements);
382
- engine.lastScrollDebugContext.activeElms = carryAll(engine.lastScrollDebugContext.activeElms);
383
- engine.pinnedScrollLine = engine.pinnedScrollLine === null ? null : carry(engine.pinnedScrollLine);
384
- engine.lines = lines;
385
- if (engine.layout === "stage")
386
- replaceStageElements(engine, dropped, replaced);
387
- }
388
- /**
389
- * Starts the same animation on another element at the point the first one has reached, or answers
390
- * null when there is nothing left of it to carry on.
391
- */
392
- function continueAnimation(animation, element) {
393
- const effect = animation?.effect;
394
- if (!animation || !effect || typeof effect.getKeyframes !== "function" || animation.playState === "finished") {
395
- return null;
396
- }
397
- if (animation.playState === "idle")
398
- return null;
399
- const continued = element.animate(effect.getKeyframes(), { ...effect.getTiming(), composite: effect.composite });
400
- continued.playbackRate = animation.playbackRate;
401
- continued.currentTime = animation.currentTime;
402
- if (animation.playState === "paused")
403
- continued.pause();
404
- return continued;
405
- }
406
- /**
407
- * Moves what the stage held for each replaced line onto the line built in its place, and lets go of
408
- * every dropped line. A replacement starts exactly where and as visible as the line it replaced, so
409
- * placing the stage afterwards only moves it if the new song puts it somewhere else.
410
- */
411
- function replaceStageElements(engine, dropped, replaced) {
412
- for (const [line, previous] of replaced) {
413
- const element = line.lyricElement;
414
- const role = previous.lyricElement.dataset.stageRole;
415
- const y = engine.stageY.get(previous.lyricElement);
416
- if (role === undefined || y === undefined)
417
- continue;
418
- element.dataset.stageRole = role;
419
- const visible = previous.lyricElement.dataset.stageVisible !== undefined;
420
- if (visible)
421
- element.dataset.stageVisible = "";
422
- // A line replaced mid-glide carries on gliding from wherever the one it replaced had got to.
423
- const move = continueAnimation(engine.stageMoves.get(previous.lyricElement), element);
424
- if (move === null) {
425
- snapStageElement(engine, element, y);
426
- }
427
- else {
428
- engine.stageMoves.set(element, move);
429
- engine.stageY.set(element, y);
430
- }
431
- const fade = continueAnimation(engine.stageFades.get(previous.lyricElement), element) ??
432
- element.animate([{ [STAGE_OPACITY_PROPERTY]: isStageRoleVisible(role) ? 1 : 0 }], {
433
- duration: 0,
434
- fill: "forwards",
435
- });
436
- if (!isStageRoleVisible(role)) {
437
- fade.onfinish = () => {
438
- if (engine.stageFades.get(element) === fade)
439
- delete element.dataset.stageVisible;
440
- };
441
- }
442
- engine.stageFades.set(element, fade);
443
- const blur = continueAnimation(engine.stageBlurs.get(previous.lyricElement), element);
444
- if (blur !== null)
445
- engine.stageBlurs.set(element, blur);
446
- }
447
- for (const line of dropped) {
448
- const element = line.lyricElement;
449
- for (const animations of [engine.stageMoves, engine.stageFades, engine.stageBlurs]) {
450
- animations.get(element)?.cancel();
451
- animations.delete(element);
452
- }
453
- engine.stageY.delete(element);
454
- engine.stageMetrics.delete(element);
455
- }
456
- // The roles are planned again against the new lines, even where they come out the same.
457
- engine.stageKey = "";
458
- }
459
- /**
460
- * Carries a swapped view across the layout change it caused. The line the reader is following holds
461
- * still on screen: the scroll moves by however far that line moved in the container. Every other
462
- * line that moved, relative to it, slides from where it was rather than jumping.
463
- *
464
- * Which line is followed depends on who owns the scroll. While the engine does, it is the line the
465
- * last scroll aimed at; while the reader does, it is the first line they could see.
466
- *
467
- * @param before - Where each line was in the container before the swap and how tall, from `swapLyrics`
468
- * @param scrollTopBefore - The scroll position the swap began at
469
- */
470
- export function settleSwappedLines(engine, before, scrollTopBefore) {
471
- const container = engine.lyricsContainer;
472
- const scrollElement = engine.host.getScrollElement();
473
- if (container === null || scrollElement === null || engine.layout === "stage")
474
- return;
475
- const readerOwnsScroll = engine.scrollResumeTime > Date.now();
476
- const followed = readerOwnsScroll
477
- ? engine.lines.find(line => {
478
- const was = before.get(line);
479
- return was !== undefined && was.position + was.height > scrollTopBefore;
480
- })
481
- : (engine.lastScrollElements.findLast(line => before.has(line)) ??
482
- engine.lines.find(line => before.has(line) && line.isScrolled));
483
- const followedWas = followed === undefined ? undefined : before.get(followed)?.position;
484
- // A line that has not been measured, because the view is not on screen, has nowhere to hold still.
485
- if (followed !== undefined && followedWas !== undefined && followedWas >= 0 && followed.position >= 0) {
486
- const moved = followed.position - followedWas;
487
- if (Math.abs(moved) >= DECORATION_MIN_SHIFT_PX)
488
- scrollElement.scrollTop = scrollTopBefore + moved;
489
- }
490
- // Read back rather than assumed: the browser may have clamped the write, or clamped the scroll for
491
- // a song that got shorter before anything here wrote it. Either way the event that follows is not
492
- // the reader's, and a write the browser clamped to nothing sends none.
493
- const shift = scrollElement.scrollTop - scrollTopBefore;
494
- if (shift !== 0) {
495
- engine.skipScrolls += 1;
496
- engine.skipScrollsDecayTimes.push(Date.now() + 2000);
497
- if (engine.scrollPos >= 0)
498
- engine.scrollPos += shift;
499
- }
500
- if (!decorationSlideAllowed(engine, container))
501
- return;
502
- for (const line of engine.lines) {
503
- const was = before.get(line);
504
- if (was === undefined || was.position < 0 || line.position < 0)
505
- continue;
506
- // From where it is on screen, which a line scroll still running carries away from its place.
507
- const onScreenShift = was.position + was.offset - line.position + shift;
508
- if (Math.abs(onScreenShift) >= DECORATION_MIN_SHIFT_PX)
509
- slideElementBy(line.lyricElement, onScreenShift);
510
- }
511
- }
512
- function resetStage(engine) {
513
- for (const animation of [
514
- ...engine.stageMoves.values(),
515
- ...engine.stageFades.values(),
516
- ...engine.stageBlurs.values(),
517
- ]) {
518
- animation.cancel();
519
- }
520
- engine.stageMoves.clear();
521
- engine.stageFades.clear();
522
- engine.stageBlurs.clear();
523
- engine.stageMetrics.clear();
524
- engine.stageY.clear();
525
- engine.stageKey = "";
526
- engine.stageHeight = 0;
527
- if (engine.stageBox !== null) {
528
- engine.stageBox = null;
529
- engine.host.onStageLayout?.(null);
530
- }
531
- }
532
- /**
533
- * Lets go of a part moving to another line or leaving the view: its animations stop, back to the pool
534
- * they came from, and it shows no sung state until a line that is being sung sets it up again.
535
- */
536
- export function releasePart(part) {
537
- resetPartAnimations(part);
538
- togglePartClass(part, PAUSED_CLASS, false);
539
- togglePartClass(part, ANIMATING_CLASS, false);
540
- part.wordState = WORD_STATE_UPCOMING;
541
- part.lyricElement.setAttribute(WORD_STATE_ATTR, WORD_STATE_UPCOMING);
542
- part.highlightElement.setAttribute(WORD_STATE_ATTR, WORD_STATE_UPCOMING);
543
- part.imageLayers?.highlight?.setAttribute(WORD_STATE_ATTR, WORD_STATE_UPCOMING);
544
- }
545
- function resetPartAnimations(part) {
546
- for (const animation of part.animations) {
547
- animation.cancel();
548
- const pool = pooledWaveAnimations.get(animation);
549
- if (pool)
550
- pool.push(animation);
551
- }
552
- part.animations = [];
553
- }
554
- function resetLineAnimations(lineData) {
555
- const children = [lineData, ...lineData.parts];
556
- children.forEach(resetPartAnimations);
557
- }
558
- function hasLineAnimations(lineData) {
559
- return [lineData, ...lineData.parts].some(part => part.animations.length > 0);
560
- }
561
- function markLineAnimationsStopped(lineData) {
562
- lineData.isAnimating = false;
563
- lineData.isAnimationPlayStatePlaying = false;
564
- lineData.accumulatedOffsetMs = 0;
565
- }
566
- function resetLineAnimationState(lineData) {
567
- resetLineAnimations(lineData);
568
- markLineAnimationsStopped(lineData);
569
- }
570
- function togglePartClass(part, className, force) {
571
- part.lyricElement.classList.toggle(className, force);
572
- if ("highlightElement" in part) {
573
- part.highlightElement.classList.toggle(className, force);
574
- part.imageLayers?.highlight?.classList.toggle(className, force);
575
- }
576
- }
577
- function setAnimationsPlayState(lineData, isPlaying) {
578
- const children = [lineData, ...lineData.parts];
579
- for (const part of children) {
580
- togglePartClass(part, PAUSED_CLASS, !isPlaying);
581
- for (const animation of part.animations) {
582
- if (isPlaying) {
583
- animation.play();
584
- }
585
- else {
586
- animation.pause();
587
- }
588
- }
589
- }
590
- }
591
- function clearLineStateClasses(lineData) {
592
- lineData.lyricElement.classList.remove(ANIMATING_CLASS);
593
- for (const part of [lineData, ...lineData.parts]) {
594
- togglePartClass(part, PAUSED_CLASS, false);
595
- }
596
- }
597
- export function updateWordStates(lineData, currentTime) {
598
- const parts = lineData.parts;
599
- const lineEndTime = lineData.time + lineData.duration;
600
- for (let i = 0; i < parts.length; i++) {
601
- const part = parts[i];
602
- const endTime = part.duration > 0 ? part.time + part.duration : (parts[i + 1]?.time ?? lineEndTime);
603
- let state = WORD_STATE_PAST;
604
- if (currentTime < part.time) {
605
- state = WORD_STATE_UPCOMING;
606
- }
607
- else if (currentTime < endTime) {
608
- state = WORD_STATE_ACTIVE;
609
- }
610
- if (part.wordState === state)
611
- continue;
612
- part.wordState = state;
613
- part.lyricElement.setAttribute(WORD_STATE_ATTR, state);
614
- part.highlightElement.setAttribute(WORD_STATE_ATTR, state);
615
- part.imageLayers?.highlight?.setAttribute(WORD_STATE_ATTR, state);
616
- }
617
- }
618
- const LINE_SYNCED_WORD_CLASS = "blyrics-line-synced-word";
619
- const INSTRUMENTAL_FILL_SELECTOR = ".blyrics--instrumental-fill";
620
- const INSTRUMENTAL_WAVE_CLIP_SELECTOR = ".blyrics--wave-clip";
621
- const INSTRUMENTAL_WAVE_PATH_SELECTOR = ".blyrics--wave-path";
622
- const INSTRUMENTAL_WAVE_PATH_HIGH_FALLBACK = `path("${INSTRUMENTAL_WAVE_PATH_HIGH}")`;
623
- const INSTRUMENTAL_WAVE_PATH_LOW_FALLBACK = `path("${INSTRUMENTAL_WAVE_PATH_LOW}")`;
624
- const LINE_SCROLL_INDEX_PROPERTY = "--blyrics-line-scroll-index";
625
- const LINE_SCROLL_ACTIVE_INDEX_PROPERTY = "--blyrics-line-scroll-active-index";
626
- const LINE_SCROLL_RELATIVE_INDEX_PROPERTY = "--blyrics-line-scroll-relative-index";
627
- const LINE_SCROLL_ABS_RELATIVE_INDEX_PROPERTY = "--blyrics-line-scroll-abs-relative-index";
628
- const LINE_SCROLL_SIDE_PROPERTY = "--blyrics-line-scroll-side";
629
- const LINE_SCROLL_DELTA_PROPERTY = "--blyrics-line-scroll-delta-px";
630
- const LINE_SCROLL_DISTANCE_PROPERTY = "--blyrics-line-scroll-distance-px";
631
- const LINE_SCROLL_WILL_CHANGE_VALUE = "transform, translate";
632
- const LINE_SCROLL_INLINE_PROPERTIES = [
633
- LINE_SCROLL_INDEX_PROPERTY,
634
- LINE_SCROLL_ACTIVE_INDEX_PROPERTY,
635
- LINE_SCROLL_RELATIVE_INDEX_PROPERTY,
636
- LINE_SCROLL_ABS_RELATIVE_INDEX_PROPERTY,
637
- LINE_SCROLL_SIDE_PROPERTY,
638
- LINE_SCROLL_DELTA_PROPERTY,
639
- LINE_SCROLL_DISTANCE_PROPERTY,
640
- ...LINE_SCROLL_STYLE_SETTINGS.map(([property]) => property),
641
- ];
642
- const animationTimingTracks = new WeakMap();
643
- function mirrorImageHighlightAnimations(part, animations) {
644
- const target = part.imageLayers?.highlight;
645
- if (!target)
646
- return [];
647
- const mirrors = [];
648
- for (const animation of animations) {
649
- const effect = animation.effect;
650
- if (!effect || effect.target !== part.highlightElement)
651
- continue;
652
- const mirror = target.animate(effect.getKeyframes(), effect.getTiming());
653
- mirror.playbackRate = animation.playbackRate;
654
- mirror.currentTime = animation.currentTime;
655
- const timing = animationTimingTracks.get(animation);
656
- if (timing)
657
- animationTimingTracks.set(mirror, { ...timing, skipDriftSample: true });
658
- mirrors.push(mirror);
659
- }
660
- return mirrors;
661
- }
662
- function trackLyricAnimationTiming(engine, animation, timing) {
663
- animationTimingTracks.set(animation, {
664
- ...timing,
665
- appliedTimingOffsetMs: timing.appliedTimingOffsetMs ?? engine.learnedAnimationTimingOffsetMs,
666
- });
667
- // Being tracked is what makes an animation the song's rather than the interface's, so it is also
668
- // what decides which ones follow the song's rate.
669
- animation.playbackRate = engine.playbackRate;
670
- return animation;
671
- }
672
- // Finished per-letter wave animations are pooled and retargeted onto new letters, since recreating
673
- // ~150 identical ones per line activation is pure churn.
674
- const pooledWaveAnimations = new WeakMap();
675
- const pooledWaveKeyframeSignatures = new WeakMap();
676
- function acquireWaveAnimation(engine, letterElement, keyframes, keyframeSignature, timing) {
677
- const pool = engine.waveAnimationPool;
678
- const pooled = pool[pool.length - 1];
679
- const effect = pooled?.effect;
680
- if (pooled && effect && typeof effect.setKeyframes === "function") {
681
- pool.pop();
682
- effect.target = letterElement;
683
- if (pooledWaveKeyframeSignatures.get(pooled) !== keyframeSignature) {
684
- effect.setKeyframes(keyframes);
685
- pooledWaveKeyframeSignatures.set(pooled, keyframeSignature);
686
- }
687
- effect.updateTiming(timing);
688
- pooled.play();
689
- return pooled;
690
- }
691
- const animation = letterElement.animate(keyframes, timing);
692
- pooledWaveAnimations.set(animation, pool);
693
- pooledWaveKeyframeSignatures.set(animation, keyframeSignature);
694
- return animation;
695
- }
696
- /**
697
- * Puts the animations already running onto a new rate. Setting `playbackRate` keeps `currentTime`,
698
- * so each one carries on from where the song left it rather than restarting.
699
- */
700
- function applyPlaybackRateToRunningAnimations(engine) {
701
- for (const line of engine.lines) {
702
- for (const animation of line.animations) {
703
- if (animationTimingTracks.has(animation))
704
- animation.playbackRate = engine.playbackRate;
705
- }
706
- for (const part of line.parts) {
707
- for (const animation of part.animations) {
708
- if (animationTimingTracks.has(animation))
709
- animation.playbackRate = engine.playbackRate;
710
- }
711
- }
712
- }
713
- }
714
- function correctedAnimationTimeMs(targetTimeMs, appliedTimingOffsetMs, maxTimeMs) {
715
- const scheduledTimeMs = targetTimeMs - appliedTimingOffsetMs;
716
- return maxTimeMs === undefined ? scheduledTimeMs : Math.min(scheduledTimeMs, maxTimeMs);
717
- }
718
- function correctedWrappedAnimationTimeMs(targetTimeMs, appliedTimingOffsetMs, wrapDurationMs) {
719
- return positiveModulo(targetTimeMs - appliedTimingOffsetMs, wrapDurationMs);
720
- }
721
- function correctedScrollTimeS(engine, currentTime) {
722
- return currentTime - engine.learnedAnimationTimingOffsetMs / 1000;
723
- }
724
- function timingValueToMs(value) {
725
- if (typeof value === "number") {
726
- return Number.isFinite(value) || value === Number.POSITIVE_INFINITY ? value : null;
727
- }
728
- if (typeof value === "string") {
729
- const durationMs = toMs(value);
730
- return durationMs > 0 ? durationMs : null;
731
- }
732
- if (!value || typeof value !== "object") {
733
- return null;
734
- }
735
- const numericValue = value;
736
- if (typeof numericValue.to !== "function") {
737
- return null;
738
- }
739
- try {
740
- const msValue = numericValue.to("ms").value;
741
- return typeof msValue === "number" && Number.isFinite(msValue) ? msValue : null;
742
- }
743
- catch (_err) {
744
- return null;
745
- }
746
- }
747
- function animationCurrentTimeMs(animation) {
748
- return timingValueToMs(animation.currentTime);
749
- }
750
- // A finished animation's currentTime stops at its end time, which counts the delay, so that is where
751
- // the expected time has to stop too. Clamping to the active duration alone saturates a delayed
752
- // animation as soon as it is created and hides any drift in it.
753
- function animationEndTimeMs(animation) {
754
- return timingValueToMs(animation.effect?.getComputedTiming().endTime);
755
- }
756
- function wrappedTimingOffsetMs(actualTimeMs, expectedTimeMs, wrapDurationMs) {
757
- return positiveModulo(actualTimeMs - expectedTimeMs + wrapDurationMs / 2, wrapDurationMs) - wrapDurationMs / 2;
758
- }
759
- function normalizeAnimationTimeMs(animation, timeMs, timing) {
760
- if (!Number.isFinite(timeMs) || timeMs < 0) {
761
- return null;
762
- }
763
- if (timing.wrapDurationMs && timing.wrapDurationMs > 0) {
764
- return positiveModulo(timeMs, timing.wrapDurationMs);
765
- }
766
- const endTimeMs = animationEndTimeMs(animation);
767
- if (endTimeMs !== null && Number.isFinite(endTimeMs)) {
768
- return Math.min(timeMs, endTimeMs);
769
- }
770
- return timeMs;
771
- }
772
- function animationTimingSample(part, animation, currentTime) {
773
- const timing = animationTimingTracks.get(animation);
774
- if (!timing || timing.skipDriftSample) {
775
- return null;
776
- }
777
- if (animation.playState === "idle") {
778
- return null;
779
- }
780
- const actualTimeMs = animationCurrentTimeMs(animation);
781
- if (actualTimeMs === null) {
782
- return null;
783
- }
784
- const rawExpectedTimeMs = (currentTime - part.time) * 1000 + timing.offsetMs;
785
- const expectedTimeMs = normalizeAnimationTimeMs(animation, rawExpectedTimeMs, timing);
786
- const normalizedActualTimeMs = normalizeAnimationTimeMs(animation, actualTimeMs, timing);
787
- if (expectedTimeMs === null || normalizedActualTimeMs === null) {
788
- return null;
789
- }
790
- const offsetMs = timing.wrapDurationMs && timing.wrapDurationMs > 0
791
- ? wrappedTimingOffsetMs(normalizedActualTimeMs, expectedTimeMs, timing.wrapDurationMs)
792
- : normalizedActualTimeMs - expectedTimeMs;
793
- const biasOffsetMs = offsetMs + timing.appliedTimingOffsetMs;
794
- return {
795
- actualTimeMs: normalizedActualTimeMs,
796
- appliedTimingOffsetMs: timing.appliedTimingOffsetMs,
797
- biasOffsetMs,
798
- expectedTimeMs,
799
- offsetMs,
800
- playState: animation.playState,
801
- };
802
- }
803
- function largestNativeTimingSample(part, currentTime) {
804
- let largestSample = null;
805
- for (const animation of part.animations) {
806
- const sample = animationTimingSample(part, animation, currentTime);
807
- if (sample === null) {
808
- continue;
809
- }
810
- if (largestSample === null || Math.abs(sample.offsetMs) > Math.abs(largestSample.offsetMs)) {
811
- largestSample = sample;
812
- }
813
- }
814
- return largestSample;
815
- }
816
- function lineNativeTimingSample(lineData, currentTime) {
817
- let largestSample = null;
818
- for (const part of [lineData, ...lineData.parts]) {
819
- const sample = largestNativeTimingSample(part, currentTime);
820
- if (sample === null) {
821
- continue;
822
- }
823
- if (largestSample === null || Math.abs(sample.offsetMs) > Math.abs(largestSample.offsetMs)) {
824
- largestSample = sample;
825
- }
826
- }
827
- return largestSample;
828
- }
829
- function linePreview(lineData) {
830
- return lineData.lyricElement.textContent?.trim().replace(/\s+/g, " ").slice(0, 80) ?? "";
831
- }
832
- function canUseTimingSampleForDrift(sample, isPlaying) {
833
- if (!isPlaying) {
834
- return false;
835
- }
836
- return sample.playState === "running" || sample.playState === "finished";
837
- }
838
- function learnAnimationTimingOffset(engine, sample) {
839
- if (Math.abs(sample.biasOffsetMs) > ANIMATION_TIMING_LEARN_SAMPLE_LIMIT_MS) {
840
- return engine.learnedAnimationTimingOffsetMs;
841
- }
842
- engine.learnedAnimationTimingOffsetMs = clamp(engine.learnedAnimationTimingOffsetMs +
843
- (sample.biasOffsetMs - engine.learnedAnimationTimingOffsetMs) * ANIMATION_TIMING_LEARN_RATE, -ANIMATION_TIMING_MAX_LEARNED_OFFSET_MS, ANIMATION_TIMING_MAX_LEARNED_OFFSET_MS);
844
- return engine.learnedAnimationTimingOffsetMs;
845
- }
846
- function shouldLogAnimationTiming(engine, lineData, sample, now) {
847
- if (!ENABLE_ANIMATION_TIMING_LOGS.getBooleanValue()) {
848
- return false;
849
- }
850
- const isVisibilityLogWindow = now < engine.animationTimingVisibilityLogUntil;
851
- if (!isVisibilityLogWindow && Math.abs(sample.offsetMs) < ANIMATION_TIMING_LOG_THRESHOLD_MS) {
852
- return false;
853
- }
854
- const lastLogTime = animationTimingLastLogTimes.get(lineData) ?? 0;
855
- if (now - lastLogTime < ANIMATION_TIMING_LOG_INTERVAL_MS) {
856
- return false;
857
- }
858
- animationTimingLastLogTimes.set(lineData, now);
859
- return true;
860
- }
861
- function logAnimationTiming(engine, reason, lineData, lineIndex, sample, currentTime, accumulatedOffsetMs, learnedOffsetMs = engine.learnedAnimationTimingOffsetMs, residualOffsetMs = sample.offsetMs) {
862
- if (!ENABLE_ANIMATION_TIMING_LOGS.getBooleanValue()) {
863
- return;
864
- }
865
- engine.host.log("WAAPI timing", {
866
- reason,
867
- lineIndex,
868
- lineTimeS: roundedMs(lineData.time * 1000) / 1000,
869
- mediaTimeS: roundedMs(currentTime * 1000) / 1000,
870
- actualTimeMs: roundedMs(sample.actualTimeMs),
871
- expectedTimeMs: roundedMs(sample.expectedTimeMs),
872
- offsetMs: roundedMs(sample.offsetMs),
873
- learnedOffsetMs: roundedMs(learnedOffsetMs),
874
- appliedTimingOffsetMs: roundedMs(sample.appliedTimingOffsetMs),
875
- biasOffsetMs: roundedMs(sample.biasOffsetMs),
876
- residualOffsetMs: roundedMs(residualOffsetMs),
877
- accumulatedOffsetMs: roundedMs(accumulatedOffsetMs),
878
- playState: sample.playState,
879
- text: linePreview(lineData),
880
- });
881
- }
882
- function logAnimationCleanup(engine, reason, lineData, lineIndex, currentTime, staleAnimationEndTime) {
883
- if (!ENABLE_ANIMATION_TIMING_LOGS.getBooleanValue()) {
884
- return;
885
- }
886
- engine.host.log("Animation cleanup", {
887
- reason,
888
- lineIndex,
889
- lineTimeS: roundedMs(lineData.time * 1000) / 1000,
890
- mediaTimeS: roundedMs(currentTime * 1000) / 1000,
891
- staleAnimationEndTimeS: roundedMs(staleAnimationEndTime * 1000) / 1000,
892
- runningAnimationCount: [lineData, ...lineData.parts].reduce((count, part) => count + part.animations.length, 0),
893
- text: linePreview(lineData),
894
- });
895
- }
896
- export function noteVisibilityChange(engine) {
897
- if (!ENABLE_ANIMATION_TIMING_LOGS.getBooleanValue()) {
898
- return;
899
- }
900
- if (!engine.lyricsContainer)
901
- return;
902
- const runningAnimationCount = engine.lines.reduce((count, line) => count + [line, ...line.parts].reduce((lineCount, part) => lineCount + part.animations.length, 0), 0);
903
- if (engine.document.visibilityState === "visible") {
904
- engine.animationTimingVisibilityLogUntil = Date.now() + ANIMATION_TIMING_LOG_WINDOW_MS;
905
- engine.host.log("Visibility changed; keeping WAAPI animations for timing verification", {
906
- visibilityState: engine.document.visibilityState,
907
- runningAnimationCount,
908
- resetSkipped: true,
909
- timingLogWindowMs: ANIMATION_TIMING_LOG_WINDOW_MS,
910
- });
911
- return;
912
- }
913
- engine.host.log("Visibility changed; WAAPI animations left intact", {
914
- visibilityState: engine.document.visibilityState,
915
- runningAnimationCount,
916
- resetSkipped: true,
917
- });
918
- }
919
- function activeTextGradientKeyframes(config) {
920
- return [
921
- {
922
- "--lyric-transition-amount-start": config.highlight.swipeStartFrom,
923
- "--lyric-transition-amount-end": config.highlight.swipeEndFrom,
924
- },
925
- {
926
- "--lyric-transition-amount-start": config.highlight.swipeStartTo,
927
- "--lyric-transition-amount-end": config.highlight.swipeEndTo,
928
- },
929
- ];
930
- }
931
- function activeTextGlowKeyframes(config, part) {
932
- if (part.imageLayers)
933
- return [
934
- { filter: `blur(${config.highlight.imageGlowFrom})`, opacity: config.highlight.imageGlowOpacityFrom },
935
- { filter: `blur(${config.highlight.imageGlowTo})`, opacity: config.highlight.imageGlowOpacityTo },
936
- ];
937
- return [{ filter: config.highlight.glowFrom }, { filter: config.highlight.glowTo }];
938
- }
939
- function activeTextVisibleKeyframes() {
940
- return [{ opacity: 1 }, { opacity: 1 }];
941
- }
942
- function activeTextInstantKeyframes(config) {
943
- return [
944
- {
945
- opacity: 1,
946
- "--lyric-transition-amount-start": config.highlight.swipeStartTo,
947
- "--lyric-transition-amount-end": config.highlight.swipeEndTo,
948
- },
949
- {
950
- opacity: 1,
951
- "--lyric-transition-amount-start": config.highlight.swipeStartTo,
952
- "--lyric-transition-amount-end": config.highlight.swipeEndTo,
953
- },
954
- ];
955
- }
956
- function lineSyncedTextKeyframes(config) {
957
- return [
958
- {
959
- opacity: 0,
960
- "--lyric-transition-amount-start": config.highlight.swipeStartTo,
961
- "--lyric-transition-amount-end": config.highlight.swipeEndTo,
962
- },
963
- {
964
- opacity: 1,
965
- "--lyric-transition-amount-start": config.highlight.swipeStartTo,
966
- "--lyric-transition-amount-end": config.highlight.swipeEndTo,
967
- },
968
- ];
969
- }
970
- function fadeOutTextKeyframes(config, part) {
971
- return [
972
- {
973
- opacity: 1,
974
- filter: part.imageLayers ? "none" : config.highlight.glowTo,
975
- "--lyric-transition-amount-start": config.highlight.swipeStartTo,
976
- "--lyric-transition-amount-end": config.highlight.swipeEndTo,
977
- },
978
- {
979
- opacity: 0,
980
- filter: part.imageLayers ? "none" : config.highlight.glowTo,
981
- "--lyric-transition-amount-start": config.highlight.swipeStartTo,
982
- "--lyric-transition-amount-end": config.highlight.swipeEndTo,
983
- },
984
- ];
985
- }
986
- // null unless the ramp is linear and forward; planLetterMaskSweep sweeps the whole word instead there.
987
- export function computeLetterSwipeWindows(swipe, letterCount, swipeDurationMs) {
988
- if (swipe.easing !== "linear" || swipeDurationMs <= 0 || letterCount <= 0) {
989
- return null;
990
- }
991
- const startFrom = Number.parseFloat(swipe.startFrom);
992
- const startTo = Number.parseFloat(swipe.startTo);
993
- const endFrom = Number.parseFloat(swipe.endFrom);
994
- const endTo = Number.parseFloat(swipe.endTo);
995
- if (![startFrom, startTo, endFrom, endTo].every(Number.isFinite) || startTo <= startFrom || endTo <= endFrom) {
996
- return null;
997
- }
998
- const startAt = (timeMs) => startFrom + ((startTo - startFrom) * timeMs) / swipeDurationMs;
999
- const endAt = (timeMs) => endFrom + ((endTo - endFrom) * timeMs) / swipeDurationMs;
1000
- const timeWhereEnd = (value) => (swipeDurationMs * (value - endFrom)) / (endTo - endFrom);
1001
- const timeWhereStart = (value) => (swipeDurationMs * (value - startFrom)) / (startTo - startFrom);
1002
- const windows = [];
1003
- for (let index = 0; index < letterCount; index++) {
1004
- const beginMs = clamp(timeWhereEnd(index / letterCount), 0, swipeDurationMs);
1005
- const finishMs = clamp(timeWhereStart((index + 1) / letterCount), 0, swipeDurationMs);
1006
- windows.push({
1007
- delayMs: beginMs,
1008
- durationMs: Math.max(finishMs - beginMs, 1),
1009
- from: { start: startAt(beginMs), end: endAt(beginMs) },
1010
- to: { start: startAt(finishMs), end: endAt(finishMs) },
1011
- });
1012
- }
1013
- return windows;
1014
- }
1015
- // Per-letter mask reveal. A linear forward ramp keeps the short windowed animations so a settled letter
1016
- // holds a finished one; any other easing runs the same geometry over the whole duration, letting the
1017
- // theme easing warp when each letter reveals, so it ends revealed rather than swept past.
1018
- export function planLetterMaskSweep(swipe, letterCount, swipeDurationMs, rtl) {
1019
- if (letterCount <= 0)
1020
- return [];
1021
- const windows = computeLetterSwipeWindows({ ...swipe, easing: "linear" }, letterCount, swipeDurationMs);
1022
- if (!windows)
1023
- return [];
1024
- const maskSpan = letterCount + 2;
1025
- const maskPositionAt = (start, index) => {
1026
- const q = (0.5 * maskSpan - (start * letterCount - index)) / (maskSpan - 1);
1027
- return `${(rtl ? 1 - q : q) * 100}% 0%`;
1028
- };
1029
- const linear = swipe.easing === "linear";
1030
- const durationMs = swipeDurationMs > 0 ? swipeDurationMs : 1;
1031
- return windows.map((window, index) => {
1032
- const from = maskPositionAt(window.from.start, index);
1033
- const to = maskPositionAt(window.to.start, index);
1034
- if (linear) {
1035
- return {
1036
- keyframes: [
1037
- { offset: 0, maskPosition: from },
1038
- { offset: 1, maskPosition: to },
1039
- ],
1040
- delayMs: window.delayMs,
1041
- durationMs: window.durationMs,
1042
- easing: "linear",
1043
- };
1044
- }
1045
- const revealStart = clamp(window.delayMs / durationMs, 0, 1);
1046
- const revealEnd = clamp((window.delayMs + window.durationMs) / durationMs, 0, 1);
1047
- const keyframes = [{ offset: 0, maskPosition: from }];
1048
- if (revealStart > 0)
1049
- keyframes.push({ offset: revealStart, maskPosition: from });
1050
- if (revealEnd > revealStart)
1051
- keyframes.push({ offset: revealEnd, maskPosition: to });
1052
- if (revealEnd < 1)
1053
- keyframes.push({ offset: 1, maskPosition: to });
1054
- return { keyframes, delayMs: 0, durationMs, easing: swipe.easing };
1055
- });
1056
- }
1057
- function swipeRamp(config) {
1058
- return {
1059
- easing: config.highlight.swipeEasing,
1060
- startFrom: config.highlight.swipeStartFrom,
1061
- startTo: config.highlight.swipeStartTo,
1062
- endFrom: config.highlight.swipeEndFrom,
1063
- endTo: config.highlight.swipeEndTo,
1064
- };
1065
- }
1066
- // How far through its float a letter crests, as a keyframe offset.
1067
- const LETTER_WAVE_CREST_OFFSET = 0.4;
1068
- // WebRender redraws a cached tile only after a quarter device pixel of movement, so Gecko letters step.
1069
- // An invisible additive opacity ripple changes every frame and forces the redraw.
1070
- const GECKO_REDRAW = isGecko();
1071
- const GECKO_REDRAW_KEYFRAMES = [{ opacity: 0 }, { opacity: -0.002 }, { opacity: 0 }];
1072
- const GECKO_REDRAW_PERIOD_MS = 200;
1073
- // When each letter's wave starts, counted from the start of the word, and how long it lasts. A letter
1074
- // crests just as the swipe finishes lighting it. If the swipe lights it faster than the float rises,
1075
- // it starts early enough to make that, which on a short word means before the word itself does. If the
1076
- // swipe lights it slower, it starts as the swipe touches it and its float stretches to crest on time.
1077
- export function planLetterWave(swipe, letterCount, wordDurationMs, swipeDurationMs, swipeLeadMs, floatDurationMs) {
1078
- const riseMs = floatDurationMs * LETTER_WAVE_CREST_OFFSET;
1079
- const windows = computeLetterSwipeWindows({ ...swipe, easing: "linear" }, letterCount, swipeDurationMs);
1080
- const timings = [];
1081
- for (let index = 0; index < letterCount; index++) {
1082
- if (!windows) {
1083
- // No windows for this ramp, so spread the letters evenly over the word.
1084
- timings.push({ delayMs: (wordDurationMs * index) / letterCount, durationMs: floatDurationMs });
1085
- continue;
1086
- }
1087
- // The swipe runs swipeLeadMs ahead of the word, so take the lead back off.
1088
- const touchedMs = windows[index].delayMs - swipeLeadMs;
1089
- const litMs = touchedMs + windows[index].durationMs;
1090
- if (litMs - riseMs > touchedMs) {
1091
- timings.push({ delayMs: touchedMs, durationMs: (litMs - touchedMs) / LETTER_WAVE_CREST_OFFSET });
1092
- }
1093
- else {
1094
- timings.push({ delayMs: litMs - riseMs, durationMs: floatDurationMs });
1095
- }
1096
- }
1097
- return timings;
1098
- }
1099
- function startRichSyncedHighlightAnimations(engine, part, config, swipeTimeMs, wordTimeMs, swipeDurationMs, glowDurationMs, appliedTimingOffsetMs) {
1100
- const animations = [];
1101
- const highlight = part.highlightElement;
1102
- let swipeAnimation;
1103
- if (config.enabled.highlightSwipe) {
1104
- const swipeTiming = { appliedTimingOffsetMs, offsetMs: swipeTimeMs - wordTimeMs };
1105
- const swipeCurrentTimeMs = correctedAnimationTimeMs(swipeTimeMs, appliedTimingOffsetMs, swipeDurationMs);
1106
- const highlightLetters = part.highlightLetterElements;
1107
- if (highlightLetters && highlightLetters.length > 0) {
1108
- const sweeps = planLetterMaskSweep(swipeRamp(config), highlightLetters.length, swipeDurationMs, part.highlightElement.classList.contains(RTL_CLASS));
1109
- sweeps.forEach((sweep, index) => {
1110
- const targets = [highlightLetters[index], part.imageLayers?.glowLetters[index]].filter((target) => target !== undefined);
1111
- for (const target of targets) {
1112
- const animation = trackLyricAnimationTiming(engine, target.animate(sweep.keyframes.map(frame => ({
1113
- offset: frame.offset,
1114
- maskPosition: frame.maskPosition,
1115
- WebkitMaskPosition: frame.maskPosition,
1116
- })), { duration: sweep.durationMs, delay: sweep.delayMs, easing: sweep.easing, fill: "both" }),
1117
- // The last letter's sweep ends last, so it alone covers the whole word.
1118
- index === sweeps.length - 1 && target === highlightLetters[index]
1119
- ? swipeTiming
1120
- : { ...swipeTiming, skipDriftSample: true });
1121
- animation.currentTime = swipeCurrentTimeMs;
1122
- if (index === 0)
1123
- swipeAnimation = animation;
1124
- animations.push(animation);
1125
- }
1126
- });
1127
- }
1128
- else {
1129
- swipeAnimation = trackLyricAnimationTiming(engine, highlight.animate(activeTextGradientKeyframes(config), {
1130
- duration: swipeDurationMs,
1131
- easing: config.highlight.swipeEasing,
1132
- fill: "forwards",
1133
- }), swipeTiming);
1134
- swipeAnimation.currentTime = swipeCurrentTimeMs;
1135
- animations.push(swipeAnimation);
1136
- }
1137
- }
1138
- const opacityAnimation = trackLyricAnimationTiming(engine, highlight.animate(config.enabled.highlightSwipe ? activeTextVisibleKeyframes() : activeTextInstantKeyframes(config), {
1139
- duration: 1,
1140
- easing: "linear",
1141
- fill: "forwards",
1142
- }), { appliedTimingOffsetMs, offsetMs: 0 });
1143
- opacityAnimation.currentTime = correctedAnimationTimeMs(wordTimeMs, appliedTimingOffsetMs, 1);
1144
- animations.push(opacityAnimation);
1145
- let glowAnimation;
1146
- if (config.enabled.highlightGlow && !part.glowSuppressed) {
1147
- glowAnimation = trackLyricAnimationTiming(engine, (part.imageLayers?.glow ?? highlight).animate(activeTextGlowKeyframes(config, part), {
1148
- duration: glowDurationMs,
1149
- easing: config.highlight.glowEasing,
1150
- fill: part.imageLayers ? "forwards" : config.highlight.glowRestingInvisible ? "none" : "forwards",
1151
- }), { appliedTimingOffsetMs, offsetMs: 0 });
1152
- glowAnimation.currentTime = correctedAnimationTimeMs(wordTimeMs, appliedTimingOffsetMs, glowDurationMs);
1153
- animations.push(glowAnimation);
1154
- }
1155
- return { animations, swipe: swipeAnimation, fade: opacityAnimation, glow: glowAnimation };
1156
- }
1157
- function startLineSyncedHighlightAnimations(engine, part, config, wordTimeMs, glowDurationMs, appliedTimingOffsetMs) {
1158
- const animations = [];
1159
- const fadeInDuration = config.enabled.highlightFade ? config.highlight.fadeInDurationMs : 1;
1160
- const highlight = part.highlightElement;
1161
- const opacityAnimation = trackLyricAnimationTiming(engine, highlight.animate(lineSyncedTextKeyframes(config), {
1162
- duration: fadeInDuration,
1163
- easing: config.enabled.highlightFade ? config.highlight.fadeInEasing : "linear",
1164
- fill: "forwards",
1165
- }), { appliedTimingOffsetMs, offsetMs: 0 });
1166
- opacityAnimation.currentTime = correctedAnimationTimeMs(wordTimeMs, appliedTimingOffsetMs, fadeInDuration);
1167
- animations.push(opacityAnimation);
1168
- let glowAnimation;
1169
- if (config.enabled.highlightGlow && !part.glowSuppressed) {
1170
- glowAnimation = trackLyricAnimationTiming(engine, (part.imageLayers?.glow ?? highlight).animate(activeTextGlowKeyframes(config, part), {
1171
- duration: glowDurationMs,
1172
- easing: config.highlight.glowEasing,
1173
- fill: part.imageLayers ? "forwards" : config.highlight.glowRestingInvisible ? "none" : "forwards",
1174
- }), { appliedTimingOffsetMs, offsetMs: 0 });
1175
- glowAnimation.currentTime = correctedAnimationTimeMs(wordTimeMs, appliedTimingOffsetMs, glowDurationMs);
1176
- animations.push(glowAnimation);
1177
- }
1178
- return { animations, fade: opacityAnimation, glow: glowAnimation };
1179
- }
1180
- function startLineAnimation(engine, lineData, config, currentTime, appliedTimingOffsetMs) {
1181
- resetPartAnimations(lineData);
1182
- const rawElapsedMs = (currentTime - lineData.time) * 1000;
1183
- if (!config.enabled.lineScale) {
1184
- lineData.animations = [];
1185
- return;
1186
- }
1187
- const animation = trackLyricAnimationTiming(engine, lineData.lyricElement.animate([{ transform: config.line.enterFrom }, { transform: config.line.enterTo }], {
1188
- duration: config.line.durationMs,
1189
- easing: config.line.enterEasing,
1190
- fill: "forwards",
1191
- }), { appliedTimingOffsetMs, offsetMs: 0 });
1192
- animation.currentTime = correctedAnimationTimeMs(rawElapsedMs, appliedTimingOffsetMs, config.line.durationMs);
1193
- lineData.animations = [animation];
1194
- }
1195
- function startLineExitAnimation(lineData, config) {
1196
- resetPartAnimations(lineData);
1197
- if (!config.enabled.lineScale) {
1198
- return;
1199
- }
1200
- const animation = lineData.lyricElement.animate([{ transform: config.line.exitFrom }, { transform: config.line.exitTo }], {
1201
- duration: config.line.durationMs,
1202
- easing: config.line.exitEasing,
1203
- fill: "none",
1204
- });
1205
- lineData.animations = [animation];
1206
- animation.addEventListener("finish", () => {
1207
- resetPartAnimations(lineData);
1208
- }, { once: true });
1209
- }
1210
- function startWordAnimations(engine, part, config, currentTime, appliedTimingOffsetMs) {
1211
- resetPartAnimations(part);
1212
- const rawElapsedMs = (currentTime - part.time) * 1000;
1213
- // Providers do ship words that end before they start: one -0.01s word in a Musixmatch richsync
1214
- // was enough to make animate() throw here, and the throw took the rest of the tick with it, so
1215
- // the line never finished setting up and the engine tried it again on every frame.
1216
- const timedDurationMs = Math.max(0, part.duration * 1000);
1217
- const isLineSyncedWord = part.lyricElement.classList.contains(LINE_SYNCED_WORD_CLASS);
1218
- const swipeLeadMs = timedDurationMs * SWIPE_LEAD_RATIO.getNumberValue();
1219
- const swipeTimeMs = rawElapsedMs + swipeLeadMs;
1220
- const wordTimeMs = rawElapsedMs;
1221
- const swipeDurationMs = timedDurationMs * SWIPE_DURATION_RATIO.getNumberValue();
1222
- const glowDurationMs = Math.max(timedDurationMs * config.highlight.glowDurationRatio, config.highlight.glowMinDurationMs);
1223
- const highlightAnimations = isLineSyncedWord
1224
- ? startLineSyncedHighlightAnimations(engine, part, config, wordTimeMs, config.highlight.glowMinDurationMs, appliedTimingOffsetMs)
1225
- : startRichSyncedHighlightAnimations(engine, part, config, swipeTimeMs, wordTimeMs, swipeDurationMs, glowDurationMs, appliedTimingOffsetMs);
1226
- const wobbleAnimations = [];
1227
- if (config.enabled.wordWobble) {
1228
- const wobbleKeyframes = [
1229
- { transform: config.word.wobbleFrom },
1230
- {
1231
- transform: config.word.wobblePeak,
1232
- offset: config.word.wobblePeakOffset,
1233
- easing: config.word.wobblePeakEasing,
1234
- },
1235
- {
1236
- transform: config.word.wobbleSettle,
1237
- offset: Math.max(config.word.wobblePeakOffset, config.word.wobbleSettleOffset),
1238
- },
1239
- { transform: config.word.wobbleTo, easing: config.word.wobbleEndEasing },
1240
- ];
1241
- const wobbleOptions = {
1242
- duration: config.word.wobbleDurationMs,
1243
- easing: config.word.wobbleEasing,
1244
- fill: "forwards",
1245
- };
1246
- const wobbleStartMs = correctedAnimationTimeMs(wordTimeMs, appliedTimingOffsetMs, config.word.wobbleDurationMs);
1247
- for (const wordElement of part.wobbleElements) {
1248
- const animation = trackLyricAnimationTiming(engine, wordElement.animate(wobbleKeyframes, wobbleOptions), {
1249
- appliedTimingOffsetMs,
1250
- offsetMs: 0,
1251
- });
1252
- animation.currentTime = wobbleStartMs;
1253
- wobbleAnimations.push(animation);
1254
- }
1255
- const letters = part.letterElements;
1256
- if (letters && letters.length > 0) {
1257
- const emphasise = part.lyricElement?.dataset.longWord === "true";
1258
- const emphasisPeak = emphasise ? ` scale(${config.letterWave.emphasisScale})` : "";
1259
- const emphasisRest = emphasise ? " scale(1)" : "";
1260
- const floatKeyframes = [
1261
- { transform: `translateY(0)${emphasisRest}`, easing: config.letterWave.riseEasing },
1262
- {
1263
- transform: `${config.letterWave.transform}${emphasisPeak}`,
1264
- offset: LETTER_WAVE_CREST_OFFSET,
1265
- easing: config.letterWave.fallEasing,
1266
- },
1267
- { transform: `${config.letterWave.settle}${emphasisRest}` },
1268
- ];
1269
- const letterCount = letters.length;
1270
- const waves = planLetterWave(swipeRamp(config), letterCount, timedDurationMs, swipeDurationMs, swipeLeadMs, config.letterWave.durationMs);
1271
- // A letter that starts before the word would have a negative delay, which the drift check reads
1272
- // as the wave running behind once it finishes. Run the wave's clock ahead by the head start
1273
- // instead, the way the swipe carries its lead, so every delay stays at zero or above.
1274
- const waveLeadMs = Math.max(0, -Math.min(...waves.map(wave => wave.delayMs)));
1275
- const waveEndsMs = waves.map(wave => wave.delayMs + wave.durationMs);
1276
- const lastWaveEndMs = Math.max(...waveEndsMs);
1277
- const lastEndingWaveIndex = waveEndsMs.lastIndexOf(lastWaveEndMs);
1278
- const cascadeDurationMs = waveLeadMs + lastWaveEndMs;
1279
- const floatStartMs = correctedAnimationTimeMs(wordTimeMs + waveLeadMs, appliedTimingOffsetMs, cascadeDurationMs);
1280
- const floatKeyframeSignature = JSON.stringify(floatKeyframes);
1281
- // Glow letters only show while the glow does: never when it is off or renders nothing for this
1282
- // word, and not once it has faded out. Their waves stop there instead of running to the end.
1283
- const glowLetters = config.enabled.highlightGlow && !part.glowSuppressed ? part.imageLayers?.glowLetters : undefined;
1284
- const glowEndMs = Number.parseFloat(config.highlight.imageGlowOpacityTo) === 0 ? waveLeadMs + glowDurationMs : Infinity;
1285
- const animateLetters = (letters, endMs, sampled) => {
1286
- letters?.forEach((letterElement, index) => {
1287
- const delayMs = waves[index].delayMs + waveLeadMs;
1288
- if (delayMs >= endMs)
1289
- return;
1290
- const endDelayMs = Math.min(0, endMs - delayMs - waves[index].durationMs);
1291
- const animation = trackLyricAnimationTiming(engine, acquireWaveAnimation(engine, letterElement, floatKeyframes, floatKeyframeSignature, {
1292
- duration: waves[index].durationMs,
1293
- delay: delayMs,
1294
- endDelay: endDelayMs,
1295
- fill: "forwards",
1296
- }), {
1297
- appliedTimingOffsetMs,
1298
- offsetMs: waveLeadMs,
1299
- // The wave that ends last covers the whole word. A theme's swipe ramp can make that an early letter.
1300
- skipDriftSample: !sampled || index !== lastEndingWaveIndex,
1301
- });
1302
- animation.currentTime = floatStartMs;
1303
- wobbleAnimations.push(animation);
1304
- if (!GECKO_REDRAW || !sampled)
1305
- return;
1306
- const redraw = trackLyricAnimationTiming(engine, letterElement.animate(GECKO_REDRAW_KEYFRAMES, {
1307
- duration: GECKO_REDRAW_PERIOD_MS,
1308
- iterations: waves[index].durationMs / GECKO_REDRAW_PERIOD_MS,
1309
- delay: delayMs,
1310
- composite: "add",
1311
- }), { appliedTimingOffsetMs, offsetMs: waveLeadMs, skipDriftSample: true });
1312
- redraw.currentTime = floatStartMs;
1313
- wobbleAnimations.push(redraw);
1314
- });
1315
- };
1316
- animateLetters(part.letterElements, Infinity, true);
1317
- animateLetters(part.highlightLetterElements, Infinity, false);
1318
- animateLetters(glowLetters, glowEndMs, false);
1319
- }
1320
- }
1321
- part.animations = [
1322
- ...highlightAnimations.animations,
1323
- ...mirrorImageHighlightAnimations(part, highlightAnimations.animations),
1324
- ...wobbleAnimations,
1325
- ];
1326
- }
1327
- function startLineAnimations(engine, lineData, config, currentTime) {
1328
- const appliedTimingOffsetMs = engine.learnedAnimationTimingOffsetMs;
1329
- startLineAnimation(engine, lineData, config, currentTime, appliedTimingOffsetMs);
1330
- if (lineData.lyricElement.dataset.instrumental === "true") {
1331
- startInstrumentalAnimations(engine, lineData, config, currentTime, appliedTimingOffsetMs);
1332
- return;
1333
- }
1334
- resolveLineGlowSuppression(engine, lineData, config);
1335
- for (const part of lineData.parts) {
1336
- startWordAnimations(engine, part, config, currentTime, appliedTimingOffsetMs);
1337
- }
1338
- }
1339
- function startWordExitAnimation(part, config, imagePaint = []) {
1340
- resetPartAnimations(part);
1341
- const fadeDuration = config.enabled.highlightFade ? config.highlight.fadeOutDurationMs : 1;
1342
- const animation = part.highlightElement.animate(fadeOutTextKeyframes(config, part), {
1343
- duration: fadeDuration,
1344
- easing: config.enabled.highlightFade ? config.highlight.fadeOutEasing : "linear",
1345
- fill: "none",
1346
- });
1347
- part.animations = [animation, ...mirrorImageHighlightAnimations(part, [animation])];
1348
- // Keep the current blur, letter masks and motion visible until the parent fade ends.
1349
- for (const { target, frame } of imagePaint) {
1350
- part.animations.push(target.animate([frame, frame], { duration: fadeDuration, fill: "none" }));
1351
- }
1352
- animation.addEventListener("finish", () => {
1353
- resetPartAnimations(part);
1354
- }, { once: true });
1355
- }
1356
- function startLineExitAnimations(engine, lineData, config, currentTime) {
1357
- // Read the entire line before cancelling any effects, so this does not alternate
1358
- // per-word style reads with writes. There are no extra reads during normal ticks.
1359
- const imagePaint = new Map();
1360
- for (const part of lineData.parts) {
1361
- if (!part.imageLayers || currentTime < part.time)
1362
- continue;
1363
- const style = engine.window.getComputedStyle(part.imageLayers.glow);
1364
- const paint = [
1365
- { target: part.imageLayers.glow, frame: { opacity: style.opacity, filter: style.filter } },
1366
- ];
1367
- for (const target of part.letterElements ?? []) {
1368
- paint.push({ target, frame: { transform: engine.window.getComputedStyle(target).transform } });
1369
- }
1370
- for (const target of [...(part.highlightLetterElements ?? []), ...part.imageLayers.glowLetters]) {
1371
- const letterStyle = engine.window.getComputedStyle(target);
1372
- paint.push({ target, frame: { maskPosition: letterStyle.maskPosition, transform: letterStyle.transform } });
1373
- }
1374
- imagePaint.set(part, paint);
1375
- }
1376
- startLineExitAnimation(lineData, config);
1377
- if (lineData.lyricElement.dataset.instrumental === "true") {
1378
- startInstrumentalExitAnimations(engine, lineData, config, currentTime);
1379
- return;
1380
- }
1381
- for (const part of lineData.parts) {
1382
- if (currentTime >= part.time) {
1383
- startWordExitAnimation(part, config, imagePaint.get(part));
1384
- }
1385
- else {
1386
- resetPartAnimations(part);
1387
- }
1388
- }
1389
- }
1390
- function animateInstrumentalChild(engine, lineData, selector, keyframes, options, timing) {
1391
- const element = lineData.lyricElement.querySelector(selector);
1392
- if (!element)
1393
- return null;
1394
- const animation = timing
1395
- ? trackLyricAnimationTiming(engine, element.animate(keyframes, options), timing)
1396
- : element.animate(keyframes, options);
1397
- lineData.animations.push(animation);
1398
- return animation;
1399
- }
1400
- function startInstrumentalAnimations(engine, lineData, config, currentTime, appliedTimingOffsetMs) {
1401
- const rawElapsedMs = (currentTime - lineData.time) * 1000;
1402
- const durationMs = Math.max(lineData.duration * 1000, 1);
1403
- const fillFadeDuration = config.enabled.instrumental ? config.instrumental.fillFadeDurationMs : 1;
1404
- const fillAnimation = animateInstrumentalChild(engine, lineData, INSTRUMENTAL_FILL_SELECTOR, [{ opacity: 0 }, { opacity: 1 }], {
1405
- duration: fillFadeDuration,
1406
- easing: config.enabled.instrumental ? config.instrumental.fillFadeEasing : "linear",
1407
- fill: "forwards",
1408
- }, { appliedTimingOffsetMs, offsetMs: 0 });
1409
- let fillTravelAnimation = null;
1410
- let waveFlattenAnimation = null;
1411
- let waveOscillationAnimation = null;
1412
- if (config.enabled.instrumental) {
1413
- fillTravelAnimation = animateInstrumentalChild(engine, lineData, INSTRUMENTAL_WAVE_CLIP_SELECTOR, [{ transform: config.instrumental.fillFrom }, { transform: config.instrumental.fillTo }], {
1414
- duration: durationMs,
1415
- easing: config.instrumental.fillEasing,
1416
- fill: "both",
1417
- }, { appliedTimingOffsetMs, offsetMs: 0 });
1418
- waveFlattenAnimation = animateInstrumentalChild(engine, lineData, INSTRUMENTAL_WAVE_PATH_SELECTOR, [{ transform: config.instrumental.waveFrom }, { transform: config.instrumental.waveTo }], {
1419
- duration: durationMs,
1420
- easing: config.instrumental.waveEasing,
1421
- fill: "both",
1422
- }, { appliedTimingOffsetMs, offsetMs: 0 });
1423
- waveOscillationAnimation = animateInstrumentalChild(engine, lineData, INSTRUMENTAL_WAVE_PATH_SELECTOR, [
1424
- { d: config.instrumental.wavePathHigh },
1425
- { d: config.instrumental.wavePathLow, offset: 0.5 },
1426
- { d: config.instrumental.wavePathHigh },
1427
- ], {
1428
- duration: config.instrumental.waveOscillationDurationMs,
1429
- easing: config.instrumental.waveOscillationEasing,
1430
- iterations: Infinity,
1431
- }, {
1432
- appliedTimingOffsetMs,
1433
- offsetMs: 0,
1434
- wrapDurationMs: config.instrumental.waveOscillationDurationMs,
1435
- });
1436
- }
1437
- if (fillAnimation) {
1438
- fillAnimation.currentTime = correctedAnimationTimeMs(rawElapsedMs, appliedTimingOffsetMs, fillFadeDuration);
1439
- }
1440
- for (const animation of [fillTravelAnimation, waveFlattenAnimation]) {
1441
- if (animation) {
1442
- animation.currentTime = correctedAnimationTimeMs(rawElapsedMs, appliedTimingOffsetMs, durationMs);
1443
- }
1444
- }
1445
- if (waveOscillationAnimation) {
1446
- waveOscillationAnimation.currentTime = correctedWrappedAnimationTimeMs(rawElapsedMs, appliedTimingOffsetMs, Math.max(config.instrumental.waveOscillationDurationMs, 1));
1447
- }
1448
- }
1449
- function startInstrumentalExitAnimations(engine, lineData, config, currentTime) {
1450
- if (currentTime < lineData.time)
1451
- return;
1452
- const fadeDuration = config.enabled.instrumental && config.enabled.highlightFade ? config.highlight.fadeOutDurationMs : 1;
1453
- animateInstrumentalChild(engine, lineData, INSTRUMENTAL_FILL_SELECTOR, [{ opacity: 1 }, { opacity: 0 }], {
1454
- duration: fadeDuration,
1455
- easing: config.enabled.instrumental ? config.highlight.fadeOutEasing : "linear",
1456
- fill: "none",
1457
- });
1458
- }
1459
- export function clearStyleCaches(engine) {
1460
- dropPendingLineScroll(engine);
1461
- engine.cachedDurations.clear();
1462
- engine.cachedCSSValues.clear();
1463
- engine.cachedAnimationSettings = null;
1464
- engine.cachedLineScrollTiming.clear();
1465
- }
1466
- function getCSSValue(engine, lyricsElement, property, fallback) {
1467
- let value = engine.cachedCSSValues.get(property);
1468
- if (value === undefined) {
1469
- value = engine.window.getComputedStyle(lyricsElement).getPropertyValue(property).trim() || fallback;
1470
- engine.cachedCSSValues.set(property, value);
1471
- }
1472
- return value;
1473
- }
1474
- /**
1475
- * Gets and caches a css duration.
1476
- * The cache belongs to one engine instance, which resolves every lookup against its own lyrics
1477
- * container, so this function does not key its cache on the element provided -- it assumes that
1478
- * it isn't relevant to the calling code
1479
- *
1480
- * @param lyricsElement - the element to look up against
1481
- * @param property - the css property to look up
1482
- * @return - in ms
1483
- */
1484
- function getCSSDurationInMs(engine, lyricsElement, property) {
1485
- let duration = engine.cachedDurations.get(property);
1486
- if (duration === undefined) {
1487
- duration = toMs(getCSSValue(engine, lyricsElement, property, "0ms"));
1488
- engine.cachedDurations.set(property, duration);
1489
- }
1490
- return duration;
1491
- }
1492
- function getCSSDurationWithFallback(engine, lyricsElement, property, fallback) {
1493
- return Math.max(toMs(getCSSValue(engine, lyricsElement, property, fallback)), 1);
1494
- }
1495
- function getCSSNumber(engine, lyricsElement, property, fallback) {
1496
- const value = Number.parseFloat(getCSSValue(engine, lyricsElement, property, `${fallback}`));
1497
- return Number.isFinite(value) ? value : fallback;
1498
- }
1499
- function getCSSBoolean(engine, lyricsElement, property, fallback) {
1500
- const value = getCSSValue(engine, lyricsElement, property, fallback ? "1" : "0").toLowerCase();
1501
- if (value === "false" || value === "off" || value === "none")
1502
- return false;
1503
- const numericValue = Number.parseFloat(value);
1504
- if (Number.isFinite(numericValue))
1505
- return numericValue > 0;
1506
- return fallback;
1507
- }
1508
- function getCSSOffset(engine, lyricsElement, property, fallback) {
1509
- return Math.max(0, Math.min(1, getCSSNumber(engine, lyricsElement, property, fallback)));
1510
- }
1511
- // The comment setting is shared by every view in a bundle; the custom property lets a theme scope it to one.
1512
- function getTargetScrollRatio(engine, lyricsElement) {
1513
- const scoped = Number.parseFloat(getCSSValue(engine, lyricsElement, "--blyrics-target-scroll-pos-ratio", ""));
1514
- return Number.isFinite(scoped) ? Math.max(0, Math.min(1, scoped)) : SCROLL_POS_OFFSET_RATIO.getNumberValue();
1515
- }
1516
- // Compose the glow filter so the color stays an unresolved var(--blyrics-glow-color).
1517
- // Reading a fully composed --blyrics-highlight-glow-filter-* off the container resolves the
1518
- // nested color there, which would defeat per-word overrides like
1519
- // .blyrics--word[data-long-word] { --blyrics-glow-color: ... }. Building the filter here with
1520
- // the color left as a literal var lets the Web Animations API resolve it against each animated
1521
- // word instead. A theme that sets the full filter var still wins, but its color resolves once
1522
- // at the container (globally), as before.
1523
- // A glow whose resolved color falls below half a quantization step stays invisible even after the
1524
- // blur spreads it, so the per-frame drop-shadow can be skipped with no pixel changing.
1525
- const GLOW_INVISIBLE_ALPHA = 0.5 / 255;
1526
- function alphaToken(token) {
1527
- const value = token.endsWith("%") ? Number.parseFloat(token) / 100 : Number.parseFloat(token);
1528
- return clamp(value, 0, 1);
1529
- }
1530
- // null for an unrecognized format, which the caller treats as opaque so a visible glow is never dropped.
1531
- export function parseColorAlpha(value) {
1532
- const color = value.trim().toLowerCase();
1533
- if (color === "")
1534
- return null;
1535
- if (color === "transparent")
1536
- return 0;
1537
- const slashAlpha = color.match(/\/\s*([0-9]*\.?[0-9]+%?)\s*\)\s*$/);
1538
- if (slashAlpha)
1539
- return alphaToken(slashAlpha[1]);
1540
- const commaAlpha = color.match(/^(?:rgba|hsla)\([^)]*,\s*([0-9]*\.?[0-9]+%?)\s*\)$/);
1541
- if (commaAlpha)
1542
- return alphaToken(commaAlpha[1]);
1543
- const hex = color.match(/^#([0-9a-f]{4}|[0-9a-f]{8})$/);
1544
- if (hex) {
1545
- const digits = hex[1];
1546
- const alphaHex = digits.length === 8 ? digits.slice(6) : digits.slice(3).repeat(2);
1547
- return Number.parseInt(alphaHex, 16) / 255;
1548
- }
1549
- const opaqueFunction = /^(?:rgb|hsl|hwb|lab|lch|oklab|oklch|color)\(/.test(color);
1550
- const opaqueHex = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/.test(color);
1551
- const namedColor = /^[a-z]+$/.test(color);
1552
- if (opaqueFunction || opaqueHex || namedColor)
1553
- return 1;
1554
- return null;
1555
- }
1556
- // Per-word glow is resolved only when the container glow already renders nothing, so an empty word
1557
- // drops its blur while a word a theme lit up keeps it.
1558
- function resolveLineGlowSuppression(engine, lineData, config) {
1559
- if (lineData.parts.some(part => part.imageLayers) || config.highlight.glowContainerAlpha >= GLOW_INVISIBLE_ALPHA) {
1560
- for (const part of lineData.parts)
1561
- part.glowSuppressed = false;
1562
- return;
1563
- }
1564
- for (const part of lineData.parts) {
1565
- const color = engine.window.getComputedStyle(part.highlightElement).getPropertyValue("--blyrics-glow-color");
1566
- part.glowSuppressed = (parseColorAlpha(color) ?? 1) < GLOW_INVISIBLE_ALPHA;
1567
- }
1568
- }
1569
- function resolveGlowFilter(engine, lyricsElement, suffix, radiusDefault) {
1570
- const override = getCSSValue(engine, lyricsElement, `--blyrics-highlight-glow-filter-${suffix}`, "");
1571
- if (override)
1572
- return override;
1573
- const radius = getCSSValue(engine, lyricsElement, `--blyrics-highlight-glow-radius-${suffix}`, radiusDefault);
1574
- return `drop-shadow(0 0 ${radius} var(--blyrics-glow-color))`;
1575
- }
1576
- // Only the engine's own drop-shadow(0 0 <radius> ...) resting shape counts, so a theme override or a
1577
- // non-zero radius keeps its permanent glow on fill:forwards.
1578
- function isGlowRestingInvisible(glowTo) {
1579
- const value = glowTo.trim();
1580
- if (value === "" || value === "none")
1581
- return true;
1582
- const match = value.match(/^drop-shadow\(\s*0\s+0\s+(\S+)\s+var\(--blyrics-glow-color\)\)$/);
1583
- return match ? Number.parseFloat(match[1]) === 0 : false;
1584
- }
1585
- function readAnimationConfig(engine, lyricsElement) {
1586
- const prefersReducedMotion = engine.window.matchMedia(REDUCED_MOTION_QUERY).matches;
1587
- const scrollEasing = getCSSValue(engine, lyricsElement, "--blyrics-lyric-scroll-timing-function", "cubic-bezier(0.86, 0, 0.2, 1)");
1588
- return {
1589
- enabled: {
1590
- lineScale: getCSSBoolean(engine, lyricsElement, "--blyrics-animate-line-scale", true),
1591
- wordWobble: getCSSBoolean(engine, lyricsElement, "--blyrics-animate-word-wobble", true),
1592
- highlightSwipe: getCSSBoolean(engine, lyricsElement, "--blyrics-animate-highlight-swipe", true),
1593
- highlightGlow: getCSSBoolean(engine, lyricsElement, "--blyrics-animate-highlight-glow", true),
1594
- highlightFade: getCSSBoolean(engine, lyricsElement, "--blyrics-animate-highlight-fade", true),
1595
- scroll: getCSSBoolean(engine, lyricsElement, "--blyrics-animate-scroll", true),
1596
- instrumental: getCSSBoolean(engine, lyricsElement, "--blyrics-animate-instrumental", true),
1597
- },
1598
- line: {
1599
- durationMs: getCSSDurationWithFallback(engine, lyricsElement, "--blyrics-scale-transition-duration", "0.166s"),
1600
- enterEasing: getCSSValue(engine, lyricsElement, "--blyrics-line-enter-easing", "ease"),
1601
- exitEasing: getCSSValue(engine, lyricsElement, "--blyrics-line-exit-easing", "ease"),
1602
- enterFrom: getCSSValue(engine, lyricsElement, "--blyrics-line-enter-transform-from", "scale(var(--blyrics-scale))"),
1603
- enterTo: getCSSValue(engine, lyricsElement, "--blyrics-line-enter-transform-to", "scale(var(--blyrics-active-scale))"),
1604
- exitFrom: getCSSValue(engine, lyricsElement, "--blyrics-line-exit-transform-from", "scale(var(--blyrics-active-scale))"),
1605
- exitTo: getCSSValue(engine, lyricsElement, "--blyrics-line-exit-transform-to", "scale(var(--blyrics-scale))"),
1606
- },
1607
- highlight: {
1608
- fadeInDurationMs: getCSSDurationWithFallback(engine, lyricsElement, "--blyrics-lyric-highlight-fade-in-duration", "0.33s"),
1609
- fadeOutDurationMs: getCSSDurationWithFallback(engine, lyricsElement, "--blyrics-lyric-highlight-fade-out-duration", "0.5s"),
1610
- fadeInEasing: getCSSValue(engine, lyricsElement, "--blyrics-lyric-highlight-fade-in-easing", "ease"),
1611
- fadeOutEasing: getCSSValue(engine, lyricsElement, "--blyrics-lyric-highlight-fade-out-easing", "ease"),
1612
- swipeEasing: getCSSValue(engine, lyricsElement, "--blyrics-highlight-swipe-easing", "linear"),
1613
- swipeStartFrom: getCSSValue(engine, lyricsElement, "--blyrics-highlight-swipe-start-from", "-0.2"),
1614
- swipeEndFrom: getCSSValue(engine, lyricsElement, "--blyrics-highlight-swipe-end-from", "-0.1"),
1615
- swipeStartTo: getCSSValue(engine, lyricsElement, "--blyrics-highlight-swipe-start-to", "1.4"),
1616
- swipeEndTo: getCSSValue(engine, lyricsElement, "--blyrics-highlight-swipe-end-to", "1.5"),
1617
- imageGlowFrom: getCSSValue(engine, lyricsElement, "--blyrics-highlight-glow-radius-from", "0.8rem"),
1618
- imageGlowTo: getCSSValue(engine, lyricsElement, "--blyrics-highlight-glow-radius-to", "0px"),
1619
- imageGlowOpacityFrom: getCSSValue(engine, lyricsElement, "--blyrics-image-glow-opacity-from", "0.5"),
1620
- imageGlowOpacityTo: getCSSValue(engine, lyricsElement, "--blyrics-image-glow-opacity-to", "0"),
1621
- glowFrom: resolveGlowFilter(engine, lyricsElement, "from", "0.8rem"),
1622
- glowTo: resolveGlowFilter(engine, lyricsElement, "to", "0"),
1623
- glowDurationRatio: getCSSNumber(engine, lyricsElement, "--blyrics-highlight-glow-duration-ratio", 1.2),
1624
- glowMinDurationMs: getCSSDurationWithFallback(engine, lyricsElement, "--blyrics-highlight-glow-min-duration", "1.2s"),
1625
- glowEasing: getCSSValue(engine, lyricsElement, "--blyrics-highlight-glow-easing", "ease"),
1626
- glowContainerAlpha: parseColorAlpha(getCSSValue(engine, lyricsElement, "--blyrics-glow-color", "")) ?? 1,
1627
- glowRestingInvisible: isGlowRestingInvisible(resolveGlowFilter(engine, lyricsElement, "to", "0")),
1628
- },
1629
- word: {
1630
- wobbleDurationMs: getCSSDurationWithFallback(engine, lyricsElement, "--blyrics-wobble-duration", "1s"),
1631
- wobbleEasing: getCSSValue(engine, lyricsElement, "--blyrics-word-wobble-easing", "ease"),
1632
- wobblePeakEasing: getCSSValue(engine, lyricsElement, "--blyrics-word-wobble-peak-easing", "ease-in-out"),
1633
- wobbleEndEasing: getCSSValue(engine, lyricsElement, "--blyrics-word-wobble-end-easing", "ease-out"),
1634
- wobbleFrom: getCSSValue(engine, lyricsElement, "--blyrics-word-wobble-transform-from", "scaleX(1)"),
1635
- wobblePeak: getCSSValue(engine, lyricsElement, "--blyrics-word-wobble-transform-peak", "translateX(0.05em) scaleX(1.025)"),
1636
- wobbleSettle: getCSSValue(engine, lyricsElement, "--blyrics-word-wobble-transform-settle", "translateX(0) scaleX(1)"),
1637
- wobbleTo: getCSSValue(engine, lyricsElement, "--blyrics-word-wobble-transform-to", "scaleX(1)"),
1638
- wobblePeakOffset: getCSSOffset(engine, lyricsElement, "--blyrics-word-wobble-peak-offset", 0.125),
1639
- wobbleSettleOffset: getCSSOffset(engine, lyricsElement, "--blyrics-word-wobble-settle-offset", 0.75),
1640
- },
1641
- letterWave: {
1642
- transform: getCSSValue(engine, lyricsElement, "--blyrics-letter-wave-transform", "translateY(-0.06em)"),
1643
- settle: getCSSValue(engine, lyricsElement, "--blyrics-letter-wave-settle", "translateY(-0.05em)"),
1644
- emphasisScale: getCSSValue(engine, lyricsElement, "--blyrics-letter-wave-emphasis-scale", "1.08"),
1645
- durationMs: getCSSDurationWithFallback(engine, lyricsElement, "--blyrics-letter-wave-duration", "0.9s"),
1646
- riseEasing: getCSSValue(engine, lyricsElement, "--blyrics-letter-wave-rise-easing", "ease-in-out"),
1647
- fallEasing: getCSSValue(engine, lyricsElement, "--blyrics-letter-wave-fall-easing", "ease-in-out"),
1648
- },
1649
- instrumental: {
1650
- fillFadeDurationMs: getCSSDurationWithFallback(engine, lyricsElement, "--blyrics-instrumental-fill-fade-duration", "150ms"),
1651
- fillFadeEasing: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-fill-fade-easing", "ease"),
1652
- fillFrom: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-fill-transform-from", "translateY(78%)"),
1653
- fillTo: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-fill-transform-to", "translateY(-4%)"),
1654
- fillEasing: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-fill-easing", "linear"),
1655
- waveFrom: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-wave-transform-from", "scaleY(1.2)"),
1656
- waveTo: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-wave-transform-to", "scaleY(0.0001)"),
1657
- waveEasing: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-wave-easing", "ease-in"),
1658
- wavePathHigh: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-wave-path-high", INSTRUMENTAL_WAVE_PATH_HIGH_FALLBACK),
1659
- wavePathLow: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-wave-path-low", INSTRUMENTAL_WAVE_PATH_LOW_FALLBACK),
1660
- waveOscillationDurationMs: getCSSDurationWithFallback(engine, lyricsElement, "--blyrics-instrumental-wave-oscillation-duration", "1.25s"),
1661
- waveOscillationEasing: getCSSValue(engine, lyricsElement, "--blyrics-instrumental-wave-oscillation-easing", "ease-in-out"),
1662
- },
1663
- lineScroll: {
1664
- easing: scrollEasing,
1665
- differentialEffects: !prefersReducedMotion,
1666
- },
1667
- };
1668
- }
1669
- function readScrollTiming() {
1670
- return { earlyScrollConsiderS: Math.max(0, EARLY_SCROLL_CONSIDER.getNumberValue()) };
1671
- }
1672
- function getAnimationSettings(engine, lyricsElement) {
1673
- if (!engine.cachedAnimationSettings) {
1674
- const config = readAnimationConfig(engine, lyricsElement);
1675
- engine.cachedAnimationSettings = {
1676
- config,
1677
- scrollTiming: readScrollTiming(),
1678
- };
1679
- }
1680
- return engine.cachedAnimationSettings;
1681
- }
1682
- function clearLineScrollAnimations(engine) {
1683
- const records = engine.lineScrollAnimations;
1684
- engine.lineScrollAnimations = [];
1685
- for (const record of records) {
1686
- record.animation.cancel();
1687
- clearLineScrollInlineProperties(engine, record.lineElement, record.token);
1688
- }
1689
- }
1690
- function removeLineScrollAnimation(engine, record) {
1691
- const index = engine.lineScrollAnimations.indexOf(record);
1692
- if (index !== -1) {
1693
- engine.lineScrollAnimations.splice(index, 1);
1694
- }
1695
- clearLineScrollInlineProperties(engine, record.lineElement, record.token);
1696
- }
1697
- function trackLineScrollAnimation(engine, animation, lineElement, token) {
1698
- const record = { animation, lineElement, token };
1699
- engine.lineScrollAnimations.push(record);
1700
- animation.addEventListener("finish", () => removeLineScrollAnimation(engine, record), { once: true });
1701
- animation.addEventListener("cancel", () => removeLineScrollAnimation(engine, record), { once: true });
1702
- }
1703
- function lineScrollSide(relativeIndex, scrollDeltaPx) {
1704
- const isScrollingUp = scrollDeltaPx < 0;
1705
- if (relativeIndex < 0)
1706
- return isScrollingUp ? "below" : "above";
1707
- if (relativeIndex > 0)
1708
- return isScrollingUp ? "above" : "below";
1709
- return "active";
1710
- }
1711
- function setLineScrollSettingProperty(lineElement, property, setting) {
1712
- const value = setting.getStringValue().trim();
1713
- if (value) {
1714
- lineElement.style.setProperty(property, value);
1715
- }
1716
- else {
1717
- lineElement.style.removeProperty(property);
1718
- }
1719
- }
1720
- function setLineScrollStyleProperties(lineElement) {
1721
- for (const [property, setting] of LINE_SCROLL_STYLE_SETTINGS) {
1722
- setLineScrollSettingProperty(lineElement, property, setting);
1723
- }
1724
- }
1725
- function lineScrollTranslate(side, state, useDifferentialEffects) {
1726
- const sideProperty = `--blyrics-line-scroll-${side}-translate-y-${state}`;
1727
- const sharedProperty = `--blyrics-line-scroll-translate-y-${state}`;
1728
- const fallback = state === "start" ? "var(--blyrics-line-scroll-delta-px, 0px)" : "0px";
1729
- if (useDifferentialEffects) {
1730
- return `0 var(${sideProperty}, var(${sharedProperty}, ${fallback}))`;
1731
- }
1732
- return `0 var(${sharedProperty}, ${fallback})`;
1733
- }
1734
- function normalizedTranslate(translateValue) {
1735
- const translate = translateValue.trim();
1736
- return translate && translate !== "none" ? translate : "0px 0px";
1737
- }
1738
- function restoreInlineStyleProperty(lineElement, property, previousValue, previousPriority) {
1739
- if (previousValue) {
1740
- lineElement.style.setProperty(property, previousValue, previousPriority);
1741
- }
1742
- else {
1743
- lineElement.style.removeProperty(property);
1744
- }
1745
- }
1746
- function lineScrollDurationProperty(side, fallbackMs, useDifferentialEffects) {
1747
- return useDifferentialEffects
1748
- ? `var(--blyrics-line-scroll-${side}-duration, var(--blyrics-line-scroll-duration, ${fallbackMs}ms))`
1749
- : `var(--blyrics-line-scroll-duration, ${fallbackMs}ms)`;
1750
- }
1751
- function clearLineScrollInlineProperties(engine, lineElement, token) {
1752
- if (token !== undefined && engine.lineScrollElementTokens.get(lineElement) !== token) {
1753
- return;
1754
- }
1755
- for (const property of LINE_SCROLL_INLINE_PROPERTIES) {
1756
- lineElement.style.removeProperty(property);
1757
- }
1758
- engine.lineScrollElementTokens.delete(lineElement);
1759
- }
1760
- function lineScrollEasingProperty(side, keyframe, fallback, useDifferentialEffects) {
1761
- return useDifferentialEffects
1762
- ? `var(--blyrics-line-scroll-${side}-${keyframe}-easing, var(--blyrics-line-scroll-${keyframe}-easing, var(--blyrics-line-scroll-timing-function, ${fallback})))`
1763
- : `var(--blyrics-line-scroll-${keyframe}-easing, var(--blyrics-line-scroll-timing-function, ${fallback}))`;
1764
- }
1765
- /**
1766
- * Resolves one temporary computed-style probe for every visible line. Keeping
1767
- * each property in its own write/read/restore phase preserves the original
1768
- * resolver semantics while reducing N style flushes to one flush per probe.
1769
- */
1770
- function batchResolveLineScrollProperty(engine, items, property, probeValue, readValue) {
1771
- const previous = items.map(item => ({
1772
- value: item.lineElement.style.getPropertyValue(property),
1773
- priority: item.lineElement.style.getPropertyPriority(property),
1774
- }));
1775
- for (const item of items) {
1776
- item.lineElement.style.setProperty(property, probeValue(item), "important");
1777
- }
1778
- const values = items.map(item => readValue(engine.window.getComputedStyle(item.lineElement)));
1779
- for (let index = 0; index < items.length; index++) {
1780
- restoreInlineStyleProperty(items[index].lineElement, property, previous[index].value, previous[index].priority);
1781
- }
1782
- return values;
1783
- }
1784
- function isLineVisibleDuringScroll(lineData, fromScrollTop, toScrollTop, viewportHeight) {
1785
- const visibleTop = Math.min(fromScrollTop, toScrollTop);
1786
- const visibleBottom = Math.max(fromScrollTop + viewportHeight, toScrollTop + viewportHeight);
1787
- const lineTop = lineData.position;
1788
- const lineBottom = lineData.position + lineData.height;
1789
- return lineBottom >= visibleTop && lineTop <= visibleBottom;
1790
- }
1791
- function clearVisibleLyricWillChange(engine) {
1792
- for (const element of engine.visibleWillChangeElements) {
1793
- element.style.removeProperty("will-change");
1794
- }
1795
- engine.visibleWillChangeElements = new Set();
1796
- }
1797
- // Near-viewport lines come from the intersection observer with one viewport of overscan, not from
1798
- // scrollTop, because a scaled/transformed scroll decouples layout coords from what is on screen.
1799
- const LINE_CULL_ROOT_MARGIN = "100% 0px 100% 0px";
1800
- function cullLine(element) {
1801
- element.style.setProperty("content-visibility", "auto");
1802
- }
1803
- function uncullLine(element) {
1804
- element.style.removeProperty("content-visibility");
1805
- }
1806
- function clearOffscreenLineCulling(engine) {
1807
- for (const element of engine.culledLineElements) {
1808
- uncullLine(element);
1809
- }
1810
- engine.culledLineElements = new Set();
1811
- }
1812
- // Rebuilt rather than updated on every line change or relayout, so a skipped line's placeholder height
1813
- // is always freshly measured. Without IntersectionObserver every line stays rendered.
1814
- export function setupLineCullObserver(engine) {
1815
- engine.lineCullObserver?.disconnect();
1816
- clearOffscreenLineCulling(engine);
1817
- if (engine.layout === "stage") {
1818
- engine.lineCullObserver = null;
1819
- return;
1820
- }
1821
- const ObserverConstructor = engine.window.IntersectionObserver;
1822
- if (typeof ObserverConstructor !== "function" || engine.lines.length === 0) {
1823
- engine.lineCullObserver = null;
1824
- return;
1825
- }
1826
- // Scroll anchoring would compensate residual cull height-shifts with a scroll the engine misreads as the user's (Firefox); the engine owns scrollTop, so disable it.
1827
- engine.host.getScrollElement()?.style.setProperty("overflow-anchor", "none");
1828
- // Pin each line's skipped placeholder to its last rendered size, so skipping a line never shifts the
1829
- // container's scroll height, which the engine would misread as a user scroll.
1830
- const restingHeights = engine.lines.map(line => line.lyricElement.offsetHeight);
1831
- engine.lines.forEach((line, index) => {
1832
- line.lyricElement.style.setProperty("contain-intrinsic-block-size", `auto ${restingHeights[index]}px`);
1833
- });
1834
- const observer = new ObserverConstructor(entries => {
1835
- for (const entry of entries) {
1836
- const element = entry.target;
1837
- if (entry.isIntersecting) {
1838
- if (engine.culledLineElements.delete(element))
1839
- uncullLine(element);
1840
- }
1841
- else if (!engine.culledLineElements.has(element)) {
1842
- cullLine(element);
1843
- engine.culledLineElements.add(element);
1844
- }
1845
- }
1846
- }, { root: null, rootMargin: LINE_CULL_ROOT_MARGIN, threshold: 0 });
1847
- for (const line of engine.lines) {
1848
- observer.observe(line.lyricElement);
1849
- }
1850
- engine.lineCullObserver = observer;
1851
- }
1852
- function updateVisibleLyricWillChange(engine, lines, fromScrollTop, toScrollTop, viewportHeight) {
1853
- const nextVisibleElements = new Set();
1854
- for (const line of lines) {
1855
- if (isLineVisibleDuringScroll(line, fromScrollTop, toScrollTop, viewportHeight)) {
1856
- line.lyricElement.style.setProperty("will-change", LINE_SCROLL_WILL_CHANGE_VALUE);
1857
- nextVisibleElements.add(line.lyricElement);
1858
- }
1859
- }
1860
- for (const element of engine.visibleWillChangeElements) {
1861
- if (!nextVisibleElements.has(element)) {
1862
- element.style.removeProperty("will-change");
1863
- }
1864
- }
1865
- engine.visibleWillChangeElements = nextVisibleElements;
1866
- }
1867
- // The credits and the footer after the last line scroll with the lines. Their bounds come from the
1868
- // relayout-time cache, not a getBoundingClientRect here, which would force a synchronous recalc
1869
- // mid-tick after the scroll commit dirtied style.
1870
- function getLineScrollItems(engine, lines) {
1871
- const trailing = [engine.cachedCreditsItem, engine.cachedFooterItem].filter(item => item !== null);
1872
- return trailing.length > 0 ? [...lines, ...trailing] : lines;
1873
- }
1874
- function measureTrailingItem(lyricsElement, className) {
1875
- const element = lyricsElement.querySelector(`:scope > .${className}`);
1876
- if (!element)
1877
- return null;
1878
- const bounds = getRelativeLayoutBounds(lyricsElement, element);
1879
- return { lyricElement: element, position: bounds.y, height: bounds.height };
1880
- }
1881
- // A leading line slower than the one behind closes their gap by distance times progress difference.
1882
- function lineScrollStaggerScale(lines, activeLineIndex, scrollDistancePx, naturalAdvance) {
1883
- if (naturalAdvance)
1884
- return 1;
1885
- const active = lines[activeLineIndex];
1886
- const steps = [lines[activeLineIndex - 1], lines[activeLineIndex + 1]]
1887
- .filter(neighbour => neighbour !== undefined)
1888
- .map(neighbour => Math.abs(active.position - neighbour.position));
1889
- const stepPx = steps.length > 0 ? Math.min(...steps) : active.height;
1890
- return Math.min(1, stepPx / scrollDistancePx);
1891
- }
1892
- function prepareLineScrollOffsets(engine, lines, activeLineIndex, scrollDeltaPx, fromScrollTop, toScrollTop, viewportHeight, config, naturalAdvance) {
1893
- if (!config.enabled.scroll || activeLineIndex < 0) {
1894
- return null;
1895
- }
1896
- const scrollDistancePx = Math.abs(scrollDeltaPx);
1897
- const translateThemed = LINE_SCROLL_TRANSLATE_SETTINGS.some(setting => setting.isManuallySet());
1898
- const defaultStartTranslate = `0px ${scrollDeltaPx}px`;
1899
- // Preserve the original windowing exactly: only lines intersecting the
1900
- // union of the old and new viewports receive scroll animations.
1901
- const requests = [];
1902
- for (let index = 0; index < lines.length; index++) {
1903
- if (!isLineVisibleDuringScroll(lines[index], fromScrollTop, toScrollTop, viewportHeight)) {
1904
- continue;
1905
- }
1906
- const lineElement = lines[index].lyricElement;
1907
- const relativeIndex = index - activeLineIndex;
1908
- const side = lineScrollSide(relativeIndex, scrollDeltaPx);
1909
- const token = ++engine.lineScrollAnimationToken;
1910
- engine.lineScrollElementTokens.set(lineElement, token);
1911
- const item = { lineElement, side, token };
1912
- const timingKey = `${side}|${Math.abs(relativeIndex)}`;
1913
- requests.push({ item, index, relativeIndex, timingKey, timing: engine.cachedLineScrollTiming.get(timingKey) });
1914
- }
1915
- // The line-scroll vars reach the DOM only for an uncached line, or every line when a theme drives the
1916
- // translate off them, so an otherwise-cached scroll leaves the visible lines untouched.
1917
- const linesToWrite = requests.filter(request => translateThemed || !request.timing);
1918
- for (const { item, index, relativeIndex } of linesToWrite) {
1919
- const lineElement = item.lineElement;
1920
- lineElement.style.setProperty(LINE_SCROLL_INDEX_PROPERTY, String(index));
1921
- lineElement.style.setProperty(LINE_SCROLL_ACTIVE_INDEX_PROPERTY, String(activeLineIndex));
1922
- lineElement.style.setProperty(LINE_SCROLL_RELATIVE_INDEX_PROPERTY, String(relativeIndex));
1923
- lineElement.style.setProperty(LINE_SCROLL_ABS_RELATIVE_INDEX_PROPERTY, String(Math.abs(relativeIndex)));
1924
- lineElement.style.setProperty(LINE_SCROLL_SIDE_PROPERTY, item.side);
1925
- lineElement.style.setProperty(LINE_SCROLL_DELTA_PROPERTY, `${scrollDeltaPx}px`);
1926
- lineElement.style.setProperty(LINE_SCROLL_DISTANCE_PROPERTY, `${scrollDistancePx}px`);
1927
- setLineScrollStyleProperties(lineElement);
1928
- }
1929
- const misses = requests.filter(request => !request.timing);
1930
- if (misses.length > 0) {
1931
- const missItems = misses.map(request => request.item);
1932
- const durations = batchResolveLineScrollProperty(engine, missItems, "transition-duration", item => lineScrollDurationProperty(item.side, LINE_SCROLL_FALLBACK_DURATION_MS, config.lineScroll.differentialEffects), style => {
1933
- const durationMs = toMs(style.transitionDuration.split(",")[0].trim());
1934
- return durationMs > 0 ? durationMs : LINE_SCROLL_FALLBACK_DURATION_MS;
1935
- });
1936
- const startEasings = batchResolveLineScrollProperty(engine, missItems, "transition-timing-function", item => lineScrollEasingProperty(item.side, "start", config.lineScroll.easing, config.lineScroll.differentialEffects), style => style.transitionTimingFunction.trim() || config.lineScroll.easing);
1937
- const endEasings = batchResolveLineScrollProperty(engine, missItems, "transition-timing-function", item => lineScrollEasingProperty(item.side, "end", config.lineScroll.easing, config.lineScroll.differentialEffects), style => style.transitionTimingFunction.trim() || config.lineScroll.easing);
1938
- misses.forEach((request, resolveIndex) => {
1939
- const timing = {
1940
- durationMs: durations[resolveIndex],
1941
- startEasing: startEasings[resolveIndex],
1942
- endEasing: endEasings[resolveIndex],
1943
- };
1944
- engine.cachedLineScrollTiming.set(request.timingKey, timing);
1945
- request.timing = timing;
1946
- });
1947
- }
1948
- let startTranslates = null;
1949
- let endTranslates = null;
1950
- if (translateThemed) {
1951
- const items = requests.map(request => request.item);
1952
- startTranslates = batchResolveLineScrollProperty(engine, items, "translate", item => lineScrollTranslate(item.side, "start", config.lineScroll.differentialEffects), style => normalizedTranslate(style.translate));
1953
- endTranslates = batchResolveLineScrollProperty(engine, items, "translate", item => lineScrollTranslate(item.side, "end", config.lineScroll.differentialEffects), style => normalizedTranslate(style.translate));
1954
- }
1955
- const staggerScale = lineScrollStaggerScale(lines, activeLineIndex, scrollDistancePx, naturalAdvance);
1956
- const activeDurationMs = requests.find(request => request.relativeIndex === 0)?.timing?.durationMs;
1957
- return {
1958
- items: requests.map((request, requestIndex) => {
1959
- const timing = request.timing;
1960
- return {
1961
- ...request.item,
1962
- durationMs: activeDurationMs === undefined
1963
- ? timing.durationMs
1964
- : activeDurationMs + (timing.durationMs - activeDurationMs) * staggerScale,
1965
- startEasing: timing.startEasing,
1966
- endEasing: timing.endEasing,
1967
- startTranslate: startTranslates ? startTranslates[requestIndex] : defaultStartTranslate,
1968
- endTranslate: endTranslates ? endTranslates[requestIndex] : "0px 0px",
1969
- };
1970
- }),
1971
- };
1972
- }
1973
- function startPreparedLineScroll(engine, plan) {
1974
- for (const item of plan.items) {
1975
- if (!item.lineElement.isConnected || engine.lineScrollElementTokens.get(item.lineElement) !== item.token)
1976
- continue;
1977
- const animation = item.lineElement.animate([
1978
- { translate: item.startTranslate, easing: item.startEasing },
1979
- { translate: item.endTranslate, easing: item.endEasing },
1980
- ], {
1981
- composite: "add",
1982
- duration: item.durationMs,
1983
- easing: "linear",
1984
- fill: "none",
1985
- });
1986
- trackLineScrollAnimation(engine, animation, item.lineElement, item.token);
1987
- }
1988
- }
1989
- function discardLineScrollPlan(engine, plan) {
1990
- for (const item of plan.items) {
1991
- clearLineScrollInlineProperties(engine, item.lineElement, item.token);
1992
- }
1993
- }
1994
- function dropPendingLineScroll(engine) {
1995
- if (!engine.pendingLineScroll)
1996
- return;
1997
- discardLineScrollPlan(engine, engine.pendingLineScroll.plan);
1998
- engine.pendingLineScroll = null;
1999
- }
2000
- function pendingLineScrollMatches(engine, activeLine, fromScrollTop, toScrollTop) {
2001
- return !!(engine.pendingLineScroll &&
2002
- engine.pendingLineScroll.activeLineElement === activeLine.lyricElement &&
2003
- Math.abs(engine.pendingLineScroll.fromScrollTop - fromScrollTop) <= 2 &&
2004
- Math.abs(engine.pendingLineScroll.toScrollTop - toScrollTop) <= 2);
2005
- }
2006
- function commitOrPrepareLineScroll(engine, lines, activeLine, scrollDeltaPx, fromScrollTop, toScrollTop, viewportHeight, config, naturalAdvance) {
2007
- if (pendingLineScrollMatches(engine, activeLine, fromScrollTop, toScrollTop)) {
2008
- const pending = engine.pendingLineScroll;
2009
- engine.pendingLineScroll = null;
2010
- startPreparedLineScroll(engine, pending.plan);
2011
- return;
2012
- }
2013
- dropPendingLineScroll(engine);
2014
- const plan = prepareLineScrollOffsets(engine, lines, lines.findIndex(line => line.lyricElement === activeLine.lyricElement), scrollDeltaPx, fromScrollTop, toScrollTop, viewportHeight, config, naturalAdvance);
2015
- if (plan)
2016
- startPreparedLineScroll(engine, plan);
2017
- }
2018
- function prepareUpcomingLineScroll(engine, lines, activeLine, scrollDeltaPx, fromScrollTop, toScrollTop, viewportHeight, config, naturalAdvance) {
2019
- if (pendingLineScrollMatches(engine, activeLine, fromScrollTop, toScrollTop))
2020
- return;
2021
- dropPendingLineScroll(engine);
2022
- const activeLineIndex = lines.findIndex(line => line.lyricElement === activeLine.lyricElement);
2023
- const plan = prepareLineScrollOffsets(engine, lines, activeLineIndex, scrollDeltaPx, fromScrollTop, toScrollTop, viewportHeight, config, naturalAdvance);
2024
- if (plan) {
2025
- engine.pendingLineScroll = {
2026
- plan,
2027
- activeLineElement: activeLine.lyricElement,
2028
- fromScrollTop,
2029
- toScrollTop,
2030
- };
2031
- }
2032
- }
2033
- // -- Skip Scrolls Decay --------------------------
2034
- function decaySkipScrolls(engine, now, keepsReserve) {
2035
- let j = 0;
2036
- for (; j < engine.skipScrollsDecayTimes.length; j++) {
2037
- if (engine.skipScrollsDecayTimes[j] > now) {
2038
- break;
2039
- }
2040
- }
2041
- engine.skipScrollsDecayTimes = engine.skipScrollsDecayTimes.slice(j);
2042
- engine.skipScrolls = Math.max(keepsReserve ? 1 : 0, engine.skipScrolls - j);
2043
- }
2044
- // -- Passive Scroll Engine --------------------------
2045
- /**
2046
- * The "no lyrics" message is one line at time zero, which is shaped exactly like unsynced lyrics.
2047
- * Nothing here applies to it: passive scroll would drift the message up and down for the length of
2048
- * the song, and there is no line to sync.
2049
- */
2050
- function hasNoLyricsPlaceholder(engine) {
2051
- return engine.lyricsContainer?.dataset.noLyrics === "true";
2052
- }
2053
- /**
2054
- * Unsynced lyrics that this view still has on screen. `syncType` outlives the lyrics it was derived
2055
- * from, so the container is the term that says they are still there.
2056
- */
2057
- export function hasUnsyncedLyrics(engine) {
2058
- return engine.lyricsContainer !== null && engine.syncType === "none" && !hasNoLyricsPlaceholder(engine);
2059
- }
2060
- function stopPassiveScrollLoop(engine) {
2061
- if (engine.passiveRAFId !== null) {
2062
- engine.window.cancelAnimationFrame(engine.passiveRAFId);
2063
- engine.passiveRAFId = null;
2064
- }
2065
- }
2066
- function startPassiveScrollLoop(engine) {
2067
- if (engine.passiveRAFId !== null)
2068
- return;
2069
- engine.passiveRAFId = engine.window.requestAnimationFrame(() => passiveScrollRAFLoop(engine));
2070
- }
2071
- function passiveScrollRAFLoop(engine) {
2072
- engine.passiveRAFId = null;
2073
- if (!engine.passiveScrollEnabled || !PASSIVE_SCROLL_ENABLED.getBooleanValue() || !hasUnsyncedLyrics(engine))
2074
- return;
2075
- passiveScrollEngine(engine, playbackClock.lastPlayState);
2076
- engine.passiveRAFId = engine.window.requestAnimationFrame(() => passiveScrollRAFLoop(engine));
2077
- }
2078
- function passiveScrollEngine(engine, isPlaying) {
2079
- if (!engine.host.isViewVisible())
2080
- return;
2081
- if (engine.host.isLoaderActive())
2082
- return;
2083
- const tabRenderer = engine.host.getScrollElement();
2084
- if (!tabRenderer)
2085
- return;
2086
- const now = Date.now();
2087
- // -- Accumulate play time --------------------------
2088
- if (engine.passiveLastWallTime > 0 && isPlaying) {
2089
- const wallDelta = (now - engine.passiveLastWallTime) / 1000;
2090
- engine.passiveScrollAccumulatedTime += Math.min(wallDelta, 0.5);
2091
- }
2092
- engine.passiveLastWallTime = now;
2093
- // -- User scroll interruption --------------------------
2094
- if (engine.scrollResumeTime > now) {
2095
- return;
2096
- }
2097
- if (engine.wasUserScrolling) {
2098
- engine.host.setResumeAffordanceVisible(false);
2099
- engine.lyricsContainer?.classList.remove(USER_SCROLLING_CLASS);
2100
- engine.wasUserScrolling = false;
2101
- // Re-sync accumulated time to current scroll position so scroll continues from where user left off
2102
- const maxScroll = tabRenderer.scrollHeight - tabRenderer.clientHeight;
2103
- if (maxScroll > 0) {
2104
- const ratio = tabRenderer.scrollTop / maxScroll;
2105
- const numLines = engine.lines.length;
2106
- const scrollDuration = numLines * PASSIVE_SECONDS_PER_LINE.getNumberValue();
2107
- engine.passiveScrollAccumulatedTime = ratio * scrollDuration;
2108
- }
2109
- }
2110
- // -- Cycle calculation --------------------------
2111
- const numLines = engine.lines.length;
2112
- if (numLines === 0)
2113
- return;
2114
- const scrollDuration = numLines * PASSIVE_SECONDS_PER_LINE.getNumberValue();
2115
- const bottomPause = PASSIVE_BOTTOM_PAUSE_S.getNumberValue();
2116
- const resetDuration = PASSIVE_RESET_DURATION_S.getNumberValue();
2117
- const topPause = PASSIVE_TOP_PAUSE_S.getNumberValue();
2118
- const cycleLength = scrollDuration + bottomPause + resetDuration + topPause;
2119
- const maxScroll = tabRenderer.scrollHeight - tabRenderer.clientHeight;
2120
- if (maxScroll <= 0)
2121
- return;
2122
- const cycleTime = engine.passiveScrollAccumulatedTime % cycleLength;
2123
- let targetScroll;
2124
- if (cycleTime < scrollDuration) {
2125
- // Phase 1: linear scroll down
2126
- targetScroll = (cycleTime / scrollDuration) * maxScroll;
2127
- }
2128
- else if (cycleTime < scrollDuration + bottomPause) {
2129
- // Phase 2: hold at bottom
2130
- targetScroll = maxScroll;
2131
- }
2132
- else if (cycleTime < scrollDuration + bottomPause + resetDuration) {
2133
- // Phase 3: ease-out scroll back to top
2134
- const resetProgress = (cycleTime - scrollDuration - bottomPause) / resetDuration;
2135
- const eased = 1 - (1 - resetProgress) * (1 - resetProgress);
2136
- targetScroll = maxScroll * (1 - eased);
2137
- }
2138
- else {
2139
- // Phase 4: hold at top
2140
- targetScroll = 0;
2141
- }
2142
- tabRenderer.scrollTop = targetScroll;
2143
- engine.passiveScrollTop = tabRenderer.scrollTop;
2144
- }
2145
- /**
2146
- * The drift writes the scroll every frame, and a browser folds that scroll and the reader's into one
2147
- * event, so the drift's own scrolls are told apart by where they land rather than by counting them.
2148
- */
2149
- function isPassiveDriftScroll(engine) {
2150
- const scrollTop = engine.host.getScrollElement()?.scrollTop;
2151
- return (engine.passiveScrollTop !== null &&
2152
- scrollTop !== undefined &&
2153
- Math.abs(scrollTop - engine.passiveScrollTop) < PASSIVE_DRIFT_SCROLL_TOLERANCE_PX);
2154
- }
2155
- /**
2156
- * Sets up a ResizeObserver on the tab renderer to cache its height.
2157
- * Avoids calling getBoundingClientRect() every tick which causes layout thrashing.
2158
- */
2159
- function setupTabRendererObserver(engine, element) {
2160
- if (engine.tabRendererResizeObserver) {
2161
- engine.tabRendererResizeObserver.disconnect();
2162
- }
2163
- engine.tabRendererResizeObserver = new engine.window.ResizeObserver(() => {
2164
- dropPendingLineScroll(engine);
2165
- if (element && element.isConnected) {
2166
- measureScrollViewport(engine, element);
2167
- }
2168
- });
2169
- engine.tabRendererResizeObserver.observe(element);
2170
- engine.observedTabRenderer = element;
2171
- measureScrollViewport(engine, element);
2172
- }
2173
- const NO_SCROLL_INSETS = { top: 0, bottom: 0 };
2174
- function resolveScrollInset(value, viewportHeight) {
2175
- const amount = Number.parseFloat(value);
2176
- if (!Number.isFinite(amount) || amount <= 0)
2177
- return 0;
2178
- return value.trim().endsWith("%") ? (viewportHeight * amount) / 100 : amount;
2179
- }
2180
- /**
2181
- * The scroll element's `scroll-padding` is the part of its viewport a host has declared unreadable,
2182
- * such as an edge faded out by a mask. Insets that leave no band at all are ignored rather than
2183
- * obeyed, since there would be nowhere left to put a line.
2184
- */
2185
- export function resolveScrollInsets(scrollPaddingTop, scrollPaddingBottom, viewportHeight) {
2186
- const top = resolveScrollInset(scrollPaddingTop, viewportHeight);
2187
- const bottom = resolveScrollInset(scrollPaddingBottom, viewportHeight);
2188
- return top + bottom < viewportHeight ? { top, bottom } : NO_SCROLL_INSETS;
2189
- }
2190
- function measureScrollViewport(engine, element) {
2191
- const height = element.getBoundingClientRect().height;
2192
- const { scrollPaddingTop, scrollPaddingBottom } = engine.window.getComputedStyle(element);
2193
- engine.cachedTabRendererHeight = height;
2194
- engine.cachedScrollInsets = resolveScrollInsets(scrollPaddingTop, scrollPaddingBottom, height);
2195
- }
2196
- /**
2197
- * The line the singer is on: the latest one still being sung. An earlier line still running is a
2198
- * tail, such as a background echo or a held note, and a later one is still in its lookahead. A line
2199
- * stays active past its own end until the next one starts, so a started line only wins while it runs.
2200
- */
2201
- export function findScrollAnchor(sungLines, scrollTime) {
2202
- return (sungLines.findLast(line => line.time <= scrollTime && scrollTime < line.time + line.duration) ??
2203
- sungLines.findLast(line => line.time <= scrollTime) ??
2204
- sungLines[0]);
2205
- }
2206
- /**
2207
- * Where to scroll so the lines being sung sit around the target, inside the visible band. When they
2208
- * do not all fit, the anchor keeps its top in view and the rest give way. `overflowsBand` tells the
2209
- * caller the view is pinned to the anchor, and has to move on once that line ends.
2210
- *
2211
- * @param sungLines - In order, never empty. The last is the last active line.
2212
- */
2213
- export function computeActiveLinesScrollTop(sungLines, anchor, viewportHeight, insets, targetOffset) {
2214
- const first = sungLines[0];
2215
- const last = sungLines[sungLines.length - 1];
2216
- const averageCentre = sungLines.reduce((total, line) => total + line.position + line.height / 2, 0) / sungLines.length;
2217
- const visibleBottom = viewportHeight - insets.bottom;
2218
- let scrollTop = averageCentre - targetOffset;
2219
- scrollTop = Math.max(scrollTop, last.position + last.height - visibleBottom);
2220
- scrollTop = Math.min(scrollTop, last.position - insets.top);
2221
- scrollTop = Math.min(scrollTop, first.position - insets.top);
2222
- scrollTop = Math.max(scrollTop, anchor.position + anchor.height - visibleBottom);
2223
- scrollTop = Math.min(scrollTop, anchor.position - insets.top);
2224
- return {
2225
- scrollTop,
2226
- overflowsBand: last.position + last.height - first.position > visibleBottom - insets.top,
2227
- };
2228
- }
2229
- /**
2230
- * Fills in everything a caller left out of a tick. The tick reads each of these arithmetically, so
2231
- * a missing one would not fail: it would quietly turn the playback time into NaN and leave the view
2232
- * matching no line at all.
2233
- */
2234
- export function resolveTickOptions(options) {
2235
- return {
2236
- isPlaying: options.isPlaying,
2237
- eventCreationTime: options.eventCreationTime ?? NO_PLAYER_SNAPSHOT,
2238
- smoothScroll: options.smoothScroll ?? true,
2239
- globalLyricOffset: options.globalLyricOffset ?? 0,
2240
- lyricOffset: options.lyricOffset ?? 0,
2241
- richsyncOffsetTrim: options.richsyncOffsetTrim ?? 0,
2242
- lineOffsetTrim: options.lineOffsetTrim ?? 0,
2243
- passiveScrollEnabled: options.passiveScrollEnabled ?? false,
2244
- playbackRate: resolvePlaybackRate(options.playbackRate),
2245
- followPausedSeeks: options.followPausedSeeks ?? false,
2246
- countEveryUserScroll: options.countEveryUserScroll ?? false,
2247
- };
2248
- }
2249
- // A rate of zero or less would freeze every animation that follows the song, which is a second
2250
- // answer to the question `isPlaying` already answers.
2251
- function resolvePlaybackRate(rate) {
2252
- return rate !== undefined && Number.isFinite(rate) && rate > 0 ? rate : 1;
2253
- }
2254
- // -- Stage layout --------------------------------------------
2255
- const STAGE_MOTION = { durationMs: 380, easing: "cubic-bezier(0.2, 0, 0, 1)" };
2256
- // Read by an important rule in stage.css, so a theme's own important opacity cannot reveal a line
2257
- // the stage is hiding or fading.
2258
- const STAGE_OPACITY_PROPERTY = "--blyrics-stage-opacity";
2259
- const stageOpacityRegistrations = new WeakSet();
2260
- const STAGE_FADE_IN_MS = 300;
2261
- const STAGE_FADE_IN_DELAY_MS = 70;
2262
- const STAGE_FADE_OUT_MS = 220;
2263
- // Lines blur out and in across a handoff, so one reads as turning into the next.
2264
- const STAGE_BLUR = "blur(3px)";
2265
- const STAGE_GAP_EM = 0.32;
2266
- function stageElements(engine) {
2267
- const elements = [];
2268
- const items = [];
2269
- let lastEnd = 0;
2270
- for (const line of engine.lines) {
2271
- const end = line.time + line.duration;
2272
- lastEnd = Math.max(lastEnd, end);
2273
- elements.push(line.lyricElement);
2274
- items.push({
2275
- kind: line.lyricElement.dataset.instrumental === "true"
2276
- ? "instrumental"
2277
- : line.lyricElement.dataset.blank === "true"
2278
- ? "blank"
2279
- : "line",
2280
- start: line.time,
2281
- end,
2282
- });
2283
- }
2284
- const credits = engine.lyricsContainer?.querySelector(`:scope > .${CREDITS_CLASS}`);
2285
- if (credits) {
2286
- elements.push(credits);
2287
- items.push({ kind: "credits", start: lastEnd, end: Number.POSITIVE_INFINITY });
2288
- }
2289
- return { elements, items };
2290
- }
2291
- function originXOf(align) {
2292
- if (align === "center")
2293
- return 0.5;
2294
- if (align === "right" || align === "end")
2295
- return 1;
2296
- return 0;
2297
- }
2298
- const ELEMENT_NODE = 1;
2299
- const TEXT_NODE = 3;
2300
- function contentWidthOf(element, style) {
2301
- return (element.clientWidth - (Number.parseFloat(style.paddingLeft) || 0) - (Number.parseFloat(style.paddingRight) || 0));
2302
- }
2303
- // A block that fills its parent is looked inside; inline boxes and shrunk blocks (the romanization pill) count whole.
2304
- function collectContentRects(engine, range, node, contentWidth, rects) {
2305
- for (const child of node.childNodes) {
2306
- if (child.nodeType === TEXT_NODE) {
2307
- range.selectNodeContents(child);
2308
- rects.push(...range.getClientRects());
2309
- continue;
2310
- }
2311
- if (child.nodeType !== ELEMENT_NODE)
2312
- continue;
2313
- const element = child;
2314
- const style = engine.window.getComputedStyle(element);
2315
- if (style.display === "none")
2316
- continue;
2317
- if (style.display === "contents") {
2318
- collectContentRects(engine, range, element, contentWidth, rects);
2319
- }
2320
- else if (style.display.startsWith("inline")) {
2321
- rects.push(...element.getClientRects());
2322
- }
2323
- else if (element.offsetWidth < contentWidth - 1) {
2324
- rects.push(element.getBoundingClientRect());
2325
- }
2326
- else {
2327
- collectContentRects(engine, range, element, contentWidthOf(element, style), rects);
2328
- }
2329
- }
2330
- return rects;
2331
- }
2332
- export function measureStage(engine) {
2333
- engine.stageMetrics.clear();
2334
- const container = engine.lyricsContainer;
2335
- if (!container)
2336
- return;
2337
- engine.stageFontSize = Number.parseFloat(engine.window.getComputedStyle(container).fontSize) || 16;
2338
- const range = engine.document.createRange();
2339
- for (const element of stageElements(engine).elements) {
2340
- const style = engine.window.getComputedStyle(element);
2341
- const originX = originXOf(style.textAlign);
2342
- const span = stageTextSpan(element.offsetLeft, element.offsetWidth, element.getBoundingClientRect(), collectContentRects(engine, range, element, contentWidthOf(element, style), []), { left: Number.parseFloat(style.paddingLeft) || 0, right: Number.parseFloat(style.paddingRight) || 0 }, originX);
2343
- engine.stageMetrics.set(element, {
2344
- height: element.offsetHeight,
2345
- left: span.left,
2346
- width: span.width,
2347
- originX,
2348
- });
2349
- }
2350
- engine.stageKey = "";
2351
- engine.stageRemeasured = true;
2352
- }
2353
- function currentTranslateY(engine, element, fallback) {
2354
- const parts = engine.window.getComputedStyle(element).translate.split(" ");
2355
- const y = Number.parseFloat(parts[1] ?? "");
2356
- return Number.isFinite(y) ? y : fallback;
2357
- }
2358
- function snapStageElement(engine, element, y) {
2359
- engine.stageMoves.get(element)?.cancel();
2360
- engine.stageMoves.set(element, element.animate([{ translate: `0 ${y}px` }], { duration: 0, fill: "forwards" }));
2361
- engine.stageY.set(element, y);
2362
- }
2363
- function placeStageElement(engine, { element, placement, wasVisible, fromY, fromOpacity }, instant, reduced) {
2364
- engine.stageMoves.get(element)?.cancel();
2365
- engine.stageFades.get(element)?.cancel();
2366
- const moveMs = instant || reduced ? 0 : STAGE_MOTION.durationMs;
2367
- engine.stageMoves.set(element, element.animate([{ translate: `0 ${fromY}px` }, { translate: `0 ${placement.y}px` }], {
2368
- duration: moveMs,
2369
- easing: STAGE_MOTION.easing,
2370
- fill: "forwards",
2371
- }));
2372
- const fadeMs = instant ? 0 : placement.visible ? STAGE_FADE_IN_MS : STAGE_FADE_OUT_MS;
2373
- if (placement.visible)
2374
- element.dataset.stageVisible = "";
2375
- else if (fadeMs === 0)
2376
- delete element.dataset.stageVisible;
2377
- const fade = element.animate([{ [STAGE_OPACITY_PROPERTY]: fromOpacity }, { [STAGE_OPACITY_PROPERTY]: placement.visible ? 1 : 0 }], {
2378
- duration: fadeMs,
2379
- delay: placement.visible && !instant ? STAGE_FADE_IN_DELAY_MS : 0,
2380
- easing: placement.visible ? "ease-out" : "ease",
2381
- // Backwards too: the fade replaces one that was cancelled, and through its delay the line would
2382
- // otherwise drop to the stylesheet's resting opacity of zero.
2383
- fill: "both",
2384
- });
2385
- if (!placement.visible && fadeMs > 0) {
2386
- fade.onfinish = () => {
2387
- if (engine.stageFades.get(element) === fade)
2388
- delete element.dataset.stageVisible;
2389
- };
2390
- }
2391
- engine.stageFades.set(element, fade);
2392
- engine.stageY.set(element, placement.y);
2393
- engine.stageBlurs.get(element)?.cancel();
2394
- engine.stageBlurs.delete(element);
2395
- if (fadeMs === 0 || reduced || wasVisible === placement.visible)
2396
- return;
2397
- const blurs = ["none", STAGE_BLUR];
2398
- engine.stageBlurs.set(element, element.animate((placement.visible ? blurs.reverse() : blurs).map(filter => ({ filter })), {
2399
- duration: fadeMs,
2400
- delay: placement.visible ? STAGE_FADE_IN_DELAY_MS : 0,
2401
- easing: placement.visible ? "ease-out" : "ease",
2402
- // Added to the theme's own filter rather than replacing it, and held only until the line is in focus.
2403
- composite: "add",
2404
- fill: placement.visible ? "backwards" : "forwards",
2405
- }));
2406
- }
2407
- // Registered from script rather than with @property, which Firefox ignores in a stylesheet
2408
- // cross-origin to the document. Unregistered, the fade would snap instead of interpolating.
2409
- function registerStageOpacity(engine) {
2410
- const css = engine.window.CSS;
2411
- if (stageOpacityRegistrations.has(engine.window) || typeof css?.registerProperty !== "function")
2412
- return;
2413
- stageOpacityRegistrations.add(engine.window);
2414
- try {
2415
- css.registerProperty({ name: STAGE_OPACITY_PROPERTY, syntax: "<number>", inherits: false, initialValue: "0" });
2416
- }
2417
- catch (error) {
2418
- engine.host.log("Stage opacity property was already registered", error);
2419
- }
2420
- }
2421
- function isStageRoleVisible(role) {
2422
- return role !== "queued" && role !== "gone";
2423
- }
2424
- function sameBox(a, b) {
2425
- if (a === null || b === null)
2426
- return a === b;
2427
- return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
2428
- }
2429
- function applyStage(engine, timeS, instant) {
2430
- const container = engine.lyricsContainer;
2431
- if (!container)
2432
- return;
2433
- registerStageOpacity(engine);
2434
- const { elements, items } = stageElements(engine);
2435
- const roles = planStage(items, timeS);
2436
- const key = roles.join(",");
2437
- if (key === engine.stageKey && !instant)
2438
- return;
2439
- engine.stageKey = key;
2440
- const remeasured = engine.stageRemeasured;
2441
- engine.stageRemeasured = false;
2442
- const metrics = elements.map(element => engine.stageMetrics.get(element) ?? { height: 0, left: 0, width: 0, originX: 0 });
2443
- const geometry = {
2444
- stageHeight: container.clientHeight,
2445
- gap: engine.stageFontSize * STAGE_GAP_EM,
2446
- activeScale: getCSSNumber(engine, container, "--blyrics-active-scale", 1),
2447
- };
2448
- // Lines sit on the floor, so a resize moves every place by how far the floor moved.
2449
- const floorShift = remeasured && engine.stageHeight > 0 ? geometry.stageHeight - engine.stageHeight : 0;
2450
- engine.stageHeight = geometry.stageHeight;
2451
- const { placements, box } = layoutStage(roles, items, metrics, elements.map(element => {
2452
- const y = engine.stageY.get(element);
2453
- return y === undefined ? null : y + floorShift;
2454
- }), geometry);
2455
- // Only the elements whose place changed move. A line that stays where it is keeps its running
2456
- // animations, and one already hidden stays hidden without being animated again.
2457
- const moves = [];
2458
- elements.forEach((element, index) => {
2459
- const placement = placements[index];
2460
- const previousY = engine.stageY.get(element);
2461
- const wasVisible = element.dataset.stageRole !== undefined && isStageRoleVisible(element.dataset.stageRole);
2462
- const unchanged = previousY !== undefined && wasVisible === placement.visible && (!placement.visible || previousY === placement.y);
2463
- // After a resize a line still on screen, fading out included, jumps to its new place and keeps
2464
- // the fade and blur it was in the middle of.
2465
- const onScreen = placement.visible || element.dataset.stageVisible !== undefined;
2466
- if (remeasured && !instant && onScreen && element.dataset.stageRole === roles[index]) {
2467
- if (previousY !== placement.y)
2468
- snapStageElement(engine, element, placement.y);
2469
- return;
2470
- }
2471
- if (unchanged && !instant)
2472
- return;
2473
- moves.push({
2474
- element,
2475
- placement,
2476
- wasVisible,
2477
- // A queued line rises from below the floor as it is now, never from where an older size put it.
2478
- fromY: element.dataset.stageRole === "queued" && placement.visible
2479
- ? queuedStageY(geometry.stageHeight, metrics[index].height, geometry.gap)
2480
- : currentTranslateY(engine, element, previousY ?? placement.y),
2481
- fromOpacity: Number(engine.window.getComputedStyle(element).opacity) || 0,
2482
- });
2483
- });
2484
- const reduced = engine.window.matchMedia(REDUCED_MOTION_QUERY).matches;
2485
- elements.forEach((element, index) => {
2486
- if (element.dataset.stageRole !== roles[index])
2487
- element.dataset.stageRole = roles[index];
2488
- });
2489
- for (const move of moves)
2490
- placeStageElement(engine, move, instant, reduced);
2491
- if (!sameBox(box, engine.stageBox)) {
2492
- engine.stageBox = box;
2493
- engine.host.onStageLayout?.(box);
2494
- }
2495
- }
2496
- /**
2497
- * Seconds to add to the player time to get the lyric time this view renders: the theme's offset
2498
- * and the trim for its sync type, less the global and per-song offsets.
2499
- */
2500
- function lyricClockShiftS(engine, lyricsElement, options) {
2501
- const syncTypeShiftS = engine.syncType === "richsync"
2502
- ? getCSSDurationInMs(engine, lyricsElement, "--blyrics-richsync-timing-offset") / 1000 -
2503
- options.richsyncOffsetTrim
2504
- : getCSSDurationInMs(engine, lyricsElement, "--blyrics-timing-offset") / 1000 - options.lineOffsetTrim;
2505
- return syncTypeShiftS - options.globalLyricOffset - options.lyricOffset;
2506
- }
2507
- /**
2508
- * The player time at which a lyric time plays, under the offsets of the last tick.
2509
- */
2510
- export function playerTimeForLyricTime(engine, lyricTimeS) {
2511
- const options = engine.lastTickOptions;
2512
- const lyricsElement = engine.lyricsContainer;
2513
- if (!options || !lyricsElement)
2514
- return lyricTimeS;
2515
- return Math.max(0, lyricTimeS - lyricClockShiftS(engine, lyricsElement, options));
2516
- }
2517
- /**
2518
- * Renders one view against a tick with nothing left out.
2519
- */
2520
- export function tickView(engine, currentTime, options) {
2521
- const { eventCreationTime, isPlaying, smoothScroll } = options;
2522
- engine.lastTickOptions = options;
2523
- engine.passiveScrollEnabled = options.passiveScrollEnabled;
2524
- if (engine.playbackRate !== options.playbackRate) {
2525
- engine.playbackRate = options.playbackRate;
2526
- applyPlaybackRateToRunningAnimations(engine);
2527
- }
2528
- const now = Date.now();
2529
- if (currentTime === 0 && !isPlaying) {
2530
- return "ok";
2531
- }
2532
- if (hasNoLyricsPlaceholder(engine)) {
2533
- stopPassiveScrollLoop(engine);
2534
- return "ok";
2535
- }
2536
- if (hasUnsyncedLyrics(engine)) {
2537
- // The stage shows lines by their time, and unsynced lines have none.
2538
- if (engine.layout === "stage")
2539
- return "ok";
2540
- if (!playbackClock.lastPlayState && isPlaying) {
2541
- engine.scrollResumeTime = 0;
2542
- }
2543
- playbackClock.lastPlayState = isPlaying;
2544
- if (!options.passiveScrollEnabled)
2545
- return "ok";
2546
- startPassiveScrollLoop(engine);
2547
- return "ok";
2548
- }
2549
- const timeJumped = Math.abs(currentTime - playbackClock.lastTime - (eventCreationTime - playbackClock.lastEventCreationTime) / 1000) >
2550
- TIME_JUMP_THRESHOLD;
2551
- // Without a player snapshot the reading is the media clock, which runs backwards only on a seek, so a
2552
- // loop shorter than the jump threshold still re-arms lines. A snapshot host's extrapolated clock is
2553
- // pulled back by every correction, so it is left to the threshold.
2554
- const mediaSteppedBack = eventCreationTime === NO_PLAYER_SNAPSHOT &&
2555
- isPlaying &&
2556
- currentTime < playbackClock.lastTime - CLOCK_RESYNC_THRESHOLD_S;
2557
- // A clock that was already paused only moves when the host seeks it, however small the step, as a
2558
- // scrub does. The tick that pauses lands a moment past the last playing one and is not a seek.
2559
- const pausedSeek = options.followPausedSeeks && !isPlaying && !playbackClock.lastPlayState && currentTime !== playbackClock.lastTime;
2560
- if (timeJumped)
2561
- dropPendingLineScroll(engine);
2562
- playbackClock.lastTime = currentTime;
2563
- playbackClock.lastPlayState = isPlaying;
2564
- playbackClock.lastEventCreationTime = eventCreationTime;
2565
- let timeOffset = now - eventCreationTime;
2566
- if (!isPlaying || eventCreationTime === NO_PLAYER_SNAPSHOT) {
2567
- timeOffset = 0;
2568
- }
2569
- currentTime += timeOffset / 1000;
2570
- if (SMOOTH_PLAYBACK_CLOCK) {
2571
- if (isPlaying && !timeJumped) {
2572
- currentTime = smoothedPlaybackTime(playbackClock.smoothedTime, playbackClock.smoothedAt, currentTime, now, engine.playbackRate);
2573
- }
2574
- playbackClock.smoothedTime = currentTime;
2575
- playbackClock.smoothedAt = isPlaying ? now : NO_PLAYER_SNAPSHOT;
2576
- }
2577
- if (!engine.host.isViewVisible()) {
2578
- clearVisibleLyricWillChange(engine);
2579
- return "ok";
2580
- }
2581
- if (engine.host.syncAdState()) {
2582
- return "ok";
2583
- }
2584
- try {
2585
- const lyricsElement = engine.lyricsContainer;
2586
- // If lyrics element doesn't exist, clear the interval and return silently
2587
- if (!lyricsElement) {
2588
- engine.host.log(NO_LYRICS_ELEMENT_LOG);
2589
- return "lyrics-missing";
2590
- }
2591
- const lines = engine.lines;
2592
- currentTime += lyricClockShiftS(engine, lyricsElement, options);
2593
- const lyricScrollTime = correctedScrollTimeS(engine, currentTime) +
2594
- getCSSDurationInMs(engine, lyricsElement, "--blyrics-scroll-timing-offset") / 1000;
2595
- const { config: animationConfig, scrollTiming } = getAnimationSettings(engine, lyricsElement);
2596
- // Read layout values before the loop writes class changes, to avoid forced reflow
2597
- const isStage = engine.layout === "stage";
2598
- const tabRenderer = isStage ? null : engine.host.getScrollElement();
2599
- if (!isStage && !tabRenderer) {
2600
- clearVisibleLyricWillChange(engine);
2601
- return "ok";
2602
- }
2603
- if (tabRenderer && tabRenderer !== engine.observedTabRenderer) {
2604
- setupTabRendererObserver(engine, tabRenderer);
2605
- }
2606
- const tabRendererHeight = tabRenderer
2607
- ? (engine.cachedTabRendererHeight ?? tabRenderer.getBoundingClientRect().height)
2608
- : 0;
2609
- // Read before the loop's class writes so this layout read is batched and forces no mid-frame reflow.
2610
- let scrollTop = tabRenderer?.scrollTop ?? 0;
2611
- const maxScrollTop = tabRenderer ? Math.max(0, tabRenderer.scrollHeight - tabRenderer.clientHeight) : 0;
2612
- if (!isStage && animationConfig.enabled.scroll) {
2613
- updateVisibleLyricWillChange(engine, lines, scrollTop, engine.pendingLineScroll?.toScrollTop ?? scrollTop, tabRendererHeight);
2614
- }
2615
- else {
2616
- dropPendingLineScroll(engine);
2617
- clearVisibleLyricWillChange(engine);
2618
- clearLineScrollAnimations(engine);
2619
- }
2620
- let activeElems = [];
2621
- const linesToAnimate = [];
2622
- let newLyricSelected = timeJumped;
2623
- lines.every((lineData, index) => {
2624
- const time = lineData.time;
2625
- let nextTime = Infinity;
2626
- if (index + 1 < lines.length) {
2627
- const nextLyric = lines[index + 1];
2628
- nextTime = nextLyric.time;
2629
- }
2630
- if (lyricScrollTime >= time - scrollTiming.earlyScrollConsiderS &&
2631
- (lyricScrollTime < nextTime || lyricScrollTime < time + lineData.duration)) {
2632
- activeElems.push(lineData);
2633
- if (!engine.lastScrollElements.includes(lineData) && lyricScrollTime >= time) {
2634
- newLyricSelected = true;
2635
- }
2636
- // const timeDelta = lyricScrollTime - time;
2637
- // if (engine.selectedElementIndex !== index && timeDelta > 0.05 && index > 0) {
2638
- // Utils.log(`[BetterLyrics] Scrolling to new lyric was late, dt: ${timeDelta.toFixed(5)}s`);
2639
- // }
2640
- engine.selectedElementIndex = index;
2641
- if (!lineData.isScrolled) {
2642
- lineData.lyricElement.classList.add(CURRENT_LYRICS_CLASS);
2643
- lineData.isScrolled = true;
2644
- }
2645
- }
2646
- else {
2647
- if (lineData.isScrolled) {
2648
- lineData.lyricElement.classList.remove(CURRENT_LYRICS_CLASS);
2649
- lineData.isScrolled = false;
2650
- }
2651
- }
2652
- /**
2653
- * Time in seconds to set up animations. This shouldn't affect any visible effects, just help when the browser stutters
2654
- */
2655
- let setUpAnimationEarlyTime = 2;
2656
- if (!isPlaying) {
2657
- setUpAnimationEarlyTime = 0;
2658
- }
2659
- const effectiveEndTime = Math.max(nextTime, time + lineData.duration + 0.05);
2660
- if (currentTime + setUpAnimationEarlyTime >= time && currentTime < effectiveEndTime) {
2661
- if (!lineData.isSelected) {
2662
- lineData.isSelected = true;
2663
- lineData.lyricElement.classList.add(ANIMATING_CLASS);
2664
- }
2665
- if (isPlaying !== lineData.isAnimationPlayStatePlaying) {
2666
- lineData.isAnimationPlayStatePlaying = isPlaying;
2667
- setAnimationsPlayState(lineData, isPlaying);
2668
- if (isPlaying)
2669
- lineData.isAnimating = false; // reset the animation against current media time
2670
- }
2671
- // Lead-in animations have no timing sample for the drift check, so a jump while playing must reset them.
2672
- if (((timeJumped && isPlaying) || mediaSteppedBack || pausedSeek) && lineData.isAnimating)
2673
- resetLineAnimationState(lineData);
2674
- updateWordStates(lineData, currentTime);
2675
- const nativeTimingSample = lineNativeTimingSample(lineData, currentTime);
2676
- let usedNativeTimingSampleForDrift = false;
2677
- lineData.accumulatedOffsetMs = lineData.accumulatedOffsetMs / ANIMATION_TIMING_ACCUMULATION_DECAY;
2678
- if (nativeTimingSample !== null && canUseTimingSampleForDrift(nativeTimingSample, isPlaying)) {
2679
- usedNativeTimingSampleForDrift = true;
2680
- const learnedOffsetMs = learnAnimationTimingOffset(engine, nativeTimingSample);
2681
- const residualOffsetMs = nativeTimingSample.offsetMs;
2682
- lineData.accumulatedOffsetMs += residualOffsetMs * ANIMATION_TIMING_ACCUMULATION_WEIGHT;
2683
- if (shouldLogAnimationTiming(engine, lineData, nativeTimingSample, now)) {
2684
- logAnimationTiming(engine, "sample", lineData, index, nativeTimingSample, currentTime, lineData.accumulatedOffsetMs, learnedOffsetMs, residualOffsetMs);
2685
- }
2686
- }
2687
- else if (nativeTimingSample !== null && shouldLogAnimationTiming(engine, lineData, nativeTimingSample, now)) {
2688
- logAnimationTiming(engine, "ignored-sample", lineData, index, nativeTimingSample, currentTime, lineData.accumulatedOffsetMs);
2689
- }
2690
- if (lineData.isAnimating &&
2691
- usedNativeTimingSampleForDrift &&
2692
- Math.abs(lineData.accumulatedOffsetMs) > ANIMATION_TIMING_RESET_THRESHOLD_MS &&
2693
- isPlaying) {
2694
- if (nativeTimingSample !== null) {
2695
- logAnimationTiming(engine, "drift-reset", lineData, index, nativeTimingSample, currentTime, lineData.accumulatedOffsetMs);
2696
- }
2697
- resetLineAnimationState(lineData);
2698
- }
2699
- if (!lineData.isAnimating) {
2700
- // We'll take care of the animation setup in a batch later
2701
- linesToAnimate.push(lineData);
2702
- }
2703
- }
2704
- else {
2705
- const staleAnimationEndTime = effectiveEndTime + animationConfig.highlight.fadeOutDurationMs / 1000 + 0.05;
2706
- if (lineData.isSelected) {
2707
- if (isPlaying || timeJumped || pausedSeek) {
2708
- if (currentTime > staleAnimationEndTime) {
2709
- logAnimationCleanup(engine, "selected-stale-reset", lineData, index, currentTime, staleAnimationEndTime);
2710
- resetLineAnimationState(lineData);
2711
- }
2712
- else {
2713
- startLineExitAnimations(engine, lineData, animationConfig, currentTime);
2714
- markLineAnimationsStopped(lineData);
2715
- }
2716
- }
2717
- else {
2718
- setAnimationsPlayState(lineData, false);
2719
- lineData.isAnimationPlayStatePlaying = false;
2720
- }
2721
- lineData.isSelected = false;
2722
- clearLineStateClasses(lineData);
2723
- updateWordStates(lineData, currentTime);
2724
- }
2725
- else if (hasLineAnimations(lineData) && (timeJumped || currentTime > staleAnimationEndTime)) {
2726
- logAnimationCleanup(engine, timeJumped ? "time-jump-reset" : "stale-reset", lineData, index, currentTime, staleAnimationEndTime);
2727
- resetLineAnimationState(lineData);
2728
- }
2729
- if (timeJumped) {
2730
- updateWordStates(lineData, currentTime);
2731
- }
2732
- }
2733
- return true;
2734
- });
2735
- if (linesToAnimate.length > 0) {
2736
- for (const lineData of linesToAnimate) {
2737
- startLineAnimations(engine, lineData, animationConfig, currentTime);
2738
- lineData.isAnimating = true;
2739
- lineData.lastAnimSetupAt = now;
2740
- lineData.isAnimationPlayStatePlaying = isPlaying;
2741
- lineData.accumulatedOffsetMs = 0;
2742
- if (!isPlaying)
2743
- setAnimationsPlayState(lineData, false);
2744
- }
2745
- }
2746
- const lastSungLine = lines.findLast(lineData => lineData.lyricElement.dataset.instrumental !== "true");
2747
- const creditsFocused = lastSungLine !== undefined &&
2748
- (engine.cachedCreditsItem?.height ?? 0) > 0 &&
2749
- lyricScrollTime >= lastSungLine.time + lastSungLine.duration;
2750
- if (creditsFocused !== engine.creditsFocused) {
2751
- engine.creditsFocused = creditsFocused;
2752
- if (creditsFocused)
2753
- lyricsElement.dataset.creditsFocused = "true";
2754
- else
2755
- delete lyricsElement.dataset.creditsFocused;
2756
- newLyricSelected = true;
2757
- }
2758
- if (isStage || !tabRenderer) {
2759
- if (isStage)
2760
- applyStage(engine, currentTime, timeJumped);
2761
- return "ok";
2762
- }
2763
- if (engine.scrollResumeTime < Date.now() || engine.scrollPos === -1) {
2764
- if (activeElems.length == 0) {
2765
- activeElems.push(lines[0]);
2766
- }
2767
- // Offset so lyrics appear towards the center of the screen.
2768
- const scrollPosOffset = tabRendererHeight * getTargetScrollRatio(engine, lyricsElement);
2769
- let lastActiveLyric = activeElems[activeElems.length - 1];
2770
- // Ignore lyrics close to finishing unless it is the last active lyric.
2771
- const sungLines = activeElems.filter((lineData, index) => lyricScrollTime < lineData.time + lineData.duration - LYRIC_ENDING_THRESHOLD_S.getNumberValue() ||
2772
- index == activeElems.length - 1);
2773
- const lyricPositions = sungLines.map(lineData => lineData.position + lineData.height / 2);
2774
- const scrollInsets = engine.cachedScrollInsets;
2775
- const scrollAnchor = findScrollAnchor(sungLines, lyricScrollTime);
2776
- const scrollTarget = computeActiveLinesScrollTop(sungLines, scrollAnchor, tabRendererHeight, scrollInsets, scrollPosOffset);
2777
- let scrollPos = scrollTarget.scrollTop;
2778
- const pinned = engine.pinnedScrollLine;
2779
- if (pinned &&
2780
- pinned !== scrollAnchor &&
2781
- (!sungLines.includes(pinned) || lyricScrollTime >= pinned.time + pinned.duration)) {
2782
- newLyricSelected = true;
2783
- }
2784
- const credits = engine.cachedCreditsItem;
2785
- if (engine.creditsFocused && credits && lastSungLine) {
2786
- // Tall credits would otherwise carry the last line out of view while it is still being sung.
2787
- scrollPos = Math.min(credits.position + credits.height / 2 - scrollPosOffset, lastSungLine.position - scrollInsets.top);
2788
- }
2789
- // Past either end the browser clamps the write and reports nothing, leaving the view aiming
2790
- // at a position it never reached and re-aiming once per remaining line.
2791
- scrollPos = clamp(scrollPos, 0, maxScrollTop);
2792
- if (ENABLE_DEBUG_RENDER.getBooleanValue()) {
2793
- let transform = engine.window.getComputedStyle(lyricsElement).transform;
2794
- const matrix = new engine.window.DOMMatrix(transform);
2795
- let yTransform = matrix.f;
2796
- let yTop = scrollTop - yTransform;
2797
- const ctx = engine.host.debug?.beginFrame(yTop);
2798
- if (ctx) {
2799
- ctx.strokeStyle = "green";
2800
- ctx.fillStyle = "green";
2801
- ctx?.fillText("visible top", 0, scrollTop);
2802
- ctx?.beginPath();
2803
- ctx?.moveTo(40, scrollTop);
2804
- ctx?.lineTo(1000, scrollTop);
2805
- ctx.stroke();
2806
- ctx.strokeStyle = "blue";
2807
- ctx.fillStyle = "blue";
2808
- ctx?.fillText("visible bottom", 0, scrollTop + tabRendererHeight);
2809
- ctx?.beginPath();
2810
- ctx?.moveTo(40, scrollTop + tabRendererHeight);
2811
- ctx?.lineTo(1000, scrollTop + tabRendererHeight);
2812
- ctx.stroke();
2813
- ctx.strokeStyle = "yellow";
2814
- ctx.fillStyle = "yellow";
2815
- ctx?.fillText("target", 0, scrollTop + scrollPosOffset);
2816
- ctx?.beginPath();
2817
- ctx?.moveTo(40, scrollTop + scrollPosOffset);
2818
- ctx?.lineTo(1000, scrollTop + scrollPosOffset);
2819
- ctx.stroke();
2820
- function debugLyrics(xOffset, name, activeElems, lyricPositions, lyricScrollTime) {
2821
- ctx.strokeStyle = "red";
2822
- ctx.fillStyle = "red";
2823
- ctx.fillText(name, xOffset + 2, yTop + 45);
2824
- ctx.fillText("scroll time: " + lyricScrollTime.toFixed(3), xOffset + 2, yTop + 60);
2825
- activeElems.forEach(elm => {
2826
- let timeTillActive = elm.time - lyricScrollTime;
2827
- let endTime = elm.time + elm.duration;
2828
- let timeTillEnd = endTime - lyricScrollTime;
2829
- if (timeTillEnd < LYRIC_ENDING_THRESHOLD_S.getNumberValue()) {
2830
- ctx.strokeStyle = "gray";
2831
- ctx.fillStyle = "gray";
2832
- }
2833
- else if (timeTillActive > 0) {
2834
- ctx.strokeStyle = "magenta";
2835
- ctx.fillStyle = "magenta";
2836
- }
2837
- else {
2838
- ctx.strokeStyle = "orange";
2839
- ctx.fillStyle = "orange";
2840
- }
2841
- ctx?.beginPath();
2842
- ctx?.moveTo(xOffset + 5, elm.position);
2843
- ctx?.lineTo(xOffset + 5, elm.position + elm.height);
2844
- ctx?.stroke();
2845
- ctx?.fillText("time: start=" + elm.time.toFixed(2) + " end=" + endTime.toFixed(2), xOffset + 15, elm.position);
2846
- ctx?.fillText("till active: " + timeTillActive.toFixed(2), xOffset + 15, elm.position + 15);
2847
- ctx?.fillText("till end: " + timeTillEnd.toFixed(2), xOffset + 15, elm.position + 30);
2848
- });
2849
- ctx.strokeStyle = "pink";
2850
- ctx.fillStyle = "pink";
2851
- lyricPositions.forEach(lyricPosition => {
2852
- ctx?.beginPath();
2853
- ctx?.arc(xOffset + 5, lyricPosition, 5, 0, 2 * Math.PI, false);
2854
- ctx?.fill();
2855
- });
2856
- }
2857
- debugLyrics(0, "realtime", activeElems, lyricPositions, lyricScrollTime);
2858
- debugLyrics(160, "last scroll", engine.lastScrollDebugContext.activeElms, engine.lastScrollDebugContext.centers, engine.lastScrollDebugContext.lyricScrollTime);
2859
- }
2860
- }
2861
- const timeUntilUpcomingScrollMs = (lastActiveLyric.time - lyricScrollTime) * 1000;
2862
- // Only a scroll from where the engine itself left the view keeps the theme's full stagger.
2863
- const naturalAdvance = !timeJumped && !engine.wasUserScrolling && engine.scrollPos >= 0 && Math.abs(scrollTop - engine.scrollPos) <= 2;
2864
- if (smoothScroll &&
2865
- animationConfig.enabled.scroll &&
2866
- !newLyricSelected &&
2867
- !engine.wasUserScrolling &&
2868
- timeUntilUpcomingScrollMs > 0 &&
2869
- timeUntilUpcomingScrollMs <= SCROLL_PREPARE_LEAD_MS &&
2870
- !engine.lastScrollElements.includes(lastActiveLyric) &&
2871
- Math.abs(scrollTop - scrollPos) > 2) {
2872
- updateVisibleLyricWillChange(engine, lines, scrollTop, scrollPos, tabRendererHeight);
2873
- prepareUpcomingLineScroll(engine, getLineScrollItems(engine, lines), lastActiveLyric, scrollPos - scrollTop, scrollTop, scrollPos, tabRendererHeight, animationConfig, naturalAdvance);
2874
- }
2875
- if (engine.wasUserScrolling || newLyricSelected) {
2876
- // Remember future lines only when their group is committed, so they cannot scroll
2877
- // again at their start. Entering the lookahead window alone does not commit a group.
2878
- engine.lastScrollElements = activeElems;
2879
- engine.pinnedScrollLine = scrollTarget.overflowsBand ? scrollAnchor : null;
2880
- engine.lastScrollDebugContext.lyricScrollTime = lyricScrollTime;
2881
- engine.lastScrollDebugContext.centers = lyricPositions;
2882
- engine.lastScrollDebugContext.activeElms = activeElems;
2883
- if (smoothScroll && Math.abs(scrollTop - scrollPos) > 2) {
2884
- const scrollDeltaPx = scrollPos - scrollTop;
2885
- if (animationConfig.enabled.scroll) {
2886
- updateVisibleLyricWillChange(engine, lines, scrollTop, scrollPos, tabRendererHeight);
2887
- const lineScrollItems = getLineScrollItems(engine, lines);
2888
- commitOrPrepareLineScroll(engine, lineScrollItems, lastActiveLyric, scrollDeltaPx, scrollTop, scrollPos, tabRendererHeight, animationConfig, naturalAdvance);
2889
- }
2890
- }
2891
- else {
2892
- dropPendingLineScroll(engine);
2893
- }
2894
- scrollTop = scrollPos;
2895
- engine.scrollPos = scrollTop;
2896
- const scrollTopBeforeWrite = tabRenderer.scrollTop;
2897
- tabRenderer.scrollTop = scrollTop;
2898
- if (tabRenderer.scrollTop !== scrollTopBeforeWrite) {
2899
- engine.skipScrolls += 1;
2900
- engine.skipScrollsDecayTimes.push(Date.now() + 2000);
2901
- }
2902
- }
2903
- }
2904
- if (engine.wasUserScrolling && engine.scrollResumeTime < Date.now()) {
2905
- engine.host.setResumeAffordanceVisible(false);
2906
- lyricsElement.classList.remove(USER_SCROLLING_CLASS);
2907
- engine.wasUserScrolling = false;
2908
- }
2909
- decaySkipScrolls(engine, now, !options.countEveryUserScroll);
2910
- }
2911
- catch (err) {
2912
- if (!err.message?.includes("undefined")) {
2913
- engine.host.log(LYRICS_CHECK_INTERVAL_ERROR, err);
2914
- }
2915
- }
2916
- return "ok";
2917
- }
2918
- /**
2919
- * Sizes the padding above the first line and below the last one so either can sit at the view's
2920
- * target scroll position.
2921
- *
2922
- * The first two candidates are exact, and both are measured from the container. They are worth
2923
- * nothing while it is not rendering: every line reports zero, which reads as content that already
2924
- * runs past the last line and asks for no padding at all, and the last lines of the song then have
2925
- * nowhere to scroll to. The viewport keeps its height whether the lyrics render or not, so the
2926
- * space it alone demands below the last line is always knowable, and it is the floor. Over-padding
2927
- * costs nothing visible; under-padding strands the end of every song.
2928
- */
2929
- export function computeScrollPadding(measurements) {
2930
- const { viewportHeight, targetScrollRatio, contentHeight, lastLineCentre } = measurements;
2931
- const top = Math.max(0, viewportHeight * targetScrollRatio - measurements.firstLineHeight / 2);
2932
- const lastLineTargetContentHeight = lastLineCentre === null ? viewportHeight : lastLineCentre + viewportHeight * (1 - targetScrollRatio);
2933
- const trailingContentHeight = measurements.footerHeight + measurements.lastLineHeight / 2;
2934
- const viewportTailSpace = viewportHeight * (1 - targetScrollRatio) - trailingContentHeight;
2935
- const bottom = Math.max(lastLineTargetContentHeight - contentHeight, viewportHeight - contentHeight, viewportTailSpace, 0);
2936
- return { top, bottom: Math.ceil(bottom) };
2937
- }
2938
- /**
2939
- * Sizes the padding this view needs and writes it where the stylesheet reads it, which is the
2940
- * document's root element. That makes it the second thing a view writes per document rather than
2941
- * per view, alongside the theme's `<style>`, so it is the same one renderer per document constraint
2942
- * the README states under Theme settings and not a new one: a second renderer in this document
2943
- * overwrites these two properties with the padding its own viewport needs, and the first view is
2944
- * then padded for a viewport it is not in.
2945
- *
2946
- * The root rather than the container because these are published names. Both readers in this repo
2947
- * select `.blyrics-container`, but the extension's own `mobile.css` is one of them, from outside
2948
- * the module, and a theme is free to read them anywhere: narrowing where they resolve would break
2949
- * such a theme silently, the way any custom property that stops resolving does. That is a real cost
2950
- * against a corruption the module already forbids.
2951
- */
2952
- function applyScrollPadding(engine) {
2953
- const lyricsElement = engine.lyricsContainer;
2954
- const tabRenderer = engine.host.getScrollElement();
2955
- if (!lyricsElement || !tabRenderer)
2956
- return;
2957
- if (hasNoLyricsPlaceholder(engine)) {
2958
- setScrollPadding(engine, lyricsElement, { top: 0, bottom: 0 });
2959
- return;
2960
- }
2961
- const tabRendererHeight = tabRenderer.getBoundingClientRect().height;
2962
- const scrollPosOffsetRatio = getTargetScrollRatio(engine, lyricsElement);
2963
- const currentPaddingBottom = Number.parseFloat(engine.window.getComputedStyle(lyricsElement).paddingBottom) || 0;
2964
- const lyricsHeightWithoutBottomPadding = Math.max(0, lyricsElement.scrollHeight - currentPaddingBottom);
2965
- const lyricLines = lyricsElement.querySelectorAll(`:scope > .${LINE_CLASS}`);
2966
- const firstLyric = lyricLines[0] ?? null;
2967
- const lastLyric = lyricLines[lyricLines.length - 1] ?? null;
2968
- const credits = lyricsElement.querySelector(`:scope > .${CREDITS_CLASS}`);
2969
- const creditsBounds = credits ? getRelativeLayoutBounds(lyricsElement, credits) : null;
2970
- // The credits take the focus once the song ends, so they are the last thing the scroll must reach.
2971
- const lastLyricBounds = creditsBounds && creditsBounds.height > 0
2972
- ? creditsBounds
2973
- : lastLyric
2974
- ? getRelativeLayoutBounds(lyricsElement, lastLyric)
2975
- : null;
2976
- const footer = lyricsElement.querySelector(`:scope > .${FOOTER_CLASS}`);
2977
- const { top, bottom } = computeScrollPadding({
2978
- viewportHeight: tabRendererHeight,
2979
- targetScrollRatio: scrollPosOffsetRatio,
2980
- contentHeight: lyricsHeightWithoutBottomPadding,
2981
- firstLineHeight: firstLyric ? getRelativeLayoutBounds(lyricsElement, firstLyric).height : 0,
2982
- lastLineCentre: lastLyricBounds ? lastLyricBounds.y + lastLyricBounds.height / 2 : null,
2983
- lastLineHeight: lastLyricBounds?.height ?? 0,
2984
- footerHeight: footer ? getRelativeLayoutBounds(lyricsElement, footer).height : 0,
2985
- });
2986
- setScrollPadding(engine, lyricsElement, { top, bottom });
2987
- }
2988
- function setScrollPadding(engine, lyricsElement, { top, bottom }) {
2989
- engine.document.documentElement.style.setProperty("--blyrics-padding-top", top + "px");
2990
- engine.document.documentElement.style.setProperty("--blyrics-padding-bottom", bottom + "px");
2991
- // Inline, because a theme's own `.blyrics-container { padding }` is appended after the package's
2992
- // stylesheet at the same weight and would otherwise take this room away.
2993
- lyricsElement.style.setProperty("padding-bottom", bottom + "px");
2994
- }
2995
- /**
2996
- * Re-reads the view's layout: the scroll padding first, then the line positions the padding moved.
2997
- *
2998
- * @param measureLines - Pass false while the lines are not being rendered. An unrendered container
2999
- * measures every line as zero height at zero offset, which would leave the scroll maths with
3000
- * nothing to work from once rendering resumes.
3001
- */
3002
- export function relayout(engine, measureLines) {
3003
- if (engine.layout === "stage") {
3004
- if (!measureLines || !engine.lyricsContainer)
3005
- return;
3006
- engine.cachedCreditsItem = measureTrailingItem(engine.lyricsContainer, CREDITS_CLASS);
3007
- measureStage(engine);
3008
- return;
3009
- }
3010
- applyScrollPadding(engine);
3011
- const scrollElement = engine.host.getScrollElement();
3012
- if (scrollElement)
3013
- measureScrollViewport(engine, scrollElement);
3014
- if (!measureLines)
3015
- return;
3016
- const lyricsElement = engine.lyricsContainer;
3017
- if (!lyricsElement)
3018
- return;
3019
- // Both dimensions, because both are what a resize is compared against. The scroll padding written
3020
- // above lands on this container, so a measurement that records only the width leaves every later
3021
- // resize report looking like a new height, and each one measures again and forces a rescroll.
3022
- engine.lyricWidth = lyricsElement.clientWidth;
3023
- engine.lyricHeight = lyricsElement.clientHeight;
3024
- // Skipped lines report intrinsic size, so un-cull before the walk reads offsetTop/offsetHeight.
3025
- clearOffscreenLineCulling(engine);
3026
- for (const line of engine.lines) {
3027
- const bounds = getRelativeLayoutBounds(lyricsElement, line.lyricElement);
3028
- line.position = bounds.y;
3029
- line.height = bounds.height;
3030
- line.decorations = new Map(lineDecorators(line.lyricElement).map(element => [element, getRelativeLayoutBounds(lyricsElement, element).y]));
3031
- }
3032
- engine.cachedCreditsItem = measureTrailingItem(lyricsElement, CREDITS_CLASS);
3033
- engine.cachedFooterItem = measureTrailingItem(lyricsElement, FOOTER_CLASS);
3034
- // Re-arm from the fresh measurements, so a line skipped after this holds its new placeholder height.
3035
- setupLineCullObserver(engine);
3036
- engine.wasUserScrolling = true; // trigger rescrolls
3037
- engine.host.debug?.resize();
3038
- }
3039
- // -- Decoration slide --------------------------
3040
- const DECORATION_SLIDE_MS = 350;
3041
- const DECORATION_SLIDE_EASING = "cubic-bezier(0.25, 1, 0.5, 1)";
3042
- const DECORATION_MIN_SHIFT_PX = 0.5;
3043
- function slideElementBy(element, dy) {
3044
- element.animate({ translate: [`0 ${dy}px`, "0 0"] }, { duration: DECORATION_SLIDE_MS, easing: DECORATION_SLIDE_EASING, composite: "add" });
3045
- }
3046
- function decorationSlideAllowed(engine, container) {
3047
- if (engine.window.matchMedia(REDUCED_MOTION_QUERY).matches)
3048
- return false;
3049
- return (engine.window.getComputedStyle(container).getPropertyValue("--blyrics-animate-decoration-entry").trim() !== "0");
3050
- }
3051
- function lineDecorators(lineElement) {
3052
- return [
3053
- ...lineElement.querySelectorAll(`.${ROMANIZED_LYRICS_CLASS}`),
3054
- ...lineElement.querySelectorAll(`.${TRANSLATED_LYRICS_CLASS}`),
3055
- ];
3056
- }
3057
- /**
3058
- * Snapshots where the lines and their decorators sit now, so the remeasure that follows can slide
3059
- * each one from there to wherever a streamed decoration just pushed it. Returns null when nothing
3060
- * should animate, and otherwise a function to call once the new layout is measured: the line rides
3061
- * its own shift and a decorator rides only the part of its shift its line did not already carry, so
3062
- * a survivor whose line held still still slides into the gap a removed sibling left.
3063
- */
3064
- function captureDecorationSlide(engine) {
3065
- const container = engine.lyricsContainer;
3066
- if (!container || engine.layout === "stage" || !decorationSlideAllowed(engine, container))
3067
- return null;
3068
- const before = engine.lines.map(line => ({
3069
- line,
3070
- position: line.position,
3071
- decorations: new Map(line.decorations),
3072
- }));
3073
- return () => {
3074
- for (const { line, position, decorations } of before) {
3075
- const lineShift = position - line.position;
3076
- if (Math.abs(lineShift) >= DECORATION_MIN_SHIFT_PX)
3077
- slideElementBy(line.lyricElement, lineShift);
3078
- for (const [element, was] of decorations) {
3079
- const now = line.decorations.get(element);
3080
- if (now === undefined)
3081
- continue;
3082
- const shift = was - now - lineShift;
3083
- if (Math.abs(shift) >= DECORATION_MIN_SHIFT_PX)
3084
- slideElementBy(element, shift);
3085
- }
3086
- }
3087
- };
3088
- }
3089
- // -- Debounced Lyrics Update --------------------------
3090
- function cancelLyricPositionUpdate(engine) {
3091
- if (engine.pendingLyricsUpdateFrame === null)
3092
- return;
3093
- engine.window.cancelAnimationFrame(engine.pendingLyricsUpdateFrame);
3094
- engine.pendingLyricsUpdateFrame = null;
3095
- }
3096
- /**
3097
- * Renders this view again against the last player snapshot, without moving the clock on. The
3098
- * options are built now rather than handed in, so a caller that reads settings at tick time still
3099
- * reads them at tick time.
3100
- *
3101
- * @param buildTickOptions - Given the snapshot the tick will run against, returns what to render it
3102
- * with.
3103
- */
3104
- export function retickFromPlaybackClock(engine, buildTickOptions) {
3105
- return tickView(engine, playbackClock.lastTime, resolveTickOptions(buildTickOptions(playbackClock.lastEventCreationTime, playbackClock.lastPlayState)));
3106
- }
3107
- /**
3108
- * Called when a new lyrics element is added to trigger re-sync.
3109
- * Debounced via requestAnimationFrame to avoid O(n²) layout thrashing
3110
- * when translations/romanizations load (each addition would otherwise
3111
- * re-measure ALL lines).
3112
- *
3113
- * @param isViewRendering - Asked on the frame rather than now. A driver that has stopped ticking is
3114
- * one whose lines may no longer be rendered, and an unrendered line measures as nothing, so a
3115
- * false answer declines both the re-measurement and the re-tick.
3116
- * @param retick - Runs after the re-measurement, on the frame.
3117
- */
3118
- export function scheduleLyricPositionUpdate(engine, isViewRendering, retick) {
3119
- if (engine.pendingLyricsUpdateFrame !== null) {
3120
- return;
3121
- }
3122
- dropPendingLineScroll(engine);
3123
- engine.pendingLyricsUpdateFrame = engine.window.requestAnimationFrame(() => {
3124
- engine.pendingLyricsUpdateFrame = null;
3125
- const isRendering = isViewRendering();
3126
- const playSlide = isRendering ? captureDecorationSlide(engine) : null;
3127
- relayout(engine, isRendering);
3128
- playSlide?.();
3129
- if (!isRendering)
3130
- return;
3131
- retick();
3132
- });
3133
- }