feat(design): 加 unlucky-design 令牌 crate(M3 色彩/排版/形状/动效/图标)

D26 把视觉基线锁到 Material 3 Expressive,本 crate 是「UI 整体性」的地基:
令牌唯一真源,后续 iced 页面只消费不新增。零第三方依赖、零 UI 框架依赖
(cargo tree -p unlucky-design --edges normal 只有它自己一行)。

- 色彩:49 个 M3 语义角色 × light/dark,种子色派生 6 条 tone 调色板;
  tone 轴严格用 CIELAB L*(偏差 ≤1),色相/彩度用 OKLCh 近似 CAM16 并在
  模块文档里写明口径与已知偏差(不宣称是标准 HCT 动态取色)
- 对比度:26 组文字对 × 6 组种子 × 2 模式全部 ≥4.5:1;3 条例外显式登记
  (Outline 非文字 3:1、OutlineVariant 装饰、SurfaceVariant 是容器色)
- 排版:M3 type scale 15 档 + 三平台字体族回退栈(只写族名,不内嵌受限字体)
- 形状/高程/动效:Expressive 形状刻度 + shape morph 数据、elevation 级别与
  surface container 映射、时长/缓动/弹簧(纯函数可采样)
- 图标:24 个从 Slint 版迁移的 SVG path + 4 个新增,IconKind 冻结只可末尾追加;
  写明 Slint 的 stroke-width 是绝对像素、SVG 是 viewBox 用户单位的语义差异,
  换算封装成 Icon::stroke_width
- 组件档位表:20 个组件的形状/高程/字体/动效一次取全

TODO(M63):elevation shadow 的 blur/offset/alpha 与四组弹簧参数是占位值,
接口先定、数值待玻璃视觉规格表(tower 已通告边界)。
This commit is contained in:
AskaEth committed 2026-11-01 15:34:04 +08:00
1 parent fef0922073
commit 65ca0ed29a
25 files changed
+4622 -1

No files matched your search

