// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2), // src/components/visualizer/cadenza/: VisualizerCadenza.tsx, cadenzaEnvelopes.ts, cadenzaFragments.ts, // cadenzaPlacements.ts, cadenzaPreparedState.ts and cadenzaOverlayNodes.ts: 心象. // The heavy layout style. A line is measured and wrapped first; one word is picked as its hero, set large in the // middle, and the rest are pushed out around it to places where nothing overlaps. Every word then eases toward // what the clock says it should be (waiting, sung, passed), frame by frame, and drifts outward once sung. // // Changed from Folia: React became a plain renderer; the text is measured and wrapped with a canvas instead of // pretext (same greedy breaking; CJK may break between any two characters, closing punctuation stays with the // character before it); the settings are Folia's (font scale, width, motion, glow). import { resolveThemeFontWeight, type Line, type Theme, type Word } from '../types'; import { colorWithAlpha, mixColors, resolveWordColor } from '../color'; import { buildWordGraphemeTimings, isCJK, segmentTextWords, splitGraphemes, type GraphemeTiming } from '../lyrics/graphemes'; import { getLineTransitionTiming, type LineTransitionTiming } from '../lyrics/renderHints'; import { isInterludeLine } from '../lyrics/timeline'; import type { StyleContext, StyleRenderer } from './registry'; const ACTIVE_PULSE_FREQUENCY = 10; const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value)); const mix = (from: number, to: number, amount: number) => from + (to - from) * amount; const easeOutCubic = (value: number) => 1 - Math.pow(1 - clamp(value, 0, 1), 3); const easeInOutQuad = (value: number) => { const normalized = clamp(value, 0, 1); return normalized < 0.5 ? 2 * normalized * normalized : 1 - Math.pow(-2 * normalized + 2, 2) / 2; }; // ---- Timing: what each word and the whole line should look like at a moment of the song ------------------- interface LineTiming { renderHints: NonNullable | null; lineRenderEndTime: number; wordRevealMode: 'normal' | 'fast' | 'instant'; lastWordEndTime: number; linePassHold: number; transitionTiming: LineTransitionTiming; } const resolveLineRenderTiming = (line: Line): LineTiming => { const renderHints = line.renderHints ?? null; const wordRevealMode = renderHints?.wordRevealMode ?? 'normal'; const lastWord = line.words[line.words.length - 1]; const rawDuration = renderHints?.rawDuration ?? Math.max(line.endTime - line.startTime, 0); const transitionTiming = getLineTransitionTiming(rawDuration, renderHints?.lineTransitionMode ?? 'normal', wordRevealMode); return { renderHints, lineRenderEndTime: renderHints?.renderEndTime ?? line.endTime, wordRevealMode, lastWordEndTime: lastWord?.endTime ?? line.endTime, linePassHold: transitionTiming.linePassHold, transitionTiming, }; }; const getWordStatus = (time: number, lineTiming: LineTiming, word: Word) => { const lookahead = lineTiming.wordRevealMode === 'fast' ? 0.045 : lineTiming.wordRevealMode === 'instant' ? 0 : 0.18; const activeEndTime = lineTiming.wordRevealMode === 'instant' ? lineTiming.lineRenderEndTime : word.endTime; if (time >= word.startTime - lookahead && time <= activeEndTime) return 'active' as const; if (time > activeEndTime) return 'passed' as const; return 'waiting' as const; }; const getWordProgress = (time: number, wordRevealMode: LineTiming['wordRevealMode'], word: Word) => { if (wordRevealMode === 'instant') return time < word.startTime ? 0 : 1; const duration = Math.max(word.endTime - word.startTime, wordRevealMode === 'fast' ? 0.045 : 0.01); return clamp((time - word.startTime) / duration, 0, 1); }; const getKeyframedGlow = (progress: number) => { if (progress <= 0 || progress >= 1) return 0; if (progress < 0.3) return easeOutCubic(progress / 0.3); return 1 - clamp((progress - 0.3) / 0.7, 0, 1); }; const getGlowEnvelope = (time: number, lineTiming: LineTiming, word: Word) => { if (lineTiming.wordRevealMode === 'instant') { if (time < word.startTime || time > lineTiming.lineRenderEndTime) return 0; return getKeyframedGlow(clamp((time - word.startTime) / 0.067, 0, 1)); } if (lineTiming.wordRevealMode === 'fast') { const duration = Math.max(word.endTime - word.startTime, 0.045); if (time < word.startTime) return 0; if (time <= word.endTime) { const progress = clamp((time - word.startTime) / duration, 0, 1); if (progress < 0.14) return easeOutCubic(progress / 0.14); if (progress < 0.82) return 1; return mix(1, 0.92, (progress - 0.82) / 0.18); } return Math.pow(1 - clamp((time - word.endTime) / 0.14, 0, 1), 2); } const duration = Math.max(word.endTime - word.startTime, 0.1); if (time < word.startTime) return 0; if (time <= word.endTime) { const progress = clamp((time - word.startTime) / duration, 0, 1); if (progress < 0.18) return easeOutCubic(progress / 0.18); if (progress < 0.9) return 1; return mix(1, 0.9, (progress - 0.9) / 0.1); } return 0.9 * Math.pow(1 - clamp((time - word.endTime) / 0.9, 0, 1), 2); }; const getCharGlow = (time: number, word: Word, glyphIndex: number, glyphCount: number, timings: GraphemeTiming[]) => { const duration = Math.max(word.endTime - word.startTime, 0.1); const singleDuration = duration / Math.max(glyphCount, 1); const timing = timings[glyphIndex]; const charDuration = timing ? Math.max(timing.endTime - timing.startTime, 0.001) : singleDuration; const charStartTime = timing?.startTime ?? (word.startTime + singleDuration * glyphIndex); const elapsed = time - charStartTime; const activeGlow = elapsed <= 0 ? 0 : getKeyframedGlow(elapsed / (charDuration * 6)); if (time <= word.endTime) return activeGlow; return activeGlow * Math.pow(1 - clamp((time - word.endTime) / 0.9, 0, 1), 2); }; const getBodyMix = (time: number, lineTiming: LineTiming, word: Word) => { if (lineTiming.wordRevealMode === 'instant') { if (time < word.startTime) return 0; return time <= lineTiming.lineRenderEndTime ? 1 : 0; } if (time < word.startTime) return 0; if (time <= word.endTime) return getWordProgress(time, lineTiming.wordRevealMode, word); return 1 - clamp((time - word.endTime) / (lineTiming.wordRevealMode === 'fast' ? 0.12 : 0.8), 0, 1); }; const getLineEnvelope = (time: number, line: Line, lineTiming: LineTiming) => { const renderHints = lineTiming.renderHints; const lineEndTime = lineTiming.lineRenderEndTime; const linePassStart = Math.max(lineTiming.lastWordEndTime, line.startTime) + lineTiming.linePassHold; if (renderHints?.lineTransitionMode === 'none') return { opacity: 1, scale: 1, blur: 0 }; const { enterDuration, exitDuration } = lineTiming.transitionTiming; if (renderHints?.lineTransitionMode === 'fast') { const exitStart = Math.max(line.startTime + enterDuration + 0.01, linePassStart, lineEndTime - exitDuration); const enterProgress = easeOutCubic(clamp((time - line.startTime) / enterDuration, 0, 1)); let opacity = mix(0.65, 1, enterProgress); let scale = mix(0.97, 1, enterProgress); let blur = mix(4, 0, enterProgress); const exitProgress = easeOutCubic(clamp((time - exitStart) / exitDuration, 0, 1)); if (exitProgress > 0) { opacity = mix(opacity, 0, exitProgress); scale = mix(scale, 1.03, exitProgress); blur = Math.max(blur, mix(0, 6, exitProgress)); } return { opacity: clamp(opacity, 0, 1), scale, blur }; } const preEnter = Math.min(0.1, enterDuration * 0.35); const enterProgress = easeOutCubic(clamp((time - (line.startTime - preEnter)) / (enterDuration + preEnter), 0, 1)); let opacity = mix(0, 1, enterProgress); let scale = mix(0.9, 1, enterProgress); let blur = mix(10, 0, enterProgress); const exitStart = Math.max(linePassStart, lineEndTime - exitDuration); const exitProgress = easeOutCubic(clamp((time - exitStart) / exitDuration, 0, 1)); if (exitProgress > 0) { opacity *= 1 - exitProgress; scale = mix(scale, 1.1, exitProgress); blur = Math.max(blur, mix(0, 20, exitProgress)); } return { opacity: clamp(opacity, 0, 1), scale, blur }; }; const getPassedDrift = (time: number, word: Word) => (time <= word.endTime ? 0 : easeInOutQuad(clamp((time - word.endTime) / 5, 0, 1))); const buildDomTextShadow = (color: string, intensity: number) => { const glow = clamp(intensity, 0, 1.6); if (glow <= 0.01) return 'none'; return [ `0 0 40px ${colorWithAlpha(color, Math.min(0.98, glow))}`, `0 0 40px ${colorWithAlpha(color, Math.min(0.92, glow * 0.92))}`, `0 0 40px ${colorWithAlpha(color, Math.min(0.35, glow * 0.26))}`, ].join(', '); }; // ---- Layout: measure and wrap the line, cut it into word fragments, give each a place ---------------------- interface WrappedLine { start: number; end: number; width: number; } const CLOSING = /^[,。!?、:;)」』】》〉〕]…,.!?;:)\]}'"’”]+$/u; const OPENING = /^[(「『【《〈〔[([{‘“]+$/u; /** Greedy wrapping over unbreakable runs of graphemes, widths from the canvas. */ const wrapLine = (text: string, graphemes: string[], measure: (text: string) => number, maxWidth: number): WrappedLine[] => { // Runs that must stay together, as [start, end) grapheme offsets. const runs: Array<{ start: number; end: number; space: boolean }> = []; let cursor = 0; for (const part of segmentTextWords(text)) { const count = splitGraphemes(part.segment).length; if (count === 0) continue; const space = /^\s+$/.test(part.segment); const previous = runs[runs.length - 1]; if (!space && previous && !previous.space && (CLOSING.test(part.segment) || OPENING.test(graphemes.slice(previous.start, previous.end).join('')))) { previous.end += count; } else if (!space && part.isWordLike && isCJK(part.segment) && count > 1) { for (let index = 0; index < count; index += 1) runs.push({ start: cursor + index, end: cursor + index + 1, space: false }); } else { runs.push({ start: cursor, end: cursor + count, space }); } cursor += count; } const lines: WrappedLine[] = []; const slice = (start: number, end: number) => graphemes.slice(start, end).join(''); let lineStart = -1; let lineEnd = -1; const flush = () => { if (lineStart < 0) return; lines.push({ start: lineStart, end: lineEnd, width: measure(slice(lineStart, lineEnd)) }); lineStart = -1; }; for (const run of runs) { // A line never starts with a space, and a space at its end hangs outside it. if (run.space) { continue; } if (lineStart < 0) { lineStart = run.start; lineEnd = run.end; continue; } if (measure(slice(lineStart, run.end)) <= maxWidth) { lineEnd = run.end; } else { flush(); lineStart = run.start; lineEnd = run.end; } } flush(); return lines.length ? lines : [{ start: 0, end: graphemes.length, width: measure(text) }]; }; interface WordRange { wordIndex: number; word: Word; start: number; end: number; color: string; graphemeTimings: GraphemeTiming[]; } interface WordFragment { wordIndex: number; word: Word; text: string; color: string; startX: number; endX: number; fragmentStartInWord: number; wordGraphemeCount: number; wordGraphemeTimings: GraphemeTiming[]; fragmentIndexInWord: number; isPrimaryFragment: boolean; isSplitAcrossLines: boolean; } interface WordPlacement { id: string; word: Word; text: string; color: string; x: number; y: number; width: number; height: number; rotate: number; scale: number; passedRotate: number; passedDriftX: number; passedDriftY: number; fragmentStartInWord: number; wordGraphemeCount: number; wordGraphemeTimings: GraphemeTiming[]; isInterlude: boolean; glyphs: string[]; cjk: boolean; ascent?: number; } /** Each lyric word found again in the line's graphemes, in order. */ const findWordRanges = (line: Line, graphemes: string[], theme: Theme): WordRange[] => { const ranges: WordRange[] = []; let cursor = 0; line.words.forEach((word, wordIndex) => { const target = splitGraphemes(word.text); let start = -1; for (let i = cursor; i <= graphemes.length - target.length; i++) { let isMatch = true; for (let j = 0; j < target.length; j++) { if (graphemes[i + j] !== target[j]) { isMatch = false; break; } } if (isMatch) { start = i; break; } } if (start === -1) start = clamp(cursor, 0, graphemes.length); const end = clamp(start + target.length, start, graphemes.length); ranges.push({ wordIndex, word, start, end, color: resolveWordColor(word.text, theme.wordColors, theme.accentColor), graphemeTimings: buildWordGraphemeTimings(word) }); cursor = end; }); return ranges; }; type LineView = { width: number; fragments: WordFragment[] }; const buildLineFragments = (graphemes: string[], wrapped: WrappedLine[], ranges: WordRange[], measure: (text: string) => number): LineView[] => { // A wrapped line can cut straight through a lyric word, so fragments are built per wrapped line first. const countByWord = new Map(); const views = wrapped.map((line) => { const fragments = ranges.flatMap((range) => { if (range.end <= line.start || range.start >= line.end) return []; const fragmentStart = Math.max(range.start, line.start); const fragmentEnd = Math.min(range.end, line.end); countByWord.set(range.wordIndex, (countByWord.get(range.wordIndex) ?? 0) + 1); return [{ wordIndex: range.wordIndex, word: range.word, text: graphemes.slice(fragmentStart, fragmentEnd).join(''), color: range.color, startX: measure(graphemes.slice(line.start, fragmentStart).join('')), endX: measure(graphemes.slice(line.start, fragmentEnd).join('')), fragmentStartInWord: fragmentStart - range.start, wordGraphemeCount: Math.max(range.end - range.start, 1), wordGraphemeTimings: range.graphemeTimings, fragmentIndexInWord: 0, isPrimaryFragment: true, isSplitAcrossLines: false, }]; }); return { width: line.width, fragments }; }); const seen = new Map(); for (const view of views) { for (const fragment of view.fragments) { const index = seen.get(fragment.wordIndex) ?? 0; seen.set(fragment.wordIndex, index + 1); fragment.fragmentIndexInWord = index; fragment.isPrimaryFragment = index === 0; fragment.isSplitAcrossLines = (countByWord.get(fragment.wordIndex) ?? 1) > 1; } } return views; }; /** The one word of a line that is set large: long, and near the middle. */ const buildEmphasisMap = (lineData: LineView[], isInterlude: boolean) => { const emphasisMap = new Map(); if (isInterlude) return emphasisMap; const primaryFragments = lineData.flatMap((view) => view.fragments).filter((fragment) => fragment.isPrimaryFragment); // A word split across wrapped lines is not a candidate: its pieces would all take the centre and stack. const candidates = primaryFragments .filter((fragment) => !fragment.isSplitAcrossLines && fragment.text.trim().length > 0) .map((fragment) => { const graphemeCount = Math.max(fragment.wordGraphemeCount, splitGraphemes(fragment.word.text).length, 1); const semanticWeight = isCJK(fragment.word.text) ? 0.18 : Math.min(graphemeCount * 0.08, 0.36); const centerBias = 1 - Math.abs(fragment.wordIndex - (primaryFragments.length - 1) / 2) / Math.max(primaryFragments.length, 1); return { fragment, score: semanticWeight + centerBias * 0.18 }; }) .sort((a, b) => b.score - a.score); const hero = candidates[0]; if (hero) emphasisMap.set(hero.fragment.wordIndex, 1.46 * (1 + clamp(hero.score - 0.48, 0, 0.52))); return emphasisMap; }; const buildWordPlacements = ( lineData: LineView[], fontPx: number, lineHeight: number, maxWidth: number, animationIntensity: Theme['animationIntensity'], seed: number, isInterlude: boolean, ): WordPlacement[] => { // From here on fragments are no longer slices of text but animated objects: geometry and per-state motion. const totalHeight = Math.max(lineData.length, 1) * lineHeight; const baseMargin = animationIntensity === 'calm' ? 4 : 6; const baseScale = animationIntensity === 'chaotic' ? 1.02 : animationIntensity === 'calm' ? 1 : 1.01; const emphasisMap = buildEmphasisMap(lineData, isInterlude); const heroWordIndex = [...emphasisMap.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null; const placements: WordPlacement[] = []; const occupied: Array<{ left: number; top: number; right: number; bottom: number }> = []; const overlapWith = (left: number, top: number, right: number, bottom: number) => { let overlapArea = 0; for (const rect of occupied) { const overlapWidth = Math.max(0, Math.min(right, rect.right) - Math.max(left, rect.left)); const overlapHeight = Math.max(0, Math.min(bottom, rect.bottom) - Math.max(top, rect.top)); if (overlapWidth > 0 && overlapHeight > 0) overlapArea += overlapWidth * overlapHeight; } return overlapArea; }; const pushPlacementRect = (left: number, top: number, width: number, height: number, padding: number) => { occupied.push({ left: left - padding, top: top - height - padding, right: left + width + padding, bottom: top + padding }); }; const placementPlans = lineData.flatMap((view, lineIndex) => { const lineLeft = -view.width / 2; const baselineY = -totalHeight / 2 + fontPx + lineIndex * lineHeight; return view.fragments.map((fragment, fragmentIndex) => { const emphasis = emphasisMap.get(fragment.wordIndex) ?? 1; const width = Math.max(fragment.endX - fragment.startX, fontPx * 0.18); const scale = emphasis > 1 ? baseScale * emphasis : baseScale; const height = fontPx * scale * 0.95; return { fragment, lineIndex, fragmentIndex, emphasis, width, height, scale, baseX: lineLeft + fragment.startX, baseY: baselineY, collisionWidth: width * scale * (emphasis > 1 ? 1.48 : 1.26), collisionHeight: height * (emphasis > 1 ? 1.36 : 1.24), padding: baseMargin + (emphasis > 1 ? 10 : 2), }; }); }).sort((a, b) => { const emphasisDelta = b.emphasis - a.emphasis; if (Math.abs(emphasisDelta) > 0.001) return emphasisDelta; if (a.lineIndex !== b.lineIndex) return a.lineIndex - b.lineIndex; return a.fragment.startX - b.fragment.startX; }); const heroPlan = heroWordIndex === null ? null : placementPlans.find((plan) => plan.fragment.wordIndex === heroWordIndex) ?? null; const heroMetrics = heroPlan ? { centerX: (heroPlan.width * heroPlan.scale) / 2, centerY: -heroPlan.height * 0.46, width: heroPlan.width * heroPlan.scale } : null; placementPlans.forEach((plan) => { const { fragment, lineIndex, fragmentIndex, emphasis, width, height, scale, collisionWidth, collisionHeight, padding } = plan; const wordSeed = seed + fragment.wordIndex * 17 + lineIndex * 31 + fragmentIndex * 13; const random = (offset: number) => { const x = Math.sin(wordSeed + offset) * 10000; return x - Math.floor(x); }; const passedRotate = (random(3) - 0.5) * (animationIntensity === 'chaotic' ? 20 : 12); const step = Math.max(10, Math.round(fontPx * 0.14)); const maxRadius = emphasis > 1 ? Math.max(20, lineHeight * 0.5) : Math.max(lineHeight * 2.2, collisionWidth * 0.75, 56); // The hero takes the centre; the others start where the wrapped text put them. let preferredX = emphasis > 1 ? -width / 2 : plan.baseX; let preferredY = emphasis > 1 ? 0 : plan.baseY; if (!isInterlude && emphasis <= 1 && heroMetrics) { // Pushed out of the hero's way along the line from its centre. const wordCenterX = preferredX + width / 2; const wordCenterY = preferredY - height * 0.46; let dx = wordCenterX - heroMetrics.centerX; let dy = wordCenterY - heroMetrics.centerY; const distance = Math.hypot(dx, dy); if (distance < 1) { dx = preferredX >= 0 ? 1 : -1; dy = lineIndex % 2 === 0 ? -0.65 : 0.65; } const minHeroSeparation = heroMetrics.width * 0.34 + width * 0.52 + padding * 2; if (distance < minHeroSeparation) { const normalizedDistance = Math.max(Math.hypot(dx, dy), 1); const push = minHeroSeparation - distance; preferredX += (dx / normalizedDistance) * push; preferredY += (dy / normalizedDistance) * push * 0.92; } } const horizontalMin = (-maxWidth / 2) - 72; const horizontalMax = (maxWidth / 2) + 72; const verticalMin = -Math.max(totalHeight * 0.9, lineHeight * 1.6); const verticalMax = Math.max(totalHeight * 0.9, lineHeight * 1.45); let chosenX = preferredX; let chosenY = preferredY; let found = false; let bestFallback = { x: preferredX, y: preferredY, score: Number.POSITIVE_INFINITY }; const baseAngle = heroMetrics && emphasis <= 1 ? Math.atan2(preferredY, preferredX + width / 2) : 0; // Search outward in rings for the nearest place that touches nothing already placed. for (let radius = 0; radius <= maxRadius && !found; radius += step) { const sampleCount = radius === 0 ? 1 : emphasis > 1 ? 8 : Math.max(12, Math.round((Math.PI * 2 * radius) / Math.max(step * 1.1, 10))); for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) { const angle = baseAngle + (sampleIndex / sampleCount) * Math.PI * 2; const dx = radius === 0 ? 0 : Math.cos(angle) * radius; const dy = radius === 0 ? 0 : Math.sin(angle) * radius * (emphasis > 1 ? 0.8 : 0.92); const left = preferredX + dx - padding; const top = preferredY + dy - collisionHeight - padding; const right = left + collisionWidth + padding * 2; const bottom = top + collisionHeight + padding * 2; if (!(left >= horizontalMin && right <= horizontalMax && top >= verticalMin && bottom <= verticalMax)) continue; const overlapArea = overlapWith(left, top, right, bottom); const score = overlapArea * 2.2 + Math.hypot(dx, dy); if (score < bestFallback.score) bestFallback = { x: preferredX + dx, y: preferredY + dy, score }; if (overlapArea === 0) { chosenX = preferredX + dx; chosenY = preferredY + dy; found = true; break; } } } if (!found) { chosenX = bestFallback.x; chosenY = bestFallback.y; } pushPlacementRect(chosenX, chosenY, collisionWidth, collisionHeight, padding); // Once sung, a word drifts a little further out from the middle. const outwardX = chosenX + width / 2; const outwardY = chosenY - height * 0.46; const outwardLength = Math.max(Math.hypot(outwardX, outwardY), 1); const driftAmount = isInterlude ? 3 + random(6) * 3 : emphasis > 1 ? 4 + random(6) * 4 : animationIntensity === 'chaotic' ? 8 + random(6) * 9 : 5 + random(6) * 6; placements.push({ id: `${fragment.word.text}-${fragment.wordIndex}-${lineIndex}-${fragmentIndex}-${fragment.fragmentIndexInWord}`, word: fragment.word, text: fragment.text, color: fragment.color, x: chosenX, y: chosenY, width, height, rotate: 0, scale, passedRotate, passedDriftX: (outwardX / outwardLength) * driftAmount + (random(7) - 0.5) * 2.4, passedDriftY: (outwardY / outwardLength) * driftAmount * 0.72 + (random(8) - 0.5) * 2, fragmentStartInWord: fragment.fragmentStartInWord, wordGraphemeCount: fragment.wordGraphemeCount, wordGraphemeTimings: fragment.wordGraphemeTimings, isInterlude, glyphs: splitGraphemes(fragment.text), cjk: isCJK(fragment.text), }); }); return placements; }; interface PreparedLine { font: string; fontPx: number; placements: WordPlacement[]; timing: LineTiming; } const chooseFontPx = (width: number, line: Line) => { const graphemeCount = splitGraphemes(line.fullText).length || 1; const wordCount = line.words.length || 1; const widthBase = clamp(width * 0.086, 34, 94); const lengthPenalty = graphemeCount > 12 ? Math.min((graphemeCount - 12) * 1.8, 34) : 0; const densityPenalty = wordCount > 7 ? Math.min((wordCount - 7) * 1.5, 18) : 0; return clamp(widthBase - lengthPenalty - densityPenalty, 28, 104); }; // ---- Drawing: every word eases toward its target each frame; the DOM is written only where it changed ------ interface WordNodes { outer: HTMLDivElement; inner: HTMLDivElement; body: HTMLSpanElement; glow: HTMLSpanElement; glyphSpans: HTMLSpanElement[]; glyphShadows: string[]; written: Record; frame: number; } interface Animated { x: number; y: number; rotation: number; scale: number; bodyAlpha: number; blur: number; activeMix: number; glowAlpha: number; } const createWordNodes = (texts: string[]): WordNodes => { const outer = document.createElement('div'); outer.className = 'folia-cadenza__word'; const inner = document.createElement('div'); inner.className = 'folia-cadenza__inner'; const body = document.createElement('span'); body.className = 'folia-cadenza__body'; const glow = document.createElement('span'); glow.className = 'folia-cadenza__glow'; const glyphSpans = texts.map((text) => { const span = document.createElement('span'); span.textContent = text; glow.append(span); return span; }); inner.append(body, glow); outer.append(inner); return { outer, inner, body, glow, glyphSpans, glyphShadows: [], written: {}, frame: -1 }; }; const STATUS_DRAW_ORDER = ['waiting', 'passed', 'active'] as const; export const createCadenza = (context: StyleContext): StyleRenderer => { const { layer, theme, width, height } = context; const { fontScale: FONT_SCALE, widthRatio: WIDTH_RATIO, motionAmount: MOTION_AMOUNT, glowIntensity } = context.tunings.cadenza; const GLOW_INTENSITY = Math.max(glowIntensity, 0); const lineLayer = document.createElement('div'); lineLayer.className = 'folia-cadenza'; const overlay = document.createElement('div'); overlay.className = 'folia-cadenza__overlay'; const canvas = document.createElement('canvas'); canvas.className = 'folia-cadenza__canvas'; lineLayer.append(overlay, canvas); layer.append(lineLayer); const canvasContext = canvas.getContext('2d'); const prepared = new Map(); const nodes = new Map(); const animated = new Map(); let activeLine: Line | null = null; let frameNumber = 0; let layerWritten = ''; const prepare = (line: Line): PreparedLine | null => { const cached = prepared.get(line); if (cached) return cached; if (!canvasContext || width <= 0 || height <= 0) return null; const fontPx = clamp(chooseFontPx(width, line) * FONT_SCALE, 24, 132); const font = `${resolveThemeFontWeight(theme, 700)} ${fontPx}px ${theme.fontStack}`; canvasContext.font = font; const measure = (text: string) => (text ? canvasContext.measureText(text).width : 0); const text = line.fullText; const graphemes = splitGraphemes(text); const lineHeight = Math.round(fontPx * (isCJK(text) ? 1.22 : 1.1)); const availableWidth = Math.max(width - 48, 120); const minWidth = Math.min(220, availableWidth); const wrapCompression = graphemes.length > 12 ? clamp(0.92 - (graphemes.length - 12) * 0.018, 0.62, 0.92) : 0.92; const maxWidth = clamp(Math.min(width * WIDTH_RATIO * wrapCompression, 820), minWidth, availableWidth); const wrapped = wrapLine(text, graphemes, measure, maxWidth); const fragments = buildLineFragments(graphemes, wrapped, findWordRanges(line, graphemes, theme), measure); const state: PreparedLine = { font, fontPx, placements: buildWordPlacements(fragments, fontPx, lineHeight, maxWidth, theme.animationIntensity, line.startTime * 1000, isInterludeLine(line)), timing: resolveLineRenderTiming(line), }; prepared.set(line, state); return state; }; const clearWords = () => { for (const entry of nodes.values()) entry.outer.remove(); nodes.clear(); }; const writeLayer = (opacity: number, blur: number, scale: number, perspective: number) => { const next = `${opacity}|${blur.toFixed(2)}|${scale}|${perspective}`; if (next === layerWritten) return; layerWritten = next; lineLayer.style.opacity = String(opacity); lineLayer.style.filter = blur > 0.05 ? `blur(${blur.toFixed(2)}px)` : 'none'; lineLayer.style.transform = `scale(${scale})`; lineLayer.style.perspective = `${perspective}px`; }; const set = (entry: WordNodes, key: string, value: string, apply: (value: string) => void) => { if (entry.written[key] === value) return; entry.written[key] = value; apply(value); }; const draw = (time: number, delta: number) => { if (!canvasContext) return; const dpr = Math.min(window.devicePixelRatio || 1, 2); const pixelWidth = Math.floor(Math.max(width, 1) * dpr); const pixelHeight = Math.floor(Math.max(height, 1) * dpr); if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) { canvas.width = pixelWidth; canvas.height = pixelHeight; } canvasContext.setTransform(dpr, 0, 0, dpr, 0, 0); canvasContext.clearRect(0, 0, width, height); const state = activeLine ? prepare(activeLine) : null; if (!activeLine || !state) { writeLayer(0, 0, 1, 1000); clearWords(); return; } const line = activeLine; const lineTiming = state.timing; const envelope = getLineEnvelope(time, line, lineTiming); const wordRevealMode = lineTiming.wordRevealMode; const instant = wordRevealMode === 'instant'; const lineSeed = Math.abs(Math.sin(line.startTime * 997.1)); const energy = clamp(context.audio().power / 255, 0, 1); const motionEnergy = energy * MOTION_AMOUNT; const focusY = height * 0.42 + Math.sin(time * 2.3) * (3 + motionEnergy * 8); writeLayer(envelope.opacity, envelope.blur, envelope.scale, theme.animationIntensity === 'chaotic' ? 500 + Math.round(lineSeed * 500) : 1000); canvasContext.font = state.font; canvasContext.textBaseline = 'alphabetic'; frameNumber += 1; const dt = clamp(delta, 1 / 240, 0.05); const transformAmount = 1 - Math.exp(-11 * dt); const visualAmount = 1 - Math.exp(-14 * dt); const glowAmount = 1 - Math.exp(-16 * dt); // Words are drawn waiting first and active last, so the word being sung sits on top. const byStatus: Record<(typeof STATUS_DRAW_ORDER)[number], WordPlacement[]> = { waiting: [], passed: [], active: [] }; for (const placement of state.placements) byStatus[getWordStatus(time, lineTiming, placement.word)].push(placement); let placementIndex = -1; for (const status of STATUS_DRAW_ORDER) { for (const placement of byStatus[status]) { placementIndex += 1; const progress = getWordProgress(time, wordRevealMode, placement.word); const passedAlpha = instant ? 0 : theme.animationIntensity === 'chaotic' ? 0.9 : 0.82; const pulse = status === 'active' && !instant ? 1 + Math.sin(time * ACTIVE_PULSE_FREQUENCY + placement.word.startTime * 5) * 0.04 * MOTION_AMOUNT : 1; const drift = instant ? 0 : getPassedDrift(time, placement.word); const targetScale = status === 'waiting' ? instant ? placement.scale : Math.max(placement.scale * 0.5, 0.5) : status === 'active' ? instant ? placement.scale : placement.scale * 1.3 * pulse : placement.scale; const targetRotation = status === 'waiting' ? instant ? placement.rotate : placement.rotate + 20 : status === 'passed' && !instant ? placement.rotate + placement.passedRotate * drift : placement.rotate; const targetX = width / 2 + placement.x + Math.sin(time * 1.2 + placementIndex * 0.6) * motionEnergy * 4 + (status === 'passed' ? placement.passedDriftX * drift : 0); const targetY = focusY + placement.y + Math.cos(time * 1.5 + placementIndex * 0.4) * motionEnergy * 2.5 + (status === 'passed' ? placement.passedDriftY * drift : 0); const targetBodyAlpha = status === 'waiting' ? 0 : status === 'active' ? 1 : passedAlpha; const targetBlur = status === 'waiting' && !instant ? 10 : 0; const targetActiveMix = getBodyMix(time, lineTiming, placement.word); const targetGlowAlpha = getGlowEnvelope(time, lineTiming, placement.word); let state2 = animated.get(placement.id); if (!state2) { const asActive = instant && time >= placement.word.startTime; state2 = { x: width / 2 + placement.x, y: focusY + placement.y, rotation: asActive ? targetRotation : targetRotation + 16, scale: asActive ? targetScale : Math.max(placement.scale * 0.5, 0.5), bodyAlpha: asActive ? targetBodyAlpha : 0, blur: asActive ? targetBlur : 10, activeMix: asActive ? targetActiveMix : 0, glowAlpha: asActive ? targetGlowAlpha : 0, }; animated.set(placement.id, state2); } state2.x = mix(state2.x, targetX, transformAmount); state2.y = mix(state2.y, targetY, transformAmount); state2.rotation = mix(state2.rotation, targetRotation, transformAmount); state2.scale = mix(state2.scale, targetScale, transformAmount); state2.bodyAlpha = mix(state2.bodyAlpha, targetBodyAlpha, visualAmount); state2.blur = mix(state2.blur, targetBlur, visualAmount); state2.activeMix = mix(state2.activeMix, targetActiveMix, visualAmount); state2.glowAlpha = mix(state2.glowAlpha, targetGlowAlpha, glowAmount); if (state2.bodyAlpha < 0.015 && state2.glowAlpha < 0.015) continue; const visualWidth = placement.width * state2.scale; const visualHeight = placement.height * state2.scale; if (status === 'active' && !placement.isInterlude && line.isChorus) { // A chorus word sends out a ring as it is sung. const scaledLeft = state2.x - (visualWidth - placement.width) / 2; canvasContext.strokeStyle = colorWithAlpha(placement.color, 0.45 * (1 - progress) * state2.bodyAlpha); canvasContext.lineWidth = 1.2; canvasContext.beginPath(); canvasContext.arc(scaledLeft + visualWidth / 2, state2.y - visualHeight * 0.42, Math.max(visualWidth, visualHeight * 1.08) * (0.55 + progress * 0.45), 0, Math.PI * 2); canvasContext.stroke(); } const splitGlow = wordRevealMode === 'normal' && !placement.cjk && placement.glyphs.length > 1; let entry = nodes.get(placement.id); if (!entry) { entry = createWordNodes(splitGlow ? placement.glyphs : [placement.text]); nodes.set(placement.id, entry); overlay.append(entry.outer); } entry.frame = frameNumber; const own = entry; placement.ascent ??= canvasContext.measureText(placement.text).actualBoundingBoxAscent; const ascent = placement.ascent || state.fontPx * 0.78; set(own, 'outer', `translate3d(${(state2.x + placement.width / 2).toFixed(2)}px, ${(state2.y - placement.height * 0.42).toFixed(2)}px, 0) rotate(${state2.rotation.toFixed(3)}deg) scale(${state2.scale.toFixed(4)})`, (value) => { own.outer.style.transform = value; }); set(own, 'font', state.font, (value) => { own.inner.style.font = value; }); set(own, 'inner', `translate3d(${(-placement.width / 2).toFixed(2)}px, ${(placement.height * 0.42 - ascent).toFixed(2)}px, 0)`, (value) => { own.inner.style.transform = value; }); set(own, 'text', placement.text, (value) => { own.body.textContent = value; }); set(own, 'color', mixColors(theme.primaryColor, placement.color, state2.activeMix), (value) => { own.body.style.color = value; }); set(own, 'opacity', state2.bodyAlpha.toFixed(3), (value) => { own.body.style.opacity = value; }); set(own, 'filter', state2.blur > 0.05 ? `blur(${state2.blur.toFixed(2)}px)` : 'none', (value) => { own.body.style.filter = value; }); const glowScale = clamp(state2.glowAlpha, 0, 1) * GLOW_INTENSITY; own.glyphSpans.forEach((span, glyphIndex) => { const intensity = splitGlow ? getCharGlow(time, placement.word, placement.fragmentStartInWord + glyphIndex, Math.max(placement.wordGraphemeCount, placement.glyphs.length), placement.wordGraphemeTimings) * glowScale : targetGlowAlpha * glowScale; const shadow = buildDomTextShadow(placement.color, intensity); if (own.glyphShadows[glyphIndex] === shadow) return; own.glyphShadows[glyphIndex] = shadow; span.style.textShadow = shadow; }); } } for (const [key, entry] of nodes) { if (entry.frame === frameNumber) continue; entry.outer.remove(); nodes.delete(key); } }; return { setLine(line) { activeLine = line; animated.clear(); clearWords(); if (line) prepare(line); }, frame(time, delta) { draw(time, delta); }, destroy() { clearWords(); lineLayer.remove(); }, }; };