@braccato/core 1.20.0 → 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 +1 -1
  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 +6 -3
  68. package/package.json +1 -1
  69. package/dist/engine.d.ts +0 -471
  70. package/dist/engine.js +0 -3133
@@ -0,0 +1,319 @@
1
+ import { CREDITS_CLASS } from "../constants.js";
2
+ import { layoutStage, planStage, queuedStageY, stageTextSpan, } from "../stage.js";
3
+ import { getCSSNumber } from "./cssValues.js";
4
+ import { REDUCED_MOTION_QUERY } from "./motionPreference.js";
5
+ const STAGE_MOTION = { durationMs: 380, easing: "cubic-bezier(0.2, 0, 0, 1)" };
6
+ // Read by an important rule in stage.css, so a theme's own important opacity cannot reveal a line the stage
7
+ // is hiding or fading.
8
+ const STAGE_OPACITY_PROPERTY = "--blyrics-stage-opacity";
9
+ const STAGE_FADE_IN_MS = 300;
10
+ const STAGE_FADE_IN_DELAY_MS = 70;
11
+ const STAGE_FADE_OUT_MS = 220;
12
+ const HANDOFF_BLUR = "blur(3px)";
13
+ const STAGE_GAP_EM = 0.32;
14
+ const ELEMENT_NODE = 1;
15
+ const TEXT_NODE = 3;
16
+ const UNMEASURED = { height: 0, left: 0, width: 0, originX: 0 };
17
+ const stageOpacityRegistrations = new WeakSet();
18
+ export function applyStage(engine, timeS, instant) {
19
+ const container = engine.lyricsContainer;
20
+ if (!container)
21
+ return;
22
+ registerStageOpacity(engine);
23
+ const { elements, items } = stageElements(engine);
24
+ const roles = planStage(items, timeS);
25
+ const key = roles.join(",");
26
+ if (key === engine.stageKey && !instant)
27
+ return;
28
+ engine.stageKey = key;
29
+ const remeasured = engine.stageRemeasured;
30
+ engine.stageRemeasured = false;
31
+ const metrics = elements.map(element => engine.stageMetrics.get(element) ?? UNMEASURED);
32
+ const geometry = {
33
+ stageHeight: container.clientHeight,
34
+ gap: engine.stageFontSize * STAGE_GAP_EM,
35
+ activeScale: getCSSNumber(engine, container, "--blyrics-active-scale", 1),
36
+ };
37
+ const floorShift = remeasured && engine.stageHeight > 0 ? geometry.stageHeight - engine.stageHeight : 0;
38
+ engine.stageHeight = geometry.stageHeight;
39
+ const previousYs = elements.map(element => {
40
+ const y = engine.stageY.get(element);
41
+ return y === undefined ? null : y + floorShift;
42
+ });
43
+ const { placements, box } = layoutStage(roles, items, metrics, previousYs, geometry);
44
+ const moves = prepareStageMoves(engine, elements, roles, placements, metrics, geometry, { remeasured, instant });
45
+ const reduced = engine.window.matchMedia(REDUCED_MOTION_QUERY).matches;
46
+ elements.forEach((element, index) => {
47
+ if (element.dataset.stageRole !== roles[index])
48
+ element.dataset.stageRole = roles[index];
49
+ });
50
+ for (const move of moves)
51
+ placeStageElement(engine, move, instant, reduced);
52
+ if (!sameBox(box, engine.stageBox)) {
53
+ engine.stageBox = box;
54
+ engine.host.onStageLayout?.(box);
55
+ }
56
+ }
57
+ function prepareStageMoves(engine, elements, roles, placements, metrics, geometry, { remeasured, instant }) {
58
+ const moves = [];
59
+ elements.forEach((element, index) => {
60
+ const placement = placements[index];
61
+ const role = element.dataset.stageRole;
62
+ const previousY = engine.stageY.get(element);
63
+ const wasVisible = role !== undefined && isStageRoleVisible(role);
64
+ const onScreen = placement.visible || element.dataset.stageVisible !== undefined;
65
+ if (remeasured && !instant && onScreen && role === roles[index]) {
66
+ if (previousY !== placement.y)
67
+ snapStageElement(engine, element, placement.y);
68
+ return;
69
+ }
70
+ const unchanged = previousY !== undefined && wasVisible === placement.visible && (!placement.visible || previousY === placement.y);
71
+ if (unchanged && !instant)
72
+ return;
73
+ const risesFromBelowFloor = role === "queued" && placement.visible;
74
+ moves.push({
75
+ element,
76
+ placement,
77
+ wasVisible,
78
+ fromY: risesFromBelowFloor
79
+ ? queuedStageY(geometry.stageHeight, metrics[index].height, geometry.gap)
80
+ : currentTranslateY(engine, element, previousY ?? placement.y),
81
+ fromOpacity: Number(engine.window.getComputedStyle(element).opacity) || 0,
82
+ });
83
+ });
84
+ return moves;
85
+ }
86
+ function placeStageElement(engine, { element, placement, wasVisible, fromY, fromOpacity }, instant, reduced) {
87
+ engine.stageMoves.get(element)?.cancel();
88
+ engine.stageFades.get(element)?.cancel();
89
+ engine.stageMoves.set(element, element.animate([{ translate: `0 ${fromY}px` }, { translate: `0 ${placement.y}px` }], {
90
+ duration: instant || reduced ? 0 : STAGE_MOTION.durationMs,
91
+ easing: STAGE_MOTION.easing,
92
+ fill: "forwards",
93
+ }));
94
+ const showing = placement.visible;
95
+ const fadeMs = instant ? 0 : showing ? STAGE_FADE_IN_MS : STAGE_FADE_OUT_MS;
96
+ const delayMs = showing && !instant ? STAGE_FADE_IN_DELAY_MS : 0;
97
+ if (showing)
98
+ element.dataset.stageVisible = "";
99
+ else if (fadeMs === 0)
100
+ delete element.dataset.stageVisible;
101
+ const fade = element.animate([{ [STAGE_OPACITY_PROPERTY]: fromOpacity }, { [STAGE_OPACITY_PROPERTY]: showing ? 1 : 0 }], {
102
+ duration: fadeMs,
103
+ delay: delayMs,
104
+ easing: showing ? "ease-out" : "ease",
105
+ // Backwards fill preserves the sampled opacity during the replacement fade's delay.
106
+ fill: "both",
107
+ });
108
+ if (!showing && fadeMs > 0) {
109
+ fade.onfinish = () => {
110
+ if (engine.stageFades.get(element) === fade)
111
+ delete element.dataset.stageVisible;
112
+ };
113
+ }
114
+ engine.stageFades.set(element, fade);
115
+ engine.stageY.set(element, placement.y);
116
+ engine.stageBlurs.get(element)?.cancel();
117
+ engine.stageBlurs.delete(element);
118
+ if (fadeMs === 0 || reduced || wasVisible === showing)
119
+ return;
120
+ const blurs = showing ? [HANDOFF_BLUR, "none"] : ["none", HANDOFF_BLUR];
121
+ engine.stageBlurs.set(element, element.animate(blurs.map(filter => ({ filter })), {
122
+ duration: fadeMs,
123
+ delay: showing ? STAGE_FADE_IN_DELAY_MS : 0,
124
+ easing: showing ? "ease-out" : "ease",
125
+ // Add to the theme's filter; release the blur once focused.
126
+ composite: "add",
127
+ fill: showing ? "backwards" : "forwards",
128
+ }));
129
+ }
130
+ function snapStageElement(engine, element, y) {
131
+ engine.stageMoves.get(element)?.cancel();
132
+ engine.stageMoves.set(element, element.animate([{ translate: `0 ${y}px` }], { duration: 0, fill: "forwards" }));
133
+ engine.stageY.set(element, y);
134
+ }
135
+ // Registered from script because Firefox was seen not to apply @property from this package's stylesheet
136
+ // when it loads cross-origin to the page. An unregistered property would snap instead of interpolating.
137
+ function registerStageOpacity(engine) {
138
+ const css = engine.window.CSS;
139
+ if (stageOpacityRegistrations.has(engine.window) || typeof css?.registerProperty !== "function")
140
+ return;
141
+ stageOpacityRegistrations.add(engine.window);
142
+ try {
143
+ css.registerProperty({ name: STAGE_OPACITY_PROPERTY, syntax: "<number>", inherits: false, initialValue: "0" });
144
+ }
145
+ catch (error) {
146
+ engine.host.log("Stage opacity property was already registered", error);
147
+ }
148
+ }
149
+ export function measureStage(engine) {
150
+ engine.stageMetrics.clear();
151
+ const container = engine.lyricsContainer;
152
+ if (!container)
153
+ return;
154
+ engine.stageFontSize = Number.parseFloat(engine.window.getComputedStyle(container).fontSize) || 16;
155
+ const range = engine.document.createRange();
156
+ for (const element of stageElements(engine).elements) {
157
+ const style = engine.window.getComputedStyle(element);
158
+ const originX = originXOf(style.textAlign);
159
+ const padding = {
160
+ left: Number.parseFloat(style.paddingLeft) || 0,
161
+ right: Number.parseFloat(style.paddingRight) || 0,
162
+ };
163
+ const contentRects = collectContentRects(engine, range, element, contentWidthOf(element, style), []);
164
+ const span = stageTextSpan(element.offsetLeft, element.offsetWidth, element.getBoundingClientRect(), contentRects, padding, originX);
165
+ engine.stageMetrics.set(element, { height: element.offsetHeight, left: span.left, width: span.width, originX });
166
+ }
167
+ forceStageReplan(engine);
168
+ engine.stageRemeasured = true;
169
+ }
170
+ export function replaceStageElements(engine, dropped, previousOf) {
171
+ for (const [line, previous] of previousOf)
172
+ carryStageState(engine, previous.lyricElement, line.lyricElement);
173
+ for (const line of dropped)
174
+ forgetStageElement(engine, line.lyricElement);
175
+ forceStageReplan(engine);
176
+ }
177
+ function carryStageState(engine, from, to) {
178
+ const role = from.dataset.stageRole;
179
+ const y = engine.stageY.get(from);
180
+ if (role === undefined || y === undefined)
181
+ return;
182
+ to.dataset.stageRole = role;
183
+ if (from.dataset.stageVisible !== undefined)
184
+ to.dataset.stageVisible = "";
185
+ const move = continueAnimation(engine.stageMoves.get(from), to);
186
+ if (move === null) {
187
+ snapStageElement(engine, to, y);
188
+ }
189
+ else {
190
+ engine.stageMoves.set(to, move);
191
+ engine.stageY.set(to, y);
192
+ }
193
+ const visible = isStageRoleVisible(role);
194
+ const fade = continueAnimation(engine.stageFades.get(from), to) ??
195
+ to.animate([{ [STAGE_OPACITY_PROPERTY]: visible ? 1 : 0 }], { duration: 0, fill: "forwards" });
196
+ if (!visible) {
197
+ fade.onfinish = () => {
198
+ if (engine.stageFades.get(to) === fade)
199
+ delete to.dataset.stageVisible;
200
+ };
201
+ }
202
+ engine.stageFades.set(to, fade);
203
+ const blur = continueAnimation(engine.stageBlurs.get(from), to);
204
+ if (blur !== null)
205
+ engine.stageBlurs.set(to, blur);
206
+ }
207
+ function forgetStageElement(engine, element) {
208
+ for (const animations of [engine.stageMoves, engine.stageFades, engine.stageBlurs]) {
209
+ animations.get(element)?.cancel();
210
+ animations.delete(element);
211
+ }
212
+ engine.stageY.delete(element);
213
+ engine.stageMetrics.delete(element);
214
+ }
215
+ export function resetStage(engine) {
216
+ for (const animations of [engine.stageMoves, engine.stageFades, engine.stageBlurs]) {
217
+ for (const animation of animations.values())
218
+ animation.cancel();
219
+ animations.clear();
220
+ }
221
+ engine.stageMetrics.clear();
222
+ engine.stageY.clear();
223
+ forceStageReplan(engine);
224
+ engine.stageHeight = 0;
225
+ if (engine.stageBox !== null) {
226
+ engine.stageBox = null;
227
+ engine.host.onStageLayout?.(null);
228
+ }
229
+ }
230
+ export function currentTranslateY(engine, element, fallback) {
231
+ const y = Number.parseFloat(engine.window.getComputedStyle(element).translate.split(" ")[1] ?? "");
232
+ return Number.isFinite(y) ? y : fallback;
233
+ }
234
+ function forceStageReplan(engine) {
235
+ engine.stageKey = "";
236
+ }
237
+ function continueAnimation(animation, element) {
238
+ const effect = animation?.effect;
239
+ if (!animation || typeof effect?.getKeyframes !== "function")
240
+ return null;
241
+ if (animation.playState === "finished" || animation.playState === "idle")
242
+ return null;
243
+ const continued = element.animate(effect.getKeyframes(), { ...effect.getTiming(), composite: effect.composite });
244
+ continued.playbackRate = animation.playbackRate;
245
+ continued.currentTime = animation.currentTime;
246
+ if (animation.playState === "paused")
247
+ continued.pause();
248
+ return continued;
249
+ }
250
+ function stageElements(engine) {
251
+ const elements = [];
252
+ const items = [];
253
+ let lastEnd = 0;
254
+ for (const line of engine.lines) {
255
+ const end = line.time + line.duration;
256
+ lastEnd = Math.max(lastEnd, end);
257
+ elements.push(line.lyricElement);
258
+ items.push({ kind: stageItemKind(line.lyricElement), start: line.time, end });
259
+ }
260
+ const credits = engine.lyricsContainer?.querySelector(`:scope > .${CREDITS_CLASS}`);
261
+ if (credits) {
262
+ elements.push(credits);
263
+ items.push({ kind: "credits", start: lastEnd, end: Number.POSITIVE_INFINITY });
264
+ }
265
+ return { elements, items };
266
+ }
267
+ function stageItemKind(element) {
268
+ if (element.dataset.instrumental === "true")
269
+ return "instrumental";
270
+ if (element.dataset.blank === "true")
271
+ return "blank";
272
+ return "line";
273
+ }
274
+ function isStageRoleVisible(role) {
275
+ return role !== "queued" && role !== "gone";
276
+ }
277
+ function sameBox(a, b) {
278
+ if (a === null || b === null)
279
+ return a === b;
280
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
281
+ }
282
+ function originXOf(align) {
283
+ if (align === "center")
284
+ return 0.5;
285
+ if (align === "right" || align === "end")
286
+ return 1;
287
+ return 0;
288
+ }
289
+ function contentWidthOf(element, style) {
290
+ const padding = (Number.parseFloat(style.paddingLeft) || 0) + (Number.parseFloat(style.paddingRight) || 0);
291
+ return element.clientWidth - padding;
292
+ }
293
+ function fillsWidth(element, contentWidth) {
294
+ return element.offsetWidth >= contentWidth - 1;
295
+ }
296
+ function collectContentRects(engine, range, node, contentWidth, rects) {
297
+ for (const child of node.childNodes) {
298
+ if (child.nodeType === TEXT_NODE) {
299
+ range.selectNodeContents(child);
300
+ rects.push(...range.getClientRects());
301
+ continue;
302
+ }
303
+ if (child.nodeType !== ELEMENT_NODE)
304
+ continue;
305
+ const element = child;
306
+ const style = engine.window.getComputedStyle(element);
307
+ if (style.display === "none")
308
+ continue;
309
+ if (style.display === "contents")
310
+ collectContentRects(engine, range, element, contentWidth, rects);
311
+ else if (style.display.startsWith("inline"))
312
+ rects.push(...element.getClientRects());
313
+ else if (!fillsWidth(element, contentWidth))
314
+ rects.push(element.getBoundingClientRect());
315
+ else
316
+ collectContentRects(engine, range, element, contentWidthOf(element, style), rects);
317
+ }
318
+ return rects;
319
+ }
@@ -0,0 +1,13 @@
1
+ import type { ResolvedTickOptions, TickOptions } from "../types.js";
2
+ import type { AnimationEngineInstance } from "./instance.js";
3
+ /**
4
+ * "lyrics-missing" means this instance has nothing left to render. Whether that ends ticking is the
5
+ * driver's call, not the instance's: one instance running dry must not silence another.
6
+ */
7
+ export type AnimationTickStatus = "ok" | "lyrics-missing";
8
+ export declare function resolveTickOptions(options: TickOptions): ResolvedTickOptions;
9
+ export declare function tickView(engine: AnimationEngineInstance, reportedTimeS: number, options: ResolvedTickOptions): AnimationTickStatus;
10
+ export declare function relayout(engine: AnimationEngineInstance, linesAreRendered: boolean): void;
11
+ export declare function cancelLyricPositionUpdate(engine: AnimationEngineInstance): void;
12
+ export declare function retickFromPlaybackClock(engine: AnimationEngineInstance, buildTickOptions: (eventCreationTime: number, isPlaying: boolean) => TickOptions): AnimationTickStatus;
13
+ export declare function scheduleLyricPositionUpdate(engine: AnimationEngineInstance, isViewRendering: () => boolean, retick: () => void): void;
@@ -0,0 +1,246 @@
1
+ import { CREDITS_CLASS, CURRENT_LYRICS_CLASS, FOOTER_CLASS } from "../constants.js";
2
+ import { getRelativeLayoutBounds } from "../util.js";
3
+ import { getAnimationSettings } from "./animationConfig.js";
4
+ import { applyPlaybackRateToRunningAnimations, correctedScrollTimeS } from "./animationTiming.js";
5
+ import { followFocusedLines, lastSungLine } from "./autoScroll.js";
6
+ import { advancePlaybackClock, lyricClockShiftS, NO_PLAYER_SNAPSHOT, playbackClock } from "./clock.js";
7
+ import { getCSSDurationInMs } from "./cssValues.js";
8
+ import { clearOffscreenLineCulling, clearVisibleLyricWillChange, setupLineCullObserver, updateVisibleLyricWillChange, } from "./culling.js";
9
+ import { captureDecorationSlide, lineDecorators } from "./decorationSlides.js";
10
+ import { driveLineAnimations } from "./lineLifecycle.js";
11
+ import { clearLineScrollAnimations, dropPendingLineScroll, measureTrailingItem } from "./lineScroll.js";
12
+ import { hasNoLyricsPlaceholder, hasUnsyncedLyrics, startPassiveScrollLoop, stopPassiveScrollLoop, } from "./passiveScroll.js";
13
+ import { applyScrollPadding, measureScrollViewport, setupTabRendererObserver } from "./scrollViewport.js";
14
+ import { applyStage, measureStage } from "./stageMotion.js";
15
+ import { requestRescroll } from "./userScroll.js";
16
+ const NO_LYRICS_ELEMENT_LOG = "No lyrics element found on the page, skipping lyrics injection";
17
+ const TICK_ERROR_LOG = "Error in lyrics tick:";
18
+ export function resolveTickOptions(options) {
19
+ return {
20
+ isPlaying: options.isPlaying,
21
+ eventCreationTime: options.eventCreationTime ?? NO_PLAYER_SNAPSHOT,
22
+ smoothScroll: options.smoothScroll ?? true,
23
+ globalLyricOffset: options.globalLyricOffset ?? 0,
24
+ lyricOffset: options.lyricOffset ?? 0,
25
+ richsyncOffsetTrim: options.richsyncOffsetTrim ?? 0,
26
+ lineOffsetTrim: options.lineOffsetTrim ?? 0,
27
+ passiveScrollEnabled: options.passiveScrollEnabled ?? false,
28
+ playbackRate: usablePlaybackRate(options.playbackRate),
29
+ followPausedSeeks: options.followPausedSeeks ?? false,
30
+ countEveryUserScroll: options.countEveryUserScroll ?? false,
31
+ };
32
+ }
33
+ function usablePlaybackRate(rate) {
34
+ return rate !== undefined && Number.isFinite(rate) && rate > 0 ? rate : 1;
35
+ }
36
+ export function tickView(engine, reportedTimeS, options) {
37
+ rememberTickOptions(engine, options);
38
+ if (reportedTimeS === 0 && !options.isPlaying)
39
+ return "ok";
40
+ if (hasNoLyricsPlaceholder(engine)) {
41
+ stopPassiveScrollLoop(engine);
42
+ return "ok";
43
+ }
44
+ if (hasUnsyncedLyrics(engine)) {
45
+ followUnsyncedLyrics(engine, options);
46
+ return "ok";
47
+ }
48
+ const now = Date.now();
49
+ const playhead = advancePlaybackClock(reportedTimeS, options, engine.playbackRate, now);
50
+ if (playhead.jumped)
51
+ dropPendingLineScroll(engine);
52
+ if (!engine.host.isViewVisible()) {
53
+ clearVisibleLyricWillChange(engine);
54
+ return "ok";
55
+ }
56
+ if (engine.host.syncAdState())
57
+ return "ok";
58
+ const lyricsElement = engine.lyricsContainer;
59
+ if (!lyricsElement) {
60
+ engine.host.log(NO_LYRICS_ELEMENT_LOG);
61
+ return "lyrics-missing";
62
+ }
63
+ try {
64
+ renderSyncedLyrics(engine, lyricsElement, playhead, options, now);
65
+ }
66
+ catch (error) {
67
+ if (!isUndefinedAccessError(error))
68
+ engine.host.log(TICK_ERROR_LOG, error);
69
+ }
70
+ return "ok";
71
+ }
72
+ function rememberTickOptions(engine, options) {
73
+ engine.lastTickOptions = options;
74
+ engine.passiveScrollEnabled = options.passiveScrollEnabled;
75
+ if (engine.playbackRate === options.playbackRate)
76
+ return;
77
+ engine.playbackRate = options.playbackRate;
78
+ applyPlaybackRateToRunningAnimations(engine);
79
+ }
80
+ function followUnsyncedLyrics(engine, { isPlaying, passiveScrollEnabled }) {
81
+ if (engine.layout === "stage")
82
+ return;
83
+ if (isPlaying && !playbackClock.lastPlayState)
84
+ engine.scrollResumeTime = 0;
85
+ playbackClock.lastPlayState = isPlaying;
86
+ if (passiveScrollEnabled)
87
+ startPassiveScrollLoop(engine);
88
+ }
89
+ function isUndefinedAccessError(error) {
90
+ return error.message?.includes("undefined") ?? false;
91
+ }
92
+ function renderSyncedLyrics(engine, lyricsElement, playhead, options, now) {
93
+ const lyricTimeS = playhead.timeS + lyricClockShiftS(engine, lyricsElement, options);
94
+ const scrollTimeS = correctedScrollTimeS(engine, lyricTimeS) +
95
+ getCSSDurationInMs(engine, lyricsElement, "--blyrics-scroll-timing-offset") / 1000;
96
+ const { config, scrollTiming } = getAnimationSettings(engine, lyricsElement);
97
+ const isStage = engine.layout === "stage";
98
+ const scroller = isStage ? null : readScrollerBeforeWrites(engine);
99
+ if (!isStage && !scroller) {
100
+ clearVisibleLyricWillChange(engine);
101
+ return;
102
+ }
103
+ if (scroller && config.enabled.scroll) {
104
+ const pendingScrollTop = engine.pendingLineScroll?.toScrollTop ?? scroller.scrollTop;
105
+ updateVisibleLyricWillChange(engine, engine.lines, scroller.scrollTop, pendingScrollTop, scroller.height);
106
+ }
107
+ else {
108
+ stopLineScrolling(engine);
109
+ }
110
+ const focus = focusLines(engine, scrollTimeS, scrollTiming.earlyScrollConsiderS);
111
+ driveLineAnimations({ engine, lyricTimeS, playhead, config, now });
112
+ const creditsFocusChanged = updateCreditsFocus(engine, lyricsElement, scrollTimeS);
113
+ if (!scroller) {
114
+ applyStage(engine, lyricTimeS, playhead.jumped);
115
+ return;
116
+ }
117
+ followFocusedLines({
118
+ engine,
119
+ lyricsElement,
120
+ scroller,
121
+ focusedLines: focus.lines,
122
+ scrollTimeS,
123
+ config,
124
+ smoothScroll: options.smoothScroll,
125
+ countEveryUserScroll: options.countEveryUserScroll,
126
+ jumped: playhead.jumped,
127
+ focusChanged: playhead.jumped || focus.reachedUncommittedLine || creditsFocusChanged,
128
+ now,
129
+ });
130
+ }
131
+ function readScrollerBeforeWrites(engine) {
132
+ const element = engine.host.getScrollElement();
133
+ if (!element)
134
+ return null;
135
+ if (element !== engine.observedTabRenderer)
136
+ setupTabRendererObserver(engine, element);
137
+ return {
138
+ element,
139
+ height: engine.cachedTabRendererHeight ?? element.getBoundingClientRect().height,
140
+ scrollTop: element.scrollTop,
141
+ maxScrollTop: Math.max(0, element.scrollHeight - element.clientHeight),
142
+ };
143
+ }
144
+ function stopLineScrolling(engine) {
145
+ dropPendingLineScroll(engine);
146
+ clearVisibleLyricWillChange(engine);
147
+ clearLineScrollAnimations(engine);
148
+ }
149
+ function focusLines(engine, scrollTimeS, earlyScrollConsiderS) {
150
+ const lines = engine.lines;
151
+ const focused = [];
152
+ let reachedUncommittedLine = false;
153
+ for (let index = 0; index < lines.length; index++) {
154
+ const line = lines[index];
155
+ const nextLineStartS = lines[index + 1]?.time ?? Infinity;
156
+ const inFocus = scrollTimeS >= line.time - earlyScrollConsiderS &&
157
+ (scrollTimeS < nextLineStartS || scrollTimeS < line.time + line.duration);
158
+ setLineCurrent(line, inFocus);
159
+ if (!inFocus)
160
+ continue;
161
+ focused.push(line);
162
+ engine.selectedElementIndex = index;
163
+ if (scrollTimeS >= line.time && !engine.lastScrollElements.includes(line))
164
+ reachedUncommittedLine = true;
165
+ }
166
+ return { lines: focused, reachedUncommittedLine };
167
+ }
168
+ function setLineCurrent(line, current) {
169
+ if (line.isScrolled === current)
170
+ return;
171
+ line.isScrolled = current;
172
+ line.lyricElement.classList.toggle(CURRENT_LYRICS_CLASS, current);
173
+ }
174
+ function updateCreditsFocus(engine, lyricsElement, scrollTimeS) {
175
+ const lastLine = lastSungLine(engine);
176
+ const focused = lastLine !== undefined &&
177
+ (engine.cachedCreditsItem?.height ?? 0) > 0 &&
178
+ scrollTimeS >= lastLine.time + lastLine.duration;
179
+ if (focused === engine.creditsFocused)
180
+ return false;
181
+ engine.creditsFocused = focused;
182
+ if (focused)
183
+ lyricsElement.dataset.creditsFocused = "true";
184
+ else
185
+ delete lyricsElement.dataset.creditsFocused;
186
+ return true;
187
+ }
188
+ export function relayout(engine, linesAreRendered) {
189
+ if (engine.layout === "stage") {
190
+ if (!linesAreRendered || !engine.lyricsContainer)
191
+ return;
192
+ engine.cachedCreditsItem = measureTrailingItem(engine.lyricsContainer, CREDITS_CLASS);
193
+ measureStage(engine);
194
+ return;
195
+ }
196
+ applyScrollPadding(engine);
197
+ const scrollElement = engine.host.getScrollElement();
198
+ if (scrollElement)
199
+ measureScrollViewport(engine, scrollElement);
200
+ if (!linesAreRendered)
201
+ return;
202
+ const lyricsElement = engine.lyricsContainer;
203
+ if (!lyricsElement)
204
+ return;
205
+ engine.lyricWidth = lyricsElement.clientWidth;
206
+ engine.lyricHeight = lyricsElement.clientHeight;
207
+ measureLinePositions(engine, lyricsElement);
208
+ engine.cachedCreditsItem = measureTrailingItem(lyricsElement, CREDITS_CLASS);
209
+ engine.cachedFooterItem = measureTrailingItem(lyricsElement, FOOTER_CLASS);
210
+ setupLineCullObserver(engine);
211
+ requestRescroll(engine);
212
+ engine.host.debug?.resize();
213
+ }
214
+ function measureLinePositions(engine, lyricsElement) {
215
+ clearOffscreenLineCulling(engine);
216
+ for (const line of engine.lines) {
217
+ const bounds = getRelativeLayoutBounds(lyricsElement, line.lyricElement);
218
+ line.position = bounds.y;
219
+ line.height = bounds.height;
220
+ line.decorations = new Map(lineDecorators(line.lyricElement).map(element => [element, getRelativeLayoutBounds(lyricsElement, element).y]));
221
+ }
222
+ }
223
+ export function cancelLyricPositionUpdate(engine) {
224
+ if (engine.pendingLyricsUpdateFrame === null)
225
+ return;
226
+ engine.window.cancelAnimationFrame(engine.pendingLyricsUpdateFrame);
227
+ engine.pendingLyricsUpdateFrame = null;
228
+ }
229
+ export function retickFromPlaybackClock(engine, buildTickOptions) {
230
+ const options = buildTickOptions(playbackClock.lastEventCreationTime, playbackClock.lastPlayState);
231
+ return tickView(engine, playbackClock.lastTime, resolveTickOptions(options));
232
+ }
233
+ export function scheduleLyricPositionUpdate(engine, isViewRendering, retick) {
234
+ if (engine.pendingLyricsUpdateFrame !== null)
235
+ return;
236
+ dropPendingLineScroll(engine);
237
+ engine.pendingLyricsUpdateFrame = engine.window.requestAnimationFrame(() => {
238
+ engine.pendingLyricsUpdateFrame = null;
239
+ const isRendering = isViewRendering();
240
+ const playSlide = isRendering ? captureDecorationSlide(engine) : null;
241
+ relayout(engine, isRendering);
242
+ playSlide?.();
243
+ if (isRendering)
244
+ retick();
245
+ });
246
+ }
@@ -0,0 +1,7 @@
1
+ import type { LineData } from "../inject.js";
2
+ import type { DriftSample } from "./animationTiming.js";
3
+ import type { AnimationEngineInstance } from "./instance.js";
4
+ export declare function shouldLogAnimationTiming(engine: AnimationEngineInstance, line: LineData, sample: DriftSample, now: number): boolean;
5
+ export declare function logAnimationTiming(engine: AnimationEngineInstance, reason: string, line: LineData, lineIndex: number, sample: DriftSample, lyricTimeS: number, accumulatedOffsetMs: number, learnedOffsetMs?: number): void;
6
+ export declare function logAnimationCleanup(engine: AnimationEngineInstance, reason: string, line: LineData, lineIndex: number, lyricTimeS: number, staleAfterS: number): void;
7
+ export declare function noteVisibilityChange(engine: AnimationEngineInstance): void;
@@ -0,0 +1,81 @@
1
+ import { registerThemeSetting } from "../themeSettings.js";
2
+ import { roundedMs } from "../util.js";
3
+ const TIMING_LOGS_ENABLED = registerThemeSetting("blyrics-debug-animation-timing", false);
4
+ const VISIBILITY_LOG_WINDOW_MS = 3000;
5
+ const PER_LINE_LOG_INTERVAL_MS = 750;
6
+ const LOGGED_OFFSET_THRESHOLD_MS = 30;
7
+ const lastLogTimes = new WeakMap();
8
+ export function shouldLogAnimationTiming(engine, line, sample, now) {
9
+ if (!TIMING_LOGS_ENABLED.getBooleanValue())
10
+ return false;
11
+ const inVisibilityWindow = now < engine.animationTimingVisibilityLogUntil;
12
+ if (!inVisibilityWindow && Math.abs(sample.offsetMs) < LOGGED_OFFSET_THRESHOLD_MS)
13
+ return false;
14
+ if (now - (lastLogTimes.get(line) ?? 0) < PER_LINE_LOG_INTERVAL_MS)
15
+ return false;
16
+ lastLogTimes.set(line, now);
17
+ return true;
18
+ }
19
+ export function logAnimationTiming(engine, reason, line, lineIndex, sample, lyricTimeS, accumulatedOffsetMs, learnedOffsetMs = engine.learnedAnimationTimingOffsetMs) {
20
+ if (!TIMING_LOGS_ENABLED.getBooleanValue())
21
+ return;
22
+ engine.host.log("WAAPI timing", {
23
+ reason,
24
+ lineIndex,
25
+ lineTimeS: roundedSeconds(line.time),
26
+ mediaTimeS: roundedSeconds(lyricTimeS),
27
+ actualTimeMs: roundedMs(sample.actualTimeMs),
28
+ expectedTimeMs: roundedMs(sample.expectedTimeMs),
29
+ offsetMs: roundedMs(sample.offsetMs),
30
+ learnedOffsetMs: roundedMs(learnedOffsetMs),
31
+ appliedTimingOffsetMs: roundedMs(sample.appliedTimingOffsetMs),
32
+ biasOffsetMs: roundedMs(sample.biasOffsetMs),
33
+ residualOffsetMs: roundedMs(sample.offsetMs),
34
+ accumulatedOffsetMs: roundedMs(accumulatedOffsetMs),
35
+ playState: sample.playState,
36
+ text: linePreview(line),
37
+ });
38
+ }
39
+ export function logAnimationCleanup(engine, reason, line, lineIndex, lyricTimeS, staleAfterS) {
40
+ if (!TIMING_LOGS_ENABLED.getBooleanValue())
41
+ return;
42
+ engine.host.log("Animation cleanup", {
43
+ reason,
44
+ lineIndex,
45
+ lineTimeS: roundedSeconds(line.time),
46
+ mediaTimeS: roundedSeconds(lyricTimeS),
47
+ staleAnimationEndTimeS: roundedSeconds(staleAfterS),
48
+ runningAnimationCount: countAnimations(line),
49
+ text: linePreview(line),
50
+ });
51
+ }
52
+ export function noteVisibilityChange(engine) {
53
+ if (!TIMING_LOGS_ENABLED.getBooleanValue() || !engine.lyricsContainer)
54
+ return;
55
+ const visibilityState = engine.document.visibilityState;
56
+ const runningAnimationCount = engine.lines.reduce((count, line) => count + countAnimations(line), 0);
57
+ if (visibilityState !== "visible") {
58
+ engine.host.log("Visibility changed; WAAPI animations left intact", {
59
+ visibilityState,
60
+ runningAnimationCount,
61
+ resetSkipped: true,
62
+ });
63
+ return;
64
+ }
65
+ engine.animationTimingVisibilityLogUntil = Date.now() + VISIBILITY_LOG_WINDOW_MS;
66
+ engine.host.log("Visibility changed; keeping WAAPI animations for timing verification", {
67
+ visibilityState,
68
+ runningAnimationCount,
69
+ resetSkipped: true,
70
+ timingLogWindowMs: VISIBILITY_LOG_WINDOW_MS,
71
+ });
72
+ }
73
+ function countAnimations(line) {
74
+ return line.parts.reduce((count, part) => count + part.animations.length, line.animations.length);
75
+ }
76
+ function roundedSeconds(timeS) {
77
+ return roundedMs(timeS * 1000) / 1000;
78
+ }
79
+ function linePreview(line) {
80
+ return line.lyricElement.textContent?.trim().replace(/\s+/g, " ").slice(0, 80) ?? "";
81
+ }
@@ -0,0 +1,12 @@
1
+ import type { AnimationEngineInstance } from "./instance.js";
2
+ export declare function resetScrollResume(engine: AnimationEngineInstance): void;
3
+ /**
4
+ * Resume autoscroll immediately for every live view.
5
+ */
6
+ export declare function resumeAllAutoscroll(): void;
7
+ export declare function noteUserScroll(engine: AnimationEngineInstance, lyricsAreUnsynced: boolean): void;
8
+ export declare function hasContainerResized(engine: AnimationEngineInstance, width: number, height: number): boolean;
9
+ export declare function writeEngineScrollTop(engine: AnimationEngineInstance, scroller: HTMLElement, scrollTop: number, now: number): void;
10
+ export declare function noteEngineScrollEvent(engine: AnimationEngineInstance, now: number): void;
11
+ export declare function requestRescroll(engine: AnimationEngineInstance): void;
12
+ export declare function decaySkipScrolls(engine: AnimationEngineInstance, now: number, keepsReserve: boolean): void;