@braccato/core 1.20.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +40 -37
  2. package/dist/README.md +40 -37
  3. package/dist/constants.d.ts +10 -0
  4. package/dist/constants.js +10 -0
  5. package/dist/engine/animationConfig.d.ts +83 -0
  6. package/dist/engine/animationConfig.js +93 -0
  7. package/dist/engine/animationDrift.d.ts +11 -0
  8. package/dist/engine/animationDrift.js +43 -0
  9. package/dist/engine/animationTiming.d.ts +26 -0
  10. package/dist/engine/animationTiming.js +120 -0
  11. package/dist/engine/autoScroll.d.ts +24 -0
  12. package/dist/engine/autoScroll.js +103 -0
  13. package/dist/engine/clock.d.ts +29 -0
  14. package/dist/engine/clock.js +70 -0
  15. package/dist/engine/contextSweep.d.ts +10 -0
  16. package/dist/engine/contextSweep.js +102 -0
  17. package/dist/engine/cssValues.d.ts +13 -0
  18. package/dist/engine/cssValues.js +47 -0
  19. package/dist/engine/culling.d.ts +6 -0
  20. package/dist/engine/culling.js +76 -0
  21. package/dist/engine/debugOverlay.d.ts +14 -0
  22. package/dist/engine/debugOverlay.js +58 -0
  23. package/dist/engine/decorationSlides.d.ts +6 -0
  24. package/dist/engine/decorationSlides.js +53 -0
  25. package/dist/engine/elementMotion.d.ts +17 -0
  26. package/dist/engine/elementMotion.js +98 -0
  27. package/dist/engine/glow.d.ts +7 -0
  28. package/dist/engine/glow.js +59 -0
  29. package/dist/engine/instance.d.ts +105 -0
  30. package/dist/engine/instance.js +89 -0
  31. package/dist/engine/instrumentalAnimations.d.ts +7 -0
  32. package/dist/engine/instrumentalAnimations.js +59 -0
  33. package/dist/engine/letterPlans.d.ts +31 -0
  34. package/dist/engine/letterPlans.js +62 -0
  35. package/dist/engine/lineAnimationState.d.ts +10 -0
  36. package/dist/engine/lineAnimationState.js +82 -0
  37. package/dist/engine/lineAnimations.d.ts +5 -0
  38. package/dist/engine/lineAnimations.js +63 -0
  39. package/dist/engine/lineLifecycle.d.ts +12 -0
  40. package/dist/engine/lineLifecycle.js +92 -0
  41. package/dist/engine/lineScroll.d.ts +47 -0
  42. package/dist/engine/lineScroll.js +184 -0
  43. package/dist/engine/lineScrollStyle.d.ts +32 -0
  44. package/dist/engine/lineScrollStyle.js +133 -0
  45. package/dist/engine/liveViews.d.ts +3 -0
  46. package/dist/engine/liveViews.js +5 -0
  47. package/dist/engine/motionCurves.d.ts +19 -0
  48. package/dist/engine/motionCurves.js +85 -0
  49. package/dist/engine/motionPreference.d.ts +1 -0
  50. package/dist/engine/motionPreference.js +1 -0
  51. package/dist/engine/passiveScroll.d.ts +10 -0
  52. package/dist/engine/passiveScroll.js +93 -0
  53. package/dist/engine/renderedLines.d.ts +16 -0
  54. package/dist/engine/renderedLines.js +130 -0
  55. package/dist/engine/scrollViewport.d.ts +36 -0
  56. package/dist/engine/scrollViewport.js +104 -0
  57. package/dist/engine/stageMotion.d.ts +7 -0
  58. package/dist/engine/stageMotion.js +319 -0
  59. package/dist/engine/sweepPlans.d.ts +36 -0
  60. package/dist/engine/sweepPlans.js +59 -0
  61. package/dist/engine/tick.d.ts +16 -0
  62. package/dist/engine/tick.js +270 -0
  63. package/dist/engine/timingLogs.d.ts +7 -0
  64. package/dist/engine/timingLogs.js +81 -0
  65. package/dist/engine/userScroll.d.ts +12 -0
  66. package/dist/engine/userScroll.js +62 -0
  67. package/dist/engine/wavePool.d.ts +7 -0
  68. package/dist/engine/wavePool.js +22 -0
  69. package/dist/engine/wordAnimations.d.ts +5 -0
  70. package/dist/engine/wordAnimations.js +238 -0
  71. package/dist/imageHighlights.d.ts +0 -11
  72. package/dist/imageHighlights.js +2 -48
  73. package/dist/index.d.ts +3 -2
  74. package/dist/index.js +2 -1
  75. package/dist/inject.d.ts +41 -2
  76. package/dist/inject.js +73 -28
  77. package/dist/renderer.js +10 -3
  78. package/dist/styles/image-highlights.css +1 -59
  79. package/dist/styles/lyrics.css +128 -57
  80. package/dist/types.d.ts +1 -1
  81. package/dist/view.d.ts +2 -2
  82. package/dist/view.js +7 -3
  83. package/package.json +1 -1
  84. package/dist/engine.d.ts +0 -471
  85. package/dist/engine.js +0 -3133
