Skip to content

Folium API 参考 ​

当前契约版本:Folium 1.3(运行时用 folium.host.folium.minor 做功能探测)。

本文列出模组能用到的全部公开类型,内容直接来自契约文件 src/mods/folium/contract.ts, 成员说明保留契约里的原文注释。平台规则(清单、权限、生命周期、安全模型)见 Folium 规范, 从零开始写模组、调试与发布到模组市场见 模组开发与贡献指南。

目录 ​

客户端入口 ​

模组的 client 入口默认导出 activate(folium),参数就是 FoliumClientApi,所有能力都从这里取。

FoliumContextKind ​

Where a client runs: the main window, or the transparent video export window.

ts
type FoliumContextKind = 'main' | 'export'

FoliumHostInfo ​

The host, for runtime feature detection (folium.host).

成员类型说明
folium{ major: number; minor: number }The Folium version (major, minor).
foliastring | nullFolia app version, or null when the host cannot tell.

FoliumStorage ​

folium.storage: this mod's data file (shared with its main entry, 1 MB). Needs the filesystem.data permission; values must be JSON-serializable.

成员类型说明
get()<T = unknown>(key: string): Promise<T | undefined>The stored value, or undefined.
set()(key: string, value: unknown): Promise<void>Stores a JSON-serializable value.
has()(key: string): Promise<boolean>Whether the key exists.
delete()(key: string): Promise<void>Removes the key.
keys()(): Promise<string[]>All keys.

FoliumRpc ​

folium.rpc: calls into this mod's main entry.

成员类型说明
call()<T = unknown>(name: string, ...args: unknown[]): Promise<T>Calls the function the main entry registered with api.rpc.handle(name, fn); arguments and result must be JSON-serializable.

FoliumLogger ​

folium.log. error entries show in the mods panel under the mod.

成员类型说明
info()(message: string, details?: unknown): voidInformational log.
warn()(message: string, details?: unknown): voidWarning.
error()(message: string, details?: unknown): voidError; shown in the mods panel.

FoliumClientApi ​

The object a client entry's activate(folium) receives.

成员类型说明
readonly modIdstringThis mod's id.
readonly hostFoliumHostInfoHost versions, for feature detection.
readonly env{ readonly context: FoliumContextKind }Where this client runs.
readonly logFoliumLoggerLogging.
readonly registriesFoliumRegistriesEverything a mod can add to the host.
readonly eventsFoliumEventsThe event bus.
readonly playbackFoliumPlaybackServicePlayback state and control.
readonly uiFoliumUiServiceToasts, panels, files, embeds, icons.
readonly netFoliumNetServiceNetwork access through the host.
readonly storageFoliumStorageThis mod's data file.
readonly rpcFoliumRpcCalls into this mod's main entry.
readonly lyricsFoliumLyricsHelpersFolium 1.3.
readonly themeFoliumThemeHelpersFolium 1.3.
readonly experimentalReadonly<Record<string, unknown>>Unfrozen surfaces; each requires the matching manifest experimental opt-in.
readonly internalsReadonly<Record<string, unknown>>Host internals with no compatibility promise. Only available when the manifest pins host versions with "folia"; otherwise accessing it throws.

相关:FoliumHostInfo · FoliumContextKind · FoliumLogger · FoliumRegistries · FoliumEvents · FoliumPlaybackService · FoliumUiService · FoliumNetService · FoliumStorage · FoliumRpc · FoliumLyricsHelpers · FoliumThemeHelpers

FoliumClientModule ​

The shape of a client entry module.

成员类型说明
default(folium: FoliumClientApi) => void | FoliumDisposer | Promise<void | FoliumDisposer>activate(folium); may return a disposer, which runs before the host removes the mod's registrations.

相关:FoliumClientApi · FoliumDisposer

注册表与条目 ​

folium.registries.<名称>.register(def) 返回 FoliumRegistryHandle。条目 id 由宿主加上命名空间成为 <modid>:<id>;模组停用时宿主自动撤下它注册的一切。

FoliumVisualizerDef ​

A lyric animation mode. Its mode id is mod:<modid>:<id>.

成员类型说明
idstringLocal id; the mode id becomes mod:<modid>:<id>.
labelFoliumLabelName in the mode picker.
order?numberPosition in the mode picker; default 500 (after builtin modes).
mountFoliumMount<FoliumStageContext>Draws the visualizer into its container.
settings?FoliumParam[]Settings schema; the host renders the form under the mode picker, persists the values and includes them in visual config import/export.
settingsPanel?FoliumMount<FoliumSettingsPanelContext>Replaces the host-rendered form; values still follow settings.
hostLayers?{ background?: boolean; subtitles?: boolean }Host-rendered layers around the visualizer. Both default to true.

相关:FoliumLabel · FoliumMount · FoliumStageContext · FoliumParam · FoliumSettingsPanelContext

FoliumTuningDef ​

Extra tuning knobs for a builtin visualizer mode that declares Folium tunables.

成员类型说明
idstringLocal id.
targetstringA builtin visualizer mode that declares foliumTunables, e.g. "sonnet".
labelFoliumLabelCard title.
paramsFoliumParam[]Number params only; keys and ranges are checked against the target's whitelist.

相关:FoliumLabel · FoliumParam

FoliumCommandContext ​

What a command receives when it runs.

成员类型说明
readonly valuesFoliumParamValuesValidated parameter values (defaults merged).

相关:FoliumParamValues

FoliumCommandDef ​

A command in the mods panel and the command palette. run executes in the renderer; hand Node work to the main entry through folium.rpc.