+253
View File
@@ -0,0 +1,253 @@
//! # 色彩令牌(M3 color roles)
//!
//! 49 个 M3 语义色角色 × light/dark 两套,全部由**一个种子色**派生([`Palettes`]),
//! 再按官方 tone 映射表解析成具体色值([`Scheme`])。
//!
//! ```no_run
//! use unlucky_design::color::{Color, Role, Scheme, SchemeFlavor};
//!
//! let light = Scheme::baseline(SchemeFlavor::Light);
//! let surface = light.get(Role::Surface);
//! let on_surface = light.get(Role::OnSurface);
//! assert!(on_surface.contrast_ratio(surface) > 4.5);
//!
//! // 用户自定义强调色:表面中性色不动,只换强调族。
//! let custom = Scheme::from_accent(SchemeFlavor::Light, Color::from_hex("#006A5C").unwrap());
//! assert_eq!(custom.get(Role::Surface), surface);
//! ```
//!
//! ## 口径声明:这是 M3 **近似**,不是标准 HCT 动态取色
//!
//! 标准 M3 的调色板建在 **HCT**(CAM16 色相/彩度 + CIELAB `L*`)上。本 crate 不实现 CAM16,
//! 用的是 **OKLCh**(色相/彩度)+ **CIELAB `L*`**(tone 轴)。具体差异:
//!
//! | 轴 | 标准 M3 | 本实现 | 影响 |
//! |---|---|---|---|
//! | tone | CIELAB `L*` | CIELAB `L*`(二分反解 OKLab 明度,误差 ≤1 tone) | **无偏差**:tone 定义严格对齐 |
//! | 色相 | CAM16 hue | OKLCh hue(种子色相原样保留) | 绝对色相角不同,但「同族色相恒定」这个性质成立;派生色(tertiary = +60°)偏移量与 M3 不完全相同 |
//! | 彩度 | CAM16 chroma(如 primary 36 / secondary 16 / neutral 6) | OKLCh chroma(标定值见 [`palettes`]) | 数值量纲不同,语义等价;饱和度观感与官方色板会有可见差别(不是抄错,是量纲换算不通用) |
//! | gamut | CAM16 gamut mapping(按色相压缩彩度) | 按 tone 二分压 OKLCh 彩度进 sRGB | 极端 tone(5/95+)的饱和度可能比官方色板略低 |
//! | 动态色 | Material You 从壁纸取 5 组种子 | 只用**一个**种子 + 固定派生规则 | 没有「多色壁纸取色」能力;本启动器用不到(壁纸取色是安卓端特性) |
//! | 对比度模式 | Dynamic Contrast 三档(standard/medium/high) | 只有 standard | 不提供高对比方案;WCAG AA 在 standard 下已满足(见 [`super::color::contrast`] 与测试) |
//!
//! 结论:**不许对外宣称「标准 M3 动态取色」**。要对比官方色板时按上表解释差异,
//! 不要试图逐值对齐 material-color-utilities 的输出(那需要 CAM16 + HCT,是另一个量级的实现)。
//!
//! ## 对比度纪律(WCAG AA)
//!
//! - 所有 `on-*` 与其承载色(`*-container`、`primary`、`surface`)都满足 **≥ 4.5:1**;
//! 这一条由 `tests/contrast_aa.rs` 全表验证,且因为 tone 轴固定,**换任何种子色都成立**
//! (WCAG 对比度只取决于相对亮度,而 tone 直接钉住 L*)。
//! - 例外(显式登记,非缺陷):
//! - [`Role::Outline`] 对 [`Role::Surface`]:M3 定义的**非文字**元素(输入框描边),
//! 目标 3:1,实测 light 4.29:1 / dark 6.5:1;
//! - [`Role::OutlineVariant`] 对 [`Role::Surface`]:纯装饰分隔线,M3 不要求对比度下限;
//! - [`Role::SurfaceVariant`]:它是**容器**色(不是前景),不参与对比度门禁。
//! - 禁用态按 M3 的 alpha 叠加([`state::DISABLED_CONTENT_ALPHA`]),刻意低于 AA。
pub mod palettes;
pub mod roles;
pub mod scheme;
pub mod space;
pub mod state;
pub mod tonal;
pub use palettes::{PaletteSlot, Palettes, BASELINE_SEED};
pub use roles::Role;
pub use scheme::{Scheme, SchemeFlavor, SCRIM_ALPHA, SHADOW_ALPHA};
pub use state::StateLayer;
pub use tonal::TonalPalette;
/// sRGB 颜色(8 bit/通道 + alpha),刻意不用第三方颜色类型:本 crate 零依赖。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Color {
/// 红通道。
pub r: u8,
/// 绿通道。
pub g: u8,
/// 蓝通道。
pub b: u8,
/// alpha(0 = 全透明,255 = 不透明)。
pub a: u8,
}
impl Color {
/// 不透明颜色。
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b, a: 255 }
}
/// 带 alpha 的颜色(`a` 为 0..=255)。
pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
Self { r, g, b, a }
}
/// 纯黑。
pub const BLACK: Color = Color::rgb(0, 0, 0);
/// 纯白。
pub const WHITE: Color = Color::rgb(255, 255, 255);
/// 从 `#RRGGBB` / `#RGB` / `#AARRGGBB` 解析(不合法返回 `None`)。
///
/// 只给配置读取与测试用——UI 代码里**不许出现色字面量**,一律走 [`Role`]。
pub fn from_hex(text: &str) -> Option<Self> {
let hex = text.trim().trim_start_matches('#');
let parse = |s: &str| u8::from_str_radix(s, 16).ok();
match hex.len() {
3 => {
let d = |i: usize| {
let v = parse(&hex[i..i + 1])?;
Some(v * 17)
};
Some(Self::rgb(d(0)?, d(1)?, d(2)?))
}
6 => Some(Self::rgb(
parse(&hex[0..2])?,
parse(&hex[2..4])?,
parse(&hex[4..6])?,
)),
8 => Some(Self::rgba(
parse(&hex[2..4])?,
parse(&hex[4..6])?,
parse(&hex[6..8])?,
parse(&hex[0..2])?,
)),
_ => None,
}
}
/// 不透明部分转 `#RRGGBB`(alpha < 255 时附 `#AARRGGBB` 形式)。
pub fn to_hex(self) -> String {
if self.a == 255 {
format!("#{:02X}{:02X}{:02X}", self.r, self.g, self.b)
} else {
format!("#{:02X}{:02X}{:02X}{:02X}", self.a, self.r, self.g, self.b)
}
}
/// 改 alpha(`alpha` 0..1,越界夹取)。
pub fn with_alpha(self, alpha: f32) -> Self {
Self {
a: (alpha.clamp(0.0, 1.0) * 255.0).round() as u8,
..self
}
}
/// alpha 归一化到 0..1。
pub fn alpha(self) -> f32 {
f32::from(self.a) / 255.0
}
/// 是否完全不透明。
pub fn is_opaque(self) -> bool {
self.a == 255
}
/// WCAG 相对亮度(0..1,按 sRGB→XYZ 的 Y 行计算)。
pub fn relative_luminance(self) -> f32 {
let lin = |c: u8| space::srgb_to_linear(f32::from(c) / 255.0);
space::luminance([lin(self.r), lin(self.g), lin(self.b)])
}
/// CIELAB `L*`(0..100)——这就是 M3 的 **tone**。
///
/// 调色板按这条轴生成,验收也按这条轴断言;想知道某个色值「是几号 tone」就用它。
pub fn lstar(self) -> f32 {
space::lstar_from_luminance(self.relative_luminance())
}
/// WCAG 对比度(1..21)。`self` 与 `other` 都不透明时才严格;带 alpha 时先算「不计 alpha」的值。
pub fn contrast_ratio(self, other: Self) -> f32 {
let a = self.relative_luminance();
let b = other.relative_luminance();
let (hi, lo) = if a > b { (a, b) } else { (b, a) };
(hi + 0.05) / (lo + 0.05)
}
/// alpha 合成:`self` 叠在 `bg` 之上,返回不透明结果。
///
/// 这是 M3 状态层/禁用态/遮罩的唯一合成口径(非预乘 alpha)。
pub fn over(self, bg: Self) -> Self {
let sa = self.alpha();
if sa >= 1.0 {
return self;
}
let blend = |fg: u8, b: u8| {
let v = f32::from(fg) * sa + f32::from(b) * (1.0 - sa);
v.round().clamp(0.0, 255.0) as u8
};
let a = sa + bg.alpha() * (1.0 - sa);
Self {
r: blend(self.r, bg.r),
g: blend(self.g, bg.g),
b: blend(self.b, bg.b),
a: (a * 255.0).round().clamp(0.0, 255.0) as u8,
}
}
/// 两色线性插值(`t` 0..1),用于动画中间帧(GPU 路径的 shape morph 用得上)。
pub fn lerp(self, other: Self, t: f32) -> Self {
let t = t.clamp(0.0, 1.0);
let mix = |a: u8, b: u8| {
(f32::from(a) + (f32::from(b) - f32::from(a)) * t)
.round()
.clamp(0.0, 255.0) as u8
};
Self {
r: mix(self.r, other.r),
g: mix(self.g, other.g),
b: mix(self.b, other.b),
a: mix(self.a, other.a),
}
}
/// 从线性 RGB(0..1,可越界)构造:先夹取再 sRGB 编码。
fn from_linear_f32(rgb: [f32; 3]) -> Self {
let enc = |c: f32| {
(space::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0)
.round()
.clamp(0.0, 255.0) as u8
};
Self::rgb(enc(rgb[0]), enc(rgb[1]), enc(rgb[2]))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_roundtrip() {
let c = Color::from_hex("#6750A4").expect("合法 hex");
assert_eq!(c, Color::rgb(0x67, 0x50, 0xA4));
assert_eq!(c.to_hex(), "#6750A4");
assert_eq!(Color::from_hex("6750a4"), Some(c));
assert_eq!(Color::from_hex("#FFF"), Some(Color::WHITE));
assert_eq!(Color::from_hex("#80FF0000").map(|c| c.a), Some(0x80));
assert_eq!(Color::from_hex("#12345"), None);
assert_eq!(Color::from_hex("zzzzzz"), None);
}
#[test]
fn contrast_extremes() {
assert!((Color::BLACK.contrast_ratio(Color::WHITE) - 21.0).abs() < 0.01);
assert!((Color::WHITE.contrast_ratio(Color::WHITE) - 1.0).abs() < 0.001);
}
#[test]
fn over_composites_correctly() {
let black_50 = Color::BLACK.with_alpha(0.5);
let got = black_50.over(Color::WHITE);
// with_alpha 量化到 128/255 = 0.50196,所以结果落在 127(不是 128)。
assert_eq!((got.r, got.a), (127, 255));
}
#[test]
fn lerp_hits_endpoints() {
let a = Color::rgb(0, 0, 0);
let b = Color::rgb(255, 255, 255);
assert_eq!(a.lerp(b, 0.0), a);
assert_eq!(a.lerp(b, 1.0), b);
assert_eq!(a.lerp(b, 0.5).r, 128);
}
}
+141
View File
@@ -0,0 +1,141 @@
//! 六条 tone 调色板的集合(M3 scheme 的原料)。
//!
//! 角色 → 调色板槽位 → tone 的三段映射在 [`super::scheme`];这里只负责「种子 → 六条调色板」。
use super::tonal::TonalPalette;
use super::Color;
/// M3 baseline 种子色(与 material-color-utilities 的默认基线同值)。
pub const BASELINE_SEED: Color = Color::rgb(0x67, 0x50, 0xA4);
/// 调色板槽位(M3 的六条 tonal palette)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaletteSlot {
/// 主调色板(种子色相)。
Primary,
/// 次调色板(同色相、低彩度)。
Secondary,
/// 第三调色板(种子色相 +60°,中彩度)。
Tertiary,
/// 中性调色板(近零彩度的表面色)。
Neutral,
/// 中性变体调色板(比中性略彩色,做分隔与次级容器)。
NeutralVariant,
/// 错误调色板(固定红相)。
Error,
}
// 下面几个常数是**我们的标定值**(OKLCh 彩度单位),不是 M3 的 CAM16 chroma:
// CAM16 的 chroma 36/16/24/6/8 量纲与本实现不同,直接照抄会得到过饱和的色板。
/// 次色的彩度上限。
const SECONDARY_CHROMA: f32 = 0.055;
/// 第三色的彩度上限。
const TERTIARY_CHROMA: f32 = 0.085;
/// 中性的彩度上限(几乎是灰)。
const NEUTRAL_CHROMA: f32 = 0.008;
/// 中性变体的彩度上限。
const NEUTRAL_VARIANT_CHROMA: f32 = 0.016;
/// 错误色的色相(OKLCh 红相)。
const ERROR_HUE_DEG: f32 = 25.0;
/// 错误色的彩度上限。
const ERROR_CHROMA: f32 = 0.18;
/// 第三色调色板的色相偏移。
const TERTIARY_HUE_SHIFT_DEG: f32 = 60.0;
/// 一套完整的六条调色板。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Palettes {
/// 主要调色板。
pub primary: TonalPalette,
/// 次要调色板。
pub secondary: TonalPalette,
/// 第三调色板。
pub tertiary: TonalPalette,
/// 中性调色板。
pub neutral: TonalPalette,
/// 中性变体调色板。
pub neutral_variant: TonalPalette,
/// 错误调色板。
pub error: TonalPalette,
}
impl Palettes {
/// 出厂基线(种子 `#6750A4`,等价 M3 baseline)。
pub fn baseline() -> Self {
Self::from_seed(BASELINE_SEED)
}
/// 从一个种子色派生全套调色板。
pub fn from_seed(seed: Color) -> Self {
let primary = TonalPalette::from_color(seed);
Self {
primary,
secondary: primary.limited_chroma(SECONDARY_CHROMA),
tertiary: primary
.rotated(TERTIARY_HUE_SHIFT_DEG)
.limited_chroma(TERTIARY_CHROMA),
neutral: primary.with_chroma(NEUTRAL_CHROMA),
neutral_variant: primary.with_chroma(NEUTRAL_VARIANT_CHROMA),
error: TonalPalette::new(ERROR_HUE_DEG, ERROR_CHROMA),
}
}
/// 只换强调色:primary/secondary/tertiary 跟着新强调色走,**表面中性色保持不变**。
///
/// 这是「用户自定义强调色」的正确语义——换强调色不该让整个界面底色变脏;
/// 也因为 tone 轴固定,任何色相都能自动满足 WCAG AA(不需要再算一遍对比度)。
pub fn with_accent(self, accent: Color) -> Self {
let accent_primary = TonalPalette::from_color(accent);
Self {
primary: accent_primary,
secondary: accent_primary.limited_chroma(SECONDARY_CHROMA),
tertiary: accent_primary
.rotated(TERTIARY_HUE_SHIFT_DEG)
.limited_chroma(TERTIARY_CHROMA),
..self
}
}
/// 按槽位取调色板。
pub fn slot(&self, slot: PaletteSlot) -> TonalPalette {
match slot {
PaletteSlot::Primary => self.primary,
PaletteSlot::Secondary => self.secondary,
PaletteSlot::Tertiary => self.tertiary,
PaletteSlot::Neutral => self.neutral,
PaletteSlot::NeutralVariant => self.neutral_variant,
PaletteSlot::Error => self.error,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn baseline_seed_is_the_primary_palette_hue() {
let palettes = Palettes::baseline();
let seed_lch = super::super::space::Oklch::from_color(BASELINE_SEED);
let delta = (palettes.primary.hue_deg() - seed_lch.hue_deg).abs();
assert!(delta < 0.01, "primary 调色板应保持种子色相,偏差 {delta}°");
}
#[test]
fn accent_override_keeps_surfaces() {
let base = Palettes::baseline();
let accent = Color::rgb(0x00, 0x6A, 0x5C);
let swapped = base.with_accent(accent);
assert_eq!(swapped.neutral, base.neutral);
assert_eq!(swapped.neutral_variant, base.neutral_variant);
assert_eq!(swapped.error, base.error);
assert_ne!(swapped.primary.hue_deg(), base.primary.hue_deg());
}
#[test]
fn neutral_variant_is_less_chromatic_than_primary() {
let palettes = Palettes::baseline();
assert!(palettes.neutral.chroma() < palettes.neutral_variant.chroma());
assert!(palettes.neutral_variant.chroma() < palettes.secondary.chroma());
}
}
+276
View File
@@ -0,0 +1,276 @@
//! M3 语义色角色:`Role` 枚举是**唯一的名字清单**(49 个,M3 基础集全覆盖)。
//!
//! 后续 iced 页面不许另起名字(如 `bg-card` / `fg-primary`)——Fluent 时代的旧名到此为止,
//! 要表达「卡片底」就用 [`Role::SurfaceContainerLow`],要表达「次要文字」就用
//! [`Role::OnSurfaceVariant`](对应关系见 `DevDocs/SubAgentsTalk/design-令牌约定.md`)。
/// M3 语义色角色(49 个)。
///
/// 顺序即 [`Role::ALL`] 的顺序,也是 [`super::Scheme`] 内部数组的下标:
/// **只允许在末尾追加**,插到中间会静默改变已存盘的颜色映射。
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Role {
/// 主色:主操作填充、选中指示。
Primary,
/// 主色之上的前景(文字/图标)。
OnPrimary,
/// 主色容器:次级强调块、选中片。
PrimaryContainer,
/// 主色容器之上的前景。
OnPrimaryContainer,
/// 次色:低频强调、图表。
Secondary,
/// 次色之上的前景。
OnSecondary,
/// 次色容器。
SecondaryContainer,
/// 次色容器之上的前景。
OnSecondaryContainer,
/// 第三色:与主/次形成对比的装饰强调。
Tertiary,
/// 第三色之上的前景。
OnTertiary,
/// 第三色容器。
TertiaryContainer,
/// 第三色容器之上的前景。
OnTertiaryContainer,
/// 错误色:错误文字、危险操作填充。
Error,
/// 错误色之上的前景。
OnError,
/// 错误容器:错误提示底。
ErrorContainer,
/// 错误容器之上的前景。
OnErrorContainer,
/// 表面:窗口/内容底色(M3 最新口径里取代 background)。
Surface,
/// 表面之上的主体文字。
OnSurface,
/// 表面变体:中性分隔/次级容器(**不是**文字色)。
SurfaceVariant,
/// 表面变体之上的次级文字/图标。
OnSurfaceVariant,
/// 背景(M3 已并入 surface,保留以兼容旧值)。
Background,
/// 背景之上的文本(同上,保留兼容)。
OnBackground,
/// 变暗的表面(模态背后的压暗层)。
SurfaceDim,
/// 变亮的表面(深色下的抬高底)。
SurfaceBright,
/// 最低层容器(比 surface 更低)。
SurfaceContainerLowest,
/// 低层容器:卡片。
SurfaceContainerLow,
/// 标准容器:卡片/面板。
SurfaceContainer,
/// 高层容器:浮层。
SurfaceContainerHigh,
/// 最高层容器:对话框/菜单。
SurfaceContainerHighest,
/// 描边:输入框边框等(非文字,3:1 即可)。
Outline,
/// 弱描边:分隔线(纯装饰)。
OutlineVariant,
/// 反相表面:Snackbar / Tooltip 底。
InverseSurface,
/// 反相表面之上的文字。
InverseOnSurface,
/// 反相表面之上的强调。
InversePrimary,
/// 阴影色(通常带 alpha,见 [`super::Scheme::shadow`])。
Shadow,
/// 遮罩色(模态背景,通常带 alpha)。
Scrim,
/// 表面着色(M3 旧规范的 elevation tint,现已被 surface container 取代)。
SurfaceTint,
/// 固定主色(深浅模式同值,用于需要跨模式稳定的块)。
PrimaryFixed,
/// 固定主色的暗档。
PrimaryFixedDim,
/// 固定主色之上的前景。
OnPrimaryFixed,
/// 固定主色暗档之上的前景。
OnPrimaryFixedVariant,
/// 固定次色。
SecondaryFixed,
/// 固定次色的暗档。
SecondaryFixedDim,
/// 固定次色之上的前景。
OnSecondaryFixed,
/// 固定次色暗档之上的前景。
OnSecondaryFixedVariant,
/// 固定第三色。
TertiaryFixed,
/// 固定第三色的暗档。
TertiaryFixedDim,
/// 固定第三色之上的前景。
OnTertiaryFixed,
/// 固定第三色暗档之上的前景。
OnTertiaryFixedVariant,
}
impl Role {
/// 全部 49 个角色,按 `Role as usize` 顺序排列。
pub const ALL: [Role; 49] = [
Role::Primary,
Role::OnPrimary,
Role::PrimaryContainer,
Role::OnPrimaryContainer,
Role::Secondary,
Role::OnSecondary,
Role::SecondaryContainer,
Role::OnSecondaryContainer,
Role::Tertiary,
Role::OnTertiary,
Role::TertiaryContainer,
Role::OnTertiaryContainer,
Role::Error,
Role::OnError,
Role::ErrorContainer,
Role::OnErrorContainer,
Role::Surface,
Role::OnSurface,
Role::SurfaceVariant,
Role::OnSurfaceVariant,
Role::Background,
Role::OnBackground,
Role::SurfaceDim,
Role::SurfaceBright,
Role::SurfaceContainerLowest,
Role::SurfaceContainerLow,
Role::SurfaceContainer,
Role::SurfaceContainerHigh,
Role::SurfaceContainerHighest,
Role::Outline,
Role::OutlineVariant,
Role::InverseSurface,
Role::InverseOnSurface,
Role::InversePrimary,
Role::Shadow,
Role::Scrim,
Role::SurfaceTint,
Role::PrimaryFixed,
Role::PrimaryFixedDim,
Role::OnPrimaryFixed,
Role::OnPrimaryFixedVariant,
Role::SecondaryFixed,
Role::SecondaryFixedDim,
Role::OnSecondaryFixed,
Role::OnSecondaryFixedVariant,
Role::TertiaryFixed,
Role::TertiaryFixedDim,
Role::OnTertiaryFixed,
Role::OnTertiaryFixedVariant,
];
/// 稳定字符串名(kebab-case),用于日志、配置、快照对拍与文档表格。
pub const fn name(self) -> &'static str {
match self {
Role::Primary => "primary",
Role::OnPrimary => "on-primary",
Role::PrimaryContainer => "primary-container",
Role::OnPrimaryContainer => "on-primary-container",
Role::Secondary => "secondary",
Role::OnSecondary => "on-secondary",
Role::SecondaryContainer => "secondary-container",
Role::OnSecondaryContainer => "on-secondary-container",
Role::Tertiary => "tertiary",
Role::OnTertiary => "on-tertiary",
Role::TertiaryContainer => "tertiary-container",
Role::OnTertiaryContainer => "on-tertiary-container",
Role::Error => "error",
Role::OnError => "on-error",
Role::ErrorContainer => "error-container",
Role::OnErrorContainer => "on-error-container",
Role::Surface => "surface",
Role::OnSurface => "on-surface",
Role::SurfaceVariant => "surface-variant",
Role::OnSurfaceVariant => "on-surface-variant",
Role::Background => "background",
Role::OnBackground => "on-background",
Role::SurfaceDim => "surface-dim",
Role::SurfaceBright => "surface-bright",
Role::SurfaceContainerLowest => "surface-container-lowest",
Role::SurfaceContainerLow => "surface-container-low",
Role::SurfaceContainer => "surface-container",
Role::SurfaceContainerHigh => "surface-container-high",
Role::SurfaceContainerHighest => "surface-container-highest",
Role::Outline => "outline",
Role::OutlineVariant => "outline-variant",
Role::InverseSurface => "inverse-surface",
Role::InverseOnSurface => "inverse-on-surface",
Role::InversePrimary => "inverse-primary",
Role::Shadow => "shadow",
Role::Scrim => "scrim",
Role::SurfaceTint => "surface-tint",
Role::PrimaryFixed => "primary-fixed",
Role::PrimaryFixedDim => "primary-fixed-dim",
Role::OnPrimaryFixed => "on-primary-fixed",
Role::OnPrimaryFixedVariant => "on-primary-fixed-variant",
Role::SecondaryFixed => "secondary-fixed",
Role::SecondaryFixedDim => "secondary-fixed-dim",
Role::OnSecondaryFixed => "on-secondary-fixed",
Role::OnSecondaryFixedVariant => "on-secondary-fixed-variant",
Role::TertiaryFixed => "tertiary-fixed",
Role::TertiaryFixedDim => "tertiary-fixed-dim",
Role::OnTertiaryFixed => "on-tertiary-fixed",
Role::OnTertiaryFixedVariant => "on-tertiary-fixed-variant",
}
}
/// 该角色是否是「文字/图标前景色」(`on-*` 与 `inverse-on-surface` 一类)。
///
/// 用于对比度门禁区分两类要求:前景对容器 ≥ 4.5:1(WCAG AA 正文),
/// 非文字元素 ≥ 3:1。
pub const fn is_foreground(self) -> bool {
matches!(
self,
Role::OnPrimary
| Role::OnPrimaryContainer
| Role::OnSecondary
| Role::OnSecondaryContainer
| Role::OnTertiary
| Role::OnTertiaryContainer
| Role::OnError
| Role::OnErrorContainer
| Role::OnSurface
| Role::OnSurfaceVariant
| Role::OnBackground
| Role::InverseOnSurface
| Role::InversePrimary
| Role::OnPrimaryFixed
| Role::OnPrimaryFixedVariant
| Role::OnSecondaryFixed
| Role::OnSecondaryFixedVariant
| Role::OnTertiaryFixed
| Role::OnTertiaryFixedVariant
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_is_in_enum_order() {
for (i, role) in Role::ALL.iter().enumerate() {
assert_eq!(*role as usize, i, "Role::ALL 顺序必须等于枚举声明顺序");
}
}
#[test]
fn names_are_unique_and_kebab() {
let mut seen = std::collections::BTreeSet::new();
for role in Role::ALL {
let name = role.name();
assert!(seen.insert(name), "角色名重复:{name}");
assert!(
name.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
"角色名必须是 kebab-case:{name}"
);
}
}
}
+313
View File
@@ -0,0 +1,313 @@
//! 一套完整的 M3 语义色方案(`Scheme`):角色 → 调色板槽位 → tone 的三段映射。
//!
//! tone 表取自 M3 基础方案的官方映射(light/dark 各一列)。固定角色
//! (`*-fixed*`)深浅同值,因为它们的用途就是「跨模式稳定」。
use super::palettes::{PaletteSlot, Palettes};
use super::roles::Role;
use super::Color;
/// 深浅模式。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SchemeFlavor {
/// 浅色(亮底暗字)。
Light,
/// 深色(暗底亮字)。
Dark,
}
impl SchemeFlavor {
/// 是否深色模式。
pub const fn is_dark(self) -> bool {
matches!(self, SchemeFlavor::Dark)
}
/// 反过来那一个。
pub const fn toggled(self) -> Self {
match self {
SchemeFlavor::Light => SchemeFlavor::Dark,
SchemeFlavor::Dark => SchemeFlavor::Light,
}
}
/// 稳定字符串名(`light` / `dark`),写配置与日志用。
pub const fn name(self) -> &'static str {
match self {
SchemeFlavor::Light => "light",
SchemeFlavor::Dark => "dark",
}
}
}
/// 阴影色透明度(M3 阴影 = 纯黑 + 这个 alpha;绘制阴影时叠在背景上)。
pub const SHADOW_ALPHA: f32 = 0.20;
/// 遮罩色透明度(模态背景压暗层)。
pub const SCRIM_ALPHA: f32 = 0.32;
/// 一条「角色 → 槽位 + tone」映射。
struct ToneRow {
role: Role,
slot: PaletteSlot,
light: f32,
dark: f32,
}
/// 49 个角色的 tone 映射表,**下标必须等于 `Role as usize`**(由测试钉死)。
const TONE_TABLE: [ToneRow; 49] = [
row(Role::Primary, PaletteSlot::Primary, 40.0, 80.0),
row(Role::OnPrimary, PaletteSlot::Primary, 100.0, 20.0),
row(Role::PrimaryContainer, PaletteSlot::Primary, 90.0, 30.0),
row(Role::OnPrimaryContainer, PaletteSlot::Primary, 10.0, 90.0),
row(Role::Secondary, PaletteSlot::Secondary, 40.0, 80.0),
row(Role::OnSecondary, PaletteSlot::Secondary, 100.0, 20.0),
row(Role::SecondaryContainer, PaletteSlot::Secondary, 90.0, 30.0),
row(
Role::OnSecondaryContainer,
PaletteSlot::Secondary,
10.0,
90.0,
),
row(Role::Tertiary, PaletteSlot::Tertiary, 40.0, 80.0),
row(Role::OnTertiary, PaletteSlot::Tertiary, 100.0, 20.0),
row(Role::TertiaryContainer, PaletteSlot::Tertiary, 90.0, 30.0),
row(Role::OnTertiaryContainer, PaletteSlot::Tertiary, 10.0, 90.0),
row(Role::Error, PaletteSlot::Error, 40.0, 80.0),
row(Role::OnError, PaletteSlot::Error, 100.0, 20.0),
row(Role::ErrorContainer, PaletteSlot::Error, 90.0, 30.0),
row(Role::OnErrorContainer, PaletteSlot::Error, 10.0, 90.0),
row(Role::Surface, PaletteSlot::Neutral, 98.0, 6.0),
row(Role::OnSurface, PaletteSlot::Neutral, 10.0, 90.0),
row(
Role::SurfaceVariant,
PaletteSlot::NeutralVariant,
90.0,
30.0,
),
row(
Role::OnSurfaceVariant,
PaletteSlot::NeutralVariant,
30.0,
80.0,
),
row(Role::Background, PaletteSlot::Neutral, 99.0, 10.0),
row(Role::OnBackground, PaletteSlot::Neutral, 10.0, 90.0),
row(Role::SurfaceDim, PaletteSlot::Neutral, 87.0, 6.0),
row(Role::SurfaceBright, PaletteSlot::Neutral, 98.0, 24.0),
row(
Role::SurfaceContainerLowest,
PaletteSlot::Neutral,
100.0,
4.0,
),
row(Role::SurfaceContainerLow, PaletteSlot::Neutral, 96.0, 10.0),
row(Role::SurfaceContainer, PaletteSlot::Neutral, 94.0, 12.0),
row(Role::SurfaceContainerHigh, PaletteSlot::Neutral, 92.0, 17.0),
row(
Role::SurfaceContainerHighest,
PaletteSlot::Neutral,
90.0,
22.0,
),
row(Role::Outline, PaletteSlot::NeutralVariant, 50.0, 60.0),
row(
Role::OutlineVariant,
PaletteSlot::NeutralVariant,
80.0,
30.0,
),
row(Role::InverseSurface, PaletteSlot::Neutral, 20.0, 90.0),
row(Role::InverseOnSurface, PaletteSlot::Neutral, 95.0, 20.0),
row(Role::InversePrimary, PaletteSlot::Primary, 80.0, 40.0),
row(Role::Shadow, PaletteSlot::Neutral, 0.0, 0.0),
row(Role::Scrim, PaletteSlot::Neutral, 0.0, 0.0),
row(Role::SurfaceTint, PaletteSlot::Primary, 40.0, 80.0),
row(Role::PrimaryFixed, PaletteSlot::Primary, 90.0, 90.0),
row(Role::PrimaryFixedDim, PaletteSlot::Primary, 80.0, 80.0),
row(Role::OnPrimaryFixed, PaletteSlot::Primary, 10.0, 10.0),
row(
Role::OnPrimaryFixedVariant,
PaletteSlot::Primary,
30.0,
30.0,
),
row(Role::SecondaryFixed, PaletteSlot::Secondary, 90.0, 90.0),
row(Role::SecondaryFixedDim, PaletteSlot::Secondary, 80.0, 80.0),
row(Role::OnSecondaryFixed, PaletteSlot::Secondary, 10.0, 10.0),
row(
Role::OnSecondaryFixedVariant,
PaletteSlot::Secondary,
30.0,
30.0,
),
row(Role::TertiaryFixed, PaletteSlot::Tertiary, 90.0, 90.0),
row(Role::TertiaryFixedDim, PaletteSlot::Tertiary, 80.0, 80.0),
row(Role::OnTertiaryFixed, PaletteSlot::Tertiary, 10.0, 10.0),
row(
Role::OnTertiaryFixedVariant,
PaletteSlot::Tertiary,
30.0,
30.0,
),
];
/// `const` 友好的行构造器(数组初始化里不能调用非 const fn 之外的东西)。
const fn row(role: Role, slot: PaletteSlot, light: f32, dark: f32) -> ToneRow {
ToneRow {
role,
slot,
light,
dark,
}
}
/// 一套语义色(49 个角色,全部已解析成具体颜色)。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Scheme {
flavor: SchemeFlavor,
colors: [Color; 49],
}
impl Scheme {
/// 出厂基线方案(种子 `#6750A4`)。
pub fn baseline(flavor: SchemeFlavor) -> Self {
Self::from_palettes(&Palettes::baseline(), flavor)
}
/// 指定种子色的方案(表面色与强调色同源)。
pub fn from_seed(flavor: SchemeFlavor, seed: Color) -> Self {
Self::from_palettes(&Palettes::from_seed(seed), flavor)
}
/// 只覆盖强调色(表面中性色仍走基线,见 [`Palettes::with_accent`])。
pub fn from_accent(flavor: SchemeFlavor, accent: Color) -> Self {
Self::from_palettes(&Palettes::baseline().with_accent(accent), flavor)
}
/// 直接从调色板集合构建(高级入口:整仓测试与自定义 scheme 用)。
pub fn from_palettes(palettes: &Palettes, flavor: SchemeFlavor) -> Self {
let colors = std::array::from_fn(|i| {
let entry = &TONE_TABLE[i];
let tone = match flavor {
SchemeFlavor::Light => entry.light,
SchemeFlavor::Dark => entry.dark,
};
palettes.slot(entry.slot).tone(tone)
});
Self { flavor, colors }
}
/// 该角色在指定模式下的 tone 值(M3 语义;文档表格、调试与测试用)。
pub fn tone_of(role: Role, flavor: SchemeFlavor) -> f32 {
let entry = &TONE_TABLE[role as usize];
debug_assert_eq!(entry.role, role, "TONE_TABLE 下标必须等于角色序号");
match flavor {
SchemeFlavor::Light => entry.light,
SchemeFlavor::Dark => entry.dark,
}
}
/// 取角色色值。
pub fn get(&self, role: Role) -> Color {
self.colors[role as usize]
}
/// 当前模式。
pub fn flavor(&self) -> SchemeFlavor {
self.flavor
}
/// 按角色顺序遍历(`for (role, color) in scheme.iter()`)。
pub fn iter(&self) -> impl Iterator<Item = (Role, Color)> + '_ {
Role::ALL.iter().copied().map(|role| (role, self.get(role)))
}
/// 阴影色(纯黑 + [`SHADOW_ALPHA`])。
pub fn shadow(&self) -> Color {
self.get(Role::Shadow).with_alpha(SHADOW_ALPHA)
}
/// 遮罩色(纯黑 + [`SCRIM_ALPHA`])。
pub fn scrim(&self) -> Color {
self.get(Role::Scrim).with_alpha(SCRIM_ALPHA)
}
/// 两个角色的 WCAG 对比度(1..21)。
pub fn contrast(&self, fg: Role, bg: Role) -> f32 {
self.get(fg).contrast_ratio(self.get(bg))
}
}
impl std::ops::Index<Role> for Scheme {
type Output = Color;
fn index(&self, role: Role) -> &Color {
&self.colors[role as usize]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tone_table_matches_role_order() {
for (i, entry) in TONE_TABLE.iter().enumerate() {
assert_eq!(
entry.role as usize,
i,
"TONE_TABLE 第 {i} 行是 {},顺序与 Role 枚举不一致",
entry.role.name()
);
}
}
#[test]
fn fixed_roles_are_identical_across_flavors() {
let light = Scheme::baseline(SchemeFlavor::Light);
let dark = Scheme::baseline(SchemeFlavor::Dark);
for role in [
Role::PrimaryFixed,
Role::PrimaryFixedDim,
Role::OnPrimaryFixed,
Role::OnPrimaryFixedVariant,
Role::SecondaryFixed,
Role::TertiaryFixedDim,
] {
assert_eq!(
light.get(role),
dark.get(role),
"{} 应跨模式同值",
role.name()
);
}
}
#[test]
fn light_and_dark_differ_on_text_pairs() {
let light = Scheme::baseline(SchemeFlavor::Light);
let dark = Scheme::baseline(SchemeFlavor::Dark);
assert_ne!(light.get(Role::OnSurface), dark.get(Role::OnSurface));
assert!(light.get(Role::Surface).relative_luminance() > 0.8);
assert!(dark.get(Role::Surface).relative_luminance() < 0.05);
}
#[test]
fn shadow_and_scrim_carry_alpha() {
let scheme = Scheme::baseline(SchemeFlavor::Light);
assert_eq!(scheme.shadow().a, (SHADOW_ALPHA * 255.0).round() as u8);
assert_eq!(scheme.scrim().a, (SCRIM_ALPHA * 255.0).round() as u8);
}
#[test]
fn accent_override_changes_primary_only() {
let base = Scheme::baseline(SchemeFlavor::Light);
let teal = Scheme::from_accent(SchemeFlavor::Light, Color::rgb(0x00, 0x6A, 0x5C));
assert_ne!(base.get(Role::Primary), teal.get(Role::Primary));
assert_eq!(base.get(Role::Surface), teal.get(Role::Surface));
assert_eq!(
base.get(Role::Outline),
teal.get(Role::Outline),
"强调色覆盖不该动中性描边"
);
}
}
+190
View File
@@ -0,0 +1,190 @@
//! 色彩空间转换:sRGB ↔ 线性 RGB ↔ CIELAB(tone 轴)+ OKLab/OKLCh(色相/彩度轴)。
//!
//! 这里只放**纯数学**,不认识任何语义色角色。口径说明见 [`super`] 的模块文档。
use super::Color;
/// gamut 判定容差:线性 RGB 允许露出这么点负值/溢出(浮点误差),别因此误判「越界」。
const GAMUT_EPS: f32 = 1.0e-4;
/// sRGB 编码值(0..1)→ 线性光强。
pub(crate) fn srgb_to_linear(c: f32) -> f32 {
if c <= 0.040_45 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
}
/// 线性光强 → sRGB 编码值(0..1),结果不夹取,越界由调用方处理。
pub(crate) fn linear_to_srgb(c: f32) -> f32 {
if c <= 0.003_130_8 {
c * 12.92
} else {
1.055 * c.powf(1.0 / 2.4) - 0.055
}
}
/// 线性 RGB → CIE XYZ(D65 白点,sRGB 原色)。
pub(crate) fn linear_to_xyz(rgb: [f32; 3]) -> [f32; 3] {
let [r, g, b] = rgb;
[
0.412_456_4 * r + 0.357_576_1 * g + 0.180_437_5 * b,
0.212_672_9 * r + 0.715_152_2 * g + 0.072_175_0 * b,
0.019_333_9 * r + 0.119_192 * g + 0.950_304_1 * b,
]
}
/// 相对亮度 Y(WCAG 与 CIELAB 共用这条 Y,白点 1.0)。
pub(crate) fn luminance(rgb: [f32; 3]) -> f32 {
linear_to_xyz(rgb)[1]
}
/// CIELAB `L*`(M3 的 **tone** 就是这个轴,0 = 黑 / 100 = 白)。
pub(crate) fn lstar_from_luminance(y: f32) -> f32 {
let t = y.max(0.0);
if t > 0.008_856 {
116.0 * t.cbrt() - 16.0
} else {
903.296_3 * t
}
}
/// `L*` → 相对亮度 Y([`lstar_from_luminance`] 的逆)。
pub(crate) fn luminance_from_lstar(lstar: f32) -> f32 {
let l = lstar.clamp(0.0, 100.0);
if l > 8.0 {
((l + 16.0) / 116.0).powi(3)
} else {
l / 903.296_3
}
}
/// 线性 RGB → OKLab。
pub(crate) fn linear_to_oklab(rgb: [f32; 3]) -> [f32; 3] {
let [r, g, b] = rgb;
let l = 0.412_221_47 * r + 0.536_332_55 * g + 0.051_445_99 * b;
let m = 0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b;
let s = 0.088_302_46 * r + 0.281_718_84 * g + 0.629_978_7 * b;
let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt());
[
0.210_454_26 * l_ + 0.793_617_8 * m_ - 0.004_072_047 * s_,
1.977_998_5 * l_ - 2.428_592_2 * m_ + 0.450_593_7 * s_,
0.025_904_037 * l_ + 0.782_771_77 * m_ - 0.808_675_77 * s_,
]
}
/// OKLab → 线性 RGB(可能越界,负值表示超出 sRGB gamut)。
pub(crate) fn oklab_to_linear(lab: [f32; 3]) -> [f32; 3] {
let [l, a, b] = lab;
let l_ = l + 0.396_337_78 * a + 0.215_803_76 * b;
let m_ = l - 0.105_561_346 * a - 0.063_854_17 * b;
let s_ = l - 0.089_484_18 * a - 1.291_485_5 * b;
let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
[
4.076_741_7 * l3 - 3.307_711_6 * m3 + 0.230_969_94 * s3,
-1.268_438 * l3 + 2.609_757_4 * m3 - 0.341_319_38 * s3,
-0.004_196_086_3 * l3 - 0.703_418_6 * m3 + 1.707_614_7 * s3,
]
}
/// OKLCh → 线性 RGB。
pub(crate) fn oklch_to_linear(l: f32, chroma: f32, hue_deg: f32) -> [f32; 3] {
let h = hue_deg.to_radians();
oklab_to_linear([l, chroma * h.cos(), chroma * h.sin()])
}
/// 线性 RGB 是否落在 sRGB 立方体内([`GAMUT_EPS`] 容差)。
pub(crate) fn in_gamut(rgb: [f32; 3]) -> bool {
rgb.iter()
.all(|c| *c >= -GAMUT_EPS && *c <= 1.0 + GAMUT_EPS)
}
/// 求「在保证 `L* = lstar` 的前提下,OKLab 明度该取多少」。
///
/// OKLab 的 L 不是 Y 的纯函数(彩色会偏离),所以给定 tone 与色相/彩度时用二分反解,
/// 让最终颜色的 **CIELAB L\* 精确等于 tone**——M3 的 tone 定义在 L\* 上,这一点必须对齐。
pub(crate) fn oklab_lightness_for_tone(chroma: f32, hue_deg: f32, lstar: f32) -> f32 {
let target = luminance_from_lstar(lstar);
let mut lo = 0.0_f32;
let mut hi = 1.0_f32;
for _ in 0..32 {
let mid = 0.5 * (lo + hi);
if luminance(oklch_to_linear(mid, chroma, hue_deg)) < target {
lo = mid;
} else {
hi = mid;
}
}
0.5 * (lo + hi)
}
/// 在该 tone / 色相下,把彩度压进 sRGB gamut 后能取到的最大值(上限 `chroma_max`)。
pub(crate) fn chroma_in_gamut(lstar: f32, hue_deg: f32, chroma_max: f32) -> f32 {
let hi0 = chroma_max.max(0.0);
if in_gamut(oklch_to_linear(
oklab_lightness_for_tone(hi0, hue_deg, lstar),
hi0,
hue_deg,
)) {
return hi0;
}
let mut lo = 0.0_f32;
let mut hi = hi0;
for _ in 0..24 {
let mid = 0.5 * (lo + hi);
let ok = in_gamut(oklch_to_linear(
oklab_lightness_for_tone(mid, hue_deg, lstar),
mid,
hue_deg,
));
if ok {
lo = mid;
} else {
hi = mid;
}
}
lo
}
/// OKLCh 坐标(色相用度,0..360)。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Oklch {
/// 明度 0..1(中性灰时 ≈ 相对亮度的立方根)。
pub lightness: f32,
/// 彩度(0 = 中性灰)。
pub chroma: f32,
/// 色相角,单位度,0..360。
pub hue_deg: f32,
}
impl Oklch {
/// 从一个 sRGB 颜色取色相/彩度(用作调色板的种子)。
pub fn from_color(color: Color) -> Self {
let lin = color.to_linear_f32();
let [l, a, b] = linear_to_oklab(lin);
let mut hue = b.atan2(a).to_degrees();
if hue < 0.0 {
hue += 360.0;
}
Self {
lightness: l,
chroma: (a * a + b * b).sqrt(),
hue_deg: hue,
}
}
/// 在色相环上旋转(用于派生 tertiary 这类同族但不同色的调色板)。
pub fn rotated(mut self, deg: f32) -> Self {
self.hue_deg = (self.hue_deg + deg).rem_euclid(360.0);
self
}
}
impl Color {
/// 线性光强三元组(0..1,越界不夹取)。
fn to_linear_f32(self) -> [f32; 3] {
let f = |c: u8| srgb_to_linear(f32::from(c) / 255.0);
[f(self.r), f(self.g), f(self.b)]
}
}
+96
View File
@@ -0,0 +1,96 @@
//! M3 状态层(state layer)与禁用态透明度。
//!
//! M3 的 hover/pressed 不是「另一种灰」,而是**内容色自身 + 固定 alpha** 叠在容器上——
//! 所以同一套令牌在任何底色上都成立,不必为每种底色各配一套(这条从 Fluent 时代沿用,
//! 见 `DevDocs/SubAgentsTalk/ui-integration-contract.md` §2 的三态叠加层思路)。
use super::Color;
/// 状态层的四种状态与对应 alpha(M3 规范值)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateLayer {
/// 悬停:内容色 8%。
Hover,
/// 键盘焦点:内容色 10%。
Focus,
/// 按下:内容色 10%。
Pressed,
/// 拖拽中:内容色 16%。
Dragged,
}
impl StateLayer {
/// 叠加透明度(0..1)。
pub const fn alpha(self) -> f32 {
match self {
StateLayer::Hover => 0.08,
StateLayer::Focus | StateLayer::Pressed => 0.10,
StateLayer::Dragged => 0.16,
}
}
/// 把状态层叠到容器色上,得到**最终不透明色**。
///
/// `content` 一般是容器上的前景角色(例如 FilledButton 用 `on-primary`,
/// 中性表面上的按钮用 `on-surface`)。
pub fn over(self, content: Color, container: Color) -> Color {
content.with_alpha(self.alpha()).over(container)
}
}
/// 禁用态的透明度(M3):容器 12%、内容 38%。
///
/// 别用「灰化」近似——深色模式下灰化会降低对比度,alpha 叠加两种模式都成立。
pub const DISABLED_CONTAINER_ALPHA: f32 = 0.12;
/// 禁用态内容(文字/图标)透明度。
pub const DISABLED_CONTENT_ALPHA: f32 = 0.38;
/// 禁用态容器色:`on_surface` 12% 叠在 `surface` 上。
pub fn disabled_container(scheme: &super::Scheme) -> Color {
scheme
.get(super::Role::OnSurface)
.with_alpha(DISABLED_CONTAINER_ALPHA)
.over(scheme.get(super::Role::Surface))
}
/// 禁用态内容色:`on_surface` 38% 叠在容器上。
pub fn disabled_content(scheme: &super::Scheme, container: Color) -> Color {
scheme
.get(super::Role::OnSurface)
.with_alpha(DISABLED_CONTENT_ALPHA)
.over(container)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::color::{Role, Scheme, SchemeFlavor};
#[test]
fn hover_is_lighter_than_pressed_on_dark_container() {
let scheme = Scheme::baseline(SchemeFlavor::Dark);
let container = scheme.get(Role::SurfaceContainer);
let content = scheme.get(Role::OnSurface);
let hover = StateLayer::Hover.over(content, container);
let pressed = StateLayer::Pressed.over(content, container);
assert_eq!(hover.a, 255);
assert!(pressed.relative_luminance() > hover.relative_luminance());
}
#[test]
fn state_layer_alpha_matches_m3() {
assert!((StateLayer::Hover.alpha() - 0.08).abs() < f32::EPSILON);
assert!((StateLayer::Dragged.alpha() - 0.16).abs() < f32::EPSILON);
}
#[test]
fn disabled_content_stays_visible() {
let scheme = Scheme::baseline(SchemeFlavor::Light);
let container = disabled_container(&scheme);
let content = disabled_content(&scheme, container);
// 禁用态不追求 AA(规范就是这么定的),但必须仍可辨(> 1.5:1)。
let ratio = content.contrast_ratio(container);
assert!(ratio > 1.5, "禁用态对比度过低:{ratio}");
assert!(ratio < 4.5, "禁用态不该和正文一样醒目:{ratio}");
}
}
+146
View File
@@ -0,0 +1,146 @@
//! tone 调色板:一个种子色 → 一条「固定色相/彩度、tone 任取」的调色板。
//!
//! 这是 M3 tonal palette 的**近似实现**:色相恒定、按 tone 取色、按 tone 压彩度进 sRGB gamut。
//! 口径与已知偏差见 [`super`] 模块文档(OKLCh 而非 CAM16/HCT)。
use super::space::{self, Oklch};
use super::Color;
/// 一条 tone 调色板(色相固定 + 彩度上限)。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TonalPalette {
hue_deg: f32,
chroma: f32,
}
impl TonalPalette {
/// 直接给色相(度)与彩度上限(OKLCh 单位,0 = 中性灰)建调色板。
pub fn new(hue_deg: f32, chroma: f32) -> Self {
Self {
hue_deg: hue_deg.rem_euclid(360.0),
chroma: chroma.max(0.0),
}
}
/// 从种子色取色相与彩度(等价 M3 的 `palette from seed`)。
pub fn from_color(seed: Color) -> Self {
let lch = Oklch::from_color(seed);
Self::new(lch.hue_deg, lch.chroma)
}
/// 固定色相,改彩度上限(用于把种子彩度压到 secondary/neutral 档)。
pub fn with_chroma(self, chroma: f32) -> Self {
Self::new(self.hue_deg, chroma)
}
/// 彩度不超过 `limit`(种子本身更灰时保持更灰,不硬拉饱和)。
pub fn limited_chroma(self, limit: f32) -> Self {
self.with_chroma(self.chroma.min(limit))
}
/// 旋转色相(derived hue)。
pub fn rotated(self, deg: f32) -> Self {
Self::new(self.hue_deg + deg, self.chroma)
}
/// 该调色板的色相(度)。
pub fn hue_deg(self) -> f32 {
self.hue_deg
}
/// 该调色板的彩度上限(OKLCh 单位)。
pub fn chroma(self) -> f32 {
self.chroma
}
/// 取某个 tone 的颜色(tone 0..100,超出夹取)。
///
/// 实现口径:CIELAB `L*` 精确等于 tone(M3 的 tone 定义),彩度按该 tone 的 gamut 上限
/// 二分裁剪——所以 tone 0 恒为纯黑、tone 100 恒为纯白,且同 tone 的 WCAG 对比度
/// 与色相无关(这是对比度门禁能跨种子稳定的原因)。
pub fn tone(self, tone: f32) -> Color {
let lstar = tone.clamp(0.0, 100.0);
// 端点直接给纯黑/纯白:近黑处的 gamut 容差会放进微小彩度,导致 tone 0 偏色。
if lstar <= 0.0 {
return Color::BLACK;
}
if lstar >= 100.0 {
return Color::WHITE;
}
let chroma = space::chroma_in_gamut(lstar, self.hue_deg, self.chroma);
let lightness = space::oklab_lightness_for_tone(chroma, self.hue_deg, lstar);
Color::from_linear_f32(space::oklch_to_linear(lightness, chroma, self.hue_deg))
}
}
#[cfg(test)]
mod tests {
use super::*;
const SEED: Color = Color::rgb(0x67, 0x50, 0xA4);
fn lstar_of(color: Color) -> f32 {
color.lstar()
}
#[test]
fn tone_matches_lstar_within_one_unit() {
let palette = TonalPalette::from_color(SEED);
for tone in [
0.0_f32, 6.0, 10.0, 30.0, 40.0, 50.0, 80.0, 90.0, 95.0, 98.0, 100.0,
] {
let got = lstar_of(palette.tone(tone));
assert!(
(got - tone).abs() <= 1.0,
"tone {tone} 的 L* 是 {got},偏差超过 1(量化误差上限)"
);
}
}
#[test]
fn extremes_are_pure_black_and_white() {
let palette = TonalPalette::from_color(SEED);
assert_eq!(palette.tone(0.0), Color::rgb(0, 0, 0));
assert_eq!(palette.tone(100.0), Color::rgb(255, 255, 255));
assert_eq!(palette.tone(-5.0), Color::rgb(0, 0, 0));
assert_eq!(palette.tone(120.0), Color::rgb(255, 255, 255));
}
#[test]
fn seed_hue_is_preserved_across_tones() {
let palette = TonalPalette::from_color(SEED);
for tone in [30.0_f32, 50.0, 70.0] {
let lch = Oklch::from_color(palette.tone(tone));
let delta = (lch.hue_deg - palette.hue_deg()).abs();
let delta = delta.min(360.0 - delta);
assert!(delta < 3.0, "tone {tone} 色相偏移 {delta}° 过大");
}
}
#[test]
fn neutral_palette_is_gray() {
let neutral = TonalPalette::new(120.0, 0.0);
let c = neutral.tone(50.0);
let spread = f32::from(c.r.max(c.g).max(c.b) - c.r.min(c.g).min(c.b));
assert!(
spread <= 1.0,
"彩度 0 的调色板应当接近中性灰,实测通道差 {spread}"
);
}
#[test]
fn chroma_never_leaves_gamut() {
// 高彩度种子在极端 tone 上必须被裁到 gamut 内(不出现「负 RGB」削顶后的色带)。
let hot = TonalPalette::new(30.0, 0.4);
for tone in [5.0_f32, 20.0, 40.0, 60.0, 80.0, 95.0] {
let lch = Oklch::from_color(hot.tone(tone));
assert!(
lch.chroma <= 0.4 + 1.0e-3,
"tone {tone} 彩度 {} 超出请求上限",
lch.chroma
);
let got = lstar_of(hot.tone(tone));
assert!((got - tone).abs() <= 1.0, "tone {tone} 的 L* 是 {got}");
}
}
}