use crate::inherited::InheritedWidget;
use crate::widget::{Widget, WidgetNode};
use crate::{Color, Point, Size};
use std::any::Any;
use std::rc::Rc;
pub mod tokens;
pub use tokens::{
define_theme, overlay, ColorToken, DurationToken, EasingToken, FocusTokens, FontFamilyToken, FontSizeToken,
FontWeightToken, LengthToken, RadiusTokens, Shadow, ShadowLayer, ShadowToken, SizeTokens, SpacingStep, TextRole,
TextRoleStyle, ThemeDefinition, TokenError, TokenOverrides, Tokens, Value as TokenValue, Variant,
};
#[derive(Debug, Clone, PartialEq)]
pub struct TextTheme {
pub headline: TextStyleTheme,
pub title: TextStyleTheme,
pub body: TextStyleTheme,
pub caption: TextStyleTheme,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TextStyleTheme {
pub font_size: f32,
pub color: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ButtonStyle {
pub background: Color,
pub foreground: Color,
pub radius: f32,
pub focus_ring_color: Color,
pub focus_ring_width: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ButtonVariant {
Primary,
Normal,
Tertiary,
Success,
Warning,
Error,
Info,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ButtonVariantStyle {
pub background: Color,
pub foreground: Color,
pub border: Color,
pub hover_background: Color,
pub pressed_background: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ButtonVariants {
pub primary: ButtonVariantStyle,
pub normal: ButtonVariantStyle,
pub tertiary: ButtonVariantStyle,
pub success: ButtonVariantStyle,
pub warning: ButtonVariantStyle,
pub error: ButtonVariantStyle,
pub info: ButtonVariantStyle,
}
impl ButtonVariants {
pub fn get(&self, variant: ButtonVariant) -> &ButtonVariantStyle {
match variant {
ButtonVariant::Primary => &self.primary,
ButtonVariant::Normal => &self.normal,
ButtonVariant::Tertiary => &self.tertiary,
ButtonVariant::Success => &self.success,
ButtonVariant::Warning => &self.warning,
ButtonVariant::Error => &self.error,
ButtonVariant::Info => &self.info,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct AvatarStyle {
pub palette: [Color; 6],
pub foreground: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ControlStyle {
pub background: Color,
pub border: Color,
pub checked_background: Color,
pub checked_foreground: Color,
pub disabled_background: Color,
pub disabled_border: Color,
pub toggle_off: Color,
pub slider_track: Color,
pub slider_range_active: Color,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ControlGeometry {
pub indicator_size: f32,
pub border_width: f32,
pub label_gap: f32,
pub focus_ring_width: f32,
pub focus_ring_offset: f32,
pub indicator_radius: f32,
pub button_height_sm: f32,
pub button_height_md: f32,
pub button_height_lg: f32,
pub button_padding_h: f32,
pub button_border_width: f32,
pub switch_width: f32,
pub switch_height: f32,
pub switch_thumb: f32,
pub switch_thumb_inset: f32,
pub slider_track_height: f32,
pub slider_thumb_size: f32,
}
impl Default for ControlGeometry {
fn default() -> Self {
Self {
indicator_size: MGUI_INDICATOR_SIZE,
border_width: 1.0,
label_gap: 8.0,
focus_ring_width: 2.0,
focus_ring_offset: 3.0,
switch_width: 40.0,
switch_height: 24.0,
switch_thumb: 20.0,
switch_thumb_inset: 2.0,
slider_track_height: 4.0,
slider_thumb_size: 20.0,
indicator_radius: 4.0,
button_height_sm: 28.0,
button_height_md: 32.0,
button_height_lg: 36.0,
button_padding_h: 12.0,
button_border_width: 1.0,
}
}
}
impl ControlGeometry {
pub fn button_height_at(&self, which: usize) -> f32 {
match which {
0 => self.button_height_sm,
1 => self.button_height_md,
_ => self.button_height_lg,
}
}
}
pub const MGUI_INDICATOR_SIZE: f32 = 18.0;
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 best_on(tokens: &Tokens, background: Color) -> Color {
use crate::theme::tokens::ColorToken;
if luminance(background) < 0.5 {
tokens.color(ColorToken::OnDark)
} else {
tokens.color(ColorToken::OnLight)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ScrollbarStyle {
pub thumb_color: Color,
pub thumb_hover_color: Color,
pub thumb_radius: f32,
pub thumb_width: f32,
pub hit_width: f32,
pub thumb_min_size: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct InputStyle {
pub background: Color,
pub border: Color,
pub focused_border: Color,
pub text_color: Color,
pub placeholder_color: Color,
pub radius: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TooltipStyle {
pub background: Color,
pub foreground: Color,
pub border: Color,
pub radius: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MenuStyle {
pub background: Color,
pub foreground: Color,
pub hover_background: Color,
pub border: Color,
pub radius: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TabStyle {
pub background: Color,
pub active_foreground: Color,
pub inactive_foreground: Color,
pub hover_background: Color,
pub indicator_color: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct NavStyle {
pub active_background: Color,
pub active_foreground: Color,
pub foreground: Color,
pub hover_background: Color,
pub indicator_color: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FeedbackStyle {
pub progress_track: Color,
pub progress_value: Color,
pub success: Color,
pub warning: Color,
pub info: Color,
pub error: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DropdownStyle {
pub background: Color,
pub foreground: Color,
pub placeholder: Color,
pub border: Color,
pub open_border: Color,
pub hover: Color,
pub selected_background: Color,
pub disabled: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DialogStyle {
pub barrier: Color,
pub background: Color,
pub radius: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ListStyle {
pub hover_background: Color,
pub selected_background: Color,
pub foreground: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SpacingScale {
pub xxs: f32,
pub xs: f32,
pub s: f32,
pub m: f32,
pub l: f32,
pub xl: f32,
pub control_padding: f32,
pub container_padding: f32,
pub container_gap: f32,
}
impl Default for SpacingScale {
fn default() -> Self {
Self {
xxs: 2.0,
xs: 4.0,
s: 8.0,
m: 16.0,
l: 24.0,
xl: 32.0,
control_padding: 8.0,
container_padding: 16.0,
container_gap: 8.0,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ThemeData {
pub background: Color,
pub foreground: Color,
pub primary: Color,
pub accent: Color,
pub surface: Color,
pub error: Color,
pub high_contrast: bool,
pub border: Color, pub divider: Color, pub hover: Color, pub disabled: Color, pub selection: Color, pub icon: Color,
pub radius_sm: f32, pub radius_md: f32, pub radius_lg: f32,
pub spacing: f32, pub space: SpacingScale,
pub text: TextTheme,
pub button: ButtonStyle,
pub button_variants: ButtonVariants,
pub avatar: AvatarStyle,
pub control: ControlStyle,
pub geom: ControlGeometry,
pub scrollbar: ScrollbarStyle,
pub input: InputStyle,
pub tooltip: TooltipStyle,
pub menu: MenuStyle,
pub tab: TabStyle,
pub nav: NavStyle,
pub feedback: FeedbackStyle,
pub dropdown: DropdownStyle,
pub dialog: DialogStyle,
pub list: ListStyle,
}
impl Default for ThemeData {
fn default() -> Self {
Self::neutral_dark()
}
}
impl ThemeData {
pub fn dark() -> Self {
Self::neutral_dark()
}
pub fn light() -> Self {
Self::neutral_light()
}
pub fn neutral(dark: bool) -> Self {
Self::from_tokens(&crate::theme::tokens::define_theme().resolve(dark))
}
pub fn neutral_light() -> Self {
Self::neutral(false)
}
pub fn neutral_dark() -> Self {
Self::neutral(true)
}
pub fn from_tokens(tokens: &Tokens) -> Self {
use crate::theme::tokens::{ColorToken as C, SpacingStep as S, TextRole as R};
let color = |token: C| tokens.color(token);
let radius = tokens.radius();
let focus = tokens.focus();
let surface = color(C::BackgroundSurface);
let popover = color(C::BackgroundPopover);
let accent = color(C::Accent);
let filled_variant = |fill: C, on: C| ButtonVariantStyle {
background: color(fill),
foreground: color(on),
border: Color::TRANSPARENT,
hover_background: tokens.hovered(color(fill)),
pressed_background: tokens.pressed(color(fill)),
};
let button_variants = ButtonVariants {
primary: filled_variant(C::Accent, C::OnAccent),
normal: ButtonVariantStyle {
background: surface,
foreground: color(C::TextPrimary),
border: color(C::BorderEmphasized),
hover_background: tokens.hovered(surface),
pressed_background: tokens.pressed(surface),
},
tertiary: ButtonVariantStyle {
background: Color::TRANSPARENT,
foreground: color(C::TextPrimary),
border: Color::TRANSPARENT,
hover_background: color(C::OverlayHover),
pressed_background: color(C::OverlayPressed),
},
success: filled_variant(C::Success, C::OnSuccess),
warning: filled_variant(C::Warning, C::OnWarning),
error: filled_variant(C::Error, C::OnError),
info: filled_variant(C::Info, C::OnInfo),
};
let tooltip_bg = color(C::BackgroundInverted);
let body = tokens.text_role(R::Body);
let heading = tokens.text_role(R::HeadingTwo);
let text = TextTheme {
headline: TextStyleTheme { font_size: tokens.text_role(R::HeadingOne).size, color: color(C::TextPrimary) },
title: TextStyleTheme { font_size: heading.size, color: color(C::TextPrimary) },
body: TextStyleTheme { font_size: body.size, color: color(C::TextPrimary) },
caption: TextStyleTheme { font_size: tokens.text_role(R::Supporting).size, color: color(C::TextSecondary) },
};
let track = color(C::Track);
let scrollbar = ScrollbarStyle {
thumb_color: track,
thumb_hover_color: color(C::BorderEmphasized),
thumb_radius: radius.inner,
thumb_width: tokens.spacing(S::S2),
hit_width: tokens.spacing(S::S2) + 2.0,
thumb_min_size: tokens.spacing(S::S6),
};
let size = tokens.element_size();
Self {
background: color(C::BackgroundBody),
foreground: color(C::TextPrimary),
primary: accent,
accent: color(C::TextAccent),
surface,
error: color(C::TextError),
high_contrast: false,
border: color(C::Border),
divider: color(C::Border),
hover: color(C::OverlayHover),
disabled: color(C::TextDisabled),
selection: color(C::AccentMuted),
icon: color(C::IconPrimary),
radius_sm: radius.inner,
radius_md: radius.element,
radius_lg: radius.container,
spacing: tokens.spacing(S::S2),
space: SpacingScale {
xxs: tokens.spacing(S::S0_5),
xs: tokens.spacing(S::S1),
s: tokens.spacing(S::S2),
m: tokens.spacing(S::S4),
l: tokens.spacing(S::S6),
xl: tokens.spacing(S::S8),
control_padding: tokens.spacing(S::S2),
container_padding: tokens.spacing(S::S4),
container_gap: tokens.spacing(S::S2),
},
text,
button: ButtonStyle {
background: accent,
foreground: color(C::OnAccent),
radius: radius.element,
focus_ring_color: focus.color,
focus_ring_width: focus.width,
},
button_variants,
avatar: AvatarStyle {
palette: [
color(C::DataCategoricalBlue),
color(C::DataCategoricalGreen),
color(C::DataCategoricalOrange),
color(C::DataCategoricalPurple),
color(C::DataCategoricalRed),
color(C::DataCategoricalTeal),
],
foreground: color(C::OnAccent),
},
control: ControlStyle {
background: surface,
border: color(C::BorderEmphasized),
checked_background: accent,
checked_foreground: color(C::OnAccent),
disabled_background: color(C::BackgroundMuted),
disabled_border: color(C::Border),
toggle_off: track,
slider_track: track,
slider_range_active: accent,
},
geom: ControlGeometry {
indicator_size: MGUI_INDICATOR_SIZE,
border_width: tokens.border_width(),
label_gap: tokens.spacing(S::S2),
focus_ring_width: focus.width,
focus_ring_offset: focus.offset,
indicator_radius: radius.inner,
switch_width: 40.0,
switch_height: 24.0,
switch_thumb: 20.0,
switch_thumb_inset: 2.0,
slider_track_height: 4.0,
slider_thumb_size: 20.0,
button_height_sm: size.sm,
button_height_md: size.md,
button_height_lg: size.lg,
button_padding_h: tokens.spacing(S::S3),
button_border_width: tokens.border_width(),
},
scrollbar,
input: InputStyle {
background: surface,
border: color(C::BorderEmphasized),
focused_border: focus.color,
text_color: color(C::TextPrimary),
placeholder_color: color(C::TextSecondary),
radius: radius.element,
},
tooltip: TooltipStyle {
background: tooltip_bg,
foreground: best_on(tokens, tooltip_bg),
border: Color::TRANSPARENT,
radius: radius.element,
},
menu: MenuStyle {
background: popover,
foreground: color(C::TextPrimary),
hover_background: tokens.hovered(popover),
border: color(C::Border),
radius: radius.container,
},
tab: TabStyle {
background: surface,
active_foreground: color(C::TextPrimary),
inactive_foreground: color(C::TextSecondary),
hover_background: tokens.hovered(surface),
indicator_color: accent,
},
nav: NavStyle {
active_background: color(C::AccentMuted),
active_foreground: color(C::TextAccent),
foreground: color(C::TextPrimary),
hover_background: tokens.hovered(surface),
indicator_color: accent,
},
feedback: FeedbackStyle {
progress_track: track,
progress_value: accent,
success: color(C::TextSuccess),
warning: color(C::TextWarning),
info: color(C::TextInfo),
error: color(C::TextError),
},
dropdown: DropdownStyle {
background: popover,
foreground: color(C::TextPrimary),
placeholder: color(C::TextSecondary),
border: color(C::BorderEmphasized),
open_border: focus.color,
hover: tokens.hovered(popover),
selected_background: color(C::AccentMuted),
disabled: color(C::TextDisabled),
},
dialog: DialogStyle {
barrier: color(C::Overlay),
background: color(C::BackgroundCard),
radius: radius.container,
},
list: ListStyle {
hover_background: tokens.hovered(surface),
selected_background: color(C::AccentMuted),
foreground: color(C::TextPrimary),
},
}
}
pub fn high_contrast(dark: bool) -> Self {
use crate::theme::tokens::ColorToken as C;
let (bg, fg, dim, primary, on_primary, focus, info, error, success, warning, hover, selection, barrier) =
if dark {
(
Color::BLACK,
Color::WHITE,
Color::from_rgb8(0xB0, 0xB0, 0xB0),
Color::from_rgb8(0xFF, 0xD7, 0x00),
Color::BLACK,
Color::WHITE,
Color::from_rgb8(0x00, 0xFF, 0xFF),
Color::from_rgb8(0xFF, 0x80, 0x80),
Color::from_rgb8(0x7C, 0xFC, 0x7C),
Color::from_rgb8(0xFF, 0xD7, 0x00),
Color::rgba(1.0, 1.0, 1.0, 0.20),
Color::rgba(1.0, 0.843, 0.0, 0.35),
Color::rgba(0.0, 0.0, 0.0, 0.85),
)
} else {
(
Color::WHITE,
Color::BLACK,
Color::from_rgb8(0x50, 0x50, 0x50),
Color::from_rgb8(0x00, 0x33, 0xCC),
Color::WHITE,
Color::BLACK,
Color::from_rgb8(0x00, 0x5A, 0x5A),
Color::from_rgb8(0xB0, 0x00, 0x20),
Color::from_rgb8(0x00, 0x64, 0x00),
Color::from_rgb8(0x7A, 0x4F, 0x00),
Color::rgba(0.0, 0.0, 0.0, 0.12),
Color::rgba(0.0, 0.2, 0.8, 0.18),
Color::rgba(0.0, 0.0, 0.0, 0.60),
)
};
let mut def = define_theme().named("high-contrast");
for (token, color) in [
(C::BackgroundBody, bg),
(C::BackgroundSurface, bg),
(C::BackgroundCard, bg),
(C::BackgroundPopover, bg),
(C::BackgroundMuted, bg),
(C::BackgroundInverted, fg),
(C::TextPrimary, fg),
(C::TextSecondary, dim),
(C::TextDisabled, dim),
(C::TextAccent, primary),
(C::TextInfo, info),
(C::TextSuccess, success),
(C::TextWarning, warning),
(C::TextError, error),
(C::IconPrimary, fg),
(C::IconSecondary, dim),
(C::IconDisabled, dim),
(C::Accent, primary),
(C::AccentMuted, selection),
(C::OnAccent, on_primary),
(C::Info, info),
(C::OnInfo, on_primary),
(C::Success, success),
(C::OnSuccess, on_primary),
(C::Warning, warning),
(C::OnWarning, on_primary),
(C::Error, error),
(C::OnError, on_primary),
(C::Border, fg),
(C::BorderEmphasized, fg),
(C::BorderInfo, info),
(C::BorderSuccess, success),
(C::BorderWarning, warning),
(C::BorderError, error),
(C::OverlayHover, hover),
(C::OverlayPressed, hover),
(C::Overlay, barrier),
(C::Track, dim),
(C::Skeleton, dim),
(C::Shadow, bg),
(C::FocusOutline, focus),
(C::DataCategoricalBlue, Color::from_rgb8(0x00, 0x50, 0x80)),
(C::DataCategoricalGreen, Color::from_rgb8(0x00, 0x50, 0x00)),
(C::DataCategoricalOrange, Color::from_rgb8(0x6B, 0x2A, 0x00)),
(C::DataCategoricalPurple, Color::from_rgb8(0x3B, 0x00, 0x80)),
(C::DataCategoricalRed, Color::from_rgb8(0x90, 0x00, 0x00)),
(C::DataCategoricalTeal, Color::from_rgb8(0x00, 0x4A, 0x4A)),
] {
def.set_color(token, color, color);
}
for name in [
"--radius-inner",
"--radius-element",
"--radius-container",
"--radius-page",
"--radius-chat",
"--focus-outline-width",
] {
let value = if name == "--focus-outline-width" { "3px" } else { "0px" };
def.set_token(name, value).expect("内置 token 名与形状必然合法");
}
let mut theme = Self::from_tokens(&def.resolve(dark));
theme.high_contrast = true;
theme
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Direction {
#[default]
Ltr,
Rtl,
}
pub const fn resolve_color(explicit: Option<Color>, themed: Color) -> Color {
match explicit {
Some(color) => color,
None => themed,
}
}
pub const fn resolve_f32(explicit: Option<f32>, themed: f32) -> f32 {
match explicit {
Some(value) => value,
None => themed,
}
}
#[derive(Debug)]
pub struct ThemeWidget {
pub theme: Rc<ThemeData>,
pub direction: Direction,
pub child: Option<WidgetNode>,
}
impl ThemeWidget {
pub fn new(theme: ThemeData) -> Self {
Self::from_rc(Rc::new(theme))
}
pub fn from_rc(theme: Rc<ThemeData>) -> Self {
Self { theme, direction: Direction::Ltr, child: None }
}
pub fn dark() -> Self {
Self::new(ThemeData::dark())
}
pub fn light() -> Self {
Self::new(ThemeData::light())
}
pub fn with_direction(mut self, d: Direction) -> Self {
self.direction = d;
self
}
pub fn child(mut self, c: impl Widget) -> Self {
self.child = Some(WidgetNode::new(c));
self
}
pub fn child_node(mut self, c: WidgetNode) -> Self {
self.child = Some(c);
self
}
}
impl InheritedWidget for ThemeWidget {
fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
if let Some(old_theme) = old.as_any().downcast_ref::<ThemeWidget>() {
if Rc::ptr_eq(&self.theme, &old_theme.theme) {
return self.direction != old_theme.direction;
}
*self.theme != *old_theme.theme || self.direction != old_theme.direction
} else {
true
}
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl ThemeWidget {
pub fn theme(&self) -> &ThemeData {
&self.theme
}
pub fn direction(&self) -> Direction {
self.direction
}
}
impl Widget for ThemeWidget {
fn as_any(&self) -> &dyn Any {
self
}
fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
Some(self)
}
fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
match &self.child {
Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
}
}
fn children(&self) -> Vec<WidgetNode> {
self.child.clone().into_iter().collect()
}
fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
}
}
#[derive(Debug)]
pub struct DirectionWidget {
pub direction: Direction,
pub child: Option<WidgetNode>,
}
impl DirectionWidget {
pub fn new(d: Direction) -> Self {
Self { direction: d, child: None }
}
pub fn child(mut self, c: impl Widget) -> Self {
self.child = Some(WidgetNode::new(c));
self
}
}
impl InheritedWidget for DirectionWidget {
fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
if let Some(old_dir) = old.as_any().downcast_ref::<DirectionWidget>() {
self.direction != old_dir.direction
} else {
true
}
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl DirectionWidget {
pub fn direction(&self) -> Direction {
self.direction
}
}
impl Widget for DirectionWidget {
fn as_any(&self) -> &dyn Any {
self
}
fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
Some(self)
}
fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
match &self.child {
Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
}
}
fn children(&self) -> Vec<WidgetNode> {
self.child.clone().into_iter().collect()
}
fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocaleSnapshot {
pub tag: Rc<str>,
pub direction: Direction,
pub generation: u64,
}
impl LocaleSnapshot {
pub fn new(tag: impl Into<Rc<str>>, direction: Direction, generation: u64) -> Self {
Self { tag: tag.into(), direction, generation }
}
pub fn tag(&self) -> &str {
&self.tag
}
}
#[derive(Debug)]
pub struct LocaleWidget {
pub locale: LocaleSnapshot,
pub child: Option<WidgetNode>,
}
impl LocaleWidget {
pub fn new(locale: LocaleSnapshot) -> Self {
Self { locale, child: None }
}
pub fn child_node(mut self, c: WidgetNode) -> Self {
self.child = Some(c);
self
}
pub fn locale(&self) -> &LocaleSnapshot {
&self.locale
}
}
impl InheritedWidget for LocaleWidget {
fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
old.as_any().downcast_ref::<LocaleWidget>().map(|old| self.locale != old.locale).unwrap_or(true)
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl Widget for LocaleWidget {
fn as_any(&self) -> &dyn Any {
self
}
fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
Some(self)
}
fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
match &self.child {
Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
}
}
fn children(&self) -> Vec<WidgetNode> {
self.child.clone().into_iter().collect()
}
fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
}
}
#[cfg(test)]
mod tests {
use super::tokens::{ColorToken as C, FontSizeToken, LengthToken, SpacingStep};
use super::*;
use crate::inherited::InheritedWidget;
#[test]
fn locale_widget_notifies_on_generation_change() {
let a = LocaleWidget::new(LocaleSnapshot::new("en", Direction::Ltr, 1));
let b = LocaleWidget::new(LocaleSnapshot::new("ar", Direction::Rtl, 2));
let same = LocaleWidget::new(LocaleSnapshot::new("ar", Direction::Rtl, 2));
assert!(b.update_should_notify(&a));
assert!(!same.update_should_notify(&b));
}
fn contrast(a: Color, b: Color) -> f32 {
let (la, lb) = (luminance(a), luminance(b));
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
}
fn themed(definition: tokens::ThemeDefinition, dark: bool) -> ThemeData {
ThemeData::from_tokens(&definition.resolve(dark))
}
#[test]
fn neutral_palette_matches_astryx_tokens() {
let light = ThemeData::neutral_light();
assert_eq!(light.primary, Color::from_rgb8(0x00, 0x64, 0xE0));
assert_eq!(light.background, Color::from_rgb8(0xF1, 0xF4, 0xF7));
assert_eq!(light.surface, Color::WHITE);
assert_eq!(light.foreground, Color::from_rgb8(0x0A, 0x13, 0x17));
assert_eq!(light.button.foreground, Color::WHITE);
assert_eq!(light.button.radius, 8.0, "Astryx 按钮用 --radius-element");
assert_eq!(light.input.radius, 8.0);
assert_eq!(light.dialog.radius, 12.0, "Astryx 容器用 --radius-container");
let dark = ThemeData::neutral_dark();
assert_eq!(dark.primary, Color::from_rgb8(0x26, 0x94, 0xFE));
assert_eq!(dark.background, Color::from_rgb8(0x11, 0x11, 0x12));
assert_eq!(dark.surface, Color::from_rgb8(0x1F, 0x1F, 0x22));
assert_eq!(dark.foreground, Color::from_rgb8(0xDF, 0xE2, 0xE5));
assert_eq!(dark.button_variants.error.foreground, Color::from_rgb8(0x0A, 0x13, 0x17));
assert_eq!((light.radius_sm, light.radius_md, light.radius_lg), (4.0, 8.0, 12.0));
assert_eq!(light.text.body.font_size, 14.0, "--text-body-size");
assert_eq!(light.text.headline.font_size, 24.0, "--text-heading-1-size");
assert_eq!(light.text.caption.font_size, 12.0, "--text-supporting-size");
assert_eq!(light.spacing, 8.0, "--spacing-2");
assert_eq!(light.scrollbar.thumb_width, 8.0);
}
#[test]
fn aliases_and_default_are_the_same_theme() {
assert_eq!(ThemeData::dark(), ThemeData::neutral(true));
assert_eq!(ThemeData::light(), ThemeData::neutral(false));
assert_eq!(ThemeData::default(), ThemeData::neutral_dark());
assert_ne!(ThemeData::neutral_light(), ThemeData::neutral_dark());
}
#[test]
fn button_metrics_follow_element_spacing_and_border_tokens() {
let base = themed(define_theme(), false);
assert_eq!(
(base.geom.button_height_sm, base.geom.button_height_md, base.geom.button_height_lg),
(28.0, 32.0, 36.0),
"Astryx --size-element-sm/md/lg 默认档"
);
assert_eq!((base.geom.button_padding_h, base.geom.button_border_width), (12.0, 1.0));
let tuned = themed(
define_theme()
.token("--size-element-md", "2.5rem")
.expect("合法 token")
.token("--spacing-3", "1rem")
.expect("合法 token")
.token("--border-width", "2px")
.expect("合法 token"),
false,
);
assert_eq!(tuned.geom.button_height_md, 40.0, "2.5rem = 40px,只有 md 变");
assert_eq!((tuned.geom.button_height_sm, tuned.geom.button_height_lg), (28.0, 36.0));
assert_eq!((tuned.geom.button_padding_h, tuned.geom.button_border_width), (16.0, 2.0));
let rounded = themed(define_theme().radius_multiplier(1.5), false);
assert_eq!(rounded.geom.button_height_md, 32.0);
assert!(rounded.geom.indicator_radius > base.geom.indicator_radius);
}
#[test]
fn emphasis_and_focus_all_follow_the_accent_token() {
for t in [ThemeData::neutral_light(), ThemeData::neutral_dark()] {
assert_eq!(t.button.focus_ring_color, t.primary);
assert_eq!(t.tab.indicator_color, t.primary);
assert_eq!(t.nav.indicator_color, t.primary);
assert_eq!(t.feedback.progress_value, t.primary);
assert_eq!(t.dropdown.open_border, t.primary);
assert_eq!(t.input.focused_border, t.primary);
assert_eq!(t.text.body.color, t.foreground);
assert_eq!(t.button.focus_ring_width, 2.0, "--focus-outline-width");
}
}
#[test]
fn button_variants_and_avatar_come_from_status_tokens() {
let light = ThemeData::neutral_light();
assert_eq!(light.button_variants.primary.background, light.primary);
assert_eq!(light.button_variants.primary.foreground, Color::WHITE);
assert_eq!(light.button_variants.tertiary.background, Color::TRANSPARENT);
assert_eq!(light.button_variants.normal.background, light.surface);
assert_ne!(light.button_variants.normal.border, Color::TRANSPARENT, "常规按钮有描边");
let dark = ThemeData::neutral_dark();
assert_eq!(dark.button_variants.success.background, Color::from_rgb8(0x0D, 0x86, 0x26));
assert_eq!(dark.button_variants.error.background, Color::from_rgb8(0xF5, 0x39, 0x4F));
assert_ne!(dark.feedback.success, dark.button_variants.success.background);
assert_eq!(dark.avatar.foreground, Color::WHITE, "分类色上写 --color-on-dark");
let mut seen = std::collections::HashSet::new();
for color in dark.avatar.palette {
let key = ((color.r * 255.0) as i32, (color.g * 255.0) as i32, (color.b * 255.0) as i32);
assert!(seen.insert(key), "Avatar 轮换池不该重复");
}
}
#[test]
fn hover_and_pressed_are_composited_overlays() {
for dark in [false, true] {
let t = ThemeData::neutral(dark);
assert!(t.hover.a < 1.0, "--color-overlay-hover 是带 alpha 的叠加层");
let primary = t.button_variants.primary;
assert_ne!(primary.hover_background, primary.background);
assert_ne!(primary.hover_background, primary.pressed_background, "hover 与 pressed 不同档");
assert!(primary.hover_background.a >= 1.0, "叠加后填色仍是不透明色");
assert_ne!(t.list.hover_background, t.surface);
assert_ne!(t.menu.hover_background, t.dropdown.background);
}
}
#[test]
fn overriding_one_token_restyles_the_whole_tree() {
let base = ThemeData::neutral_dark();
let brand = themed(tokens::define_theme().token("--color-accent", "#7B61FF").unwrap(), true);
let purple = Color::from_rgb8(0x7B, 0x61, 0xFF);
assert_eq!(brand.primary, purple);
assert_eq!(brand.button.background, purple);
assert_eq!(brand.button.focus_ring_color, purple);
assert_eq!(brand.input.focused_border, purple);
assert_eq!(brand.tab.indicator_color, purple);
assert_eq!(brand.nav.indicator_color, purple);
assert_eq!(brand.feedback.progress_value, purple);
assert_eq!(brand.button_variants.primary.hover_background, tokens::overlay(purple, base.hover));
assert_ne!(brand, base);
let square = themed(tokens::define_theme().radius_multiplier(0.0), false);
assert_eq!((square.radius_sm, square.radius_md, square.radius_lg), (0.0, 0.0, 0.0));
assert_eq!(square.button.radius, 0.0);
assert_eq!(square.dialog.radius, 0.0);
assert_eq!(square.input.radius, 0.0);
let large = themed(tokens::define_theme().text_scale(18.0, 1.2), false);
let large_tokens = tokens::define_theme().text_scale(18.0, 1.2).resolve(false);
assert_eq!(large.text.body.font_size, large_tokens.font_size(FontSizeToken::Base));
assert_eq!(large.text.body.font_size, 18.0);
assert_eq!(large.text.caption.font_size, large_tokens.font_size(FontSizeToken::Sm));
assert_eq!(large.text.caption.font_size, 15.0, "--text-supporting-size = --font-size-sm");
let roomy = themed(tokens::define_theme().token("--spacing-2", "12px").unwrap(), false);
assert_eq!(roomy.spacing, 12.0);
assert_eq!(roomy.space.s, 12.0);
assert_eq!(roomy.space.control_padding, 12.0);
}
#[test]
fn status_text_meets_aa_contrast_on_both_surfaces() {
for dark in [false, true] {
let t = ThemeData::neutral(dark);
for (label, color, bg) in [
("正文/表面", t.foreground, t.surface),
("次要/表面", t.text.caption.color, t.surface),
("成功/表面", t.feedback.success, t.surface),
("警告/表面", t.feedback.warning, t.surface),
("错误/表面", t.feedback.error, t.surface),
("信息/表面", t.feedback.info, t.surface),
("正文/画布", t.foreground, t.background),
] {
let ratio = contrast(color, bg);
assert!(ratio >= 4.5, "{label} 对比度 {ratio:.2} < 4.5 (dark={dark})");
}
}
}
#[test]
fn filled_button_label_keeps_the_astryx_contrast_floor() {
let light = ThemeData::neutral_light();
assert!(contrast(light.button.foreground, light.button.background) >= 4.5, "浅色档主按钮应达 4.5:1");
let dark = ThemeData::neutral_dark();
let ratio = contrast(dark.button.foreground, dark.button.background);
assert!(ratio >= 3.0, "深色档主按钮文字对比度 {ratio:.2} < 3.0(Astryx 原值即 3.11)");
let hc = ThemeData::high_contrast(true);
assert!(contrast(hc.button.foreground, hc.button.background) >= 4.5, "高对比度档主按钮不足 4.5:1");
}
#[test]
fn overlay_tokens_are_visible_on_their_own_container() {
for dark in [false, true] {
let tokens = tokens::define_theme().resolve(dark);
let surface = tokens.color(C::BackgroundSurface);
assert_ne!(tokens.hovered(surface), surface, "dark={dark}");
assert_ne!(tokens.pressed(surface), tokens.hovered(surface), "dark={dark}");
}
}
#[test]
fn neutral_light_and_dark_have_opposite_luminance() {
let light = ThemeData::neutral_light();
let dark = ThemeData::neutral_dark();
let luma = |c: Color| c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722;
assert!(luma(light.background) > 0.8, "浅色画布应接近白色");
assert!(luma(dark.background) < 0.15, "深色画布应接近黑色");
assert!(luma(light.foreground) < 0.2, "浅色主题正文应为深色");
assert!(luma(dark.foreground) > 0.6, "深色主题正文应为浅色");
}
#[test]
fn high_contrast_palette_meets_wcag_and_uses_square_corners() {
for dark in [false, true] {
let theme = ThemeData::high_contrast(dark);
assert!(theme.high_contrast);
assert_eq!(theme.background, if dark { Color::BLACK } else { Color::WHITE });
assert!(contrast(theme.foreground, theme.background) >= 7.0, "正文对比度不足");
assert!(contrast(theme.primary, theme.background) >= 4.5, "主色对比度不足");
assert!(contrast(theme.border, theme.background) >= 3.0, "边框对比度不足");
assert!(contrast(theme.text.caption.color, theme.background) >= 4.5, "次要文字对比度不足");
assert!(contrast(theme.button.foreground, theme.button.background) >= 4.5, "主按钮文字对比度不足");
assert!(
contrast(theme.button_variants.normal.foreground, theme.button_variants.normal.background) >= 4.5,
"常规按钮文字对比度不足"
);
assert!(contrast(theme.input.text_color, theme.input.background) >= 7.0, "输入框文字对比度不足");
assert!(contrast(theme.tooltip.foreground, theme.tooltip.background) >= 7.0, "Tooltip 文字对比度不足");
assert_eq!(theme.radius_sm, 0.0);
assert_eq!(theme.radius_md, 0.0);
assert_eq!(theme.radius_lg, 0.0);
assert_eq!(theme.button.radius, 0.0);
assert_eq!(theme.input.radius, 0.0);
assert_eq!(theme.dialog.radius, 0.0);
assert_eq!(theme.menu.radius, 0.0);
assert!(theme.button.focus_ring_width >= 3.0);
assert_eq!(theme.divider, theme.foreground, "分割线走前景色");
}
}
#[test]
fn theme_derivation_is_cheap_enough_for_live_editing() {
let definition = crate::theme::tokens::define_theme().radius_multiplier(1.5);
let iterations = 200;
let start = std::time::Instant::now();
for _ in 0..iterations {
let theme = ThemeData::from_tokens(&definition.resolve(true));
std::hint::black_box(&theme);
}
let per = start.elapsed().as_micros() as f64 / iterations as f64;
assert!(per < 2_000.0, "单次 resolve + from_tokens = {per:.0}µs,实时改 token 会掉帧");
}
#[test]
fn spacing_scale_defaults() {
let s = ThemeData::neutral_dark().space;
assert_eq!((s.xxs, s.xs, s.s, s.m, s.l, s.xl), (2.0, 4.0, 8.0, 16.0, 24.0, 32.0));
assert_eq!(s.control_padding, 8.0, "控件默认内边距");
assert_eq!(s.container_padding, 16.0, "容器默认内边距");
assert_eq!(s.container_gap, 8.0, "容器默认子项间距");
let tokens = tokens::define_theme().resolve(true);
assert_eq!(tokens.spacing(SpacingStep::S0_5), 2.0);
assert_eq!(tokens.spacing(SpacingStep::S8), 32.0);
assert_eq!(tokens.length(LengthToken::RadiusContainer), 12.0);
}
}