成员类型说明
idstringLocal id.
labelFoliumLabelCommand name.
description?FoliumLabelShown under the name.
keywords?string[]Extra search terms for the command palette (label texts are always included).
params?FoliumParam[]Shown in the mods panel and the command palette; a palette entry with params opens a form.
run()(ctx: FoliumCommandContext): unknown | Promise<unknown>Runs the command; the result is shown as a summary (a string, { outputPath } or { message }).

相关:FoliumLabel · FoliumParam · FoliumCommandContext

FoliumBackgroundContext ​

Lyric-free context for background types: they paint behind every mode, previews included.

成员类型说明
readonly staticModebooleanA still preview: draw one frame, do not animate.
isPaused()(): booleanPlayback is paused.
getTheme()(): FoliumThemeThe current theme.
getSettings()(): FoliumParamValuesThis background's settings values (defaults merged).
getCoverUrl()(): string | nullCover image URL of the displayed song.
subscribe()(listener: () => void): FoliumDisposerCalled when pause, theme, settings or cover change.
readonly audioFoliumAudioFolium 1.2.

相关:FoliumTheme · FoliumParamValues · FoliumDisposer · FoliumAudio

FoliumBackgroundDef ​

A background type in the background picker; it paints behind every mode, previews and export included.

成员类型说明
idstringLocal id.
labelFoliumLabelName in the background picker.
order?numberPosition in the picker; default 500.
mountFoliumMount<FoliumBackgroundContext>Draws the background into its container.
settings?FoliumParam[]Settings schema, as for visualizers.
settingsPanel?FoliumMount<FoliumSettingsPanelContext>Replaces the host-rendered form; values still follow settings.

相关:FoliumLabel · FoliumMount · FoliumBackgroundContext · FoliumParam · FoliumSettingsPanelContext

FoliumStageSlot ​

Where a stage layer sits on the player page:

  • player.stage.back: above the background, under the lyrics;
  • player.stage.front: above the lyrics, under the player chrome;
  • app.overlay: above the whole app.
ts
type FoliumStageSlot = 'player.stage.back' | 'player.stage.front' | 'app.overlay'

FoliumStageLayerDef ​

A layer on the live player page (never in previews, OBS sources or the export window). Needs the ui.stage permission.

成员类型说明
idstringLocal id.
slotFoliumStageSlotWhere the layer sits.
order?numberStacking order within the slot; default 500.
interactive?booleanWhen false (default) the layer is click-through, so it cannot block the player; elements that should still take clicks set pointer-events: auto. When true the whole layer captures the pointer.
mountFoliumMount<FoliumStageContext>Draws the layer into its container.

相关:FoliumStageSlot · FoliumMount · FoliumStageContext

FoliumSettingsSectionDef ​

The mod's own settings, shown in the mods panel when the mod's row is expanded. Values are readable in every context.

成员类型说明
idstringLocal id.
labelFoliumLabelSection title.
description?FoliumLabelShown under the title.
settingsFoliumParam[]The fields.
settingsPanel?FoliumMount<FoliumSettingsPanelContext>Replaces the host-rendered form; values still follow settings.

相关:FoliumLabel · FoliumParam · FoliumMount · FoliumSettingsPanelContext

FoliumPlayerPanelTabDef ​

A tab in the player panel. folium.ui.openPlayerPanel(id) opens it.

成员类型说明
idstringLocal id; pass it to folium.ui.openPlayerPanel.
labelFoliumLabelTab title.
order?numberTab order; default 500.
mountFoliumMount<FoliumPanelContext>Draws the tab into its container.

相关:FoliumLabel · FoliumMount · FoliumPanelContext

FoliumProgressContext ​

Progress-bar context shared by control buttons and progress layers.

成员类型说明
readonly currentTimeFoliumClockThe playback clock (audio time).
getDuration()(): numberTrack duration, seconds; 0 when unknown.
timeToRatio()(seconds: number): number0..1 position of a time on the track (0 when the duration is unknown).
seek()(seconds: number): voidSeeks the host player; ignored while the host bar is disabled.
getColors()(): { fill: string; track: string; text: string }The host bar's colors, so mod UI can match it.
subscribe()(listener: () => void): FoliumDisposerCalled when the duration or the colors change.

相关:FoliumClock · FoliumDisposer

FoliumControlSlot ​

The side of the progress bar a control button sits on.

ts
type FoliumControlSlot = 'progress.leading' | 'progress.trailing'

FoliumControlButtonDef ​

A button next to the progress bar. All three host progress bars (floating controls x2, Lattice) show it.

成员类型说明
idstringLocal id.
slotFoliumControlSlotLeft or right of the bar.
order?numberOrder within the slot; default 500.
hideWhenCollapsed?booleanFolium 1.3: leave the collapsed floating capsule alone. The button is not mounted there, only on the expanded capsule and Lattice. Default false.
mountFoliumMount<FoliumProgressContext>Draws the button into its container.

相关:FoliumControlSlot · FoliumMount · FoliumProgressContext

FoliumProgressLayerDef ​

A layer over the progress track. Its container is click-through so seeking keeps working; elements that should take clicks set pointer-events: auto.

成员类型说明
idstringLocal id.
order?numberStacking order; default 500.
mountFoliumMount<FoliumProgressContext>Draws the layer into its container, which spans the track.

相关:FoliumMount · FoliumProgressContext

FoliumStyleDef ​

Mod CSS, injected inside @layer folium-mods and removed with the mod. The stable targets are the host's public parts: [data-folium-part="progress.track"] etc. (see mods/README.md for the list). Anything else in the host DOM is not API.

成员类型说明
idstringLocal id.
cssstringThe stylesheet.

FoliumRegistryHandle ​

What register returns.

成员类型说明
readonly idFoliumIdFull namespaced id (modid:name).
unregister()(): voidRemoves the entry now (the host also removes it when the mod stops).

相关:FoliumId

