// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2), // src/components/visualizer/partita/VisualizerPartita.tsx, partitaLayout.ts and PartitaChunk.tsx: 云阶. // The line is cut into uneven chunks, one to a row, each row pushed left or right of the one above like steps; // a corner of hairlines draws itself under a chunk as it is sung, and the words inside are 流光's words. // // Changed from Folia: React became a plain renderer; the stage's box stands in for the window; the settings are // Folia's (guide lines, semantic layout, stagger range), without the optional overlap fit. The // guide lines rest in the lyric colour rather than white, so they also show on a light theme, and a chunk // starts in its waiting pose instead of fading out from a visible one as it mounts. import type { Line, StageTunings, Theme, Word } from '../types'; import { colorWithAlpha, resolveWordColor } from '../color'; import { GlowWord, LineContainer, type GlowWordConfig, type GlowWordRenderProfile, type WordStatus, getGlowWordActiveEndTime, getGlowWordLineContainerMotion, resolveGlowWordRenderProfile, statusAt, } from '../glowWord'; import { resolveLyricTextDirection, splitGraphemes } from '../lyrics/graphemes'; import { buildDisplayWordsFromLayoutUnits, buildPostLyricLayoutUnits, type LyricLayoutUnit } from '../lyrics/layoutUnits'; import { Motion } from '../motion'; import type { StyleContext, StyleRenderer } from './registry'; interface RowConfig extends GlowWordConfig { marginBottom: string; } interface Row { chunkWords: Word[]; displayWords: Word[]; config: RowConfig; rowIndex: number; } /** Each display word's own small offset, turn and drift inside its chunk (the chunk's place is on its container). */ const buildPartitaWordConfigs = (displayWords: Word[], rowConfig: RowConfig, intensity: Theme['animationIntensity']): GlowWordConfig[] => { const isCalm = intensity === 'calm'; const isChaotic = intensity === 'chaotic'; const baseSpread = isChaotic ? 15 : isCalm ? 0 : 6; const baseRotate = isChaotic ? 8 : isCalm ? 0 : 3; return displayWords.map((_, idx) => { const wordSeed = displayWords[0].startTime + idx * 7.13; const random = (offset: number) => { const x = Math.sin(wordSeed + offset) * 10000; return x - Math.floor(x); }; return { id: `${rowConfig.id}-w${idx}`, x: (random(1) - 0.5) * baseSpread * 2, y: (random(2) - 0.5) * baseSpread * 2, rotate: (random(3) - 0.5) * baseRotate * 2, scale: rowConfig.scale, passedRotate: (random(8) - 0.5) * 20, }; }); }; const buildRows = (line: Line, theme: Theme, windowHeight: number, tuning: StageTunings['partita']): { rows: Row[]; totalGraphemes: number; perspective: number } => { const STAGGER_MIN = Math.min(tuning.staggerMin, tuning.staggerMax); const STAGGER_MAX = Math.max(tuning.staggerMin, tuning.staggerMax); // 云阶 wants the line to feel composed, not scattered: first decide how many rows the line gets. const intensity = theme.animationIntensity; const isChaotic = intensity === 'chaotic'; const isCalm = intensity === 'calm'; const totalGraphemes = Math.max(splitGraphemes(line.fullText.replace(/\s+/g, '')).length, line.words.length, 1); const layoutUnits = buildPostLyricLayoutUnits(line, { semantic: tuning.useSemanticLayout, sticky: true }); const baseRowHeight = 100; const availableHeight = windowHeight * 0.65; const targetRowCount = Math.max(1, Math.floor(availableHeight / baseRowHeight)); const actualRowCount = Math.min(layoutUnits.length, targetRowCount); let seed = line.startTime; const random = () => { const x = Math.sin(seed++) * 10000; return x - Math.floor(x); }; const chunks: LyricLayoutUnit[][] = []; let remainingUnits = layoutUnits.length; let remainingChunks = actualRowCount; let unitIndex = 0; for (let c = 0; c < actualRowCount; c++) { // Chunk lengths are uneven on purpose: an even split looks mechanical. const isLastChunk = c === actualRowCount - 1; const avg = remainingUnits / remainingChunks; let chunkLength = 1; if (isLastChunk) { chunkLength = remainingUnits; } else { const max = Math.ceil(avg * 1.5); chunkLength = Math.max(1, Math.min(max, Math.round(avg + (random() - 0.5) * avg))); } chunkLength = Math.max(1, Math.min(chunkLength, remainingUnits - (remainingChunks - 1))); chunks.push(layoutUnits.slice(unitIndex, unitIndex + chunkLength)); unitIndex += chunkLength; remainingUnits -= chunkLength; remainingChunks--; } const rows: Row[] = []; chunks.forEach((chunkUnits, rowIndex) => { const chunkWords = chunkUnits.flatMap(unit => unit.words); const displayWords = buildDisplayWordsFromLayoutUnits(chunkUnits); if (chunkWords.length === 0) return; const graphemeCount = splitGraphemes(chunkWords.map(w => w.text.trim()).join('').replace(/\s+/g, '')).length; const rowBias = rowIndex - (actualRowCount - 1) / 2; const isStaggeredLeft = rowIndex % 2 === 0; // The stagger is the move of this style: rows offset and in sequence, still read as one line. const staggerMagnitude = STAGGER_MIN + random() * Math.max(STAGGER_MAX - STAGGER_MIN, 0); const staggerX = isStaggeredLeft ? -staggerMagnitude : staggerMagnitude; const staggerScale = isCalm ? 1 : 0.8 + random() * 0.9; rows.push({ chunkWords, displayWords, rowIndex, config: { id: `${rowIndex}-${chunkWords[0].startTime}`, x: staggerX, y: isCalm ? 0 : rowBias * 2.5, rotate: isChaotic ? (isStaggeredLeft ? -3 : 3) : 0, scale: (isChaotic ? 1 + Math.min(graphemeCount * 0.01, 0.05) : 1) * staggerScale, marginBottom: isChaotic ? '0.4rem' : '0.6rem', passedRotate: (rowIndex % 2 === 0 ? 1 : -1) * (isChaotic ? 6 : 3), }, }); }); return { rows, totalGraphemes, perspective: isChaotic ? 720 : 1000 }; }; /** One chunk: its place and entrance, the corner of guide lines under it, and its words. */ class Chunk { readonly el: HTMLDivElement; readonly words: GlowWord[]; #status: WordStatus = 'waiting'; #motion: Motion<'opacity' | 'scale' | 'x'>; #guides: { el: HTMLSpanElement; motion: Motion<'grow' | 'opacity'>; glow: string }[] = []; #start: number; #end: number; #lookahead: number; #config: RowConfig; #side: 'left' | 'right'; #activeColor: string; #restColor: { passed: string; waiting: string }; constructor(row: Row, theme: Theme, renderProfile: GlowWordRenderProfile, isChorus: boolean | undefined, fontSize: string, showGuideLines: boolean) { const { config, displayWords, chunkWords } = row; this.#config = config; this.#start = chunkWords[0].startTime; this.#end = getGlowWordActiveEndTime(chunkWords[chunkWords.length - 1], renderProfile); this.#lookahead = renderProfile.wordLookahead; this.#side = row.rowIndex % 2 === 0 ? 'left' : 'right'; const joined = displayWords.map(w => w.text).join(' '); this.#activeColor = resolveWordColor(joined, theme.wordColors, theme.accentColor); this.#restColor = { passed: colorWithAlpha(theme.primaryColor, 0.22), waiting: colorWithAlpha(theme.primaryColor, 0.14) }; const el = this.el = document.createElement('div'); el.className = 'folia-partita__chunk'; el.dir = resolveLyricTextDirection(joined); el.style.marginBottom = config.marginBottom; const side = this.#side; this.#motion = new Motion({ opacity: 0, scale: 0.85, x: config.x + (side === 'left' ? -40 : 40) }, (values) => { el.style.opacity = String(values.opacity); el.style.transform = `translate(${(values.x as number).toFixed(2)}px, ${config.y}px) scale(${(values.scale as number).toFixed(4)}) rotate(${config.rotate}deg)`; }); // The corner: a short upright at the outer end and a rule under the chunk, drawn from that end. for (const kind of showGuideLines ? (['upright', 'rule'] as const) : []) { const guide = document.createElement('span'); guide.className = `folia-partita__guide folia-partita__guide--${kind} folia-partita__guide--${side}`; guide.setAttribute('aria-hidden', 'true'); guide.style.backgroundColor = this.#restColor.waiting; el.append(guide); const motion = new Motion({ grow: 0, opacity: 0 }, (values) => { guide.style.opacity = String(values.opacity); guide.style.transform = kind === 'upright' ? `scaleY(${values.grow})` : `scaleX(${values.grow})`; }); this.#guides.push({ el: guide, motion, glow: kind === 'upright' ? '45' : '35' }); } const wordConfigs = buildPartitaWordConfigs(displayWords, config, theme.animationIntensity); this.words = displayWords.map((word, index) => { const glowWord = new GlowWord({ word, config: wordConfigs[index], theme, baseColor: theme.primaryColor, activeColor: resolveWordColor(word.text, theme.wordColors, theme.accentColor), renderProfile, isChorus, fontSize, layoutStyle: { marginInlineEnd: '0.8rem' }, }); el.append(glowWord.el); return glowWord; }); } update(time: number) { for (const word of this.words) word.update(time); const next = statusAt(time, this.#start, this.#end, this.#lookahead); if (next === this.#status) return; this.#status = next; const waiting = next === 'waiting'; const config = this.#config; void this.#motion.to( { opacity: waiting ? 0 : 1, scale: waiting ? 0.85 : 1, x: waiting ? config.x + (this.#side === 'left' ? -40 : 40) : config.x }, next === 'active' ? { type: 'spring', stiffness: 200, damping: 20, opacity: { duration: 0.1 } } : { duration: 0.4, ease: 'easeOut' }, ); for (const guide of this.#guides) { guide.el.style.backgroundColor = next === 'active' ? this.#activeColor : this.#restColor[next]; guide.el.style.boxShadow = next === 'active' ? `0 0 10px ${colorWithAlpha(this.#activeColor, Number.parseInt(guide.glow, 16) / 255)}` : 'none'; void guide.motion.to({ grow: waiting ? 0 : 1, opacity: waiting ? 0 : 1 }, { duration: 0.4, ease: 'easeOut' }); } } destroy() { this.#motion.destroy(); for (const guide of this.#guides) guide.motion.destroy(); for (const word of this.words) word.destroy(); } } interface ShownLine { container: LineContainer; chunks: Chunk[]; } export const createPartita = (context: StyleContext): StyleRenderer => { const { layer, theme, height } = context; const tuning = context.tunings.partita; const area = document.createElement('div'); area.className = 'folia-area folia-area--float'; const float = { calm: { distance: 10, duration: 8.5 }, normal: { distance: 14, duration: 7 }, chaotic: { distance: 18, duration: 5.8 } }[theme.animationIntensity]; area.style.setProperty('--folia-float', `${float.distance}px`); area.style.animationDuration = `${float.duration}s`; layer.append(area); let shown: ShownLine | null = null; const leaving = new Set(); const build = (line: Line): ShownLine => { const renderProfile = resolveGlowWordRenderProfile(line); const layout = buildRows(line, theme, height, tuning); const densityScale = layout.totalGraphemes > 40 ? 0.8 : 1; const sized = densityScale * context.fontScale; const fontSize = `clamp(${(2.5 * sized).toFixed(3)}rem, ${(5.5 * sized).toFixed(3)}cqw, ${(4.5 * sized).toFixed(3)}rem)`; const slot = document.createElement('div'); slot.className = 'folia-slot'; const box = document.createElement('div'); box.className = 'folia-partita__line'; box.style.perspective = `${layout.perspective}px`; const column = document.createElement('div'); column.className = 'folia-partita__column'; const stack = document.createElement('div'); stack.className = 'folia-partita__stack'; const chunks = layout.rows.map((row) => { const chunk = new Chunk(row, theme, renderProfile, line.isChorus, fontSize, tuning.showGuideLines); stack.append(chunk.el); return chunk; }); column.append(stack); box.append(column); slot.append(box); area.append(slot); return { container: new LineContainer(box, getGlowWordLineContainerMotion(renderProfile), slot), chunks }; }; const retire = (line: ShownLine) => { leaving.add(line); void line.container.leave().then(() => { leaving.delete(line); for (const chunk of line.chunks) chunk.destroy(); }); }; return { setLine(line, _index, time) { if (shown) retire(shown); shown = null; if (!line) return; shown = build(line); for (const chunk of shown.chunks) chunk.update(time); void shown.container.enter(); }, frame(time) { if (shown) for (const chunk of shown.chunks) chunk.update(time); for (const line of leaving) for (const chunk of line.chunks) chunk.update(time); }, destroy() { for (const line of [...leaving, ...(shown ? [shown] : [])]) { for (const chunk of line.chunks) chunk.destroy(); line.container.destroy(); } leaving.clear(); shown = null; area.remove(); }, }; };