@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
@@ -0,0 +1,119 @@
1
+ import { registerThemeSetting } from "../themeSettings.js";
2
+ import { toMs } from "../util.js";
3
+ const FALLBACK_DURATION_MS = 750;
4
+ const DEFAULT_TRAILING_DURATION = "calc(750ms + log(var(--blyrics-line-scroll-abs-relative-index) + 2, 2.71828) * 80ms + (var(--blyrics-line-scroll-abs-relative-index) + 1) * 20ms)";
5
+ function themeSetting(property, defaultValue) {
6
+ return [property, registerThemeSetting(property.slice(2), defaultValue)];
7
+ }
8
+ const THEME_SETTINGS = [
9
+ themeSetting("--blyrics-line-scroll-duration", DEFAULT_TRAILING_DURATION),
10
+ themeSetting("--blyrics-line-scroll-above-duration", "calc(750ms + min(var(--blyrics-line-scroll-abs-relative-index), 6) * 20ms)"),
11
+ themeSetting("--blyrics-line-scroll-active-duration", ""),
12
+ themeSetting("--blyrics-line-scroll-below-duration", DEFAULT_TRAILING_DURATION),
13
+ themeSetting("--blyrics-line-scroll-timing-function", "var(--blyrics-lyric-scroll-timing-function)"),
14
+ themeSetting("--blyrics-line-scroll-start-easing", "var(--blyrics-line-scroll-timing-function)"),
15
+ themeSetting("--blyrics-line-scroll-end-easing", "linear"),
16
+ themeSetting("--blyrics-line-scroll-above-start-easing", ""),
17
+ themeSetting("--blyrics-line-scroll-active-start-easing", ""),
18
+ themeSetting("--blyrics-line-scroll-below-start-easing", ""),
19
+ themeSetting("--blyrics-line-scroll-above-end-easing", ""),
20
+ themeSetting("--blyrics-line-scroll-active-end-easing", ""),
21
+ themeSetting("--blyrics-line-scroll-below-end-easing", ""),
22
+ themeSetting("--blyrics-line-scroll-translate-y-start", "var(--blyrics-line-scroll-delta-px)"),
23
+ themeSetting("--blyrics-line-scroll-translate-y-end", "0px"),
24
+ themeSetting("--blyrics-line-scroll-above-translate-y-start", ""),
25
+ themeSetting("--blyrics-line-scroll-active-translate-y-start", ""),
26
+ themeSetting("--blyrics-line-scroll-below-translate-y-start", ""),
27
+ themeSetting("--blyrics-line-scroll-above-translate-y-end", ""),
28
+ themeSetting("--blyrics-line-scroll-active-translate-y-end", ""),
29
+ themeSetting("--blyrics-line-scroll-below-translate-y-end", ""),
30
+ ];
31
+ const TRANSLATE_SETTINGS = THEME_SETTINGS.filter(([property]) => property.includes("translate-y")).map(([, setting]) => setting);
32
+ const INDEX_PROPERTY = "--blyrics-line-scroll-index";
33
+ const ACTIVE_INDEX_PROPERTY = "--blyrics-line-scroll-active-index";
34
+ const RELATIVE_INDEX_PROPERTY = "--blyrics-line-scroll-relative-index";
35
+ const ABS_RELATIVE_INDEX_PROPERTY = "--blyrics-line-scroll-abs-relative-index";
36
+ const SIDE_PROPERTY = "--blyrics-line-scroll-side";
37
+ const DELTA_PROPERTY = "--blyrics-line-scroll-delta-px";
38
+ const DISTANCE_PROPERTY = "--blyrics-line-scroll-distance-px";
39
+ const INLINE_PROPERTIES = [
40
+ INDEX_PROPERTY,
41
+ ACTIVE_INDEX_PROPERTY,
42
+ RELATIVE_INDEX_PROPERTY,
43
+ ABS_RELATIVE_INDEX_PROPERTY,
44
+ SIDE_PROPERTY,
45
+ DELTA_PROPERTY,
46
+ DISTANCE_PROPERTY,
47
+ ...THEME_SETTINGS.map(([property]) => property),
48
+ ];
49
+ export function themeOverridesScrollTranslate() {
50
+ return TRANSLATE_SETTINGS.some(setting => setting.isManuallySet());
51
+ }
52
+ export function writeScrollVariables(lineElement, variables) {
53
+ const style = lineElement.style;
54
+ style.setProperty(INDEX_PROPERTY, String(variables.index));
55
+ style.setProperty(ACTIVE_INDEX_PROPERTY, String(variables.activeIndex));
56
+ style.setProperty(RELATIVE_INDEX_PROPERTY, String(variables.relativeIndex));
57
+ style.setProperty(ABS_RELATIVE_INDEX_PROPERTY, String(Math.abs(variables.relativeIndex)));
58
+ style.setProperty(SIDE_PROPERTY, variables.side);
59
+ style.setProperty(DELTA_PROPERTY, `${variables.deltaPx}px`);
60
+ style.setProperty(DISTANCE_PROPERTY, `${Math.abs(variables.deltaPx)}px`);
61
+ for (const [property, setting] of THEME_SETTINGS) {
62
+ const value = setting.getStringValue().trim();
63
+ if (value)
64
+ style.setProperty(property, value);
65
+ else
66
+ style.removeProperty(property);
67
+ }
68
+ }
69
+ export function clearScrollVariables(lineElement) {
70
+ for (const property of INLINE_PROPERTIES)
71
+ lineElement.style.removeProperty(property);
72
+ }
73
+ function scrollVariable(name, side, differential, fallback) {
74
+ const shared = `var(--blyrics-line-scroll-${name}, ${fallback})`;
75
+ return differential ? `var(--blyrics-line-scroll-${side}-${name}, ${shared})` : shared;
76
+ }
77
+ export function resolveScrollTimings(engine, lines, { lineScroll }) {
78
+ const differential = lineScroll.differentialEffects;
79
+ const durations = batchProbeComputedStyle(engine, lines, "transition-duration", line => scrollVariable("duration", line.side, differential, `${FALLBACK_DURATION_MS}ms`), style => {
80
+ const durationMs = toMs(style.transitionDuration.split(",")[0].trim());
81
+ return durationMs > 0 ? durationMs : FALLBACK_DURATION_MS;
82
+ });
83
+ const easingsAt = (keyframe) => batchProbeComputedStyle(engine, lines, "transition-timing-function", line => scrollVariable(`${keyframe}-easing`, line.side, differential, `var(--blyrics-line-scroll-timing-function, ${lineScroll.easing})`), style => style.transitionTimingFunction.trim() || lineScroll.easing);
84
+ const startEasings = easingsAt("start");
85
+ const endEasings = easingsAt("end");
86
+ return lines.map((_, index) => ({
87
+ durationMs: durations[index],
88
+ startEasing: startEasings[index],
89
+ endEasing: endEasings[index],
90
+ }));
91
+ }
92
+ export function resolveThemedTranslates(engine, lines, { lineScroll }) {
93
+ const translatesAt = (keyframe) => batchProbeComputedStyle(engine, lines, "translate", line => {
94
+ const fallback = keyframe === "start" ? "var(--blyrics-line-scroll-delta-px, 0px)" : "0px";
95
+ return `0 ${scrollVariable(`translate-y-${keyframe}`, line.side, lineScroll.differentialEffects, fallback)}`;
96
+ }, style => normalizedTranslate(style.translate));
97
+ return { start: translatesAt("start"), end: translatesAt("end") };
98
+ }
99
+ function normalizedTranslate(translateValue) {
100
+ const translate = translateValue.trim();
101
+ return translate && translate !== "none" ? translate : "0px 0px";
102
+ }
103
+ function batchProbeComputedStyle(engine, lines, property, probeValue, readValue) {
104
+ const previous = lines.map(({ lineElement }) => ({
105
+ value: lineElement.style.getPropertyValue(property),
106
+ priority: lineElement.style.getPropertyPriority(property),
107
+ }));
108
+ for (const line of lines)
109
+ line.lineElement.style.setProperty(property, probeValue(line), "important");
110
+ const values = lines.map(line => readValue(engine.window.getComputedStyle(line.lineElement)));
111
+ lines.forEach(({ lineElement }, index) => {
112
+ const { value, priority } = previous[index];
113
+ if (value)
114
+ lineElement.style.setProperty(property, value, priority);
115
+ else
116
+ lineElement.style.removeProperty(property);
117
+ });
118
+ return values;
119
+ }
@@ -0,0 +1,3 @@
1
+ import type { AnimationEngineInstance } from "./instance.js";
2
+ export declare const liveEngines: Set<AnimationEngineInstance>;
3
+ export declare function forEveryLiveView(runOperation: (engine: AnimationEngineInstance) => void): void;
@@ -0,0 +1,5 @@
1
+ export const liveEngines = new Set();
2
+ export function forEveryLiveView(runOperation) {
3
+ for (const engine of liveEngines)
4
+ runOperation(engine);
5
+ }
@@ -0,0 +1 @@
1
+ export declare const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
@@ -0,0 +1 @@
1
+ export const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
@@ -0,0 +1,10 @@
1
+ import type { AnimationEngineInstance } from "./instance.js";
2
+ export declare function hasNoLyricsPlaceholder(engine: AnimationEngineInstance): boolean;
3
+ export declare function hasUnsyncedLyrics(engine: AnimationEngineInstance): boolean;
4
+ export declare function startPassiveScrollLoop(engine: AnimationEngineInstance): void;
5
+ export declare function stopPassiveScrollLoop(engine: AnimationEngineInstance): void;
6
+ /**
7
+ * The drift writes the scroll every frame, and a browser folds that scroll and the reader's into one
8
+ * event, so the drift's own scrolls are told apart by where they land rather than by counting them.
9
+ */
10
+ export declare function isPassiveDriftScroll(engine: AnimationEngineInstance): boolean;
@@ -0,0 +1,93 @@
1
+ import { USER_SCROLLING_CLASS } from "../constants.js";
2
+ import { registerThemeSetting } from "../themeSettings.js";
3
+ import { playbackClock } from "./clock.js";
4
+ const PASSIVE_SCROLL_ENABLED = registerThemeSetting("blyrics-passive-scroll-enabled", true);
5
+ const SECONDS_PER_LINE = registerThemeSetting("blyrics-passive-scroll-seconds-per-line", 3.5);
6
+ const BOTTOM_PAUSE_S = registerThemeSetting("blyrics-passive-scroll-bottom-pause-s", 1.5);
7
+ const RESET_DURATION_S = registerThemeSetting("blyrics-passive-scroll-reset-duration-s", 0.6);
8
+ const TOP_PAUSE_S = registerThemeSetting("blyrics-passive-scroll-top-pause-s", 0.8);
9
+ const MAX_FRAME_STEP_S = 0.5;
10
+ const DRIFT_SCROLL_TOLERANCE_PX = 1;
11
+ export function hasNoLyricsPlaceholder(engine) {
12
+ return engine.lyricsContainer?.dataset.noLyrics === "true";
13
+ }
14
+ export function hasUnsyncedLyrics(engine) {
15
+ return engine.lyricsContainer !== null && engine.syncType === "none" && !hasNoLyricsPlaceholder(engine);
16
+ }
17
+ export function startPassiveScrollLoop(engine) {
18
+ if (engine.passiveRAFId !== null)
19
+ return;
20
+ engine.passiveRAFId = engine.window.requestAnimationFrame(() => passiveScrollFrame(engine));
21
+ }
22
+ export function stopPassiveScrollLoop(engine) {
23
+ if (engine.passiveRAFId === null)
24
+ return;
25
+ engine.window.cancelAnimationFrame(engine.passiveRAFId);
26
+ engine.passiveRAFId = null;
27
+ }
28
+ function passiveScrollFrame(engine) {
29
+ engine.passiveRAFId = null;
30
+ if (!engine.passiveScrollEnabled || !PASSIVE_SCROLL_ENABLED.getBooleanValue() || !hasUnsyncedLyrics(engine))
31
+ return;
32
+ advancePassiveScroll(engine, playbackClock.lastPlayState);
33
+ engine.passiveRAFId = engine.window.requestAnimationFrame(() => passiveScrollFrame(engine));
34
+ }
35
+ function advancePassiveScroll(engine, isPlaying) {
36
+ if (!engine.host.isViewVisible() || engine.host.isLoaderActive())
37
+ return;
38
+ const scroller = engine.host.getScrollElement();
39
+ if (!scroller)
40
+ return;
41
+ const now = Date.now();
42
+ if (engine.passiveLastWallTime > 0 && isPlaying) {
43
+ engine.passiveScrollAccumulatedTime += Math.min((now - engine.passiveLastWallTime) / 1000, MAX_FRAME_STEP_S);
44
+ }
45
+ engine.passiveLastWallTime = now;
46
+ if (engine.scrollResumeTime > now)
47
+ return;
48
+ if (engine.wasUserScrolling)
49
+ resumeFromUserScroll(engine, scroller);
50
+ const scrollDurationS = engine.lines.length * SECONDS_PER_LINE.getNumberValue();
51
+ const maxScrollTop = scroller.scrollHeight - scroller.clientHeight;
52
+ if (engine.lines.length === 0 || maxScrollTop <= 0)
53
+ return;
54
+ const scrollTop = passiveCycleScrollTop(engine.passiveScrollAccumulatedTime, scrollDurationS, maxScrollTop);
55
+ scroller.scrollTop = scrollTop;
56
+ engine.passiveScrollTop = scroller.scrollTop;
57
+ }
58
+ /**
59
+ * The drift writes the scroll every frame, and a browser folds that scroll and the reader's into one
60
+ * event, so the drift's own scrolls are told apart by where they land rather than by counting them.
61
+ */
62
+ export function isPassiveDriftScroll(engine) {
63
+ const scrollTop = engine.host.getScrollElement()?.scrollTop;
64
+ return (engine.passiveScrollTop !== null &&
65
+ scrollTop !== undefined &&
66
+ Math.abs(scrollTop - engine.passiveScrollTop) < DRIFT_SCROLL_TOLERANCE_PX);
67
+ }
68
+ function resumeFromUserScroll(engine, scroller) {
69
+ engine.host.setResumeAffordanceVisible(false);
70
+ engine.lyricsContainer?.classList.remove(USER_SCROLLING_CLASS);
71
+ engine.wasUserScrolling = false;
72
+ const maxScrollTop = scroller.scrollHeight - scroller.clientHeight;
73
+ if (maxScrollTop <= 0)
74
+ return;
75
+ const scrollDurationS = engine.lines.length * SECONDS_PER_LINE.getNumberValue();
76
+ engine.passiveScrollAccumulatedTime = (scroller.scrollTop / maxScrollTop) * scrollDurationS;
77
+ }
78
+ function passiveCycleScrollTop(playedS, scrollDurationS, maxScrollTop) {
79
+ const reachesBottomS = scrollDurationS;
80
+ const leavesBottomS = reachesBottomS + BOTTOM_PAUSE_S.getNumberValue();
81
+ const resetDurationS = RESET_DURATION_S.getNumberValue();
82
+ const reachesTopS = leavesBottomS + resetDurationS;
83
+ const cycleS = playedS % (reachesTopS + TOP_PAUSE_S.getNumberValue());
84
+ if (cycleS < reachesBottomS)
85
+ return (cycleS / scrollDurationS) * maxScrollTop;
86
+ if (cycleS < leavesBottomS)
87
+ return maxScrollTop;
88
+ if (cycleS < reachesTopS) {
89
+ const remaining = 1 - (cycleS - leavesBottomS) / resetDurationS;
90
+ return maxScrollTop * remaining * remaining;
91
+ }
92
+ return 0;
93
+ }
@@ -0,0 +1,17 @@
1
+ import type { LineData } from "../inject.js";
2
+ import type { LyricSyncType } from "../types.js";
3
+ import type { AnimationEngineInstance } from "./instance.js";
4
+ type LinePlacement = {
5
+ position: number;
6
+ height: number;
7
+ scrollAnimationOffset: number;
8
+ };
9
+ export declare function clearOnScreenLyrics(engine: AnimationEngineInstance): boolean;
10
+ export declare function hasRenderedLines(engine: AnimationEngineInstance): boolean;
11
+ export declare function getRenderedLines(engine: AnimationEngineInstance): LineData[];
12
+ export declare function getRenderedSyncType(engine: AnimationEngineInstance): LyricSyncType;
13
+ export declare function clearLyrics(engine: AnimationEngineInstance): void;
14
+ export declare function lineScrollOffset(engine: AnimationEngineInstance, element: HTMLElement): number;
15
+ export declare function replaceRenderedLines(engine: AnimationEngineInstance, lines: LineData[], dropped: readonly LineData[], previousOf: ReadonlyMap<LineData, LineData>): void;
16
+ export declare function settleSwappedLines(engine: AnimationEngineInstance, before: ReadonlyMap<LineData, LinePlacement>, scrollTopBefore: number): void;
17
+ export {};
@@ -0,0 +1,137 @@
1
+ import { ANIMATING_CLASS, CURRENT_LYRICS_CLASS } from "../constants.js";
2
+ import { clearOffscreenLineCulling, clearVisibleLyricWillChange } from "./culling.js";
3
+ import { DECORATION_MIN_SHIFT_PX, decorationSlideAllowed, slideElementBy } from "./decorationSlides.js";
4
+ import { resetLineAnimationState, togglePartClass } from "./lineAnimationState.js";
5
+ import { clearLineScrollAnimations, dropPendingLineScroll, removeLineScrollAnimation } from "./lineScroll.js";
6
+ import { stopPassiveScrollLoop } from "./passiveScroll.js";
7
+ import { currentTranslateY, replaceStageElements, resetStage } from "./stageMotion.js";
8
+ import { noteEngineScrollEvent } from "./userScroll.js";
9
+ export function clearOnScreenLyrics(engine) {
10
+ if (!engine.lyricsContainer)
11
+ return false;
12
+ engine.lyricsContainer.replaceChildren();
13
+ resetStage(engine);
14
+ return true;
15
+ }
16
+ export function hasRenderedLines(engine) {
17
+ return engine.lines.length > 0;
18
+ }
19
+ export function getRenderedLines(engine) {
20
+ return engine.lines;
21
+ }
22
+ export function getRenderedSyncType(engine) {
23
+ return engine.syncType;
24
+ }
25
+ export function clearLyrics(engine) {
26
+ engine.scrollPos = -1;
27
+ dropPendingLineScroll(engine);
28
+ clearLineScrollAnimations(engine);
29
+ clearVisibleLyricWillChange(engine);
30
+ engine.lineCullObserver?.disconnect();
31
+ engine.lineCullObserver = null;
32
+ clearOffscreenLineCulling(engine);
33
+ for (const line of engine.lines) {
34
+ resetLineAnimationState(line);
35
+ line.isSelected = false;
36
+ }
37
+ engine.skipScrollsDecayTimes = [];
38
+ engine.lastScrollElements = [];
39
+ engine.pinnedScrollLine = null;
40
+ engine.lastScrollDebugContext.activeElms = [];
41
+ engine.lastScrollDebugContext.centers = [];
42
+ engine.passiveScrollAccumulatedTime = 0;
43
+ engine.passiveLastWallTime = 0;
44
+ engine.passiveScrollTop = null;
45
+ stopPassiveScrollLoop(engine);
46
+ engine.lines = [];
47
+ engine.cachedFooterItem = null;
48
+ engine.cachedCreditsItem = null;
49
+ engine.creditsFocused = false;
50
+ engine.lyricsContainer = null;
51
+ engine.waveAnimationPool.length = 0;
52
+ resetStage(engine);
53
+ }
54
+ export function lineScrollOffset(engine, element) {
55
+ const scrolling = engine.lineScrollAnimations.some(record => record.lineElement === element);
56
+ return scrolling ? currentTranslateY(engine, element, 0) : 0;
57
+ }
58
+ export function replaceRenderedLines(engine, lines, dropped, previousOf) {
59
+ for (const [line, previous] of previousOf)
60
+ carrySelection(line, previous);
61
+ dropPendingLineScroll(engine);
62
+ const droppedElements = new Set(dropped.map(line => line.lyricElement));
63
+ for (const record of [...engine.lineScrollAnimations]) {
64
+ if (!droppedElements.has(record.lineElement))
65
+ continue;
66
+ record.animation.cancel();
67
+ removeLineScrollAnimation(engine, record);
68
+ }
69
+ for (const line of dropped) {
70
+ resetLineAnimationState(line);
71
+ line.isSelected = false;
72
+ engine.visibleWillChangeElements.delete(line.lyricElement);
73
+ engine.culledLineElements.delete(line.lyricElement);
74
+ }
75
+ const successorOf = new Map();
76
+ for (const [line, previous] of previousOf)
77
+ successorOf.set(previous, line);
78
+ const carry = (line) => successorOf.get(line) ?? (droppedElements.has(line.lyricElement) ? null : line);
79
+ const carryAll = (from) => from.map(carry).filter((line) => line !== null);
80
+ engine.lastScrollElements = carryAll(engine.lastScrollElements);
81
+ engine.lastScrollDebugContext.activeElms = carryAll(engine.lastScrollDebugContext.activeElms);
82
+ engine.pinnedScrollLine = engine.pinnedScrollLine === null ? null : carry(engine.pinnedScrollLine);
83
+ engine.lines = lines;
84
+ if (engine.layout === "stage")
85
+ replaceStageElements(engine, dropped, previousOf);
86
+ }
87
+ function carrySelection(line, previous) {
88
+ line.isScrolled = previous.isScrolled;
89
+ line.isSelected = previous.isSelected;
90
+ togglePartClass(line, CURRENT_LYRICS_CLASS, previous.lyricElement.classList.contains(CURRENT_LYRICS_CLASS));
91
+ togglePartClass(line, ANIMATING_CLASS, previous.lyricElement.classList.contains(ANIMATING_CLASS));
92
+ }
93
+ export function settleSwappedLines(engine, before, scrollTopBefore) {
94
+ const container = engine.lyricsContainer;
95
+ const scroller = engine.host.getScrollElement();
96
+ if (container === null || scroller === null || engine.layout === "stage")
97
+ return;
98
+ const now = Date.now();
99
+ const followed = followedLine(engine, before, scrollTopBefore, now);
100
+ const followedWas = followed === undefined ? undefined : before.get(followed)?.position;
101
+ if (followed !== undefined && followedWas !== undefined && isMeasured(followedWas) && isMeasured(followed.position)) {
102
+ const moved = followed.position - followedWas;
103
+ if (Math.abs(moved) >= DECORATION_MIN_SHIFT_PX)
104
+ scroller.scrollTop = scrollTopBefore + moved;
105
+ }
106
+ // Layout or this write may clamp scrolling; count an engine scroll event only when the actual position changed.
107
+ const appliedShift = scroller.scrollTop - scrollTopBefore;
108
+ if (appliedShift !== 0) {
109
+ noteEngineScrollEvent(engine, now);
110
+ if (engine.scrollPos >= 0)
111
+ engine.scrollPos += appliedShift;
112
+ }
113
+ if (!decorationSlideAllowed(engine, container))
114
+ return;
115
+ for (const line of engine.lines) {
116
+ const was = before.get(line);
117
+ if (was === undefined || !isMeasured(was.position) || !isMeasured(line.position))
118
+ continue;
119
+ const onScreenShift = was.position + was.scrollAnimationOffset - line.position + appliedShift;
120
+ if (Math.abs(onScreenShift) >= DECORATION_MIN_SHIFT_PX)
121
+ slideElementBy(line.lyricElement, onScreenShift);
122
+ }
123
+ }
124
+ function followedLine(engine, before, scrollTopBefore, now) {
125
+ const readerOwnsScroll = engine.scrollResumeTime > now;
126
+ if (readerOwnsScroll) {
127
+ return engine.lines.find(line => {
128
+ const was = before.get(line);
129
+ return was !== undefined && was.position + was.height > scrollTopBefore;
130
+ });
131
+ }
132
+ return (engine.lastScrollElements.findLast(line => before.has(line)) ??
133
+ engine.lines.find(line => before.has(line) && line.isScrolled));
134
+ }
135
+ function isMeasured(position) {
136
+ return position >= 0;
137
+ }
@@ -0,0 +1,36 @@
1
+ import type { AnimationEngineInstance } from "./instance.js";
2
+ export interface ScrollInsets {
3
+ readonly top: number;
4
+ readonly bottom: number;
5
+ }
6
+ export declare const NO_SCROLL_INSETS: ScrollInsets;
7
+ interface ScrollTargetLine {
8
+ readonly time: number;
9
+ readonly duration: number;
10
+ readonly position: number;
11
+ readonly height: number;
12
+ }
13
+ interface ScrollPaddingMeasurements {
14
+ viewportHeight: number;
15
+ targetScrollRatio: number;
16
+ contentHeightWithoutBottomPadding: number;
17
+ firstLineHeight: number;
18
+ lastLineCentre: number | null;
19
+ lastLineHeight: number;
20
+ footerHeight: number;
21
+ }
22
+ export declare function getTargetScrollRatio(engine: AnimationEngineInstance, lyricsElement: HTMLElement): number;
23
+ export declare function setupTabRendererObserver(engine: AnimationEngineInstance, element: HTMLElement): void;
24
+ export declare function measureScrollViewport(engine: AnimationEngineInstance, element: HTMLElement): void;
25
+ export declare function resolveScrollInsets(scrollPaddingTop: string, scrollPaddingBottom: string, viewportHeight: number): ScrollInsets;
26
+ export declare function findScrollAnchor<Line extends ScrollTargetLine>(sungLines: readonly Line[], scrollTime: number): Line;
27
+ export declare function computeActiveLinesScrollTop(sungLines: readonly ScrollTargetLine[], anchor: ScrollTargetLine, viewportHeight: number, insets: ScrollInsets, targetOffset: number): {
28
+ scrollTop: number;
29
+ overflowsBand: boolean;
30
+ };
31
+ export declare function computeScrollPadding(measurements: ScrollPaddingMeasurements): {
32
+ top: number;
33
+ bottom: number;
34
+ };
35
+ export declare function applyScrollPadding(engine: AnimationEngineInstance): void;
36
+ export {};
@@ -0,0 +1,104 @@
1
+ import { CREDITS_CLASS, FOOTER_CLASS, LINE_CLASS } from "../constants.js";
2
+ import { registerThemeSetting } from "../themeSettings.js";
3
+ import { clamp, getRelativeLayoutBounds } from "../util.js";
4
+ import { getCSSValue } from "./cssValues.js";
5
+ import { dropPendingLineScroll } from "./lineScroll.js";
6
+ import { hasNoLyricsPlaceholder } from "./passiveScroll.js";
7
+ const TARGET_SCROLL_POSITION_RATIO = registerThemeSetting("blyrics-target-scroll-pos-ratio", 0.37);
8
+ export const NO_SCROLL_INSETS = { top: 0, bottom: 0 };
9
+ export function getTargetScrollRatio(engine, lyricsElement) {
10
+ const themed = Number.parseFloat(getCSSValue(engine, lyricsElement, "--blyrics-target-scroll-pos-ratio", ""));
11
+ return Number.isFinite(themed) ? clamp(themed, 0, 1) : TARGET_SCROLL_POSITION_RATIO.getNumberValue();
12
+ }
13
+ export function setupTabRendererObserver(engine, element) {
14
+ engine.tabRendererResizeObserver?.disconnect();
15
+ engine.tabRendererResizeObserver = new engine.window.ResizeObserver(() => {
16
+ dropPendingLineScroll(engine);
17
+ if (element.isConnected)
18
+ measureScrollViewport(engine, element);
19
+ });
20
+ engine.tabRendererResizeObserver.observe(element);
21
+ engine.observedTabRenderer = element;
22
+ measureScrollViewport(engine, element);
23
+ }
24
+ export function measureScrollViewport(engine, element) {
25
+ const height = element.getBoundingClientRect().height;
26
+ const { scrollPaddingTop, scrollPaddingBottom } = engine.window.getComputedStyle(element);
27
+ engine.cachedTabRendererHeight = height;
28
+ engine.cachedScrollInsets = resolveScrollInsets(scrollPaddingTop, scrollPaddingBottom, height);
29
+ }
30
+ export function resolveScrollInsets(scrollPaddingTop, scrollPaddingBottom, viewportHeight) {
31
+ const top = resolveScrollInset(scrollPaddingTop, viewportHeight);
32
+ const bottom = resolveScrollInset(scrollPaddingBottom, viewportHeight);
33
+ const leavesABand = top + bottom < viewportHeight;
34
+ return leavesABand ? { top, bottom } : NO_SCROLL_INSETS;
35
+ }
36
+ function resolveScrollInset(value, viewportHeight) {
37
+ const amount = Number.parseFloat(value);
38
+ if (!Number.isFinite(amount) || amount <= 0)
39
+ return 0;
40
+ return value.trim().endsWith("%") ? (viewportHeight * amount) / 100 : amount;
41
+ }
42
+ export function findScrollAnchor(sungLines, scrollTime) {
43
+ const latestRunning = sungLines.findLast(line => line.time <= scrollTime && scrollTime < line.time + line.duration);
44
+ return latestRunning ?? sungLines.findLast(line => line.time <= scrollTime) ?? sungLines[0];
45
+ }
46
+ export function computeActiveLinesScrollTop(sungLines, anchor, viewportHeight, insets, targetOffset) {
47
+ const first = sungLines[0];
48
+ const last = sungLines[sungLines.length - 1];
49
+ const visibleBottom = viewportHeight - insets.bottom;
50
+ const clampToLineBounds = (scrollTop, line) => Math.min(Math.max(scrollTop, line.position + line.height - visibleBottom), line.position - insets.top);
51
+ const averageCentre = sungLines.reduce((total, line) => total + line.position + line.height / 2, 0) / sungLines.length;
52
+ const showingLast = clampToLineBounds(averageCentre - targetOffset, last);
53
+ const showingFirstTop = Math.min(showingLast, first.position - insets.top);
54
+ return {
55
+ scrollTop: clampToLineBounds(showingFirstTop, anchor),
56
+ overflowsBand: last.position + last.height - first.position > visibleBottom - insets.top,
57
+ };
58
+ }
59
+ export function computeScrollPadding(measurements) {
60
+ const { viewportHeight, targetScrollRatio, lastLineCentre } = measurements;
61
+ const contentHeight = measurements.contentHeightWithoutBottomPadding;
62
+ const belowTarget = viewportHeight * (1 - targetScrollRatio);
63
+ const top = Math.max(0, viewportHeight * targetScrollRatio - measurements.firstLineHeight / 2);
64
+ const lastLineAtTarget = (lastLineCentre === null ? viewportHeight : lastLineCentre + belowTarget) - contentHeight;
65
+ const fillsViewport = viewportHeight - contentHeight;
66
+ const unrenderedFloor = belowTarget - (measurements.footerHeight + measurements.lastLineHeight / 2);
67
+ const bottom = Math.max(lastLineAtTarget, fillsViewport, unrenderedFloor, 0);
68
+ return { top, bottom: Math.ceil(bottom) };
69
+ }
70
+ // These published properties must remain document-scoped for external stylesheets and themes. A second
71
+ // renderer in the same document overwrites them.
72
+ export function applyScrollPadding(engine) {
73
+ const lyricsElement = engine.lyricsContainer;
74
+ const scroller = engine.host.getScrollElement();
75
+ if (!lyricsElement || !scroller)
76
+ return;
77
+ if (hasNoLyricsPlaceholder(engine)) {
78
+ setScrollPadding(engine, lyricsElement, { top: 0, bottom: 0 });
79
+ return;
80
+ }
81
+ const bounds = (element) => (element ? getRelativeLayoutBounds(lyricsElement, element) : null);
82
+ const child = (className) => lyricsElement.querySelector(`:scope > .${className}`);
83
+ const lines = lyricsElement.querySelectorAll(`:scope > .${LINE_CLASS}`);
84
+ const creditsBounds = bounds(child(CREDITS_CLASS));
85
+ const lastTargetBounds = creditsBounds && creditsBounds.height > 0 ? creditsBounds : bounds(lines[lines.length - 1] ?? null);
86
+ const currentBottomPadding = Number.parseFloat(engine.window.getComputedStyle(lyricsElement).paddingBottom) || 0;
87
+ setScrollPadding(engine, lyricsElement, computeScrollPadding({
88
+ viewportHeight: scroller.getBoundingClientRect().height,
89
+ targetScrollRatio: getTargetScrollRatio(engine, lyricsElement),
90
+ contentHeightWithoutBottomPadding: Math.max(0, lyricsElement.scrollHeight - currentBottomPadding),
91
+ firstLineHeight: bounds(lines[0] ?? null)?.height ?? 0,
92
+ lastLineCentre: lastTargetBounds ? lastTargetBounds.y + lastTargetBounds.height / 2 : null,
93
+ lastLineHeight: lastTargetBounds?.height ?? 0,
94
+ footerHeight: bounds(child(FOOTER_CLASS))?.height ?? 0,
95
+ }));
96
+ }
97
+ function setScrollPadding(engine, lyricsElement, { top, bottom }) {
98
+ const rootStyle = engine.document.documentElement.style;
99
+ rootStyle.setProperty("--blyrics-padding-top", `${top}px`);
100
+ rootStyle.setProperty("--blyrics-padding-bottom", `${bottom}px`);
101
+ // Inline, because a theme's `.blyrics-container { padding }` comes after the package stylesheet at equal
102
+ // specificity and would otherwise take this room away.
103
+ lyricsElement.style.setProperty("padding-bottom", `${bottom}px`);
104
+ }
@@ -0,0 +1,7 @@
1
+ import type { LineData } from "../inject.js";
2
+ import type { AnimationEngineInstance } from "./instance.js";
3
+ export declare function applyStage(engine: AnimationEngineInstance, timeS: number, instant: boolean): void;
4
+ export declare function measureStage(engine: AnimationEngineInstance): void;
5
+ export declare function replaceStageElements(engine: AnimationEngineInstance, dropped: readonly LineData[], previousOf: ReadonlyMap<LineData, LineData>): void;
6
+ export declare function resetStage(engine: AnimationEngineInstance): void;
7
+ export declare function currentTranslateY(engine: AnimationEngineInstance, element: HTMLElement, fallback: number): number;