FoliumSettingsSectionHandle ​

What settingsSections.register returns: the handle plus the section's values.

ts
interface FoliumSettingsSectionHandle extends FoliumRegistryHandle
成员类型说明
readonly paramsFoliumParamAccessThe section's values (defaults merged) and write access.

相关:FoliumRegistryHandle · FoliumParamAccess

FoliumRegistry ​

Every registry has this one method.

ts
interface FoliumRegistry<Def, Handle extends FoliumRegistryHandle = FoliumRegistryHandle>
成员类型说明
register()(def: Def): HandleAdds an entry; throws on an invalid definition or a duplicate id.

相关:FoliumRegistryHandle

FoliumRegistries ​

All registries, as folium.registries. UI-only ones (commands, stageLayers, playerPanelTabs, controlButtons, progressLayers, styles) accept registrations and do nothing in the export window.

成员类型说明
visualizersFoliumRegistry<FoliumVisualizerDef>Lyric animation modes.
tuningsFoliumRegistry<FoliumTuningDef>Tuning knobs for builtin modes.
commandsFoliumRegistry<FoliumCommandDef>Commands.
backgroundsFoliumRegistry<FoliumBackgroundDef>Background types.
stageLayersFoliumRegistry<FoliumStageLayerDef>Player page layers (ui.stage).
settingsSectionsFoliumRegistry<FoliumSettingsSectionDef, FoliumSettingsSectionHandle>The mod's own settings.
playerPanelTabsFoliumRegistry<FoliumPlayerPanelTabDef>Player panel tabs.
controlButtonsFoliumRegistry<FoliumControlButtonDef>Progress bar buttons.
progressLayersFoliumRegistry<FoliumProgressLayerDef>Layers over the progress track.
stylesFoliumRegistry<FoliumStyleDef>Mod CSS for public parts.

相关:FoliumRegistry · FoliumVisualizerDef · FoliumTuningDef · FoliumCommandDef · FoliumBackgroundDef · FoliumStageLayerDef · FoliumSettingsSectionDef · FoliumSettingsSectionHandle · FoliumPlayerPanelTabDef · FoliumControlButtonDef · FoliumProgressLayerDef · FoliumStyleDef

宿主容器与上下文 ​

界面类条目都是 mount(container, ctx) => dispose?:宿主创建并回收容器,通过 ctx 提供时钟、主题、设置、音频等只读信息与订阅。

FoliumMount ​

Everything UI-shaped is mounted into a container the host owns. The host creates it (inside a ShadowRoot for panels), passes theme colors as --folium-* CSS custom properties, and calls the disposer when it removes the container. Mods never query or mutate host DOM outside their container.

ts
type FoliumMount<Ctx> = (container: HTMLElement, ctx: Ctx) => void | FoliumDisposer

相关:FoliumDisposer

FoliumPanelContext ​

Context for panel-like containers (player panel tabs, settings panels).

成员类型说明
readonly localestringThe UI locale, e.g. zh-CN.
getTheme()(): FoliumThemeThe current theme.
subscribe()(listener: () => void): FoliumDisposerCalled when the theme changes.

相关:FoliumTheme · FoliumDisposer

FoliumSettingsPanelContext ​

Context for a custom settings panel (settingsPanel): the panel draws the form, the schema still owns the values.

ts
interface FoliumSettingsPanelContext extends FoliumPanelContext
成员类型说明
readonly paramsFoliumParamAccessRead and write the values the schema describes.

相关:FoliumPanelContext · FoliumParamAccess

FoliumClock ​

A clock in seconds. on fires while it runs; read it with get when you need it now.

成员类型说明
get()(): numberCurrent time, seconds.
on()(event: 'change', listener: (seconds: number) => void): FoliumDisposerCalled with the time on every change.

相关:FoliumDisposer

FoliumSurface ​

What the host draws around the content.

成员类型说明
transparentbooleanThe host renders onto a transparent surface (OBS source, alpha export).
hostBackgroundbooleanThe host is painting its configured background under this content.

FoliumAudioBands ​

Analyser band energies, each 0..1.

成员类型说明
readonly bassnumber20–150 Hz
readonly lowMidnumber150–400 Hz
readonly midnumber400–1200 Hz
readonly vocalnumber1000–3500 Hz
readonly treblenumber3500 Hz and up

FoliumAudio ​

Folium 1.2: the host's audio analyser, for audio-reactive content. Values change every frame and nothing is announced: read them inside your own frame loop. Previews feed a synthetic signal; silence (or no analyser) reads as 0.

成员类型说明
getPower()(): numberOverall energy (bass + low mid, shaped), 0..1.
getBands()(): FoliumAudioBandsThe same object on every call, refreshed in place; copy it to keep a reading.
getSpectrum()(): Uint8Array | nullRaw analyser FFT magnitudes (0–255), or null when there are none. The host reuses the array.

相关:FoliumAudioBands

FoliumDisplay ​

Context for lyric-synced content (visualizers, stage layers). Snapshot fields are fixed for one mount; the host remounts only when the lyric data, the song or staticMode changes (or the preview line in static mode). Everything else is read through getters, and subscribe fires when any getter's value changes, including while paused, when currentTime is idle.

Folium 1.3: the host's display settings for lyric content, named and valued as builtin modes receive them. A mod that turns off hostLayers.subtitles and draws its own reads the subtitle settings here.

