Skip to content

简体中文

English

theme - 主题与 CSS 变量 ​

用于生成色阶的基础色(字符串或 DEFAULT)及派生源必须是有效颜色。无效输入会抛错;更新或重装失败时保留原配置、缓存和已注入 CSS。纯自定义值与覆盖项仍允许 var(...) 等原样 CSS,不作为基础色解析。

设计系统级的主题色生成器。从基础色自动生成完整的色阶面板、语义色和暗色模式,并输出为 CSS 变量,可直接注入到页面 DOM 或作为字符串用于 SSR。

🎨 在线体验

想要直观体验主题配色效果?试试 配色工坊 — 输入一个主色即可一键生成完整配色方案。

插件依赖

主题复用 palette 的色阶算法,使用时只需注册 theme。

独立主题实例 ​

命名导出 createTheme(options, { styleId? }?) 不需要注册全局插件。每个实例独立持有配置、缓存和样式元素,输入和读取的配置/变量均为防御性快照;自定义生成函数保留函数身份。

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()

方法:getCss()、getVars('light' | 'dark')(默认 light)、getOptions()、update(partial, deep = true)、inject()、remove()。update 验证通过后才提交状态并更新自身 DOM;remove 仅移除自身元素,保留配置,可再次 inject。SSR inject 只返回 CSS。

默认自动分配样式 ID,也可显式指定唯一 styleId;已有同名元素不会被接管或覆盖。多个实例若不应在 CSS 中重叠,需要设置不同 cssSelector、darkSelector 或 prefix;状态隔离不改变 CSS 层叠规则。旧全局插件继续使用原有 API 和样式元素。

getVars('dark') 是完整暗色变量快照,包含没有暗色覆盖的浅色/自定义变量;没有启用 darkMode 时与浅色内容相同。全局 xcolor.getThemeVars('dark') 及 generateTheme(options).darkVars 提供相同能力,返回变量仍是具体颜色值。

安装 ​

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

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

注意:colors 为必填项。

① 基础色#1890ffprimary② 色阶面板 (50–900)50100200300400500600700800900基准色③ 语义色bg← 50disabled← 200border← 300hover← 400active← 600text← 900④ CSS 变量--x-primary-500: #1890ff; --x-primary-hover: #40a9ff; ...

配置选项 ​

xcolor.use(themePlugin, options) 的 options 参数类型为 XColorThemeOptions:

选项类型默认值说明
colorsRecord<string, ColorConfig>—必填。颜色定义,键名作为 CSS 变量名的一部分
prefixstring'--x'CSS 变量名前缀
typeThemePaletteType'antd'色阶生成类型
shadesShade[][50,100,...,950]要生成的色阶级别
semanticbooleantrue是否自动生成语义色(hover、active 等)
darkMode'class' | 'media' | falsefalse暗色模式策略
darkSelectorstring'.dark'暗色模式 CSS 选择器(darkMode: 'class' 时)
cssSelectorstring':root'浅色模式 CSS 选择器
formatThemeCssFormat'hex'CSS 变量值的输出格式
deriveboolean | XColorThemeDeriveOptionsfalse是否从源色自动派生整套语义角色色(secondary、success 等)。详见 Derive 派生整套语义色

颜色定义 (ColorConfig) ​

每个颜色条目支持三种写法:

ts
xcolor.use(themePlugin, {
  colors: {
    // ① 字符串简写 — 自动生成完整色阶 + 语义色
    primary: '#1890ff',

    // ② 带 DEFAULT 的对象 — 自动生成 + 覆盖某些值
    success: {
      DEFAULT: '#52c41a',
      hover: '#73d13d'
    },

    // ③ 不含 DEFAULT 的对象 — 纯自定义,不生成色阶
    brand: {
      logo: '#ff6600',
      accent: { light: '#ce93d8', dark: '#7b1fa2' }
    }
  }
})

想快速看到效果?参考 完整示例 查看生成的 CSS 输出。

DEFAULT 是保留键名

DEFAULT 是一个特殊保留键名,用于标识颜色条目的基础色。当检测到 DEFAULT 时,插件会将其作为色阶生成的基准色(对应 shade 500),并自动生成完整的色阶面板和语义色。DEFAULT 本身不会出现在生成的 CSS 变量名中。

