Skip to content

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.

ts
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 ​

ts
import xcolor from '@xpyjs/color'
import themePlugin from '@xpyjs/color/plugins/theme'

xcolor.use(themePlugin, {
  colors: {
    primary: '#1890ff'
  }
})

Note: colors is required.

① Base Color#1890ffprimary② Shade Palette (50–900)50100200300400500600700800900base③ Semantic Colorsbg← 50disabled← 200border← 300hover← 400active← 600text← 900④ CSS Variables--x-primary-500: #1890ff; --x-primary-hover: #40a9ff; ...

Configuration Options ​

The options parameter of xcolor.use(themePlugin, options) has the type XColorThemeOptions:

OptionTypeDefaultDescription
colorsRecord<string, ColorConfig>—Required. Color definitions; keys become part of CSS variable names
prefixstring'--x'CSS variable name prefix
typeThemePaletteType'antd'Palette generation type
shadesShade[][50,100,...,950]Shade levels to generate
semanticbooleantrueWhether to auto-generate semantic colors (hover, active, etc.)
darkMode'class' | 'media' | falsefalseDark mode strategy
darkSelectorstring'.dark'Dark mode CSS selector (when darkMode: 'class')
cssSelectorstring':root'Light mode CSS selector
formatThemeCssFormat'hex'Output format for CSS variable values
deriveboolean | XColorThemeDeriveOptionsfalseAuto-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:

ts
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.

ts
// 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 NameShadePurpose
hover400Hover state
active600Active/pressed state
disabled200Disabled state
border300Border color
bg50Background color
text900Text color
ts
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 50

You can override auto-generated semantic colors using the object format:

ts
xcolor.use(themePlugin, {
  colors: {
    primary: {
      DEFAULT: '#1890ff',
      hover: '#40a9ff'   // override the auto-generated hover color
    }
  }
})

Dark Mode ​

☀️ Light Mode50100200300400500600700800900🌙 Dark ModeDark mode reverses shade order, reduces saturation & brightness
ts
// 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 ​

ValueExample
'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 ​

ts
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):

css
: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:

ts
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
  }
})
FieldTypeDefaultDescription
enabledbooleantrueExplicit toggle when using the object form
fromstring'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)
rolesBuiltinRole[]all 5Roles to derive. Can be trimmed to derive only some
huesPartial<Record<BuiltinRole, number>>—Override default hue anchors (degrees)
aliasPartial<Record<BuiltinRole, string>>—Role name → CSS variable name segment mapping
chromaScalenumber1Chroma multiplier for derived colors. >1 increases saturation, <1 decreases
lightnessShiftnumber0Lightness 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:

RoleDefault Hue (°)Color RegionMeaning
error27RedError / failure / danger
warning70Amber / OrangeWarning / caution
success145GreenSuccess / confirmation
info235Blue-cyanInformational / neutral
secondarysource + 180°ComplementaryAccent / secondary
→
primary
error
warning
success
info
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:

OKLCh Hue WheelH = hue angle (0°–360°)0°90°180°270°error 27°warning 70°success 145°primary209°info 235°secondary(209°+180°=29°)

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 spaceOKLCh (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 forDesign systems seeking visual consistencySimple use cases or legacy browser needs

User Override Priority ​

Colors explicitly provided in colors always take priority over derived values:

ts
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 value

Renaming Roles (alias) ​

If your project uses different naming conventions, rename the output variables via alias:

ts
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']   // undefined

When using alias, user overrides should also use the alias key:

ts
xcolor.use(themePlugin, {
  colors: {
    primary: '#1890ff',
    warn: '#faad14'       // override using alias 'warn'
  },
  derive: {
    alias: { warning: 'warn' }
  }
})

Deriving Only Some Roles ​

ts
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 requested

Using a Custom Source Color ​

ts
xcolor.use(themePlugin, {
  colors: {
    brand: '#6200ea'  // use brand color as derivation source
  },
  derive: {
    from: 'brand'     // derive from brand instead of primary
  }
})

Adjusting Chroma & Lightness ​

ts
// 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)

ts
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

ts
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>

ts
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.

ParameterTypeDefaultDescription
optionsPartial<XColorThemeOptions>—Partial configuration to merge
deepbooleantrueWhether to deep merge. false uses shallow merge
ts
// 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.

ts
xcolor.removeTheme()

Full Examples ​

Basic Usage ​

ts
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:

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 ​

ts
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 ​

ts
// 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 ​

ts
import type {
  XColorThemeOptions,
  ThemeResult,
  ThemeCssFormat,
  ColorConfig,
  BuiltinRole,
  ThemeDeriveAlgorithm,
  XColorThemeDeriveOptions
} from '@xpyjs/color/plugins/theme'

Generate CSS in SSR or build tools ​

ts
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.

Released under the MIT License.