// SPDX-License-Identifier: AGPL-3.0-only // Ported from Folia (https://github.com/chthollyphile/folia-major, v0.8.2), src/utils/appearanceCodec.ts: the // shareable config code (`folia-theme://` followed by base64 of a minified JSON), which Folia copies from and // pastes into its settings to carry a look from one Folia to another. See ./README.md. // // A look made in Folia (its own colours, the lyric style and that style's settings, type size, the band at the // foot) can be loaded here, and one changed here can be written back out as a code Folia reads. // // Changed from Folia: only what this port draws is read (a theme's two sides, the lyric style, the settings of // 流光 / 心象 / 云阶 / 倾诉, type, the geometric shapes and vignette, the band); everything else in a code is // ignored, and written codes carry only those fields. import type { Appearance, StageTunings, ThemeOverride } from './types'; const PREFIX = 'folia-theme://'; type Fields = Record; const isObject = (value: unknown): value is Fields => typeof value === 'object' && value !== null && !Array.isArray(value); const number = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined); const boolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined); const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : undefined); /** A colour as CSS can take it from an untrusted code: hex or rgb()/rgba() only. */ const colour = (value: unknown) => { const string = text(value); return string && /^(#[0-9a-fA-F]{3,8}|rgba?\([\d\s.,%/]+\))$/.test(string) ? string : undefined; }; const intensity = (value: unknown): ThemeOverride['animationIntensity'] => (value === 'calm' || value === 'normal' || value === 'chaotic' ? value : undefined); const compact = (fields: T): T => Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined)) as T; const readSide = (side: unknown, minified: boolean): ThemeOverride | undefined => { // A side this port wrote only to complete the theme (see writeFoliaConfig) is not one the look set. if (!isObject(side) || side.xb === 1) return undefined; const pick = (short: string, long: string) => side[minified ? short : long]; const words = pick('wc', 'wordColors'); const wordColors = Array.isArray(words) ? words.flatMap((entry) => (isObject(entry) && text(entry.word) && colour(entry.color) ? [{ word: text(entry.word)!, color: colour(entry.color)! }] : [])) : undefined; const result = compact({ backgroundColor: colour(pick('bg', 'backgroundColor')), primaryColor: colour(pick('pc', 'primaryColor')), accentColor: colour(pick('ac', 'accentColor')), secondaryColor: colour(pick('sc', 'secondaryColor')), animationIntensity: intensity(pick('ai', 'animationIntensity')), wordColors: wordColors?.length ? wordColors : undefined, }); return Object.keys(result).length ? result : undefined; }; const scheme = (value: unknown): StageTunings['tilt']['colorScheme'] | undefined => (value === 'default' || value === 'swap' || value === 'accentAll' || value === 'primaryAll' ? value : undefined); /** The four styles' settings, from the short keys of an old code or the full names of the `visualizerTunings` bundle. */ const readTunings = (config: Fields, minified: boolean): Appearance['tunings'] => { const bundle = isObject(config[minified ? 'vt' : 'visualizerTunings']) ? config[minified ? 'vt' : 'visualizerTunings'] as Fields : {}; const full = (name: keyof StageTunings) => (isObject(bundle[name]) ? bundle[name] as Fields : isObject(config[`${name}Tuning`]) ? config[`${name}Tuning`] as Fields : {}); const short = (key: string) => (minified && isObject(config[key]) ? config[key] as Fields : {}); const classic = full('classic'); const cadenza = full('cadenza'); const partita = full('partita'); const tilt = full('tilt'); const ct = short('ct'); const cat = short('cat'); const pt = short('pt'); const tt = short('tt'); const result = { classic: compact({ enableWordRotation: boolean(classic.enableWordRotation ?? ct.ewr), breathingFloatMultiplier: number(classic.breathingFloatMultiplier ?? ct.bfm), wordSpacing: number(classic.wordSpacing ?? ct.cws), }), cadenza: compact({ fontScale: number(cadenza.fontScale ?? cat.cfs), widthRatio: number(cadenza.widthRatio ?? cat.wr), motionAmount: number(cadenza.motionAmount ?? cat.ma), glowIntensity: number(cadenza.glowIntensity ?? cat.gi), }), partita: compact({ showGuideLines: boolean(partita.showGuideLines ?? pt.sgl), useSemanticLayout: boolean(partita.useSemanticLayout ?? pt.usl), staggerMin: number(partita.staggerMin ?? pt.smi), staggerMax: number(partita.staggerMax ?? pt.sma), }), tilt: compact({ splitProbability: number(tilt.splitProbability ?? tt.sp), tiltStyleProbability: number(tilt.tiltStyleProbability ?? tt.tsp), colorScheme: scheme(tilt.colorScheme ?? tt.tcs), }), }; const kept = Object.fromEntries(Object.entries(result).filter(([, value]) => Object.keys(value).length)); return Object.keys(kept).length ? kept : undefined; }; /** A Folia config code (or its JSON, minified or with full names) as a look. Throws when the text is not one. */ export const readFoliaConfig = (input: string): Appearance => { const trimmed = input.trim(); const coded = trimmed.startsWith(PREFIX); let parsed: unknown; if (coded) { const bytes = Uint8Array.from(atob(trimmed.slice(PREFIX.length)), (char) => char.charCodeAt(0)); parsed = JSON.parse(new TextDecoder().decode(bytes)); } else parsed = JSON.parse(trimmed); if (!isObject(parsed)) throw new Error('Invalid format'); const config = parsed; const minified = coded || ['t', 'vm', 'vt', 'ct', 'cat', 'pt', 'tt', 'lfn', 'lfw', 'dvgb', 'dvv', 'soo'].some((key) => config[key] !== undefined); const pick = (short: string, long: string) => config[minified ? short : long]; const theme = pick('t', 'theme'); const light = isObject(theme) ? readSide(theme[minified ? 'l' : 'light'], minified) : undefined; const dark = isObject(theme) ? readSide(theme[minified ? 'd' : 'dark'], minified) : undefined; const fallbacks = pick('lff', 'lyricsFontFallbackFamilies'); const families = [text(pick('lcf', 'lyricsCustomFontFamily')), ...(Array.isArray(fallbacks) ? fallbacks.map(text) : [])] .filter((family): family is string => Boolean(family)) .slice(0, 6); const subtitle = compact({ hidden: boolean(pick('hpts', 'hidePlayerTranslationSubtitle')), opacity: number(pick('soo', 'subtitleOverlayOpacity')), background: boolean(pick('sob', 'subtitleOverlayBackground')), blur: boolean(pick('sulb', 'subtitleUpcomingLyricsBlur')), scale: number(pick('sfsz', 'subtitleFontScale')), }); const look: Appearance = compact({ theme: light || dark ? compact({ light, dark }) : undefined, style: text(pick('vm', 'visualizerMode')), tunings: readTunings(config, minified), fontScale: number(pick('lfn', 'lyricsFontScale')), fontWeight: number(pick('lfw', 'lyricsFontWeight')), fontFamilies: families.length ? families : undefined, hideShapes: boolean(pick('dvgb', 'disableVisualizerGeometricBackground')), hideVignette: boolean(pick('dvv', 'disableVisualizerVignette')), opacity: number(pick('vo', 'visualizerOpacity')), subtitle: Object.keys(subtitle).length ? subtitle : undefined, }); if (!Object.keys(look).length) throw new Error('Nothing of a look in this configuration'); return look; }; const writeSide = (side: ThemeOverride | undefined, name: string, borrowed = false) => (side ? compact({ n: name, xb: borrowed ? 1 : undefined, bg: side.backgroundColor, pc: side.primaryColor, ac: side.accentColor, sc: side.secondaryColor, ai: side.animationIntensity, wc: side.wordColors, }) : undefined); /** * A look as a config code Folia reads. Folia's themes have two sides; a look that sets one has the other written * with the same colours and marked `xb` (a key Folia passes over), so that read back here it is still unset. */ export const writeFoliaConfig = (look: Appearance): string => { const tunings = look.tunings ?? {}; const light = look.theme?.light; const dark = look.theme?.dark; const minified = compact({ t: light || dark ? { l: writeSide(light ?? dark, 'Xikari Day', !light) ?? {}, d: writeSide(dark ?? light, 'Xikari Night', !dark) ?? {} } : undefined, vm: look.style, vt: Object.keys(tunings).length ? tunings : undefined, lfn: look.fontScale, lfw: look.fontWeight, lcf: look.fontFamilies?.[0], lff: look.fontFamilies && look.fontFamilies.length > 1 ? look.fontFamilies.slice(1) : undefined, dvgb: look.hideShapes, dvv: look.hideVignette, vo: look.opacity, hpts: look.subtitle?.hidden, soo: look.subtitle?.opacity, sob: look.subtitle?.background, sulb: look.subtitle?.blur, sfsz: look.subtitle?.scale, }); const bytes = new TextEncoder().encode(JSON.stringify(minified)); return `${PREFIX}${btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''))}`; };