请勿将 DEFAULT 用于其他用途,它在任何嵌套层级中都具有特殊含义。

色阶 ​

色阶使用了 palette 插件的算法进行生成,支持多种预设类型,也可以传入自定义函数。更多细节请参考 palette 插件文档。

ts
// 使用线性插值
xcolor.use(themePlugin, {
  type: 'linear',
  colors: { primary: '#1890ff' }
})

// 使用自定义函数
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: true(默认)时,自动生成以下语义色变量:

语义名对应色阶用途
hover400悬停状态
active600激活/按下状态
disabled200禁用状态
border300边框颜色
bg50背景色
text900文本颜色
ts
const vars = xcolor.getThemeVars()
vars['--x-primary-hover']    // 色阶 400 对应的颜色
vars['--x-primary-active']   // 色阶 600 对应的颜色
vars['--x-primary-bg']       // 色阶 50 对应的颜色

可通过对象写法覆盖自动生成的语义色:

ts
xcolor.use(themePlugin, {
  colors: {
    primary: {
      DEFAULT: '#1890ff',
      hover: '#40a9ff'   // 覆盖自动生成的 hover 色
    }
  }
})

暗色模式 ​

☀️ 浅色模式50100200300400500600700800900🌙 暗色模式暗色模式自动反转色阶顺序,降低饱和度和明度
ts
// CSS class 策略
xcolor.use(themePlugin, {
  colors: { primary: '#1890ff' },
  darkMode: 'class',
  darkSelector: '.dark'  // 默认值
})
// 生成:.dark { --x-primary-500: ...; }

// CSS media 策略
xcolor.use(themePlugin, {
  colors: { primary: '#1890ff' },
  darkMode: 'media'
})
// 生成:@media (prefers-color-scheme: dark) { :root { --x-primary-500: ...; } }

暗色模式会自动反转色阶顺序,并降低饱和度和明度以适应暗色背景。

输出格式 ​

值示例
'hex'#1890ff
'rgb'rgb(24, 144, 255)
'hsl'hsl(209, 100%, 55%)

Derive 派生整套语义色 ​

在实际项目中,通常只需一个品牌主色(如 primary),就希望自动得到 success、warning、error、info、secondary 等配套色——它们的饱和度、明度与主色保持统一风格,但色相各异。derive 选项就是为此设计的。

快速开始 ​

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

只需一行 derive: true,即可从 primary 自动派生 5 个语义角色色,每个角色都会像 primary 一样生成完整的色阶面板(50–950)和语义状态色(hover、active 等)。

生成的 CSS 变量(示例):

css
:root {
  /* primary — 用户提供 */
  --x-primary-50:  #e4f6ff;
  --x-primary-500: #1890ff;
  --x-primary-900: #002766;
  --x-primary-hover: ...;
  --x-primary-active: ...;
  /* ... 更多 primary 色阶 & 语义色 ... */

  /* secondary — 自动派生(互补色) */
  --x-secondary-50:  #fff7e6;
  --x-secondary-500: #d58a18;
  --x-secondary-900: ...;
  --x-secondary-hover: ...;
  /* ... */

  /* success — 自动派生(绿色系) */
  --x-success-50:  #f0fff4;
  --x-success-500: #00a66b;
  --x-success-900: ...;
  /* ... */

  /* warning — 自动派生(琥珀/橙色系) */
  --x-warning-500: #c1751d;
  /* ... */

  /* error — 自动派生(红色系) */
  --x-error-500: #d56059;
  /* ... */

  /* info — 自动派生(蓝青色系) */
  --x-info-500: #2199d9;
  /* ... */
}

以上色值仅为示意,实际值取决于源色和算法。

派生配置 (XColorThemeDeriveOptions) ​

当需要更精细的控制时,可传入对象配置:

