@braccato/core 1.20.1 → 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 (51) 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 +0 -5
  6. package/dist/engine/animationConfig.js +0 -5
  7. package/dist/engine/animationTiming.d.ts +2 -1
  8. package/dist/engine/animationTiming.js +3 -2
  9. package/dist/engine/contextSweep.d.ts +10 -0
  10. package/dist/engine/contextSweep.js +102 -0
  11. package/dist/engine/culling.js +9 -0
  12. package/dist/engine/decorationSlides.d.ts +1 -1
  13. package/dist/engine/decorationSlides.js +13 -4
  14. package/dist/engine/elementMotion.d.ts +17 -0
  15. package/dist/engine/elementMotion.js +98 -0
  16. package/dist/engine/glow.js +1 -1
  17. package/dist/engine/instance.d.ts +5 -2
  18. package/dist/engine/instance.js +3 -1
  19. package/dist/engine/letterPlans.d.ts +0 -11
  20. package/dist/engine/letterPlans.js +0 -41
  21. package/dist/engine/lineAnimationState.js +0 -3
  22. package/dist/engine/lineAnimations.d.ts +1 -1
  23. package/dist/engine/lineAnimations.js +5 -24
  24. package/dist/engine/lineLifecycle.js +1 -1
  25. package/dist/engine/lineScroll.d.ts +5 -6
  26. package/dist/engine/lineScroll.js +36 -26
  27. package/dist/engine/lineScrollStyle.d.ts +8 -3
  28. package/dist/engine/lineScrollStyle.js +18 -4
  29. package/dist/engine/motionCurves.d.ts +19 -0
  30. package/dist/engine/motionCurves.js +85 -0
  31. package/dist/engine/renderedLines.d.ts +1 -2
  32. package/dist/engine/renderedLines.js +8 -15
  33. package/dist/engine/sweepPlans.d.ts +36 -0
  34. package/dist/engine/sweepPlans.js +59 -0
  35. package/dist/engine/tick.d.ts +4 -1
  36. package/dist/engine/tick.js +30 -6
  37. package/dist/engine/wavePool.d.ts +0 -1
  38. package/dist/engine/wordAnimations.d.ts +1 -5
  39. package/dist/engine/wordAnimations.js +88 -66
  40. package/dist/imageHighlights.d.ts +0 -11
  41. package/dist/imageHighlights.js +2 -48
  42. package/dist/inject.d.ts +41 -2
  43. package/dist/inject.js +72 -27
  44. package/dist/renderer.js +3 -2
  45. package/dist/styles/image-highlights.css +1 -59
  46. package/dist/styles/lyrics.css +128 -57
  47. package/dist/view.d.ts +1 -1
  48. package/dist/view.js +4 -3
  49. package/package.json +1 -1
  50. package/dist/engine/highlightKeyframes.d.ts +0 -8
  51. package/dist/engine/highlightKeyframes.js +0 -37
