Skip to main content

teksilo_theme_fluent/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Fluent (Windows 11 / WinUI 3) theme preset for Teksilo.
5//!
6//! A full Fluent theme: the WinUI theme-resource colour dictionaries, the
7//! two-radius geometry, the WinUI type ramp, Fluent's control durations and
8//! easing, and Tier-3 chrome for the widgets whose WinUI counterpart is
9//! structurally its own thing.
10//!
11//! ```ignore
12//! use teksilo_theme_fluent as fluent;
13//!
14//! TeksiloAppBuilder::new()
15//!     .theme(fluent::light())
16//!     .initial_window(WindowConfig::new().title("Fluent demo"))
17//!     .run();
18//! ```
19//!
20//! ## What makes it read as Fluent
21//!
22//! - **The elevation edge.** A raised control carries a heavier stroke on
23//!   one edge — the bottom in light (a cast shadow), the top in dark (a
24//!   catch-light) — and loses it when pressed. WinUI gets this from a
25//!   gradient border brush anchored to a fixed 3 dp band; see
26//!   [`palette::FluentEdgeSide`].
27//! - **A high-contrast focus ring, never the accent.** Two tones: a 2 dp
28//!   near-black (light) or white (dark) outer ring with a 1 dp opposite
29//!   inner ring between it and the control. It reads on any background,
30//!   which is why Fluent does not tint it.
31//! - **The accent focus underline.** A focused field's bottom edge grows to
32//!   2 dp and turns accent while its fill brightens.
33//! - **Neutral selection plus an accent pill.** A selected list row gets a
34//!   grey wash and a 3 × 16 dp accent bar on its leading edge.
35//! - **An asymmetric accent ramp.** The light theme fills with a *darkened*
36//!   accent and white labels, the dark theme with a *lightened* one and
37//!   black labels — which is how both clear contrast from one seed colour.
38//!
39//! ## Two radii, 32 dp, no tracking
40//!
41//! Fluent's geometry is `ControlCornerRadius` 4 dp for anything in the page
42//! and `OverlayCornerRadius` 8 dp for anything that floats (tooltips
43//! excepted — they float but round at 4). Interactive controls share a
44//! 32 dp height. The type ramp specifies **zero** letter-spacing at every
45//! rung: Fluent's size-appropriate texture comes from Segoe UI Variable's
46//! optical-size axis, not from tracking — the opposite of Material 3.
47//!
48//! ## Accent colour
49//!
50//! `AccentFillColor*` is not a literal in WinUI's dictionary; it binds to
51//! the ramp Windows generates from the user's chosen accent. [`light`] and
52//! [`dark`] resolve it against the Windows out-of-box `#0078D4`;
53//! [`light_with_accent`] / [`dark_with_accent`] rebuild the whole theme
54//! around a different seed, so an app that reads the live Windows accent —
55//! or wants a brand colour — stays Fluent everywhere else.
56//!
57//! ## Known limitations
58//!
59//! - **Mica and Acrylic are their solid fallbacks.** Both are compositor
60//!   materials: Mica samples the desktop wallpaper, Acrylic blurs what is
61//!   behind the window. Neither is expressible in a flat-fill renderer, and
62//!   Teksilo's wgpu surface does not expose compositor-side blur. Every
63//!   surface therefore uses the opaque fallback WinUI itself falls back to
64//!   when the material is unavailable — which is the documented behaviour
65//!   on a machine with transparency effects off, not an approximation.
66//! - **Segoe UI Variable cannot be bundled.** It is proprietary, so the
67//!   default build keeps the metric-neutral bundled Inter and the
68//!   `system-fonts` feature names the Windows faces for the text engine to
69//!   resolve. See [`typography`].
70//! - **The accent ramp is reconstructed, not published.** Microsoft
71//!   documents that Windows generates `SystemAccentColorLight1..3` /
72//!   `Dark1..3` from the base accent but not *how*.
73//!   [`palette::FluentAccentRamp::windows_default`] carries the measured
74//!   values for `#0078D4`; `from_base` approximates the curve for any other
75//!   seed.
76//! - **Widget chrome is chosen at build time.** Switching between Fluent
77//!   and another preset at runtime re-tints instantly but keeps the shapes
78//!   the tree was built with — a property of the styling system, not of
79//!   this preset.
80
81mod color;
82pub mod motion;
83pub mod palette;
84pub mod shape;
85pub mod styles;
86pub mod typography;
87
88pub use palette::{FluentAccentRamp, FluentEdgeSide, FluentPalette};
89
90use std::rc::Rc;
91
92use teksilo_core::presets::intui;
93use teksilo_core::styles::{Theme, ThemeAppearance};
94use teksilo_tokens::{Color, InputTokens, TargetDensity};
95
96/// Fluent light theme, on the Windows default accent `#0078D4`.
97pub fn light() -> Theme {
98    build(ThemeAppearance::Light, FluentPalette::light())
99}
100
101/// Fluent dark theme, on the Windows default accent `#0078D4`.
102pub fn dark() -> Theme {
103    build(ThemeAppearance::Dark, FluentPalette::dark())
104}
105
106/// Fluent light theme rebuilt around `accent` — the substitution Windows
107/// performs when the user picks an accent colour.
108///
109/// ```ignore
110/// let theme = teksilo_theme_fluent::light_with_accent(Color::from_hex("#B146C2"));
111/// ```
112pub fn light_with_accent(accent: Color) -> Theme {
113    build(
114        ThemeAppearance::Light,
115        FluentPalette::light_with_accent(ramp_for(accent)),
116    )
117}
118
119/// Fluent dark theme rebuilt around `accent`.
120pub fn dark_with_accent(accent: Color) -> Theme {
121    build(
122        ThemeAppearance::Dark,
123        FluentPalette::dark_with_accent(ramp_for(accent)),
124    )
125}
126
127/// The measured Windows ramp when the seed *is* the default accent,
128/// the approximation otherwise.
129fn ramp_for(accent: Color) -> FluentAccentRamp {
130    let default = FluentAccentRamp::windows_default();
131    if accent == default.base {
132        default
133    } else {
134        FluentAccentRamp::from_base(accent)
135    }
136}
137
138fn build(appearance: ThemeAppearance, palette: FluentPalette) -> Theme {
139    let light = appearance == ThemeAppearance::Light;
140    // Starting from the IntUI baseline keeps every token Fluent has no
141    // opinion about (the chart palette, the find-match highlight) at a
142    // sensible value instead of at zero.
143    let mut theme = if light {
144        intui::light().with_id("fluent.light")
145    } else {
146        intui::dark().with_id("fluent.dark")
147    };
148
149    theme.colors = if light {
150        color::fluent_light_colors(&palette)
151    } else {
152        color::fluent_dark_colors(&palette)
153    };
154    theme.shape = if light {
155        shape::fluent_light_shape()
156    } else {
157        shape::fluent_dark_shape()
158    };
159    theme.typography = typography::fluent_typography();
160    theme.motion = motion::fluent_motion();
161    theme.extensions.insert(palette);
162
163    install_styles(&mut theme);
164    theme
165        .extensions
166        .insert(teksilo_core::styles::DensityProjection(reproject));
167    theme
168}
169
170/// Re-derive a Fluent theme for another density.
171///
172/// Registered as the theme's [`DensityProjection`](teksilo_core::styles::DensityProjection), so
173/// `WidgetTree::set_input_density` (and `Theme::with_density`) rebuild the
174/// Tier-3 slots this preset installs instead of carrying their Compact
175/// dimensions across — a Fluent button is 32 dp at Compact and reaches the
176/// density's target size above it. Colours, id, the [`FluentPalette`]
177/// extension and any slot the app installed itself ride across untouched.
178///
179/// Fluent has no published touch ladder of its own (WinUI states 40 px / 7.5 mm
180/// as a *recommendation*, not a metric that scales its controls), so this uses
181/// the generic [`InputTokens::for_density`] ladder — unlike Material 3, which
182/// overrides it with its own 48 dp.
183fn reproject(base: &Theme, density: TargetDensity) -> Theme {
184    let mut theme = base.clone();
185    theme.input = InputTokens::for_density(density);
186    install_styles(&mut theme);
187    theme
188}
189
190/// Install the Fluent Tier-3 chrome. Every style resolves its colours from
191/// the live theme at paint time, so one install serves both appearances —
192/// and a custom-accent theme too.
193fn install_styles(theme: &mut Theme) {
194    // Every metric below comes from `theme.input`, so `reproject` can re-run
195    // this alone to move the whole preset to another density.
196    let tokens = theme.input;
197    let slots = &mut theme.style_slots;
198
199    // Structurally Fluent — see `styles`.
200    slots.button = Some(Rc::new(styles::button::FluentButtonStyle));
201    slots.toggle = Some(Rc::new(styles::toggle::FluentToggleStyle));
202    slots.checkbox = Some(Rc::new(styles::checkbox::FluentCheckboxStyle));
203    slots.radio = Some(Rc::new(styles::radio::FluentRadioStyle));
204    slots.text_input = Some(Rc::new(styles::text_input::FluentTextInputStyle));
205    slots.slider = Some(Rc::new(styles::slider::FluentSliderStyle));
206    slots.menu_item = Some(Rc::new(styles::menu_item::FluentMenuItemStyle::for_tokens(
207        &tokens,
208    )));
209    slots.standard_item = Some(Rc::new(styles::standard_item::FluentStandardItemStyle));
210
211    // Fluent metrics over the shipped composition.
212    slots.card = Some(Rc::new(styles::metrics::FluentCardStyle));
213    slots.panel = Some(Rc::new(styles::metrics::fluent_panel_style_for(&tokens)));
214    slots.popover = Some(Rc::new(styles::metrics::fluent_popover_style_for(&tokens)));
215    slots.tooltip = Some(Rc::new(styles::metrics::fluent_tooltip_style_for(&tokens)));
216    slots.dialog = Some(Rc::new(styles::metrics::fluent_dialog_style_for(&tokens)));
217    slots.snackbar = Some(Rc::new(styles::metrics::fluent_snackbar_style_for(&tokens)));
218    slots.toast = Some(Rc::new(styles::metrics::fluent_toast_style_for(&tokens)));
219    slots.banner = Some(Rc::new(styles::metrics::fluent_banner_style_for(&tokens)));
220    slots.combo_box = Some(Rc::new(styles::metrics::fluent_combo_box_style_for(
221        &tokens,
222    )));
223    slots.icon_button = Some(Rc::new(styles::metrics::fluent_icon_button_style_for(
224        &tokens,
225    )));
226    slots.link = Some(Rc::new(styles::metrics::fluent_link_style_for(&tokens)));
227    slots.segmented_control = Some(Rc::new(
228        styles::metrics::fluent_segmented_control_style_for(&tokens),
229    ));
230    slots.badge = Some(Rc::new(styles::metrics::fluent_badge_style_for(&tokens)));
231    slots.progress_bar = Some(Rc::new(styles::metrics::fluent_progress_bar_style_for(
232        &tokens,
233    )));
234    slots.scroll_bar = Some(Rc::new(styles::metrics::fluent_scroll_bar_style_for(
235        &tokens,
236    )));
237    slots.tab = Some(Rc::new(styles::metrics::fluent_tab_style_for(&tokens)));
238    slots.table = Some(Rc::new(styles::metrics::fluent_table_style_for(&tokens)));
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use crate::palette::argb;
245    use std::collections::BTreeSet;
246    use teksilo_core::styles::ComponentStyleSlots;
247
248    #[test]
249    fn light_reports_light_appearance() {
250        assert_eq!(light().appearance, ThemeAppearance::Light);
251        assert!(!light().is_dark());
252    }
253
254    #[test]
255    fn dark_reports_dark_appearance() {
256        assert_eq!(dark().appearance, ThemeAppearance::Dark);
257        assert!(dark().is_dark());
258    }
259
260    #[test]
261    fn ids_are_namespaced() {
262        assert_eq!(light().id.as_str(), "fluent.light");
263        assert_eq!(dark().id.as_str(), "fluent.dark");
264        // The widget-catalog persists and restores themes by this id, so
265        // a rename here silently breaks restore-on-launch.
266        assert_eq!(light_with_accent(Color::WHITE).id.as_str(), "fluent.light");
267        assert_eq!(dark_with_accent(Color::WHITE).id.as_str(), "fluent.dark");
268    }
269
270    #[test]
271    fn light_and_dark_have_distinct_surfaces() {
272        assert_ne!(light().colors.surface_main, dark().colors.surface_main);
273    }
274
275    #[test]
276    fn surfaces_are_the_winui_solid_backgrounds() {
277        assert_eq!(light().colors.surface_main, argb("#F3F3F3"));
278        assert_eq!(dark().colors.surface_main, argb("#FF202020"));
279    }
280
281    #[test]
282    fn accent_is_the_asymmetric_ramp() {
283        // Light fills with a darkened accent, dark with a lightened one —
284        // so white-on-light and black-on-dark both clear contrast.
285        assert_eq!(light().colors.accent, argb("#0067C0"));
286        assert_eq!(dark().colors.accent, argb("#4CC2FF"));
287        assert_eq!(light().colors.text_on_accent, Color::WHITE);
288        assert_eq!(dark().colors.text_on_accent, Color::BLACK);
289    }
290
291    #[test]
292    fn focus_indicator_is_high_contrast_not_accent() {
293        for t in [light(), dark()] {
294            assert_ne!(t.colors.focus_ring, t.colors.accent);
295        }
296        assert_eq!(light().colors.focus_ring, argb("#E4000000"));
297        assert_eq!(dark().colors.focus_ring, Color::WHITE);
298    }
299
300    #[test]
301    fn geometry_is_the_two_fluent_radii() {
302        for t in [light(), dark()] {
303            assert_eq!(t.shape.radius_control, 4.0);
304            assert_eq!(t.shape.radius_popup, 8.0);
305        }
306    }
307
308    #[test]
309    fn body_is_the_winui_body_ramp_with_no_tracking() {
310        let t = light();
311        assert!((t.typography.body.size - 14.0).abs() < 0.01);
312        assert_eq!(t.typography.body.letter_spacing, 0.0);
313        assert_eq!(t.typography.small.letter_spacing, 0.0);
314    }
315
316    #[test]
317    fn motion_uses_the_fluent_control_durations() {
318        use std::time::Duration;
319        for t in [light(), dark()] {
320            assert_eq!(t.motion.duration_fast, Duration::from_millis(167));
321            assert_eq!(t.motion.duration_normal, Duration::from_millis(250));
322        }
323    }
324
325    #[test]
326    fn palette_extension_present_and_appearance_matched() {
327        let l = light().extension::<FluentPalette>().copied().unwrap();
328        let d = dark().extension::<FluentPalette>().copied().unwrap();
329        assert_eq!(l.elevation_edge, FluentEdgeSide::Bottom);
330        assert_eq!(d.elevation_edge, FluentEdgeSide::Top);
331        // The extension carries tokens `ColorTokens` has no slot for.
332        assert_eq!(l.control_stroke_secondary, argb("#29000000"));
333        assert_eq!(d.control_fill_input_active, argb("#B31E1E1E"));
334    }
335
336    /// The slots Fluent deliberately leaves to the widget's default
337    /// `Recipe*Style`, each with the reason it is inherited rather than filled.
338    const FLUENT_UNFILLED: &[(&str, &str)] = &[
339        (
340            "split_button",
341            "WinUI SplitButton is not transcribed; the recipe frame paints from the theme surface and border roles",
342        ),
343        (
344            "splitter",
345            "WinUI ships no splitter; the recipe's thin resting divider reads the theme border role",
346        ),
347        (
348            "radio_tile",
349            "WinUI ships no selectable card; the recipe surface reads the preset's surface and accent roles",
350        ),
351        (
352            "chart",
353            "WinUI ships no chart; the teksilo-charts default reads the series colours and the theme border role",
354        ),
355        (
356            "color_picker",
357            "WinUI ColorPicker is not transcribed; the recipe panel reads the theme roles",
358        ),
359        (
360            "spin_box",
361            "WinUI NumberBox spin buttons are not transcribed; the recipe frames the widget's field and step buttons in theme roles",
362        ),
363        (
364            "date_edit",
365            "the recipe is a passthrough around the TextInput, which the text_input slot already styles",
366        ),
367        (
368            "rich_text_editor",
369            "the recipe frames the viewport in theme border and surface roles; the text is document content",
370        ),
371        (
372            "list_container",
373            "the recipe is only the drag-insertion line, drawn in the accent role this preset maps",
374        ),
375        (
376            "drop_zone",
377            "WinUI ships no drop-zone control; the recipe tints its region from the theme roles",
378        ),
379        (
380            "drop_target",
381            "WinUI ships no drop-target control; the recipe border reads the theme roles and its hints are cards, which the card slot styles",
382        ),
383        (
384            "grid_view",
385            "the recipe's focus ring, marquee and insertion bar use the focused and accent roles this preset maps",
386        ),
387        (
388            "web_view",
389            "the page paints itself; the recipe only tints the overlay shown over it, from theme roles",
390        ),
391        (
392            "text_selection",
393            "its geometry is teksilo_core::text_touch's, shared with hit testing, and its colours follow the accent role",
394        ),
395        (
396            "calendar",
397            "WinUI CalendarView is not transcribed; the recipe's day cells read the accent and selection roles this preset maps",
398        ),
399        (
400            "search_field",
401            "its field is a TextInput, which resolves the text_input slot, and its suggestion popup resolves the popover slot, both filled",
402        ),
403        (
404            "avatar",
405            "WinUI PersonPicture is not transcribed; the recipe's initials disc and focus ring read the theme roles",
406        ),
407    ];
408
409    /// Whether the installed slots and [`FLUENT_UNFILLED`] are exactly
410    /// [`ComponentStyleSlots::NAMES`], with no slot in both: a slot added to the
411    /// framework must be either filled by this preset or listed with a reason.
412    #[test]
413    fn installed_and_unfilled_slots_partition_the_roster() {
414        let unfilled: BTreeSet<&str> = FLUENT_UNFILLED.iter().map(|(name, _)| *name).collect();
415        assert_eq!(
416            unfilled.len(),
417            FLUENT_UNFILLED.len(),
418            "a slot is listed twice"
419        );
420        for (name, reason) in FLUENT_UNFILLED {
421            assert!(
422                !reason.trim().is_empty(),
423                "{name} is listed without a reason"
424            );
425        }
426        let names: BTreeSet<&str> = ComponentStyleSlots::NAMES.iter().copied().collect();
427        for t in [light(), dark(), light().with_density(TargetDensity::Touch)] {
428            let installed: BTreeSet<&str> = t.style_slots.installed().into_iter().collect();
429            let both: Vec<_> = installed.intersection(&unfilled).collect();
430            assert!(
431                both.is_empty(),
432                "installed yet listed as unfilled: {both:?}"
433            );
434            let covered: BTreeSet<&str> = installed.union(&unfilled).copied().collect();
435            let missing: Vec<_> = names.difference(&covered).collect();
436            let unknown: Vec<_> = covered.difference(&names).collect();
437            assert!(
438                missing.is_empty() && unknown.is_empty(),
439                "neither installed nor listed: {missing:?}; not a slot: {unknown:?}"
440            );
441        }
442    }
443
444    #[test]
445    fn custom_accent_rebuilds_the_whole_accent_family() {
446        let seed = Color::from_hex("#B146C2");
447        let t = light_with_accent(seed);
448        let base = light();
449        assert_ne!(t.colors.accent, base.colors.accent);
450        assert_ne!(t.colors.text_link, base.colors.text_link);
451        assert_ne!(
452            t.colors.selection_bg_active,
453            base.colors.selection_bg_active
454        );
455        // Neutral tokens are untouched — only the accent family moves.
456        assert_eq!(t.colors.surface_main, base.colors.surface_main);
457        assert_eq!(t.colors.text_primary, base.colors.text_primary);
458        assert_eq!(t.colors.focus_ring, base.colors.focus_ring);
459        // …and the extension follows, so widget chrome sees it too.
460        let p = t.extension::<FluentPalette>().copied().unwrap();
461        assert_eq!(p.accent_ramp.base, seed);
462        assert_eq!(p.system_fill_attention, seed);
463    }
464
465    #[test]
466    fn passing_the_default_accent_reproduces_the_measured_ramp() {
467        let default = FluentAccentRamp::windows_default();
468        assert_eq!(
469            light_with_accent(default.base).colors.accent,
470            light().colors.accent
471        );
472        assert_eq!(
473            dark_with_accent(default.base).colors.accent,
474            dark().colors.accent
475        );
476    }
477
478    #[test]
479    fn the_theme_survives_the_window_inactive_projection() {
480        // The paint walker swaps this palette in on focus loss; a preset
481        // that left `accent` unmapped would produce a no-op here.
482        for t in [light(), dark()] {
483            let inactive = t.for_inactive_window();
484            assert_ne!(inactive.colors.accent, t.colors.accent);
485            assert_eq!(inactive.colors.surface_main, t.colors.surface_main);
486        }
487    }
488    /// A density switch must re-derive the Tier-3 slots this preset installs.
489    ///
490    /// The slots are `Some(..)`, so `Theme::with_density`'s token-only path
491    /// would carry their Compact dimensions across and leave a Fluent list row
492    /// at 40 dp under Touch. The registered `DensityProjection` is what stops
493    /// that; this asserts it is registered, reached, and carries real numbers.
494    #[test]
495    fn a_density_switch_re_derives_the_installed_slots() {
496        let base = light();
497        let before = base
498            .style_slots
499            .standard_item
500            .clone()
501            .expect("slot installed");
502
503        let touch = base.with_density(TargetDensity::Touch);
504        let after = touch
505            .style_slots
506            .standard_item
507            .clone()
508            .expect("slot survives");
509
510        assert_eq!(touch.input.density, TargetDensity::Touch);
511        assert!(
512            !Rc::ptr_eq(&before, &after),
513            "the projection must rebuild the preset's own slots, not carry them across"
514        );
515
516        // …and the numbers they are rebuilt with are the density's.
517        let compact = styles::standard_item::fluent_standard_item_recipe_for(
518            &InputTokens::for_density(TargetDensity::Compact),
519        );
520        let touched = styles::standard_item::fluent_standard_item_recipe_for(
521            &InputTokens::for_density(TargetDensity::Touch),
522        );
523        assert_eq!(
524            compact.min_height_single_line, 40.0,
525            "WinUI's own 40 dp row"
526        );
527        assert_eq!(touched.min_height_single_line, 44.0, "the Touch target");
528
529        // Everything the preset does not own rides across untouched.
530        assert_eq!(touch.id, base.id);
531        assert_eq!(touch.colors, base.colors);
532        assert!(touch.extension::<FluentPalette>().is_some());
533    }
534
535    /// The menu slot is rebuilt for the density too, so the metrics
536    /// `MenuItem`, `MenuSeparator` and `MenuList` read follow it, and
537    /// switching back to Compact gives the Compact metrics again.
538    #[test]
539    fn a_density_switch_reprojects_the_menu_metrics() {
540        use teksilo_core::styles::MenuItemStyle;
541
542        let base = light();
543        let metrics = |t: &Theme| {
544            t.style_slots
545                .menu_item
546                .as_ref()
547                .expect("slot installed")
548                .metrics()
549        };
550        for density in [
551            TargetDensity::Compact,
552            TargetDensity::Comfortable,
553            TargetDensity::Touch,
554        ] {
555            let t = base.with_density(density);
556            assert_eq!(
557                metrics(&t),
558                styles::menu_item::FluentMenuItemStyle::for_tokens(&InputTokens::for_density(
559                    density
560                ))
561                .metrics(),
562                "{density:?}",
563            );
564        }
565        let compact = metrics(&base);
566        let touch = metrics(&base.with_density(TargetDensity::Touch));
567        assert_eq!(compact.item_height, 37.0, "WinUI's own 37 dp row");
568        assert_eq!(touch.item_height, 44.0, "the Touch target");
569        assert!(touch.separator_height > compact.separator_height);
570        assert!(touch.trailing_column_width > compact.trailing_column_width);
571        let back = base
572            .with_density(TargetDensity::Touch)
573            .with_density(TargetDensity::Compact);
574        assert_eq!(metrics(&back), compact);
575    }
576}