// SPDX-License-Identifier: AGPL-3.0-only // Part of the Folia lyric stage port (see ./README.md). The host of the port: what Folia spreads over // VisualizerRenderer.tsx, VisualizerBackdrop.tsx, VisualizerShell.tsx, runtime.ts and its playback bridge is one // class here. It owns the backdrop, the lyric style on screen and the band of coming lines, reads the song's // clock every frame, and tells the style when the line on screen changes. // // The page that mounts it stays on the other side of a small surface: it hands over the lines (as time stamps // and words), a theme, the audio levels and a clock, and nothing of Folia's reaches back into the page. The page // also imports the stage's sheet, ./folia.css (a sheet brought in by this lazily loaded script would not survive // the site's page swaps). import type { Appearance, AudioLevels, Line, StageTunings, Theme } from './types'; import { DEFAULT_TUNINGS, SILENT_AUDIO } from './types'; import { GeometricBackground } from './background'; import { SubtitleOverlay } from './subtitle'; import { buildLinesFromStamps, findLatestActiveLineIndex } from './lyrics/timeline'; import { LYRIC_STYLES, type LyricStyle, type StyleContext, type StyleRenderer } from './styles/registry'; import { createStill } from './styles/still'; export { LYRIC_STYLES } from './styles/registry'; export type { Appearance, AudioLevels, Theme } from './types'; export interface FoliaStageOptions { /** Seconds into the song, read every frame. */ clock: () => number; playing: () => boolean; theme: Theme; /** Whether the host shows its day side: a look's colours for that side are the ones taken. */ daylight?: boolean; style?: string; appearance?: Appearance; } /** How long the stage keeps drawing after the music stops or jumps, so motion in flight can land. */ const SETTLE_MS = 1600; export class FoliaStage { readonly el: HTMLDivElement; #options: FoliaStageOptions; #base: Theme; #daylight: boolean; #appearance: Appearance; #theme: Theme; #background: GeometricBackground; #subtitle: SubtitleOverlay; #shell: HTMLDivElement; #style: LyricStyle; #renderer: StyleRenderer | null = null; #layer: HTMLDivElement | null = null; #lines: Line[] = []; #index = -2; #time = 0; #audio: AudioLevels = { ...SILENT_AUDIO }; #frame = 0; #last = 0; #settleUntil = 0; #active = false; #paused = true; #still = false; #size = { width: 0, height: 0 }; #resize: ResizeObserver; #resizeTimer = 0; #destroyed = false; constructor(host: HTMLElement, options: FoliaStageOptions) { this.#options = options; this.#base = options.theme; this.#daylight = Boolean(options.daylight); this.#appearance = options.appearance ?? {}; this.#theme = this.#resolveTheme(); this.#style = LYRIC_STYLES.find((style) => style.id === options.style) ?? LYRIC_STYLES[0]; const el = this.el = document.createElement('div'); el.className = 'folia'; // Its box does not wait for the stylesheet: the styles measure it as soon as they are mounted. el.style.position = 'absolute'; el.style.inset = '0'; this.#background = new GeometricBackground(this.#theme); this.#shell = document.createElement('div'); this.#shell.className = 'folia__shell'; this.#subtitle = new SubtitleOverlay(this.#theme); el.append(this.#background.el, this.#shell, this.#subtitle.el); this.#applyLook(); host.append(el); this.#size = { width: el.clientWidth, height: el.clientHeight }; this.#resize = new ResizeObserver(() => { const width = el.clientWidth; const height = el.clientHeight; if (width === this.#size.width && height === this.#size.height) return; this.#size = { width, height }; // Sizes are worked out per line; a new size lays the line out again once the resizing has stopped. window.clearTimeout(this.#resizeTimer); this.#resizeTimer = window.setTimeout(() => this.#mountStyle(), 140); }); this.#resize.observe(el); } get style() { return this.#style.id; } get hasLyrics() { return this.#lines.length > 0; } /** A song's lyrics: time stamps and words, earliest first (a stamp without words ends the line before it). Empty for none. */ setSong(stamps: ReadonlyArray<{ time: number; text: string }>) { this.#lines = buildLinesFromStamps(stamps); this.#index = -2; this.#time = this.#options.clock(); this.#background.build(); this.#mountStyle(); } setStyle(id: string) { const style = LYRIC_STYLES.find((entry) => entry.id === id); if (!style || style === this.#style) return; this.#style = style; this.#mountStyle(true); } /** The host's own colours and type, and which side (day or night) it shows. */ setTheme(theme: Theme, daylight = this.#daylight) { this.#base = theme; this.#daylight = daylight; this.#restyle(); } /** A look (./appearance.ts reads one from a Folia config code): colours, the styles' settings, sizes. */ setAppearance(appearance: Appearance) { this.#appearance = appearance; this.#restyle(); } /** For a reader who asked for less motion: the backdrop holds still and the lines are set plainly (Folia's 静止). */ setStill(still: boolean) { if (still === this.#still) return; this.#still = still; this.#background.setPaused(still || this.#paused); this.#mountStyle(); } /** The music's levels, each 0..255; all zero while it is silent or its motion is switched off. */ setAudio(audio: AudioLevels) { this.#audio = audio; } /** Whether anyone can see the stage; nothing is drawn while it is off screen. */ setActive(active: boolean) { if (this.#active === active) return; this.#active = active; this.nudge(); } /** Look at the clock again: the music started, stopped or jumped. */ nudge() { if (this.#destroyed) return; const paused = !this.#options.playing(); if (paused !== this.#paused) { this.#paused = paused; this.#background.setPaused(paused || this.#still); } this.#settleUntil = performance.now() + SETTLE_MS; if (!this.#frame && this.#active) { this.#last = performance.now(); this.#frame = requestAnimationFrame(this.#tick); } } destroy() { this.#destroyed = true; cancelAnimationFrame(this.#frame); window.clearTimeout(this.#resizeTimer); this.#resize.disconnect(); this.#renderer?.destroy(); this.#background.destroy(); this.#subtitle.destroy(); this.el.remove(); } /** The host's theme with the look's colours for the side on show, its weight and its font families laid over it. */ #resolveTheme(): Theme { const look = this.#appearance; const side = (this.#daylight ? look.theme?.light : look.theme?.dark) ?? {}; const families = (look.fontFamilies ?? []).filter(Boolean).map((family) => `"${family.replace(/["\\]/g, '')}"`); return { ...this.#base, ...Object.fromEntries(Object.entries(side).filter(([, value]) => value !== undefined && value !== '')), fontStack: families.length ? `${families.join(', ')}, ${this.#base.fontStack}` : this.#base.fontStack, ...(look.fontWeight ? { fontWeight: look.fontWeight } : {}), }; } #restyle() { this.#theme = this.#resolveTheme(); this.#applyLook(); this.#background.setTheme(this.#theme); this.#subtitle.setTheme(this.#theme); this.#mountStyle(); } #applyLook() { const theme = this.#theme; const look = this.#appearance; this.el.style.setProperty('--folia-font', theme.fontStack); this.el.style.color = theme.primaryColor; if (look.hideVignette) this.el.style.setProperty('--folia-vignette', '0'); else this.el.style.removeProperty('--folia-vignette'); this.#shell.style.opacity = look.opacity === undefined ? '' : String(Math.min(1, Math.max(0, look.opacity))); this.#subtitle.setOptions(look.subtitle ?? {}); } #tunings(): StageTunings { const look = this.#appearance.tunings ?? {}; return { classic: { ...DEFAULT_TUNINGS.classic, ...look.classic }, cadenza: { ...DEFAULT_TUNINGS.cadenza, ...look.cadenza }, partita: { ...DEFAULT_TUNINGS.partita, ...look.partita }, tilt: { ...DEFAULT_TUNINGS.tilt, ...look.tilt }, }; } /** Puts the chosen style on stage; with `fade`, the one before it fades out under the new one. */ #mountStyle(fade = false) { if (this.#destroyed) return; const previous = this.#renderer; const previousLayer = this.#layer; if (previous && previousLayer) { if (fade) { previousLayer.style.transition = 'opacity .36s ease, filter .36s ease'; previousLayer.style.opacity = '0'; previousLayer.style.filter = 'blur(8px)'; window.setTimeout(() => { previous.destroy(); previousLayer.remove(); }, 380); } else { previous.destroy(); previousLayer.remove(); } } this.#renderer = null; this.#layer = null; this.#background.setHideShapes(Boolean(this.#style.hideShapes || this.#appearance.hideShapes)); if (!this.#lines.length || this.#size.width <= 0 || this.#size.height <= 0) { this.#subtitle.update([], -1, 0, false); return; } const layer = this.#layer = document.createElement('div'); layer.className = `folia__layer folia__layer--${this.#still ? 'still' : this.#style.id}`; if (fade) layer.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 360, easing: 'ease' }); this.#shell.append(layer); const scale = this.#appearance.fontScale; const context: StyleContext = { layer, theme: this.#theme, lines: this.#lines, width: this.#size.width, height: this.#size.height, rem: Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16, audio: () => this.#audio, tunings: this.#tunings(), fontScale: scale && Number.isFinite(scale) ? Math.min(2, Math.max(0.5, scale)) : 1, }; this.#renderer = this.#still ? createStill(context) : this.#style.create(context); this.#index = -2; this.#step(0); this.nudge(); } #tick = (now: number) => { this.#frame = 0; if (this.#destroyed) return; const delta = Math.min(0.1, Math.max(0.001, (now - this.#last) / 1000)); this.#last = now; this.#step(delta); const playing = this.#options.playing(); if (this.#active && (playing || now < this.#settleUntil)) this.#frame = requestAnimationFrame(this.#tick); }; #step(delta: number) { const playing = this.#options.playing(); const raw = this.#options.clock(); // The element's clock can arrive in steps; between them the stage runs on its own and leans back toward // it, so words do not stutter. A real jump (a seek, a new song) is taken at once. const predicted = this.#time + (playing ? delta : 0); this.#time = playing && Math.abs(raw - predicted) < 0.12 ? predicted + (raw - predicted) * 0.12 : raw; const time = this.#time; this.#background.frame(this.#audio, delta); const renderer = this.#renderer; if (!renderer) return; const index = findLatestActiveLineIndex(this.#lines, time); if (index !== this.#index) { this.#index = index; renderer.setLine(this.#lines[index] ?? null, index, time); this.#subtitle.update(this.#lines, index, time); } renderer.frame(time, delta); } }