ThemeRuntime API Reference
Complete API reference for the ThemeRuntime class from @tokiforge/core.
Overview
ThemeRuntime is the core runtime engine for theme management. It handles theme switching, CSS variable injection, and system theme detection.
Import
import { ThemeRuntime } from '@tokiforge/core';Constructor
new ThemeRuntime(config)
Create a new theme runtime instance.
Signature:
constructor(config: ThemeConfig)Parameters:
config: ThemeConfig- Theme configuration
Config:
interface ThemeConfig {
themes: Theme[];
defaultTheme?: string;
}
interface Theme {
name: string;
tokens: DesignTokens;
}Example:
import { ThemeRuntime } from '@tokiforge/core';
const runtime = new ThemeRuntime({
themes: [
{ name: 'light', tokens: lightTokens },
{ name: 'dark', tokens: darkTokens },
],
defaultTheme: 'light',
});Instance Methods
init(selector?, prefix?)
Initialize the runtime and inject CSS variables for the default theme.
Signature:
init(selector?: string, prefix?: string): voidParameters:
selector?: string- CSS selector (default::root)prefix?: string- CSS variable prefix (default:hf)
Example:
runtime.init(':root', 'hf');Note: This method is SSR-safe and does nothing in server environments.
applyTheme(themeName, selector?, prefix?)
Switch to a specific theme and inject its CSS variables.
Signature:
applyTheme(
themeName: string,
selector?: string,
prefix?: string
): voidParameters:
themeName: string- Name of the theme to applyselector?: string- CSS selector (default::root)prefix?: string- CSS variable prefix (default:hf)
Example:
runtime.applyTheme('dark');
runtime.applyTheme('light', ':root', 'myapp');Throws:
Errorif theme name is not found
Events:
Dispatches a tokiforge:theme-change custom event:
window.addEventListener('tokiforge:theme-change', (e) => {
const { theme, tokens } = e.detail;
console.log('Theme changed to:', theme);
});getCurrentTheme()
Get the name of the currently active theme.
Signature:
getCurrentTheme(): stringReturns: string - Current theme name
Example:
const current = runtime.getCurrentTheme();
console.log(current); // 'light' or 'dark'getThemeTokens(themeName?)
Get tokens for a specific theme or the current theme.
Signature:
getThemeTokens(themeName?: string): DesignTokensParameters:
themeName?: string- Theme name (optional, defaults to current theme)
Returns: DesignTokens - Theme tokens
Example:
// Get current theme tokens
const tokens = runtime.getThemeTokens();
// Get specific theme tokens
const darkTokens = runtime.getThemeTokens('dark');Throws:
Errorif theme name is not found
getAvailableThemes()
Get all available theme names.
Signature:
getAvailableThemes(): string[]Returns: string[] - Array of theme names
Example:
const themes = runtime.getAvailableThemes();
console.log(themes); // ['light', 'dark']nextTheme()
Cycle to the next available theme.
Signature:
nextTheme(): stringReturns: string - New theme name
Example:
const newTheme = runtime.nextTheme();
console.log(newTheme); // 'dark' (if current was 'light')Behavior:
- Cycles through themes in order
- Wraps around to first theme after last
destroy()
Cleanup runtime and remove injected CSS.
Signature:
destroy(): voidExample:
runtime.destroy();Use Cases:
- Component unmounting
- Cleanup before reinitialization
- Memory management
Instance Methods (continued)
watchSystemTheme(callback)
Watch for system theme changes and call the callback.
Signature:
watchSystemTheme(
callback: (theme: 'light' | 'dark') => void
): () => voidParameters:
callback: (theme: 'light' | 'dark') => void- Callback function
Returns: () => void - Unwatch function
Example:
const unwatch = runtime.watchSystemTheme((theme) => {
console.log('System theme changed to:', theme);
runtime.applyTheme(theme);
});
// Stop watching
unwatch();Note: Returns a no-op function in server environments.
Static Methods
ThemeRuntime.detectSystemTheme()
Detect the system's color scheme preference.
Signature:
static detectSystemTheme(): 'light' | 'dark'Returns: 'light' | 'dark' - System theme preference
Example:
const systemTheme = ThemeRuntime.detectSystemTheme();
console.log(systemTheme); // 'light' or 'dark'
// Apply system theme
runtime.applyTheme(systemTheme);Note: Returns 'light' in server environments.
Usage Examples
Basic Setup
import { ThemeRuntime } from '@tokiforge/core';
const runtime = new ThemeRuntime({
themes: [
{ name: 'light', tokens: lightTokens },
{ name: 'dark', tokens: darkTokens },
],
defaultTheme: 'light',
});
// Initialize
runtime.init();
// Switch theme
runtime.applyTheme('dark');System Theme Detection
import { ThemeRuntime } from '@tokiforge/core';
const runtime = new ThemeRuntime(config);
// Apply system theme on init
const systemTheme = ThemeRuntime.detectSystemTheme();
runtime.applyTheme(systemTheme);
// Watch for system theme changes
runtime.watchSystemTheme((theme) => {
runtime.applyTheme(theme);
});Custom Selector and Prefix
import { ThemeRuntime } from '@tokiforge/core';
const runtime = new ThemeRuntime(config);
// Use custom selector and prefix
runtime.init('body.theme-light', 'myapp');
// Apply theme with custom settings
runtime.applyTheme('dark', 'body.theme-dark', 'myapp');Theme Change Events
import { ThemeRuntime } from '@tokiforge/core';
const runtime = new ThemeRuntime(config);
runtime.init();
// Listen for theme changes
window.addEventListener('tokiforge:theme-change', (e) => {
const { theme, tokens } = e.detail;
console.log('Theme:', theme);
console.log('Tokens:', tokens);
});
// Trigger change
runtime.applyTheme('dark');SSR-Safe Usage
import { ThemeRuntime } from '@tokiforge/core';
const runtime = new ThemeRuntime(config);
// Safe in both server and client
if (typeof window !== 'undefined') {
runtime.init();
runtime.applyTheme('dark');
}Cleanup
import { ThemeRuntime } from '@tokiforge/core';
const runtime = new ThemeRuntime(config);
runtime.init();
// Later, cleanup
runtime.destroy();CSS Variable Injection
The runtime injects CSS variables into the document head:
<style id="tokiforge-theme">
:root {
--hf-color-primary: #7C3AED;
--hf-color-accent: #06B6D4;
--hf-spacing-md: 16px;
}
</style>The style element is reused and updated on theme changes for performance.
Best Practices
- Initialize once - Call
init()once per runtime instance - Use consistent selectors - Use the same selector/prefix throughout
- Cleanup on unmount - Call
destroy()when component unmounts - Handle SSR - Check for
windowbefore using in SSR environments - Listen to events - Use
tokiforge:theme-changeevent for reactivity
Related
- See TokenParser API for parsing tokens
- Check TokenExporter API for exporting tokens
- View Core API for complete overview
- Learn about Theming Guide for theme strategies