@@ -0,0 +1,98 @@
1
+ import { bakeMotion, curveEndMs, offsetAt } from "./motionCurves.js";
2
+ const EASING_TABLE_STEPS = 128;
3
+ export function timelineNow(engine) {
4
+ const timelineTime = engine.document.timeline?.currentTime;
5
+ return typeof timelineTime === "number" ? timelineTime : Date.now();
6
+ }
7
+ export function addElementCurve(engine, element, curve) {
8
+ const nowMs = timelineNow(engine);
9
+ playCurves(engine, element, [...runningCurves(engine, element, nowMs), curve], nowMs);
10
+ }
11
+ export function removeElementCurves(engine, element, kind) {
12
+ const nowMs = timelineNow(engine);
13
+ const running = runningCurves(engine, element, nowMs);
14
+ if (!running.some(curve => curve.kind === kind))
15
+ return;
16
+ playCurves(engine, element, running.filter(curve => curve.kind !== kind), nowMs);
17
+ }
18
+ export function stopElementMotion(engine, element) {
19
+ const motion = engine.elementMotions.get(element);
20
+ if (!motion)
21
+ return;
22
+ engine.elementMotions.delete(element);
23
+ motion.animation.cancel();
24
+ for (const curve of motion.curves)
25
+ curve.onEnd?.();
26
+ }
27
+ export function stopAllElementMotion(engine) {
28
+ for (const element of [...engine.elementMotions.keys()])
29
+ stopElementMotion(engine, element);
30
+ }
31
+ export function elementMotionOffsetPx(engine, element) {
32
+ const motion = engine.elementMotions.get(element);
33
+ return motion ? offsetAt(motion.curves, timelineNow(engine), easingLookup(engine)) : 0;
34
+ }
35
+ function runningCurves(engine, element, nowMs) {
36
+ return (engine.elementMotions.get(element)?.curves ?? []).filter(curve => curveEndMs(curve) > nowMs);
37
+ }
38
+ function playCurves(engine, element, curves, nowMs) {
39
+ const previous = engine.elementMotions.get(element);
40
+ for (const curve of previous?.curves ?? [])
41
+ if (!curves.includes(curve))
42
+ curve.onEnd?.();
43
+ if (curves.length === 0) {
44
+ engine.elementMotions.delete(element);
45
+ previous?.animation.cancel();
46
+ return;
47
+ }
48
+ const baked = bakeMotion(curves, nowMs, easingLookup(engine));
49
+ const animation = element.animate(baked.keyframes, { duration: baked.durationMs, easing: "linear", fill: "none" });
50
+ animation.startTime = baked.startMs;
51
+ const motion = { animation, curves };
52
+ engine.elementMotions.set(element, motion);
53
+ previous?.animation.cancel();
54
+ const settle = () => {
55
+ if (engine.elementMotions.get(element) !== motion)
56
+ return;
57
+ engine.elementMotions.delete(element);
58
+ for (const curve of curves)
59
+ curve.onEnd?.();
60
+ };
61
+ animation.addEventListener("finish", settle, { once: true });
62
+ animation.addEventListener("cancel", settle, { once: true });
63
+ }
64
+ function easingLookup(engine) {
65
+ return easing => {
66
+ let table = engine.easingTables.get(easing);
67
+ if (!table) {
68
+ table = sampleEasing(engine, easing);
69
+ engine.easingTables.set(easing, table);
70
+ }
71
+ return tableEasing(table);
72
+ };
73
+ }
74
+ function tableEasing(table) {
75
+ return progress => {
76
+ const position = Math.min(Math.max(progress, 0), 1) * EASING_TABLE_STEPS;
77
+ const step = Math.min(Math.floor(position), EASING_TABLE_STEPS - 1);
78
+ return table[step] + (table[step + 1] - table[step]) * (position - step);
79
+ };
80
+ }
81
+ function sampleEasing(engine, easing) {
82
+ const table = Float64Array.from({ length: EASING_TABLE_STEPS + 1 }, (_, step) => step / EASING_TABLE_STEPS);
83
+ const { KeyframeEffect: Effect, Animation: Player } = engine.window;
84
+ if (typeof Effect !== "function" || typeof Player !== "function")
85
+ return table;
86
+ try {
87
+ const effect = new Effect(null, null, { duration: EASING_TABLE_STEPS, easing, fill: "both" });
88
+ const player = new Player(effect, null);
89
+ for (let step = 0; step <= EASING_TABLE_STEPS; step++) {
90
+ player.currentTime = step;
91
+ table[step] = effect.getComputedTiming().progress ?? table[step];
92
+ }
93
+ }
94
+ catch (error) {
95
+ engine.host.log("Line motion easing could not be sampled, so it is treated as linear", easing, error);
96
+ }
97
+ return table;
98
+ }
@@ -19,7 +19,7 @@ export function isGlowRestingInvisible(glowTo) {
19
19
  }
