@braccato/core 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Better Lyrics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,128 @@
1
+ import { CSSResult } from 'lit';
2
+ import { LitElement } from 'lit';
3
+ import { TemplateResult } from 'lit';
4
+
5
+ export declare class BraccatoElement extends LitElement {
6
+ static styles: CSSResult[];
7
+ lyrics: Lyric[];
8
+ currentTime: number;
9
+ playing: boolean;
10
+ scrollMode: "internal" | "external";
11
+ scrollContainer: HTMLElement | null;
12
+ dir: "auto" | "ltr" | "rtl";
13
+ longWordThreshold: number;
14
+ lineSyncedDelay: number;
15
+ disableRichsync: boolean;
16
+ debug: boolean;
17
+ source: string | null;
18
+ src: string | null;
19
+ onLineActive?: (line: Lyric, index: number) => void;
20
+ onLineInactive?: (line: Lyric, index: number) => void;
21
+ private _lyricsData;
22
+ private _animState;
23
+ private _rafId;
24
+ private _lastLyrics;
25
+ private _resizeObserver;
26
+ private _mediaElement;
27
+ private _lastSrc;
28
+ private _srcAbortController;
29
+ connectedCallback(): void;
30
+ disconnectedCallback(): void;
31
+ updated(changed: Map<string, unknown>): void;
32
+ render(): TemplateResult<1>;
33
+ private _log;
34
+ private _injectLyrics;
35
+ private _recalculatePositions;
36
+ private _startLoop;
37
+ private _stopLoop;
38
+ private _tickCount;
39
+ private _tick;
40
+ private _getScrollContainer;
41
+ private _onScroll;
42
+ private _handleLineClick;
43
+ private _resolveMediaElement;
44
+ private _fetchLyricsFromSrc;
45
+ private _emitError;
46
+ resumeAutoscroll(): void;
47
+ recalculatePositions(): void;
48
+ }
49
+
50
+ export declare interface BraccatoEventMap {
51
+ "braccato:line-click": CustomEvent<{
52
+ time: number;
53
+ lineIndex: number;
54
+ }>;
55
+ "braccato:word-click": CustomEvent<{
56
+ time: number;
57
+ lineIndex: number;
58
+ wordIndex: number;
59
+ }>;
60
+ "braccato:lyrics-loaded": CustomEvent<{
61
+ syncType: SyncType;
62
+ lineCount: number;
63
+ }>;
64
+ "braccato:scroll-state": CustomEvent<{
65
+ userScrolling: boolean;
66
+ }>;
67
+ "braccato:error": CustomEvent<{
68
+ error: Error;
69
+ }>;
70
+ }
71
+
72
+ export declare interface LineData {
73
+ parts: PartData[];
74
+ isScrolled: boolean;
75
+ isAnimationPlayStatePlaying: boolean;
76
+ accumulatedOffsetMs: number;
77
+ isAnimating: boolean;
78
+ lastAnimSetupAt: number;
79
+ isSelected: boolean;
80
+ height: number;
81
+ position: number;
82
+ time: number;
83
+ duration: number;
84
+ element: HTMLElement;
85
+ animationStartTimeMs: number;
86
+ }
87
+
88
+ export declare interface Lyric {
89
+ startTimeMs: number;
90
+ words: string;
91
+ durationMs: number;
92
+ key?: string;
93
+ parts?: LyricPart[];
94
+ agent?: string;
95
+ translation?: {
96
+ text: string;
97
+ lang: string;
98
+ };
99
+ romanization?: string;
100
+ timedRomanization?: LyricPart[];
101
+ isInstrumental?: boolean;
102
+ }
103
+
104
+ export declare interface LyricPart {
105
+ startTimeMs: number;
106
+ words: string;
107
+ durationMs: number;
108
+ isBackground?: boolean;
109
+ }
110
+
111
+ export declare interface LyricsData {
112
+ lines: LineData[];
113
+ syncType: SyncType;
114
+ width: number;
115
+ height: number;
116
+ container: HTMLElement;
117
+ }
118
+
119
+ export declare interface PartData {
120
+ time: number;
121
+ duration: number;
122
+ element: HTMLElement;
123
+ animationStartTimeMs: number;
124
+ }
125
+
126
+ export declare type SyncType = "richsync" | "synced" | "none";
127
+
128
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,872 @@
1
+ import { LitElement as st, unsafeCSS as J, html as ot } from "lit";
2
+ import { property as D } from "lit/decorators.js";
3
+ function F(t) {
4
+ if (!t) return 0;
5
+ if (typeof t == "number") return t;
6
+ const e = t.match(/^([\d.]+)(h|m|s|ms)$/);
7
+ if (e) {
8
+ const i = Number.parseFloat(e[1]), o = e[2];
9
+ if (o === "h") return Math.round(i * 36e5);
10
+ if (o === "m") return Math.round(i * 6e4);
11
+ if (o === "s") return Math.round(i * 1e3);
12
+ if (o === "ms") return Math.round(i);
13
+ }
14
+ const a = t.split(":").map((i) => i.replace(/[^0-9.]/g, ""));
15
+ let r = 0;
16
+ try {
17
+ return a.length === 1 ? r = Number.parseFloat(a[0]) * 1e3 : a.length === 2 ? r = Number.parseInt(a[0], 10) * 6e4 + Number.parseFloat(a[1]) * 1e3 : a.length === 3 && (r = Number.parseInt(a[0], 10) * 36e5 + Number.parseInt(a[1], 10) * 6e4 + Number.parseFloat(a[2]) * 1e3), Math.round(r);
18
+ } catch {
19
+ return 0;
20
+ }
21
+ }
22
+ function k(t, e) {
23
+ const a = t.getAttribute(e);
24
+ if (a !== null) return a;
25
+ for (const r of t.attributes)
26
+ if (r.localName === e) return r.value;
27
+ return null;
28
+ }
29
+ function G(t) {
30
+ const e = {
31
+ text: "",
32
+ begin: k(t, "begin") ? F(k(t, "begin")) : void 0,
33
+ end: k(t, "end") ? F(k(t, "end")) : void 0,
34
+ role: k(t, "role") ?? void 0,
35
+ children: []
36
+ };
37
+ for (const a of t.childNodes)
38
+ if (a.nodeType === 3) {
39
+ const r = a.textContent ?? "";
40
+ e.text += r, e.children.push({ text: r, children: [] });
41
+ } else a.nodeType === 1 && e.children.push(G(a));
42
+ return e;
43
+ }
44
+ function $(t, e, a = !1) {
45
+ let r = "";
46
+ const i = [];
47
+ let o = !1;
48
+ for (const n of t) {
49
+ const s = a || n.role === "x-bg";
50
+ if (n.children.length > 0)
51
+ if (s && !a) {
52
+ const c = $(n.children, e, !0);
53
+ r += c.text, i.push(...c.parts), c.isWordSynced && (o = !0);
54
+ } else if (n.begin !== void 0 && n.end !== void 0) {
55
+ const c = n.children.map((d) => d.text).join("") || n.text;
56
+ i.push({
57
+ startTimeMs: n.begin,
58
+ durationMs: n.end - n.begin,
59
+ words: c,
60
+ isBackground: s || void 0
61
+ }), r += c, o = !0;
62
+ } else {
63
+ const c = $(n.children, e, s);
64
+ r += c.text, i.push(...c.parts), c.isWordSynced && (o = !0);
65
+ }
66
+ else if (n.text)
67
+ if (r += n.text, n.begin !== void 0 && n.end !== void 0)
68
+ i.push({
69
+ startTimeMs: n.begin,
70
+ durationMs: n.end - n.begin,
71
+ words: n.text,
72
+ isBackground: s || void 0
73
+ }), o = !0;
74
+ else {
75
+ const c = i[i.length - 1];
76
+ i.push({
77
+ startTimeMs: c ? c.startTimeMs + c.durationMs : e,
78
+ durationMs: 0,
79
+ words: n.text,
80
+ isBackground: s || void 0
81
+ });
82
+ }
83
+ }
84
+ return o ? { parts: i, text: r, isWordSynced: o } : { parts: [], text: r, isWordSynced: !1 };
85
+ }
86
+ function ct(t, e, a) {
87
+ if (t.length === 0) return t;
88
+ const r = [], i = (s, c) => ({
89
+ startTimeMs: s,
90
+ durationMs: c,
91
+ words: "",
92
+ parts: [],
93
+ isInstrumental: !0
94
+ });
95
+ t[0].startTimeMs > a && r.push(i(0, t[0].startTimeMs));
96
+ for (let s = 0; s < t.length; s++)
97
+ if (r.push(t[s]), s < t.length - 1) {
98
+ const c = t[s].startTimeMs + t[s].durationMs, d = t[s + 1].startTimeMs - c;
99
+ d > a && r.push(i(c, d));
100
+ }
101
+ const o = t[t.length - 1], n = o.startTimeMs + o.durationMs;
102
+ return e - n > a && r.push(i(n, e - n)), r;
103
+ }
104
+ function lt(t, e = {}) {
105
+ const a = t.replace(/\\"/g, '"'), r = new DOMParser().parseFromString(a, "text/xml"), i = r.querySelector("tt"), o = (i ? k(i, "lang") : null) ?? void 0, n = r.querySelector("body");
106
+ if (!n) return { lyrics: [], isWordSynced: !1, language: o };
107
+ const s = n.getAttribute("dur"), c = s ? F(s) : 0, d = n.querySelectorAll("p"), p = /* @__PURE__ */ new Map();
108
+ let f = !1;
109
+ const m = /* @__PURE__ */ new Map(), h = [
110
+ ...r.querySelectorAll("agent"),
111
+ ...r.getElementsByTagNameNS("http://www.w3.org/ns/ttml#metadata", "agent")
112
+ ];
113
+ let x = 0;
114
+ for (const w of h) {
115
+ const u = k(w, "id"), _ = k(w, "type");
116
+ u && (m.has(u) || (_ === "person" || _ === "character" ? (x++, m.set(u, `v${x}`)) : m.set(u, "v1000")));
117
+ }
118
+ for (const w of d) {
119
+ const u = F(k(w, "begin") ?? void 0), _ = F(k(w, "end") ?? void 0), E = k(w, "key") ?? String(p.size), A = k(w, "agent") ?? void 0, y = A ? m.get(A) ?? A : void 0, S = Array.from(w.childNodes).filter((b) => b.nodeType === 1 || b.nodeType === 3).map(
120
+ (b) => b.nodeType === 1 ? G(b) : { text: b.textContent ?? "", children: [] }
121
+ ), l = $(S, u);
122
+ l.isWordSynced && (f = !0), p.set(E, {
123
+ agent: y,
124
+ durationMs: _ - u,
125
+ parts: l.parts,
126
+ startTimeMs: u,
127
+ words: l.text,
128
+ key: E
129
+ });
130
+ }
131
+ const g = r.querySelectorAll("translations");
132
+ for (const w of g) {
133
+ const u = w.getAttribute("lang");
134
+ if (!u) continue;
135
+ const _ = w.querySelectorAll("translation");
136
+ for (const E of _) {
137
+ const A = E.getAttribute("for"), y = E.querySelector("text"), S = y == null ? void 0 : y.textContent;
138
+ if (A && S) {
139
+ const l = p.get(A);
140
+ l && (l.translation = { text: S, lang: u });
141
+ }
142
+ }
143
+ }
144
+ const v = r.querySelectorAll("transliterations");
145
+ for (const w of v) {
146
+ const u = w.querySelectorAll("transliteration");
147
+ for (const _ of u) {
148
+ const E = _.getAttribute("for");
149
+ if (!E) continue;
150
+ const A = p.get(E);
151
+ if (!A) continue;
152
+ const y = _.querySelectorAll("text");
153
+ let S = "";
154
+ const l = [];
155
+ for (const b of y) {
156
+ const N = Array.from(b.childNodes).filter((T) => T.nodeType === 1 || T.nodeType === 3).map(
157
+ (T) => T.nodeType === 1 ? G(T) : { text: T.textContent ?? "", children: [] }
158
+ ), M = $(N, A.startTimeMs);
159
+ S += M.text, l.push(...M.parts);
160
+ }
161
+ A.romanization = S, l.length > 0 && (A.timedRomanization = l);
162
+ }
163
+ }
164
+ let P = Array.from(p.values());
165
+ const L = e.instrumentalGapMs ?? 5e3;
166
+ return c > 0 && (P = ct(P, c, L)), { lyrics: P, isWordSynced: f, language: o };
167
+ }
168
+ const dt = {
169
+ detect(t) {
170
+ return t.includes("<tt") && t.includes("</tt>");
171
+ },
172
+ parse(t, e = 0) {
173
+ return lt(t).lyrics;
174
+ }
175
+ }, ut = ["ti", "ar", "al", "au", "lr", "length", "by", "offset", "re", "tool", "ve", "#"];
176
+ function K(t) {
177
+ if (!t) return 0;
178
+ if (typeof t == "number") return t;
179
+ const e = t.split(":");
180
+ let a = 0;
181
+ try {
182
+ if (e.length === 1)
183
+ a = Number.parseFloat(e[0]) * 1e3;
184
+ else if (e.length === 2) {
185
+ const r = Number.parseInt(e[0], 10), i = Number.parseFloat(e[1]);
186
+ a = r * 60 * 1e3 + i * 1e3;
187
+ } else if (e.length === 3) {
188
+ const r = Number.parseInt(e[0], 10), i = Number.parseInt(e[1], 10), o = Number.parseFloat(e[2]);
189
+ a = r * 3600 * 1e3 + i * 60 * 1e3 + o * 1e3;
190
+ }
191
+ return Math.round(a);
192
+ } catch {
193
+ return 0;
194
+ }
195
+ }
196
+ function mt(t, e) {
197
+ var a;
198
+ const r = t.split(`
199
+ `), i = [], o = {};
200
+ for (const n of r) {
201
+ const s = n.trim(), c = s.match(/^\[(\w+):(.*)\]$/);
202
+ if (c && ut.includes(c[1])) {
203
+ o[c[1]] = c[2];
204
+ continue;
205
+ }
206
+ const d = /\[(\d+:\d+\.\d+)\]/g, p = /<(\d+:\d+\.\d+)>/g, f = [];
207
+ for (const L of s.matchAll(d))
208
+ f.push(K(L[1]));
209
+ if (f.length === 0) continue;
210
+ const m = s.replace(d, "").trim(), h = [];
211
+ let x = null, g = "";
212
+ m.split(p).forEach((L, w) => {
213
+ if (w % 2 === 0) {
214
+ let u = L;
215
+ u.length > 0 && u[0] === " " && (u = u.substring(1)), u.length > 0 && u[u.length - 1] === " " && (u = u.substring(0, u.length - 1)), g += u, h.length > 0 && h[h.length - 1].startTimeMs && (h[h.length - 1].words += u);
216
+ } else {
217
+ const u = K(L);
218
+ x !== null && h.length > 0 && (h[h.length - 1].durationMs = u - x), h.push({ startTimeMs: u, words: "", durationMs: 0 }), x = u;
219
+ }
220
+ });
221
+ const v = Math.min(...f), P = Math.max(...f) - v;
222
+ i.push({
223
+ startTimeMs: v,
224
+ words: g.trim(),
225
+ durationMs: P,
226
+ parts: h.length > 0 ? h : void 0
227
+ });
228
+ }
229
+ for (let n = 0; n < i.length; n++) {
230
+ const s = i[n];
231
+ if (n + 1 < i.length) {
232
+ const c = i[n + 1];
233
+ if (s.durationMs === 0 && (s.durationMs = Math.max(c.startTimeMs - s.startTimeMs, 0)), s.parts && s.parts.length > 0) {
234
+ let d = c.startTimeMs;
235
+ for (const f of s.parts)
236
+ d = Math.max(d, f.startTimeMs);
237
+ const p = s.parts[s.parts.length - 1];
238
+ p.durationMs = Math.max(c.startTimeMs - p.startTimeMs, 0), s.durationMs = Math.max(d - s.startTimeMs, 0);
239
+ }
240
+ } else if (s.durationMs === 0 && (s.durationMs = e - s.startTimeMs), s.parts && s.parts.length > 0) {
241
+ const c = s.parts[s.parts.length - 1];
242
+ c.durationMs = e - c.startTimeMs;
243
+ }
244
+ }
245
+ if (o.offset) {
246
+ let n = Number(o.offset);
247
+ Number.isNaN(n) && (n = 0), n = n * 1e3;
248
+ for (const s of i)
249
+ s.startTimeMs -= n, (a = s.parts) == null || a.forEach((c) => {
250
+ c.startTimeMs -= n;
251
+ });
252
+ }
253
+ return i;
254
+ }
255
+ function ft(t) {
256
+ for (const r of t)
257
+ if (r.parts)
258
+ for (let i = 1; i < r.parts.length; i++) {
259
+ const o = r.parts[i], n = r.parts[i - 1];
260
+ if (o.words === " " && n.words !== " ") {
261
+ const s = o.durationMs - n.durationMs;
262
+ if (Math.abs(s) <= 15 || o.durationMs <= 100) {
263
+ const c = o.durationMs;
264
+ n.durationMs += c, o.durationMs -= c, o.startTimeMs += c;
265
+ }
266
+ }
267
+ }
268
+ let e = 0, a = 0;
269
+ for (const r of t)
270
+ if (!(!r.parts || r.parts.length === 0))
271
+ for (let i = 0; i < r.parts.length - 2; i++) {
272
+ const o = r.parts[i];
273
+ o.words !== " " && (o.durationMs <= 100 && e++, a++);
274
+ }
275
+ if (a > 0 && e / a > 0.5)
276
+ for (let r = 0; r < t.length; r++) {
277
+ const i = t[r];
278
+ if (!(!i.parts || i.parts.length === 0))
279
+ for (let o = 0; o < i.parts.length; o++) {
280
+ const n = i.parts[o];
281
+ if (n.words !== " " && n.durationMs <= 400) {
282
+ let s = null;
283
+ o + 1 < i.parts.length ? s = i.parts[o + 1] : r + 1 < t.length && t[r + 1].parts && t[r + 1].parts.length > 0 && (s = t[r + 1].parts[0]), s === null ? n.durationMs = 300 : s.words === " " ? (n.durationMs += s.durationMs, s.startTimeMs += s.durationMs, s.durationMs = 0) : n.durationMs = s.startTimeMs - n.startTimeMs;
284
+ }
285
+ }
286
+ }
287
+ }
288
+ const pt = {
289
+ detect(t) {
290
+ return /\[\d+:\d+\.\d+\]/.test(t);
291
+ },
292
+ parse(t, e = 0) {
293
+ const a = mt(t, e);
294
+ return ft(a), a;
295
+ }
296
+ };
297
+ function Q(t) {
298
+ const e = t.trim().match(/^(\d+):(\d+):(\d+)[,.](\d+)$/);
299
+ if (!e) return 0;
300
+ const a = Number.parseInt(e[1], 10), r = Number.parseInt(e[2], 10), i = Number.parseInt(e[3], 10), o = Number.parseInt(e[4].padEnd(3, "0").slice(0, 3), 10);
301
+ return a * 36e5 + r * 6e4 + i * 1e3 + o;
302
+ }
303
+ const ht = {
304
+ detect(t) {
305
+ return /\d+\r?\n\d{2}:\d{2}:\d{2}[,.]\d+ --> \d{2}:\d{2}:\d{2}[,.]\d+/.test(t);
306
+ },
307
+ parse(t, e = 0) {
308
+ const a = t.trim().split(/\r?\n\r?\n/), r = [];
309
+ for (const i of a) {
310
+ const o = i.split(/\r?\n/);
311
+ if (o.length < 2) continue;
312
+ const n = o.find((h) => h.includes("-->"));
313
+ if (!n) continue;
314
+ const [s, c] = n.split("-->").map((h) => h.trim()), d = Q(s), p = Q(c), f = o.indexOf(n), m = o.slice(f + 1).join(`
315
+ `).replace(/<[^>]+>/g, "").trim();
316
+ m && r.push({
317
+ startTimeMs: d,
318
+ words: m,
319
+ durationMs: p - d
320
+ });
321
+ }
322
+ return r;
323
+ }
324
+ }, nt = {
325
+ detect(t) {
326
+ return !0;
327
+ },
328
+ parse(t, e = 0) {
329
+ return t.split(`
330
+ `).map((a) => ({
331
+ startTimeMs: 0,
332
+ words: a,
333
+ durationMs: 0
334
+ }));
335
+ }
336
+ }, bt = {
337
+ detect(t) {
338
+ return /\[\d+,\d+\]/.test(t) && /\(\d+,\d+\)/.test(t);
339
+ },
340
+ parse(t, e = 0) {
341
+ const a = t.split(`
342
+ `), r = [];
343
+ for (const i of a) {
344
+ const o = i.trim().match(/^\[(\d+),(\d+)\](.*)$/);
345
+ if (!o) continue;
346
+ const n = Number.parseInt(o[1], 10), s = Number.parseInt(o[2], 10), c = o[3], d = [];
347
+ let p = "";
348
+ const f = /([^(]*)\((\d+),(\d+)\)/g;
349
+ for (const m of c.matchAll(f)) {
350
+ const h = m[1], x = Number.parseInt(m[2], 10), g = Number.parseInt(m[3], 10);
351
+ p += h, d.push({ startTimeMs: x, words: h, durationMs: g });
352
+ }
353
+ r.push({
354
+ startTimeMs: n,
355
+ words: p,
356
+ durationMs: s,
357
+ parts: d.length > 0 ? d : void 0
358
+ });
359
+ }
360
+ return r;
361
+ }
362
+ }, gt = [dt, pt, ht, bt, nt];
363
+ function yt(t) {
364
+ for (const e of gt)
365
+ if (e.detect(t)) return e;
366
+ return nt;
367
+ }
368
+ const St = 25e3;
369
+ function vt() {
370
+ return {
371
+ skipScrolls: 0,
372
+ skipScrollsDecayTimes: [],
373
+ scrollResumeTime: 0,
374
+ scrollPos: 0,
375
+ nextScrollAllowedTime: 0,
376
+ wasUserScrolling: !1,
377
+ doneFirstInstantScroll: !1,
378
+ queuedScroll: !1
379
+ };
380
+ }
381
+ function Tt(t) {
382
+ t.skipScrollsDecayTimes = [], t.doneFirstInstantScroll = !1, t.queuedScroll = !1;
383
+ }
384
+ function X(t) {
385
+ t.wasUserScrolling = !0, t.scrollResumeTime = Date.now() + St;
386
+ }
387
+ function tt(t) {
388
+ t.scrollResumeTime = 0;
389
+ }
390
+ function _t(t) {
391
+ return t.scrollResumeTime > Date.now();
392
+ }
393
+ function wt(t, e) {
394
+ let a = 0;
395
+ for (; a < t.skipScrollsDecayTimes.length && !(t.skipScrollsDecayTimes[a] > e); a++)
396
+ ;
397
+ t.skipScrollsDecayTimes = t.skipScrollsDecayTimes.slice(a), t.skipScrolls -= a, t.skipScrolls < 1 && (t.skipScrolls = 1);
398
+ }
399
+ const U = "braccato--animating", j = "braccato--pre-animating", W = "braccato--paused", et = "braccato--active", Mt = "braccato--user-scrolling", xt = 0.5, Ct = 0.5, Et = 0.62, At = 0.37, Lt = 150, Y = /* @__PURE__ */ new Map();
400
+ function kt(t) {
401
+ return t ? t.endsWith("ms") ? Number.parseFloat(t.slice(0, -2)) : t.endsWith("s") ? Number.parseFloat(t.slice(0, -1)) * 1e3 : 0 : 0;
402
+ }
403
+ function q(t, e) {
404
+ let a = Y.get(e);
405
+ return a === void 0 && (a = kt(getComputedStyle(t).getPropertyValue(e)), Y.set(e, a)), a;
406
+ }
407
+ function rt(t) {
408
+ t.offsetHeight;
409
+ }
410
+ function Dt() {
411
+ return {
412
+ scroll: vt(),
413
+ selectedElementIndex: 0,
414
+ lastTime: 0,
415
+ lastPlayState: !1,
416
+ lastEventCreationTime: 0,
417
+ lastActiveElements: []
418
+ };
419
+ }
420
+ function It(t) {
421
+ Tt(t.scroll), t.lastActiveElements = [], Y.clear();
422
+ }
423
+ function Nt(t, e) {
424
+ const a = Date.now();
425
+ let { currentTime: r, isPlaying: i, smoothScroll: o } = e;
426
+ const {
427
+ eventCreationTime: n,
428
+ lyricsData: s,
429
+ scrollContainer: c,
430
+ scrollPosRatio: d = At,
431
+ endingThreshold: p = Ct,
432
+ earlyScrollConsider: f = Et,
433
+ queueScrollMs: m = Lt
434
+ } = e;
435
+ if (r === 0 && !i) return;
436
+ const h = Math.abs(r - t.lastTime - (n - t.lastEventCreationTime) / 1e3) > xt;
437
+ t.lastTime = r, t.lastPlayState = i, t.lastEventCreationTime = n;
438
+ const x = i ? a - n : 0;
439
+ r += x / 1e3;
440
+ const { lines: g, container: v, syncType: P } = s;
441
+ P === "richsync" ? r += q(v, "--braccato-richsync-timing-offset") / 1e3 : r += q(v, "--braccato-timing-offset") / 1e3;
442
+ const L = r + q(v, "--braccato-scroll-timing-offset") / 1e3, w = c.getBoundingClientRect().height;
443
+ let u = c.scrollTop;
444
+ const _ = [], E = [];
445
+ let A = h;
446
+ for (let S = 0; S < g.length; S++) {
447
+ const l = g[S], b = l.time, N = S + 1 < g.length ? g[S + 1].time : Number.POSITIVE_INFINITY;
448
+ L >= b - f && (L < N || L < b + l.duration) ? (_.push(l), !t.lastActiveElements.includes(l) && L >= b && (A = !0), t.selectedElementIndex = S, l.isScrolled || (l.element.classList.add(et), l.isScrolled = !0)) : l.isScrolled && (l.element.classList.remove(et), l.isScrolled = !1);
449
+ const M = i ? 2 : 0, T = Math.max(N, b + l.duration + 0.05);
450
+ if (r + M >= b && r < T) {
451
+ l.isSelected = !0;
452
+ const z = r - b, R = (a - l.animationStartTimeMs) / 1e3 - z;
453
+ if (l.accumulatedOffsetMs = l.accumulatedOffsetMs / 1.08, l.accumulatedOffsetMs += R * 1e3 * 0.4, l.isAnimating && Math.abs(l.accumulatedOffsetMs) > 100 && i && (l.isAnimating = !1), i !== l.isAnimationPlayStatePlaying) {
454
+ l.isAnimationPlayStatePlaying = i;
455
+ const Z = [l, ...l.parts];
456
+ if (i) {
457
+ for (const O of Z)
458
+ O.element.classList.remove(W);
459
+ l.isAnimating = !1;
460
+ } else
461
+ for (const O of Z)
462
+ O.animationStartTimeMs > a ? (O.element.classList.remove(U), O.element.classList.remove(j)) : O.element.classList.add(W);
463
+ }
464
+ l.isAnimating || E.push(l);
465
+ } else if (l.isSelected) {
466
+ const z = [l, ...l.parts];
467
+ for (const R of z)
468
+ R.element.style.setProperty("--braccato-swipe-delay", ""), R.element.style.setProperty("--braccato-anim-delay", ""), R.element.classList.remove(U), R.element.classList.remove(j), R.element.classList.remove(W), R.animationStartTimeMs = Number.POSITIVE_INFINITY;
469
+ l.isSelected = !1, l.isAnimating = !1;
470
+ }
471
+ }
472
+ if (E.length > 0) {
473
+ for (const S of E) {
474
+ const l = [S, ...S.parts];
475
+ for (const b of l) {
476
+ const N = r - b.time;
477
+ b.element.classList.remove(U), b.element.classList.remove(W), b.element.style.setProperty("--braccato-swipe-delay", `${-N - b.duration * 0.1}s`), b.element.style.setProperty("--braccato-anim-delay", `${-N}s`), b.element.classList.add(j);
478
+ }
479
+ }
480
+ rt(E[0].element);
481
+ for (const S of E) {
482
+ const l = [S, ...S.parts];
483
+ for (const b of l) {
484
+ const N = r - b.time;
485
+ b.element.classList.add(U), b.animationStartTimeMs = a - N * 1e3;
486
+ }
487
+ S.isAnimating = !0, S.lastAnimSetupAt = a, S.isAnimationPlayStatePlaying = !0, S.accumulatedOffsetMs = 0;
488
+ }
489
+ }
490
+ const y = t.scroll;
491
+ if (y.scrollResumeTime < a || y.scrollPos === -1) {
492
+ _.length === 0 && _.push(g[0]), t.lastActiveElements = _.filter((T) => L >= T.time);
493
+ const S = w * d, l = _[_.length - 1], b = _.filter((T, z) => L < T.time + T.duration - p || z === _.length - 1).map((T) => T.position + T.height / 2);
494
+ let M = b.reduce((T, z) => T + z, 0) / b.length - S;
495
+ if (M = Math.min(M, _[0].position), M = Math.max(M, l.position - w + l.height), M = Math.min(M, l.position), M = Math.max(0, M), u === 0 && !y.doneFirstInstantScroll && (o = !1, y.doneFirstInstantScroll = !0, y.nextScrollAllowedTime = 0), y.wasUserScrolling || A || y.queuedScroll)
496
+ if (a > y.nextScrollAllowedTime) {
497
+ if (y.queuedScroll = !1, o && Math.abs(u - M) > 2) {
498
+ v.style.transitionTimingFunction = "", v.style.transitionProperty = "", v.style.transitionDuration = "";
499
+ const T = q(v, "transition-duration");
500
+ v.style.transition = "none", v.style.transform = `translate(0px, ${-(u - M)}px)`, rt(v), v.style.transition = "", v.style.transform = "translate(0px, 0px)", y.nextScrollAllowedTime = T + a + 20;
501
+ }
502
+ u = M, y.scrollPos = u, c.scrollTop = u, y.skipScrolls += 1, y.skipScrollsDecayTimes.push(a + 2e3);
503
+ } else (y.nextScrollAllowedTime - a < m || h) && (y.queuedScroll = !0);
504
+ }
505
+ y.wasUserScrolling && y.scrollResumeTime < a && (v.classList.remove(Mt), y.wasUserScrolling = !1), wt(y, a);
506
+ }
507
+ const Rt = /[\p{Script=Arabic}\p{Script=Hebrew}\p{Script=Syriac}\p{Script=Thaana}]/u;
508
+ function Pt(t) {
509
+ return Rt.test(t);
510
+ }
511
+ const zt = "braccato--line", Ot = "braccato--word", Ft = "braccato--break", B = "braccato-background-lyric", at = "braccato-rtl", Ut = "braccato-zero-dur-animate", Wt = "braccato--romanized", qt = "braccato--translated";
512
+ function H(t, e) {
513
+ const a = document.createElement("span");
514
+ a.classList.add(Ft), a.style.order = String(e), t.appendChild(a);
515
+ }
516
+ function Bt(t, e) {
517
+ const a = /([\s\u200B\u00AD\p{Dash_Punctuation}])/gu;
518
+ let r = [], i = !1;
519
+ const o = () => {
520
+ if (r.length > 0) {
521
+ const n = document.createElement("span");
522
+ for (const s of r) n.appendChild(s);
523
+ i && n.classList.add(B), t.appendChild(n), r = [];
524
+ }
525
+ };
526
+ for (const n of e) {
527
+ const s = i !== n.classList.contains(B), c = !(n.textContent.length === 1 && n.textContent[0] === " ");
528
+ s || r.push(n), (n.textContent.length > 0 && a.test(n.textContent[n.textContent.length - 1]) || s) && o(), s && c && (r.push(n), i = n.classList.contains(B));
529
+ }
530
+ o();
531
+ }
532
+ function it(t, e, a, r) {
533
+ let i = [], o = !0;
534
+ const n = [];
535
+ for (const s of t) {
536
+ const c = Pt(s.words);
537
+ !c && s.words.trim().length > 0 && (o = !1, i.reverse().forEach((f) => n.push(f)), i = []);
538
+ const d = document.createElement("span");
539
+ d.classList.add(Ot), s.durationMs === 0 && d.classList.add(Ut), c && d.classList.add(at);
540
+ const p = {
541
+ time: s.startTimeMs / 1e3,
542
+ duration: s.durationMs / 1e3,
543
+ element: d,
544
+ animationStartTimeMs: Number.POSITIVE_INFINITY
545
+ };
546
+ d.textContent = s.words, d.dataset.time = String(p.time), d.dataset.duration = String(p.duration), d.dataset.content = s.words, d.style.setProperty("--braccato-duration", `${s.durationMs}ms`), s.durationMs > r && (d.dataset.longWord = "true"), s.isBackground && d.classList.add(B), s.words.trim().length === 0 && (d.style.display = "inline"), s.words.trim().length !== 0 && e.parts.push(p), c ? i.push(d) : n.push(d);
547
+ }
548
+ if (o && i.length > 0) {
549
+ a.classList.add(at);
550
+ for (const s of i) n.push(s);
551
+ } else i.length > 0 && i.reverse().forEach((s) => n.push(s));
552
+ Bt(a, n);
553
+ }
554
+ function $t(t, e, a = {}) {
555
+ const { longWordThreshold: r = 1500, lineSyncedAnimationDelay: i = 50, disableRichsync: o = !1 } = a;
556
+ e.replaceChildren();
557
+ let s = t.every((p) => p.startTimeMs === 0) ? "none" : "synced";
558
+ const c = [];
559
+ for (let p = 0; p < t.length; p++) {
560
+ const f = t[p], m = document.createElement("div");
561
+ m.classList.add(zt);
562
+ const h = {
563
+ element: m,
564
+ time: f.startTimeMs / 1e3,
565
+ duration: f.durationMs / 1e3,
566
+ parts: [],
567
+ isScrolled: !1,
568
+ animationStartTimeMs: Number.POSITIVE_INFINITY,
569
+ isAnimationPlayStatePlaying: !1,
570
+ accumulatedOffsetMs: 0,
571
+ isAnimating: !1,
572
+ lastAnimSetupAt: 0,
573
+ isSelected: !1,
574
+ height: -1,
575
+ position: -1
576
+ };
577
+ if (f.isInstrumental) {
578
+ m.dataset.instrumental = "true", m.dataset.time = String(h.time), m.dataset.duration = String(h.duration), m.dataset.lineNumber = String(p), c.push(h), e.appendChild(m);
579
+ continue;
580
+ }
581
+ let x = f.parts ?? [];
582
+ if ((x.length === 0 || o) && (x = f.words.split(" ").map((g, v) => ({
583
+ startTimeMs: f.startTimeMs + v * i,
584
+ words: g.trim().length < 1 ? g : `${g} `,
585
+ durationMs: 0
586
+ }))), x.every((g) => g.durationMs === 0) || (s = "richsync"), it(x, h, m, r), H(m, 1), m.dataset.time = String(h.time), m.dataset.duration = String(h.duration), m.dataset.lineNumber = String(p), m.style.setProperty("--braccato-duration", `${f.durationMs}ms`), f.agent && (m.dataset.agent = f.agent), f.romanization) {
587
+ H(m, 4);
588
+ const g = document.createElement("div");
589
+ g.classList.add(Wt), g.style.order = "5", f.timedRomanization && f.timedRomanization.length > 0 && !o ? it(f.timedRomanization, h, g, r) : g.textContent = `
590
+ ${f.romanization}`, m.appendChild(g);
591
+ }
592
+ if (f.translation) {
593
+ H(m, 6);
594
+ const g = document.createElement("div");
595
+ g.classList.add(qt), g.style.order = "7", g.textContent = `
596
+ ${f.translation.text}`, m.appendChild(g);
597
+ }
598
+ c.push(h), e.appendChild(m);
599
+ }
600
+ e.dataset.sync = s;
601
+ const d = document.createElement("div");
602
+ return d.className = "braccato--spacer", d.style.height = "100px", e.appendChild(d), {
603
+ lines: c,
604
+ syncType: s,
605
+ width: e.clientWidth,
606
+ height: e.clientHeight,
607
+ container: e
608
+ };
609
+ }
610
+ const jt = ":host{display:block;overflow-y:auto;position:relative;container-type:size;scrollbar-width:none}:host::-webkit-scrollbar{display:none}:host(:has(.braccato--user-scrolling)){scrollbar-width:thin;scrollbar-color:rgba(255,255,255,.15) transparent}:host(:has(.braccato--user-scrolling))::-webkit-scrollbar{display:block;width:6px}:host(:has(.braccato--user-scrolling))::-webkit-scrollbar-thumb{background:#ffffff26;border-radius:3px}:host(:has(.braccato--user-scrolling))::-webkit-scrollbar-track{background:transparent}.braccato-container{font-family:var(--braccato-font-family);font-size:var(--braccato-font-size);font-weight:var(--braccato-font-weight);isolation:isolate;line-height:var(--braccato-line-height);position:relative;z-index:1;transition:transform var(--braccato-scroll-duration) var(--braccato-scroll-timing-function) 0s;padding-top:2rem;padding-bottom:0}.braccato-container>div{cursor:pointer;padding:var(--braccato-padding) 0;transform-origin:left center;word-break:break-word;transition:filter calc(var(--braccato-duration) / 3) .4s,opacity calc(var(--braccato-duration) / 2) .166s,transform .166s var(--braccato-anim-delay, 0s)}.braccato-container:has(.braccato--active):not(.braccato--user-scrolling)>div:not(.braccato--active):not(.braccato--active~div){opacity:.33;filter:blur(2.5px)}.braccato-container>div.braccato--active{opacity:1;filter:blur(0px)}.braccato-container>div.braccato--active~div{opacity:.66;filter:blur(0px)}.braccato-container>.braccato--animating{opacity:1!important;filter:blur(0px)!important}.braccato-container>div:hover{opacity:1!important;filter:blur(0px)!important;transform:scale(var(--braccato-hover-scale, 1.01));transition:all .3s ease}.braccato--active{cursor:default}:not(.braccato-background-lyric){order:0}.braccato-background-lyric{order:2}.braccato--line>span>span.braccato-background-lyric{font-size:.75em;font-weight:500}.braccato--line{transform:scale(var(--braccato-scale));transition-property:transform;transition-duration:var(--braccato-scale-transition-duration);transition-timing-function:ease;display:flex;flex-flow:row wrap;align-items:start;align-content:flex-start;padding-left:.25em;padding-right:.25em;box-sizing:border-box}.braccato--line.braccato--animating{transform:scale(var(--braccato-active-scale));transition-delay:var(--braccato-anim-delay)}.braccato--line>span{color:var(--braccato-inactive-color);display:inline-block;white-space:pre-wrap}.braccato--word{white-space:pre;display:inline-block;transform:translateY(0);position:relative}.braccato--line.braccato--pre-animating,.braccato--line.braccato--pre-animating .braccato--word{will-change:transform}.braccato--break{flex-basis:100%;height:0}.braccato--word.braccato--animating{animation:braccato-wobble var(--braccato-wobble-duration) forwards ease;animation-delay:var(--braccato-anim-delay);animation-play-state:running}.braccato--word.braccato--animating.braccato--paused{animation-play-state:paused}.braccato--word:after{position:absolute;content:attr(data-content);top:-2rem;left:-2rem;white-space:pre-wrap;padding:2rem;pointer-events:none;color:transparent;box-sizing:content-box;width:100%;background-image:linear-gradient(90deg,var(--braccato-active-color) calc(100% * var(--lyric-transition-amount-start) - 4rem * var(--lyric-transition-amount-start) + 2rem),#00000000 calc(100% * var(--lyric-transition-amount-end) - 4rem * var(--lyric-transition-amount-end) + 2rem + 1px));opacity:0;--lyric-transition-amount-start: -.2;--lyric-transition-amount-end: -.1;--braccato-glow-color: color(display-p3 1 1 1 / .0001);transition:--lyric-transition-amount-start 1s linear 1000s,--lyric-transition-amount-end 1s linear 1000s,opacity .5s ease;-webkit-background-clip:text;background-clip:text}.braccato--word[data-long-word]:after{--braccato-glow-color: color(display-p3 1 1 1 / 1)}.braccato--word.braccato--pre-animating:not(.braccato--animating):after{transition:none;--lyric-transition-amount-start: -.2;--lyric-transition-amount-end: -.1;opacity:0}.braccato--word.braccato--pre-animating:not(.braccato--animating):not(.braccato-zero-dur-animate):after{opacity:1}.braccato--word.braccato--animating:after{opacity:1;animation:braccato-glow max(calc(var(--braccato-duration) * 1.2),1.2s) forwards ease;animation-delay:var(--braccato-anim-delay);animation-play-state:running;--lyric-transition-amount-start: 1.4;--lyric-transition-amount-end: 1.5;transition-property:--lyric-transition-amount-start,--lyric-transition-amount-end,opacity;transition-duration:calc(var(--braccato-duration) * 1.6),calc(var(--braccato-duration) * 1.6),var(--braccato-highlight-fade-in-duration);transition-timing-function:linear,linear,ease;transition-delay:var(--braccato-swipe-delay),var(--braccato-swipe-delay),var(--braccato-anim-delay)}.braccato--word.braccato--animating.braccato--paused:after{transition-duration:100000000s,100000000s,100000000s;--lyric-transition-amount-start: 10;--lyric-transition-amount-end: 10;opacity:.5;animation-play-state:paused}.braccato--translated,.braccato--romanized{display:block;font-size:var(--braccato-translated-font-size);font-weight:var(--braccato-translated-font-weight);font-family:var(--braccato-translated-font-family);color:var(--braccato-translated-color);white-space:normal;line-height:1.1;margin-top:8px}.braccato--romanized>span{color:var(--braccato-inactive-color);display:inline-block;white-space:pre-wrap}.braccato--romanized{width:fit-content;font-size:calc(var(--braccato-translated-font-size) / 1.25);background:#ffffff0d;padding:.375rem .75rem;border:1px solid rgba(255,255,255,.1);border-radius:1rem}.braccato-rtl{direction:rtl}.braccato-rtl.braccato--word:after{background-image:linear-gradient(270deg,var(--braccato-active-color) calc(100% * var(--lyric-transition-amount-start) - 4rem * var(--lyric-transition-amount-start) + 2rem),#00000000 calc(100% * var(--lyric-transition-amount-end) - 4rem * var(--lyric-transition-amount-end) + 2rem + 1px))}.braccato--line[data-agent=v2],.braccato--line[data-agent=v3]{justify-content:flex-end;text-align:right;transform-origin:right center!important}.braccato--line[data-agent=v1000]{justify-content:center;text-align:center;transform-origin:center center!important}.braccato--spacer{padding:0;margin:0}.braccato-autoscroll-btn{font-family:var(--braccato-font-family);position:absolute;display:block;font-size:1.75rem;font-weight:600;white-space:normal;line-height:1.1;width:fit-content;background:#ffffff0d;padding:.5rem 1rem;border:1px solid rgba(255,255,255,.1);border-radius:1rem;color:#fff;left:50%;transform:translate(-50%,2em);-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px);pointer-events:auto;cursor:pointer;-webkit-user-select:none;user-select:none;z-index:100;transition:opacity .15s linear .05s,transform .2s cubic-bezier(.5,1,.89,1)}.braccato-autoscroll-btn[hidden]{transition:opacity .1s linear,transform .15s ease-in;opacity:0;pointer-events:none;transform:translate(-50%,-3em)}@keyframes braccato-wobble{0%{transform:translateY(0)}to{transform:translateY(-.0375em)}}@keyframes braccato-glow{0%{filter:drop-shadow(0 0 .8rem var(--braccato-glow-color))}to{filter:drop-shadow(0 0 0rem var(--braccato-glow-color))}}", Ht = ':host{--braccato-text-color: color(display-p3 1 1 1 / 1);--braccato-glow-color: color(display-p3 1 1 1 / .5);--braccato-active-color: var(--braccato-text-color);--braccato-inactive-color: color( from var(--braccato-text-color) display-p3 r g b / var(--braccato-inactive-opacity, .3) );--braccato-active-opacity: 1;--braccato-inactive-opacity: .3;--braccato-richsync-timing-offset: .15s;--braccato-timing-offset: .115s;--braccato-scroll-timing-offset: .5s;--braccato-font-family: "Satoshi", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;--braccato-font-size: 3rem;--braccato-font-weight: 600;--braccato-line-height: 1.333;--braccato-translated-font-size: 2rem;--braccato-translated-font-weight: 600;--braccato-translated-font-family: var(--braccato-font-family);--braccato-translated-color: color(display-p3 1 1 1 / var(--braccato-translated-opacity, .6));--braccato-scale-transition-duration: .166s;--braccato-highlight-fade-in-duration: .33s;--braccato-highlight-fade-out-duration: .5s;--braccato-wobble-duration: 1s;--braccato-padding: 1.25rem;--braccato-scale: .95;--braccato-active-scale: 1;--braccato-scroll-duration: .75s;--braccato-scroll-timing-function: cubic-bezier(.86, 0, .07, 1)}';
611
+ var Gt = Object.defineProperty, I = (t, e, a, r) => {
612
+ for (var i = void 0, o = t.length - 1, n; o >= 0; o--)
613
+ (n = t[o]) && (i = n(e, a, i) || i);
614
+ return i && Gt(e, a, i), i;
615
+ };
616
+ function Yt() {
617
+ if (!(typeof CSS > "u" || !CSS.registerProperty))
618
+ try {
619
+ CSS.registerProperty({
620
+ name: "--lyric-transition-amount-start",
621
+ syntax: "<number>",
622
+ inherits: !1,
623
+ initialValue: "0"
624
+ }), CSS.registerProperty({
625
+ name: "--lyric-transition-amount-end",
626
+ syntax: "<number>",
627
+ inherits: !1,
628
+ initialValue: "0"
629
+ });
630
+ } catch {
631
+ }
632
+ }
633
+ Yt();
634
+ const V = class V extends st {
635
+ constructor() {
636
+ super(...arguments), this.lyrics = [], this.currentTime = 0, this.playing = !1, this.scrollMode = "internal", this.scrollContainer = null, this.dir = "auto", this.longWordThreshold = 1500, this.lineSyncedDelay = 50, this.disableRichsync = !1, this.debug = !1, this.source = null, this.src = null, this._lyricsData = null, this._animState = Dt(), this._rafId = null, this._lastLyrics = [], this._resizeObserver = null, this._mediaElement = null, this._lastSrc = null, this._srcAbortController = null, this._tickCount = 0, this._onScroll = () => {
637
+ const e = this._animState.scroll;
638
+ if (e.skipScrolls > 0) {
639
+ e.skipScrolls--;
640
+ return;
641
+ }
642
+ _t(e) ? X(e) : (X(e), this.dispatchEvent(
643
+ new CustomEvent("braccato:scroll-state", {
644
+ detail: { userScrolling: !0 },
645
+ bubbles: !0,
646
+ composed: !0
647
+ })
648
+ ));
649
+ };
650
+ }
651
+ // -- Lifecycle --------------------------
652
+ connectedCallback() {
653
+ super.connectedCallback(), this._startLoop();
654
+ }
655
+ disconnectedCallback() {
656
+ var e;
657
+ super.disconnectedCallback(), this._stopLoop(), (e = this._resizeObserver) == null || e.disconnect();
658
+ }
659
+ updated(e) {
660
+ e.has("lyrics") && this.lyrics !== this._lastLyrics && (this._lastLyrics = this.lyrics, this._injectLyrics()), e.has("source") && this._resolveMediaElement(), e.has("src") && this.src !== this._lastSrc && (this._lastSrc = this.src, this._fetchLyricsFromSrc());
661
+ }
662
+ render() {
663
+ return ot`<div class="braccato-container" part="container"></div>`;
664
+ }
665
+ // -- Lyric Injection --------------------------
666
+ _log(...e) {
667
+ this.debug && console.log("[braccato]", ...e);
668
+ }
669
+ _injectLyrics() {
670
+ var i, o, n, s;
671
+ const e = (i = this.shadowRoot) == null ? void 0 : i.querySelector(".braccato-container");
672
+ if (!e) {
673
+ this._log("_injectLyrics: no container found in shadowRoot");
674
+ return;
675
+ }
676
+ if (It(this._animState), !this.lyrics || this.lyrics.length === 0) {
677
+ this._log("_injectLyrics: no lyrics, clearing"), e.replaceChildren(), this._lyricsData = null;
678
+ return;
679
+ }
680
+ const a = {
681
+ longWordThreshold: this.longWordThreshold,
682
+ lineSyncedAnimationDelay: this.lineSyncedDelay,
683
+ disableRichsync: this.disableRichsync
684
+ };
685
+ this._lyricsData = $t(this.lyrics, e, a), this._log("_injectLyrics: rendered", {
686
+ lineCount: this._lyricsData.lines.length,
687
+ syncType: this._lyricsData.syncType,
688
+ firstLineTime: (o = this._lyricsData.lines[0]) == null ? void 0 : o.time,
689
+ lastLineTime: (n = this._lyricsData.lines[this._lyricsData.lines.length - 1]) == null ? void 0 : n.time,
690
+ containerSize: { w: e.clientWidth, h: e.clientHeight }
691
+ });
692
+ for (let c = 0; c < this._lyricsData.lines.length; c++)
693
+ this._lyricsData.lines[c].element.addEventListener("click", (p) => this._handleLineClick(p, c));
694
+ const r = this._getScrollContainer();
695
+ this._log("_injectLyrics: scrollContainer", r.tagName, r.className), r.addEventListener("scroll", this._onScroll, { passive: !0 }), (s = this._resizeObserver) == null || s.disconnect(), this._resizeObserver = new ResizeObserver(() => this._recalculatePositions()), this._resizeObserver.observe(e), this._recalculatePositions(), this.dispatchEvent(
696
+ new CustomEvent("braccato:lyrics-loaded", {
697
+ detail: { syncType: this._lyricsData.syncType, lineCount: this._lyricsData.lines.length },
698
+ bubbles: !0,
699
+ composed: !0
700
+ })
701
+ );
702
+ }
703
+ // -- Position Calculation --------------------------
704
+ _recalculatePositions() {
705
+ if (!this._lyricsData) return;
706
+ const e = this._lyricsData.container;
707
+ this._lyricsData.width = e.clientWidth, this._lyricsData.height = e.clientHeight;
708
+ for (const a of this._lyricsData.lines) {
709
+ const r = a.element.getBoundingClientRect(), i = e.getBoundingClientRect();
710
+ a.position = r.top - i.top + e.scrollTop, a.height = r.height;
711
+ }
712
+ this._animState.scroll.wasUserScrolling = !0;
713
+ }
714
+ // -- Animation Loop --------------------------
715
+ _startLoop() {
716
+ const e = () => {
717
+ this._tick(), this._rafId = requestAnimationFrame(e);
718
+ };
719
+ this._rafId = requestAnimationFrame(e);
720
+ }
721
+ _stopLoop() {
722
+ this._rafId !== null && (cancelAnimationFrame(this._rafId), this._rafId = null);
723
+ }
724
+ _tick() {
725
+ if (!this._lyricsData || this._lyricsData.syncType === "none") return;
726
+ if (this._tickCount++, this.debug && this._tickCount % 60 === 0) {
727
+ const i = this._lyricsData.lines.filter((n) => n.isScrolled), o = this._lyricsData.lines.filter((n) => n.isAnimating);
728
+ this._log("tick", {
729
+ currentTime: this.currentTime,
730
+ currentTimeSec: this.currentTime / 1e3,
731
+ playing: this.playing,
732
+ syncType: this._lyricsData.syncType,
733
+ activeLineCount: i.length,
734
+ animatingLineCount: o.length,
735
+ selectedIndex: this._animState.selectedElementIndex,
736
+ scrollResumeTime: this._animState.scroll.scrollResumeTime,
737
+ isUserScrolling: this._animState.scroll.wasUserScrolling
738
+ });
739
+ }
740
+ const e = this._mediaElement, a = e ? e.currentTime * 1e3 : this.currentTime, r = e ? !e.paused : this.playing;
741
+ Nt(this._animState, {
742
+ currentTime: a / 1e3,
743
+ eventCreationTime: Date.now(),
744
+ isPlaying: r,
745
+ smoothScroll: !0,
746
+ lyricsData: this._lyricsData,
747
+ scrollContainer: this._getScrollContainer()
748
+ });
749
+ }
750
+ // -- Scroll --------------------------
751
+ _getScrollContainer() {
752
+ return this.scrollMode === "external" && this.scrollContainer ? this.scrollContainer : this;
753
+ }
754
+ // -- Events --------------------------
755
+ _handleLineClick(e, a) {
756
+ var o, n;
757
+ const r = (o = this._lyricsData) == null ? void 0 : o.lines[a];
758
+ if (!r) return;
759
+ const i = r.time * 1e3;
760
+ if (this._log("lineClick", { lineIndex: a, time: i, lineTimeSec: r.time, currentTime: this.currentTime }), e.altKey && ((n = this._lyricsData) == null ? void 0 : n.syncType) === "richsync") {
761
+ const s = e.target.closest(".braccato--word");
762
+ if (s) {
763
+ const c = Number.parseFloat(s.dataset.time || "0") * 1e3, d = r.parts.findIndex((p) => p.element === s);
764
+ this.dispatchEvent(
765
+ new CustomEvent("braccato:word-click", {
766
+ detail: { time: c, lineIndex: a, wordIndex: d },
767
+ bubbles: !0,
768
+ composed: !0
769
+ })
770
+ );
771
+ return;
772
+ }
773
+ }
774
+ this._mediaElement && (this._mediaElement.currentTime = i / 1e3, this._mediaElement.paused && this._mediaElement.play()), this.dispatchEvent(
775
+ new CustomEvent("braccato:line-click", {
776
+ detail: { time: i, lineIndex: a },
777
+ bubbles: !0,
778
+ composed: !0
779
+ })
780
+ ), tt(this._animState.scroll);
781
+ }
782
+ // -- Source Binding --------------------------
783
+ _resolveMediaElement() {
784
+ if (!this.source) {
785
+ this._mediaElement = null;
786
+ return;
787
+ }
788
+ const e = document.querySelector(this.source);
789
+ e instanceof HTMLMediaElement ? this._mediaElement = e : (this._mediaElement = null, this._log("source: no media element found for selector", this.source));
790
+ }
791
+ async _fetchLyricsFromSrc() {
792
+ var a;
793
+ if ((a = this._srcAbortController) == null || a.abort(), !this.src) {
794
+ this.lyrics = [];
795
+ return;
796
+ }
797
+ const e = new AbortController();
798
+ this._srcAbortController = e;
799
+ try {
800
+ const r = await fetch(this.src, { signal: e.signal });
801
+ if (!r.ok) {
802
+ this._emitError(new Error(`Failed to fetch lyrics: ${r.status} ${r.statusText}`));
803
+ return;
804
+ }
805
+ const i = await r.text();
806
+ if (e.signal.aborted) return;
807
+ const o = this._mediaElement ? this._mediaElement.duration * 1e3 : 3e5, n = yt(i);
808
+ this.lyrics = n.parse(i, o);
809
+ } catch (r) {
810
+ if (r instanceof DOMException && r.name === "AbortError") return;
811
+ this._emitError(r instanceof Error ? r : new Error(String(r)));
812
+ }
813
+ }
814
+ _emitError(e) {
815
+ this._log("error", e.message), this.dispatchEvent(
816
+ new CustomEvent("braccato:error", {
817
+ detail: { error: e },
818
+ bubbles: !0,
819
+ composed: !0
820
+ })
821
+ );
822
+ }
823
+ // -- Public Methods --------------------------
824
+ resumeAutoscroll() {
825
+ tt(this._animState.scroll);
826
+ }
827
+ recalculatePositions() {
828
+ this._recalculatePositions();
829
+ }
830
+ };
831
+ V.styles = [J(Ht), J(jt)];
832
+ let C = V;
833
+ I([
834
+ D({ type: Array })
835
+ ], C.prototype, "lyrics");
836
+ I([
837
+ D({ attribute: "current-time", type: Number })
838
+ ], C.prototype, "currentTime");
839
+ I([
840
+ D({ type: Boolean, reflect: !0 })
841
+ ], C.prototype, "playing");
842
+ I([
843
+ D({ attribute: "scroll-mode", type: String, reflect: !0 })
844
+ ], C.prototype, "scrollMode");
845
+ I([
846
+ D({ attribute: !1 })
847
+ ], C.prototype, "scrollContainer");
848
+ I([
849
+ D({ type: String, reflect: !0 })
850
+ ], C.prototype, "dir");
851
+ I([
852
+ D({ attribute: "long-word-threshold", type: Number })
853
+ ], C.prototype, "longWordThreshold");
854
+ I([
855
+ D({ attribute: "line-synced-delay", type: Number })
856
+ ], C.prototype, "lineSyncedDelay");
857
+ I([
858
+ D({ attribute: "disable-richsync", type: Boolean })
859
+ ], C.prototype, "disableRichsync");
860
+ I([
861
+ D({ type: Boolean })
862
+ ], C.prototype, "debug");
863
+ I([
864
+ D({ type: String, reflect: !0 })
865
+ ], C.prototype, "source");
866
+ I([
867
+ D({ type: String, reflect: !0 })
868
+ ], C.prototype, "src");
869
+ customElements.define("braccato-lyrics", C);
870
+ export {
871
+ C as BraccatoElement
872
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@braccato/core",
3
+ "version": "0.1.0",
4
+ "description": "Synchronized lyrics web component with word-by-word animations",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/better-lyrics/braccato",
10
+ "directory": "packages/core"
11
+ },
12
+ "homepage": "https://github.com/better-lyrics/braccato",
13
+ "keywords": [
14
+ "lyrics",
15
+ "sync",
16
+ "web-component",
17
+ "lit",
18
+ "music",
19
+ "karaoke",
20
+ "ttml"
21
+ ],
22
+ "sideEffects": true,
23
+ "main": "dist/index.js",
24
+ "types": "dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "dependencies": {
38
+ "lit": "^3.2.1",
39
+ "@braccato/parsers": "^0.1.0"
40
+ },
41
+ "devDependencies": {
42
+ "typescript": "^5.7.3",
43
+ "vite": "^6.0.7",
44
+ "vite-plugin-dts": "^4.3.0"
45
+ },
46
+ "scripts": {
47
+ "build": "vite build",
48
+ "dev": "vite build --watch",
49
+ "typecheck": "tsc --noEmit"
50
+ }
51
+ }