@@ -0,0 +1,120 @@
1
+ import { positiveModulo, toMs } from "../util.js";
2
+ const songClockTracks = new WeakMap();
3
+ export function followSongClock(engine, animation, track) {
4
+ songClockTracks.set(animation, {
5
+ ...track,
6
+ appliedTimingOffsetMs: track.appliedTimingOffsetMs ?? engine.learnedAnimationTimingOffsetMs,
7
+ });
8
+ animation.playbackRate = engine.playbackRate;
9
+ return animation;
10
+ }
11
+ /** Repeats a word's own animations on the cells of a sweep drawn for it from copies of its line. */
12
+ export function mirrorHighlightAnimations(part, animations) {
13
+ const target = part.sweepContext?.host;
14
+ if (!target)
15
+ return [];
16
+ const mirrors = [];
17
+ for (const animation of animations) {
18
+ const effect = animation.effect;
19
+ if (!effect || effect.target !== part.highlightElement)
20
+ continue;
21
+ const mirror = target.animate(effect.getKeyframes(), effect.getTiming());
22
+ mirror.playbackRate = animation.playbackRate;
23
+ mirror.currentTime = animation.currentTime;
24
+ const track = songClockTracks.get(animation);
25
+ if (track)
26
+ songClockTracks.set(mirror, { ...track, skipDriftSample: true });
27
+ mirrors.push(mirror);
28
+ }
29
+ return mirrors;
30
+ }
31
+ export function applyPlaybackRateToRunningAnimations(engine) {
32
+ const followRate = (animations) => {
33
+ for (const animation of animations) {
34
+ if (songClockTracks.has(animation))
35
+ animation.playbackRate = engine.playbackRate;
36
+ }
37
+ };
38
+ for (const line of engine.lines) {
39
+ followRate(line.animations);
40
+ for (const part of line.parts)
41
+ followRate(part.animations);
42
+ }
43
+ }
44
+ export function correctedAnimationTimeMs(targetTimeMs, appliedTimingOffsetMs, maxTimeMs) {
45
+ const scheduledTimeMs = targetTimeMs - appliedTimingOffsetMs;
46
+ return maxTimeMs === undefined ? scheduledTimeMs : Math.min(scheduledTimeMs, maxTimeMs);
47
+ }
48
+ export function correctedWrappedAnimationTimeMs(targetTimeMs, appliedTimingOffsetMs, wrapDurationMs) {
49
+ return positiveModulo(targetTimeMs - appliedTimingOffsetMs, wrapDurationMs);
50
+ }
51
+ export function correctedScrollTimeS(engine, lyricTimeS) {
52
+ return lyricTimeS - engine.learnedAnimationTimingOffsetMs / 1000;
53
+ }
54
+ export function largestDriftSample(line, lyricTimeS) {
55
+ let largest = accumulateLargestDriftSample(line, lyricTimeS, null);
56
+ for (const part of line.parts)
57
+ largest = accumulateLargestDriftSample(part, lyricTimeS, largest);
58
+ return largest;
59
+ }
60
+ function accumulateLargestDriftSample(part, lyricTimeS, largest) {
61
+ for (const animation of part.animations) {
62
+ const sample = driftSample(part, animation, lyricTimeS);
63
+ if (sample && (!largest || Math.abs(sample.offsetMs) > Math.abs(largest.offsetMs)))
64
+ largest = sample;
65
+ }
66
+ return largest;
67
+ }
68
+ function driftSample(part, animation, lyricTimeS) {
69
+ const track = songClockTracks.get(animation);
70
+ if (!track || track.skipDriftSample || animation.playState === "idle")
71
+ return null;
72
+ const rawActualTimeMs = timingValueToMs(animation.currentTime);
73
+ if (rawActualTimeMs === null)
74
+ return null;
75
+ const expectedTimeMs = normalizedTimeMs(animation, (lyricTimeS - part.time) * 1000 + track.offsetMs, track);
76
+ const actualTimeMs = normalizedTimeMs(animation, rawActualTimeMs, track);
77
+ if (expectedTimeMs === null || actualTimeMs === null)
78
+ return null;
79
+ const wrapDurationMs = track.wrapDurationMs ?? 0;
80
+ const offsetMs = wrapDurationMs > 0 ? wrappedOffsetMs(actualTimeMs, expectedTimeMs, wrapDurationMs) : actualTimeMs - expectedTimeMs;
81
+ return {
82
+ actualTimeMs,
83
+ appliedTimingOffsetMs: track.appliedTimingOffsetMs,
84
+ biasOffsetMs: offsetMs + track.appliedTimingOffsetMs,
85
+ expectedTimeMs,
86
+ offsetMs,
87
+ playState: animation.playState,
88
+ };
89
+ }
90
+ function normalizedTimeMs(animation, timeMs, track) {
91
+ if (!Number.isFinite(timeMs) || timeMs < 0)
92
+ return null;
93
+ if (track.wrapDurationMs && track.wrapDurationMs > 0)
94
+ return positiveModulo(timeMs, track.wrapDurationMs);
95
+ // Clamp to the effect's endTime, including delay/endDelay. Clamping to duration can hide drift in delayed
96
+ // letter waves.
97
+ const endTimeMs = timingValueToMs(animation.effect?.getComputedTiming().endTime);
98
+ return endTimeMs !== null && Number.isFinite(endTimeMs) ? Math.min(timeMs, endTimeMs) : timeMs;
99
+ }
100
+ function wrappedOffsetMs(actualTimeMs, expectedTimeMs, wrapDurationMs) {
101
+ return positiveModulo(actualTimeMs - expectedTimeMs + wrapDurationMs / 2, wrapDurationMs) - wrapDurationMs / 2;
102
+ }
103
+ function timingValueToMs(value) {
104
+ if (typeof value === "number")
105
+ return Number.isFinite(value) || value === Number.POSITIVE_INFINITY ? value : null;
106
+ if (typeof value === "string") {
107
+ const durationMs = toMs(value);
108
+ return durationMs > 0 ? durationMs : null;
109
+ }
110
+ const numeric = value;
111
+ if (typeof numeric?.to !== "function")
112
+ return null;
113
+ try {
114
+ const ms = numeric.to("ms").value;
115
+ return typeof ms === "number" && Number.isFinite(ms) ? ms : null;
116
+ }
117
+ catch {
118
+ return null;
119
+ }
120
+ }
@@ -0,0 +1,24 @@
1
+ import type { LineData } from "../inject.js";
2
+ import type { AnimationConfig } from "./animationConfig.js";
3
+ import type { AnimationEngineInstance } from "./instance.js";
4
+ export interface ScrollerReading {
5
+ element: HTMLElement;
6
+ height: number;
7
+ scrollTop: number;
8
+ maxScrollTop: number;
9
+ }
10
+ export interface AutoScrollTick {
11
+ engine: AnimationEngineInstance;
12
+ lyricsElement: HTMLElement;
13
+ scroller: ScrollerReading;
14
+ focusedLines: LineData[];
15
+ scrollTimeS: number;
16
+ config: AnimationConfig;
17
+ smoothScroll: boolean;
18
+ countEveryUserScroll: boolean;
19
+ jumped: boolean;
20
+ focusChanged: boolean;
21
+ now: number;
22
+ }
23
+ export declare function followFocusedLines(tick: AutoScrollTick): void;
24
+ export declare function lastSungLine(engine: AnimationEngineInstance): LineData | undefined;
@@ -0,0 +1,103 @@
1
+ import { USER_SCROLLING_CLASS } from "../constants.js";
2
+ import { registerThemeSetting } from "../themeSettings.js";
3
+ import { clamp } from "../util.js";
4
+ import { updateVisibleLyricWillChange } from "./culling.js";
5
+ import { drawScrollDebugOverlay, isDebugOverlayEnabled } from "./debugOverlay.js";
6
+ import { commitOrPrepareLineScroll, dropPendingLineScroll, getLineScrollItems, prepareUpcomingLineScroll, SCROLL_PREPARE_LEAD_MS, } from "./lineScroll.js";
7
+ import { computeActiveLinesScrollTop, findScrollAnchor, getTargetScrollRatio } from "./scrollViewport.js";
8
+ import { decaySkipScrolls, writeEngineScrollTop } from "./userScroll.js";
9
+ const LYRIC_ENDING_THRESHOLD_S = registerThemeSetting("blyrics-lyric-ending-threshold-s", 0.5);
10
+ const SCROLL_DEADBAND_PX = 2;
11
+ export function followFocusedLines(tick) {
12
+ const { engine, lyricsElement, now } = tick;
13
+ if (isAutoScrolling(engine, now))
14
+ scrollToFocusedLines(tick);
15
+ if (engine.wasUserScrolling && engine.scrollResumeTime < now) {
16
+ engine.host.setResumeAffordanceVisible(false);
17
+ lyricsElement.classList.remove(USER_SCROLLING_CLASS);
18
+ engine.wasUserScrolling = false;
19
+ }
20
+ decaySkipScrolls(engine, now, !tick.countEveryUserScroll);
21
+ }
22
+ function isAutoScrolling(engine, now) {
23
+ return engine.scrollResumeTime < now || engine.scrollPos === -1;
24
+ }
25
+ export function lastSungLine(engine) {
26
+ return engine.lines.findLast(line => line.lyricElement.dataset.instrumental !== "true");
27
+ }
28
+ function scrollToFocusedLines(tick) {
29
+ const { engine, lyricsElement, scroller, scrollTimeS, config, smoothScroll, jumped } = tick;
30
+ const followedLines = tick.focusedLines.length > 0 ? tick.focusedLines : engine.lines.slice(0, 1);
31
+ const leadLine = followedLines.at(-1);
32
+ if (!leadLine)
33
+ return;
34
+ const targetOffset = scroller.height * getTargetScrollRatio(engine, lyricsElement);
35
+ const endingThresholdS = LYRIC_ENDING_THRESHOLD_S.getNumberValue();
36
+ const sungLines = followedLines.filter(line => line === leadLine || scrollTimeS < line.time + line.duration - endingThresholdS);
37
+ const lineCenters = sungLines.map(line => line.position + line.height / 2);
38
+ const anchor = findScrollAnchor(sungLines, scrollTimeS);
39
+ const target = computeActiveLinesScrollTop(sungLines, anchor, scroller.height, engine.cachedScrollInsets, targetOffset);
40
+ const toScrollTop = clamp(creditsAwareScrollTop(engine, target.scrollTop, targetOffset), 0, scroller.maxScrollTop);
41
+ if (isDebugOverlayEnabled()) {
42
+ drawScrollDebugOverlay(engine, {
43
+ lyricsElement,
44
+ scrollTop: scroller.scrollTop,
45
+ viewportHeight: scroller.height,
46
+ targetOffset,
47
+ followedLines,
48
+ lineCenters,
49
+ scrollTimeS,
50
+ endingThresholdS,
51
+ });
52
+ }
53
+ const pinned = engine.pinnedScrollLine;
54
+ const pinnedLineFinished = pinned !== null &&
55
+ pinned !== anchor &&
56
+ (!sungLines.includes(pinned) || scrollTimeS >= pinned.time + pinned.duration);
57
+ const mustCommit = tick.focusChanged || pinnedLineFinished || engine.wasUserScrolling;
58
+ const fromScrollTop = scroller.scrollTop;
59
+ const moves = Math.abs(toScrollTop - fromScrollTop) > SCROLL_DEADBAND_PX;
60
+ const animatesScroll = smoothScroll && config.enabled.scroll;
61
+ const request = () => ({
62
+ lines: getLineScrollItems(engine, engine.lines),
63
+ activeLine: leadLine,
64
+ fromScrollTop,
65
+ toScrollTop,
66
+ viewportHeight: scroller.height,
67
+ config,
68
+ continuesEngineScroll: !jumped &&
69
+ !engine.wasUserScrolling &&
70
+ engine.scrollPos >= 0 &&
71
+ Math.abs(fromScrollTop - engine.scrollPos) <= SCROLL_DEADBAND_PX,
72
+ });
73
+ const msUntilLeadLine = (leadLine.time - scrollTimeS) * 1000;
74
+ const leadLineIsNext = msUntilLeadLine > 0 && msUntilLeadLine <= SCROLL_PREPARE_LEAD_MS;
75
+ if (animatesScroll && moves && !mustCommit && leadLineIsNext && !engine.lastScrollElements.includes(leadLine)) {
76
+ updateVisibleLyricWillChange(engine, engine.lines, fromScrollTop, toScrollTop, scroller.height);
77
+ prepareUpcomingLineScroll(engine, request());
78
+ }
79
+ if (!mustCommit)
80
+ return;
81
+ engine.lastScrollElements = followedLines;
82
+ engine.pinnedScrollLine = target.overflowsBand ? anchor : null;
83
+ engine.lastScrollDebugContext = { lyricScrollTime: scrollTimeS, centers: lineCenters, activeElms: followedLines };
84
+ if (smoothScroll && moves) {
85
+ if (config.enabled.scroll) {
86
+ updateVisibleLyricWillChange(engine, engine.lines, fromScrollTop, toScrollTop, scroller.height);
87
+ commitOrPrepareLineScroll(engine, request());
88
+ }
89
+ }
90
+ else {
91
+ dropPendingLineScroll(engine);
92
+ }
93
+ writeEngineScrollTop(engine, scroller.element, toScrollTop, tick.now);
94
+ }
95
+ function creditsAwareScrollTop(engine, scrollTop, targetOffset) {
96
+ const credits = engine.cachedCreditsItem;
97
+ const lastLine = lastSungLine(engine);
98
+ if (!engine.creditsFocused || !credits || !lastLine)
99
+ return scrollTop;
100
+ const creditsCentered = credits.position + credits.height / 2 - targetOffset;
101
+ const lastLineAtTop = lastLine.position - engine.cachedScrollInsets.top;
102
+ return Math.min(creditsCentered, lastLineAtTop);
103
+ }
@@ -0,0 +1,29 @@
1
+ import type { ResolvedTickOptions } from "../types.js";
2
+ import type { AnimationEngineInstance } from "./instance.js";
3
+ export declare const SMOOTH_PLAYBACK_CLOCK: boolean;
4
+ export declare const CLOCK_RESYNC_THRESHOLD_S = 0.06;
5
+ export declare const NO_PLAYER_SNAPSHOT = -1;
6
+ interface PlaybackClock {
7
+ lastTime: number;
8
+ lastPlayState: boolean;
9
+ lastEventCreationTime: number;
10
+ smoothedTime: number;
11
+ smoothedAt: number;
12
+ }
13
+ export declare const playbackClock: PlaybackClock;
14
+ /**
15
+ * Clears the shared playback history when switching songs.
16
+ */
17
+ export declare function resetPlaybackClock(): void;
18
+ export declare function smoothedPlaybackTime(previousTime: number, previousAt: number, rawTime: number, now: number, playbackRate: number): number;
19
+ export interface Playhead {
20
+ timeS: number;
21
+ isPlaying: boolean;
22
+ jumped: boolean;
23
+ mediaClockRanBackwards: boolean;
24
+ seekedWhilePaused: boolean;
25
+ }
26
+ export declare function advancePlaybackClock(reportedTimeS: number, { isPlaying, eventCreationTime, followPausedSeeks }: ResolvedTickOptions, playbackRate: number, now: number): Playhead;
27
+ export declare function lyricClockShiftS(engine: AnimationEngineInstance, lyricsElement: HTMLElement, options: ResolvedTickOptions): number;
28
+ export declare function playerTimeForLyricTime(engine: AnimationEngineInstance, lyricTimeS: number): number;
29
+ export {};
@@ -0,0 +1,70 @@
1
+ import { isGecko } from "../util.js";
2
+ import { getCSSDurationInMs } from "./cssValues.js";
3
+ // Gecko has been seen to step media time about every 40 ms, so a read can lag by up to one step (never
4
+ // lead), and that lag would reseek lines as drift. A read off by more than a step plus margin is treated as
5
+ // a seek or a timer spike.
6
+ export const SMOOTH_PLAYBACK_CLOCK = isGecko();
7
+ export const CLOCK_RESYNC_THRESHOLD_S = 0.06;
8
+ const CLOCK_SLEW_PER_S = 0.1;
9
+ export const NO_PLAYER_SNAPSHOT = -1;
10
+ export const playbackClock = {
11
+ lastTime: 0,
12
+ lastPlayState: false,
13
+ lastEventCreationTime: NO_PLAYER_SNAPSHOT,
14
+ smoothedTime: 0,
15
+ smoothedAt: NO_PLAYER_SNAPSHOT,
16
+ };
17
+ /**
18
+ * Clears the shared playback history when switching songs.
19
+ */
20
+ export function resetPlaybackClock() {
21
+ playbackClock.lastTime = 0;
22
+ playbackClock.lastPlayState = false;
23
+ playbackClock.lastEventCreationTime = NO_PLAYER_SNAPSHOT;
24
+ playbackClock.smoothedAt = NO_PLAYER_SNAPSHOT;
25
+ }
26
+ export function smoothedPlaybackTime(previousTime, previousAt, rawTime, now, playbackRate) {
27
+ if (previousAt === NO_PLAYER_SNAPSHOT)
28
+ return rawTime;
29
+ const elapsedS = Math.max(0, now - previousAt) / 1000;
30
+ const predictedTime = previousTime + elapsedS * playbackRate;
31
+ const errorS = rawTime - predictedTime;
32
+ if (errorS >= 0 || Math.abs(errorS) >= CLOCK_RESYNC_THRESHOLD_S)
33
+ return rawTime;
34
+ return predictedTime + errorS * Math.min(1, elapsedS * CLOCK_SLEW_PER_S);
35
+ }
36
+ const TIME_JUMP_THRESHOLD_S = 0.5;
37
+ export function advancePlaybackClock(reportedTimeS, { isPlaying, eventCreationTime, followPausedSeeks }, playbackRate, now) {
38
+ const snapshotGapS = (eventCreationTime - playbackClock.lastEventCreationTime) / 1000;
39
+ const jumped = Math.abs(reportedTimeS - playbackClock.lastTime - snapshotGapS) > TIME_JUMP_THRESHOLD_S;
40
+ const readsMediaClockDirectly = eventCreationTime === NO_PLAYER_SNAPSHOT;
41
+ const mediaClockRanBackwards = readsMediaClockDirectly && isPlaying && reportedTimeS < playbackClock.lastTime - CLOCK_RESYNC_THRESHOLD_S;
42
+ const seekedWhilePaused = followPausedSeeks && !isPlaying && !playbackClock.lastPlayState && reportedTimeS !== playbackClock.lastTime;
43
+ playbackClock.lastTime = reportedTimeS;
44
+ playbackClock.lastPlayState = isPlaying;
45
+ playbackClock.lastEventCreationTime = eventCreationTime;
46
+ const snapshotAgeS = isPlaying && !readsMediaClockDirectly ? (now - eventCreationTime) / 1000 : 0;
47
+ let timeS = reportedTimeS + snapshotAgeS;
48
+ if (SMOOTH_PLAYBACK_CLOCK) {
49
+ if (isPlaying && !jumped) {
50
+ timeS = smoothedPlaybackTime(playbackClock.smoothedTime, playbackClock.smoothedAt, timeS, now, playbackRate);
51
+ }
52
+ playbackClock.smoothedTime = timeS;
53
+ playbackClock.smoothedAt = isPlaying ? now : NO_PLAYER_SNAPSHOT;
54
+ }
55
+ return { timeS, isPlaying, jumped, mediaClockRanBackwards, seekedWhilePaused };
56
+ }
57
+ export function lyricClockShiftS(engine, lyricsElement, options) {
58
+ const syncTypeShiftS = engine.syncType === "richsync"
59
+ ? getCSSDurationInMs(engine, lyricsElement, "--blyrics-richsync-timing-offset") / 1000 -
60
+ options.richsyncOffsetTrim
61
+ : getCSSDurationInMs(engine, lyricsElement, "--blyrics-timing-offset") / 1000 - options.lineOffsetTrim;
62
+ return syncTypeShiftS - options.globalLyricOffset - options.lyricOffset;
63
+ }
64
+ export function playerTimeForLyricTime(engine, lyricTimeS) {
65
+ const options = engine.lastTickOptions;
66
+ const lyricsElement = engine.lyricsContainer;
67
+ if (!options || !lyricsElement)
68
+ return lyricTimeS;
69
+ return Math.max(0, lyricTimeS - lyricClockShiftS(engine, lyricsElement, options));
70
+ }
@@ -0,0 +1,10 @@
1
+ import { type LineData } from "../inject.js";
2
+ import type { AnimationConfig } from "./animationConfig.js";
3
+ /**
4
+ * Places the sweep cells of a line's inline words over the boxes those words are laid out in. Runs
5
+ * when the line starts animating and reads layout first, so the reads land before the line's writes;
6
+ * a word laid out as it was last time keeps its cells.
7
+ */
8
+ export declare function placeContextSweeps(line: LineData, config: AnimationConfig): void;
9
+ /** Whether a line started before its inline words could be placed, and has to start over to show them. */
10
+ export declare function hasUnplacedContextSweeps(line: LineData): boolean;
@@ -0,0 +1,102 @@
1
+ import { BIDI_RUN_CLASS, HIGHLIGHT_RUN_CLASS, RTL_CLASS, SWEEP_CLONE_CLASS, SWEEP_CONTEXT_CLASS, SWEEP_TARGET_CLASS, SWEEP_WINDOW_CLASS, WORD_CLASS, } from "../constants.js";
2
+ import { createSweepCell } from "../inject.js";
3
+ import { swipeRamp } from "./letterPlans.js";
4
+ import { cellFade } from "./sweepPlans.js";
5
+ /**
6
+ * Places the sweep cells of a line's inline words over the boxes those words are laid out in. Runs
7
+ * when the line starts animating and reads layout first, so the reads land before the line's writes;
8
+ * a word laid out as it was last time keeps its cells.
9
+ */
10
+ export function placeContextSweeps(line, config) {
11
+ for (const part of line.parts)
12
+ if (part.sweepContext)
13
+ part.sweepContext.unplaced = true;
14
+ const placements = line.parts.flatMap(part => (part.sweepContext ? [measure(part)] : []));
15
+ for (const placement of placements)
16
+ if (placement)
17
+ place(placement, config);
18
+ }
19
+ // The cells sit outside the word, so they are handed the colours a theme may set on the word itself.
20
+ const WORD_COLORS = ["--blyrics-lyric-active-color", "--blyrics-glow-color"];
21
+ function measure(part) {
22
+ const word = part.lyricElement;
23
+ const run = word.closest(`.${BIDI_RUN_CLASS}:not(.${HIGHLIGHT_RUN_CLASS})`);
24
+ const contentLine = run?.parentElement;
25
+ if (!run || !contentLine || !part.sweepContext || typeof word.getClientRects !== "function")
26
+ return null;
27
+ const lineRect = contentLine.getBoundingClientRect();
28
+ // The line may be mid-scale, so boxes are read on screen and scaled back to the line's own pixels.
29
+ const scale = contentLine.offsetWidth > 0 ? lineRect.width / contentLine.offsetWidth : 1;
30
+ const local = (rect) => ({
31
+ x: (rect.left - lineRect.left) / scale,
32
+ y: (rect.top - lineRect.top) / scale,
33
+ width: rect.width / scale,
34
+ height: rect.height / scale,
35
+ });
36
+ const runBox = local(run.getBoundingClientRect());
37
+ const fragments = Array.from(word.getClientRects(), local).filter(box => box.width > 0);
38
+ // A line the browser skipped laying out has no boxes yet; it is placed once it comes into view.
39
+ if (fragments.length === 0)
40
+ return null;
41
+ const style = word.ownerDocument.defaultView?.getComputedStyle(part.highlightElement);
42
+ const colors = WORD_COLORS.map((name) => [name, style?.getPropertyValue(name).trim() ?? ""]);
43
+ const key = JSON.stringify([[runBox, fragments].flat().map(box => Object.values(box).map(Math.round)), colors]);
44
+ return { part, context: part.sweepContext, contentLine, run, runBox, fragments, colors, key };
45
+ }
46
+ /** Whether a line started before its inline words could be placed, and has to start over to show them. */
47
+ export function hasUnplacedContextSweeps(line) {
48
+ return line.isAnimating && line.parts.some(part => part.sweepContext?.unplaced);
49
+ }
50
+ function place({ part, context, contentLine, run, runBox, fragments, colors, key }, config) {
51
+ const placedAt = key + JSON.stringify(swipeRamp(config));
52
+ if (context.placedAt === placedAt && context.host?.isConnected) {
53
+ context.unplaced = false;
54
+ return;
55
+ }
56
+ context.host?.remove();
57
+ const doc = contentLine.ownerDocument;
58
+ const host = doc.createElement("span");
59
+ host.classList.add(SWEEP_CONTEXT_CLASS);
60
+ host.setAttribute("aria-hidden", "true");
61
+ for (const [name, value] of colors)
62
+ if (value)
63
+ host.style.setProperty(name, value);
64
+ const wordIndex = Array.from(run.querySelectorAll(`.${WORD_CLASS}`)).indexOf(part.lyricElement);
65
+ const lineCopy = run.cloneNode(true);
66
+ lineCopy.classList.add(SWEEP_CLONE_CLASS);
67
+ lineCopy.querySelectorAll(`.${WORD_CLASS}`)[wordIndex]?.classList.add(SWEEP_TARGET_CLASS);
68
+ const wordWidth = fragments.reduce((sum, box) => sum + box.width, 0);
69
+ const direction = part.lyricElement.classList.contains(RTL_CLASS) ? "rtl" : "ltr";
70
+ let start = 0;
71
+ const cells = fragments.map(box => {
72
+ const window = doc.createElement("span");
73
+ window.classList.add(SWEEP_WINDOW_CLASS);
74
+ window.dir = direction;
75
+ Object.assign(window.style, {
76
+ left: `${box.x}px`,
77
+ top: `${box.y}px`,
78
+ width: `${box.width}px`,
79
+ height: `${box.height}px`,
80
+ });
81
+ const span = { start: start / wordWidth, width: box.width / wordWidth };
82
+ start += box.width;
83
+ window.style.setProperty("--blyrics-sweep-fade", String(cellFade(swipeRamp(config), span)));
84
+ const cell = createSweepCell(doc, window, into => {
85
+ const copy = lineCopy.cloneNode(true);
86
+ Object.assign(copy.style, {
87
+ left: `${runBox.x - box.x}px`,
88
+ top: `${runBox.y - box.y}px`,
89
+ width: `${runBox.width}px`,
90
+ });
91
+ into.appendChild(copy);
92
+ return undefined;
93
+ });
94
+ host.appendChild(window);
95
+ return { ...cell, span };
96
+ });
97
+ contentLine.appendChild(host);
98
+ context.host = host;
99
+ context.placedAt = placedAt;
100
+ context.unplaced = false;
101
+ part.sweep = cells.length > 0 ? cells : undefined;
102
+ }
@@ -0,0 +1,13 @@
1
+ import type { AnimationEngineInstance } from "./instance.js";
2
+ export interface ThemeReader {
3
+ string(property: string, fallback: string): string;
4
+ durationMs(property: string, fallback: string): number;
5
+ number(property: string, fallback: number): number;
6
+ fraction(property: string, fallback: number): number;
7
+ flag(property: string, fallback: boolean): boolean;
8
+ }
9
+ export declare function clearStyleCaches(engine: AnimationEngineInstance): void;
10
+ export declare function getCSSValue(engine: AnimationEngineInstance, lyricsElement: HTMLElement, property: string, fallback: string): string;
11
+ export declare function getCSSDurationInMs(engine: AnimationEngineInstance, lyricsElement: HTMLElement, property: string): number;
12
+ export declare function getCSSNumber(engine: AnimationEngineInstance, lyricsElement: HTMLElement, property: string, fallback: number): number;
13
+ export declare function createThemeReader(engine: AnimationEngineInstance, lyricsElement: HTMLElement): ThemeReader;
@@ -0,0 +1,47 @@
1
+ import { clamp, toMs } from "../util.js";
2
+ import { dropPendingLineScroll } from "./lineScroll.js";
3
+ export function clearStyleCaches(engine) {
4
+ dropPendingLineScroll(engine);
5
+ engine.cachedDurations.clear();
6
+ engine.cachedCSSValues.clear();
7
+ engine.cachedAnimationSettings = null;
8
+ engine.cachedLineScrollTiming.clear();
9
+ }
10
+ // Property-only caching assumes every lookup for this engine uses its lyrics container.
11
+ export function getCSSValue(engine, lyricsElement, property, fallback) {
12
+ let value = engine.cachedCSSValues.get(property);
13
+ if (value === undefined) {
14
+ value = engine.window.getComputedStyle(lyricsElement).getPropertyValue(property).trim() || fallback;
15
+ engine.cachedCSSValues.set(property, value);
16
+ }
17
+ return value;
18
+ }
19
+ export function getCSSDurationInMs(engine, lyricsElement, property) {
20
+ let duration = engine.cachedDurations.get(property);
21
+ if (duration === undefined) {
22
+ duration = toMs(getCSSValue(engine, lyricsElement, property, "0ms"));
23
+ engine.cachedDurations.set(property, duration);
24
+ }
25
+ return duration;
26
+ }
27
+ export function getCSSNumber(engine, lyricsElement, property, fallback) {
28
+ const value = Number.parseFloat(getCSSValue(engine, lyricsElement, property, `${fallback}`));
29
+ return Number.isFinite(value) ? value : fallback;
30
+ }
31
+ export function createThemeReader(engine, lyricsElement) {
32
+ const string = (property, fallback) => getCSSValue(engine, lyricsElement, property, fallback);
33
+ const number = (property, fallback) => getCSSNumber(engine, lyricsElement, property, fallback);
34
+ return {
35
+ string,
36
+ number,
37
+ durationMs: (property, fallback) => Math.max(toMs(string(property, fallback)), 1),
38
+ fraction: (property, fallback) => clamp(number(property, fallback), 0, 1),
39
+ flag: (property, fallback) => {
40
+ const value = string(property, fallback ? "1" : "0").toLowerCase();
41
+ if (value === "false" || value === "off" || value === "none")
42
+ return false;
43
+ const numeric = Number.parseFloat(value);
44
+ return Number.isFinite(numeric) ? numeric > 0 : fallback;
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,6 @@
1
+ import type { AnimationEngineInstance } from "./instance.js";
2
+ import { type LineScrollItem } from "./lineScroll.js";
3
+ export declare function setupLineCullObserver(engine: AnimationEngineInstance): void;
4
+ export declare function clearOffscreenLineCulling(engine: AnimationEngineInstance): void;
5
+ export declare function updateVisibleLyricWillChange(engine: AnimationEngineInstance, lines: LineScrollItem[], fromScrollTop: number, toScrollTop: number, viewportHeight: number): void;
6
+ export declare function clearVisibleLyricWillChange(engine: AnimationEngineInstance): void;
@@ -0,0 +1,76 @@
1
+ import { hasUnplacedContextSweeps } from "./contextSweep.js";
2
+ import { resetLineAnimationState } from "./lineAnimationState.js";
3
+ import { isLineVisibleDuringScroll, LINE_SCROLL_WILL_CHANGE_VALUE } from "./lineScroll.js";
4
+ // Use screen intersections because transformed scrolling decouples layout coordinates from visibility.
5
+ const ONE_VIEWPORT_OVERSCAN = "100% 0px 100% 0px";
6
+ export function setupLineCullObserver(engine) {
7
+ engine.lineCullObserver?.disconnect();
8
+ engine.lineCullObserver = null;
9
+ clearOffscreenLineCulling(engine);
10
+ const Observer = engine.window.IntersectionObserver;
11
+ if (engine.layout === "stage" || typeof Observer !== "function" || engine.lines.length === 0)
12
+ return;
13
+ // The engine owns scrollTop; Firefox's scroll anchoring would answer cull height shifts with a scroll the
14
+ // engine reads as the user's.
15
+ engine.host.getScrollElement()?.style.setProperty("overflow-anchor", "none");
16
+ pinCulledLineHeights(engine);
17
+ const observer = new Observer(entries => {
18
+ for (const entry of entries) {
19
+ const element = entry.target;
20
+ if (entry.isIntersecting) {
21
+ if (engine.culledLineElements.delete(element))
22
+ uncullLine(element);
23
+ restartUnplacedLine(engine, element);
24
+ }
25
+ else if (!engine.culledLineElements.has(element)) {
26
+ cullLine(element);
27
+ engine.culledLineElements.add(element);
28
+ }
29
+ }
30
+ }, { root: null, rootMargin: ONE_VIEWPORT_OVERSCAN, threshold: 0 });
31
+ for (const line of engine.lines)
32
+ observer.observe(line.lyricElement);
33
+ engine.lineCullObserver = observer;
34
+ }
35
+ /** A line that started while it was skipped starts over now that its words have boxes to place on. */
36
+ function restartUnplacedLine(engine, element) {
37
+ const line = engine.lines.find(candidate => candidate.lyricElement === element);
38
+ if (line && hasUnplacedContextSweeps(line))
39
+ resetLineAnimationState(line);
40
+ }
41
+ export function clearOffscreenLineCulling(engine) {
42
+ for (const element of engine.culledLineElements)
43
+ uncullLine(element);
44
+ engine.culledLineElements = new Set();
45
+ }
46
+ function pinCulledLineHeights(engine) {
47
+ const renderedHeights = engine.lines.map(line => line.lyricElement.offsetHeight);
48
+ engine.lines.forEach((line, index) => {
49
+ line.lyricElement.style.setProperty("contain-intrinsic-block-size", `auto ${renderedHeights[index]}px`);
50
+ });
51
+ }
52
+ function cullLine(element) {
53
+ element.style.setProperty("content-visibility", "auto");
54
+ }
55
+ function uncullLine(element) {
56
+ element.style.removeProperty("content-visibility");
57
+ }
58
+ export function updateVisibleLyricWillChange(engine, lines, fromScrollTop, toScrollTop, viewportHeight) {
59
+ const visibleElements = new Set();
60
+ for (const line of lines) {
61
+ if (!isLineVisibleDuringScroll(line, fromScrollTop, toScrollTop, viewportHeight))
62
+ continue;
63
+ line.lyricElement.style.setProperty("will-change", LINE_SCROLL_WILL_CHANGE_VALUE);
64
+ visibleElements.add(line.lyricElement);
65
+ }
66
+ for (const element of engine.visibleWillChangeElements) {
67
+ if (!visibleElements.has(element))
68
+ element.style.removeProperty("will-change");
69
+ }
70
+ engine.visibleWillChangeElements = visibleElements;
71
+ }
72
+ export function clearVisibleLyricWillChange(engine) {
73
+ for (const element of engine.visibleWillChangeElements)
74
+ element.style.removeProperty("will-change");
75
+ engine.visibleWillChangeElements = new Set();
76
+ }
@@ -0,0 +1,14 @@
1
+ import type { LineData } from "../inject.js";
2
+ import type { AnimationEngineInstance } from "./instance.js";
3
+ export interface ScrollDebugFrame {
4
+ lyricsElement: HTMLElement;
5
+ scrollTop: number;
6
+ viewportHeight: number;
7
+ targetOffset: number;
8
+ followedLines: LineData[];
9
+ lineCenters: number[];
10
+ scrollTimeS: number;
11
+ endingThresholdS: number;
12
+ }
13
+ export declare function isDebugOverlayEnabled(): boolean;
14
+ export declare function drawScrollDebugOverlay(engine: AnimationEngineInstance, frame: ScrollDebugFrame): void;