@braccato/core 1.22.0 → 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 (102) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +202 -607
  3. package/js/element.js +234 -0
  4. package/js/renderer.d.ts +157 -0
  5. package/js/renderer.js +535 -0
  6. package/package.json +22 -17
  7. package/pkg/braccato_core_rs.d.ts +236 -0
  8. package/pkg/braccato_core_rs.js +1735 -0
  9. package/pkg/braccato_core_rs_bg.wasm +0 -0
  10. package/pkg/braccato_core_rs_bg.wasm.d.ts +55 -0
  11. package/dist/LICENSE +0 -21
  12. package/dist/README.md +0 -639
  13. package/dist/element.d.ts +0 -168
  14. package/dist/element.js +0 -730
  15. package/dist/engine/animationConfig.d.ts +0 -84
  16. package/dist/engine/animationConfig.js +0 -95
  17. package/dist/engine/animationDrift.d.ts +0 -11
  18. package/dist/engine/animationDrift.js +0 -43
  19. package/dist/engine/animationTiming.d.ts +0 -27
  20. package/dist/engine/animationTiming.js +0 -145
  21. package/dist/engine/autoScroll.d.ts +0 -24
  22. package/dist/engine/autoScroll.js +0 -103
  23. package/dist/engine/clock.d.ts +0 -29
  24. package/dist/engine/clock.js +0 -70
  25. package/dist/engine/contextSweep.d.ts +0 -10
  26. package/dist/engine/contextSweep.js +0 -102
  27. package/dist/engine/cssValues.d.ts +0 -13
  28. package/dist/engine/cssValues.js +0 -47
  29. package/dist/engine/culling.d.ts +0 -6
  30. package/dist/engine/culling.js +0 -76
  31. package/dist/engine/debugOverlay.d.ts +0 -14
  32. package/dist/engine/debugOverlay.js +0 -58
  33. package/dist/engine/decorationSlides.d.ts +0 -6
  34. package/dist/engine/decorationSlides.js +0 -53
  35. package/dist/engine/elementMotion.d.ts +0 -18
  36. package/dist/engine/elementMotion.js +0 -98
  37. package/dist/engine/glow.d.ts +0 -7
  38. package/dist/engine/glow.js +0 -59
  39. package/dist/engine/instance.d.ts +0 -105
  40. package/dist/engine/instance.js +0 -89
  41. package/dist/engine/instrumentalAnimations.d.ts +0 -7
  42. package/dist/engine/instrumentalAnimations.js +0 -59
  43. package/dist/engine/letterPlans.d.ts +0 -31
  44. package/dist/engine/letterPlans.js +0 -62
  45. package/dist/engine/lineAnimationState.d.ts +0 -10
  46. package/dist/engine/lineAnimationState.js +0 -82
  47. package/dist/engine/lineAnimations.d.ts +0 -5
  48. package/dist/engine/lineAnimations.js +0 -63
  49. package/dist/engine/lineLifecycle.d.ts +0 -12
  50. package/dist/engine/lineLifecycle.js +0 -92
  51. package/dist/engine/lineScroll.d.ts +0 -47
  52. package/dist/engine/lineScroll.js +0 -184
  53. package/dist/engine/lineScrollStyle.d.ts +0 -32
  54. package/dist/engine/lineScrollStyle.js +0 -133
  55. package/dist/engine/liveViews.d.ts +0 -3
  56. package/dist/engine/liveViews.js +0 -5
  57. package/dist/engine/motionCurves.d.ts +0 -19
  58. package/dist/engine/motionCurves.js +0 -85
  59. package/dist/engine/motionPreference.d.ts +0 -1
  60. package/dist/engine/motionPreference.js +0 -1
  61. package/dist/engine/passiveScroll.d.ts +0 -10
  62. package/dist/engine/passiveScroll.js +0 -93
  63. package/dist/engine/renderedLines.d.ts +0 -16
  64. package/dist/engine/renderedLines.js +0 -130
  65. package/dist/engine/scrollViewport.d.ts +0 -36
  66. package/dist/engine/scrollViewport.js +0 -104
  67. package/dist/engine/stageMotion.d.ts +0 -7
  68. package/dist/engine/stageMotion.js +0 -319
  69. package/dist/engine/sweepPlans.d.ts +0 -38
  70. package/dist/engine/sweepPlans.js +0 -66
  71. package/dist/engine/tick.d.ts +0 -16
  72. package/dist/engine/tick.js +0 -270
  73. package/dist/engine/timingLogs.d.ts +0 -7
  74. package/dist/engine/timingLogs.js +0 -81
  75. package/dist/engine/userScroll.d.ts +0 -12
  76. package/dist/engine/userScroll.js +0 -62
  77. package/dist/engine/wavePool.d.ts +0 -7
  78. package/dist/engine/wavePool.js +0 -22
  79. package/dist/engine/wordAnimations.d.ts +0 -5
  80. package/dist/engine/wordAnimations.js +0 -206
  81. package/dist/imageHighlights.d.ts +0 -4
  82. package/dist/imageHighlights.js +0 -34
  83. package/dist/index.d.ts +0 -17
  84. package/dist/index.js +0 -12
  85. package/dist/inject.d.ts +0 -98
  86. package/dist/inject.js +0 -591
  87. package/dist/instrumental.d.ts +0 -11
  88. package/dist/instrumental.js +0 -121
  89. package/dist/language.d.ts +0 -9
  90. package/dist/language.js +0 -47
  91. package/dist/letters.d.ts +0 -2
  92. package/dist/letters.js +0 -25
  93. package/dist/renderer.d.ts +0 -29
  94. package/dist/renderer.js +0 -412
  95. package/dist/seek.d.ts +0 -1
  96. package/dist/seek.js +0 -27
  97. package/dist/stage.d.ts +0 -58
  98. package/dist/stage.js +0 -121
  99. package/dist/types.d.ts +0 -236
  100. package/dist/types.js +0 -1
  101. package/dist/view.d.ts +0 -51
  102. package/dist/view.js +0 -398
