Skip to main content

teksilo_theme_material3/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Material 3 theme preset for Teksilo.
5//!
6//! A static Material 3 theme built on the canonical baseline scheme
7//! (seed `#6750A4`, the M3 reference purple). The preset replaces the
8//! IntUI color, shape, and typography tokens with M3 values, exposes the
9//! full M3 role palette via [`Material3Palette`], and installs M3 widget
10//! chrome (pill-shaped 40 dp buttons, the M3 switch, 12 dp cards) through
11//! the Tier-3 style slots.
12//!
13//! ```ignore
14//! use teksilo_theme_material3 as m3;
15//!
16//! TeksiloAppBuilder::new()
17//!     .theme(m3::light())
18//!     .initial_window(WindowConfig::new().title("M3 demo"))
19//!     .run();
20//! ```
21//!
22//! ## What's mapped, and what isn't
23//!
24//! M3's primary/secondary/tertiary + tonal-surface model doesn't line up
25//! one-to-one with Teksilo's role taxonomy, so the color mapping projects
26//! each `ColorTokens` field onto its nearest M3 equivalent and exposes the
27//! rest (containers, secondary, tertiary, the surface-container ladder)
28//! through [`Material3Palette`]. Typography keeps Teksilo's bundled
29//! **Inter** family (which is metrically Roboto-compatible; the text
30//! engine would silently fall back to it for an unregistered "Roboto"
31//! anyway) and adopts M3's type-scale sizes / weights / letter-spacing.
32//!
33//! ### Known limitations
34//!
35//! - **State layers are pre-composited.** M3 hover/pressed are 8 % / 12 %
36//!   on-color overlays; Teksilo recipes take opaque colors, so those
37//!   layers are baked into static colors.
38//! - **Tonal / Destructive button fills** are frozen per appearance
39//!   (`RecipeColor::Static`) because there is no secondaryContainer /
40//!   error *surface* role to track reactively.
41
42mod color;
43mod palette;
44mod shape;
45mod styles;
46mod typography;
47
48pub use palette::Material3Palette;
49
50use std::rc::Rc;
51
52use teksilo_core::presets::intui;
53use teksilo_core::styles::{Theme, ThemeAppearance};
54use teksilo_tokens::{InputTokens, TargetDensity};
55
56/// Material 3's input tokens for one density ladder.
57///
58/// Identical to [`InputTokens::for_density`] except at
59/// [`TargetDensity::Touch`], where `target_size` is raised from the generic
60/// 44 dp to Material 3's own **48 dp** touch-target minimum (M3 *Accessibility
61/// — Touch targets*). 44 dp is Apple HIG / WCAG 2.2 SC 2.5.5 (level AAA); the
62/// 24 dp AA floor in `min_target_conformance` is untouched.
63///
64/// At `Compact` — the default — this is the generic ladder unchanged, so a
65/// Material 3 theme is byte-for-byte today's behaviour.
66///
67/// A density switch keeps this ladder: the preset's private `reproject` is
68/// registered as the theme's
69/// [`DensityProjection`](teksilo_core::styles::DensityProjection), so
70/// [`Theme::with_density`] and `WidgetTree::set_input_density` call back into
71/// this function instead of falling through to the generic
72/// [`InputTokens::for_density`]. An app therefore does not re-apply these
73/// tokens by hand; `a_density_switch_keeps_material3s_own_48_dp_target` pins it.
74pub fn input_tokens(density: TargetDensity) -> InputTokens {
75    let mut tokens = InputTokens::for_density(density);
76    if density == TargetDensity::Touch {
77        tokens.target_size = 48.0;
78    }
79    tokens
80}
81
82/// Material 3 light theme (baseline scheme, seed `#6750A4`).
83pub fn light() -> Theme {
84    let mut theme = intui::light().with_id("material3.light");
85    apply_material3_overrides(&mut theme, ThemeAppearance::Light);
86    theme
87}
88
89/// Re-derive a Material 3 theme for another density.
90///
91/// Registered as the theme's [`DensityProjection`](teksilo_core::styles::DensityProjection), so
92/// `WidgetTree::set_input_density` (and `Theme::with_density`) rebuild the
93/// Tier-3 slots this preset installs instead of carrying their Compact
94/// dimensions across. Colours, id, the [`Material3Palette`] extension and any
95/// slot the app installed itself ride across untouched.
96fn reproject(base: &Theme, density: TargetDensity) -> Theme {
97    let mut theme = base.clone();
98    theme.input = input_tokens(density);
99    install_style_slots(&mut theme);
100    theme
101}
102
103/// Material 3 dark theme (baseline scheme, seed `#6750A4`).
104pub fn dark() -> Theme {
105    let mut theme = intui::dark().with_id("material3.dark");
106    apply_material3_overrides(&mut theme, ThemeAppearance::Dark);
107    theme
108}
109
110fn apply_material3_overrides(theme: &mut Theme, appearance: ThemeAppearance) {
111    let light = appearance == ThemeAppearance::Light;
112
113    theme.colors = if light {
114        color::m3_light_colors()
115    } else {
116        color::m3_dark_colors()
117    };
118    theme.shape = if light {
119        shape::m3_light_shape()
120    } else {
121        shape::m3_dark_shape()
122    };
123    theme.typography = typography::m3_typography();
124    // M3's touch targets are 48 dp, not the generic ladder's 44 — a no-op at
125    // the default Compact density. See `input_tokens`.
126    theme.input = input_tokens(theme.input.density);
127    theme.extensions.insert(if light {
128        Material3Palette::light()
129    } else {
130        Material3Palette::dark()
131    });
132
133    install_style_slots(theme);
134    theme
135        .extensions
136        .insert(teksilo_core::styles::DensityProjection(reproject));
137}
138
139/// Tier-3 widget chrome. These read M3-mapped roles, so a single install
140/// serves both appearances; the dimensions come from `theme.input`, so
141/// [`reproject`] can re-run this alone for a new density.
142fn install_style_slots(theme: &mut Theme) {
143    theme.style_slots.button = Some(Rc::new(styles::button::m3_button_style(&theme.input)));
144    theme.style_slots.toggle = Some(Rc::new(styles::toggle::M3ToggleStyle));
145    theme.style_slots.card = Some(Rc::new(styles::card::M3CardStyle));
146}
147
148#[cfg(feature = "bundled-fonts")]
149mod bundled_fonts {
150    use teksilo_text::{FontFaceId, FontRegistrar, TextFontService};
151
152    /// The bundled Roboto Flex variable font (Apache-2.0, ~1.7 MB). Only
153    /// compiled under the `bundled-fonts` feature.
154    const ROBOTO: &[u8] = include_bytes!("../fonts/Roboto.ttf");
155
156    /// Registers the bundled Roboto under the family name "Roboto" for the
157    /// weights M3 uses (400 / 500) and as the default font. The two
158    /// `register_font_as` calls force the family name so the M3
159    /// typography (which uses "Roboto" under this feature) resolves
160    /// regardless of the file's internal name-table family.
161    pub struct RobotoRegistrar;
162
163    impl FontRegistrar for RobotoRegistrar {
164        fn register_on_service(&self, service: &mut TextFontService) -> Option<FontFaceId> {
165            let regular = service.register_font_as(ROBOTO, "Roboto", 400, false);
166            service.register_font_as(ROBOTO, "Roboto", 500, false);
167            service.set_default_font(regular, 14.0);
168            Some(regular)
169        }
170    }
171}
172
173/// A [`FontRegistrar`](teksilo_text::FontRegistrar) that embeds Roboto and
174/// registers it under the "Roboto" family. Pass it to the app builder so
175/// the M3 typography (which uses "Roboto" under this feature) resolves
176/// instead of falling back to the bundled default:
177///
178/// ```ignore
179/// TeksiloAppBuilder::new()
180///     .theme(material3::light())
181///     .register_fonts(material3::font_registrar())
182///     .run();
183/// ```
184///
185/// Available only under the `bundled-fonts` Cargo feature.
186#[cfg(feature = "bundled-fonts")]
187pub fn font_registrar() -> impl teksilo_text::FontRegistrar {
188    bundled_fonts::RobotoRegistrar
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use std::collections::BTreeSet;
195    use teksilo_core::styles::ComponentStyleSlots;
196    use teksilo_tokens::Color;
197
198    #[test]
199    fn light_reports_light_appearance() {
200        assert_eq!(light().appearance, ThemeAppearance::Light);
201        assert!(!light().is_dark());
202    }
203
204    #[test]
205    fn dark_reports_dark_appearance() {
206        assert_eq!(dark().appearance, ThemeAppearance::Dark);
207        assert!(dark().is_dark());
208    }
209
210    #[test]
211    fn ids_are_namespaced() {
212        assert_eq!(light().id.as_str(), "material3.light");
213        assert_eq!(dark().id.as_str(), "material3.dark");
214    }
215
216    #[test]
217    fn light_and_dark_have_distinct_surfaces() {
218        assert_ne!(light().colors.surface_main, dark().colors.surface_main);
219    }
220
221    #[test]
222    fn on_error_and_containers_use_m3_values() {
223        // The new core cross-language roles carry M3 values now.
224        let l = light().colors;
225        assert_eq!(l.text_on_error, Color::from_hex("#FFFFFF"));
226        assert_eq!(l.surface_error_container, Color::from_hex("#F9DEDC"));
227        assert_eq!(l.surface_container, Color::from_hex("#F3EDF7"));
228        let d = dark().colors;
229        assert_eq!(d.text_on_error, Color::from_hex("#601410"));
230    }
231
232    #[test]
233    fn destructive_button_label_is_on_error() {
234        use teksilo_core::styles::ButtonVariant;
235        use teksilo_tokens::TextRole;
236        let style = styles::button::m3_button_style(&InputTokens::default());
237        assert_eq!(
238            style.label_roles.get(&ButtonVariant::Destructive),
239            Some(&TextRole::OnError),
240        );
241    }
242
243    /// The fill the Filled button paints in `state` under `colors`, as the
244    /// button resolves it on every paint.
245    fn filled_fill(
246        state: teksilo_core::styles::WidgetState,
247        colors: &teksilo_tokens::ColorTokens,
248    ) -> Color {
249        use teksilo_core::styles::ButtonVariant;
250        let style = styles::button::m3_button_style(&InputTokens::default());
251        style.recipes[&ButtonVariant::Filled]
252            .fill
253            .resolve(state)
254            .resolve_flat(colors)
255            .expect("a flat fill")
256    }
257
258    #[test]
259    fn filled_button_hover_and_pressed_are_the_m3_state_layers() {
260        use teksilo_core::styles::WidgetState;
261        for theme in [light(), dark()] {
262            let c = &theme.colors;
263            for (state, alpha) in [
264                (WidgetState::Idle, 0.0),
265                (WidgetState::Hovered, 0.08),
266                (WidgetState::Pressed, 0.12),
267            ] {
268                let want = c.accent.mix(c.text_on_accent, alpha);
269                let got = filled_fill(state, c);
270                for (g, w) in got.to_array().iter().zip(want.to_array()) {
271                    assert!((g - w).abs() < 1e-6, "{state:?}: {got:?} != {want:?}");
272                }
273            }
274        }
275    }
276
277    #[test]
278    fn filled_button_label_reads_7_to_1_in_every_state_under_high_contrast() {
279        use teksilo_core::styles::{PaintState, WidgetState};
280        use teksilo_tokens::contrast::composite_contrast;
281        for (name, theme) in [("light", light()), ("dark", dark())] {
282            for window_active in [true, false] {
283                let c = theme.paint_colors(PaintState {
284                    window_active,
285                    high_contrast: true,
286                });
287                for state in [
288                    WidgetState::Idle,
289                    WidgetState::Hovered,
290                    WidgetState::Pressed,
291                    WidgetState::Focused,
292                ] {
293                    let r = composite_contrast(c.text_on_accent, filled_fill(state, &c));
294                    assert!(
295                        r >= 7.0,
296                        "{name}, window active {window_active}, {state:?}: {r:.2}"
297                    );
298                }
299            }
300        }
301    }
302
303    #[test]
304    fn accent_is_m3_primary() {
305        assert_eq!(light().colors.accent, Color::from_hex("#6750A4"));
306        assert_eq!(dark().colors.accent, Color::from_hex("#D0BCFF"));
307    }
308
309    #[test]
310    fn body_is_m3_body_medium_size() {
311        // M3 Body Medium is 14 sp (IntUI's is 13).
312        assert!((light().typography.body.size - 14.0).abs() < 0.01);
313    }
314
315    #[test]
316    fn typography_tracks_letters() {
317        // M3 specifies non-zero letter-spacing (IntUI never tracks).
318        assert!(light().typography.body.letter_spacing > 0.0);
319    }
320
321    #[test]
322    fn palette_extension_present() {
323        assert!(light().extension::<Material3Palette>().is_some());
324        assert!(dark().extension::<Material3Palette>().is_some());
325        // The extension carries roles ColorTokens can't hold (e.g. tertiary).
326        let p = dark().extension::<Material3Palette>().copied().unwrap();
327        assert_eq!(p.tertiary, Color::from_hex("#EFB8C8"));
328    }
329
330    /// A Material 3 component this preset has not transcribed: the widget's
331    /// default recipe paints it, with the M3-mapped colour roles.
332    const NOT_TRANSCRIBED: &str =
333        "the M3 component is not transcribed; the recipe paints with the M3-mapped colour roles";
334    /// A slot Material 3 specifies no component for.
335    const NO_M3_COMPONENT: &str =
336        "M3 specifies no such component; the recipe paints with the M3-mapped colour roles";
337
338    /// The slots Material 3 deliberately leaves to the widget's default
339    /// `Recipe*Style`, each with the reason it is inherited rather than filled.
340    const MATERIAL3_UNFILLED: &[(&str, &str)] = &[
341        ("split_button", NOT_TRANSCRIBED),
342        ("splitter", NO_M3_COMPONENT),
343        ("icon_button", NOT_TRANSCRIBED),
344        ("checkbox", NOT_TRANSCRIBED),
345        ("radio", NOT_TRANSCRIBED),
346        ("radio_tile", NO_M3_COMPONENT),
347        ("slider", NOT_TRANSCRIBED),
348        ("text_input", NOT_TRANSCRIBED),
349        ("combo_box", NOT_TRANSCRIBED),
350        ("menu_item", NOT_TRANSCRIBED),
351        ("panel", NO_M3_COMPONENT),
352        ("chart", NO_M3_COMPONENT),
353        ("popover", NOT_TRANSCRIBED),
354        ("tooltip", NOT_TRANSCRIBED),
355        ("scroll_bar", NO_M3_COMPONENT),
356        ("standard_item", NOT_TRANSCRIBED),
357        ("tab", NOT_TRANSCRIBED),
358        ("dialog", NOT_TRANSCRIBED),
359        ("snackbar", NOT_TRANSCRIBED),
360        ("toast", NO_M3_COMPONENT),
361        ("banner", NO_M3_COMPONENT),
362        ("badge", NOT_TRANSCRIBED),
363        ("progress_bar", NOT_TRANSCRIBED),
364        ("link", NO_M3_COMPONENT),
365        ("segmented_control", NOT_TRANSCRIBED),
366        ("avatar", NO_M3_COMPONENT),
367        ("calendar", NOT_TRANSCRIBED),
368        ("color_picker", NO_M3_COMPONENT),
369        ("spin_box", NO_M3_COMPONENT),
370        (
371            "date_edit",
372            "the recipe is a passthrough around the TextInput, so it follows whatever the text_input slot paints",
373        ),
374        ("search_field", NOT_TRANSCRIBED),
375        ("rich_text_editor", NO_M3_COMPONENT),
376        ("table", NO_M3_COMPONENT),
377        (
378            "list_container",
379            "the recipe is only the drag-insertion line, drawn in the M3-mapped accent role",
380        ),
381        ("drop_zone", NO_M3_COMPONENT),
382        ("drop_target", NO_M3_COMPONENT),
383        ("grid_view", NO_M3_COMPONENT),
384        (
385            "web_view",
386            "the page paints itself; the recipe only tints the overlay shown over it, from theme roles",
387        ),
388        (
389            "text_selection",
390            "its geometry is teksilo_core::text_touch's, shared with hit testing, and its colours follow the M3-mapped accent role",
391        ),
392    ];
393
394    /// Whether the installed slots and [`MATERIAL3_UNFILLED`] are exactly
395    /// [`ComponentStyleSlots::NAMES`], with no slot in both: a slot added to the
396    /// framework must be either filled by this preset or listed with a reason.
397    #[test]
398    fn installed_and_unfilled_slots_partition_the_roster() {
399        let unfilled: BTreeSet<&str> = MATERIAL3_UNFILLED.iter().map(|(name, _)| *name).collect();
400        assert_eq!(
401            unfilled.len(),
402            MATERIAL3_UNFILLED.len(),
403            "a slot is listed twice"
404        );
405        for (name, reason) in MATERIAL3_UNFILLED {
406            assert!(
407                !reason.trim().is_empty(),
408                "{name} is listed without a reason"
409            );
410        }
411        let names: BTreeSet<&str> = ComponentStyleSlots::NAMES.iter().copied().collect();
412        for t in [light(), dark(), light().with_density(TargetDensity::Touch)] {
413            let installed: BTreeSet<&str> = t.style_slots.installed().into_iter().collect();
414            let both: Vec<_> = installed.intersection(&unfilled).collect();
415            assert!(
416                both.is_empty(),
417                "installed yet listed as unfilled: {both:?}"
418            );
419            let covered: BTreeSet<&str> = installed.union(&unfilled).copied().collect();
420            let missing: Vec<_> = names.difference(&covered).collect();
421            let unknown: Vec<_> = covered.difference(&names).collect();
422            assert!(
423                missing.is_empty() && unknown.is_empty(),
424                "neither installed nor listed: {missing:?}; not a slot: {unknown:?}"
425            );
426        }
427    }
428
429    #[test]
430    fn dark_elevation_is_stronger_than_light() {
431        // M3 softens shadows, but dark still needs more alpha than light.
432        assert!(dark().shape.shadow_lg.color.a() > light().shape.shadow_lg.color.a());
433    }
434
435    #[test]
436    fn motion_inherits_desktop_tooltip_delays() {
437        // Material 3 overrides colour/shape/type/slots only — motion stays
438        // on `MotionTokens::default()` so tooltip feel tracks the shared
439        // desktop norms (500 / 700 / 100 ms).
440        use std::time::Duration;
441        for t in [light(), dark()] {
442            assert_eq!(t.motion.tooltip_delay, Duration::from_millis(500));
443            assert_eq!(t.motion.tooltip_delay_heavy, Duration::from_millis(700));
444            assert_eq!(t.motion.tooltip_reshow_delay, Duration::from_millis(100));
445        }
446    }
447    /// Material 3's own touch target is **48 dp**, not the generic ladder's 44,
448    /// and a density switch must carry that through to the installed button
449    /// slot rather than falling back to the generic numbers.
450    #[test]
451    fn a_density_switch_keeps_material3s_own_48_dp_target() {
452        let base = light();
453        let before = base
454            .style_slots
455            .button
456            .clone()
457            .expect("button slot installed");
458
459        let touch = base.with_density(TargetDensity::Touch);
460        let after = touch
461            .style_slots
462            .button
463            .clone()
464            .expect("button slot survives");
465
466        assert_eq!(touch.input.density, TargetDensity::Touch);
467        assert_eq!(
468            touch.input.target_size, 48.0,
469            "the projection must use Material 3's ladder, not `InputTokens::for_density`"
470        );
471        assert!(
472            !Rc::ptr_eq(&before, &after),
473            "the projection must rebuild the preset's own slots, not carry them across"
474        );
475
476        let compact =
477            styles::button::m3_button_style(&InputTokens::for_density(TargetDensity::Compact));
478        let touched = styles::button::m3_button_style(&input_tokens(TargetDensity::Touch));
479        let variant = teksilo_core::styles::ButtonVariant::Filled;
480        assert_eq!(
481            compact.recipes[&variant].min_size.height, 40.0,
482            "M3's own 40 dp button at Compact"
483        );
484        assert_eq!(
485            touched.recipes[&variant].min_size.height, 48.0,
486            "M3's 48 dp touch target, not the generic 44"
487        );
488
489        assert_eq!(touch.id, base.id);
490        assert!(touch.extension::<Material3Palette>().is_some());
491    }
492}