成员类型说明
showTextbooleanFalse while lyrics should not be drawn (e.g. the settings modal covers the player).
lyricsFontScalenumberThe user's lyric size multiplier; builtin modes scale lyric text by it.
subtitleFontScalenumberSubtitle size multiplier.
subtitleOverlayOpacitynumberSubtitle opacity, 0..1.
subtitleOverlayBackgroundbooleanSubtitles get a backing plate.
subtitleUpcomingLyricsBlurbooleanUpcoming-line subtitles are blurred.
showHarmonySubtitlebooleanBackground vocals are shown as subtitles.
harmonySubtitleBackgroundbooleanHarmony subtitles get a backing plate.
showSubtitleTranslationbooleanSubtitles show a translation or romanization.
hideTranslationSubtitlebooleanThe host hides translation subtitles here (e.g. the lyrics already carry them).
subtitleContentMode'translation' | 'romanization' | 'none'What subtitles show.
isPlayerChromeHiddenbooleanThe player controls are hidden.
isPanelOpenbooleanThe player panel is open.
visualizerOpacitynumberLyric layer opacity, 0..1.

FoliumStageContext ​

Context for lyric-synced content (visualizers, stage layers). Snapshot fields are fixed for one mount; the host remounts only when the lyric data, the song or staticMode changes (or the preview line in static mode). Everything else is read through getters, and subscribe fires when any getter's value changes, including while paused, when currentTime is idle.