@@ -1,121 +0,0 @@
1
- import { imageHighlights } from "./imageHighlights.js";
2
- export const INSTRUMENTAL_WAVE_PATH_HIGH = "M -4 3 Q 1 2 5 3 Q 10 4 14 3 Q 18 2 22 3 Q 26 4 30 3 L 30 4 L -4 4 Z";
3
- export const INSTRUMENTAL_WAVE_PATH_LOW = "M -4 3 Q 1 4 5 3 Q 10 2 14 3 Q 18 4 22 3 Q 26 2 30 3 L 30 4 L -4 4 Z";
4
- let nextInstrumentalId = 0;
5
- /**
6
- * Creates an HTML element representing an instrumental break in the lyrics.
7
- *
8
- * @param doc - Document the SVG nodes are created in
9
- * @param container - Element to place instrumental parts into
10
- * @param durationMs - Duration of the instrumental break in milliseconds
11
- * @returns HTMLDivElement representing the instrumental break
12
- */
13
- export function createInstrumentalElement(doc, container, durationMs) {
14
- container.classList.add("blyrics--instrumental");
15
- container.style.setProperty("--blyrics-duration", `${durationMs}ms`);
16
- const svgNS = "http://www.w3.org/2000/svg";
17
- const svg = doc.createElementNS(svgNS, "svg");
18
- svg.classList.add("blyrics--instrumental-icon");
19
- svg.setAttribute("viewBox", "0 0 24 24");
20
- const defs = doc.createElementNS(svgNS, "defs");
21
- // Unique per document, not per view: two renderers sharing a document would otherwise resolve
22
- // each other's url(#id) references.
23
- const idSuffix = nextInstrumentalId++;
24
- const filterId = `blyrics-glow-${idSuffix}`;
25
- const clipId = `blyrics-wave-clip-${idSuffix}`;
26
- const filter = doc.createElementNS(svgNS, "filter");
27
- filter.setAttribute("id", filterId);
28
- filter.setAttribute("x", "-100%");
29
- filter.setAttribute("y", "-100%");
30
- filter.setAttribute("width", "300%");
31
- filter.setAttribute("height", "300%");
32
- const feGaussianBlur = doc.createElementNS(svgNS, "feGaussianBlur");
33
- feGaussianBlur.setAttribute("in", "SourceGraphic");
34
- feGaussianBlur.setAttribute("stdDeviation", "5");
35
- feGaussianBlur.setAttribute("result", "blur");
36
- filter.appendChild(feGaussianBlur);
37
- const feColorMatrix = doc.createElementNS(svgNS, "feColorMatrix");
38
- feColorMatrix.setAttribute("in", "blur");
39
- feColorMatrix.setAttribute("type", "matrix");
40
- feColorMatrix.setAttribute("values", "1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0.6 0");
41
- feColorMatrix.setAttribute("result", "fadedBlur");
42
- filter.appendChild(feColorMatrix);
43
- const feMerge = doc.createElementNS(svgNS, "feMerge");
44
- const feMergeNode1 = doc.createElementNS(svgNS, "feMergeNode");
45
- feMergeNode1.setAttribute("in", "fadedBlur");
46
- feMerge.appendChild(feMergeNode1);
47
- const feMergeNode2 = doc.createElementNS(svgNS, "feMergeNode");
48
- feMergeNode2.setAttribute("in", "SourceGraphic");
49
- feMerge.appendChild(feMergeNode2);
50
- filter.appendChild(feMerge);
51
- defs.appendChild(filter);
52
- const clipPath = doc.createElementNS(svgNS, "clipPath");
53
- clipPath.setAttribute("id", clipId);
54
- clipPath.classList.add("blyrics--wave-clip");
55
- // Create the Static Block (The deep fill)
56
- // This sits at y=4 (the lowest point of the wave) and extends to bottom
57
- const waveRect = doc.createElementNS(svgNS, "path");
58
- waveRect.classList.add("blyrics--wave-rect");
59
- waveRect.setAttribute("d", "M -4 3.9 L 30 3.9 L 30 30 L -4 30 Z");
60
- clipPath.appendChild(waveRect);
61
- // Create the Wavy Top
62
- // This only contains the surface water. It closes at y=4.
63
- const wavePath = doc.createElementNS(svgNS, "path");
64
- wavePath.classList.add("blyrics--wave-path");
65
- wavePath.setAttribute("d", INSTRUMENTAL_WAVE_PATH_HIGH);
66
- clipPath.appendChild(wavePath);
67
- defs.appendChild(clipPath);
68
- svg.appendChild(defs);
69
- const bgPath = doc.createElementNS(svgNS, "path");
70
- bgPath.classList.add("blyrics--instrumental-bg");
71
- bgPath.setAttribute("d", "M10 21q-1.65 0-2.825-1.175T6 17t1.175-2.825T10 13q.575 0 1.063.138t.937.412V4q0-.425.288-.712T13 3h4q.425 0 .713.288T18 4v2q0 .425-.288.713T17 7h-3v10q0 1.65-1.175 2.825T10 21");
72
- svg.appendChild(bgPath);
73
- const g = doc.createElementNS(svgNS, "g");
74
- g.setAttribute("filter", `url(#${filterId})`);
75
- const fillPath = doc.createElementNS(svgNS, "path");
76
- fillPath.classList.add("blyrics--instrumental-fill");
77
- fillPath.setAttribute("clip-path", `url(#${clipId})`);
78
- fillPath.setAttribute("d", "M10 21q-1.65 0-2.825-1.175T6 17t1.175-2.825T10 13q.575 0 1.063.138t.937.412V4q0-.425.288-.712T13 3h4q.425 0 .713.288T18 4v2q0 .425-.288.713T17 7h-3v10q0 1.65-1.175 2.825T10 21");
79
- if (imageHighlights.getBooleanValue()) {
80
- // Fade the common group so both the image and the SDR fallback follow the original
81
- // instrumental animation. The wave and silhouette clips are inside the glow filter.
82
- fillPath.classList.remove("blyrics--instrumental-fill");
83
- fillPath.classList.add("blyrics-instrumental-color");
84
- const fill = doc.createElementNS(svgNS, "g");
85
- fill.classList.add("blyrics--instrumental-fill");
86
- fill.appendChild(fillPath);
87
- const shapeId = `${clipId}-image-shape`;
88
- const shape = doc.createElementNS(svgNS, "clipPath");
89
- shape.setAttribute("id", shapeId);
90
- const shapePath = doc.createElementNS(svgNS, "path");
91
- shapePath.setAttribute("d", fillPath.getAttribute("d"));
92
- shape.appendChild(shapePath);
93
- defs.appendChild(shape);
94
- const silhouette = doc.createElementNS(svgNS, "g");
95
- silhouette.setAttribute("clip-path", `url(#${shapeId})`);
96
- const wave = doc.createElementNS(svgNS, "g");
97
- wave.setAttribute("clip-path", `url(#${clipId})`);
98
- const image = doc.createElementNS(svgNS, "image");
99
- image.classList.add("blyrics-instrumental-image");
100
- image.setAttribute("x", "0");
101
- image.setAttribute("y", "0");
102
- image.setAttribute("width", "24");
103
- image.setAttribute("height", "24");
104
- image.setAttribute("preserveAspectRatio", "none");
105
- wave.appendChild(image);
106
- silhouette.appendChild(wave);
107
- fill.appendChild(silhouette);
108
- g.appendChild(fill);
109
- // Blur RGB directly instead of recoloring the halo with an SDR flood/shadow.
110
- filter.setAttribute("color-interpolation-filters", "sRGB");
111
- feGaussianBlur.setAttribute("stdDeviation", "1");
112
- filter.removeChild(feColorMatrix);
113
- feMergeNode1.setAttribute("in", "blur");
114
- }
115
- else {
116
- g.appendChild(fillPath);
117
- }
118
- svg.appendChild(g);
119
- container.appendChild(svg);
120
- return container;
121
- }
@@ -1,9 +0,0 @@
1
- interface LyricText {
2
- words: string;
3
- isInstrumental?: boolean;
4
- }
5
- export declare function normalizeLanguage(language?: string | null): string;
6
- export declare function resolveLyricLanguages(lyrics: readonly LyricText[], sourceLanguage?: string | null): string[];
7
- /** Tags only lyric content, leaving the host UI and source footer in their own language. */
8
- export declare function applyLyricLanguage(element: HTMLElement, language?: string | null): void;
9
- export {};
package/dist/language.js DELETED
@@ -1,47 +0,0 @@
1
- import { ROMANIZED_LYRICS_CLASS } from "./constants.js";
2
- export function normalizeLanguage(language) {
3
- if (!language || language === "auto" || language === "und")
4
- return "";
5
- try {
6
- return Intl.getCanonicalLocales(language.trim().replaceAll("_", "-"))[0] ?? "";
7
- }
8
- catch {
9
- return "";
10
- }
11
- }
12
- function detectCjkLanguage(text) {
13
- if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text))
14
- return "ja";
15
- if (/\p{Script=Hangul}/u.test(text))
16
- return "ko";
17
- // Han alone cannot distinguish Japanese, Korean, or the Chinese writing systems.
18
- return null;
19
- }
20
- function isCjkLanguage(language) {
21
- return /^(ja|ko|zh|yue)(-|$)|-(Hans|Hant)(-|$)/i.test(language);
22
- }
23
- export function resolveLyricLanguages(lyrics, sourceLanguage) {
24
- const language = normalizeLanguage(sourceLanguage);
25
- const hints = lyrics.map(line => (line.isInstrumental ? null : detectCjkLanguage(line.words)));
26
- const songHints = new Set(hints.filter(hint => hint !== null));
27
- const songHint = songHints.size === 1 ? [...songHints][0] : "";
28
- const fallback = isCjkLanguage(language) ? language : songHint || language;
29
- return lyrics.map((line, index) => {
30
- if (line.isInstrumental)
31
- return "";
32
- const hint = hints[index];
33
- if (hint && fallback.split("-")[0] !== hint)
34
- return hint;
35
- if (/\p{Script=Han}/u.test(line.words) && !isCjkLanguage(fallback))
36
- return "";
37
- return fallback;
38
- });
39
- }
40
- /** Tags only lyric content, leaving the host UI and source footer in their own language. */
41
- export function applyLyricLanguage(element, language) {
42
- const normalized = normalizeLanguage(language);
43
- element.lang = normalized;
44
- const romanization = element.querySelector(`.${ROMANIZED_LYRICS_CLASS}`);
45
- if (romanization)
46
- romanization.lang = `${normalized ? new Intl.Locale(normalized).language : "und"}-Latn`;
47
- }
package/dist/letters.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export declare function letterClusters(text: string): string[];
2
- export declare function joinLetterSegments(segments: Iterable<string>): string[];
package/dist/letters.js DELETED
@@ -1,25 +0,0 @@
1
- const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
2
- // Canonical_Combining_Class=Virama minus the ones that stay visible; Sinhala al-lakuna joins only beside a ZWJ.
3
- const CONJUNCT_VIRAMA_REGEX = /(?:[\u{94D}\u{9CD}\u{A4D}\u{ACD}\u{B4D}\u{C4D}\u{CCD}\u{D4D}\u{1039}\u{17D2}\u{1A60}\u{1B44}\u{1BAB}\u{2D7F}\u{A9C0}\u{AAF6}\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{111C0}\u{11235}\u{1134D}\u{113D0}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{11839}\u{1193E}\u{119E0}\u{11A47}\u{11A99}\u{11C3F}\u{11D45}\u{11D97}\u{11F42}]\u200D?|\u200D\u0DCA|\u0DCA\u200D)$/u;
4
- const LETTER_START_REGEX = /^\p{L}/u;
5
- const MARK_START_REGEX = /^\p{M}/u;
6
- const joinsTamilLigature = (previous, next) => (previous.endsWith("க்") && next.startsWith("ஷ")) || (previous.endsWith("ஸ்") && next.startsWith("ரீ"));
7
- export function letterClusters(text) {
8
- return joinLetterSegments(Array.from(graphemeSegmenter.segment(text), ({ segment }) => segment));
9
- }
10
- export function joinLetterSegments(segments) {
11
- const clusters = [];
12
- let previous = "";
13
- for (const segment of segments) {
14
- const joins = clusters.length > 0 &&
15
- (MARK_START_REGEX.test(segment) ||
16
- (LETTER_START_REGEX.test(segment) &&
17
- (CONJUNCT_VIRAMA_REGEX.test(previous) || joinsTamilLigature(previous, segment))));
18
- if (joins)
19
- clusters[clusters.length - 1] += segment;
20
- else
21
- clusters.push(segment);
22
- previous = segment;
23
- }
24
- return clusters;
25
- }
@@ -1,29 +0,0 @@
1
- import type { LyricsRenderer, LyricsRendererHost, LyricsRendererOptions } from "./types.js";
2
- /**
3
- * Fills in every host member the consumer left out, so the host is an extension point rather than a
4
- * cost of entry. The mount is read at call time rather than captured: `setLyrics` may be given a
5
- * different one, and both defaults that use it have to follow.
6
- *
7
- * Each member is resolved on its own rather than spread over the defaults. A host assembled from
8
- * optional pieces carries members that are present and undefined, which typecheck, and spreading
9
- * one of those leaves the renderer holding nothing where it expects a function.
10
- *
11
- * The invalidator comes back alongside the host because the memo behind the default scroll element
12
- * has no way to notice it went stale on its own.
13
- *
14
- * Exported for `renderer.selfcheck.ts` and not published from `index.ts`. A consumer reaches these
15
- * defaults by leaving host members out, so nothing outside needs to name them; what does need to is
16
- * the check that every one of them is still here and still answering.
17
- */
18
- export declare function withHostDefaults(overrides: Partial<LyricsRendererHost> | undefined, rendererWindow: Window & typeof globalThis, currentMount: () => HTMLElement | null): {
19
- host: LyricsRendererHost;
20
- forgetScrollElement: () => void;
21
- };
22
- /**
23
- * Builds a lyrics view and keeps it measured. Line positions are read once, when the lines are
24
- * built, and everything the engine scrolls by comes from that reading, so a layout that settles
25
- * afterwards leaves the whole song scrolling to stale targets. Three things settle afterwards: the
26
- * container's own size, the document's font faces, and the window. This owns all three, because
27
- * both of the views in this extension went into production having missed at least one of them.
28
- */
29
- export declare function createLyricsRenderer(rendererOptions: LyricsRendererOptions): LyricsRenderer;
package/dist/renderer.js DELETED
@@ -1,412 +0,0 @@
1
- // What a consumer holds: one object per view, composing the engine that animates the lines, the
2
- // builder that makes them and the theme settings both read. Nothing under here reaches for its
3
- // surroundings on its own, so everything the module needs from outside arrives through
4
- // `LyricsRendererOptions`, and everything it cannot do itself goes back out through the host.
5
- //
6
- // Only the document to build in and the window to schedule against are required. Every host member
7
- // but `debug` has a default, which is what makes the host an extension point a consumer overrides
8
- // one member at a time rather than a cost of entry: it answers the questions the module cannot (is
9
- // this view on screen, is a loader up) and performs the actions it must not own (seek the player).
10
- // `debug` is the exception because there is nothing to default it to. A consumer that wants the
11
- // diagnostic overlay supplies the sink, and one that says nothing draws nothing.
12
- import { imageHighlights, refreshInstrumentalImages } from "./imageHighlights.js";
13
- import { CUSTOM_THEME_STYLE_ID } from "./constants.js";
14
- import { clearLyrics, clearOnScreenLyrics as clearEngineOnScreenLyrics, getRenderedLines, getRenderedSyncType, settleSwappedLines, } from "./engine/renderedLines.js";
15
- import { clearStyleCaches as clearEngineStyleCaches } from "./engine/cssValues.js";
16
- import { createAnimationEngineInstance } from "./engine/instance.js";
17
- import { hasUnsyncedLyrics } from "./engine/passiveScroll.js";
18
- import { hasContainerResized, noteUserScroll as noteEngineUserScroll, resetScrollResume } from "./engine/userScroll.js";
19
- import { noteVisibilityChange as noteEngineVisibilityChange } from "./engine/timingLogs.js";
20
- import { relayout, resolveTickOptions, retickAtLastTime, retickFromPlaybackClock as retickEngineFromPlaybackClock, scheduleLyricPositionUpdate as scheduleEngineLyricPositionUpdate, tickView, } from "./engine/tick.js";
21
- import { parseThemeConfig, setThemeSettings } from "./themeSettings.js";
22
- import { applyLyricLanguage, normalizeLanguage, resolveLyricLanguages } from "./language.js";
23
- import { setLyrics as buildLyricsView, swapLyrics as swapLyricsView } from "./view.js";
24
- /**
25
- * What the default `seek` dispatches at the mount. A consumer that gave the renderer no way to
26
- * reach its player can listen for this instead of writing a host.
27
- */
28
- const SEEK_EVENT = "braccato:seek";
29
- const DESTROYED_SET_LYRICS_LOG = "Lyrics were handed to a renderer that has been destroyed; nothing was built";
30
- const FONT_MEASURE_LOG = "The lines could not be re-measured after the document's faces loaded";
31
- const SCROLLABLE_OVERFLOW = new Set(["auto", "scroll"]);
32
- function noop() { }
33
- /**
34
- * Whether the lines generate boxes, and so have anything to measure. Lines the page is not
35
- * rendering measure as zero height at zero offset, and every scroll target for the rest of the song
36
- * is read off those numbers, so one measurement taken while they are off the screen strands the
37
- * view until something measures it again.
38
- *
39
- * The lines rather than the container holding them, because the lines are what a re-measurement
40
- * reads. A container under `display: contents` renders its lines while generating no box of its
41
- * own, and a container emptied of its lines still generates one: asking the container answers
42
- * backwards in both directions. Asking the lines covers the container's own case as well, since a
43
- * container that generates no box takes everything inside it with it.
44
- *
45
- * `getClientRects` rather than `offsetParent`: it answers for the boxes an element generates and
46
- * nothing else, while `offsetParent` is also null for a fixed or root element, so a consumer that
47
- * positions its view differently than this module's own stylesheet does would silently stop being
48
- * measured at all.
49
- */
50
- function areLinesMeasurable(lines) {
51
- // A view with no lines has nothing to hold back, and holding it back anyway would leave the
52
- // container's own size unrecorded, so every later report of that same size reads as a change.
53
- if (lines.length === 0)
54
- return true;
55
- return lines.some(line => line.lyricElement.getClientRects().length > 0);
56
- }
57
- /**
58
- * The nearest element that scrolls, starting at the mount itself: a consumer that mounts straight
59
- * into its own scroll container means that container, not whatever else scrolls above it.
60
- */
61
- function findScrollElement(rendererWindow, mount) {
62
- for (let element = mount; element !== null; element = element.parentElement) {
63
- if (SCROLLABLE_OVERFLOW.has(rendererWindow.getComputedStyle(element).overflowY))
64
- return element;
65
- }
66
- if (mount === null)
67
- return null;
68
- // On an ordinary page every ancestor computes to `visible` and the document is what scrolls.
69
- // Standing the mount in for one leaves autoscroll writing scrollTop onto an element that cannot
70
- // scroll, which reads as lyrics that highlight and never move. `scrollingElement` is typed as
71
- // `Element` for documents whose root need not be an HTMLElement; in an HTML one it is html or body.
72
- return mount.ownerDocument.scrollingElement;
73
- }
74
- /**
75
- * Fills in every host member the consumer left out, so the host is an extension point rather than a
76
- * cost of entry. The mount is read at call time rather than captured: `setLyrics` may be given a
77
- * different one, and both defaults that use it have to follow.
78
- *
79
- * Each member is resolved on its own rather than spread over the defaults. A host assembled from
80
- * optional pieces carries members that are present and undefined, which typecheck, and spreading
81
- * one of those leaves the renderer holding nothing where it expects a function.
82
- *
83
- * The invalidator comes back alongside the host because the memo behind the default scroll element
84
- * has no way to notice it went stale on its own.
85
- *
86
- * Exported for `renderer.selfcheck.ts` and not published from `index.ts`. A consumer reaches these
87
- * defaults by leaving host members out, so nothing outside needs to name them; what does need to is
88
- * the check that every one of them is still here and still answering.
89
- */
90
- export function withHostDefaults(overrides, rendererWindow, currentMount) {
91
- const given = overrides ?? {};
92
- // The engine resolves the scroll element on every tick, and the walk reads a computed style per
93
- // ancestor, so an unmemoised default forces style resolution sixty times a second.
94
- //
95
- // A new mount is not the only thing that can change where the walk ends: an ancestor can turn
96
- // scrollable, and the same mount can be moved under a different one. Neither is observable from
97
- // here, so the memo is dropped by whoever does know the layout moved. `undefined` is the state
98
- // before the first walk, because null is an answer a renderer with no mount yet keeps.
99
- let walkedMount;
100
- let walkedScrollElement = null;
101
- function scrollElementForCurrentMount() {
102
- const mount = currentMount();
103
- if (mount !== walkedMount) {
104
- walkedMount = mount;
105
- walkedScrollElement = findScrollElement(rendererWindow, mount);
106
- }
107
- return walkedScrollElement;
108
- }
109
- return {
110
- host: {
111
- isViewVisible: given.isViewVisible ?? (() => true),
112
- isLoaderActive: given.isLoaderActive ?? (() => false),
113
- syncAdState: given.syncAdState ?? (() => false),
114
- getScrollElement: given.getScrollElement ?? scrollElementForCurrentMount,
115
- setResumeAffordanceVisible: given.setResumeAffordanceVisible ?? noop,
116
- seek: given.seek ??
117
- (timeS => {
118
- currentMount()?.dispatchEvent(new rendererWindow.CustomEvent(SEEK_EVENT, { detail: timeS, bubbles: true }));
119
- }),
120
- log: given.log ?? noop,
121
- onStageLayout: given.onStageLayout,
122
- debug: given.debug,
123
- },
124
- forgetScrollElement() {
125
- walkedMount = undefined;
126
- },
127
- };
128
- }
129
- /**
130
- * Builds a lyrics view and keeps it measured. Line positions are read once, when the lines are
131
- * built, and everything the engine scrolls by comes from that reading, so a layout that settles
132
- * afterwards leaves the whole song scrolling to stale targets. Three things settle afterwards: the
133
- * container's own size, the document's font faces, and the window. This owns all three, because
134
- * both of the views in this extension went into production having missed at least one of them.
135
- */
136
- export function createLyricsRenderer(rendererOptions) {
137
- const rendererDocument = rendererOptions.document;
138
- // `Window` types neither `ResizeObserver` nor `CustomEvent`: both are ambient `var` declarations,
139
- // so they are only reachable through `typeof globalThis`. Every real window is one.
140
- const rendererWindow = rendererOptions.window;
141
- let mount = rendererOptions.mount ?? null;
142
- let containerResizeObserver = null;
143
- // Only the theme element this renderer created, which is the only one it may take away again.
144
- let createdThemeStyleElement = null;
145
- let isDestroyed = false;
146
- let currentLyrics = [];
147
- let currentLanguage = "";
148
- const { host, forgetScrollElement } = withHostDefaults(rendererOptions.host, rendererWindow, () => mount);
149
- const engine = createAnimationEngineInstance(rendererDocument, rendererWindow, host, rendererOptions.layout ?? "scroll");
150
- let imageMediaQueries = [];
151
- const refreshImagePaint = () => refreshInstrumentalImages(engine.lyricsContainer, rendererWindow);
152
- function syncImagePaint() {
153
- if (imageHighlights.getBooleanValue() && imageMediaQueries.length === 0) {
154
- imageMediaQueries = ["(dynamic-range: high)", "(forced-colors: active)"].map(query => rendererWindow.matchMedia(query));
155
- for (const query of imageMediaQueries)
156
- query.addEventListener("change", refreshImagePaint);
157
- }
158
- else if (!imageHighlights.getBooleanValue()) {
159
- for (const query of imageMediaQueries)
160
- query.removeEventListener("change", refreshImagePaint);
161
- imageMediaQueries = [];
162
- }
163
- refreshImagePaint();
164
- }
165
- /**
166
- * Every re-measurement runs through here, which makes it the one place that knows the layout may
167
- * have moved under the view. The default scroll element is walked once and remembered, so this is
168
- * also where that walk is allowed to go stale: a resize is exactly when an ancestor is most
169
- * likely to have gained or lost its scrollbar, and it costs one walk per resize rather than one
170
- * per tick.
171
- *
172
- * The lines are only measurable while they are on screen, and whether they are is read off the
173
- * lines themselves rather than asked of the consumer: a view that is hidden while a song loads is
174
- * the normal case for a side panel, and a consumer that has to know to say so is one that will
175
- * forget. The padding is worth rewriting either way, so only the lines are held back.
176
- */
177
- function measure(measureLines = true) {
178
- forgetScrollElement();
179
- if (relayout(engine, measureLines && areLinesMeasurable(getRenderedLines(engine))))
180
- retickAtLastTime(engine);
181
- }
182
- function stopObservingContainer() {
183
- containerResizeObserver?.disconnect();
184
- containerResizeObserver = null;
185
- }
186
- /**
187
- * Drops the song, DOM and all. The engine's own clear keeps the container it was handed, because
188
- * the callers it was written for built that container themselves. This one built it, so leaving it
189
- * behind would leave a cleared view showing the song it just dropped.
190
- */
191
- function clearBuiltView() {
192
- stopObservingContainer();
193
- engine.lyricsContainer?.remove();
194
- clearLyrics(engine);
195
- currentLyrics = [];
196
- currentLanguage = "";
197
- }
198
- /**
199
- * Watches the built container for the layout it settles into. The guard is what stops this
200
- * feeding itself: re-measuring is what records the new size, so the observer has to ask whether
201
- * the size actually changed before it re-measures.
202
- */
203
- function observeContainer(container) {
204
- stopObservingContainer();
205
- const observer = new rendererWindow.ResizeObserver(entries => {
206
- const target = entries[entries.length - 1]?.target;
207
- if (!target)
208
- return;
209
- if (hasContainerResized(engine, target.clientWidth, target.clientHeight))
210
- measure();
211
- });
212
- observer.observe(container);
213
- containerResizeObserver = observer;
214
- }
215
- /**
216
- * Puts the theme's stylesheet where the document will read it. An element in the head rather than
217
- * a constructed sheet in `adoptedStyleSheets`, for two reasons: adopted sheets are ordered after
218
- * every sheet the document loaded, so one would give the theme a cascade position it does not have
219
- * when a consumer writes the element itself, and an element is findable, which is how a second
220
- * document is handed the same theme.
221
- *
222
- * Findable is why the element is resolved by id before one is created. A second renderer in the
223
- * same document writes into the element that is already there rather than adding a rival under the
224
- * same id, which would be invalid and would leave `getElementById` answering with whichever of the
225
- * two came first. Only the element this renderer created is remembered, and only that one is taken
226
- * away again: an adopted element belongs to whoever put it in the document.
227
- *
228
- * Rewriting a `<style>` with the text it already holds is not free. The sheet is re-parsed, so
229
- * every face the theme imports is re-resolved and whatever is waiting on the font event that
230
- * follows re-arms. This extension reaches a theme twice per edit, so that is the ordinary case.
231
- */
232
- function adoptThemeStyleSheet(css) {
233
- const existingElement = createdThemeStyleElement ?? rendererDocument.getElementById(CUSTOM_THEME_STYLE_ID);
234
- if (existingElement !== null) {
235
- if (existingElement.textContent !== css)
236
- existingElement.textContent = css;
237
- return;
238
- }
239
- const styleElement = rendererDocument.createElement("style");
240
- styleElement.id = CUSTOM_THEME_STYLE_ID;
241
- // Filled before it is in the document, so the first theme is parsed once rather than once empty
242
- // and once full.
243
- styleElement.textContent = css;
244
- rendererDocument.head.appendChild(styleElement);
245
- createdThemeStyleElement = styleElement;
246
- }
247
- const remeasureForViewport = () => measure();
248
- rendererWindow.addEventListener("resize", remeasureForViewport);
249
- // Lines measured before the theme's faces have loaded are measured at the fallback face's
250
- // metrics, which leaves every scroll target a little off for the rest of the song.
251
- //
252
- // The catch is what makes this measurement reportable. Every other door into `measure` is a call
253
- // the consumer made or a platform callback it registered, so a throw comes back where it can be
254
- // seen; this one is a promise nobody is holding, and without the catch a throw inside it is an
255
- // unhandled rejection with no view attached to it.
256
- void rendererDocument.fonts.ready
257
- .then(() => {
258
- if (isDestroyed)
259
- return;
260
- measure();
261
- })
262
- .catch(error => host.log(FONT_MEASURE_LOG, error));
263
- // Destruction is final, and every entry point below says so by doing nothing. Silently, because
264
- // the frame a consumer already queued arriving one tick after it tore the view down is the normal
265
- // case rather than a mistake, and a throw there turns an orderly shutdown into an error report.
266
- // The ones that answer something answer what an emptied view answers.
267
- return {
268
- setLyrics(lyrics, options) {
269
- // The one entry point whose silence hides a real mistake: a renderer that was destroyed
270
- // before it ever had a mount would otherwise swallow the throw below and look orderly.
271
- if (isDestroyed) {
272
- host.log(DESTROYED_SET_LYRICS_LOG);
273
- return;
274
- }
275
- const nextMount = options?.mount ?? mount;
276
- if (!nextMount) {
277
- throw new Error("A lyrics renderer needs a mount: give one to createLyricsRenderer or to setLyrics");
278
- }
279
- const viewOptions = {
280
- language: options?.language,
281
- loaderVisible: options?.loaderVisible ?? false,
282
- noLyrics: options?.noLyrics ?? false,
283
- songwriters: options?.songwriters,
284
- songKey: options?.songKey,
285
- };
286
- // Lyrics for the song already on screen are swapped in, so whatever the two share stays exactly
287
- // as it was. Read before the swap: the scroll is where the reader was.
288
- const scrollTopBefore = host.getScrollElement()?.scrollTop ?? 0;
289
- const swapped = swapLyricsView(engine, nextMount, lyrics, viewOptions);
290
- if (swapped === null) {
291
- // Before the mount moves, so a second song built somewhere else takes the first one's
292
- // container with it rather than orphaning it in the mount it was built in.
293
- clearBuiltView();
294
- mount = nextMount;
295
- buildLyricsView(engine, nextMount, lyrics, viewOptions);
296
- }
297
- syncImagePaint();
298
- currentLyrics = lyrics;
299
- currentLanguage = normalizeLanguage(options?.language);
300
- measure();
301
- if (swapped !== null) {
302
- settleSwappedLines(engine, swapped, scrollTopBefore);
303
- }
304
- else if (engine.lyricsContainer) {
305
- observeContainer(engine.lyricsContainer);
306
- }
307
- },
308
- setLanguage(language) {
309
- const normalized = normalizeLanguage(language);
310
- if (isDestroyed || currentLyrics.length === 0 || normalized === currentLanguage)
311
- return;
312
- currentLanguage = normalized;
313
- const languages = resolveLyricLanguages(currentLyrics, normalized);
314
- getRenderedLines(engine).forEach((line, index) => applyLyricLanguage(line.lyricElement, languages[index]));
315
- measure();
316
- },
317
- setTheme(css) {
318
- if (isDestroyed)
319
- return false;
320
- // Settings first, so a caller acting on the answer is acting on a module that already holds
321
- // the theme it is answering about.
322
- const needsLyricRebuild = setThemeSettings(parseThemeConfig(css));
323
- adoptThemeStyleSheet(css);
324
- syncImagePaint();
325
- // Everything the engine resolved off the document was resolved against the theme that just
326
- // went away.
327
- clearEngineStyleCaches(engine);
328
- // The target scroll position is one of the settings a theme carries, and the scroll padding is
329
- // sized against it, so a theme that moves the target moves the layout even when no rule in it
330
- // does.
331
- measure();
332
- return needsLyricRebuild;
333
- },
334
- tick(currentTimeS, options) {
335
- if (isDestroyed)
336
- return "lyrics-missing";
337
- return tickView(engine, currentTimeS, resolveTickOptions(options));
338
- },
339
- relayout(measureLines = true) {
340
- if (isDestroyed)
341
- return;
342
- measure(measureLines);
343
- },
344
- clear() {
345
- if (isDestroyed)
346
- return;
347
- clearBuiltView();
348
- },
349
- destroy() {
350
- if (isDestroyed)
351
- return;
352
- isDestroyed = true;
353
- clearBuiltView();
354
- // The theme outlives a song, so only this takes it away, and only the element this renderer
355
- // created: leaving that one behind would leave a document nothing renders into carrying a
356
- // stylesheet for lyrics, while taking away an adopted one would strip the renderer that owns
357
- // it. Nothing was adopted in the one renderer per document this module supports.
358
- createdThemeStyleElement?.remove();
359
- createdThemeStyleElement = null;
360
- rendererWindow.removeEventListener("resize", remeasureForViewport);
361
- for (const query of imageMediaQueries)
362
- query.removeEventListener("change", refreshImagePaint);
363
- imageMediaQueries = [];
364
- engine.destroy();
365
- },
366
- noteUserScroll() {
367
- if (isDestroyed)
368
- return;
369
- noteEngineUserScroll(engine, hasUnsyncedLyrics(engine));
370
- },
371
- noteVisibilityChange() {
372
- if (isDestroyed)
373
- return;
374
- noteEngineVisibilityChange(engine);
375
- },
376
- resumeAutoscroll() {
377
- if (isDestroyed)
378
- return;
379
- resetScrollResume(engine);
380
- },
381
- clearOnScreenLyrics() {
382
- if (isDestroyed)
383
- return false;
384
- return clearEngineOnScreenLyrics(engine);
385
- },
386
- scheduleLyricPositionUpdate(isTicking, retick) {
387
- if (isDestroyed)
388
- return;
389
- // The caller's answer is one term rather than the whole of it. This is the measuring door that
390
- // fires most, once per streamed translation and romanization, and it is reachable in exactly
391
- // the state the guard exists for: the view ticks on while the page holds it off the screen.
392
- scheduleEngineLyricPositionUpdate(engine, () => isTicking() && areLinesMeasurable(getRenderedLines(engine)), retick);
393
- },
394
- retickFromPlaybackClock(buildOptions) {
395
- if (isDestroyed)
396
- return "lyrics-missing";
397
- return retickEngineFromPlaybackClock(engine, buildOptions);
398
- },
399
- // All three answer for an emptied view. `container` and `lines` are the state clearing drops, so
400
- // they answer that way already; `syncType` is derived from lyrics that are gone and nothing
401
- // resets it, so the container is the term that says they are still there.
402
- get container() {
403
- return engine.lyricsContainer;
404
- },
405
- get lines() {
406
- return getRenderedLines(engine);
407
- },
408
- get syncType() {
409
- return engine.lyricsContainer === null ? "none" : getRenderedSyncType(engine);
410
- },
411
- };
412
- }
package/dist/seek.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare function getSeekTimeFromClick(event: MouseEvent, lyricElement: HTMLElement): number | null;