1use crate::inherited::InheritedWidget;
15use crate::widget::{Widget, WidgetNode};
16use crate::{Color, Point, Size};
17use std::any::Any;
18use std::rc::Rc;
19
20pub mod tokens;
21
22pub use tokens::{
23 define_theme, overlay, ColorToken, DurationToken, EasingToken, FocusTokens, FontFamilyToken, FontSizeToken,
24 FontWeightToken, LengthToken, RadiusTokens, Shadow, ShadowLayer, ShadowToken, SizeTokens, SpacingStep, TextRole,
25 TextRoleStyle, ThemeDefinition, TokenError, TokenOverrides, Tokens, Value as TokenValue, Variant,
26};
27
28#[derive(Debug, Clone, PartialEq)]
35pub struct TextTheme {
36 pub headline: TextStyleTheme,
37 pub title: TextStyleTheme,
38 pub body: TextStyleTheme,
39 pub caption: TextStyleTheme,
40}
41
42#[derive(Debug, Clone, PartialEq)]
43pub struct TextStyleTheme {
44 pub font_size: f32,
45 pub color: Color,
46}
47
48#[derive(Debug, Clone, PartialEq)]
50pub struct ButtonStyle {
51 pub background: Color,
52 pub foreground: Color,
53 pub radius: f32,
54 pub focus_ring_color: Color,
56 pub focus_ring_width: f32,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum ButtonVariant {
63 Primary,
65 Normal,
67 Tertiary,
69 Success,
71 Warning,
73 Error,
75 Info,
77}
78
79#[derive(Debug, Clone, PartialEq)]
81pub struct ButtonVariantStyle {
82 pub background: Color,
83 pub foreground: Color,
84 pub border: Color,
86 pub hover_background: Color,
87 pub pressed_background: Color,
88}
89
90#[derive(Debug, Clone, PartialEq)]
92pub struct ButtonVariants {
93 pub primary: ButtonVariantStyle,
94 pub normal: ButtonVariantStyle,
95 pub tertiary: ButtonVariantStyle,
96 pub success: ButtonVariantStyle,
97 pub warning: ButtonVariantStyle,
98 pub error: ButtonVariantStyle,
99 pub info: ButtonVariantStyle,
100}
101
102impl ButtonVariants {
103 pub fn get(&self, variant: ButtonVariant) -> &ButtonVariantStyle {
105 match variant {
106 ButtonVariant::Primary => &self.primary,
107 ButtonVariant::Normal => &self.normal,
108 ButtonVariant::Tertiary => &self.tertiary,
109 ButtonVariant::Success => &self.success,
110 ButtonVariant::Warning => &self.warning,
111 ButtonVariant::Error => &self.error,
112 ButtonVariant::Info => &self.info,
113 }
114 }
115}
116
117#[derive(Debug, Clone, PartialEq)]
119pub struct AvatarStyle {
120 pub palette: [Color; 6],
122 pub foreground: Color,
123}
124
125#[derive(Debug, Clone, PartialEq)]
127pub struct ControlStyle {
128 pub background: Color,
130 pub border: Color,
132 pub checked_background: Color,
134 pub checked_foreground: Color,
136 pub disabled_background: Color,
138 pub disabled_border: Color,
140 pub toggle_off: Color,
142 pub slider_track: Color,
144 pub slider_range_active: Color,
146}
147
148#[derive(Debug, Clone, Copy, PartialEq)]
157pub struct ControlGeometry {
158 pub indicator_size: f32,
160 pub border_width: f32,
162 pub label_gap: f32,
164 pub focus_ring_width: f32,
166 pub focus_ring_offset: f32,
168 pub indicator_radius: f32,
170 pub button_height_sm: f32,
172 pub button_height_md: f32,
173 pub button_height_lg: f32,
174 pub button_padding_h: f32,
176 pub button_border_width: f32,
178 pub switch_width: f32,
180 pub switch_height: f32,
181 pub switch_thumb: f32,
182 pub switch_thumb_inset: f32,
183 pub slider_track_height: f32,
185 pub slider_thumb_size: f32,
186}
187
188impl Default for ControlGeometry {
189 fn default() -> Self {
191 Self {
192 indicator_size: MGUI_INDICATOR_SIZE,
193 border_width: 1.0,
194 label_gap: 8.0,
195 focus_ring_width: 2.0,
196 focus_ring_offset: 3.0,
197 switch_width: 40.0,
198 switch_height: 24.0,
199 switch_thumb: 20.0,
200 switch_thumb_inset: 2.0,
201 slider_track_height: 4.0,
202 slider_thumb_size: 20.0,
203 indicator_radius: 4.0,
204 button_height_sm: 28.0,
205 button_height_md: 32.0,
206 button_height_lg: 36.0,
207 button_padding_h: 12.0,
208 button_border_width: 1.0,
209 }
210 }
211}
212
213impl ControlGeometry {
214 pub fn button_height_at(&self, which: usize) -> f32 {
219 match which {
220 0 => self.button_height_sm,
221 1 => self.button_height_md,
222 _ => self.button_height_lg,
223 }
224 }
225}
226
227pub const MGUI_INDICATOR_SIZE: f32 = 18.0;
234
235fn luminance(color: Color) -> f32 {
237 let channel = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
238 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
239}
240
241fn best_on(tokens: &Tokens, background: Color) -> Color {
245 use crate::theme::tokens::ColorToken;
246 if luminance(background) < 0.5 {
248 tokens.color(ColorToken::OnDark)
249 } else {
250 tokens.color(ColorToken::OnLight)
251 }
252}
253
254#[derive(Debug, Clone, PartialEq)]
255pub struct ScrollbarStyle {
256 pub thumb_color: Color,
257 pub thumb_hover_color: Color,
259 pub thumb_radius: f32,
260 pub thumb_width: f32,
262 pub hit_width: f32,
264 pub thumb_min_size: f32,
266}
267
268#[derive(Debug, Clone, PartialEq)]
270pub struct InputStyle {
271 pub background: Color,
272 pub border: Color,
273 pub focused_border: Color,
274 pub text_color: Color,
275 pub placeholder_color: Color,
276 pub radius: f32,
277}
278
279#[derive(Debug, Clone, PartialEq)]
281pub struct TooltipStyle {
282 pub background: Color,
283 pub foreground: Color,
284 pub border: Color,
285 pub radius: f32,
286}
287
288#[derive(Debug, Clone, PartialEq)]
290pub struct MenuStyle {
291 pub background: Color,
292 pub foreground: Color,
293 pub hover_background: Color,
294 pub border: Color,
295 pub radius: f32,
296}
297
298#[derive(Debug, Clone, PartialEq)]
300pub struct TabStyle {
301 pub background: Color,
302 pub active_foreground: Color,
303 pub inactive_foreground: Color,
304 pub hover_background: Color,
305 pub indicator_color: Color,
306}
307
308#[derive(Debug, Clone, PartialEq)]
310pub struct NavStyle {
311 pub active_background: Color,
312 pub active_foreground: Color,
313 pub foreground: Color,
314 pub hover_background: Color,
315 pub indicator_color: Color,
316}
317
318#[derive(Debug, Clone, PartialEq)]
320pub struct FeedbackStyle {
321 pub progress_track: Color,
322 pub progress_value: Color,
323 pub success: Color,
324 pub warning: Color,
325 pub info: Color,
327 pub error: Color,
329}
330
331#[derive(Debug, Clone, PartialEq)]
333pub struct DropdownStyle {
334 pub background: Color,
335 pub foreground: Color,
336 pub placeholder: Color,
337 pub border: Color,
338 pub open_border: Color,
339 pub hover: Color,
340 pub selected_background: Color,
341 pub disabled: Color,
342}
343
344#[derive(Debug, Clone, PartialEq)]
346pub struct DialogStyle {
347 pub barrier: Color,
348 pub background: Color,
349 pub radius: f32,
350}
351
352#[derive(Debug, Clone, PartialEq)]
354pub struct ListStyle {
355 pub hover_background: Color,
356 pub selected_background: Color,
357 pub foreground: Color,
358}
359
360#[derive(Debug, Clone, PartialEq)]
362pub struct SpacingScale {
363 pub xxs: f32,
365 pub xs: f32,
367 pub s: f32,
369 pub m: f32,
371 pub l: f32,
373 pub xl: f32,
375 pub control_padding: f32,
377 pub container_padding: f32,
379 pub container_gap: f32,
381}
382
383impl Default for SpacingScale {
384 fn default() -> Self {
385 Self {
386 xxs: 2.0,
387 xs: 4.0,
388 s: 8.0,
389 m: 16.0,
390 l: 24.0,
391 xl: 32.0,
392 control_padding: 8.0,
393 container_padding: 16.0,
394 container_gap: 8.0,
395 }
396 }
397}
398
399#[derive(Debug, Clone, PartialEq)]
411pub struct ThemeData {
412 pub background: Color,
414 pub foreground: Color,
415 pub primary: Color,
416 pub accent: Color,
417 pub surface: Color,
418 pub error: Color,
419 pub high_contrast: bool,
421
422 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,
439
440 pub text: TextTheme,
442 pub button: ButtonStyle,
443 pub button_variants: ButtonVariants,
445 pub avatar: AvatarStyle,
447 pub control: ControlStyle,
449 pub geom: ControlGeometry,
451 pub scrollbar: ScrollbarStyle,
452 pub input: InputStyle,
453 pub tooltip: TooltipStyle,
454 pub menu: MenuStyle,
455 pub tab: TabStyle,
456 pub nav: NavStyle,
457 pub feedback: FeedbackStyle,
458 pub dropdown: DropdownStyle,
459 pub dialog: DialogStyle,
460 pub list: ListStyle,
461}
462
463impl Default for ThemeData {
464 fn default() -> Self {
465 Self::neutral_dark()
466 }
467}
468
469impl ThemeData {
470 pub fn dark() -> Self {
472 Self::neutral_dark()
473 }
474
475 pub fn light() -> Self {
477 Self::neutral_light()
478 }
479 pub fn neutral(dark: bool) -> Self {
483 Self::from_tokens(&crate::theme::tokens::define_theme().resolve(dark))
484 }
485
486 pub fn neutral_light() -> Self {
487 Self::neutral(false)
488 }
489
490 pub fn neutral_dark() -> Self {
491 Self::neutral(true)
492 }
493
494 pub fn from_tokens(tokens: &Tokens) -> Self {
504 use crate::theme::tokens::{ColorToken as C, SpacingStep as S, TextRole as R};
505
506 let color = |token: C| tokens.color(token);
507 let radius = tokens.radius();
508 let focus = tokens.focus();
509 let surface = color(C::BackgroundSurface);
510 let popover = color(C::BackgroundPopover);
511 let accent = color(C::Accent);
512
513 let filled_variant = |fill: C, on: C| ButtonVariantStyle {
514 background: color(fill),
515 foreground: color(on),
516 border: Color::TRANSPARENT,
517 hover_background: tokens.hovered(color(fill)),
518 pressed_background: tokens.pressed(color(fill)),
519 };
520 let button_variants = ButtonVariants {
521 primary: filled_variant(C::Accent, C::OnAccent),
522 normal: ButtonVariantStyle {
523 background: surface,
524 foreground: color(C::TextPrimary),
525 border: color(C::BorderEmphasized),
526 hover_background: tokens.hovered(surface),
527 pressed_background: tokens.pressed(surface),
528 },
529 tertiary: ButtonVariantStyle {
530 background: Color::TRANSPARENT,
531 foreground: color(C::TextPrimary),
532 border: Color::TRANSPARENT,
533 hover_background: color(C::OverlayHover),
534 pressed_background: color(C::OverlayPressed),
535 },
536 success: filled_variant(C::Success, C::OnSuccess),
537 warning: filled_variant(C::Warning, C::OnWarning),
538 error: filled_variant(C::Error, C::OnError),
539 info: filled_variant(C::Info, C::OnInfo),
540 };
541
542 let tooltip_bg = color(C::BackgroundInverted);
544 let body = tokens.text_role(R::Body);
545 let heading = tokens.text_role(R::HeadingTwo);
546 let text = TextTheme {
547 headline: TextStyleTheme { font_size: tokens.text_role(R::HeadingOne).size, color: color(C::TextPrimary) },
548 title: TextStyleTheme { font_size: heading.size, color: color(C::TextPrimary) },
549 body: TextStyleTheme { font_size: body.size, color: color(C::TextPrimary) },
550 caption: TextStyleTheme { font_size: tokens.text_role(R::Supporting).size, color: color(C::TextSecondary) },
551 };
552
553 let track = color(C::Track);
554 let scrollbar = ScrollbarStyle {
555 thumb_color: track,
556 thumb_hover_color: color(C::BorderEmphasized),
557 thumb_radius: radius.inner,
558 thumb_width: tokens.spacing(S::S2),
560 hit_width: tokens.spacing(S::S2) + 2.0,
561 thumb_min_size: tokens.spacing(S::S6),
563 };
564
565 let size = tokens.element_size();
567
568 Self {
569 background: color(C::BackgroundBody),
570 foreground: color(C::TextPrimary),
571 primary: accent,
572 accent: color(C::TextAccent),
573 surface,
574 error: color(C::TextError),
575 high_contrast: false,
576 border: color(C::Border),
577 divider: color(C::Border),
578 hover: color(C::OverlayHover),
579 disabled: color(C::TextDisabled),
580 selection: color(C::AccentMuted),
581 icon: color(C::IconPrimary),
582 radius_sm: radius.inner,
583 radius_md: radius.element,
584 radius_lg: radius.container,
585 spacing: tokens.spacing(S::S2),
586 space: SpacingScale {
587 xxs: tokens.spacing(S::S0_5),
588 xs: tokens.spacing(S::S1),
589 s: tokens.spacing(S::S2),
590 m: tokens.spacing(S::S4),
591 l: tokens.spacing(S::S6),
592 xl: tokens.spacing(S::S8),
593 control_padding: tokens.spacing(S::S2),
594 container_padding: tokens.spacing(S::S4),
595 container_gap: tokens.spacing(S::S2),
596 },
597 text,
598 button: ButtonStyle {
599 background: accent,
600 foreground: color(C::OnAccent),
601 radius: radius.element,
602 focus_ring_color: focus.color,
603 focus_ring_width: focus.width,
604 },
605 button_variants,
606 avatar: AvatarStyle {
607 palette: [
609 color(C::DataCategoricalBlue),
610 color(C::DataCategoricalGreen),
611 color(C::DataCategoricalOrange),
612 color(C::DataCategoricalPurple),
613 color(C::DataCategoricalRed),
614 color(C::DataCategoricalTeal),
615 ],
616 foreground: color(C::OnAccent),
617 },
618 control: ControlStyle {
619 background: surface,
620 border: color(C::BorderEmphasized),
621 checked_background: accent,
622 checked_foreground: color(C::OnAccent),
623 disabled_background: color(C::BackgroundMuted),
624 disabled_border: color(C::Border),
625 toggle_off: track,
626 slider_track: track,
627 slider_range_active: accent,
628 },
629 geom: ControlGeometry {
630 indicator_size: MGUI_INDICATOR_SIZE,
632 border_width: tokens.border_width(),
633 label_gap: tokens.spacing(S::S2),
634 focus_ring_width: focus.width,
635 focus_ring_offset: focus.offset,
636 indicator_radius: radius.inner,
637 switch_width: 40.0,
639 switch_height: 24.0,
640 switch_thumb: 20.0,
641 switch_thumb_inset: 2.0,
642 slider_track_height: 4.0,
643 slider_thumb_size: 20.0,
644 button_height_sm: size.sm,
646 button_height_md: size.md,
647 button_height_lg: size.lg,
648 button_padding_h: tokens.spacing(S::S3),
649 button_border_width: tokens.border_width(),
650 },
651 scrollbar,
652 input: InputStyle {
653 background: surface,
654 border: color(C::BorderEmphasized),
655 focused_border: focus.color,
656 text_color: color(C::TextPrimary),
657 placeholder_color: color(C::TextSecondary),
658 radius: radius.element,
659 },
660 tooltip: TooltipStyle {
661 background: tooltip_bg,
662 foreground: best_on(tokens, tooltip_bg),
663 border: Color::TRANSPARENT,
664 radius: radius.element,
665 },
666 menu: MenuStyle {
667 background: popover,
668 foreground: color(C::TextPrimary),
669 hover_background: tokens.hovered(popover),
670 border: color(C::Border),
671 radius: radius.container,
672 },
673 tab: TabStyle {
674 background: surface,
675 active_foreground: color(C::TextPrimary),
676 inactive_foreground: color(C::TextSecondary),
677 hover_background: tokens.hovered(surface),
678 indicator_color: accent,
679 },
680 nav: NavStyle {
681 active_background: color(C::AccentMuted),
682 active_foreground: color(C::TextAccent),
683 foreground: color(C::TextPrimary),
684 hover_background: tokens.hovered(surface),
685 indicator_color: accent,
686 },
687 feedback: FeedbackStyle {
688 progress_track: track,
689 progress_value: accent,
690 success: color(C::TextSuccess),
691 warning: color(C::TextWarning),
692 info: color(C::TextInfo),
693 error: color(C::TextError),
694 },
695 dropdown: DropdownStyle {
696 background: popover,
697 foreground: color(C::TextPrimary),
698 placeholder: color(C::TextSecondary),
699 border: color(C::BorderEmphasized),
700 open_border: focus.color,
701 hover: tokens.hovered(popover),
702 selected_background: color(C::AccentMuted),
703 disabled: color(C::TextDisabled),
704 },
705 dialog: DialogStyle {
706 barrier: color(C::Overlay),
707 background: color(C::BackgroundCard),
708 radius: radius.container,
709 },
710 list: ListStyle {
711 hover_background: tokens.hovered(surface),
712 selected_background: color(C::AccentMuted),
713 foreground: color(C::TextPrimary),
714 },
715 }
716 }
717
718 pub fn high_contrast(dark: bool) -> Self {
730 use crate::theme::tokens::ColorToken as C;
731
732 let (bg, fg, dim, primary, on_primary, focus, info, error, success, warning, hover, selection, barrier) =
733 if dark {
734 (
735 Color::BLACK,
736 Color::WHITE,
737 Color::from_rgb8(0xB0, 0xB0, 0xB0),
738 Color::from_rgb8(0xFF, 0xD7, 0x00),
739 Color::BLACK,
740 Color::WHITE,
741 Color::from_rgb8(0x00, 0xFF, 0xFF),
742 Color::from_rgb8(0xFF, 0x80, 0x80),
743 Color::from_rgb8(0x7C, 0xFC, 0x7C),
744 Color::from_rgb8(0xFF, 0xD7, 0x00),
745 Color::rgba(1.0, 1.0, 1.0, 0.20),
746 Color::rgba(1.0, 0.843, 0.0, 0.35),
747 Color::rgba(0.0, 0.0, 0.0, 0.85),
748 )
749 } else {
750 (
751 Color::WHITE,
752 Color::BLACK,
753 Color::from_rgb8(0x50, 0x50, 0x50),
754 Color::from_rgb8(0x00, 0x33, 0xCC),
755 Color::WHITE,
756 Color::BLACK,
757 Color::from_rgb8(0x00, 0x5A, 0x5A),
758 Color::from_rgb8(0xB0, 0x00, 0x20),
759 Color::from_rgb8(0x00, 0x64, 0x00),
760 Color::from_rgb8(0x7A, 0x4F, 0x00),
761 Color::rgba(0.0, 0.0, 0.0, 0.12),
762 Color::rgba(0.0, 0.2, 0.8, 0.18),
763 Color::rgba(0.0, 0.0, 0.0, 0.60),
764 )
765 };
766
767 let mut def = define_theme().named("high-contrast");
768 for (token, color) in [
769 (C::BackgroundBody, bg),
771 (C::BackgroundSurface, bg),
772 (C::BackgroundCard, bg),
773 (C::BackgroundPopover, bg),
774 (C::BackgroundMuted, bg),
775 (C::BackgroundInverted, fg),
776 (C::TextPrimary, fg),
777 (C::TextSecondary, dim),
778 (C::TextDisabled, dim),
779 (C::TextAccent, primary),
780 (C::TextInfo, info),
781 (C::TextSuccess, success),
782 (C::TextWarning, warning),
783 (C::TextError, error),
784 (C::IconPrimary, fg),
785 (C::IconSecondary, dim),
786 (C::IconDisabled, dim),
787 (C::Accent, primary),
788 (C::AccentMuted, selection),
789 (C::OnAccent, on_primary),
790 (C::Info, info),
791 (C::OnInfo, on_primary),
792 (C::Success, success),
793 (C::OnSuccess, on_primary),
794 (C::Warning, warning),
795 (C::OnWarning, on_primary),
796 (C::Error, error),
797 (C::OnError, on_primary),
798 (C::Border, fg),
799 (C::BorderEmphasized, fg),
800 (C::BorderInfo, info),
801 (C::BorderSuccess, success),
802 (C::BorderWarning, warning),
803 (C::BorderError, error),
804 (C::OverlayHover, hover),
805 (C::OverlayPressed, hover),
806 (C::Overlay, barrier),
807 (C::Track, dim),
808 (C::Skeleton, dim),
809 (C::Shadow, bg),
810 (C::FocusOutline, focus),
811 (C::DataCategoricalBlue, Color::from_rgb8(0x00, 0x50, 0x80)),
813 (C::DataCategoricalGreen, Color::from_rgb8(0x00, 0x50, 0x00)),
814 (C::DataCategoricalOrange, Color::from_rgb8(0x6B, 0x2A, 0x00)),
815 (C::DataCategoricalPurple, Color::from_rgb8(0x3B, 0x00, 0x80)),
816 (C::DataCategoricalRed, Color::from_rgb8(0x90, 0x00, 0x00)),
817 (C::DataCategoricalTeal, Color::from_rgb8(0x00, 0x4A, 0x4A)),
818 ] {
819 def.set_color(token, color, color);
820 }
821 for name in [
822 "--radius-inner",
823 "--radius-element",
824 "--radius-container",
825 "--radius-page",
826 "--radius-chat",
827 "--focus-outline-width",
828 ] {
829 let value = if name == "--focus-outline-width" { "3px" } else { "0px" };
830 def.set_token(name, value).expect("内置 token 名与形状必然合法");
831 }
832
833 let mut theme = Self::from_tokens(&def.resolve(dark));
834 theme.high_contrast = true;
835 theme
836 }
837}
838
839#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
844pub enum Direction {
845 #[default]
846 Ltr,
847 Rtl,
848}
849
850pub const fn resolve_color(explicit: Option<Color>, themed: Color) -> Color {
859 match explicit {
860 Some(color) => color,
861 None => themed,
862 }
863}
864
865pub const fn resolve_f32(explicit: Option<f32>, themed: f32) -> f32 {
867 match explicit {
868 Some(value) => value,
869 None => themed,
870 }
871}
872
873#[derive(Debug)]
877pub struct ThemeWidget {
878 pub theme: Rc<ThemeData>,
879 pub direction: Direction,
880 pub child: Option<WidgetNode>,
881}
882
883impl ThemeWidget {
884 pub fn new(theme: ThemeData) -> Self {
885 Self::from_rc(Rc::new(theme))
886 }
887
888 pub fn from_rc(theme: Rc<ThemeData>) -> Self {
889 Self { theme, direction: Direction::Ltr, child: None }
890 }
891
892 pub fn dark() -> Self {
893 Self::new(ThemeData::dark())
894 }
895
896 pub fn light() -> Self {
897 Self::new(ThemeData::light())
898 }
899
900 pub fn with_direction(mut self, d: Direction) -> Self {
901 self.direction = d;
902 self
903 }
904
905 pub fn child(mut self, c: impl Widget) -> Self {
906 self.child = Some(WidgetNode::new(c));
907 self
908 }
909
910 pub fn child_node(mut self, c: WidgetNode) -> Self {
911 self.child = Some(c);
912 self
913 }
914}
915
916impl InheritedWidget for ThemeWidget {
917 fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
918 if let Some(old_theme) = old.as_any().downcast_ref::<ThemeWidget>() {
920 if Rc::ptr_eq(&self.theme, &old_theme.theme) {
921 return self.direction != old_theme.direction;
922 }
923 *self.theme != *old_theme.theme || self.direction != old_theme.direction
924 } else {
925 true
926 }
927 }
928
929 fn as_any(&self) -> &dyn Any {
930 self
931 }
932}
933
934impl ThemeWidget {
935 pub fn theme(&self) -> &ThemeData {
936 &self.theme
937 }
938
939 pub fn direction(&self) -> Direction {
940 self.direction
941 }
942}
943
944impl Widget for ThemeWidget {
945 fn as_any(&self) -> &dyn Any {
946 self
947 }
948
949 fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
950 Some(self)
951 }
952
953 fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
954 match &self.child {
959 Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
960 None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
961 }
962 }
963
964 fn children(&self) -> Vec<WidgetNode> {
965 self.child.clone().into_iter().collect()
966 }
967
968 fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
969 self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
970 }
971}
972
973#[derive(Debug)]
979pub struct DirectionWidget {
980 pub direction: Direction,
981 pub child: Option<WidgetNode>,
982}
983
984impl DirectionWidget {
985 pub fn new(d: Direction) -> Self {
986 Self { direction: d, child: None }
987 }
988
989 pub fn child(mut self, c: impl Widget) -> Self {
990 self.child = Some(WidgetNode::new(c));
991 self
992 }
993}
994
995impl InheritedWidget for DirectionWidget {
996 fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
997 if let Some(old_dir) = old.as_any().downcast_ref::<DirectionWidget>() {
998 self.direction != old_dir.direction
999 } else {
1000 true
1001 }
1002 }
1003
1004 fn as_any(&self) -> &dyn Any {
1005 self
1006 }
1007}
1008
1009impl DirectionWidget {
1010 pub fn direction(&self) -> Direction {
1011 self.direction
1012 }
1013}
1014
1015impl Widget for DirectionWidget {
1016 fn as_any(&self) -> &dyn Any {
1017 self
1018 }
1019
1020 fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
1021 Some(self)
1022 }
1023
1024 fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
1025 match &self.child {
1027 Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
1028 None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
1029 }
1030 }
1031
1032 fn children(&self) -> Vec<WidgetNode> {
1033 self.child.clone().into_iter().collect()
1034 }
1035
1036 fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
1037 self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
1038 }
1039}
1040
1041#[derive(Debug, Clone, PartialEq, Eq)]
1047pub struct LocaleSnapshot {
1048 pub tag: Rc<str>,
1049 pub direction: Direction,
1050 pub generation: u64,
1052}
1053
1054impl LocaleSnapshot {
1055 pub fn new(tag: impl Into<Rc<str>>, direction: Direction, generation: u64) -> Self {
1056 Self { tag: tag.into(), direction, generation }
1057 }
1058
1059 pub fn tag(&self) -> &str {
1060 &self.tag
1061 }
1062}
1063
1064#[derive(Debug)]
1066pub struct LocaleWidget {
1067 pub locale: LocaleSnapshot,
1068 pub child: Option<WidgetNode>,
1069}
1070
1071impl LocaleWidget {
1072 pub fn new(locale: LocaleSnapshot) -> Self {
1073 Self { locale, child: None }
1074 }
1075
1076 pub fn child_node(mut self, c: WidgetNode) -> Self {
1077 self.child = Some(c);
1078 self
1079 }
1080
1081 pub fn locale(&self) -> &LocaleSnapshot {
1082 &self.locale
1083 }
1084}
1085
1086impl InheritedWidget for LocaleWidget {
1087 fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
1088 old.as_any().downcast_ref::<LocaleWidget>().map(|old| self.locale != old.locale).unwrap_or(true)
1089 }
1090
1091 fn as_any(&self) -> &dyn Any {
1092 self
1093 }
1094}
1095
1096impl Widget for LocaleWidget {
1097 fn as_any(&self) -> &dyn Any {
1098 self
1099 }
1100
1101 fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
1102 Some(self)
1103 }
1104
1105 fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
1106 match &self.child {
1107 Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
1108 None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
1109 }
1110 }
1111
1112 fn children(&self) -> Vec<WidgetNode> {
1113 self.child.clone().into_iter().collect()
1114 }
1115
1116 fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
1117 self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
1118 }
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123 use super::tokens::{ColorToken as C, FontSizeToken, LengthToken, SpacingStep};
1124 use super::*;
1125 use crate::inherited::InheritedWidget;
1126
1127 #[test]
1128 fn locale_widget_notifies_on_generation_change() {
1129 let a = LocaleWidget::new(LocaleSnapshot::new("en", Direction::Ltr, 1));
1130 let b = LocaleWidget::new(LocaleSnapshot::new("ar", Direction::Rtl, 2));
1131 let same = LocaleWidget::new(LocaleSnapshot::new("ar", Direction::Rtl, 2));
1132 assert!(b.update_should_notify(&a));
1133 assert!(!same.update_should_notify(&b));
1134 }
1135
1136 fn contrast(a: Color, b: Color) -> f32 {
1137 let (la, lb) = (luminance(a), luminance(b));
1138 (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
1139 }
1140
1141 fn themed(definition: tokens::ThemeDefinition, dark: bool) -> ThemeData {
1143 ThemeData::from_tokens(&definition.resolve(dark))
1144 }
1145
1146 #[test]
1147 fn neutral_palette_matches_astryx_tokens() {
1148 let light = ThemeData::neutral_light();
1149 assert_eq!(light.primary, Color::from_rgb8(0x00, 0x64, 0xE0));
1150 assert_eq!(light.background, Color::from_rgb8(0xF1, 0xF4, 0xF7));
1151 assert_eq!(light.surface, Color::WHITE);
1152 assert_eq!(light.foreground, Color::from_rgb8(0x0A, 0x13, 0x17));
1153 assert_eq!(light.button.foreground, Color::WHITE);
1154 assert_eq!(light.button.radius, 8.0, "Astryx 按钮用 --radius-element");
1155 assert_eq!(light.input.radius, 8.0);
1156 assert_eq!(light.dialog.radius, 12.0, "Astryx 容器用 --radius-container");
1157
1158 let dark = ThemeData::neutral_dark();
1159 assert_eq!(dark.primary, Color::from_rgb8(0x26, 0x94, 0xFE));
1160 assert_eq!(dark.background, Color::from_rgb8(0x11, 0x11, 0x12));
1161 assert_eq!(dark.surface, Color::from_rgb8(0x1F, 0x1F, 0x22));
1162 assert_eq!(dark.foreground, Color::from_rgb8(0xDF, 0xE2, 0xE5));
1163 assert_eq!(dark.button_variants.error.foreground, Color::from_rgb8(0x0A, 0x13, 0x17));
1165
1166 assert_eq!((light.radius_sm, light.radius_md, light.radius_lg), (4.0, 8.0, 12.0));
1168 assert_eq!(light.text.body.font_size, 14.0, "--text-body-size");
1169 assert_eq!(light.text.headline.font_size, 24.0, "--text-heading-1-size");
1170 assert_eq!(light.text.caption.font_size, 12.0, "--text-supporting-size");
1171 assert_eq!(light.spacing, 8.0, "--spacing-2");
1172 assert_eq!(light.scrollbar.thumb_width, 8.0);
1173 }
1174
1175 #[test]
1176 fn aliases_and_default_are_the_same_theme() {
1177 assert_eq!(ThemeData::dark(), ThemeData::neutral(true));
1178 assert_eq!(ThemeData::light(), ThemeData::neutral(false));
1179 assert_eq!(ThemeData::default(), ThemeData::neutral_dark());
1180 assert_ne!(ThemeData::neutral_light(), ThemeData::neutral_dark());
1181 }
1182
1183 #[test]
1186 fn button_metrics_follow_element_spacing_and_border_tokens() {
1187 let base = themed(define_theme(), false);
1188 assert_eq!(
1189 (base.geom.button_height_sm, base.geom.button_height_md, base.geom.button_height_lg),
1190 (28.0, 32.0, 36.0),
1191 "Astryx --size-element-sm/md/lg 默认档"
1192 );
1193 assert_eq!((base.geom.button_padding_h, base.geom.button_border_width), (12.0, 1.0));
1194
1195 let tuned = themed(
1196 define_theme()
1197 .token("--size-element-md", "2.5rem")
1198 .expect("合法 token")
1199 .token("--spacing-3", "1rem")
1200 .expect("合法 token")
1201 .token("--border-width", "2px")
1202 .expect("合法 token"),
1203 false,
1204 );
1205 assert_eq!(tuned.geom.button_height_md, 40.0, "2.5rem = 40px,只有 md 变");
1206 assert_eq!((tuned.geom.button_height_sm, tuned.geom.button_height_lg), (28.0, 36.0));
1207 assert_eq!((tuned.geom.button_padding_h, tuned.geom.button_border_width), (16.0, 2.0));
1208
1209 let rounded = themed(define_theme().radius_multiplier(1.5), false);
1211 assert_eq!(rounded.geom.button_height_md, 32.0);
1212 assert!(rounded.geom.indicator_radius > base.geom.indicator_radius);
1213 }
1214
1215 #[test]
1216 fn emphasis_and_focus_all_follow_the_accent_token() {
1217 for t in [ThemeData::neutral_light(), ThemeData::neutral_dark()] {
1218 assert_eq!(t.button.focus_ring_color, t.primary);
1219 assert_eq!(t.tab.indicator_color, t.primary);
1220 assert_eq!(t.nav.indicator_color, t.primary);
1221 assert_eq!(t.feedback.progress_value, t.primary);
1222 assert_eq!(t.dropdown.open_border, t.primary);
1223 assert_eq!(t.input.focused_border, t.primary);
1224 assert_eq!(t.text.body.color, t.foreground);
1225 assert_eq!(t.button.focus_ring_width, 2.0, "--focus-outline-width");
1226 }
1227 }
1228
1229 #[test]
1230 fn button_variants_and_avatar_come_from_status_tokens() {
1231 let light = ThemeData::neutral_light();
1232 assert_eq!(light.button_variants.primary.background, light.primary);
1233 assert_eq!(light.button_variants.primary.foreground, Color::WHITE);
1234 assert_eq!(light.button_variants.tertiary.background, Color::TRANSPARENT);
1235 assert_eq!(light.button_variants.normal.background, light.surface);
1236 assert_ne!(light.button_variants.normal.border, Color::TRANSPARENT, "常规按钮有描边");
1237
1238 let dark = ThemeData::neutral_dark();
1239 assert_eq!(dark.button_variants.success.background, Color::from_rgb8(0x0D, 0x86, 0x26));
1240 assert_eq!(dark.button_variants.error.background, Color::from_rgb8(0xF5, 0x39, 0x4F));
1241 assert_ne!(dark.feedback.success, dark.button_variants.success.background);
1243 assert_eq!(dark.avatar.foreground, Color::WHITE, "分类色上写 --color-on-dark");
1244 let mut seen = std::collections::HashSet::new();
1245 for color in dark.avatar.palette {
1246 let key = ((color.r * 255.0) as i32, (color.g * 255.0) as i32, (color.b * 255.0) as i32);
1247 assert!(seen.insert(key), "Avatar 轮换池不该重复");
1248 }
1249 }
1250
1251 #[test]
1252 fn hover_and_pressed_are_composited_overlays() {
1253 for dark in [false, true] {
1254 let t = ThemeData::neutral(dark);
1255 assert!(t.hover.a < 1.0, "--color-overlay-hover 是带 alpha 的叠加层");
1256 let primary = t.button_variants.primary;
1257 assert_ne!(primary.hover_background, primary.background);
1258 assert_ne!(primary.hover_background, primary.pressed_background, "hover 与 pressed 不同档");
1259 assert!(primary.hover_background.a >= 1.0, "叠加后填色仍是不透明色");
1260 assert_ne!(t.list.hover_background, t.surface);
1261 assert_ne!(t.menu.hover_background, t.dropdown.background);
1262 }
1263 }
1264
1265 #[test]
1266 fn overriding_one_token_restyles_the_whole_tree() {
1267 let base = ThemeData::neutral_dark();
1270 let brand = themed(tokens::define_theme().token("--color-accent", "#7B61FF").unwrap(), true);
1271 let purple = Color::from_rgb8(0x7B, 0x61, 0xFF);
1272 assert_eq!(brand.primary, purple);
1273 assert_eq!(brand.button.background, purple);
1274 assert_eq!(brand.button.focus_ring_color, purple);
1275 assert_eq!(brand.input.focused_border, purple);
1276 assert_eq!(brand.tab.indicator_color, purple);
1277 assert_eq!(brand.nav.indicator_color, purple);
1278 assert_eq!(brand.feedback.progress_value, purple);
1279 assert_eq!(brand.button_variants.primary.hover_background, tokens::overlay(purple, base.hover));
1280 assert_ne!(brand, base);
1281
1282 let square = themed(tokens::define_theme().radius_multiplier(0.0), false);
1284 assert_eq!((square.radius_sm, square.radius_md, square.radius_lg), (0.0, 0.0, 0.0));
1285 assert_eq!(square.button.radius, 0.0);
1286 assert_eq!(square.dialog.radius, 0.0);
1287 assert_eq!(square.input.radius, 0.0);
1288
1289 let large = themed(tokens::define_theme().text_scale(18.0, 1.2), false);
1290 let large_tokens = tokens::define_theme().text_scale(18.0, 1.2).resolve(false);
1291 assert_eq!(large.text.body.font_size, large_tokens.font_size(FontSizeToken::Base));
1292 assert_eq!(large.text.body.font_size, 18.0);
1293 assert_eq!(large.text.caption.font_size, large_tokens.font_size(FontSizeToken::Sm));
1294 assert_eq!(large.text.caption.font_size, 15.0, "--text-supporting-size = --font-size-sm");
1295
1296 let roomy = themed(tokens::define_theme().token("--spacing-2", "12px").unwrap(), false);
1298 assert_eq!(roomy.spacing, 12.0);
1299 assert_eq!(roomy.space.s, 12.0);
1300 assert_eq!(roomy.space.control_padding, 12.0);
1301 }
1302
1303 #[test]
1304 fn status_text_meets_aa_contrast_on_both_surfaces() {
1305 for dark in [false, true] {
1306 let t = ThemeData::neutral(dark);
1307 for (label, color, bg) in [
1308 ("正文/表面", t.foreground, t.surface),
1309 ("次要/表面", t.text.caption.color, t.surface),
1310 ("成功/表面", t.feedback.success, t.surface),
1311 ("警告/表面", t.feedback.warning, t.surface),
1312 ("错误/表面", t.feedback.error, t.surface),
1313 ("信息/表面", t.feedback.info, t.surface),
1314 ("正文/画布", t.foreground, t.background),
1315 ] {
1316 let ratio = contrast(color, bg);
1317 assert!(ratio >= 4.5, "{label} 对比度 {ratio:.2} < 4.5 (dark={dark})");
1318 }
1319 }
1320 }
1321
1322 #[test]
1323 fn filled_button_label_keeps_the_astryx_contrast_floor() {
1330 let light = ThemeData::neutral_light();
1331 assert!(contrast(light.button.foreground, light.button.background) >= 4.5, "浅色档主按钮应达 4.5:1");
1332 let dark = ThemeData::neutral_dark();
1333 let ratio = contrast(dark.button.foreground, dark.button.background);
1334 assert!(ratio >= 3.0, "深色档主按钮文字对比度 {ratio:.2} < 3.0(Astryx 原值即 3.11)");
1335 let hc = ThemeData::high_contrast(true);
1337 assert!(contrast(hc.button.foreground, hc.button.background) >= 4.5, "高对比度档主按钮不足 4.5:1");
1338 }
1339
1340 #[test]
1341 fn overlay_tokens_are_visible_on_their_own_container() {
1342 for dark in [false, true] {
1343 let tokens = tokens::define_theme().resolve(dark);
1344 let surface = tokens.color(C::BackgroundSurface);
1345 assert_ne!(tokens.hovered(surface), surface, "dark={dark}");
1346 assert_ne!(tokens.pressed(surface), tokens.hovered(surface), "dark={dark}");
1347 }
1348 }
1349
1350 #[test]
1351 fn neutral_light_and_dark_have_opposite_luminance() {
1352 let light = ThemeData::neutral_light();
1353 let dark = ThemeData::neutral_dark();
1354 let luma = |c: Color| c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722;
1355 assert!(luma(light.background) > 0.8, "浅色画布应接近白色");
1356 assert!(luma(dark.background) < 0.15, "深色画布应接近黑色");
1357 assert!(luma(light.foreground) < 0.2, "浅色主题正文应为深色");
1358 assert!(luma(dark.foreground) > 0.6, "深色主题正文应为浅色");
1359 }
1360
1361 #[test]
1362 fn high_contrast_palette_meets_wcag_and_uses_square_corners() {
1363 for dark in [false, true] {
1364 let theme = ThemeData::high_contrast(dark);
1365 assert!(theme.high_contrast);
1366 assert_eq!(theme.background, if dark { Color::BLACK } else { Color::WHITE });
1367 assert!(contrast(theme.foreground, theme.background) >= 7.0, "正文对比度不足");
1368 assert!(contrast(theme.primary, theme.background) >= 4.5, "主色对比度不足");
1369 assert!(contrast(theme.border, theme.background) >= 3.0, "边框对比度不足");
1370 assert!(contrast(theme.text.caption.color, theme.background) >= 4.5, "次要文字对比度不足");
1371 assert!(contrast(theme.button.foreground, theme.button.background) >= 4.5, "主按钮文字对比度不足");
1372 assert!(
1373 contrast(theme.button_variants.normal.foreground, theme.button_variants.normal.background) >= 4.5,
1374 "常规按钮文字对比度不足"
1375 );
1376 assert!(contrast(theme.input.text_color, theme.input.background) >= 7.0, "输入框文字对比度不足");
1377 assert!(contrast(theme.tooltip.foreground, theme.tooltip.background) >= 7.0, "Tooltip 文字对比度不足");
1378 assert_eq!(theme.radius_sm, 0.0);
1379 assert_eq!(theme.radius_md, 0.0);
1380 assert_eq!(theme.radius_lg, 0.0);
1381 assert_eq!(theme.button.radius, 0.0);
1382 assert_eq!(theme.input.radius, 0.0);
1383 assert_eq!(theme.dialog.radius, 0.0);
1384 assert_eq!(theme.menu.radius, 0.0);
1385 assert!(theme.button.focus_ring_width >= 3.0);
1386 assert_eq!(theme.divider, theme.foreground, "分割线走前景色");
1387 }
1388 }
1389
1390 #[test]
1391 fn theme_derivation_is_cheap_enough_for_live_editing() {
1393 let definition = crate::theme::tokens::define_theme().radius_multiplier(1.5);
1394 let iterations = 200;
1395 let start = std::time::Instant::now();
1396 for _ in 0..iterations {
1397 let theme = ThemeData::from_tokens(&definition.resolve(true));
1398 std::hint::black_box(&theme);
1399 }
1400 let per = start.elapsed().as_micros() as f64 / iterations as f64;
1401 assert!(per < 2_000.0, "单次 resolve + from_tokens = {per:.0}µs,实时改 token 会掉帧");
1402 }
1403
1404 #[test]
1405 fn spacing_scale_defaults() {
1406 let s = ThemeData::neutral_dark().space;
1407 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));
1408 assert_eq!(s.control_padding, 8.0, "控件默认内边距");
1409 assert_eq!(s.container_padding, 16.0, "容器默认内边距");
1410 assert_eq!(s.container_gap, 8.0, "容器默认子项间距");
1411
1412 let tokens = tokens::define_theme().resolve(true);
1414 assert_eq!(tokens.spacing(SpacingStep::S0_5), 2.0);
1415 assert_eq!(tokens.spacing(SpacingStep::S8), 32.0);
1416 assert_eq!(tokens.length(LengthToken::RadiusContainer), 12.0);
1417 }
1418}