@braccato/core 1.21.6 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +202 -600
  3. package/dist/styles/lyrics.css +6 -0
  4. package/dist/util.d.ts +2 -0
  5. package/dist/util.js +4 -0
  6. package/js/element.js +234 -0
  7. package/js/renderer.d.ts +157 -0
  8. package/js/renderer.js +535 -0
  9. package/package.json +22 -17
  10. package/pkg/braccato_core_rs.d.ts +236 -0
  11. package/pkg/braccato_core_rs.js +1735 -0
  12. package/pkg/braccato_core_rs_bg.wasm +0 -0
  13. package/pkg/braccato_core_rs_bg.wasm.d.ts +55 -0
  14. package/dist/LICENSE +0 -21
  15. package/dist/README.md +0 -632
  16. package/dist/element.d.ts +0 -168
  17. package/dist/element.js +0 -730
  18. package/dist/engine/animationConfig.d.ts +0 -84
  19. package/dist/engine/animationConfig.js +0 -95
  20. package/dist/engine/animationDrift.d.ts +0 -11
  21. package/dist/engine/animationDrift.js +0 -43
  22. package/dist/engine/animationTiming.d.ts +0 -27
  23. package/dist/engine/animationTiming.js +0 -145
  24. package/dist/engine/autoScroll.d.ts +0 -24
  25. package/dist/engine/autoScroll.js +0 -103
  26. package/dist/engine/clock.d.ts +0 -29
  27. package/dist/engine/clock.js +0 -70
  28. package/dist/engine/contextSweep.d.ts +0 -10
  29. package/dist/engine/contextSweep.js +0 -102
  30. package/dist/engine/cssValues.d.ts +0 -13
  31. package/dist/engine/cssValues.js +0 -47
  32. package/dist/engine/culling.d.ts +0 -6
  33. package/dist/engine/culling.js +0 -76
  34. package/dist/engine/debugOverlay.d.ts +0 -14
  35. package/dist/engine/debugOverlay.js +0 -58
  36. package/dist/engine/decorationSlides.d.ts +0 -6
  37. package/dist/engine/decorationSlides.js +0 -53
  38. package/dist/engine/elementMotion.d.ts +0 -18
  39. package/dist/engine/elementMotion.js +0 -98
  40. package/dist/engine/glow.d.ts +0 -7
  41. package/dist/engine/glow.js +0 -59
  42. package/dist/engine/instance.d.ts +0 -105
  43. package/dist/engine/instance.js +0 -89
  44. package/dist/engine/instrumentalAnimations.d.ts +0 -7
  45. package/dist/engine/instrumentalAnimations.js +0 -59
  46. package/dist/engine/letterPlans.d.ts +0 -31
  47. package/dist/engine/letterPlans.js +0 -62
  48. package/dist/engine/lineAnimationState.d.ts +0 -10
  49. package/dist/engine/lineAnimationState.js +0 -82
  50. package/dist/engine/lineAnimations.d.ts +0 -5
  51. package/dist/engine/lineAnimations.js +0 -63
  52. package/dist/engine/lineLifecycle.d.ts +0 -12
  53. package/dist/engine/lineLifecycle.js +0 -92
  54. package/dist/engine/lineScroll.d.ts +0 -47
  55. package/dist/engine/lineScroll.js +0 -184
  56. package/dist/engine/lineScrollStyle.d.ts +0 -32
  57. package/dist/engine/lineScrollStyle.js +0 -133
  58. package/dist/engine/liveViews.d.ts +0 -3
  59. package/dist/engine/liveViews.js +0 -5
  60. package/dist/engine/motionCurves.d.ts +0 -19
  61. package/dist/engine/motionCurves.js +0 -85
  62. package/dist/engine/motionPreference.d.ts +0 -1
  63. package/dist/engine/motionPreference.js +0 -1
  64. package/dist/engine/passiveScroll.d.ts +0 -10
  65. package/dist/engine/passiveScroll.js +0 -93
  66. package/dist/engine/renderedLines.d.ts +0 -16
  67. package/dist/engine/renderedLines.js +0 -130
  68. package/dist/engine/scrollViewport.d.ts +0 -36
  69. package/dist/engine/scrollViewport.js +0 -104
  70. package/dist/engine/stageMotion.d.ts +0 -7
  71. package/dist/engine/stageMotion.js +0 -319
  72. package/dist/engine/sweepPlans.d.ts +0 -38
  73. package/dist/engine/sweepPlans.js +0 -66
  74. package/dist/engine/tick.d.ts +0 -16
  75. package/dist/engine/tick.js +0 -270
  76. package/dist/engine/timingLogs.d.ts +0 -7
  77. package/dist/engine/timingLogs.js +0 -81
  78. package/dist/engine/userScroll.d.ts +0 -12
  79. package/dist/engine/userScroll.js +0 -62
  80. package/dist/engine/wavePool.d.ts +0 -7
  81. package/dist/engine/wavePool.js +0 -22
  82. package/dist/engine/wordAnimations.d.ts +0 -5
  83. package/dist/engine/wordAnimations.js +0 -206
  84. package/dist/imageHighlights.d.ts +0 -4
  85. package/dist/imageHighlights.js +0 -34
  86. package/dist/index.d.ts +0 -17
  87. package/dist/index.js +0 -12
  88. package/dist/inject.d.ts +0 -98
  89. package/dist/inject.js +0 -591
  90. package/dist/instrumental.d.ts +0 -11
  91. package/dist/instrumental.js +0 -121
  92. package/dist/language.d.ts +0 -9
  93. package/dist/language.js +0 -47
  94. package/dist/letters.d.ts +0 -2
  95. package/dist/letters.js +0 -25
  96. package/dist/renderer.d.ts +0 -29
  97. package/dist/renderer.js +0 -412
  98. package/dist/seek.d.ts +0 -1
  99. package/dist/seek.js +0 -27
  100. package/dist/stage.d.ts +0 -58
  101. package/dist/stage.js +0 -121
  102. package/dist/types.d.ts +0 -236
  103. package/dist/types.js +0 -1
  104. package/dist/view.d.ts +0 -51
  105. package/dist/view.js +0 -396
