Skip to main content

repose_core/
locals.rs

1//! # Theming and locals
2//!
3//! Repose uses thread‑local “composition locals” for global UI parameters:
4//!
5//! - `Theme` - colors for surfaces, text, controls, etc.
6//! - `Density` - dp→px device scale factor (platform sets this).
7//! - `UiScale` - app-controlled UI scale multiplier (defaults to 1.0).
8//! - `TextScale` - user text scaling (defaults to 1.0).
9//! - `TextDirection` - LTR or RTL (defaults to LTR).
10//!
11//! Locals can be overridden for a subtree with `with_*`. If no local is set,
12//! getters fall back to global defaults (which an app can set each frame).
13
14use std::ops::Deref;
15
16use std::any::{Any, TypeId};
17use std::cell::RefCell;
18use std::collections::HashMap;
19use std::sync::OnceLock;
20
21use parking_lot::RwLock;
22
23use std::rc::Rc;
24
25use crate::Color;
26use crate::animation::{AnimationSpec, Easing};
27use crate::indication::IndicationNodeFactory;
28use web_time::Duration;
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
31pub enum TextDirection {
32    #[default]
33    Ltr,
34    Rtl,
35}
36
37thread_local! {
38    static LOCALS_STACK: RefCell<Vec<HashMap<TypeId, Box<dyn Any>>>> = RefCell::new(Vec::new());
39}
40
41#[derive(Clone, Copy, Debug, Default)]
42struct Defaults {
43    theme: Theme,
44    text_direction: TextDirection,
45    ui_scale: UiScale,
46    text_scale: TextScale,
47    density: Density,
48    window_insets: WindowInsets,
49    window_size_class: WindowSizeClass,
50    /// Logical window container size in dp (defaults match a phone portrait).
51    container_width: f32,
52    container_height: f32,
53}
54
55static DEFAULTS: OnceLock<RwLock<Defaults>> = OnceLock::new();
56
57fn defaults() -> &'static RwLock<Defaults> {
58    DEFAULTS.get_or_init(|| {
59        RwLock::new(Defaults {
60            container_width: 360.0,
61            container_height: 800.0,
62            ..Default::default()
63        })
64    })
65}
66
67/// Set the global default theme used when no local Theme is active.
68pub fn set_theme_default(t: Theme) {
69    defaults().write().theme = t;
70}
71
72/// Set the global default text direction used when no local TextDirection is active.
73pub fn set_text_direction_default(d: TextDirection) {
74    defaults().write().text_direction = d;
75}
76
77/// Set the global default UI scale used when no local UiScale is active.
78pub fn set_ui_scale_default(s: UiScale) {
79    defaults().write().ui_scale = UiScale(s.0.max(0.0));
80}
81
82/// Set the global default text scale used when no local TextScale is active.
83pub fn set_text_scale_default(s: TextScale) {
84    defaults().write().text_scale = TextScale(s.0.max(0.0));
85}
86
87/// Set the global default device density (dp→px) used when no local Density is active.
88/// Platform runners should call this whenever the window scale factor changes.
89pub fn set_density_default(d: Density) {
90    defaults().write().density = Density {
91        scale: d.scale.max(0.0),
92    };
93}
94
95/// density‑independent pixels (dp)
96#[derive(Clone, Copy, Debug, PartialEq)]
97pub struct Dp(pub f32);
98
99impl Dp {
100    /// Converts this dp value into physical pixels using current Density * UiScale.
101    pub fn to_px(self) -> f32 {
102        self.0 * density().scale * ui_scale().0
103    }
104}
105
106/// Convenience: convert a raw dp scalar into px using current Density * UiScale.
107pub fn dp_to_px(dp: f32) -> f32 {
108    Dp(dp).to_px()
109}
110
111/// Convenience: convert a raw px scalar into dp using current Density * UiScale.
112pub fn px_to_dp(px: f32) -> f32 {
113    let scale = density().scale * ui_scale().0;
114    if scale <= 0.0 { 0.0 } else { px / scale }
115}
116
117fn with_locals_frame<R>(f: impl FnOnce() -> R) -> R {
118    struct Guard;
119    impl Drop for Guard {
120        fn drop(&mut self) {
121            let _ = LOCALS_STACK.try_with(|st| {
122                st.borrow_mut().pop();
123            });
124        }
125    }
126    LOCALS_STACK.with(|st| st.borrow_mut().push(HashMap::new()));
127    let _guard = Guard;
128    f()
129}
130
131fn set_local_boxed(t: TypeId, v: Box<dyn Any>) {
132    LOCALS_STACK.with(|st| {
133        if let Some(top) = st.borrow_mut().last_mut() {
134            top.insert(t, v);
135        } else {
136            // no frame: create a temporary one
137            let mut m = HashMap::new();
138            m.insert(t, v);
139            st.borrow_mut().push(m);
140        }
141    });
142}
143
144fn get_local<T: 'static + Copy>() -> Option<T> {
145    LOCALS_STACK.with(|st| {
146        for frame in st.borrow().iter().rev() {
147            if let Some(v) = frame.get(&TypeId::of::<T>())
148                && let Some(t) = v.downcast_ref::<T>()
149            {
150                return Some(*t);
151            }
152        }
153        None
154    })
155}
156
157#[derive(Clone, Copy, Debug)]
158#[must_use]
159pub struct ColorScheme {
160    pub primary: Color,
161    pub on_primary: Color,
162    pub primary_container: Color,
163    pub on_primary_container: Color,
164
165    pub secondary: Color,
166    pub on_secondary: Color,
167    pub secondary_container: Color,
168    pub on_secondary_container: Color,
169
170    pub tertiary: Color,
171    pub on_tertiary: Color,
172    pub tertiary_container: Color,
173    pub on_tertiary_container: Color,
174
175    pub error: Color,
176    pub on_error: Color,
177    pub error_container: Color,
178    pub on_error_container: Color,
179
180    pub background: Color,
181    pub on_background: Color,
182    pub surface: Color,
183    pub on_surface: Color,
184    pub surface_variant: Color,
185    pub on_surface_variant: Color,
186    pub surface_container_lowest: Color,
187    pub surface_container_low: Color,
188    pub surface_container: Color,
189    pub surface_container_high: Color,
190    pub surface_container_highest: Color,
191    pub surface_bright: Color,
192    pub surface_dim: Color,
193    pub surface_tint: Color,
194
195    pub inverse_surface: Color,
196    pub inverse_on_surface: Color,
197    pub inverse_primary: Color,
198
199    pub outline: Color,
200    pub outline_variant: Color,
201
202    pub scrim: Color,
203    pub shadow: Color,
204    pub focus: Color,
205}
206
207impl ColorScheme {
208    pub fn dark() -> Self {
209        Self {
210            primary: Color::from_hex("#69FDBE"),
211            on_primary: Color::from_hex("#003020"),
212            primary_container: Color::from_hex("#004D40"),
213            on_primary_container: Color::from_hex("#6FF7F6"),
214
215            secondary: Color::from_hex("#B3C9A7"),
216            on_secondary: Color::from_hex("#1C3519"),
217            secondary_container: Color::from_hex("#334D2E"),
218            on_secondary_container: Color::from_hex("#CCE8B3"),
219
220            tertiary: Color::from_hex("#FFC9C1"),
221            on_tertiary: Color::from_hex("#3F1619"),
222            tertiary_container: Color::from_hex("#5D1F22"),
223            on_tertiary_container: Color::from_hex("#FFDBD8"),
224
225            error: Color::from_hex("#F2B8B5"),
226            on_error: Color::from_hex("#601410"),
227            error_container: Color::from_hex("#8C1D18"),
228            on_error_container: Color::from_hex("#F9DEDC"),
229
230            background: Color::from_hex("#1A1C1E"),
231            on_background: Color::from_hex("#E6E1E5"),
232            surface: Color::from_hex("#1A1C1E"),
233            on_surface: Color::from_hex("#E6E1E5"),
234            surface_variant: Color::from_hex("#44474E"),
235            on_surface_variant: Color::from_hex("#C4C6CE"),
236            surface_container_lowest: Color::from_hex("#0A0A0C"),
237            surface_container_low: Color::from_hex("#141115"),
238            surface_container: Color::from_hex("#19131A"),
239            surface_container_high: Color::from_hex("#1F1B22"),
240            surface_container_highest: Color::from_hex("#2A2930"),
241            surface_bright: Color::from_hex("#26292F"),
242            surface_dim: Color::from_hex("#1A1C1E"),
243            surface_tint: Color::from_hex("#69FDBE"),
244
245            inverse_surface: Color::from_hex("#E6E1E5"),
246            inverse_on_surface: Color::from_hex("#2A2930"),
247            inverse_primary: Color::from_hex("#005048"),
248
249            outline: Color::from_hex("#74777F"),
250            outline_variant: Color::from_hex("#44474E"),
251
252            scrim: Color::from_hex("#000000"),
253            shadow: Color::from_hex("#000000"),
254            focus: Color::from_hex("#006A6A"),
255        }
256    }
257
258    pub fn light() -> Self {
259        Self {
260            primary: Color::from_hex("#006A6A"),
261            on_primary: Color::WHITE,
262            primary_container: Color::from_hex("#9EF0EC"),
263            on_primary_container: Color::from_hex("#002020"),
264
265            secondary: Color::from_hex("#586146"),
266            on_secondary: Color::WHITE,
267            secondary_container: Color::from_hex("#D8E3B8"),
268            on_secondary_container: Color::from_hex("#161C0A"),
269
270            tertiary: Color::from_hex("#744639"),
271            on_tertiary: Color::WHITE,
272            tertiary_container: Color::from_hex("#FFD9CD"),
273            on_tertiary_container: Color::from_hex("#2C0E07"),
274
275            error: Color::from_hex("#BA1A1A"),
276            on_error: Color::WHITE,
277            error_container: Color::from_hex("#FFDAD6"),
278            on_error_container: Color::from_hex("#410002"),
279
280            background: Color::from_hex("#FEF7FF"),
281            on_background: Color::from_hex("#1A1C1E"),
282            surface: Color::from_hex("#FEF7FF"),
283            on_surface: Color::from_hex("#1A1C1E"),
284            surface_variant: Color::from_hex("#E1E3DE"),
285            on_surface_variant: Color::from_hex("#44474E"),
286            surface_container_lowest: Color::WHITE,
287            surface_container_low: Color::from_hex("#F4F5F0"),
288            surface_container: Color::from_hex("#EEF0E9"),
289            surface_container_high: Color::from_hex("#E9EAE4"),
290            surface_container_highest: Color::from_hex("#E3E5DF"),
291            surface_bright: Color::from_hex("#FEF7FF"),
292            surface_dim: Color::from_hex("#DEDAD0"),
293            surface_tint: Color::from_hex("#006A6A"),
294
295            inverse_surface: Color::from_hex("#2F3033"),
296            inverse_on_surface: Color::from_hex("#F1F0F4"),
297            inverse_primary: Color::from_hex("#69FDBE"),
298
299            outline: Color::from_hex("#74777F"),
300            outline_variant: Color::from_hex("#C4C6CE"),
301
302            scrim: Color::from_hex("#000000"),
303            shadow: Color::from_hex("#000000"),
304            focus: Color::from_hex("#1D4ED8"),
305        }
306    }
307}
308
309impl Default for ColorScheme {
310    fn default() -> Self {
311        Self::dark()
312    }
313}
314
315#[derive(Clone, Copy, Debug)]
316#[must_use]
317pub struct Typography {
318    pub display_large: f32,
319    pub display_medium: f32,
320    pub display_small: f32,
321    pub headline_large: f32,
322    pub headline_medium: f32,
323    pub headline_small: f32,
324    pub title_large: f32,
325    pub title_medium: f32,
326    pub title_small: f32,
327    pub body_large: f32,
328    pub body_medium: f32,
329    pub body_small: f32,
330    pub label_large: f32,
331    pub label_medium: f32,
332    pub label_small: f32,
333}
334
335impl Default for Typography {
336    fn default() -> Self {
337        Self {
338            display_large: 57.0,
339            display_medium: 45.0,
340            display_small: 36.0,
341            headline_large: 32.0,
342            headline_medium: 28.0,
343            headline_small: 24.0,
344            title_large: 22.0,
345            title_medium: 16.0,
346            title_small: 14.0,
347            body_large: 16.0,
348            body_medium: 14.0,
349            body_small: 12.0,
350            label_large: 14.0,
351            label_medium: 12.0,
352            label_small: 11.0,
353        }
354    }
355}
356
357#[derive(Clone, Copy, Debug)]
358#[must_use]
359pub struct Shapes {
360    pub extra_small: f32,
361    pub small: f32,
362    pub medium: f32,
363    pub large: f32,
364    pub extra_large: f32,
365}
366
367impl Default for Shapes {
368    fn default() -> Self {
369        Self {
370            extra_small: 4.0,
371            small: 8.0,
372            medium: 12.0,
373            large: 16.0,
374            extra_large: 28.0,
375        }
376    }
377}
378
379#[derive(Clone, Copy, Debug)]
380#[must_use]
381pub struct Spacing {
382    pub xs: f32,
383    pub sm: f32,
384    pub md: f32,
385    pub lg: f32,
386    pub xl: f32,
387    pub xxl: f32,
388}
389
390impl Default for Spacing {
391    fn default() -> Self {
392        Self {
393            xs: 4.0,
394            sm: 8.0,
395            md: 12.0,
396            lg: 16.0,
397            xl: 24.0,
398            xxl: 32.0,
399        }
400    }
401}
402
403#[derive(Clone, Copy, Debug)]
404#[must_use]
405pub struct Elevation {
406    pub level0: f32,
407    pub level1: f32,
408    pub level2: f32,
409    pub level3: f32,
410    pub level4: f32,
411    pub level5: f32,
412}
413
414impl Default for Elevation {
415    fn default() -> Self {
416        Self {
417            level0: 0.0,
418            level1: 1.0,
419            level2: 3.0,
420            level3: 6.0,
421            level4: 8.0,
422            level5: 12.0,
423        }
424    }
425}
426
427/// Centralized animation specs for M3 motion design.
428#[derive(Clone, Copy, Debug)]
429#[must_use]
430pub struct MotionScheme {
431    /// Shape / size / bounds transitions (e.g., indicator position, elevation).
432    /// M3 standard: 200 ms FastOutSlowIn.
433    pub shape: AnimationSpec,
434    /// Color state transitions (e.g., label, tab text, selection).
435    /// M3 standard: 150 ms FastOutSlowIn.
436    pub color: AnimationSpec,
437    /// Quick color changes (e.g., checkbox fill, switch track, radio ring).
438    /// M3 standard: 100 ms FastOutSlowIn.
439    pub color_fast: AnimationSpec,
440    /// Overlay / popup enter‑exit (menus, dialogs, tooltips).
441    /// M3 standard: 120 ms FastOutSlowIn.
442    pub overlay: AnimationSpec,
443    /// Spring‑based positional animation (sheets, drawers, swipe‑to‑dismiss).
444    /// M3 standard: gentle spring (ζ = 0.5, k = 200).
445    pub spring: AnimationSpec,
446    /// Expanding containers (search bar, docked search suggestions).
447    /// M3 standard: 250 ms FastOutSlowIn.
448    pub expand: AnimationSpec,
449    /// Large layout transitions (bottom sheet height, scaffold reflow).
450    /// M3 standard: 300 ms EaseOut.
451    pub layout: AnimationSpec,
452}
453
454impl Default for MotionScheme {
455    fn default() -> Self {
456        Self {
457            shape: AnimationSpec::tween(Duration::from_millis(200), Easing::FastOutSlowIn),
458            color: AnimationSpec::tween(Duration::from_millis(150), Easing::FastOutSlowIn),
459            color_fast: AnimationSpec::tween(Duration::from_millis(100), Easing::FastOutSlowIn),
460            overlay: AnimationSpec::tween(Duration::from_millis(120), Easing::FastOutSlowIn),
461            spring: AnimationSpec::spring_gentle(),
462            expand: AnimationSpec::tween(Duration::from_millis(250), Easing::FastOutSlowIn),
463            layout: AnimationSpec::tween(Duration::from_millis(300), Easing::EaseOut),
464        }
465    }
466}
467
468#[derive(Clone, Copy, Debug)]
469#[must_use]
470pub struct Theme {
471    pub colors: ColorScheme,
472    pub typography: Typography,
473    pub shapes: Shapes,
474    pub spacing: Spacing,
475    pub elevation: Elevation,
476    pub motion: MotionScheme,
477
478    pub focus: Color,
479    pub scrollbar_track: Color,
480    pub scrollbar_thumb: Color,
481    pub button_bg: Color,
482    pub button_bg_hover: Color,
483    pub button_bg_pressed: Color,
484}
485
486impl Deref for Theme {
487    type Target = ColorScheme;
488    fn deref(&self) -> &Self::Target {
489        &self.colors
490    }
491}
492
493impl Default for Theme {
494    fn default() -> Self {
495        let colors = ColorScheme::default();
496        Self {
497            colors,
498            typography: Typography::default(),
499            shapes: Shapes::default(),
500            spacing: Spacing::default(),
501            elevation: Elevation::default(),
502            motion: MotionScheme::default(),
503            focus: colors.focus,
504            scrollbar_track: Color::TRANSPARENT,
505            scrollbar_thumb: colors.outline.with_alpha(179),
506            button_bg: colors.primary,
507            button_bg_hover: colors.primary_container,
508            button_bg_pressed: colors.on_primary_container,
509        }
510    }
511}
512
513impl Theme {
514    pub fn with_colors(mut self, colors: ColorScheme) -> Self {
515        self.colors = colors;
516        self
517    }
518}
519
520/// Platform/device scale (dp→px multiplier). Platform runner should set this.
521#[derive(Clone, Copy, Debug)]
522pub struct Density {
523    pub scale: f32,
524}
525impl Default for Density {
526    fn default() -> Self {
527        Self { scale: 1.0 }
528    }
529}
530
531/// Additional UI scale multiplier (app-controlled).
532#[derive(Clone, Copy, Debug)]
533pub struct UiScale(pub f32);
534impl Default for UiScale {
535    fn default() -> Self {
536        Self(1.0)
537    }
538}
539
540#[derive(Clone, Copy, Debug)]
541pub struct TextScale(pub f32);
542impl Default for TextScale {
543    fn default() -> Self {
544        Self(1.0)
545    }
546}
547
548pub fn with_theme<R>(theme: Theme, f: impl FnOnce() -> R) -> R {
549    with_locals_frame(|| {
550        set_local_boxed(TypeId::of::<Theme>(), Box::new(theme));
551        f()
552    })
553}
554
555pub fn with_density<R>(density: Density, f: impl FnOnce() -> R) -> R {
556    with_locals_frame(|| {
557        set_local_boxed(TypeId::of::<Density>(), Box::new(density));
558        f()
559    })
560}
561
562pub fn with_ui_scale<R>(s: UiScale, f: impl FnOnce() -> R) -> R {
563    with_locals_frame(|| {
564        set_local_boxed(TypeId::of::<UiScale>(), Box::new(s));
565        f()
566    })
567}
568
569pub fn with_text_scale<R>(ts: TextScale, f: impl FnOnce() -> R) -> R {
570    with_locals_frame(|| {
571        set_local_boxed(TypeId::of::<TextScale>(), Box::new(ts));
572        f()
573    })
574}
575
576pub fn with_text_direction<R>(dir: TextDirection, f: impl FnOnce() -> R) -> R {
577    with_locals_frame(|| {
578        set_local_boxed(TypeId::of::<TextDirection>(), Box::new(dir));
579        f()
580    })
581}
582
583pub fn with_window_insets<R>(insets: WindowInsets, f: impl FnOnce() -> R) -> R {
584    with_locals_frame(|| {
585        set_local_boxed(TypeId::of::<WindowInsets>(), Box::new(insets));
586        f()
587    })
588}
589
590#[derive(Clone, Copy, Debug)]
591pub struct ContentColor(pub Color);
592
593pub fn with_content_color<R>(color: Color, f: impl FnOnce() -> R) -> R {
594    with_locals_frame(|| {
595        set_local_boxed(TypeId::of::<ContentColor>(), Box::new(ContentColor(color)));
596        f()
597    })
598}
599
600pub fn content_color() -> Color {
601    get_local::<ContentColor>()
602        .map(|c| c.0)
603        .unwrap_or_else(|| theme().on_surface)
604}
605
606/// Composition-local default indication (ripple/highlight) factory.
607/// Components like `Button` read this to get the default press feedback.
608/// Mirrors Compose's `LocalIndication`.
609#[derive(Clone, Debug)]
610pub struct LocalIndication(pub Option<Rc<dyn IndicationNodeFactory>>);
611
612impl Default for LocalIndication {
613    fn default() -> Self {
614        Self(None)
615    }
616}
617
618pub fn with_local_indication<R>(
619    indication: Option<Rc<dyn IndicationNodeFactory>>,
620    f: impl FnOnce() -> R,
621) -> R {
622    with_locals_frame(|| {
623        set_local_boxed(
624            std::any::TypeId::of::<LocalIndication>(),
625            Box::new(LocalIndication(indication)),
626        );
627        f()
628    })
629}
630
631pub fn local_indication() -> Option<Rc<dyn IndicationNodeFactory>> {
632    // Manual stack walk (get_local requires Copy, which LocalIndication is not).
633    let result = LOCALS_STACK.with(|st| {
634        for frame in st.borrow().iter().rev() {
635            if let Some(v) = frame.get(&TypeId::of::<LocalIndication>())
636                && let Some(li) = v.downcast_ref::<LocalIndication>()
637            {
638                return li.0.clone();
639            }
640        }
641        None::<Rc<dyn IndicationNodeFactory>>
642    });
643    result
644}
645
646/// System window insets (status bar, navigation bar, IME keyboard, etc.)
647#[derive(Clone, Copy, Debug, Default, PartialEq)]
648pub struct WindowInsets {
649    pub top: f32,
650    pub bottom: f32,
651    pub left: f32,
652    pub right: f32,
653    /// Soft keyboard (IME) inset from bottom of screen. Set by platform runner
654    /// when the keyboard opens/closes. Used by `imePadding()` modifier.
655    pub ime_bottom: f32,
656}
657
658/// Set the global default window insets (platform should call this when insets change).
659pub fn set_window_insets_default(insets: WindowInsets) {
660    defaults().write().window_insets = insets;
661    set_local_boxed(TypeId::of::<WindowInsets>(), Box::new(insets));
662}
663
664/// Update just the IME bottom inset (keyboard height in px). Platform runners
665/// call this when the soft keyboard opens/closes.
666pub fn set_ime_inset(height_px: f32) {
667    let mut insets = defaults().write().window_insets;
668    insets.ime_bottom = height_px;
669    // Also immediately set the thread-local so it's visible to the current frame
670    set_local_boxed(TypeId::of::<WindowInsets>(), Box::new(insets));
671}
672
673/// Query current window insets.
674pub fn window_insets() -> WindowInsets {
675    get_local::<WindowInsets>().unwrap_or_else(|| defaults().read().window_insets)
676}
677
678/// Set the logical window container size (in dp). The `LayoutEngine` calls
679/// this on every layout from the physical viewport + density.
680pub fn set_window_container_size(width_dp: f32, height_dp: f32) {
681    let mut d = defaults().write();
682    d.container_width = width_dp;
683    d.container_height = height_dp;
684}
685
686/// Set just the logical window container width (in dp). Prefer
687/// [`set_window_container_size`]; kept for hosts that update one axis at a time.
688pub fn set_window_container_width(w_dp: f32) {
689    defaults().write().container_width = w_dp;
690}
691
692/// Set just the logical window container height (in dp). Prefer
693/// [`set_window_container_size`]; kept for hosts that update one axis at a time.
694pub fn set_window_container_height(h_dp: f32) {
695    defaults().write().container_height = h_dp;
696}
697
698/// The logical window container width in dp (used by Material dropdowns).
699pub fn get_window_container_width() -> f32 {
700    defaults().read().container_width
701}
702
703/// The logical window container height in dp (used by Material search bars).
704pub fn get_window_container_height() -> f32 {
705    defaults().read().container_height
706}
707
708/// Coarse width category for a window, computed from its current size.
709///
710/// Thresholds (in dp) match the Material 3 adaptive spec:
711///
712/// - [`WidthClass::Compact`]  : width < 600 dp
713/// - [`WidthClass::Medium`]   : 600 dp <= width < 840 dp
714/// - [`WidthClass::Expanded`] : width >= 840 dp
715#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
716pub enum WidthClass {
717    #[default]
718    Compact,
719    Medium,
720    Expanded,
721}
722
723/// Coarse height category for a window, computed from its current size.
724///
725/// Thresholds (in dp) match the Material 3 adaptive spec:
726///
727/// - [`HeightClass::Compact`]  : height < 480 dp
728/// - [`HeightClass::Medium`]   : 480 dp <= height < 900 dp
729/// - [`HeightClass::Expanded`] : height >= 900 dp
730#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
731pub enum HeightClass {
732    #[default]
733    Compact,
734    Medium,
735    Expanded,
736}
737
738/// Snapshot of the current window's size category.
739///
740/// The `LayoutEngine` updates the `WindowSizeClass` default local every time
741/// the window is resized, so UI can read it via [`window_size_class()`] during
742/// composition.
743#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
744pub struct WindowSizeClass {
745    pub width: WidthClass,
746    pub height: HeightClass,
747}
748
749impl WindowSizeClass {
750    /// `true` when there is enough horizontal space for multi-pane layouts.
751    pub fn is_expanded_width(&self) -> bool {
752        matches!(self.width, WidthClass::Expanded)
753    }
754    /// `true` when there is enough horizontal space for a two-pane layout
755    /// (list + detail). Per M3 this is Medium or wider.
756    pub fn is_at_least_medium_width(&self) -> bool {
757        matches!(self.width, WidthClass::Medium | WidthClass::Expanded)
758    }
759}
760
761/// Compute a [`WindowSizeClass`] from a window size in physical pixels and
762/// the current dp→px density scale (`Density.scale * UiScale.0`).
763pub fn calculate_window_size_class(
764    width_px: u32,
765    height_px: u32,
766    density_scale: f32,
767) -> WindowSizeClass {
768    let density = density_scale.max(0.0001);
769    let width_dp = (width_px as f32) / density;
770    let height_dp = (height_px as f32) / density;
771
772    let width = if width_dp < 600.0 {
773        WidthClass::Compact
774    } else if width_dp < 840.0 {
775        WidthClass::Medium
776    } else {
777        WidthClass::Expanded
778    };
779    let height = if height_dp < 480.0 {
780        HeightClass::Compact
781    } else if height_dp < 900.0 {
782        HeightClass::Medium
783    } else {
784        HeightClass::Expanded
785    };
786
787    WindowSizeClass { width, height }
788}
789
790/// Set the global default window size class used when no local is active.
791/// Called by the `LayoutEngine` on resize.
792pub fn set_window_size_class_default(class: WindowSizeClass) {
793    defaults().write().window_size_class = class;
794}
795
796/// Override the window size class for a subtree of the composition.
797pub fn with_window_size_class<R>(class: WindowSizeClass, f: impl FnOnce() -> R) -> R {
798    with_locals_frame(|| {
799        set_local_boxed(TypeId::of::<WindowSizeClass>(), Box::new(class));
800        f()
801    })
802}
803
804/// Query current window size class. Returns a default-initialized
805/// `WindowSizeClass` (Compact/Compact) if nothing has been set yet.
806pub fn window_size_class() -> WindowSizeClass {
807    get_local::<WindowSizeClass>().unwrap_or_else(|| defaults().read().window_size_class)
808}
809
810macro_rules! def_local_getter {
811    ($fn_name:ident, $ty:ty, $default_field:ident) => {
812        pub fn $fn_name() -> $ty {
813            get_local::<$ty>().unwrap_or_else(|| defaults().read().$default_field)
814        }
815    };
816}
817
818def_local_getter!(theme, Theme, theme);
819def_local_getter!(density, Density, density);
820def_local_getter!(ui_scale, UiScale, ui_scale);
821def_local_getter!(text_scale, TextScale, text_scale);
822def_local_getter!(text_direction, TextDirection, text_direction);
823
824#[cfg(test)]
825mod tests {
826    use super::*;
827
828    #[test]
829    fn width_class_thresholds_match_m3() {
830        // Density 1.0 (1 dp = 1 px) for clarity.
831        assert_eq!(
832            calculate_window_size_class(100, 100, 1.0).width,
833            WidthClass::Compact
834        );
835        assert_eq!(
836            calculate_window_size_class(599, 100, 1.0).width,
837            WidthClass::Compact
838        );
839        assert_eq!(
840            calculate_window_size_class(600, 100, 1.0).width,
841            WidthClass::Medium
842        );
843        assert_eq!(
844            calculate_window_size_class(839, 100, 1.0).width,
845            WidthClass::Medium
846        );
847        assert_eq!(
848            calculate_window_size_class(840, 100, 1.0).width,
849            WidthClass::Expanded
850        );
851        assert_eq!(
852            calculate_window_size_class(2000, 100, 1.0).width,
853            WidthClass::Expanded
854        );
855    }
856
857    #[test]
858    fn height_class_thresholds_match_m3() {
859        assert_eq!(
860            calculate_window_size_class(100, 100, 1.0).height,
861            HeightClass::Compact
862        );
863        assert_eq!(
864            calculate_window_size_class(100, 479, 1.0).height,
865            HeightClass::Compact
866        );
867        assert_eq!(
868            calculate_window_size_class(100, 480, 1.0).height,
869            HeightClass::Medium
870        );
871        assert_eq!(
872            calculate_window_size_class(100, 899, 1.0).height,
873            HeightClass::Medium
874        );
875        assert_eq!(
876            calculate_window_size_class(100, 900, 1.0).height,
877            HeightClass::Expanded
878        );
879    }
880
881    #[test]
882    fn density_scales_thresholds() {
883        // 2.0x density: 600 dp = 1200 px.
884        let c = calculate_window_size_class(1199, 100, 2.0);
885        assert_eq!(c.width, WidthClass::Compact);
886        let c = calculate_window_size_class(1200, 100, 2.0);
887        assert_eq!(c.width, WidthClass::Medium);
888    }
889
890    #[test]
891    fn is_at_least_medium_width() {
892        let c = WindowSizeClass {
893            width: WidthClass::Compact,
894            height: HeightClass::Compact,
895        };
896        assert!(!c.is_at_least_medium_width());
897        let c = WindowSizeClass {
898            width: WidthClass::Medium,
899            height: HeightClass::Compact,
900        };
901        assert!(c.is_at_least_medium_width());
902        let c = WindowSizeClass {
903            width: WidthClass::Expanded,
904            height: HeightClass::Compact,
905        };
906        assert!(c.is_at_least_medium_width());
907    }
908}