// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2), the lyrics of the wall's playing card: // src/components/app/lattice/lyrics/ (createLatticeLyricRuntime.ts, latticeLyricLayout.ts, latticeLyricScene.ts, // latticeLyricTimeline.ts) and the tones, glow and springs they take from // src/components/visualizer/monet/monetLyricMotion.ts. See ../README.md. // // Three lines on the card: the one before (small, dim), the one being sung (its words brightening as the voice // passes, with a soft glow behind the word of the moment) and the one to come. Each line springs to its place // when the song moves on; the type is fitted once to the card, never to the sentence, so it does not pump. // // Changed from Folia: drawn with DOM text (a gradient clipped to each word for the sweep, drop-shadows for the // glow) instead of a Pixi scene; a word is one sweep unit (the site's lyrics are timed by line, the words // estimated), and translation rows show only when a line carries one. import { resolveThemeFontWeight, type Line, type Theme } from '../types'; import { colorWithAlpha, mixColors } from '../color'; import { getLineRenderEndTime } from '../lyrics/renderHints'; import { findLatestActiveLineIndex } from '../lyrics/timeline'; type Status = 'active' | 'waiting' | 'passed'; const SCROLL_SPRING = { stiffness: 142, damping: 28, mass: 0.82 }; const SCALE_SPRING = { stiffness: 150, damping: 30, mass: 0.78 }; const clamp01 = (value: number) => Math.min(1, Math.max(0, value)); const smooth = (value: number) => value * value * (3 - 2 * value); /** How a line reads by what it is to the voice, and how far from it. */ const resolveTone = (status: Status, offset: number) => { if (status === 'active') return { alpha: 1, scale: 1, blur: 0, baseAlpha: 0.34 }; const distance = Math.max(Math.abs(offset), 1); const waiting = status === 'waiting'; return { alpha: waiting ? Math.max(0.36, 0.72 - (distance - 1) * 0.18) : Math.max(0.28, 0.52 - (distance - 1) * 0.12), scale: Math.max(0.68, 0.72 * Math.pow(0.9, distance - 1)), blur: waiting ? (distance === 1 ? 0.7 : 1.8 + (distance - 2) * 0.8) : 1.1 + (distance - 1) * 0.7, baseAlpha: waiting ? 0.46 : 0.36, }; }; /** The glow behind a word: up a little past the word's own length, then held and let go by the end of the line. */ const resolveGlow = (time: number, start: number, end: number, lineEnd: number): number => { if (time <= start) return 0; const rise = Math.max(0.001, end - start) * 1.18; const peak = start + rise; const tail = Math.max(lineEnd, end + 1.05); if (time <= peak) return smooth(clamp01((time - start) / rise)); return smooth(1 - clamp01((time - peak) / Math.max(0.18, tail - peak))); }; const stepSpring = (value: number, velocity: number, target: number, delta: number, spring: { stiffness: number; damping: number; mass: number }) => { let left = Math.min(delta, 0.1); while (left > 0) { const slice = Math.min(left, 1 / 240); velocity += ((spring.stiffness * (target - value) - spring.damping * velocity) / spring.mass) * slice; value += velocity * slice; left -= slice; } const settled = Math.abs(target - value) < 0.05 && Math.abs(velocity) < 0.5; return { value: settled ? target : value, velocity: settled ? 0 : velocity, settled }; }; interface Token { el: HTMLSpanElement; start: number; end: number; fill: number; glow: number; } interface Track { index: number; line: Line; el: HTMLDivElement; tokens: Token[]; height: number; textHeight: number; y: number; vy: number; scale: number; vs: number; alpha: number; blur: number; fromAlpha: number; fromBlur: number; elapsed: number; status: Status; offset: number; leaving: boolean; written: string; } let measureCanvas: HTMLCanvasElement | null = null; const measure = (text: string, font: string) => { measureCanvas ??= document.createElement('canvas'); const context = measureCanvas.getContext('2d')!; context.font = font; const metrics = context.measureText(text); return { width: metrics.width, height: metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent }; }; export class TileLyrics { readonly el: HTMLDivElement; #theme: Theme; #lines: Line[] = []; #tracks = new Map(); #size = { width: 0, height: 0 }; #type = { fontPx: 24, lineHeight: 30, padding: 14 }; #entriesKey = ''; #lastTime = -1; constructor(theme: Theme) { this.#theme = theme; this.el = document.createElement('div'); this.el.className = 'lattice-lyrics'; this.el.setAttribute('aria-hidden', 'true'); } get hasLines() { return this.#lines.length > 0; } setTheme(theme: Theme) { this.#theme = theme; this.#clear(); } setLines(lines: Line[]) { this.#lines = lines; this.#clear(); this.el.classList.toggle('is-ready', lines.length > 0); } /** The card's box changed: fit the type again and lay the lines out afresh. */ resize() { const width = this.el.clientWidth; const height = this.el.clientHeight; if (width === this.#size.width && height === this.#size.height) return; this.#size = { width, height }; this.#fit(); this.#clear(); } /** Returns whether anything is still moving, so the wall knows to keep drawing after the music stops. */ frame(time: number, delta: number, quiet: boolean) { const { width, height } = this.#size; if (!this.#lines.length || width < 2 || height < 2) return false; if (time < this.#lastTime || Math.abs(time - this.#lastTime) > 0.75) this.#clear(); this.#lastTime = time; const entries = this.#timeline(time); const key = entries.map((entry) => `${entry.index}:${entry.status}:${entry.offset}`).join('|'); if (key !== this.#entriesKey) { this.#entriesKey = key; this.#refresh(entries); } const type = this.#type; const anchor = entries.find((entry) => entry.offset === 0); const anchorTrack = anchor ? this.#tracks.get(anchor.index) : undefined; const room = Math.max(type.lineHeight, height - type.padding * 2); const activeHeight = anchorTrack ? Math.min(room, anchorTrack.status === 'active' ? anchorTrack.height : Math.min(anchorTrack.textHeight, type.lineHeight * 2) * resolveTone(anchorTrack.status, 0).scale) : 0; const anchorY = Math.max(type.padding, height * 0.46 - activeHeight / 2); const gap = Math.max(18, type.fontPx * 0.49); let moving = false; for (const [index, track] of this.#tracks) { const tone = resolveTone(track.status, track.offset); const contextHeight = Math.min(track.textHeight, type.lineHeight * 2); let targetY = track.offset < 0 ? anchorY - contextHeight * tone.scale - gap : track.offset > 0 ? anchorY + activeHeight + gap : anchorY; if (track.leaving) targetY += track.offset < 0 || track.status === 'passed' ? -38 : 38; const sy = stepSpring(track.y, track.vy, targetY, delta, SCROLL_SPRING); const ss = stepSpring(track.scale, track.vs, tone.scale, delta, SCALE_SPRING); track.y = quiet ? targetY : sy.value; track.vy = quiet ? 0 : sy.velocity; track.scale = quiet ? tone.scale : ss.value; track.vs = quiet ? 0 : ss.velocity; track.elapsed += delta; const fade = quiet ? 1 : smooth(Math.min(1, track.elapsed / 0.28)); const blurFade = quiet ? 1 : smooth(Math.min(1, track.elapsed / 0.32)); track.alpha = track.fromAlpha + ((track.leaving ? 0 : tone.alpha) - track.fromAlpha) * fade; track.blur = track.fromBlur + (tone.blur - track.fromBlur) * blurFade; if (track.leaving && fade === 1) { track.el.remove(); this.#tracks.delete(index); continue; } moving ||= !quiet && (!sy.settled || !ss.settled || track.elapsed < 0.32); const written = `${track.y.toFixed(1)}|${track.scale.toFixed(3)}|${track.alpha.toFixed(3)}|${track.blur.toFixed(1)}`; if (written !== track.written) { track.written = written; track.el.style.transform = `translate(${type.padding}px, ${track.y.toFixed(1)}px) scale(${track.scale.toFixed(3)})`; track.el.style.opacity = track.alpha.toFixed(3); track.el.style.filter = track.blur > 0.05 ? `blur(${track.blur.toFixed(1)}px)` : 'none'; } moving = this.#sweep(track, time, quiet) || moving; } return moving; } destroy() { this.#clear(); this.el.remove(); } /** The largest of 24..64 px whose three lines (and a little air) fit the card. */ #fit() { const { width, height } = this.#size; const weight = resolveThemeFontWeight(this.#theme, 600); const fits = (size: number) => { const main = measure('国Agyp', `${weight} ${size}px ${this.#theme.fontStack}`); const lineHeight = Math.max(size * 1.18, main.height + 2); const budget = lineHeight * (3 + 2 * 0.72) + size * 0.49 * 2 + size * 1.2; return budget <= height && main.width * 3 <= Math.max(0, width - size * 1.2); }; let fontPx = 24; for (let low = 24, high = 64; low <= high;) { const size = (low + high) >> 1; if (fits(size)) { fontPx = size; low = size + 1; } else high = size - 1; } const main = measure('国Agyp', `${weight} ${fontPx}px ${this.#theme.fontStack}`); this.#type = { fontPx, lineHeight: Math.max(fontPx * 1.18, main.height + 2), padding: Math.ceil(fontPx * 0.6) }; this.el.style.setProperty('--lattice-lyric-size', `${fontPx}px`); this.el.style.setProperty('--lattice-lyric-line', `${this.#type.lineHeight.toFixed(1)}px`); this.el.style.fontWeight = String(weight); } /** The line before, the line at the voice (or, in a gap, the next to come) and the line after. */ #timeline(time: number): { index: number; status: Status; offset: number }[] { const lines = this.#lines; let anchor = findLatestActiveLineIndex(lines, time); let status: Status = 'active'; if (anchor < 0) { anchor = lines.findIndex((line) => line.startTime > time); status = 'waiting'; if (anchor < 0) { anchor = lines.length - 1; status = 'passed'; } } const entries: { index: number; status: Status; offset: number }[] = []; if (anchor > 0) entries.push({ index: anchor - 1, status: 'passed', offset: -1 }); entries.push({ index: anchor, status, offset: 0 }); if (anchor + 1 < lines.length) entries.push({ index: anchor + 1, status: 'waiting', offset: 1 }); return entries; } #refresh(entries: { index: number; status: Status; offset: number }[]) { const wanted = new Map(entries.map((entry) => [entry.index, entry])); for (const [index, track] of this.#tracks) { const entry = wanted.get(index); if (entry) { if (track.status !== entry.status || track.offset !== entry.offset || track.leaving) { track.fromAlpha = track.alpha; track.fromBlur = track.blur; track.elapsed = 0; } track.status = entry.status; track.offset = entry.offset; track.leaving = false; track.el.classList.toggle('is-active', entry.status === 'active'); this.#paint(track); } else if (!track.leaving) { track.leaving = true; track.fromAlpha = track.alpha; track.fromBlur = track.blur; track.elapsed = 0; } } for (const entry of entries) { if (this.#tracks.has(entry.index)) continue; const track = this.#build(entry.index, entry.status, entry.offset); this.#tracks.set(entry.index, track); } } #build(index: number, status: Status, offset: number): Track { const line = this.#lines[index]; const type = this.#type; const el = document.createElement('div'); el.className = status === 'active' ? 'lattice-lyric-line is-active' : 'lattice-lyric-line'; el.style.width = `${Math.max(0, this.#size.width - type.padding * 2)}px`; const text = document.createElement('div'); text.className = 'lattice-lyric-text'; const tokens: Token[] = []; // Each timed word is a span; what stands between two words in the line (spaces, marks the words leave // out) is kept as plain text, so the line reads exactly as written. let cursor = 0; for (const word of line.words) { const found = line.fullText.indexOf(word.text, cursor); const start = found >= 0 ? found : cursor; if (start > cursor) text.append(line.fullText.slice(cursor, start)); const span = document.createElement('span'); span.className = 'lattice-lyric-token'; span.textContent = word.text; text.append(span); tokens.push({ el: span, start: word.startTime, end: word.endTime, fill: -1, glow: -1 }); cursor = start + word.text.length; } if (cursor < line.fullText.length) text.append(line.fullText.slice(cursor)); el.append(text); if (line.translation) { const sub = document.createElement('div'); sub.className = 'lattice-lyric-sub'; sub.textContent = line.translation; el.append(sub); } this.el.append(el); // Measured whole: a line waiting its turn is clipped to two rows, but it will be sung at its full height. const textHeight = text.scrollHeight; const track: Track = { index, line, el, tokens, height: textHeight + (el.scrollHeight - text.offsetHeight > 0 && line.translation ? type.fontPx * 0.3 + type.fontPx * 0.5 * 1.35 : 0), textHeight, // A line comes in from a little beyond its side of the voice, small and out of focus. y: this.#size.height * 0.46 + (offset >= 0 ? 34 : -34), vy: 0, scale: 0.7, vs: 0, alpha: 0, blur: 5, fromAlpha: 0, fromBlur: 5, elapsed: 0, status, offset, leaving: false, written: '', }; this.#paint(track); return track; } /** The two colours a line's words run between: unsung (the lyric colour, thinned by the line's tone) and sung. */ #paint(track: Track) { const theme = this.#theme; const tone = resolveTone(track.status, track.offset); const word = track.line.isChorus ? mixColors(theme.primaryColor, theme.accentColor, 0.48) : colorWithAlpha(theme.primaryColor, 0.98); track.el.style.setProperty('--lattice-lyric-base', colorWithAlpha(theme.primaryColor, tone.baseAlpha)); track.el.style.setProperty('--lattice-lyric-word', word); for (const token of track.tokens) token.fill = token.glow = -1; } /** Each word's share of the sweep and its glow; only words whose numbers changed are written. */ #sweep(track: Track, time: number, quiet: boolean) { const lineEnd = getLineRenderEndTime(track.line); const chorus = Boolean(track.line.isChorus); let glowing = false; for (const token of track.tokens) { const fill = track.status === 'passed' ? 1 : track.status === 'waiting' ? 0 : clamp01((time - token.start) / Math.max(0.001, token.end - token.start)); const stepped = Math.round(fill * 200) / 200; if (stepped !== token.fill) { token.fill = stepped; token.el.style.setProperty('--f', stepped.toFixed(3)); } const glow = quiet || track.status === 'waiting' ? 0 : resolveGlow(time, token.start, token.end, lineEnd) * (chorus ? 1 : 0.88); const level = Math.round(glow * 20) / 20; if (level !== token.glow) { token.glow = level; token.el.style.setProperty('--glow', level.toFixed(2)); token.el.classList.toggle('is-glowing', level > 0); } glowing ||= level > 0 && level < 1; } return glowing && track.status !== 'active'; } #clear() { for (const track of this.#tracks.values()) track.el.remove(); this.#tracks.clear(); this.#entriesKey = ''; } }