@@ -1,130 +0,0 @@
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 { stopAllElementMotion, stopElementMotion } from "./elementMotion.js";
5
- import { resetLineAnimationState, togglePartClass } from "./lineAnimationState.js";
6
- import { dropPendingLineScroll } from "./lineScroll.js";
7
- import { stopPassiveScrollLoop } from "./passiveScroll.js";
8
- import { replaceStageElements, resetStage } from "./stageMotion.js";
9
- import { noteEngineScrollEvent } from "./userScroll.js";
10
- export function clearOnScreenLyrics(engine) {
11
- if (!engine.lyricsContainer)
12
- return false;
13
- engine.lyricsContainer.replaceChildren();
14
- resetStage(engine);
15
- return true;
16
- }
17
- export function hasRenderedLines(engine) {
18
- return engine.lines.length > 0;
19
- }
20
- export function getRenderedLines(engine) {
21
- return engine.lines;
22
- }
23
- export function getRenderedSyncType(engine) {
24
- return engine.syncType;
25
- }
26
- export function clearLyrics(engine) {
27
- engine.scrollPos = -1;
28
- dropPendingLineScroll(engine);
29
- stopAllElementMotion(engine);
30
- clearVisibleLyricWillChange(engine);
31
- engine.lineCullObserver?.disconnect();
32
- engine.lineCullObserver = null;
33
- clearOffscreenLineCulling(engine);
34
- for (const line of engine.lines) {
35
- resetLineAnimationState(line);
36
- line.isSelected = false;
37
- }
38
- engine.skipScrollsDecayTimes = [];
39
- engine.lastScrollElements = [];
40
- engine.pinnedScrollLine = null;
41
- engine.lastScrollDebugContext.activeElms = [];
42
- engine.lastScrollDebugContext.centers = [];
43
- engine.passiveScrollAccumulatedTime = 0;
44
- engine.passiveLastWallTime = 0;
45
- engine.passiveScrollTop = null;
46
- stopPassiveScrollLoop(engine);
47
- engine.lines = [];
48
- engine.cachedFooterItem = null;
49
- engine.cachedCreditsItem = null;
50
- engine.creditsFocused = false;
51
- engine.lyricsContainer = null;
52
- engine.waveAnimationPool.length = 0;
53
- resetStage(engine);
54
- }
55
- export function replaceRenderedLines(engine, lines, dropped, previousOf) {
56
- for (const [line, previous] of previousOf)
57
- carrySelection(line, previous);
58
- dropPendingLineScroll(engine);
59
- const droppedElements = new Set(dropped.map(line => line.lyricElement));
60
- for (const element of droppedElements)
61
- stopElementMotion(engine, element);
62
- for (const line of dropped) {
63
- resetLineAnimationState(line);
64
- line.isSelected = false;
65
- engine.visibleWillChangeElements.delete(line.lyricElement);
66
- engine.culledLineElements.delete(line.lyricElement);
67
- }
68
- const successorOf = new Map();
69
- for (const [line, previous] of previousOf)
70
- successorOf.set(previous, line);
71
- const carry = (line) => successorOf.get(line) ?? (droppedElements.has(line.lyricElement) ? null : line);
72
- const carryAll = (from) => from.map(carry).filter((line) => line !== null);
73
- engine.lastScrollElements = carryAll(engine.lastScrollElements);
74
- engine.lastScrollDebugContext.activeElms = carryAll(engine.lastScrollDebugContext.activeElms);
75
- engine.pinnedScrollLine = engine.pinnedScrollLine === null ? null : carry(engine.pinnedScrollLine);
76
- engine.lines = lines;
77
- if (engine.layout === "stage")
78
- replaceStageElements(engine, dropped, previousOf);
79
- }
80
- function carrySelection(line, previous) {
81
- line.isScrolled = previous.isScrolled;
82
- line.isSelected = previous.isSelected;
83
- togglePartClass(line, CURRENT_LYRICS_CLASS, previous.lyricElement.classList.contains(CURRENT_LYRICS_CLASS));
84
- togglePartClass(line, ANIMATING_CLASS, previous.lyricElement.classList.contains(ANIMATING_CLASS));
85
- }
86
- export function settleSwappedLines(engine, before, scrollTopBefore) {
87
- const container = engine.lyricsContainer;
88
- const scroller = engine.host.getScrollElement();
89
- if (container === null || scroller === null || engine.layout === "stage")
90
- return;
91
- const now = Date.now();
92
- const followed = followedLine(engine, before, scrollTopBefore, now);
93
- const followedWas = followed === undefined ? undefined : before.get(followed)?.position;
94
- if (followed !== undefined && followedWas !== undefined && isMeasured(followedWas) && isMeasured(followed.position)) {
95
- const moved = followed.position - followedWas;
96
- if (Math.abs(moved) >= DECORATION_MIN_SHIFT_PX)
97
- scroller.scrollTop = scrollTopBefore + moved;
98
- }
99
- // Layout or this write may clamp scrolling; count an engine scroll event only when the actual position changed.
100
- const appliedShift = scroller.scrollTop - scrollTopBefore;
101
- if (appliedShift !== 0) {
102
- noteEngineScrollEvent(engine, now);
103
- if (engine.scrollPos >= 0)
104
- engine.scrollPos += appliedShift;
105
- }
106
- if (!decorationSlideAllowed(engine, container))
107
- return;
108
- for (const line of engine.lines) {
109
- const was = before.get(line);
110
- if (was === undefined || !isMeasured(was.position) || !isMeasured(line.position))
111
- continue;
112
- const onScreenShift = was.position + was.motionOffset - line.position + appliedShift;
113
- if (Math.abs(onScreenShift) >= DECORATION_MIN_SHIFT_PX)
114
- slideElementBy(engine, line.lyricElement, onScreenShift);
115
- }
116
- }
117
- function followedLine(engine, before, scrollTopBefore, now) {
118
- const readerOwnsScroll = engine.scrollResumeTime > now;
119
- if (readerOwnsScroll) {
120
- return engine.lines.find(line => {
121
- const was = before.get(line);
122
- return was !== undefined && was.position + was.height > scrollTopBefore;
123
- });
124
- }
125
- return (engine.lastScrollElements.findLast(line => before.has(line)) ??
126
- engine.lines.find(line => before.has(line) && line.isScrolled));
127
- }
128
- function isMeasured(position) {
129
- return position >= 0;
130
- }
@@ -1,36 +0,0 @@
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 {};
@@ -1,104 +0,0 @@
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
- }
@@ -1,7 +0,0 @@
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;
@@ -1,319 +0,0 @@
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
- }
@@ -1,38 +0,0 @@
1
- import type { SwipeRamp } from "./letterPlans.js";
2
- /** Keyframes for a sweep cell's mask and for the text inside it, offsets in eased swipe progress. */
3
- export interface CellSweep {
4
- mask: Keyframe[];
5
- text: Keyframe[];
6
- }
7
- /**
8
- * Where a cell's mask edge rests, in the cell's widths: half a cell past its end, so the halos inside
9
- * the mask show whole once the cell is lit. `.blyrics-sweep-mask` in lyrics.css places its edge there.
10
- */
11
- export declare const SWEEP_REST = 1.5;
12
- /** A cell's place along its word, as fractions of the word's width. */
13
- export interface CellSpan {
14
- start: number;
15
- width: number;
16
- }
17
- /**
18
- * The swipe's soft edge in a cell's own widths. `.blyrics-sweep-mask` reads the same value as
19
- * `--blyrics-sweep-fade`, so the two must agree.
20
- */
21
- export declare function cellFade(swipe: SwipeRamp, span: CellSpan): number;
22
- /**
23
- * How far through the swipe, in eased progress, its start stop reaches the start of a cell. Until then
24
- * the cell's halo would show behind the edge before any of its text is lit, so its glow waits.
25
- */
26
- export declare function cellReachedAt(swipe: SwipeRamp, span: CellSpan): number;
27
- /** How far through the swipe, in eased progress, its start stop reaches the end of a cell. */
28
- export declare function cellLitAt(swipe: SwipeRamp, span: CellSpan): number;
29
- /**
30
- * Plans one cell of a sweep. In the cell's own widths the start stop runs from
31
- * `(startFrom - span.start) / span.width` to `(startTo - span.start) / span.width`, and the cell only
32
- * changes while that is between `-fade` (nothing lit yet) and `SWEEP_REST` (lit, with room for its
33
- * halo), so the motion is clamped there. `.blyrics-sweep-mask` in lyrics.css is `3 + fade` cells wide,
34
- * starting a cell before the cell, with its soft edge from `SWEEP_REST` to `fade` cells further. The
35
- * start stop moves linearly in eased progress, so keyframes at the clamp points with the swipe's
36
- * easing on the whole effect follow it exactly.
37
- */
38
- export declare function planCellSweep(swipe: SwipeRamp, span: CellSpan, rtl: boolean): CellSweep | null;