theme - Theme & CSS Variables
Palette base colors (strings or DEFAULT) and derivation sources must be valid colors. Invalid input throws; failed updates or reinstalls preserve the previous configuration, cache, and injected CSS. Custom values and overrides may still contain literal CSS such as var(...) and are not parsed as base colors.
Design-system-level theme color generator. Automatically generates complete shade palettes, semantic colors, and dark mode from base colors, outputting CSS variables that can be injected into the DOM or used as strings for SSR.
🎨 Try it live
Want to see theme colors in action? Try Theme Studio — enter a primary color and generate a full color scheme in one click.
Plugin Dependencies
Theme reuses the palette algorithms. Registering the theme plugin is sufficient.
Independent theme instances
The named createTheme(options, { styleId? }?) export needs no global registration. Each instance owns its configuration, cache and style element. Input configurations and returned options/variables are defensive snapshots; generator callbacks retain function identity.
import { createTheme } from '@xpyjs/color/plugins/theme'
const panel = createTheme({ colors: { primary: '#1890ff' }, cssSelector: '.panel', darkMode: 'class', darkSelector: '.panel.dark' })
panel.inject()
panel.update({ colors: { primary: '#722ed1' } }).getVars('dark')
panel.remove()Methods: getCss(), getVars('light' | 'dark') (default light), getOptions(), update(partial, deep = true), inject() and remove(). Updates validate before replacing state and owned DOM content. Remove deletes only the owned element, retains configuration and permits reinjection. SSR inject returns CSS without DOM access.
Style IDs are generated unless explicitly supplied. Existing same-ID elements are never adopted or overwritten. Choose distinct cssSelector/darkSelector or prefix settings when themes should not overlap in CSS; state isolation does not change the cascade. The legacy global plugin keeps its API and style element.
Dark snapshots include unchanged light/custom variables. With darkMode disabled they equal the light snapshot. xcolor.getThemeVars('dark') and generateTheme(options).darkVars expose the same complete dark snapshot.
Install
import xcolor from '@xpyjs/color'
import themePlugin from '@xpyjs/color/plugins/theme'
xcolor.use(themePlugin, {
colors: {
primary: '#1890ff'
}
})Note:
colorsis required.
Configuration Options
The options parameter of xcolor.use(themePlugin, options) has the type XColorThemeOptions:
| Option | Type | Default | Description |
|---|---|---|---|
colors | Record<string, ColorConfig> | — | Required. Color definitions; keys become part of CSS variable names |
prefix | string | '--x' | CSS variable name prefix |
type | ThemePaletteType | 'antd' | Palette generation type |
shades | Shade[] | [50,100,...,950] | Shade levels to generate |
semantic | boolean | true | Whether to auto-generate semantic colors (hover, active, etc.) |
darkMode | 'class' | 'media' | false | false | Dark mode strategy |
darkSelector | string | '.dark' | Dark mode CSS selector (when darkMode: 'class') |
cssSelector | string | ':root' | Light mode CSS selector |
format | ThemeCssFormat | 'hex' | Output format for CSS variable values |
derive | boolean | XColorThemeDeriveOptions | false | Auto-derive a full set of semantic role colors (secondary, success, etc.) from a source color. See Derive Role Colors |
Color Definition (ColorConfig)
Each color entry supports three formats:
xcolor.use(themePlugin, {
colors: {
// ① String shorthand — auto-generate full palette + semantic colors
primary: '#1890ff',
// ② Object with DEFAULT — auto-generate + override specific values
success: {
DEFAULT: '#52c41a',
hover: '#73d13d'
},
// ③ Object without DEFAULT — pure custom, no palette generation
brand: {
logo: '#ff6600',
accent: { light: '#ce93d8', dark: '#7b1fa2' }
}
}
})Want to see the output quickly? Check the Full Examples for generated CSS.
DEFAULT is a Reserved Key
DEFAULT is a special reserved key that identifies the base color of a color entry. When detected, the plugin uses it as the reference color for palette generation (mapped to shade 500) and automatically generates the full shade palette and semantic colors. DEFAULT itself does not appear in the generated CSS variable names.
Do not use DEFAULT for any other purpose — it has special meaning at any nesting level.
Palette
The palette uses the algorithm from the palette plugin to generate shades, supporting multiple preset types or a custom function. For more details, refer to the palette plugin documentation.
// Use linear interpolation
xcolor.use(themePlugin, {
type: 'linear',
colors: { primary: '#1890ff' }
})
// Use custom function
xcolor.use(themePlugin, {
type: (baseColor, shades) => {
return shades.map((s) => {
const factor = (s - 500) / 500
return factor < 0
? xcolor(baseColor.toHex()).lighten(Math.abs(factor) * 50)
: xcolor(baseColor.toHex()).darken(factor * 50)
})
},
colors: { primary: '#1890ff' }
})Semantic Colors
When semantic: true (default), the following semantic color variables are auto-generated:
| Semantic Name | Shade | Purpose |
|---|---|---|
hover | 400 | Hover state |
active | 600 | Active/pressed state |
disabled | 200 | Disabled state |
border | 300 | Border color |
bg | 50 | Background color |
text | 900 | Text color |
const vars = xcolor.getThemeVars()
vars['--x-primary-hover'] // color at shade 400
vars['--x-primary-active'] // color at shade 600
vars['--x-primary-bg'] // color at shade 50You can override auto-generated semantic colors using the object format:
xcolor.use(themePlugin, {
colors: {
primary: {
DEFAULT: '#1890ff',
hover: '#40a9ff' // override the auto-generated hover color
}
}
})Dark Mode
// CSS class strategy
xcolor.use(themePlugin, {
colors: { primary: '#1890ff' },
darkMode: 'class',
darkSelector: '.dark' // default
})
// Generates: .dark { --x-primary-500: ...; }
// CSS media query strategy
xcolor.use(themePlugin, {
colors: { primary: '#1890ff' },
darkMode: 'media'
})
// Generates: @media (prefers-color-scheme: dark) { :root { --x-primary-500: ...; } }Dark mode automatically reverses the shade order and reduces saturation and brightness to suit dark backgrounds.
Output Format
| Value | Example |
|---|---|
'hex' | #1890ff |
'rgb' | rgb(24, 144, 255) |
'hsl' | hsl(209, 100%, 55%) |
Derive Role Colors
In real-world projects, you often only have a single brand color (e.g. primary) and want to automatically generate success, warning, error, info, and secondary colors that share a unified visual style — same saturation and brightness feel, but different hues. The derive option is designed for exactly this.
Quick Start
xcolor.use(themePlugin, {
colors: { primary: '#1890ff' },
derive: true
})With just derive: true, the plugin derives 5 semantic role colors from primary. Each role gets the same full shade palette (50–950) and semantic state colors (hover, active, etc.) as any manually-provided color.
Generated CSS variables (example):
:root {
/* primary — user-provided */
--x-primary-50: #e4f6ff;
--x-primary-500: #1890ff;
--x-primary-900: #002766;
--x-primary-hover: ...;
--x-primary-active: ...;
/* ... more primary shades & semantic colors ... */
/* secondary — auto-derived (complementary) */
--x-secondary-50: #fff7e6;
--x-secondary-500: #d58a18;
--x-secondary-900: ...;
--x-secondary-hover: ...;
/* ... */
/* success — auto-derived (green region) */
--x-success-50: #f0fff4;
--x-success-500: #00a66b;
--x-success-900: ...;
/* ... */
/* warning — auto-derived (amber/orange) */
--x-warning-500: #c1751d;
/* ... */
/* error — auto-derived (red) */
--x-error-500: #d56059;
/* ... */
/* info — auto-derived (blue-cyan) */
--x-info-500: #2199d9;
/* ... */
}Color values above are illustrative; actual values depend on the source color and algorithm.
Derive Options (XColorThemeDeriveOptions)
For fine-grained control, pass an options object:
xcolor.use(themePlugin, {
colors: { primary: '#1890ff' },
derive: {
from: 'primary', // source color key
algorithm: 'oklch', // derivation algorithm
roles: ['success', 'warning', 'error', 'info', 'secondary'],
hues: { success: 150 }, // override role hue anchor
alias: { warning: 'warn' }, // rename output variables
chromaScale: 1, // chroma scaling
lightnessShift: 0 // lightness offset
}
})| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Explicit toggle when using the object form |
from | string | 'primary' | Source color key. Must be a string color or an object with DEFAULT in colors |
algorithm | 'oklch' | 'hsl' | 'oklch' | Derivation color space. oklch is perceptually uniform (recommended) |
roles | BuiltinRole[] | all 5 | Roles to derive. Can be trimmed to derive only some |
hues | Partial<Record<BuiltinRole, number>> | — | Override default hue anchors (degrees) |
alias | Partial<Record<BuiltinRole, string>> | — | Role name → CSS variable name segment mapping |
chromaScale | number | 1 | Chroma multiplier for derived colors. >1 increases saturation, <1 decreases |
lightnessShift | number | 0 | Lightness offset for derived colors (OKLCh L, range 0–1). Positive = lighter, negative = darker |
Default Role Hue Anchors
Each role has a default hue anchor in OKLCh space:
| Role | Default Hue (°) | Color Region | Meaning |
|---|---|---|---|
error | 27 | Red | Error / failure / danger |
warning | 70 | Amber / Orange | Warning / caution |
success | 145 | Green | Success / confirmation |
info | 235 | Blue-cyan | Informational / neutral |
secondary | source + 180° | Complementary | Accent / secondary |
The diagram below illustrates the OKLCh hue wheel with each role's anchor position. The source color "primary" (blue, 209°) keeps its lightness L and chroma C unchanged — only the hue H is rotated to each role's anchor, producing visually harmonious companion colors:
How it works: OKLCh is the polar form of OKLab with three independent dimensions — L (lightness), C (chroma), and H (hue). Derivation only rotates H to the target anchor while keeping L and C unchanged, ensuring all derived colors match the source in perceived brightness and saturation. This is the key advantage over HSL, where the same L value produces visibly different brightness at different hues.
Algorithm Comparison
| OKLCh (recommended) | HSL | |
|---|---|---|
| Color space | OKLCh (perceptually uniform) | HSL |
| Lightness consistency | ✅ Perceived brightness uniform across hues | ❌ Same L value looks different at different hues |
| Saturation consistency | ✅ Chroma is perceptually uniform | ❌ Notable saturation differences between pure hues |
| Best for | Design systems seeking visual consistency | Simple use cases or legacy browser needs |
User Override Priority
Colors explicitly provided in colors always take priority over derived values:
xcolor.use(themePlugin, {
colors: {
primary: '#1890ff',
success: '#52c41a' // user-defined success, derivation skipped
},
derive: true
})
const vars = xcolor.getThemeVars()
vars['--x-success-500'] // '#52c41a' — user value
vars['--x-error-500'] // derived value
vars['--x-warning-500'] // derived valueRenaming Roles (alias)
If your project uses different naming conventions, rename the output variables via alias:
xcolor.use(themePlugin, {
colors: { primary: '#1890ff' },
derive: {
alias: {
warning: 'warn', // --x-warn-500 instead of --x-warning-500
error: 'danger' // --x-danger-500 instead of --x-error-500
}
}
})
const vars = xcolor.getThemeVars()
vars['--x-warn-500'] // exists
vars['--x-danger-500'] // exists
vars['--x-warning-500'] // undefined
vars['--x-error-500'] // undefinedWhen using alias, user overrides should also use the alias key:
xcolor.use(themePlugin, {
colors: {
primary: '#1890ff',
warn: '#faad14' // override using alias 'warn'
},
derive: {
alias: { warning: 'warn' }
}
})Deriving Only Some Roles
xcolor.use(themePlugin, {
colors: { primary: '#1890ff' },
derive: {
roles: ['success', 'error'] // only these two
}
})
const vars = xcolor.getThemeVars()
vars['--x-success-500'] // exists
vars['--x-error-500'] // exists
vars['--x-warning-500'] // undefined — not requested
vars['--x-info-500'] // undefined — not requestedUsing a Custom Source Color
xcolor.use(themePlugin, {
colors: {
brand: '#6200ea' // use brand color as derivation source
},
derive: {
from: 'brand' // derive from brand instead of primary
}
})Adjusting Chroma & Lightness
// Derived colors with slightly lower saturation — softer look
xcolor.use(themePlugin, {
colors: { primary: '#1890ff' },
derive: {
chromaScale: 0.85, // reduce chroma by 15%
lightnessShift: 0.03 // slightly brighter
}
})Static Methods
The following methods are registered on the xcolor factory and are available after calling xcolor.use(themePlugin, options).
injectTheme()
Inject the generated theme CSS into <head>, creating or updating a <style id="xcolor-theme"> element.
In non-browser environments (Node.js / SSR), this method only returns the CSS string without DOM manipulation.
Return value: string (CSS string)
xcolor.use(themePlugin, {
colors: { primary: '#1890ff', success: '#52c41a' }
})
xcolor.injectTheme()
// → <style id="xcolor-theme">:root { --x-primary-500: #1890ff; ... }</style>getThemeCss()
Get the complete CSS string without injecting into the DOM.
Return value: string
const css = xcolor.getThemeCss()
// ':root {\n --x-primary-500: #1890ff;\n ...\n}\n'getThemeVars()
Get a flat map of CSS variable names to values.
Return value: Record<string, string>
const vars = xcolor.getThemeVars()
// { '--x-primary-500': '#1890ff', '--x-primary-hover': '#41a9ff', ... }
// getThemeVars() always returns a hex snapshot; format only affects getThemeCss()/injectTheme() CSS text.updateTheme(options, deep?)
Update the theme configuration. By default, uses deep merge — only pass the fields you want to change; everything else is preserved. Pass false as the second argument to use shallow merge (replaces top-level keys entirely). If a <style> tag was previously injected, the DOM is automatically updated.
| Parameter | Type | Default | Description |
|---|---|---|---|
options | Partial<XColorThemeOptions> | — | Partial configuration to merge |
deep | boolean | true | Whether to deep merge. false uses shallow merge |
// Deep merge (default) — only the primary color changes
xcolor.updateTheme({ colors: { primary: '#722ed1' } })
// Shallow merge — replaces the entire colors object
xcolor.updateTheme({ colors: { primary: '#722ed1' } }, false)
// Switch to dark mode
xcolor.updateTheme({ darkMode: 'class' })
// Modify multiple options at once
xcolor.updateTheme({
prefix: '--color',
format: 'rgb',
colors: { primary: '#1890ff', danger: '#ff4d4f' }
})removeTheme()
Remove the injected <style> tag and clear the cached theme result.
xcolor.removeTheme()Full Examples
Basic Usage
import xcolor from '@xpyjs/color'
import themePlugin from '@xpyjs/color/plugins/theme'
xcolor.use(themePlugin, {
colors: {
primary: '#1890ff',
success: '#52c41a',
warning: '#faad14',
danger: '#ff4d4f'
}
})
// Inject into the page
xcolor.injectTheme()Generated CSS:
:root {
--x-primary-50: #e4f6ff;
--x-primary-100: #bbe7ff;
/* ... more shades ... */
--x-primary-500: #1890ff;
/* ... */
--x-primary-900: #002766;
--x-primary-hover: #41a9ff;
--x-primary-active: #0a6ed9;
--x-primary-disabled: #92d5ff;
--x-primary-border: #6ac1ff;
--x-primary-bg: #e4f6ff;
--x-primary-text: #002766;
/* success, warning, danger likewise ... */
}Full Configuration with Dark Mode
xcolor.use(themePlugin, {
prefix: '--app',
type: 'antd',
colors: {
primary: '#1890ff',
success: { DEFAULT: '#52c41a', hover: '#73d13d' },
brand: { logo: '#ff6600' }
},
darkMode: 'class',
darkSelector: '[data-theme="dark"]',
format: 'hex'
})
// Get CSS for SSR
const css = xcolor.getThemeCss()Dynamic Theme Switching
// User selects a new theme color
function onColorChange(newColor: string) {
xcolor.updateTheme({
colors: { primary: newColor }
})
// If injectTheme() was called before, the DOM updates automatically
}Type Exports
import type {
XColorThemeOptions,
ThemeResult,
ThemeCssFormat,
ColorConfig,
BuiltinRole,
ThemeDeriveAlgorithm,
XColorThemeDeriveOptions
} from '@xpyjs/color/plugins/theme'Generate CSS in SSR or build tools
import { generateTheme } from '@xpyjs/color/plugins/theme'
const light = generateTheme({ colors: { primary: '#1890ff' } })
const dark = generateTheme({ colors: { primary: '#177ddc' } })
console.log(light.vars['--x-primary'], dark.vars['--x-primary'])Each call returns a separate result. It uses the current color parsers and does not update the installed theme or the DOM. getThemeVars() returns a snapshot. Invalid updates or replacements leave an already injected theme in place. Treat selectors and raw CSS values passed to the theme generator as caller-controlled CSS.