成员类型说明
readonly linesreadonly FoliumLine[]Lyrics of this song (fixed for the mount).
readonly songFoliumSong | nullThis song (fixed for the mount).
readonly staticModebooleanA still preview: draw one frame of staticLineIndex, do not animate.
readonly staticLineIndexnumber | nullOnly meaningful in static mode: the line the preview shows.
readonly seedstring | nullFolium 1.3: the geometry seed builtin modes get (the displayed song's id, or a per-mode fallback). Stable per song, identical in previews, playback and export, so seeded randomness matches everywhere.
readonly isPreviewbooleanFolium 1.3: rendering inside a settings preview rather than the player page.
readonly currentTimeFoliumClockThe lyric clock.
getLineIndex()(): numberIndex into lines of the active line; -1 between lines.
isPaused()(): booleanPlayback is paused.
getTheme()(): FoliumThemeThe current theme.
getSubtitleTheme()(): FoliumThemeFolium 1.3: the theme the host's subtitles use; equals getTheme() where there is none.
getCoverUrl()(): string | nullFolium 1.3.
getDisplay()(): FoliumDisplayFolium 1.3. The same object until a value changes; subscribe announces changes.
getSettings()(): FoliumParamValuesThis entry's settings values (defaults merged); empty without a schema.
getSurface()(): FoliumSurfaceWhat the host draws around this content.
subscribe()(listener: () => void): FoliumDisposerCalled when the line index, pause, theme, subtitle theme, cover, display, settings or surface change.
readonly audioFoliumAudioFolium 1.2.

相关:FoliumLine · FoliumSong · FoliumClock · FoliumTheme · FoliumDisplay · FoliumParamValues · FoliumSurface · FoliumDisposer · FoliumAudio

事件 ​

folium.events.on(type, handler, { priority })。通知只读、事后发出;钩子让处理器依次修改同一个事件对象。omni.* 需要选用实验接口 omni.hooks。

FoliumEventPriority ​

Handler order for one event type; handlers of the same priority run in registration order.

ts
type FoliumEventPriority = 'highest' | 'high' | 'normal' | 'low' | 'lowest'

FoliumNotificationEvents ​

Read-only notifications, emitted after the fact.

成员类型说明
playback.songChanged{ readonly song: FoliumSong | null }The displayed song changed.
playback.stateChanged{ readonly state: FoliumPlaybackState }Playing, paused or stopped.
playback.seeked{ readonly position: number }The user or a mod seeked; position in seconds.
lyrics.loaded{ readonly song: FoliumSong | null; readonly lines: readonly FoliumLine[] }Lyrics for the displayed song are ready (after lyrics.transform).
app.viewChanged{ readonly view: string }The app switched views (e.g. home, player).
visualizer.modeChanged{ readonly mode: string }The lyric animation mode changed.
theme.changed{ readonly theme: FoliumTheme }The theme or daylight mode changed.
playback.likeChanged{ readonly liked: boolean }Folium 1.3: playback.getState().liked changed (a like or unlike, or a new song).

相关:FoliumSong · FoliumPlaybackState · FoliumLine · FoliumTheme

FoliumLyricsTransformEvent ​

Synchronous hook: runs when new lyrics reach the player, before they are shown. Assign lines to rewrite them; lines left untouched (same object) keep all their host-side data, new or changed ones are built from the DTO.

Always runs on untransformed lyrics, never on its own output: when the host rebuilds lyrics already on screen (e.g. a word-segmentation update) it starts again from the untransformed version, so handlers need not be idempotent.

成员类型说明
readonly songFoliumSong | nullThe song the lyrics belong to.
linesreadonly FoliumLine[]Assign a new array to rewrite the lyrics.

相关:FoliumSong · FoliumLine

FoliumBeforePlayEvent ​

Async hook: runs before a song starts. Handlers may cancel it or play another song instead. Not run for the track an automix blend advances to: the blend starts that track seconds early on a fixed schedule and cannot wait for handlers.

成员类型说明
readonly songFoliumSongThe song about to play.
readonly cancelledbooleanA handler already cancelled.
cancel()(): voidStops the song from playing; later handlers are skipped.
replaceWith()(song: FoliumSong): voidPlays this song instead; it must carry a ref from the host.

相关:FoliumSong

FoliumOmniLyricsEvent ​

EXPERIMENTAL (manifest experimental: ["omni.hooks"]): Omni answered with lyrics for an online song. Same line rules as lyrics.transform.

成员类型说明
readonly songFoliumSongThe online song.
linesreadonly FoliumLine[]Assign a new array to rewrite the lyrics.
readonly isPureMusicbooleanOmni reported the song as instrumental.

相关:FoliumSong · FoliumLine

FoliumOmniAudioEvent ​

EXPERIMENTAL (omni.hooks): Omni resolved an audio URL; assign url to use another one.

成员类型说明
readonly songFoliumSongThe online song.
urlstring | nullAssign another https URL to play that instead.

相关:FoliumSong

FoliumHookEvents ​

Hooks: every handler receives the same event object, in priority order, and may change it.

成员类型说明
lyrics.transformFoliumLyricsTransformEventRewrite lyrics before they are shown (sync).
playback.beforePlayFoliumBeforePlayEventCancel or replace a song before it plays (async, 1.5 s per handler).
omni.lyricsResolvedFoliumOmniLyricsEventRewrite lyrics Omni fetched (experimental, omni.hooks).
omni.audioSourceResolvedFoliumOmniAudioEventReplace the audio URL Omni resolved (experimental, omni.hooks).

相关:FoliumLyricsTransformEvent · FoliumBeforePlayEvent · FoliumOmniLyricsEvent · FoliumOmniAudioEvent

FoliumEventMap ​

Every event type and its payload.

ts
type FoliumEventMap = FoliumNotificationEvents & FoliumHookEvents

相关:FoliumNotificationEvents · FoliumHookEvents

FoliumEvents ​

The event bus, as folium.events.

成员类型说明
on()<K extends keyof FoliumEventMap>(type: K, handler: (event: FoliumEventMap[K]) => void | Promise<void>, options?: { priority?: FoliumEventPriority }): FoliumDisposerAdds a handler; returns its disposer. Each handler runs in its own error boundary; a sync handler over 16 ms logs a warning.

相关:FoliumEventMap · FoliumEventPriority · FoliumDisposer

服务 ​

folium.playback / folium.ui / folium.net。标注需要权限的方法未在 mod.json 声明对应权限时抛 permission-denied:<权限>;导出窗口里调用会抛 *-unavailable-in-export-context(ui.icon 除外)。

FoliumPlaybackService ​

folium.playback. getState is always available; every other method needs the playback.control permission. All of it is unavailable in the export window.

成员类型说明
getState()(): { song: FoliumSong | null; state: FoliumPlaybackState; position: number; duration: number; liked: boolean; canLike: boolean; }The displayed song, player state, position and duration (seconds). Folium 1.3: liked (the displayed song is liked; false with no song) and canLike (toggleLike would act now; the host's own like button greys out otherwise).
play()(): voidResumes playback. Needs playback.control.
pause()(): voidPauses. Needs playback.control.
toggle()(): voidPlay/pause. Needs playback.control.
seek()(seconds: number): voidSeeks to a playback position (audio time), seconds. Needs playback.control.
seekToLyricTime()(lyricSeconds: number): voidFolium 1.3: seeks to a point on the lyric clock, e.g. line.startTime, the way clicking a lyric line does in builtin modes. The host converts lyric time to playback time (lyric offsets, lyrics-only stage sources); seek(line.startTime) would land off by the offset. Ignored while the host has now-playing controls disabled. Needs playback.control.
next()(): voidNext track. Needs playback.control.
previous()(): voidPrevious track. Needs playback.control.
playSong()(song: FoliumSong): Promise<boolean>Plays a song by its host ref. Resolves false when the ref is unknown. Needs playback.control.
enqueue()(song: FoliumSong): booleanAppends a song (by ref) to the queue. Needs playback.control.
shuffleQueue()(): booleanFolium 1.3: shuffles the play queue, keeping the current song first. False when there is nothing to shuffle (Personal FM, a queue of one, external Stage playback). Needs playback.control.
toggleLike()(): booleanFolium 1.3: likes or unlikes the displayed song, like the host's like button, which also reports the result. False when canLike is false. Needs playback.control.

相关:FoliumSong · FoliumPlaybackState

FoliumFileHandle ​

A local file the user picked for this mod.

成员类型说明
urlstringfolia-mod:// URL usable as a media/img src for this session.
namestringFile name.
sizenumberSize in bytes.
grantId?stringFolium 1.1: opaque id of a persisted grant (pickFile with persist, or restoreFile). Store it to get the file back after a restart.

FoliumIconOptions ​

Folium 1.2: options for folium.ui.icon.

成员类型说明
size?numberWidth and height in px. Default 24.
strokeWidth?numberStroke width in the icon's 24-unit grid. Default 2.
color?stringAny CSS color. Default currentColor, so the icon follows the surrounding text.

FoliumUiService ​

folium.ui. Unavailable in the export window, except icon.

成员类型说明
toast()(message: string, options?: { type?: 'info' | 'success' | 'error'; durationMs?: number }): voidShows a status message.
openPlayerPanel()(tabId?: string): voidOpens the player panel, optionally on one of this mod's panel tabs (local id).
navigate()(view: 'home' | 'player'): voidSwitches to the home or player view.
openVolume()(): voidFolium 1.3: opens the host volume panel (the command palette's volume command).
pickFile()(options?: { accept?: 'video' | 'audio' | 'image' | 'any'; persist?: boolean }): Promise<FoliumFileHandle | null>Lets the user pick a local file; null when cancelled. With persist (Folium 1.1) the pick is remembered for this mod and the handle carries a grantId for restoreFile.
restoreFile()(grantId: string): Promise<FoliumFileHandle | null>Folium 1.1: a file this mod picked with persist, as a fresh session handle. Null when the grant is unknown to this mod or the file is gone.
releaseFile()(grantId: string): Promise<void>Folium 1.1: forgets a persisted grant. URLs already handed out keep working this session.
embed()(container: HTMLElement, url: string, options?: { title?: string; allow?: string[] }): FoliumDisposerEmbeds an external page in container as a sandboxed iframe. The URL's origin must be listed in the manifest embedOrigins (needs net.embed).
icon()(name: string, options?: FoliumIconOptions): Promise<SVGSVGElement | null>Folium 1.2: one of the host's icons (lucide, named as on lucide.dev, e.g. "play", "skip-forward") as a new <svg> element the mod owns; null for an unknown name. Works in every context, the export window included.

相关:FoliumFileHandle · FoliumDisposer · FoliumIconOptions

FoliumFetchInit ​

Request options for folium.net.fetch.

成员类型说明
method?'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'Default GET.
headers?Record<string, string>Request headers.
body?stringRequest body (text).
timeoutMs?numberDefault 15000, at most 60000.

FoliumFetchResponse ​

A fully read response (body at most 5 MB); text and json return synchronously.

成员类型说明
readonly okbooleanStatus is 2xx.
readonly statusnumberHTTP status.
readonly statusTextstringHTTP status text.
readonly headersReadonly<Record<string, string>>Response headers, lowercase names.
text()(): stringThe body as text.
json()<T = unknown>(): TThe body parsed as JSON; throws on invalid JSON.

FoliumNetService ​

folium.net.

成员类型说明
fetch()(url: string, init?: FoliumFetchInit): Promise<FoliumFetchResponse>Fetch through the host (no CORS limits); needs the net.fetch permission.

相关:FoliumFetchInit · FoliumFetchResponse

共享工具 ​

folium.lyrics 与 folium.theme:内置歌词动画使用的同一批纯函数,主窗口与导出窗口都可用。

FoliumWordSegment ​

One word from folium.lyrics.segmentWords.

成员类型说明
segmentstringThe segment text.
indexnumberUTF-16 offset of the segment in the line's fullText.
isWordLikebooleanFalse for whitespace and punctuation-only segments.

FoliumWordColorRange ​

A keyword-colored span of a line's fullText (UTF-16 offsets, end exclusive).

成员类型说明
startOffsetnumberStart offset in fullText (UTF-16).
endOffsetnumberEnd offset, exclusive.
colorstringCSS color from wordColors.
prioritynumberLonger and more specific matches rank higher.

FoliumLyricsHelpers ​

Folium 1.3: the pure lyric helpers builtin modes share, so a mod lays out, times and colors lines exactly as they do. Available in both contexts.

成员类型说明
getLineRenderEndTime()(line: FoliumLine | null | undefined): numberWhen the host stops showing the line: renderHints.renderEndTime. -Infinity for null.
segmentWords()(line: Pick<FoliumLine, 'fullText' | 'wordSegments'>): FoliumWordSegment[]The user's saved split when valid, otherwise Intl.Segmenter word segmentation.
getRecentCompletedLine()(lines: readonly FoliumLine[], lineIndex: number, time: number): FoliumLine | nullWith no active line (index -1): the last line already over, for subtitles in gaps.
getUpcomingLine()(lines: readonly FoliumLine[], lineIndex: number, time: number): FoliumLine | nullThe next line: after the active one, or the first still ahead when none is active.
getUpcomingLines()(lines: readonly FoliumLine[], lineIndex: number, count?: number): FoliumLine[]Up to count (default 2) lines after the active one; empty when none is active.
buildWordColorRanges()(fullText: string, wordColors: FoliumTheme['wordColors']): FoliumWordColorRange[]Non-overlapping keyword color spans of fullText for theme.wordColors.
resolveWordColor()(wordText: string, wordColors: FoliumTheme['wordColors'], fallbackColor: string, options?: { cjkMatchMode?: 'target-contains-token' | 'bidirectional-contains' | 'exact' }): stringThe keyword color of one word, or fallbackColor.

相关:FoliumLine · FoliumWordSegment · FoliumTheme · FoliumWordColorRange

FoliumThemeHelpers ​

Folium 1.3: theme resolution builtin modes use. Available in both contexts.

成员类型说明
resolveFontStack()(theme: Pick<FoliumTheme, 'fontStyle' | 'fontFamily' | 'fontFamilyStack'>): stringCSS font-family value for lyric text.
resolveTranslationFontStack()(theme: Pick<FoliumTheme, 'fontStyle' | 'fontFamily' | 'fontFamilyStack'>): stringCSS font-family value for translations and subtitles.
resolveFontWeight()(theme: Pick<FoliumTheme, 'fontWeight'> | null | undefined, fallback: number): numberThe theme's weight, normalized, or fallback.

相关:FoliumTheme

参数 schema ​

设置分区、visualizer / background 设置、tunings 与命令参数共用 FoliumParam。读到的值已合并默认值,写入按 schema 校验。

FoliumParamType ​

Field kinds: a slider, a text box, a switch, or a choice among options.

ts
type FoliumParamType = 'number' | 'text' | 'boolean' | 'select'

FoliumParamOption ​

One choice of a select field.

成员类型说明
valuestringThe stored value.
labelFoliumLabelWhat the user sees.

相关:FoliumLabel

FoliumParam ​

One declarative field. The same schema drives settings sections, visualizer settings, tunings of builtin modes and command parameters, and it is the only source of keys, defaults and validation for the values it describes.

成员类型说明
keystringValue key, unique within the schema.
typeFoliumParamTypeField kind.
labelFoliumLabelField label.
description?FoliumLabelHelp text.
group?FoliumLabelFields sharing a group label render together under that heading.
defaultValue?string | number | booleanUsed until the user changes the field; also what reset restores.
min?numbernumber: lower bound (values are clamped).
max?numbernumber: upper bound (values are clamped).
step?numbernumber: slider step. Default 1 when both bounds are integers, else 0.01.
placeholder?stringtext: placeholder.
options?FoliumParamOption[]select: the choices; values outside them are rejected.

相关:FoliumParamType · FoliumLabel · FoliumParamOption

FoliumParamValues ​

Values keyed by field key, defaults merged. Read-only; write through FoliumParamAccess.set.

ts
type FoliumParamValues = Readonly<Record<string, unknown>>

FoliumParamAccess ​

Read/write access to one schema's persisted values (defaults already merged).

成员类型说明
readonly schemareadonly FoliumParam[]The fields, as registered (invalid declarations dropped).
get()(): FoliumParamValuesCurrent values, defaults merged.
set()(patch: Record<string, unknown>): voidValidated against the schema: unknown keys are dropped, numbers clamped, selects checked.
reset()(): voidRestores every default.
subscribe()(listener: () => void): FoliumDisposerCalled after any value changes.

相关:FoliumParam · FoliumParamValues · FoliumDisposer

数据结构 ​

歌词行与主题与内置 visualizer 收到的 Line / Theme 同名同义,是宿主投影出的冻结副本。

FoliumLyricRuby ​

Ruby (furigana) over part of a syllable. Times in seconds on the lyric clock.

成员类型说明
textstringThe ruby text.
startTimenumberStart, seconds.
endTimenumberEnd, seconds.

FoliumLyricSyllable ​

One timed syllable of a word. Times in seconds on the lyric clock.

成员类型说明
textstringThe syllable text.
startTimenumberStart, seconds.
endTimenumberEnd, seconds.
endsWithSpace?booleanA space follows this syllable.
ruby?FoliumLyricRuby[]Ruby over this syllable.
obscene?booleanMarked explicit by the lyric source.
emptyBeat?numberBeats of silence after the syllable, from the lyric source.

相关:FoliumLyricRuby

FoliumLyricAlternateText ​

Another rendering of a line or vocal: a translation, a romanization, or another role from the lyric source.

成员类型说明
rolestring'translation', 'romanization' or another role from the lyric source.
language?stringBCP 47 language tag, when the source gives one.
textstringThe full text.
syllables?FoliumLyricSyllable[]Timed syllables, when the source has them.

相关:FoliumLyricSyllable

FoliumWord ​

One timed word of a line. Times in seconds on the lyric clock.

成员类型说明
textstringThe word text, including a trailing space when there is one.
startTimenumberStart, seconds.
endTimenumberEnd, seconds.
syllables?FoliumLyricSyllable[]Timed syllables, when the source has them.

相关:FoliumLyricSyllable

FoliumBackgroundVocal ​

A background vocal (harmony) attached to a line, timed and structured like a line.

成员类型说明
textstringThe full text.
startTimenumberStart, seconds.
endTimenumberEnd, seconds.
wordsFoliumWord[]Timed words.
agentId?stringThe singer, when the source names one.
translation?stringTranslation text.
romanization?stringRomanization text.
alternateTexts?FoliumLyricAlternateText[]All alternate texts from the source.

相关:FoliumWord · FoliumLyricAlternateText

FoliumLineTimingClass ​

How short a line is: micro and short lines get faster transitions.

ts
type FoliumLineTimingClass = 'normal' | 'short' | 'micro'

FoliumLineTransitionMode ​

How the host moves a line in and out: full, fast, or no transition.

ts
type FoliumLineTransitionMode = 'normal' | 'fast' | 'none'

FoliumWordRevealMode ​

How the host reveals the words of a line: full, fast, or all at once.

ts
type FoliumWordRevealMode = 'normal' | 'fast' | 'instant'

FoliumLineRenderHints ​

How the host times a line on screen; builtin modes read the same values.

成员类型说明
rawDurationnumberendTime - startTime, seconds.
timingClassFoliumLineTimingClassHow short the line is.
renderEndTimenumberWhen the host stops showing the line (endTime plus hold/tail).
lineTransitionModeFoliumLineTransitionModeHow the line moves in and out.
wordRevealModeFoliumWordRevealModeHow its words are revealed.

相关:FoliumLineTimingClass · FoliumLineTransitionMode · FoliumWordRevealMode

FoliumLine ​

One lyric line, the same fields and meanings as the host Line builtin visualizers receive. Times in seconds on the lyric clock.

成员类型说明
wordsFoliumWord[]Timed words; a line without word timing has one word spanning the line.
startTimenumberStart, seconds.
endTimenumberThe lyric's own end time. When the line leaves the screen is renderHints.renderEndTime.
fullTextstringThe whole line.
renderHintsFoliumLineRenderHintsAlways present: the host fills in hints the lyric source did not carry.
translation?stringTranslation text.
romanization?stringRomanization text.
alternateTexts?FoliumLyricAlternateText[]All alternate texts from the source, with language and role.
id?stringLine id from the source, when it has one.
agentId?stringThe singer, when the source names one.
songPart?stringSong part name from the source, e.g. Chorus.
blockIndex?numberIndex of the song part this line belongs to.
isChorus?booleanThe line is part of a chorus.
chorusEffect?'bars' | 'circles' | 'beams'The chorus effect builtin modes draw for it.
backgroundVocals?FoliumBackgroundVocal[]Background vocals. The host's legacy single backgroundVocal is folded in here, so this is the only place to look.
wordSegments?string[]The user's saved word split; join('') equals fullText. See folium.lyrics.segmentWords.

相关:FoliumWord · FoliumLineRenderHints · FoliumLyricAlternateText · FoliumBackgroundVocal

FoliumTheme ​

The current theme, the same fields and meanings as the host Theme builtin visualizers receive, plus isDaylight.

成员类型说明
namestringTheme name.
backgroundColorstringCSS color.
primaryColorstringCSS color of lyric text.
accentColorstringCSS color for highlights.
secondaryColorstringCSS color for secondary text.
fontStyle'sans' | 'serif' | 'mono'The builtin font family class.
fontFamily?stringThe user's chosen family, if any. For a CSS font-family value use folium.theme.resolveFontStack(theme).
fontFamilyStack?string[]The user's font fallback list.
fontWeight?numberFor a concrete weight use folium.theme.resolveFontWeight(theme, fallback).
animationIntensity'calm' | 'normal' | 'chaotic'How lively animations should be; builtin modes scale motion by it.
wordColors?{ word: string; color: string }[]Keyword colors; match them with folium.lyrics.buildWordColorRanges / resolveWordColor.
lyricsIcons?string[]Decorative icon names the theme suggests.
provider?stringWhere the theme came from (e.g. an AI provider).
description?stringTheme description.
isDaylightbooleanFolium addition: builtin modes get this as a separate isDaylight prop.

FoliumSong ​

A song as mods see it. Pass it back to the host (playSong, enqueue, beforePlay.replaceWith) only when it carries a ref.

成员类型说明
idstring | nullThe song id at its source, as a string; null when unknown.
titlestringSong title.
artiststringArtists joined with /.
albumstring | nullAlbum name.
sourcestring | nullWhere the song comes from: an Omni provider id, 'local', 'navidrome', …
refstring | nullOpaque handle the host can turn back into the real song (playSong, enqueue, beforePlay.replaceWith). Valid for the session; null when the DTO was not built from a host song.

FoliumPlaybackState ​

The host player state.

ts
type FoliumPlaybackState = 'playing' | 'paused' | 'stopped'

FoliumPlaybackSnapshot ​

The whole playback picture, as main entries read it with api.runtime.getPlaybackSnapshot().

成员类型说明
songFoliumSong | nullThe displayed song.
stateFoliumPlaybackStateThe player state.
positionnumberSeconds.
durationnumberSeconds; 0 when unknown.
linesFoliumLine[]Lyrics of the displayed song.
themeFoliumTheme | nullThe current theme.
visualizerModestring | nullThe current lyric animation mode id.

相关:FoliumSong · FoliumPlaybackState · FoliumLine · FoliumTheme

实验接口 ​

需要在 mod.json 的 experimental 里选用,经 folium.experimental[name] 访问;任何 minor 版本都可能变化。

FoliumProviderSong ​

EXPERIMENTAL (omni.providers): a song as a mod provider describes it.

成员类型说明
idstringSong id within this provider.
titlestringSong title.
artistsstring[]Artist names.
album?stringAlbum name.
coverUrl?stringCover image URL.
durationMs?numberDuration in milliseconds.

FoliumAudioQuality ​

Audio quality levels an Omni provider may be asked for.

ts
type FoliumAudioQuality = 'standard' | 'high' | 'lossless' | 'hires'

FoliumOmniProviderDef ​

EXPERIMENTAL (omni.providers): an online music source. The host adapts it to its provider contract; songs from it play, queue and show lyrics like any online song. Use folium.net.fetch for network access.

成员类型说明
idstringLocal provider id.
displayNamestringFull name shown in source pickers.
shortName?stringShort badge name.
search?()(query: string, page: { limit: number; offset: number }): Promise<{ items: FoliumProviderSong[]; hasMore: boolean; total?: number }>Search songs; page is offset-based.
getSong?()(id: string): Promise<FoliumProviderSong | null>One song by id.
getAudioUrl?()(song: FoliumProviderSong, quality: FoliumAudioQuality): Promise<{ url: string; expiresAt?: number } | null>A playable URL for the song at a quality.
getLyrics?()(song: FoliumProviderSong): Promise<{ lrc: string; translationLrc?: string } | null>LRC text (plus optional translation LRC); the host parses it.

相关:FoliumProviderSong · FoliumAudioQuality

基础类型 ​

FOLIUM_VERSION ​

The Folium version this host implements; mods read it at runtime as folium.host.folium.

ts
const FOLIUM_VERSION = Object.freeze({ major: 1, minor: 3 })

FoliumId ​

modid:name, like a Forge ResourceLocation. The mod id part is added by the host.

ts
type FoliumId = string

FoliumLabel ​

Localized text keyed by locale (zh-CN, en, in); the host falls back to en, then to any entry.

ts
type FoliumLabel = Record<string, string | undefined>

FoliumDisposer ​

Undoes a registration, subscription or mount. Safe to call more than once.

ts
type FoliumDisposer = () => void

main 入口(Node) ​

mod.json 的 main 指向一个 .cjs / .js 文件,导出 activate(api),在主进程运行,拥有完整 Node.js 权限。 api 由 electron/modSystem/modApi.cjs 创建:

js
module.exports = function activate(api) {
  api.rpc.handle('export', async (spec) => api.render.exportVideo(spec));
  return () => { /* 可选:模组停用时清理 */ };
};
成员说明
api.manifest冻结的清单副本
api.host{ folium: { major, minor }, folia },与客户端的 folium.host 相同
api.log.info / warn / error(message, details?)写入模组日志;error 会显示在模组面板
api.storage.data.get / set / has / delete / keys异步;需要 filesystem.data;与客户端 folium.storage 共用同一个数据文件(上限 1 MB)
api.lifecycle.onDeactivate(fn)模组被停用、重载或应用退出时调用;activate 返回的函数效果相同
api.runtime.getPlaybackSnapshot()当前播放状态的 FoliumPlaybackSnapshot,渲染端尚未推送时为 null;需要 runtime.playback
api.rpc.handle(name, fn)注册客户端 folium.rpc.call(name, ...args) 调用的函数;名称匹配 /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/,参数与返回值需可 JSON 序列化
api.render.exportVideo(spec)按当前歌曲、动画模式与参数导出透明视频;需要 render.export 与 ffmpeg
api.experimental预留,目前为空

Released under AGPL-3.0