ts
xcolor.use(themePlugin, {
  colors: { primary: '#1890ff' },
  derive: {
    from: 'primary',       // 源色键名
    algorithm: 'oklch',    // 派生算法
    roles: ['success', 'warning', 'error', 'info', 'secondary'],
    hues: { success: 150 },         // 覆盖角色锚点色相
    alias: { warning: 'warn' },   // 重命名输出变量
    chromaScale: 1,        // 色度缩放
    lightnessShift: 0      // 明度偏移
  }
})
字段类型默认值说明
enabledbooleantrue对象形式时的显式开关
fromstring'primary'源色键名。必须是 colors 中一个字符串色值或带 DEFAULT 的对象
algorithm'oklch' | 'hsl''oklch'派生色彩空间。oklch 感知均匀,推荐使用
rolesBuiltinRole[]全 5 个要派生的角色列表。可裁剪为只派生部分角色
huesPartial<Record<BuiltinRole, number>>—覆盖角色默认锚点色相(单位:度)
aliasPartial<Record<BuiltinRole, string>>—角色名 → 输出 CSS 变量名段的映射
chromaScalenumber1派生色的色度倍率。大于 1 增加饱和度,小于 1 降低
lightnessShiftnumber0派生色的明度偏移(OKLCh 的 L,范围 0–1)。正值变亮,负值变暗

默认角色锚点色相 ​

每个角色在 OKLCh 空间中有一个默认色相锚点:

角色默认色相 (°)色彩区域含义
error27红色错误 / 失败 / 危险
warning70琥珀 / 橙色警告 / 注意
success145绿色成功 / 确认
info235蓝青色信息 / 中性提示
secondary源色 + 180°互补色副色 / 强调色
→
primary
error
warning
success
info
secondary

下图展示了 OKLCh 色相环上各角色的锚点位置。源色 primary(蓝色 209°)的 明度 L 和 色度 C 保持不变,仅旋转色相 H 至各角色的锚点,从而产出风格统一的配套色:

OKLCh 色相环H = 色相角度 (0°–360°)0°90°180°270°error 27°warning 70°success 145°primary209°info 235°secondary(209°+180°=29°)

原理说明:OKLCh 是 OKLab 的极坐标形式,L(明度)、C(色度/彩度)、H(色相)三个维度互相独立。派生时仅旋转 H(色相角度),保持 L 和 C 不变,确保所有派生色与源色在"亮暗程度"和"饱和程度"上感知一致。这是 OKLCh 相比 HSL 的最大优势——HSL 中相同的 L 值在不同色相下实际亮度差异很大。

算法对比 ​

OKLCh(推荐)HSL
色彩空间OKLCh(感知均匀)HSL
明度一致性✅ 不同色相间明度感知一致❌ 相同 L 值在不同色相下亮度差异大
饱和度一致性✅ Chroma 感知均匀❌ 纯色间饱和度差异明显
适用场景追求视觉统一的设计系统简单场景或浏览器兼容性优先

用户覆盖优先 ​

用户在 colors 中显式提供的颜色始终优先于派生结果:

ts
xcolor.use(themePlugin, {
  colors: {
    primary: '#1890ff',
    success: '#52c41a'    // 用户自定义 success,不使用派生值
  },
  derive: true
})

const vars = xcolor.getThemeVars()
vars['--x-success-500'] // '#52c41a' — 用户值
vars['--x-error-500']   // 派生值
vars['--x-warning-500'] // 派生值

角色重命名 (alias) ​

如果你的项目使用不同的命名约定,可以通过 alias 重命名输出变量:

ts
xcolor.use(themePlugin, {
  colors: { primary: '#1890ff' },
  derive: {
    alias: {
      warning: 'warn',    // --x-warn-500 而非 --x-warning-500
      error: 'danger'     // --x-danger-500 而非 --x-error-500
    }
  }
})

const vars = xcolor.getThemeVars()
vars['--x-warn-500']    // 存在
vars['--x-danger-500']  // 存在
vars['--x-warning-500'] // undefined
vars['--x-error-500']   // undefined

使用别名时,用户覆盖也应使用别名键名:

ts
xcolor.use(themePlugin, {
  colors: {
    primary: '#1890ff',
    warn: '#faad14'       // 使用别名 'warn' 覆盖
  },
  derive: {
    alias: { warning: 'warn' }
  }
})

只派生部分角色 ​

ts
xcolor.use(themePlugin, {
  colors: { primary: '#1890ff' },
  derive: {
    roles: ['success', 'error']  // 只派生这两个
  }
})

