用途
Leonardo Contrast Colors 是一个面向可访问性配色的技能,围绕 @adobe/leonardo-contrast-colors 库展开。当用户需要构建基于对比度的调色板、检查 WCAG 对比度,或生成符合无障碍要求的颜色主题时,可使用该技能。
主要能力
- 通过 BackgroundColor 定义每个主题的背景及其中性色阶,色阶按目标对比度比例生成。
- 通过 Color 定义语义色(如 blue、red),在指定对比度比例下生成色阶,支持自定义命名。
- 通过 Theme 组合一个 BackgroundColor 与一个或多个 Color,并设置亮度、对比度倍数、饱和度、输出格式与对比度公式。
- 支持 WCAG 2 与 WCAG 3(APCA)两种对比度公式。
- 提供 contrast、convertColorValue、luminance、createScale 等工具函数。
- 支持运行时修改主题属性,并重新读取输出。
使用方式
安装:
npm i @adobe/leonardo-contrast-colors
ESM 导入(推荐):
import { Theme, Color, BackgroundColor, contrast, convertColorValue, luminance, createScale } from '@adobe/leonardo-contrast-colors';
创建 BackgroundColor:
const gray = new BackgroundColor({
name: 'gray',
colorKeys: ['#cacaca'],
ratios: [2, 3, 4.5, 8]
});
创建 Color:
const blue = new Color({
name: 'blue',
colorKeys: ['#5CDBFF', '#0000FF'],
colorspace: 'LCH',
ratios: [3, 4.5]
});
创建 Theme:
const theme = new Theme({
colors: [gray, blue, red],
backgroundColor: gray,
lightness: 97,
contrast: 1,
saturation: 100,
output: 'HEX',
formula: 'wcag2'
});
读取主题输出:
- theme.contrastColors:数组,首元素为 { background: '#...' },其后每个颜色对象包含 name 与 values([{ name, contrast, value }])。
- theme.contrastColorPairs:扁平对象,如 { gray100: '#e0e0e0', blue100: '#b18cff', ... }。
- theme.contrastColorValues:仅包含颜色字符串的扁平数组。
生成 CSS 变量示例:
for (const item of theme.contrastColors) {
if (item.background) {
document.documentElement.style.setProperty('--background', item.background);
} else {
for (const v of item.values) {
document.documentElement.style.setProperty(`--${v.name}`, v.value);
}
}
}
运行时修改主题:
- theme.lightness = 8
- theme.contrast = 1.2
- theme.saturation = 80
- theme.output = 'RGB'
- theme.backgroundColor = otherBackgroundColor
- theme.colors = [gray, blue, red, green]
增删改颜色:
- theme.addColor = newColor
- theme.removeColor = { name: 'red' } 或 theme.removeColor = redColorInstance
- theme.updateColor = { name: 'red', ratios: [3, 4.5, 7] }
任何 setter 之后,重新读取 theme.contrastColors(或 pairs/values),它们在访问时计算。
工具函数:
- contrast(foregroundRgbArray, backgroundRgbArray, baseV?, method?):返回对比度比例,method 为 'wcag2'(默认)或 'wcag3',RGB 数组为 [r, g, b](0–255)。
- convertColorValue(colorString, format, object?):将颜色字符串转换为指定格式,object === true 时返回通道对象。
- luminance(r, g, b):sRGB 相对亮度(0–1)。
- createScale({ swatches, colorKeys, colorSpace?, shift?, fullScale?, smooth?, distributeLightness?, sortColor?, asFun? }):构建插值色阶(不做对比度目标),返回颜色字符串数组,asFun: true 时返回色阶函数。
适用场景
- 构建符合 WCAG 2 AA(正常文本 4.5:1)、AAA(7:1)、大文本(3:1)的配色。
- 使用 ratios: [3, 4.5] 同时覆盖大文本与正常文本,并可用对象命名,如 { 'brand--large': 3, 'brand--normal': 4.5 }。
- 使用 formula: 'wcag3' 启用 APCA,按 WCAG 3 指南解读 Lc 值。
- 生成设计令牌或 CSS 变量。
- 构建非无障碍调色板或键值间过渡时使用 createScale。
限制与说明
- 负对比度比例(如 -1.5、-3)用于比背景更浅的颜色(如深色模式文本),命名使用小数增量(如 gray25、gray50)。
- 插值色彩空间支持:LCH、LAB、RGB、HSL、HSV、HSLuv、CAM02、CAM02p、OKLAB、OKLCH。
- 输出格式支持:HEX、RGB、HSL、HSV、HSLuv、LAB、LCH、CAM02、CAM02p、OKLAB、OKLCH,值遵循 W3C CSS Color Module Level 4。
- 建议使用 LCH 或 LAB 进行插值以获得感知均匀的色阶。
- 完整 API 参数、类型与 setter 列表可参考 references/api.md。
- 关于收费、价格、平台支持等具体信息暂未提供。