20
20
  export function suppressInvisibleWordGlows(engine, line, config) {
21
21
  const containerGlowShows = config.highlight.glowContainerAlpha >= HALF_8BIT_ALPHA_STEP;
22
- if (containerGlowShows || line.parts.some(part => part.imageLayers)) {
22
+ if (containerGlowShows) {
23
23
  for (const part of line.parts)
24
24
  part.glowSuppressed = false;
25
25
  return;
@@ -2,7 +2,8 @@ import type { LineData } from "../inject.js";
2
2
  import type { LyricsLayout, LyricsRendererHost, LyricSyncType, ResolvedTickOptions } from "../types.js";
3
3
  import type { StageBox, StageMetrics } from "../stage.js";
4
4
  import { type ScrollInsets } from "./scrollViewport.js";
5
- import type { LineScrollAnimationRecord, LineScrollItem, PendingLineScroll } from "./lineScroll.js";
5
+ import type { ElementMotion } from "./elementMotion.js";
6
+ import type { LineScrollItem, PendingLineScroll, RunningLineScroll } from "./lineScroll.js";
6
7
  import type { LineScrollTiming } from "./lineScrollStyle.js";
7
8
  import type { AnimationSettings } from "./animationConfig.js";
8
9
  /**
@@ -55,7 +56,9 @@ export interface AnimationEngineInstance extends AnimEngineViewState {
55
56
  cachedLineScrollTiming: Map<string, LineScrollTiming>;
56
57
  tabRendererResizeObserver: ResizeObserver | null;
57
58
  observedTabRenderer: HTMLElement | null;
58
- lineScrollAnimations: LineScrollAnimationRecord[];
59
+ runningLineScrolls: RunningLineScroll[];
60
+ elementMotions: Map<HTMLElement, ElementMotion>;
61
+ easingTables: Map<string, Float64Array>;
59
62
  lineScrollAnimationToken: number;
60
63
  pendingLineScroll: PendingLineScroll | null;
61
64
  lineScrollElementTokens: WeakMap<HTMLElement, number>;
@@ -40,7 +40,9 @@ export function createAnimationEngineInstance(engineDocument, engineWindow, host
40
40
  cachedLineScrollTiming: new Map(),
41
41
  tabRendererResizeObserver: null,
42
42
  observedTabRenderer: null,
43
- lineScrollAnimations: [],
43
+ runningLineScrolls: [],
44
+ elementMotions: new Map(),
45
+ easingTables: new Map(),
44
46
  lineScrollAnimationToken: 0,
45
47
  pendingLineScroll: null,
46
48
  lineScrollElementTokens: new WeakMap(),
@@ -18,16 +18,6 @@ export interface LetterSwipeWindow {
18
18
  end: number;
19
19
  };
20
20
  }
21
- export interface LetterMaskKeyframe {
22
- offset: number;
23
- maskPosition: string;
24
- }
25
- export interface LetterMaskSweep {
26
- keyframes: LetterMaskKeyframe[];
27
- delayMs: number;
28
- durationMs: number;
29
- easing: string;
30
- }
31
21
  export interface LetterWaveTiming {
32
22
  delayMs: number;
33
23
  durationMs: number;
@@ -38,5 +28,4 @@ export declare const GECKO_REDRAW_KEYFRAMES: Keyframe[];
38
28
  export declare const GECKO_REDRAW_PERIOD_MS = 200;
39
29
  export declare function swipeRamp({ highlight }: AnimationConfig): SwipeRamp;
40
30
  export declare function linearForwardSwipeWindows(swipe: SwipeRamp, letterCount: number, swipeDurationMs: number): LetterSwipeWindow[] | null;
41
- export declare function planLetterMaskSweep(swipe: SwipeRamp, letterCount: number, swipeDurationMs: number, rtl: boolean): LetterMaskSweep[];
42
31
  export declare function planLetterWave(swipe: SwipeRamp, letterCount: number, wordDurationMs: number, swipeDurationMs: number, swipeLeadMs: number, floatDurationMs: number): LetterWaveTiming[];
@@ -41,47 +41,6 @@ export function linearForwardSwipeWindows(swipe, letterCount, swipeDurationMs) {
41
41
  }
42
42
  return windows;
43
43
  }
44
- export function planLetterMaskSweep(swipe, letterCount, swipeDurationMs, rtl) {
45
- const windows = linearForwardSwipeWindows({ ...swipe, easing: "linear" }, letterCount, swipeDurationMs);
46
- if (!windows)
47
- return [];
48
- const maskSpan = letterCount + 2;
49
- const maskPositionAt = (start, index) => {
50
- const position = (0.5 * maskSpan - (start * letterCount - index)) / (maskSpan - 1);
51
- return `${(rtl ? 1 - position : position) * 100}% 0%`;
52
- };
53
- const durationMs = swipeDurationMs > 0 ? swipeDurationMs : 1;
54
- return windows.map((window, index) => {
55
- const from = maskPositionAt(window.from.start, index);
56
- const to = maskPositionAt(window.to.start, index);
57
- return swipe.easing === "linear"
58
- ? windowedSweep(window, from, to)
59
- : wholeSwipeSweep(window, from, to, durationMs, swipe.easing);
60
- });
61
- }
62
- function windowedSweep(window, from, to) {
63
- return {
64
- keyframes: [
65
- { offset: 0, maskPosition: from },
66
- { offset: 1, maskPosition: to },
67
- ],
68
- delayMs: window.delayMs,
69
- durationMs: window.durationMs,
70
- easing: "linear",
71
- };
72
- }
73
- function wholeSwipeSweep(window, from, to, swipeDurationMs, easing) {
74
- const revealStart = clamp(window.delayMs / swipeDurationMs, 0, 1);
75
- const revealEnd = clamp((window.delayMs + window.durationMs) / swipeDurationMs, 0, 1);
76
- const keyframes = [{ offset: 0, maskPosition: from }];
77
- if (revealStart > 0)
78
- keyframes.push({ offset: revealStart, maskPosition: from });
79
- if (revealEnd > revealStart)
80
- keyframes.push({ offset: revealEnd, maskPosition: to });
81
- if (revealEnd < 1)
82
- keyframes.push({ offset: 1, maskPosition: to });
83
- return { keyframes, delayMs: 0, durationMs: swipeDurationMs, easing };
84
- }
85
44
  export function planLetterWave(swipe, letterCount, wordDurationMs, swipeDurationMs, swipeLeadMs, floatDurationMs) {
86
45
  const windows = linearForwardSwipeWindows({ ...swipe, easing: "linear" }, letterCount, swipeDurationMs);
87
46
  if (!windows)
@@ -7,7 +7,6 @@ export function releasePart(part) {
7
7
  part.wordState = WORD_STATE_UPCOMING;
8
8
  part.lyricElement.setAttribute(WORD_STATE_ATTR, WORD_STATE_UPCOMING);
9
9
  part.highlightElement.setAttribute(WORD_STATE_ATTR, WORD_STATE_UPCOMING);
10
- part.imageLayers?.highlight?.setAttribute(WORD_STATE_ATTR, WORD_STATE_UPCOMING);
11
10
  }
12
11
  export function resetPartAnimations(part) {
13
12
  for (const animation of part.animations) {
@@ -39,7 +38,6 @@ export function togglePartClass(part, className, force) {
39
38
  part.lyricElement.classList.toggle(className, force);
40
39
  if ("highlightElement" in part) {
41
40
  part.highlightElement.classList.toggle(className, force);
42
- part.imageLayers?.highlight?.classList.toggle(className, force);
43
41
  }
44
42
  }
45
43
  export function setAnimationsPlayState(lineData, isPlaying) {
@@ -80,6 +78,5 @@ export function updateWordStates(lineData, currentTime) {
80
78
  part.wordState = state;
81
79
  part.lyricElement.setAttribute(WORD_STATE_ATTR, state);
82
80
  part.highlightElement.setAttribute(WORD_STATE_ATTR, state);
83
- part.imageLayers?.highlight?.setAttribute(WORD_STATE_ATTR, state);
84
81
  }
85
82
  }
@@ -2,4 +2,4 @@ import type { LineData } from "../inject.js";
2
2
  import type { AnimationConfig } from "./animationConfig.js";
3
3
  import type { AnimationEngineInstance } from "./instance.js";
4
4
  export declare function startLineAnimations(engine: AnimationEngineInstance, line: LineData, config: AnimationConfig, lyricTimeS: number): void;
5
- export declare function startLineExitAnimations(engine: AnimationEngineInstance, line: LineData, config: AnimationConfig, lyricTimeS: number): void;
5
+ export declare function startLineExitAnimations(line: LineData, config: AnimationConfig, lyricTimeS: number): void;
@@ -1,10 +1,13 @@
1
1
  import { correctedAnimationTimeMs, followSongClock } from "./animationTiming.js";
2
+ import { placeContextSweeps } from "./contextSweep.js";
2
3
  import { suppressInvisibleWordGlows } from "./glow.js";
3
4
  import { startInstrumentalAnimations, startInstrumentalExitAnimations } from "./instrumentalAnimations.js";
4
5
  import { resetPartAnimations } from "./lineAnimationState.js";
5
6
  import { startWordAnimations, startWordExitAnimation } from "./wordAnimations.js";
6
7
  export function startLineAnimations(engine, line, config, lyricTimeS) {
7
8
  const appliedTimingOffsetMs = engine.learnedAnimationTimingOffsetMs;
9
+ if (!isInstrumental(line))
10
+ placeContextSweeps(line, config);
8
11
  startLineEntrance(engine, line, config, lyricTimeS, appliedTimingOffsetMs);
9
12
  if (isInstrumental(line)) {
10
13
  startInstrumentalAnimations(engine, line, config, lyricTimeS, appliedTimingOffsetMs);
@@ -14,8 +17,7 @@ export function startLineAnimations(engine, line, config, lyricTimeS) {
14
17
  for (const part of line.parts)
15
18
  startWordAnimations(engine, part, config, lyricTimeS, appliedTimingOffsetMs);
16
19
  }
17
- export function startLineExitAnimations(engine, line, config, lyricTimeS) {
18
- const heldPaint = readImagePaintBeforeWrites(engine, line, lyricTimeS);
20
+ export function startLineExitAnimations(line, config, lyricTimeS) {
19
21
  startLineExit(line, config);
20
22
  if (isInstrumental(line)) {
21
23
  startInstrumentalExitAnimations(line, config, lyricTimeS);
@@ -23,7 +25,7 @@ export function startLineExitAnimations(engine, line, config, lyricTimeS) {
23
25
  }
24
26
  for (const part of line.parts) {
25
27
  if (lyricTimeS >= part.time)
26
- startWordExitAnimation(part, config, heldPaint.get(part));
28
+ startWordExitAnimation(part, config);
27
29
  else
28
30
  resetPartAnimations(part);
29
31
  }
@@ -59,24 +61,3 @@ function startLineExit(line, config) {
59
61
  line.animations = [exit];
60
62
  exit.addEventListener("finish", () => resetPartAnimations(line), { once: true });
61
63
  }
62
- function readImagePaintBeforeWrites(engine, line, lyricTimeS) {
63
- const heldPaint = new Map();
64
- const styleOf = (element) => engine.window.getComputedStyle(element);
65
- for (const part of line.parts) {
66
- if (!part.imageLayers || lyricTimeS < part.time)
67
- continue;
68
- const glowStyle = styleOf(part.imageLayers.glow);
69
- const paint = [
70
- { target: part.imageLayers.glow, frame: { opacity: glowStyle.opacity, filter: glowStyle.filter } },
71
- ];
72
- for (const target of part.letterElements ?? []) {
73
- paint.push({ target, frame: { transform: styleOf(target).transform } });
74
- }
75
- for (const target of [...(part.highlightLetterElements ?? []), ...part.imageLayers.glowLetters]) {
76
- const letterStyle = styleOf(target);
77
- paint.push({ target, frame: { maskPosition: letterStyle.maskPosition, transform: letterStyle.transform } });
78
- }
79
- heldPaint.set(part, paint);
80
- }
81
- return heldPaint;
82
- }
@@ -63,7 +63,7 @@ function retireLine({ engine, lyricTimeS, playhead, config }, line, index, anima
63
63
  resetLineAnimationState(line);
64
64
  }
65
65
  else {
66
- startLineExitAnimations(engine, line, config, lyricTimeS);
66
+ startLineExitAnimations(line, config, lyricTimeS);
67
67
  markLineAnimationsStopped(line);
68
68
  }
69
69
  }
@@ -9,10 +9,10 @@ export interface LineScrollItem {
9
9
  height: number;
10
10
  position: number;
11
11
  }
12
- export interface LineScrollAnimationRecord {
13
- animation: Animation;
12
+ export interface RunningLineScroll {
14
13
  lineElement: HTMLElement;
15
14
  token: number;
15
+ durationMs: number;
16
16
  }
17
17
  export interface LineScrollRequest {
18
18
  lines: LineScrollItem[];
@@ -28,8 +28,8 @@ interface PlannedLineScroll extends StyledScrollLine {
28
28
  durationMs: number;
29
29
  startEasing: string;
30
30
  endEasing: string;
31
- startTranslate: string;
32
- endTranslate: string;
31
+ startPx: number;
32
+ endPx: number;
33
33
  }
34
34
  export interface PendingLineScroll {
35
35
  plan: PlannedLineScroll[];
@@ -40,8 +40,7 @@ export interface PendingLineScroll {
40
40
  export declare function commitOrPrepareLineScroll(engine: AnimationEngineInstance, request: LineScrollRequest): void;
41
41
  export declare function prepareUpcomingLineScroll(engine: AnimationEngineInstance, request: LineScrollRequest): void;
42
42
  export declare function dropPendingLineScroll(engine: AnimationEngineInstance): void;
43
- export declare function removeLineScrollAnimation(engine: AnimationEngineInstance, record: LineScrollAnimationRecord): void;
44
- export declare function clearLineScrollAnimations(engine: AnimationEngineInstance): void;
43
+ export declare function clearLineScrolls(engine: AnimationEngineInstance): void;
45
44
  export declare function isLineVisibleDuringScroll(line: LineScrollItem, fromScrollTop: number, toScrollTop: number, viewportHeight: number): boolean;
46
45
  export declare function getLineScrollItems(engine: AnimationEngineInstance, lines: LineData[]): LineScrollItem[];
47
46
  export declare function measureTrailingItem(lyricsElement: HTMLElement, className: string): LineScrollItem | null;
@@ -1,4 +1,5 @@
1
1
  import { getRelativeLayoutBounds } from "../util.js";
2
+ import { addElementCurve, removeElementCurves, timelineNow } from "./elementMotion.js";
2
3
  import { clearScrollVariables, resolveScrollTimings, resolveThemedTranslates, themeOverridesScrollTranslate, writeScrollVariables, } from "./lineScrollStyle.js";
3
4
  export const SCROLL_PREPARE_LEAD_MS = 120;
4
5
  export const LINE_SCROLL_WILL_CHANGE_VALUE = "transform, translate";
@@ -56,7 +57,15 @@ function planLineScroll(engine, request) {
56
57
  const side = scrollSide(relativeIndex, deltaPx);
57
58
  const timingKey = `${side}|${Math.abs(relativeIndex)}`;
58
59
  const cachedTiming = engine.cachedLineScrollTiming.get(timingKey);
59
- targets.push({ lineElement, side, token: claimLine(engine, lineElement), relativeIndex, timingKey, cachedTiming });
60
+ targets.push({
61
+ lineElement,
62
+ side,
63
+ heightPx: line.height,
64
+ token: claimLine(engine, lineElement),
65
+ relativeIndex,
66
+ timingKey,
67
+ cachedTiming,
68
+ });
60
69
  if (translateThemed || !cachedTiming) {
61
70
  writeScrollVariables(lineElement, { index, activeIndex, relativeIndex, side, deltaPx });
62
71
  }
@@ -76,8 +85,8 @@ function planLineScroll(engine, request) {
76
85
  : activeDurationMs + (timing.durationMs - activeDurationMs) * staggerScale,
77
86
  startEasing: timing.startEasing,
78
87
  endEasing: timing.endEasing,
79
- startTranslate: translates?.start[index] ?? `0px ${deltaPx}px`,
80
- endTranslate: translates?.end[index] ?? "0px 0px",
88
+ startPx: translates?.start[index] ?? deltaPx,
89
+ endPx: translates?.end[index] ?? 0,
81
90
  };
82
91
  });
83
92
  }
@@ -111,14 +120,22 @@ function staggerScaleKeepingLinesApart(lines, activeIndex, distancePx, continues
111
120
  return Math.min(1, stepPx / distancePx);
112
121
  }
113
122
  function startLineScroll(engine, plan) {
123
+ const startMs = timelineNow(engine);
114
124
  for (const line of plan) {
115
125
  if (!line.lineElement.isConnected || !ownsLine(engine, line.lineElement, line.token))
116
126
  continue;
117
- const animation = line.lineElement.animate([
118
- { translate: line.startTranslate, easing: line.startEasing },
119
- { translate: line.endTranslate, easing: line.endEasing },
120
- ], { composite: "add", duration: line.durationMs, easing: "linear", fill: "none" });
121
- trackLineScrollAnimation(engine, animation, line.lineElement, line.token);
127
+ const scroll = { lineElement: line.lineElement, token: line.token, durationMs: line.durationMs };
128
+ engine.runningLineScrolls.push(scroll);
129
+ addElementCurve(engine, line.lineElement, {
130
+ kind: "scroll",
131
+ startMs,
132
+ durationMs: line.durationMs,
133
+ fromPx: line.startPx,
134
+ toPx: line.endPx,
135
+ easing: line.startEasing,
136
+ endEasing: line.endEasing,
137
+ onEnd: () => endLineScroll(engine, scroll),
138
+ });
122
139
  }
123
140
  }
124
141
  function claimLine(engine, lineElement) {
@@ -135,25 +152,18 @@ function releaseLine(engine, lineElement, token) {
135
152
  clearScrollVariables(lineElement);
136
153
  engine.lineScrollElementTokens.delete(lineElement);
137
154
  }
138
- function trackLineScrollAnimation(engine, animation, lineElement, token) {
139
- const record = { animation, lineElement, token };
140
- engine.lineScrollAnimations.push(record);
141
- animation.addEventListener("finish", () => removeLineScrollAnimation(engine, record), { once: true });
142
- animation.addEventListener("cancel", () => removeLineScrollAnimation(engine, record), { once: true });
143
- }
144
- export function removeLineScrollAnimation(engine, record) {
145
- const index = engine.lineScrollAnimations.indexOf(record);
155
+ function endLineScroll(engine, scroll) {
156
+ const index = engine.runningLineScrolls.indexOf(scroll);
146
157
  if (index !== -1)
147
- engine.lineScrollAnimations.splice(index, 1);
148
- releaseLine(engine, record.lineElement, record.token);
149
- }
150
- export function clearLineScrollAnimations(engine) {
151
- const records = engine.lineScrollAnimations;
152
- engine.lineScrollAnimations = [];
153
- for (const record of records) {
154
- record.animation.cancel();
155
- releaseLine(engine, record.lineElement, record.token);
156
- }
158
+ engine.runningLineScrolls.splice(index, 1);
159
+ releaseLine(engine, scroll.lineElement, scroll.token);
160
+ }
161
+ export function clearLineScrolls(engine) {
162
+ const scrolledElements = new Set(engine.runningLineScrolls.map(scroll => scroll.lineElement));
163
+ for (const element of scrolledElements)
164
+ removeElementCurves(engine, element, "scroll");
165
+ for (const scroll of [...engine.runningLineScrolls])
166
+ endLineScroll(engine, scroll);
157
167
  }
158
168
  export function isLineVisibleDuringScroll(line, fromScrollTop, toScrollTop, viewportHeight) {
159
169
  const visibleTop = Math.min(fromScrollTop, toScrollTop);
@@ -10,6 +10,9 @@ export interface StyledScrollLine {
10
10
  lineElement: HTMLElement;
11
11
  side: LineScrollSide;
12
12
  }
13
+ interface SizedScrollLine extends StyledScrollLine {
14
+ heightPx: number;
15
+ }
13
16
  export interface ScrollVariables {
14
17
  index: number;
15
18
  activeIndex: number;
@@ -21,7 +24,9 @@ export declare function themeOverridesScrollTranslate(): boolean;
21
24
  export declare function writeScrollVariables(lineElement: HTMLElement, variables: ScrollVariables): void;
22
25
  export declare function clearScrollVariables(lineElement: HTMLElement): void;
23
26
  export declare function resolveScrollTimings(engine: AnimationEngineInstance, lines: StyledScrollLine[], { lineScroll }: AnimationConfig): LineScrollTiming[];
24
- export declare function resolveThemedTranslates(engine: AnimationEngineInstance, lines: StyledScrollLine[], { lineScroll }: AnimationConfig): {
25
- start: string[];
26
- end: string[];
27
+ export declare function resolveThemedTranslates(engine: AnimationEngineInstance, lines: SizedScrollLine[], { lineScroll }: AnimationConfig): {
28
+ start: (number | null)[];
29
+ end: (number | null)[];
27
30
  };
31
+ export declare function translateYPx(translate: string, heightPx: number): number | null;
32
+ export {};
@@ -93,12 +93,26 @@ export function resolveThemedTranslates(engine, lines, { lineScroll }) {
93
93
  const translatesAt = (keyframe) => batchProbeComputedStyle(engine, lines, "translate", line => {
94
94
  const fallback = keyframe === "start" ? "var(--blyrics-line-scroll-delta-px, 0px)" : "0px";
95
95
  return `0 ${scrollVariable(`translate-y-${keyframe}`, line.side, lineScroll.differentialEffects, fallback)}`;
96
- }, style => normalizedTranslate(style.translate));
96
+ }, style => style.translate).map((translate, index) => translateYPx(translate, lines[index].heightPx));
97
97
  return { start: translatesAt("start"), end: translatesAt("end") };
98
98
  }
99
- function normalizedTranslate(translateValue) {
100
- const translate = translateValue.trim();
101
- return translate && translate !== "none" ? translate : "0px 0px";
99
+ export function translateYPx(translate, heightPx) {
100
+ const value = translate.trim();
101
+ if (value === "" || value === "none")
102
+ return 0;
103
+ const [, y = "0px"] = value.match(/calc\([^)]*\)|\S+/g) ?? [];
104
+ const terms = y
105
+ .replace(/^calc\((.*)\)$/, "$1")
106
+ .replace(/\s+-\s+/g, " + -")
107
+ .split(/\s+\+\s+/);
108
+ let px = 0;
109
+ for (const term of terms) {
110
+ const length = term.trim().match(/^(-?[\d.]+(?:e-?\d+)?)(px|%)?$/);
111
+ if (!length || (length[2] === undefined && Number(length[1]) !== 0))
112
+ return null;
113
+ px += length[2] === "%" ? (Number(length[1]) * heightPx) / 100 : Number(length[1]);
114
+ }
115
+ return px;
102
116
  }
103
117
  function batchProbeComputedStyle(engine, lines, property, probeValue, readValue) {
104
118
  const previous = lines.map(({ lineElement }) => ({
@@ -0,0 +1,19 @@
1
+ export interface MotionCurve {
2
+ startMs: number;
3
+ durationMs: number;
4
+ fromPx: number;
5
+ toPx: number;
6
+ easing: string;
7
+ endEasing: string;
8
+ }
9
+ export type Easing = (progress: number) => number;
10
+ export type EasingLookup = (easing: string) => Easing;
11
+ export interface BakedMotion {
12
+ keyframes: Keyframe[];
13
+ startMs: number;
14
+ durationMs: number;
15
+ }
16
+ export declare function curveEndMs(curve: MotionCurve): number;
17
+ export declare function isRunningAt(curve: MotionCurve, timeMs: number): boolean;
18
+ export declare function offsetAt(curves: readonly MotionCurve[], timeMs: number, easingOf: EasingLookup): number;
19
+ export declare function bakeMotion(curves: readonly MotionCurve[], nowMs: number, easingOf: EasingLookup): BakedMotion;
@@ -0,0 +1,85 @@
1
+ const TOLERANCE_PX = 0.1;
2
+ const LONGEST_STOP_SPAN_MS = 100;
3
+ const SHORTEST_STOP_SPAN_MS = 1;
4
+ export function curveEndMs(curve) {
5
+ return curve.startMs + curve.durationMs;
6
+ }
7
+ export function isRunningAt(curve, timeMs) {
8
+ return curve.startMs <= timeMs && timeMs < curveEndMs(curve);
9
+ }
10
+ export function offsetAt(curves, timeMs, easingOf) {
11
+ return curves
12
+ .filter(curve => isRunningAt(curve, timeMs))
13
+ .reduce((sum, curve) => sum + easedOffset(curve, easingOf(curve.easing), timeMs), 0);
14
+ }
15
+ export function bakeMotion(curves, nowMs, easingOf) {
16
+ if (curves.length === 1)
17
+ return exactly(curves[0]);
18
+ const endsMs = [...new Set(curves.map(curveEndMs))].sort((a, b) => a - b);
19
+ const stops = [];
20
+ let fromMs = nowMs;
21
+ for (const toMs of endsMs) {
22
+ const running = curves
23
+ .filter(curve => curve.startMs <= fromMs && curveEndMs(curve) >= toMs)
24
+ .map(curve => ({ curve, easing: easingOf(curve.easing) }));
25
+ const path = timeMs => {
26
+ let offsetPx = 0;
27
+ for (const { curve, easing } of running)
28
+ offsetPx += easedOffset(curve, easing, timeMs);
29
+ return offsetPx;
30
+ };
31
+ const fromPx = path(fromMs);
32
+ if (stops.at(-1)?.offsetPx !== fromPx)
33
+ stops.push({ timeMs: fromMs, offsetPx: fromPx });
34
+ const spans = Math.ceil((toMs - fromMs) / LONGEST_STOP_SPAN_MS);
35
+ for (let span = 1; span <= spans; span++) {
36
+ const spanEndMs = fromMs + ((toMs - fromMs) * span) / spans;
37
+ appendStops(path, stops[stops.length - 1], { timeMs: spanEndMs, offsetPx: path(spanEndMs) }, stops);
38
+ }
39
+ fromMs = toMs;
40
+ }
41
+ const durationMs = endsMs[endsMs.length - 1] - nowMs;
42
+ const fullScalePx = Math.max(...stops.map(stop => Math.abs(stop.offsetPx))) || 1;
43
+ const easing = `linear(${stops
44
+ .map(({ timeMs, offsetPx }) => `${rounded(offsetPx / fullScalePx)} ${rounded((100 * (timeMs - nowMs)) / durationMs)}%`)
45
+ .join(", ")})`;
46
+ return {
47
+ keyframes: [
48
+ { translate: translateOf(0), easing },
49
+ { translate: translateOf(fullScalePx), easing: "linear" },
50
+ ],
51
+ startMs: nowMs,
52
+ durationMs,
53
+ };
54
+ }
55
+ function appendStops(path, from, to, stops) {
56
+ const middleMs = (from.timeMs + to.timeMs) / 2;
57
+ const middle = { timeMs: middleMs, offsetPx: path(middleMs) };
58
+ const chordPx = (from.offsetPx + to.offsetPx) / 2;
59
+ if (Math.abs(middle.offsetPx - chordPx) <= TOLERANCE_PX || to.timeMs - from.timeMs <= SHORTEST_STOP_SPAN_MS) {
60
+ stops.push(to);
61
+ return;
62
+ }
63
+ appendStops(path, from, middle, stops);
64
+ appendStops(path, middle, to, stops);
65
+ }
66
+ function exactly(curve) {
67
+ return {
68
+ keyframes: [
69
+ { translate: translateOf(curve.fromPx), easing: curve.easing },
70
+ { translate: translateOf(curve.toPx), easing: curve.endEasing },
71
+ ],
72
+ startMs: curve.startMs,
73
+ durationMs: curve.durationMs,
74
+ };
75
+ }
76
+ function easedOffset(curve, easing, timeMs) {
77
+ const progress = curve.durationMs > 0 ? Math.min(1, (timeMs - curve.startMs) / curve.durationMs) : 1;
78
+ return curve.fromPx + (curve.toPx - curve.fromPx) * easing(progress);
79
+ }
80
+ function translateOf(offsetPx) {
81
+ return `0px ${Math.round(offsetPx * 1000) / 1000}px`;
82
+ }
83
+ function rounded(value) {
84
+ return Math.round(value * 1e6) / 1e6;
85
+ }
@@ -4,14 +4,13 @@ import type { AnimationEngineInstance } from "./instance.js";
4
4
  type LinePlacement = {
5
5
  position: number;
6
6
  height: number;
7
- scrollAnimationOffset: number;
7
+ motionOffset: number;
8
8
  };
9
9
  export declare function clearOnScreenLyrics(engine: AnimationEngineInstance): boolean;
10
10
  export declare function hasRenderedLines(engine: AnimationEngineInstance): boolean;
11
11
  export declare function getRenderedLines(engine: AnimationEngineInstance): LineData[];
12
12
  export declare function getRenderedSyncType(engine: AnimationEngineInstance): LyricSyncType;
13
13
  export declare function clearLyrics(engine: AnimationEngineInstance): void;
14
- export declare function lineScrollOffset(engine: AnimationEngineInstance, element: HTMLElement): number;
15
14
  export declare function replaceRenderedLines(engine: AnimationEngineInstance, lines: LineData[], dropped: readonly LineData[], previousOf: ReadonlyMap<LineData, LineData>): void;
16
15
  export declare function settleSwappedLines(engine: AnimationEngineInstance, before: ReadonlyMap<LineData, LinePlacement>, scrollTopBefore: number): void;
17
16
  export {};