use crate::Color;
use std::collections::BTreeMap;
use std::fmt;
use std::rc::Rc;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Variant<T> {
pub light: T,
pub dark: T,
}
impl<T> Variant<T> {
pub fn of(light: T, dark: T) -> Self {
Self { light, dark }
}
pub fn get(&self, dark: bool) -> &T {
if dark {
&self.dark
} else {
&self.light
}
}
}
impl<T: Clone> Variant<T> {
pub fn both(value: T) -> Self {
Self { light: value.clone(), dark: value }
}
}
impl<T: Copy> Variant<T> {
pub fn value(&self, dark: bool) -> T {
*self.get(dark)
}
pub fn map<U: Copy>(&self, mut f: impl FnMut(&T) -> U) -> Variant<U> {
Variant { light: f(&self.light), dark: f(&self.dark) }
}
}
macro_rules! named_tokens {
(
$(#[$meta:meta])*
pub enum $name:ident { $( $(#[$attr:meta])* $variant:ident => $css:literal ),* $(,)? }
) => {
$(#[$meta])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum $name { $( $(#[$attr])* $variant, )* }
impl $name {
pub const ALL: &'static [Self] = &[$(Self::$variant),*];
pub fn as_str(self) -> &'static str {
match self { $(Self::$variant => $css),* }
}
pub fn from_name(text: &str) -> Option<Self> {
Self::ALL.iter().copied().find(|token| token.as_str() == text)
}
}
};
}
named_tokens! {
pub enum ColorToken {
Accent => "--color-accent",
AccentMuted => "--color-accent-muted",
OnAccent => "--color-on-accent",
Neutral => "--color-neutral",
BackgroundSurface => "--color-background-surface",
BackgroundBody => "--color-background-body",
BackgroundCard => "--color-background-card",
BackgroundPopover => "--color-background-popover",
BackgroundMuted => "--color-background-muted",
BackgroundInverted => "--color-background-inverted",
BackgroundErrorInverted => "--color-background-error-inverted",
TextPrimary => "--color-text-primary",
TextSecondary => "--color-text-secondary",
TextDisabled => "--color-text-disabled",
TextAccent => "--color-text-accent",
TextBlue => "--color-text-blue",
TextGreen => "--color-text-green",
TextYellow => "--color-text-yellow",
TextRed => "--color-text-red",
TextInfo => "--color-text-info",
TextSuccess => "--color-text-success",
TextWarning => "--color-text-warning",
TextError => "--color-text-error",
IconPrimary => "--color-icon-primary",
IconSecondary => "--color-icon-secondary",
IconDisabled => "--color-icon-disabled",
IconAccent => "--color-icon-accent",
IconInfo => "--color-icon-info",
IconSuccess => "--color-icon-success",
IconWarning => "--color-icon-warning",
IconError => "--color-icon-error",
Border => "--color-border",
BorderEmphasized => "--color-border-emphasized",
BorderInfo => "--color-border-info",
BorderSuccess => "--color-border-success",
BorderWarning => "--color-border-warning",
BorderError => "--color-border-error",
Info => "--color-info",
InfoMuted => "--color-info-muted",
OnInfo => "--color-on-info",
OnInfoMuted => "--color-on-info-muted",
Success => "--color-success",
SuccessMuted => "--color-success-muted",
OnSuccess => "--color-on-success",
OnSuccessMuted => "--color-on-success-muted",
Error => "--color-error",
ErrorMuted => "--color-error-muted",
OnError => "--color-on-error",
OnErrorMuted => "--color-on-error-muted",
Warning => "--color-warning",
WarningMuted => "--color-warning-muted",
OnWarning => "--color-on-warning",
OnWarningMuted => "--color-on-warning-muted",
Overlay => "--color-overlay",
OverlayHover => "--color-overlay-hover",
OverlayPressed => "--color-overlay-pressed",
Shadow => "--color-shadow",
Skeleton => "--color-skeleton",
Track => "--color-track",
TintHover => "--color-tint-hover",
OnDark => "--color-on-dark",
OnLight => "--color-on-light",
FocusOutline => "--focus-outline-color",
DataCategoricalBlue => "--color-data-categorical-blue",
DataCategoricalBrown => "--color-data-categorical-brown",
DataCategoricalCyan => "--color-data-categorical-cyan",
DataCategoricalGreen => "--color-data-categorical-green",
DataCategoricalIndigo => "--color-data-categorical-indigo",
DataCategoricalOrange => "--color-data-categorical-orange",
DataCategoricalPink => "--color-data-categorical-pink",
DataCategoricalPurple => "--color-data-categorical-purple",
DataCategoricalRed => "--color-data-categorical-red",
DataCategoricalTeal => "--color-data-categorical-teal",
}
}
named_tokens! {
pub enum LengthToken {
RadiusNone => "--radius-none",
RadiusInner => "--radius-inner",
RadiusElement => "--radius-element",
RadiusContainer => "--radius-container",
RadiusPage => "--radius-page",
RadiusChat => "--radius-chat",
RadiusFull => "--radius-full",
SizeElementSm => "--size-element-sm",
SizeElementMd => "--size-element-md",
SizeElementLg => "--size-element-lg",
BorderWidth => "--border-width",
FocusOutlineWidth => "--focus-outline-width",
FocusOutlineOffset => "--focus-outline-offset",
}
}
named_tokens! {
pub enum SpacingStep {
S0 => "--spacing-0",
S0_5 => "--spacing-0-5",
S1 => "--spacing-1",
S1_5 => "--spacing-1-5",
S2 => "--spacing-2",
S3 => "--spacing-3",
S4 => "--spacing-4",
S5 => "--spacing-5",
S6 => "--spacing-6",
S7 => "--spacing-7",
S8 => "--spacing-8",
S9 => "--spacing-9",
S10 => "--spacing-10",
S11 => "--spacing-11",
S12 => "--spacing-12",
}
}
named_tokens! {
pub enum DurationToken {
Fast => "--duration-fast",
FastMin => "--duration-fast-min",
FastMax => "--duration-fast-max",
Medium => "--duration-medium",
MediumMin => "--duration-medium-min",
MediumMax => "--duration-medium-max",
Slow => "--duration-slow",
SlowMin => "--duration-slow-min",
SlowMax => "--duration-slow-max",
}
}
named_tokens! {
pub enum FontSizeToken {
FourXs => "--font-size-4xs",
ThreeXs => "--font-size-3xs",
TwoXs => "--font-size-2xs",
Xs => "--font-size-xs",
Sm => "--font-size-sm",
Base => "--font-size-base",
Lg => "--font-size-lg",
Xl => "--font-size-xl",
TwoXl => "--font-size-2xl",
ThreeXl => "--font-size-3xl",
FourXl => "--font-size-4xl",
FiveXl => "--font-size-5xl",
}
}
impl FontSizeToken {
fn step(self) -> i32 {
match self {
Self::FourXs => -5,
Self::ThreeXs => -4,
Self::TwoXs => -3,
Self::Xs => -2,
Self::Sm => -1,
Self::Base => 0,
Self::Lg => 1,
Self::Xl => 2,
Self::TwoXl => 3,
Self::ThreeXl => 4,
Self::FourXl => 5,
Self::FiveXl => 6,
}
}
}
named_tokens! {
pub enum FontWeightToken {
Normal => "--font-weight-normal",
Medium => "--font-weight-medium",
Semibold => "--font-weight-semibold",
Bold => "--font-weight-bold",
}
}
named_tokens! {
pub enum ShadowToken {
Low => "--shadow-low",
Med => "--shadow-med",
High => "--shadow-high",
InsetHover => "--shadow-inset-hover",
InsetSelected => "--shadow-inset-selected",
InsetSuccess => "--shadow-inset-success",
InsetWarning => "--shadow-inset-warning",
InsetError => "--shadow-inset-error",
}
}
named_tokens! {
pub enum EasingToken {
Standard => "--ease-standard",
Entrance => "--ease-entrance",
Move => "--ease-move",
Exit => "--ease-exit",
}
}
named_tokens! {
pub enum TextRole {
DisplayOne => "--text-display-1",
DisplayTwo => "--text-display-2",
DisplayThree => "--text-display-3",
HeadingOne => "--text-heading-1",
HeadingTwo => "--text-heading-2",
HeadingThree => "--text-heading-3",
HeadingFour => "--text-heading-4",
HeadingFive => "--text-heading-5",
HeadingSix => "--text-heading-6",
Large => "--text-large",
Body => "--text-body",
Label => "--text-label",
Supporting => "--text-supporting",
Code => "--text-code",
}
}
impl TextRole {
pub fn stem(self) -> &'static str {
match self {
Self::DisplayOne => "display-1",
Self::DisplayTwo => "display-2",
Self::DisplayThree => "display-3",
Self::HeadingOne => "heading-1",
Self::HeadingTwo => "heading-2",
Self::HeadingThree => "heading-3",
Self::HeadingFour => "heading-4",
Self::HeadingFive => "heading-5",
Self::HeadingSix => "heading-6",
Self::Large => "large",
Self::Body => "body",
Self::Label => "label",
Self::Supporting => "supporting",
Self::Code => "code",
}
}
pub fn size_name(self) -> String {
format!("{}-size", self.as_str())
}
pub fn weight_name(self) -> String {
format!("{}-weight", self.as_str())
}
pub fn leading_name(self) -> String {
format!("{}-leading", self.as_str())
}
}
named_tokens! {
pub enum FontFamilyToken {
Body => "--font-family-body",
Display => "--font-family-display",
Mono => "--font-family-mono",
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Color,
Number,
Shadow,
Easing,
FontStack,
}
fn kind_of(name: &str) -> Option<Kind> {
if ColorToken::from_name(name).is_some() {
return Some(Kind::Color);
}
if LengthToken::from_name(name).is_some()
|| SpacingStep::from_name(name).is_some()
|| DurationToken::from_name(name).is_some()
|| FontSizeToken::from_name(name).is_some()
|| FontWeightToken::from_name(name).is_some()
{
return Some(Kind::Number);
}
if ShadowToken::from_name(name).is_some() {
return Some(Kind::Shadow);
}
if EasingToken::from_name(name).is_some() {
return Some(Kind::Easing);
}
if name.starts_with("--font-family-") {
return Some(Kind::FontStack);
}
if let Some(stem) = name.strip_prefix("--text-") {
if stem.ends_with("-size") || stem.ends_with("-weight") || stem.ends_with("-leading") {
return Some(Kind::Number);
}
}
None
}
#[derive(Clone, Debug, PartialEq)]
enum Atom {
Color(Color),
Num(f32),
LightDark(Rc<Atom>, Rc<Atom>),
Ref {
name: String,
fallback: Option<Rc<Atom>>,
},
Text(Rc<str>),
}
const REM_PX: f32 = 16.0;
fn parse_atom(text: &str) -> Atom {
let text = text.trim();
if text.is_empty() {
return Atom::Text(Rc::from(""));
}
let lower = text.to_ascii_lowercase();
if let Some(inner) = strip_call(&lower, "light-dark") {
if let Some((light, dark)) = split_top(inner, ',') {
return Atom::LightDark(Rc::new(parse_atom(light)), Rc::new(parse_atom(dark)));
}
}
if let Some(inner) = strip_call(&lower, "var") {
let (name, fallback) = match split_top(inner, ',') {
Some((name, fallback)) => (name.trim().to_string(), Some(Rc::new(parse_atom(fallback)))),
None => (inner.trim().to_string(), None),
};
return Atom::Ref { name, fallback };
}
if let Some(color) = parse_color(&lower) {
return Atom::Color(color);
}
if let Some(value) = parse_number(&lower) {
return Atom::Num(value);
}
Atom::Text(Rc::from(text))
}
fn parse_color(lower: &str) -> Option<Color> {
if let Some(digits) = lower.strip_prefix('#') {
return parse_hex(digits);
}
for name in ["rgba", "rgb"] {
if let Some(inner) = strip_call(lower, name) {
return parse_rgba(inner);
}
}
match lower {
"black" => Some(Color::BLACK),
"white" => Some(Color::WHITE),
"transparent" => Some(Color::TRANSPARENT),
_ => None,
}
}
fn parse_hex(digits: &str) -> Option<Color> {
let byte = |s: &str| u8::from_str_radix(s, 16).ok();
match digits.len() {
3 => {
let r = byte(&digits[0..1])?;
let g = byte(&digits[1..2])?;
let b = byte(&digits[2..3])?;
Some(Color::from_rgb8(r * 17, g * 17, b * 17))
}
6 => Some(Color::from_rgb8(byte(&digits[0..2])?, byte(&digits[2..4])?, byte(&digits[4..6])?)),
8 => Some(Color::from_rgba8(
byte(&digits[0..2])?,
byte(&digits[2..4])?,
byte(&digits[4..6])?,
byte(&digits[6..8])?,
)),
_ => None,
}
}
fn parse_rgba(inner: &str) -> Option<Color> {
let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
if parts.len() != 4 {
return None;
}
let r: f32 = parts[0].parse().ok()?;
let g: f32 = parts[1].parse().ok()?;
let b: f32 = parts[2].parse().ok()?;
let a: f32 = parts[3].parse().ok()?;
Some(Color::rgba(r / 255.0, g / 255.0, b / 255.0, a))
}
fn parse_number(lower: &str) -> Option<f32> {
if let Some(px) = lower.strip_suffix("px") {
return px.trim().parse::<f32>().ok();
}
if let Some(rem) = lower.strip_suffix("rem") {
return rem.trim().parse::<f32>().ok().map(|v| v * REM_PX);
}
if let Some(ms) = lower.strip_suffix("ms") {
return ms.trim().parse::<f32>().ok().map(|v| v / 1000.0);
}
if let Some(sec) = lower.strip_suffix('s') {
return sec.trim().parse::<f32>().ok();
}
lower.parse::<f32>().ok()
}
fn strip_call<'a>(lower: &'a str, name: &str) -> Option<&'a str> {
let rest = lower.strip_prefix(name)?.trim_start();
let rest = rest.strip_prefix('(')?;
rest.strip_suffix(')')
}
fn split_top(text: &str, sep: char) -> Option<(&str, &str)> {
let mut depth = 0usize;
for (index, ch) in text.char_indices() {
match ch {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
c if c == sep && depth == 0 => return Some((&text[..index], &text[index + 1..])),
_ => {}
}
}
None
}
fn split_top_all(text: &str, sep: char) -> Vec<&str> {
let mut out = Vec::new();
let mut depth = 0usize;
let mut start = 0usize;
for (index, ch) in text.char_indices() {
match ch {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
c if c == sep && depth == 0 => {
out.push(text[start..index].trim());
start = index + 1;
}
_ => {}
}
}
out.push(text[start..].trim());
out
}
fn split_top_space(text: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut depth = 0usize;
let mut start: Option<usize> = None;
for (index, ch) in text.char_indices() {
if ch == '(' {
depth += 1;
continue;
}
if ch == ')' {
depth = depth.saturating_sub(1);
continue;
}
if depth != 0 {
continue;
}
if ch.is_whitespace() {
if let Some(from) = start.take() {
out.push(&text[from..index]);
}
} else if start.is_none() {
start = Some(index);
}
}
if let Some(from) = start {
out.push(&text[from..]);
}
out
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShadowLayer {
pub inset: bool,
pub offset_x: f32,
pub offset_y: f32,
pub blur: f32,
pub spread: f32,
pub color: Color,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Shadow {
pub layers: Vec<ShadowLayer>,
}
impl Shadow {
pub fn first(&self) -> Option<ShadowLayer> {
self.layers.first().copied()
}
pub fn ring(&self) -> Option<ShadowLayer> {
self.layers.iter().copied().find(|layer| layer.inset && layer.blur == 0.0)
}
pub fn is_empty(&self) -> bool {
self.layers.is_empty()
}
}
fn parse_shadow(text: &str, table: &TokenTable, dark: bool) -> Shadow {
let mut layers = Vec::new();
for part in split_top_all(text, ',') {
if part.is_empty() {
continue;
}
layers.push(parse_shadow_layer(part, table, dark));
}
Shadow { layers }
}
fn parse_shadow_layer(text: &str, table: &TokenTable, dark: bool) -> ShadowLayer {
let mut inset = false;
let mut numbers: Vec<f32> = Vec::new();
let mut color_source = String::new();
for part in split_top_space(text) {
if part.eq_ignore_ascii_case("inset") {
inset = true;
continue;
}
if let Some(value) = parse_number(&part.to_ascii_lowercase()) {
numbers.push(value);
continue;
}
if !color_source.is_empty() {
color_source.push(' ');
}
color_source.push_str(part);
}
let color = if color_source.is_empty() {
Color::TRANSPARENT
} else {
table.color_from_source(&color_source, dark).unwrap_or(Color::TRANSPARENT)
};
ShadowLayer {
inset,
offset_x: numbers.first().copied().unwrap_or(0.0),
offset_y: numbers.get(1).copied().unwrap_or(0.0),
blur: numbers.get(2).copied().unwrap_or(0.0),
spread: numbers.get(3).copied().unwrap_or(0.0),
color,
}
}
pub const BASE_TOKENS: &[(&str, &str)] = &[
("--color-accent", "light-dark(#0064E0, #2694FE)"),
("--color-accent-muted", "light-dark(#0082FB33, #0082FB3F)"),
("--color-on-accent", "light-dark(#FFFFFF, #FFFFFF)"),
("--color-neutral", "light-dark(rgba(5, 54, 89, 0.1), rgba(223, 226, 229, 0.2))"),
("--color-background-surface", "light-dark(#FFFFFF, #1F1F22)"),
("--color-background-body", "light-dark(#F1F4F7, #111112)"),
("--color-background-card", "light-dark(#FFFFFF, #1F1F22)"),
("--color-background-popover", "light-dark(#FFFFFF, #28292C)"),
("--color-background-muted", "light-dark(#0536590C, #1111127F)"),
("--color-background-inverted", "light-dark(#0A1317, #FFFFFF)"),
("--color-background-error-inverted", "light-dark(#AA071E, #E3193B)"),
("--color-text-primary", "light-dark(#0A1317, #DFE2E5)"),
("--color-text-secondary", "light-dark(#4E606F, #AAAFB5)"),
("--color-text-disabled", "light-dark(#A4B0BC, #6F747C)"),
("--color-text-accent", "light-dark(#0064E0, #3E9EFB)"),
("--color-text-blue", "light-dark(#042F97, #AFD7FF)"),
("--color-text-green", "light-dark(#09441F, #A5F690)"),
("--color-text-yellow", "light-dark(#753F07, #FBCE03)"),
("--color-text-red", "light-dark(#7B0210, #FFB2B8)"),
("--color-text-info", "var(--color-text-blue)"),
("--color-text-success", "var(--color-text-green)"),
("--color-text-warning", "var(--color-text-yellow)"),
("--color-text-error", "var(--color-text-red)"),
("--color-icon-primary", "light-dark(#0A1317, #DFE2E5)"),
("--color-icon-secondary", "light-dark(#4E606F, #AAAFB5)"),
("--color-icon-disabled", "light-dark(#A4B0BC, #6F747C)"),
("--color-icon-accent", "light-dark(#0064E0, #2694FE)"),
("--color-icon-info", "var(--color-text-info)"),
("--color-icon-success", "var(--color-text-success)"),
("--color-icon-warning", "var(--color-text-warning)"),
("--color-icon-error", "var(--color-text-error)"),
("--color-border", "light-dark(#05365919, #F2F4F619)"),
("--color-border-emphasized", "light-dark(#CCD3DB, #494D53)"),
("--color-border-info", "var(--color-text-info)"),
("--color-border-success", "var(--color-text-success)"),
("--color-border-warning", "var(--color-text-warning)"),
("--color-border-error", "var(--color-text-error)"),
("--color-info", "light-dark(#0064E0, #0064E0)"),
("--color-info-muted", "light-dark(#0082FB33, #0082FB3F)"),
("--color-on-info", "light-dark(#FFFFFF, #FFFFFF)"),
("--color-on-info-muted", "var(--color-text-blue)"),
("--color-success", "light-dark(#0D8626, #0D8626)"),
("--color-success-muted", "light-dark(#0B991F33, #0B991F3F)"),
("--color-on-success", "light-dark(#FFFFFF, #FFFFFF)"),
("--color-on-success-muted", "var(--color-text-green)"),
("--color-error", "light-dark(#E3193B, #F5394F)"),
("--color-error-muted", "light-dark(#E3193B33, #F5394F3F)"),
("--color-on-error", "light-dark(#FFFFFF, #0A1317)"),
("--color-on-error-muted", "var(--color-text-red)"),
("--color-warning", "light-dark(#E9AF08, #F2C00B)"),
("--color-warning-muted", "light-dark(#E2A40033, #E2A4003F)"),
("--color-on-warning", "light-dark(#0A1317, #0A1317)"),
("--color-on-warning-muted", "var(--color-text-yellow)"),
("--color-overlay", "light-dark(#01122866, #11111299)"),
("--color-overlay-hover", "light-dark(#0536590C, #FFFFFF0C)"),
("--color-overlay-pressed", "light-dark(#05365919, #FFFFFF19)"),
("--color-shadow", "light-dark(rgba(5, 54, 89, 0.1), rgba(0, 0, 0, 0.3))"),
("--color-skeleton", "light-dark(#CCD3DB, #5A5E66)"),
("--color-track", "light-dark(#CCD3DB, #5A5E66)"),
("--color-tint-hover", "light-dark(black, white)"),
("--color-on-dark", "light-dark(#FFFFFF, #FFFFFF)"),
("--color-on-light", "light-dark(#000000, #000000)"),
("--color-data-categorical-blue", "light-dark(#0171E3, #0171E3)"),
("--color-data-categorical-brown", "light-dark(#965E03, #965E03)"),
("--color-data-categorical-cyan", "light-dark(#0171A4, #0171A4)"),
("--color-data-categorical-green", "light-dark(#0B991F, #0B991F)"),
("--color-data-categorical-indigo", "light-dark(#6F8AFF, #6F8AFF)"),
("--color-data-categorical-orange", "light-dark(#EB6E00, #EB6E00)"),
("--color-data-categorical-pink", "light-dark(#F351C0, #F351C0)"),
("--color-data-categorical-purple", "light-dark(#6B1EFD, #6B1EFD)"),
("--color-data-categorical-red", "light-dark(#F5394F, #F5394F)"),
("--color-data-categorical-teal", "light-dark(#08A3A3, #08A3A3)"),
("--radius-none", "0px"),
("--radius-inner", "4px"),
("--radius-element", "8px"),
("--radius-container", "12px"),
("--radius-page", "28px"),
("--radius-chat", "28px"),
("--radius-full", "9999px"),
("--size-element-sm", "28px"),
("--size-element-md", "32px"),
("--size-element-lg", "36px"),
("--border-width", "1px"),
("--focus-outline-width", "2px"),
("--focus-outline-offset", "3px"),
("--focus-outline-color", "var(--color-accent)"),
(
"--shadow-low",
"0px 1px 1px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
0px 2px 8px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2))",
),
(
"--shadow-med",
"0px 1px 2px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
0px 2px 12px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2))",
),
(
"--shadow-high",
"0px 2px 2px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
0px 8px 24px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3))",
),
("--shadow-inset-hover", "inset 0px 0px 0px 2px light-dark(rgba(5, 54, 89, 0.15), rgba(223, 226, 229, 0.2))"),
("--shadow-inset-selected", "inset 0px 0px 0px 2px rgba(1, 113, 227, 0.5)"),
("--shadow-inset-success", "inset 0px 0px 0px 2px rgba(38, 167, 86, 0.3)"),
("--shadow-inset-warning", "inset 0px 0px 0px 2px rgba(226, 164, 0, 0.3)"),
("--shadow-inset-error", "inset 0px 0px 0px 2px rgba(227, 25, 59, 0.3)"),
("--spacing-0", "0rem"),
("--spacing-0-5", "0.125rem"),
("--spacing-1", "0.25rem"),
("--spacing-1-5", "0.375rem"),
("--spacing-2", "0.5rem"),
("--spacing-3", "0.75rem"),
("--spacing-4", "1rem"),
("--spacing-5", "1.25rem"),
("--spacing-6", "1.5rem"),
("--spacing-7", "1.75rem"),
("--spacing-8", "2rem"),
("--spacing-9", "2.25rem"),
("--spacing-10", "2.5rem"),
("--spacing-11", "2.75rem"),
("--spacing-12", "3rem"),
("--duration-fast-min", "130ms"),
("--duration-fast", "175ms"),
("--duration-fast-max", "230ms"),
("--duration-medium-min", "310ms"),
("--duration-medium", "410ms"),
("--duration-medium-max", "550ms"),
("--duration-slow-min", "730ms"),
("--duration-slow", "975ms"),
("--duration-slow-max", "1300ms"),
("--ease-standard", "cubic-bezier(0.24, 1, 0.4, 1)"),
("--ease-entrance", "cubic-bezier(0.24, 1, 0.4, 1)"),
("--ease-move", "cubic-bezier(0.24, 1, 0.4, 1)"),
("--ease-exit", "cubic-bezier(0.3, 0, 0.6, 0.6)"),
("--font-size-4xs", "0.375rem"),
("--font-size-3xs", "0.4375rem"),
("--font-size-2xs", "0.5rem"),
("--font-size-xs", "0.625rem"),
("--font-size-sm", "0.75rem"),
("--font-size-base", "0.875rem"),
("--font-size-lg", "1.0625rem"),
("--font-size-xl", "1.25rem"),
("--font-size-2xl", "1.5rem"),
("--font-size-3xl", "1.8125rem"),
("--font-size-4xl", "2.1875rem"),
("--font-size-5xl", "2.625rem"),
("--font-weight-normal", "400"),
("--font-weight-medium", "500"),
("--font-weight-semibold", "600"),
("--font-weight-bold", "700"),
("--text-display-1-size", "var(--font-size-5xl)"),
("--text-display-1-weight", "var(--font-weight-normal)"),
("--text-display-1-leading", "1.2381"),
("--text-display-2-size", "var(--font-size-4xl)"),
("--text-display-2-weight", "var(--font-weight-normal)"),
("--text-display-2-leading", "1.2571"),
("--text-display-3-size", "var(--font-size-3xl)"),
("--text-display-3-weight", "var(--font-weight-normal)"),
("--text-display-3-leading", "1.2414"),
("--text-heading-1-size", "var(--font-size-2xl)"),
("--text-heading-1-weight", "var(--font-weight-semibold)"),
("--text-heading-1-leading", "1.3333"),
("--text-heading-2-size", "var(--font-size-xl)"),
("--text-heading-2-weight", "var(--font-weight-semibold)"),
("--text-heading-2-leading", "1.4"),
("--text-heading-3-size", "var(--font-size-lg)"),
("--text-heading-3-weight", "var(--font-weight-semibold)"),
("--text-heading-3-leading", "1.4118"),
("--text-heading-4-size", "var(--font-size-base)"),
("--text-heading-4-weight", "var(--font-weight-semibold)"),
("--text-heading-4-leading", "1.4286"),
("--text-heading-5-size", "var(--font-size-sm)"),
("--text-heading-5-weight", "var(--font-weight-semibold)"),
("--text-heading-5-leading", "1.6667"),
("--text-heading-6-size", "var(--font-size-xs)"),
("--text-heading-6-weight", "var(--font-weight-semibold)"),
("--text-heading-6-leading", "1.6"),
("--text-large-size", "var(--font-size-lg)"),
("--text-large-weight", "var(--font-weight-semibold)"),
("--text-large-leading", "1.4118"),
("--text-body-size", "var(--font-size-base)"),
("--text-body-weight", "var(--font-weight-normal)"),
("--text-body-leading", "1.4286"),
("--text-label-size", "var(--font-size-base)"),
("--text-label-weight", "var(--font-weight-medium)"),
("--text-label-leading", "1.4286"),
("--text-supporting-size", "var(--font-size-sm)"),
("--text-supporting-weight", "var(--font-weight-normal)"),
("--text-supporting-leading", "1.6667"),
("--font-family-body", "system-ui, 'Segoe UI', Tahoma, Arial, 'Microsoft YaHei UI', 'Segoe UI Emoji', sans-serif"),
("--font-family-display", "system-ui, 'Segoe UI', Arial, 'Microsoft YaHei UI', sans-serif"),
("--font-family-mono", "Cascadia Code, Consolas, 'SF Mono', Menlo, 'Microsoft YaHei UI', monospace"),
("--text-code-size", "var(--font-size-base)"),
("--text-code-weight", "var(--font-weight-normal)"),
("--text-code-leading", "1.4286"),
];
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Scales {
pub radius_base: f32,
pub radius_multiplier: f32,
pub text_base: f32,
pub text_ratio: f32,
pub motion_fast_ms: f32,
pub motion_medium_ms: f32,
pub motion_slow_ms: f32,
pub motion_ratio: f32,
}
impl Default for Scales {
fn default() -> Self {
Self {
radius_base: 4.0,
radius_multiplier: 1.0,
text_base: 14.0,
text_ratio: 1.2,
motion_fast_ms: 175.0,
motion_medium_ms: 410.0,
motion_slow_ms: 975.0,
motion_ratio: 0.75,
}
}
}
fn px(value: f32) -> String {
let rounded = value.round();
if (value - rounded).abs() < 0.005 {
format!("{rounded:.0}px")
} else {
format!("{value:.2}px")
}
}
fn ms10(value: f32) -> f32 {
(value / 10.0).round() * 10.0
}
impl Scales {
fn generate(&self) -> Vec<(&'static str, String)> {
let mut out = Vec::new();
let unit = self.radius_base * self.radius_multiplier;
for (token, factor) in [
(LengthToken::RadiusInner, 1.0),
(LengthToken::RadiusElement, 2.0),
(LengthToken::RadiusContainer, 3.0),
(LengthToken::RadiusPage, 7.0),
(LengthToken::RadiusChat, 7.0),
] {
out.push((token.as_str(), px(unit * factor)));
}
for token in FontSizeToken::ALL {
let size = self.text_base * self.text_ratio.powi(token.step());
out.push((token.as_str(), px(size.round())));
}
for (center, name, min_name, max_name) in [
(self.motion_fast_ms, "--duration-fast", "--duration-fast-min", "--duration-fast-max"),
(self.motion_medium_ms, "--duration-medium", "--duration-medium-min", "--duration-medium-max"),
(self.motion_slow_ms, "--duration-slow", "--duration-slow-min", "--duration-slow-max"),
] {
out.push((name, format!("{center:.0}ms")));
out.push((min_name, format!("{:.0}ms", ms10(center * self.motion_ratio))));
out.push((max_name, format!("{:.0}ms", ms10(center / self.motion_ratio))));
}
out
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TokenOverrides {
entries: BTreeMap<String, String>,
}
impl TokenOverrides {
pub fn new() -> Self {
Self::default()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn set(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
let name = name.trim();
let kind = kind_of(name).ok_or_else(|| TokenError::UnknownName(name.to_string()))?;
let atom = parse_atom(value.trim());
let shaped = match kind {
Kind::Color => matches!(atom, Atom::Color(_) | Atom::Ref { .. } | Atom::LightDark(..)),
Kind::Number => matches!(atom, Atom::Num(_) | Atom::Ref { .. } | Atom::LightDark(..)),
Kind::Shadow | Kind::Easing | Kind::FontStack => true,
};
if !shaped {
return Err(TokenError::BadValue { name: name.to_string(), value: value.to_string() });
}
self.entries.insert(name.to_string(), value.trim().to_string());
Ok(())
}
pub fn get(&self, name: &str) -> Option<&str> {
self.entries.get(name).map(String::as_str)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.entries.iter().map(|(key, value)| (key.as_str(), value.as_str()))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TokenError {
UnknownName(String),
BadValue { name: String, value: String },
}
impl fmt::Display for TokenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownName(name) => write!(f, "未知的主题 token 名: {name}"),
Self::BadValue { name, value } => write!(f, "token {name} 的值无法解析: {value}"),
}
}
}
impl std::error::Error for TokenError {}
#[derive(Clone, Debug, PartialEq)]
pub struct ThemeDefinition {
ident: String,
scales: Scales,
overrides: TokenOverrides,
}
pub fn define_theme() -> ThemeDefinition {
ThemeDefinition { ident: "neutral".to_string(), scales: Scales::default(), overrides: TokenOverrides::new() }
}
impl ThemeDefinition {
pub fn named(mut self, name: impl Into<String>) -> Self {
self.ident = name.into();
self
}
pub fn name(&self) -> &str {
&self.ident
}
pub fn radius_multiplier(mut self, multiplier: f32) -> Self {
self.scales.radius_multiplier = multiplier.clamp(0.0, 2.0);
self
}
pub fn radius_base(mut self, base: f32) -> Self {
self.scales.radius_base = base.max(0.0);
self
}
pub fn text_scale(mut self, base: f32, ratio: f32) -> Self {
self.scales.text_base = base.max(1.0);
self.scales.text_ratio = ratio.clamp(1.01, 2.0);
self
}
pub fn motion_scale(mut self, fast_ms: f32, medium_ms: f32, slow_ms: f32, ratio: f32) -> Self {
self.scales.motion_fast_ms = fast_ms.max(0.0);
self.scales.motion_medium_ms = medium_ms.max(0.0);
self.scales.motion_slow_ms = slow_ms.max(0.0);
self.scales.motion_ratio = ratio.clamp(0.1, 1.0);
self
}
pub fn scales(&self) -> Scales {
self.scales
}
pub fn token(mut self, name: &str, value: &str) -> Result<Self, TokenError> {
self.overrides.set(name, value)?;
Ok(self)
}
pub fn set_token(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
self.overrides.set(name, value)
}
pub fn set_color(&mut self, token: ColorToken, light: Color, dark: Color) {
let value = format!("light-dark({}, {})", hex_of(light), hex_of(dark));
let _ = self.overrides.set(token.as_str(), &value);
}
pub fn color(mut self, token: ColorToken, light: Color, dark: Color) -> Self {
self.set_color(token, light, dark);
self
}
pub fn tokens(mut self, overrides: TokenOverrides) -> Self {
self.overrides = overrides;
self
}
pub fn overrides(&self) -> &TokenOverrides {
&self.overrides
}
pub fn resolve(&self, dark: bool) -> Tokens {
Tokens::resolve(self, dark)
}
}
fn hex_of(color: Color) -> String {
let channel = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
let (r, g, b) = (channel(color.r), channel(color.g), channel(color.b));
if color.a >= 0.999 {
format!("#{r:02X}{g:02X}{b:02X}")
} else {
format!("#{r:02X}{g:02X}{b:02X}{:02X}", channel(color.a))
}
}
struct TokenTable {
sources: BTreeMap<String, String>,
}
const MAX_REF_DEPTH: u32 = 12;
impl TokenTable {
fn build(definition: &ThemeDefinition) -> Self {
let mut sources: BTreeMap<String, String> =
BASE_TOKENS.iter().map(|(name, value)| ((*name).to_string(), (*value).to_string())).collect();
for (name, value) in definition.scales.generate() {
sources.insert(name.to_string(), value);
}
for (name, value) in definition.overrides.iter() {
sources.insert(name.to_string(), value.to_string());
}
Self { sources }
}
fn source(&self, name: &str) -> Option<&str> {
self.sources.get(name).map(String::as_str)
}
fn expand(&self, text: &str, dark: bool, depth: u32) -> Option<Atom> {
self.expand_atom(&parse_atom(text), dark, depth)
}
fn expand_atom(&self, atom: &Atom, dark: bool, depth: u32) -> Option<Atom> {
if depth > MAX_REF_DEPTH {
return None;
}
match atom {
Atom::LightDark(light, dark_value) => {
let chosen = if dark { dark_value } else { light };
self.expand_atom(chosen, dark, depth + 1)
}
Atom::Ref { name, fallback } => match self.source(name) {
Some(source) => self.expand(source, dark, depth + 1),
None => match fallback {
Some(atom) => self.expand_atom(atom, dark, depth + 1),
None => None,
},
},
other => Some(other.clone()),
}
}
fn color(&self, name: &str, dark: bool) -> Option<Color> {
self.color_from_source(self.source(name)?, dark)
}
fn color_from_source(&self, text: &str, dark: bool) -> Option<Color> {
match self.expand(text, dark, 0)? {
Atom::Color(color) => Some(color),
_ => None,
}
}
fn number(&self, name: &str, dark: bool) -> Option<f32> {
match self.expand(self.source(name)?, dark, 0)? {
Atom::Num(value) => Some(value),
_ => None,
}
}
fn easing(&self, name: &str, dark: bool) -> Option<[f32; 4]> {
let Atom::Text(text) = self.expand(self.source(name)?, dark, 0)? else {
return None;
};
let lower = text.to_ascii_lowercase();
let inner = strip_call(&lower, "cubic-bezier")?;
let parts: Vec<f32> = inner.split(',').filter_map(|part| part.trim().parse::<f32>().ok()).collect();
if parts.len() != 4 {
return None;
}
let mut points = [0.0f32; 4];
points.copy_from_slice(&parts);
Some(points)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
Color(Color),
Number(f32),
Shadow(Shadow),
Easing([f32; 4]),
Text(Rc<str>),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextRoleStyle {
pub size: f32,
pub weight: f32,
pub leading: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Tokens {
ident: Rc<str>,
dark: bool,
scales: Scales,
values: BTreeMap<String, Value>,
}
impl Tokens {
fn resolve(definition: &ThemeDefinition, dark: bool) -> Self {
let table = TokenTable::build(definition);
let mut values: BTreeMap<String, Value> = BTreeMap::new();
for name in table.sources.keys() {
let value = match kind_of(name) {
Some(Kind::Color) => Value::Color(table.color(name, dark).unwrap_or(Color::TRANSPARENT)),
Some(Kind::Number) => Value::Number(table.number(name, dark).unwrap_or(0.0)),
Some(Kind::Shadow) => Value::Shadow(parse_shadow(table.source(name).unwrap_or_default(), &table, dark)),
Some(Kind::Easing) => match table.easing(name, dark) {
Some(points) => Value::Easing(points),
None => Value::Text(Rc::from(table.source(name).unwrap_or_default())),
},
Some(Kind::FontStack) | None => Value::Text(Rc::from(table.source(name).unwrap_or_default())),
};
values.insert(name.clone(), value);
}
Self { ident: Rc::from(definition.name()), dark, scales: definition.scales(), values }
}
pub fn name(&self) -> &str {
&self.ident
}
pub fn is_dark(&self) -> bool {
self.dark
}
pub fn scales(&self) -> Scales {
self.scales
}
pub fn value(&self, name: &str) -> Option<&Value> {
self.values.get(name)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
self.values.iter().map(|(key, value)| (key.as_str(), value))
}
fn number(&self, name: &str, fallback: f32) -> f32 {
match self.value(name) {
Some(Value::Number(value)) => *value,
_ => fallback,
}
}
pub fn font_stack(&self, token: FontFamilyToken) -> &str {
match self.value(token.as_str()) {
Some(Value::Text(text)) => text,
_ => "",
}
}
pub fn color(&self, token: ColorToken) -> Color {
match self.value(token.as_str()) {
Some(Value::Color(color)) => *color,
_ => Color::TRANSPARENT,
}
}
pub fn length(&self, token: LengthToken) -> f32 {
self.number(token.as_str(), 0.0)
}
pub fn spacing(&self, step: SpacingStep) -> f32 {
self.number(step.as_str(), 0.0)
}
pub fn duration(&self, token: DurationToken) -> f32 {
self.number(token.as_str(), 0.0)
}
pub fn font_size(&self, token: FontSizeToken) -> f32 {
self.number(token.as_str(), self.scales.text_base)
}
pub fn font_weight(&self, token: FontWeightToken) -> f32 {
self.number(token.as_str(), 400.0)
}
pub fn shadow(&self, token: ShadowToken) -> Shadow {
match self.value(token.as_str()) {
Some(Value::Shadow(shadow)) => shadow.clone(),
_ => Shadow::default(),
}
}
pub fn easing(&self, token: EasingToken) -> [f32; 4] {
match self.value(token.as_str()) {
Some(Value::Easing(points)) => *points,
_ => [0.24, 1.0, 0.4, 1.0],
}
}
pub fn text_role(&self, role: TextRole) -> TextRoleStyle {
TextRoleStyle {
size: self.number(&role.size_name(), self.font_size(FontSizeToken::Base)),
weight: self.number(&role.weight_name(), 400.0),
leading: self.number(&role.leading_name(), 1.4),
}
}
pub fn border_width(&self) -> f32 {
self.length(LengthToken::BorderWidth)
}
pub fn focus(&self) -> FocusTokens {
FocusTokens {
width: self.length(LengthToken::FocusOutlineWidth),
offset: self.length(LengthToken::FocusOutlineOffset),
color: self.color(ColorToken::FocusOutline),
}
}
pub fn radius(&self) -> RadiusTokens {
RadiusTokens {
none: self.length(LengthToken::RadiusNone),
inner: self.length(LengthToken::RadiusInner),
element: self.length(LengthToken::RadiusElement),
container: self.length(LengthToken::RadiusContainer),
page: self.length(LengthToken::RadiusPage),
chat: self.length(LengthToken::RadiusChat),
full: self.length(LengthToken::RadiusFull),
}
}
pub fn element_size(&self) -> SizeTokens {
SizeTokens {
sm: self.length(LengthToken::SizeElementSm),
md: self.length(LengthToken::SizeElementMd),
lg: self.length(LengthToken::SizeElementLg),
}
}
pub fn hovered(&self, base: Color) -> Color {
overlay(base, self.color(ColorToken::OverlayHover))
}
pub fn pressed(&self, base: Color) -> Color {
overlay(base, self.color(ColorToken::OverlayPressed))
}
pub fn color_rows(&self) -> Vec<(&'static str, Color)> {
ColorToken::ALL.iter().map(|token| (token.as_str(), self.color(*token))).collect()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FocusTokens {
pub width: f32,
pub offset: f32,
pub color: Color,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RadiusTokens {
pub none: f32,
pub inner: f32,
pub element: f32,
pub container: f32,
pub page: f32,
pub chat: f32,
pub full: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SizeTokens {
pub sm: f32,
pub md: f32,
pub lg: f32,
}
pub fn overlay(base: Color, top: Color) -> Color {
if top.a >= 1.0 {
return top;
}
let keep = 1.0 - top.a;
Color {
r: top.r * top.a + base.r * keep,
g: top.g * top.a + base.g * keep,
b: top.b * top.a + base.b * keep,
a: base.a + top.a * (1.0 - base.a),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn luminance(color: Color) -> f32 {
let channel = |v: f32| {
if v <= 0.04045 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
};
0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
}
fn contrast(a: Color, b: Color) -> f32 {
let (la, lb) = (luminance(a), luminance(b));
let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
(hi + 0.05) / (lo + 0.05)
}
#[test]
fn parses_color_shapes() {
let table = TokenTable::build(&define_theme());
let cases = [
("#0064E0", Color::from_rgb8(0x00, 0x64, 0xE0)),
("#abc", Color::from_rgb8(0xAA, 0xBB, 0xCC)),
("#0536590C", Color::from_rgba8(0x05, 0x36, 0x59, 0x0C)),
("rgba(5, 54, 89, 0.1)", Color::rgba(5.0 / 255.0, 54.0 / 255.0, 89.0 / 255.0, 0.1)),
("black", Color::BLACK),
("white", Color::WHITE),
("light-dark(#111111, #EEEEEE)", Color::from_rgb8(0x11, 0x11, 0x11)),
];
for (text, expect) in cases {
let light = table.color_from_source(text, false).unwrap_or_else(|| panic!("解析失败: {text}"));
assert_eq!(light, expect, "明档 {text}");
}
let dark = table.color_from_source("light-dark(#111111, #EEEEEE)", true).unwrap();
assert_eq!(dark, Color::from_rgb8(0xEE, 0xEE, 0xEE), "暗档取第二边");
}
#[test]
fn font_family_tokens_resolve_css_stacks() {
let tokens = define_theme().resolve(true);
for role in FontFamilyToken::ALL {
let stack = tokens.font_stack(*role);
assert!(!stack.is_empty(), "{} 应有 CSS 字体栈", role.as_str());
assert!(stack.contains("sans-serif") || stack.contains("monospace"), "{stack}");
}
let custom =
define_theme().token("--font-family-body", "'My Font', sans-serif").expect("token override").resolve(false);
assert_eq!(custom.font_stack(FontFamilyToken::Body), "'My Font', sans-serif");
}
#[test]
fn leading_values_are_positive_numbers() {
let tokens = define_theme().resolve(false);
for role in TextRole::ALL {
let style = tokens.text_role(*role);
assert!(style.leading > 0.0 && style.leading.is_finite(), "{role:?} leading={}", style.leading);
}
}
#[test]
fn parses_units() {
assert_eq!(parse_atom("8px"), Atom::Num(8.0));
assert_eq!(parse_atom("1.0625rem"), Atom::Num(17.0));
assert_eq!(parse_atom("175ms"), Atom::Num(0.175));
assert_eq!(parse_atom("1.4286"), Atom::Num(1.4286));
assert_eq!(parse_atom("400"), Atom::Num(400.0));
assert_eq!(parse_atom("#0064E0"), Atom::Color(Color::from_rgb8(0x00, 0x64, 0xE0)));
}
#[test]
fn neutral_defaults_match_astryx() {
let light = define_theme().resolve(false);
let dark = define_theme().resolve(true);
assert_eq!(light.color(ColorToken::Accent), Color::from_rgb8(0x00, 0x64, 0xE0));
assert_eq!(dark.color(ColorToken::Accent), Color::from_rgb8(0x26, 0x94, 0xFE));
assert_eq!(light.color(ColorToken::TextPrimary), Color::from_rgb8(0x0A, 0x13, 0x17));
assert_eq!(dark.color(ColorToken::BackgroundBody), Color::from_rgb8(0x11, 0x11, 0x12));
assert_eq!(light.length(LengthToken::RadiusElement), 8.0);
assert_eq!(light.length(LengthToken::SizeElementMd), 32.0);
assert_eq!(light.length(LengthToken::RadiusFull), 9999.0);
assert_eq!(light.font_size(FontSizeToken::Base), 14.0);
assert_eq!(light.font_size(FontSizeToken::FiveXl), 42.0);
assert_eq!(light.font_size(FontSizeToken::FourXs), 6.0);
assert_eq!(light.spacing(SpacingStep::S4), 16.0);
assert_eq!(light.spacing(SpacingStep::S1_5), 6.0);
assert!((light.duration(DurationToken::Fast) - 0.175).abs() < 1e-6);
assert_eq!(light.font_weight(FontWeightToken::Semibold), 600.0);
assert_eq!(light.text_role(TextRole::HeadingOne).size, 24.0);
assert_eq!(light.text_role(TextRole::HeadingOne).weight, 600.0);
assert_eq!(light.text_role(TextRole::Body).size, 14.0);
assert_eq!(light.text_role(TextRole::Supporting).size, 12.0);
assert_eq!(light.easing(EasingToken::Standard), [0.24, 1.0, 0.4, 1.0]);
assert_eq!(light.easing(EasingToken::Exit), [0.3, 0.0, 0.6, 0.6]);
assert_eq!(light.name(), "neutral");
}
#[test]
fn scale_generation_reproduces_neutral_base() {
let base: BTreeMap<&str, &str> = BASE_TOKENS.iter().copied().collect();
let generated = Scales::default().generate();
assert!(!generated.is_empty());
for (name, value) in &generated {
let literal = base.get(*name).unwrap_or_else(|| panic!("基表缺少 {name}"));
assert_eq!(&parse_atom(value), &parse_atom(literal), "scale 默认值改变了 {name}");
}
let overridden =
define_theme().radius_multiplier(2.0).token("--radius-element", "10px").unwrap().resolve(false);
assert_eq!(overridden.length(LengthToken::RadiusElement), 10.0);
assert_eq!(overridden.length(LengthToken::RadiusContainer), 24.0);
}
#[test]
fn radius_multiplier_scales_named_radii_but_not_none_or_full() {
let tokens = define_theme().radius_multiplier(1.5).resolve(false);
assert_eq!(tokens.length(LengthToken::RadiusInner), 6.0);
assert_eq!(tokens.length(LengthToken::RadiusElement), 12.0);
assert_eq!(tokens.length(LengthToken::RadiusContainer), 18.0);
assert_eq!(tokens.length(LengthToken::RadiusPage), 42.0);
assert_eq!(tokens.length(LengthToken::RadiusNone), 0.0, "0 不该被放大");
assert_eq!(tokens.length(LengthToken::RadiusFull), 9999.0, "完全圆不该被放大");
assert_eq!(tokens.radius().element, 12.0);
}
#[test]
fn text_and_motion_scales_move_the_whole_ladder() {
let tokens = define_theme().text_scale(16.0, 1.25).resolve(false);
assert_eq!(tokens.font_size(FontSizeToken::Base), 16.0);
assert_eq!(tokens.font_size(FontSizeToken::Lg), 20.0);
assert_eq!(tokens.text_role(TextRole::Body).size, 16.0);
assert_eq!(tokens.text_role(TextRole::HeadingOne).size, 31.0);
let slow = define_theme().motion_scale(200.0, 500.0, 1000.0, 0.8).resolve(false);
assert!((slow.duration(DurationToken::Fast) - 0.2).abs() < 1e-6);
assert!((slow.duration(DurationToken::FastMin) - 0.16).abs() < 1e-6);
assert!((slow.duration(DurationToken::FastMax) - 0.25).abs() < 1e-6);
assert!((slow.duration(DurationToken::Slow) - 1.0).abs() < 1e-6);
}
#[test]
fn overriding_accent_also_moves_the_focus_ring() {
let tokens = define_theme().token("--color-accent", "#7B61FF").unwrap().resolve(false);
assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x7B, 0x61, 0xFF));
assert_eq!(tokens.focus().color, Color::from_rgb8(0x7B, 0x61, 0xFF));
}
#[test]
fn status_colors_follow_the_hue_chain() {
let tokens = define_theme().resolve(true);
assert_eq!(tokens.color(ColorToken::TextError), tokens.color(ColorToken::TextRed));
assert_eq!(tokens.color(ColorToken::IconError), tokens.color(ColorToken::TextError));
assert_eq!(tokens.color(ColorToken::BorderError), tokens.color(ColorToken::TextError));
let tokens = define_theme().token("--color-text-red", "#FF0000").unwrap().resolve(false);
assert_eq!(tokens.color(ColorToken::TextError), Color::from_rgb8(0xFF, 0x00, 0x00));
assert_eq!(tokens.color(ColorToken::BorderError), Color::from_rgb8(0xFF, 0x00, 0x00));
}
#[test]
fn override_beats_base_for_both_modes() {
let def = define_theme().token("--color-background-surface", "light-dark(#111111, #EEEEEE)").unwrap();
assert_eq!(def.resolve(false).color(ColorToken::BackgroundSurface), Color::from_rgb8(0x11, 0x11, 0x11));
assert_eq!(def.resolve(true).color(ColorToken::BackgroundSurface), Color::from_rgb8(0xEE, 0xEE, 0xEE));
}
#[test]
fn color_helper_writes_two_variants() {
let tokens = define_theme()
.color(ColorToken::Accent, Color::from_rgb8(0x10, 0x20, 0x30), Color::from_rgb8(0xF0, 0xE0, 0xD0))
.resolve(false);
assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x10, 0x20, 0x30));
assert_eq!(tokens.color(ColorToken::FocusOutline), Color::from_rgb8(0x10, 0x20, 0x30));
assert_eq!(hex_of(Color::from_rgb8(0x10, 0x20, 0x30)), "#102030");
}
#[test]
fn bad_token_names_and_values_are_rejected() {
assert!(matches!(define_theme().token("--color-nope", "#fff"), Err(TokenError::UnknownName(_))));
assert!(matches!(define_theme().token("--radius-element", "not-a-length"), Err(TokenError::BadValue { .. })));
assert!(matches!(define_theme().token("--color-accent", "8px"), Err(TokenError::BadValue { .. })));
assert!(matches!(define_theme().token("--font-size-base", "#FFFFFF"), Err(TokenError::BadValue { .. })));
}
macro_rules! assert_tokens_present {
($tokens:expr, $($enum:ident),* $(,)?) => {
$(
for token in $enum::ALL {
assert!(
$tokens.value(token.as_str()).is_some(),
"基表缺少 token {}",
token.as_str()
);
}
)*
};
}
#[test]
fn every_typed_token_has_a_base_value() {
let tokens = define_theme().resolve(false);
assert_tokens_present!(
tokens,
ColorToken,
LengthToken,
SpacingStep,
DurationToken,
FontSizeToken,
FontWeightToken,
ShadowToken,
EasingToken,
);
for role in TextRole::ALL {
for name in [role.size_name(), role.weight_name(), role.leading_name()] {
assert!(tokens.value(&name).is_some(), "基表缺少 {name}");
}
}
}
#[test]
fn every_base_token_name_is_known_to_the_override_layer() {
let mut unknown = Vec::new();
for (name, _) in BASE_TOKENS {
if kind_of(name).is_none() {
unknown.push(*name);
}
}
assert!(unknown.is_empty(), "覆盖层不认识的基表名: {unknown:?}");
}
#[test]
fn shadows_are_multi_layer_with_mode_specific_colors() {
let light = define_theme().resolve(false);
let dark = define_theme().resolve(true);
let low = light.shadow(ShadowToken::Low);
assert_eq!(low.layers.len(), 2);
let first = low.first().unwrap();
assert_eq!((first.offset_x, first.offset_y, first.blur, first.spread), (0.0, 1.0, 1.0, 0.0));
assert!(!first.inset);
assert_eq!(first.color, Color::rgba(0.0, 0.0, 0.0, 0.1));
assert_eq!(dark.shadow(ShadowToken::Low).first().unwrap().color, Color::rgba(0.0, 0.0, 0.0, 0.2));
let ring = light.shadow(ShadowToken::InsetHover).ring().expect("inset 描边环");
assert!(ring.inset && ring.blur == 0.0 && ring.spread == 2.0);
assert!(light.shadow(ShadowToken::Low).ring().is_none());
}
#[test]
fn shadow_can_reference_color_shadow_token() {
let mut overrides = TokenOverrides::new();
overrides.set("--shadow-low", "0px 2px 4px var(--color-shadow)").unwrap();
let tokens = define_theme().tokens(overrides).resolve(true);
let layer = tokens.shadow(ShadowToken::Low).first().unwrap();
assert_eq!(layer.color, tokens.color(ColorToken::Shadow));
assert_eq!(layer.blur, 4.0);
}
#[test]
fn overlay_helpers_composite_alpha_tokens() {
for dark in [false, true] {
let tokens = define_theme().resolve(dark);
let base = tokens.color(ColorToken::BackgroundSurface);
let hover = tokens.hovered(base);
let pressed = tokens.pressed(base);
assert!(hover.a > 0.99, "叠加后仍是不透明底色");
assert_ne!(hover, base, "hover 必须看得见");
assert_ne!(hover, pressed, "hover 与 pressed 不同档");
let strength = |a: Color, b: Color| (a.r - b.r).abs() + (a.g - b.g).abs() + (a.b - b.b).abs();
assert!(strength(base, pressed) > strength(base, hover), "dark={dark}");
}
}
#[test]
fn neutral_text_on_surface_meets_aa_contrast() {
for dark in [false, true] {
let tokens = define_theme().resolve(dark);
let on_surface =
contrast(tokens.color(ColorToken::TextPrimary), tokens.color(ColorToken::BackgroundSurface));
assert!(on_surface >= 4.5, "正文/表面 对比度 {on_surface:.2} < 4.5 (dark={dark})");
let on_body = contrast(tokens.color(ColorToken::TextPrimary), tokens.color(ColorToken::BackgroundBody));
assert!(on_body >= 4.5, "正文/画布 对比度 {on_body:.2} < 4.5 (dark={dark})");
let secondary =
contrast(tokens.color(ColorToken::TextSecondary), tokens.color(ColorToken::BackgroundSurface));
assert!(secondary >= 4.5, "次要文本/表面 对比度 {secondary:.2} < 4.5 (dark={dark})");
}
}
#[test]
fn ref_cycles_and_unknown_refs_fall_back_without_panicking() {
let mut overrides = TokenOverrides::new();
overrides.set("--color-accent", "var(--color-accent)").unwrap();
overrides.set("--color-text-red", "var(--nope)").unwrap();
let tokens = define_theme().tokens(overrides).resolve(false);
assert_eq!(tokens.color(ColorToken::Accent), Color::TRANSPARENT);
assert_eq!(tokens.color(ColorToken::TextError), Color::TRANSPARENT);
let mut overrides = TokenOverrides::new();
overrides.set("--color-accent", "var(--nope, #123456)").unwrap();
let tokens = define_theme().tokens(overrides).resolve(false);
assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x12, 0x34, 0x56));
}
}