const vars = xcolor.getThemeVars()
vars['--x-success-500'] // 存在
vars['--x-error-500']   // 存在
vars['--x-warning-500'] // undefined — 未请求
vars['--x-info-500']    // undefined — 未请求

使用自定义源色 ​

ts
xcolor.use(themePlugin, {
  colors: {
    brand: '#6200ea'  // 使用品牌色作为派生源
  },
  derive: {
    from: 'brand'     // 从 brand 而非 primary 派生
  }
})

调整色度与明度 ​

ts
// 派生色稍微降低饱和度,更柔和
xcolor.use(themePlugin, {
  colors: { primary: '#1890ff' },
  derive: {
    chromaScale: 0.85,      // 色度降低 15%
    lightnessShift: 0.03    // 稍微提亮
  }
})

静态方法 ​

以下方法注册在 xcolor 工厂上,在调用 xcolor.use(themePlugin, options) 后可用。

injectTheme() ​

将生成的主题 CSS 注入到 <head> 中,创建或更新 <style id="xcolor-theme"> 标签。

在非浏览器环境(Node.js / SSR)中,此方法仅返回 CSS 字符串,不操作 DOM。

返回值:string(CSS 字符串)

ts
xcolor.use(themePlugin, {
  colors: { primary: '#1890ff', success: '#52c41a' }
})
xcolor.injectTheme()
// → <style id="xcolor-theme">:root { --x-primary-500: #1890ff; ... }</style>

getThemeCss() ​

获取完整的 CSS 字符串,不注入 DOM。

返回值:string

ts
const css = xcolor.getThemeCss()
// ':root {\n  --x-primary-500: #1890ff;\n  ...\n}\n'

getThemeVars() ​

获取扁平的 CSS 变量映射表。

返回值:Record<string, string>

ts
const vars = xcolor.getThemeVars()
// { '--x-primary-500': '#1890ff', '--x-primary-hover': '#41a9ff', ... }
// getThemeVars() 始终返回 hex 快照;format 只影响 getThemeCss()/injectTheme() 的 CSS 文本。

updateTheme(options, deep?) ​

更新主题配置。默认使用深合并,只需传入要修改的字段,其余保持不变。传入 false 作为第二个参数可切换为浅合并(直接替换顶层键)。如果之前已注入了 <style> 标签,DOM 会自动更新。

参数类型默认值说明
optionsPartial<XColorThemeOptions>—要合并的部分配置
deepbooleantrue是否深合并。false 时使用浅合并
ts
// 深合并(默认)— 只修改主色调,其他保留
 xcolor.updateTheme({ colors: { primary: '#722ed1' } })

// 浅合并 — 替换整个 colors 对象
xcolor.updateTheme({ colors: { primary: '#722ed1' } }, false)

// 切换到暗色模式
xcolor.updateTheme({ darkMode: 'class' })

// 同时修改多个选项
xcolor.updateTheme({
  prefix: '--color',
  format: 'rgb',
  colors: { primary: '#1890ff', danger: '#ff4d4f' }
})

removeTheme() ​

移除注入的 <style> 标签并清除缓存。

ts
xcolor.removeTheme()

完整示例 ​

基础用法 ​

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'
  }
})

// 注入到页面
xcolor.injectTheme()

生成的 CSS:

css
:root {
  --x-primary-50: #e4f6ff;
  --x-primary-100: #bbe7ff;
  /* ... 更多色阶 ... */
  --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 同理 ... */
}

带暗色模式的完整配置 ​

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'
})

// 获取 CSS 用于 SSR
const css = xcolor.getThemeCss()

动态切换主题色 ​

ts
// 用户选择新的主题色
function onColorChange(newColor: string) {
  xcolor.updateTheme({
    colors: { primary: newColor }
  })
  // 如果之前调用过 injectTheme(),DOM 会自动更新
}

类型导出 ​

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

在 SSR 或构建工具中生成 CSS ​

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'])

每次调用返回独立结果。它使用当前颜色解析器,已注册主题与 DOM 不受调用影响。getThemeVars() 返回快照。主题更新或重装失败时,已注入的样式会保留。传给主题生成器的选择器和原样 CSS 值由调用方控制。

Released under the MIT License.