// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2), // src/components/visualizer/tilt/VisualizerTilt.tsx: 倾诉. // A lyric line is set as one to four display lines, revealed one after another as they are sung. Now and then // one of them is "tilted": light italic in the accent colour, its letters stepping up and down in turn. Every // letter swells a little as the voice passes it and keeps a trace of that afterwards. // // Changed from Folia: React became a plain renderer; the stage's box stands in for the window; widths are // measured on a canvas instead of with pretext; the settings are Folia's (split and tilt probabilities, colour // scheme). import { resolveThemeFontWeight, type Line, type StageTunings, type Theme } from '../types'; import { measureTextWidth } from '../glowWord'; import { getLineRenderEndTime } from '../lyrics/renderHints'; import { splitIntoSentences } from '../lyrics/sentenceLayout'; import { Motion, type Ease } from '../motion'; import type { StyleContext, StyleRenderer } from './registry'; const CHAR_REF_LENGTH = 20; const LOG_OFFSET = 4; const LINE_THRESHOLDS = [0.45, 1.05, 1.7]; const RESPLIT_THRESHOLD = 1.6; const SCALE_FLOOR_NORMAL = 0.55; const SCALE_FLOOR_TILT = 0.5; const EASE: Ease = [0.25, 0.46, 0.45, 0.94]; const SPACE = /^\s+$/; const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' }); const graphemesOf = (text: string) => Array.from(graphemeSegmenter.segment(text), (part) => part.segment); const seededRandom = (seed: number, offset: number): number => { const x = Math.sin(seed * 1000 + offset) * 10000; return x - Math.floor(x); }; const determineLineCount = (charCount: number, seed: number, splitProbability: number): number => { const normalized = Math.log(charCount + LOG_OFFSET) / Math.log(CHAR_REF_LENGTH + LOG_OFFSET); const jitter = seededRandom(seed, 1) * 0.6 + 0.7; const score = normalized * jitter * splitProbability; if (score < LINE_THRESHOLDS[0]) return 1; if (score < LINE_THRESHOLDS[1]) return 2; if (score < LINE_THRESHOLDS[2]) return 3; return 4; }; interface TiltSegment { text: string; isTilt: boolean; isShortLastLine: boolean; charOffset: number; } interface CharTiming { startTime: number; endTime: number; } const findSegmentWordRange = (charOffset: number, segmentText: string, fullText: string, words: Line['words']) => { const segmentStart = charOffset; if (segmentStart < 0 || segmentStart >= fullText.length) return { startWordIndex: 0, endWordIndex: words.length }; const segmentEnd = segmentStart + segmentText.length; let fullTextPos = 0; let startWordIndex = 0; let endWordIndex = words.length; for (let wi = 0; wi < words.length; wi++) { const wordText = words[wi].text; const wordFullStart = fullText.indexOf(wordText, fullTextPos); if (wordFullStart === -1) { fullTextPos += wordText.length; continue; } const wordFullEnd = wordFullStart + wordText.length; if (wordFullStart <= segmentStart && wordFullEnd > segmentStart) startWordIndex = wi; if (wordFullStart < segmentEnd && wordFullEnd >= segmentEnd) { endWordIndex = wi + 1; break; } fullTextPos = wordFullEnd; } return { startWordIndex, endWordIndex }; }; /** A time for every letter of a display line that is not a space, from the words it covers. */ const buildCharTimings = (segment: TiltSegment, segmentStartTime: number, segmentEndTime: number, line: Line): CharTiming[] => { const graphemes = graphemesOf(segment.text); const nonSpaceCount = graphemes.filter((grapheme) => !SPACE.test(grapheme)).length; if (nonSpaceCount === 0) return []; const totalDuration = Math.max(segmentEndTime - segmentStartTime, 0.3); const { startWordIndex, endWordIndex } = findSegmentWordRange(segment.charOffset, segment.text, line.fullText, line.words); const timings: CharTiming[] = []; for (const word of line.words.slice(startWordIndex, endWordIndex)) { const wordGraphemes = graphemesOf(word.text).filter((grapheme) => !SPACE.test(grapheme)); if (wordGraphemes.length === 0) continue; const charDuration = Math.max(word.endTime - word.startTime, 0.05) / wordGraphemes.length; for (let index = 0; index < wordGraphemes.length && timings.length < nonSpaceCount; index++) { timings.push({ startTime: word.startTime + index * charDuration, endTime: word.startTime + (index + 1) * charDuration }); } } if (timings.length !== nonSpaceCount) { const avgCharDuration = totalDuration / nonSpaceCount; timings.length = 0; for (let index = 0; index < nonSpaceCount; index++) { timings.push({ startTime: segmentStartTime + index * avgCharDuration, endTime: segmentStartTime + (index + 1) * avgCharDuration }); } } return timings; }; /** 0..1 as the voice passes a letter, then a quarter of that left behind. */ const getCharPulseIntensity = (currentTime: number, { startTime, endTime }: CharTiming): number => { const duration = Math.min(Math.max(Math.max(endTime - startTime, 0.05), 0.2), 0.9); const elapsed = currentTime - startTime; if (elapsed < 0) return 0; if (elapsed <= duration) return Math.sin((elapsed / duration) * Math.PI); const afterElapsed = elapsed - duration; const afterglowRamp = duration * 1.2; if (afterElapsed >= afterglowRamp) return 0.25; return 0.25 * (afterElapsed / afterglowRamp); }; const markShortLastLine = (segments: TiltSegment[]): TiltSegment[] => { if (segments.length < 2) return segments; const last = segments[segments.length - 1]; if (last.isTilt || last.text.trim().length > 2) return segments; const prev = segments[segments.length - 2]; if (last.text.trim().length * 2 <= prev.text.length) segments[segments.length - 1] = { ...last, isShortLastLine: true }; return segments; }; const toSegments = (pieces: string[], tiltIndex: number): TiltSegment[] => { let offset = 0; return pieces.map((text, index) => { const leadingSpaces = text.length - text.trimStart().length; const segment = { text: text.trim(), isTilt: index === tiltIndex, isShortLastLine: false, charOffset: offset + leadingSpaces }; offset += text.length; return segment; }); }; const buildTiltLayout = (fullText: string, lineSeed: number, theme: Theme, stageWidth: number, rem: number, tuning: StageTunings['tilt'], fontScale: number): { segments: TiltSegment[]; scaleMultiplier: number } => { const SPLIT_PROBABILITY = tuning.splitProbability; const TILT_STYLE_PROBABILITY = tuning.tiltStyleProbability; const basePx = Math.max(stageWidth * 0.06875, 5.625 * rem * fontScale); const normalWeight = resolveThemeFontWeight(theme, 400); const tiltWeight = resolveThemeFontWeight(theme, 300); const widthOf = (text: string, tilt: boolean) => measureTextWidth(text, basePx, theme.fontStack, tilt ? tiltWeight : normalWeight, tilt) || text.length * basePx * 0.6; const availableWidth = Math.max(320, stageWidth) * 0.85; const isEllipsisOnly = /^[\s.…·。]+$/.test(fullText.trim()); const pieces = isEllipsisOnly ? [fullText] : splitIntoSentences(fullText, determineLineCount(fullText.trim().length, lineSeed, SPLIT_PROBABILITY), lineSeed); const candidates: number[] = []; pieces.forEach((_, index) => { if (seededRandom(lineSeed, 100 + index) < TILT_STYLE_PROBABILITY) candidates.push(index); }); const tiltIndex = candidates.length > 0 ? candidates[Math.floor(seededRandom(lineSeed, 200) * candidates.length)] : -1; const segments = toSegments(pieces, tiltIndex); const widest = (list: TiltSegment[], tilt: boolean) => Math.max(0, ...list.filter((segment) => segment.isTilt === tilt).map((segment) => widthOf(segment.text, tilt))); const tiltWidth = widest(segments, true); const normalWidth = widest(segments, false); const tiltOverflow = tiltWidth / availableWidth; const normalOverflow = normalWidth / availableWidth; const maxOverflow = Math.max(tiltOverflow, normalOverflow); let scaleMultiplier = 1; if (maxOverflow > 1) { if (maxOverflow >= RESPLIT_THRESHOLD) { // Far too wide: split into more lines before shrinking. const targetWidth = availableWidth * (RESPLIT_THRESHOLD - 0.15); const totalWidth = widthOf(fullText, false); const splits = Math.min(4, Math.max(segments.length + 1, Math.ceil(totalWidth / targetWidth))); if (splits > segments.length) { const resplit = splitIntoSentences(fullText, splits, lineSeed); const picked = resplit.length > 0 && seededRandom(lineSeed, 300) < TILT_STYLE_PROBABILITY ? Math.floor(seededRandom(lineSeed, 301) * resplit.length) : -1; const newSegments = toSegments(resplit, picked); const tilted = newSegments.find((segment) => segment.isTilt); let postScale = 1; if (tilted) { const width = widthOf(tilted.text, true); if (width > availableWidth) postScale = Math.max(SCALE_FLOOR_TILT, availableWidth / width); } else { const width = widest(newSegments, false); if (width > availableWidth) postScale = Math.max(SCALE_FLOOR_NORMAL, availableWidth / width); } return { segments: markShortLastLine(newSegments), scaleMultiplier: postScale }; } } if (tiltOverflow >= normalOverflow && tiltWidth > 0) scaleMultiplier = Math.max(SCALE_FLOOR_TILT, availableWidth / tiltWidth); else if (normalWidth > 0) scaleMultiplier = Math.max(SCALE_FLOOR_NORMAL, availableWidth / normalWidth); } return { segments: markShortLastLine(segments), scaleMultiplier }; }; interface Glyph { el: HTMLSpanElement; motion: Motion<'opacity' | 'y'>; /** Its place among the letters that are not spaces; -1 for a space. */ visual: number; rest: number; pulse: number; y: number; } /** One display line: its own entrance, and letters that come in one after another and swell with the voice. */ class TiltLine { readonly el: HTMLDivElement; #segment: TiltSegment; #motion: Motion<'opacity' | 'y' | 'scale'>; #glyphs: Glyph[] = []; #timings: CharTiming[]; #visible = false; constructor(segment: TiltSegment, theme: Theme, scaleMultiplier: number, stageWidth: number, rem: number, timings: CharTiming[], colorScheme: StageTunings['tilt']['colorScheme']) { this.#segment = segment; this.#timings = timings; const tilt = segment.isTilt; const boost = !tilt && segment.isShortLastLine ? 1.18 : 1; const scale = scaleMultiplier * boost; const tiltFontPx = Math.min(stageWidth * 0.06875 * scaleMultiplier, 5.625 * rem * scaleMultiplier); const yOffset = tiltFontPx / 6; const el = this.el = document.createElement('div'); el.className = tilt ? 'folia-tilt__line folia-tilt__line--tilt' : 'folia-tilt__line'; el.style.fontSize = `clamp(${(3.125 * scale).toFixed(3)}rem, ${(6.875 * scale).toFixed(3)}cqw, ${(5.625 * scale).toFixed(3)}rem)`; const accent = theme.accentColor || theme.primaryColor; const colors = colorScheme === 'swap' ? { normal: accent, tilt: theme.primaryColor } : colorScheme === 'accentAll' ? { normal: accent, tilt: accent } : colorScheme === 'primaryAll' ? { normal: theme.primaryColor, tilt: theme.primaryColor } : { normal: theme.primaryColor, tilt: accent }; el.style.color = tilt ? colors.tilt : colors.normal; el.style.fontWeight = String(resolveThemeFontWeight(theme, tilt ? 300 : 400)); this.#motion = new Motion(tilt ? { opacity: 0, y: 24, scale: 0.92 } : { opacity: 0, y: 20, scale: 1 }, (values) => { el.style.opacity = String(values.opacity); el.style.transform = `translateY(${(values.y as number).toFixed(2)}px) scale(${(values.scale as number).toFixed(4)})`; }); let visual = 0; for (const grapheme of graphemesOf(segment.text)) { const isSpace = SPACE.test(grapheme); const span = document.createElement('span'); span.className = isSpace ? 'folia-tilt__char folia-tilt__char--space' : 'folia-tilt__char'; span.textContent = isSpace ? ' ' : grapheme; el.append(span); // Tilted letters sit alternately above and below the line, and come in from twice as far. const rest = tilt && !isSpace ? (visual % 2 === 0 ? -1 : 1) * yOffset : 0; const glyph: Glyph = { el: span, visual: isSpace ? -1 : visual, rest, pulse: 1, y: rest * 2, motion: undefined as unknown as Glyph['motion'] }; glyph.motion = new Motion({ opacity: 0, y: rest * 2 }, (values) => { span.style.opacity = String(values.opacity); glyph.y = values.y as number; span.style.transform = `translateY(${glyph.y.toFixed(2)}px) scale(${glyph.pulse.toFixed(4)})`; }); this.#glyphs.push(glyph); if (!isSpace) visual += 1; } } setVisible(visible: boolean) { if (visible === this.#visible) return; this.#visible = visible; const tilt = this.#segment.isTilt; void this.#motion.to( visible ? { opacity: 1, y: 0, scale: 1 } : tilt ? { opacity: 0, y: 24, scale: 0.92 } : { opacity: 0, y: 20, scale: 1 }, { duration: tilt ? 0.6 : 0.55, ease: EASE }, ); for (const glyph of this.#glyphs) { void glyph.motion.to( { opacity: visible ? 1 : 0, y: visible ? glyph.rest : glyph.rest * 2 }, { duration: 0.5, delay: visible && glyph.visual >= 0 ? glyph.visual * (tilt ? 0.05 : 0.04) : 0, ease: EASE }, ); } } /** The swell of each letter under the voice. */ pulse(time: number) { if (!this.#visible) return; const amount = this.#segment.isTilt ? 0.18 : 0.15; for (const glyph of this.#glyphs) { const timing = glyph.visual >= 0 ? this.#timings[glyph.visual] : undefined; const next = timing ? 1 + getCharPulseIntensity(time, timing) * amount : 1; if (Math.abs(next - glyph.pulse) < 0.002) continue; glyph.pulse = next; glyph.el.style.transform = `translateY(${glyph.y.toFixed(2)}px) scale(${next.toFixed(4)})`; } } leave() { const tilt = this.#segment.isTilt; return this.#motion.to(tilt ? { opacity: 0, y: -16, scale: 0.95 } : { opacity: 0, y: -12 }, { duration: tilt ? 0.6 : 0.55, ease: EASE }); } destroy() { this.#motion.destroy(); for (const glyph of this.#glyphs) glyph.motion.destroy(); } } interface ShownLine { line: Line; box: HTMLDivElement; slot: HTMLDivElement; fade: Motion<'opacity'>; lines: TiltLine[]; timings: { start: number; end: number }[]; visibleIndex: number; } export const createTilt = (context: StyleContext): StyleRenderer => { const { layer, theme, width, rem } = context; const tuning = context.tunings.tilt; const area = document.createElement('div'); area.className = 'folia-area'; layer.append(area); let shown: ShownLine | null = null; const leaving = new Set(); const build = (line: Line): ShownLine => { const layout = buildTiltLayout(line.fullText, line.startTime, theme, width, rem, tuning, context.fontScale); const timings = layout.segments.map((segment) => { const { startWordIndex, endWordIndex } = findSegmentWordRange(segment.charOffset, segment.text, line.fullText, line.words); const words = line.words.slice(startWordIndex, endWordIndex); return words.length > 0 ? { start: words[0].startTime, end: words[words.length - 1].endTime } : { start: line.startTime, end: getLineRenderEndTime(line) }; }); const slot = document.createElement('div'); slot.className = 'folia-slot'; const box = document.createElement('div'); box.className = 'folia-tilt'; const lines = layout.segments.map((segment, index) => { const tiltLine = new TiltLine(segment, theme, layout.scaleMultiplier * context.fontScale, width, rem, buildCharTimings(segment, timings[index].start, timings[index].end, line), tuning.colorScheme); box.append(tiltLine.el); return tiltLine; }); slot.append(box); area.append(slot); const fade = new Motion({ opacity: 0 }, (values) => { box.style.opacity = String(values.opacity); }); void fade.to({ opacity: 1 }); return { line, box, slot, fade, lines, timings, visibleIndex: -1 }; }; const update = (entry: ShownLine, time: number) => { // Display lines appear in order, a quarter of a second ahead of their first word. let target = -1; for (let index = 0; index < entry.timings.length; index++) { if (time >= entry.timings[index].start - 0.25) target = index; } if (time < entry.line.startTime - 0.1 || time > getLineRenderEndTime(entry.line)) target = -1; if (target !== entry.visibleIndex) { entry.visibleIndex = target; entry.lines.forEach((tiltLine, index) => tiltLine.setVisible(index <= target)); } for (const tiltLine of entry.lines) tiltLine.pulse(time); }; const dispose = (entry: ShownLine) => { entry.fade.destroy(); for (const tiltLine of entry.lines) tiltLine.destroy(); entry.slot.remove(); }; return { setLine(line, _index, time) { if (shown) { const entry = shown; leaving.add(entry); void Promise.all([entry.fade.to({ opacity: 0 }, { duration: 0.45, ease: 'easeInOut' }), ...entry.lines.map((tiltLine) => tiltLine.leave())]).then(() => { leaving.delete(entry); dispose(entry); }); } shown = null; if (!line || !line.fullText) return; shown = build(line); update(shown, time); }, frame(time) { if (shown) update(shown, time); }, destroy() { for (const entry of [...leaving, ...(shown ? [shown] : [])]) dispose(entry); leaving.clear(); shown = null; area.remove(); }, }; };