Skip to main content

strata_dom/hooks/
media.rs

1//! Media query and system preference hooks (responsive queries, color scheme, reduced motion, contrast).
2
3use crate::reactive::Signal;
4use std::cell::RefCell;
5
6thread_local! {
7    static VIEWPORT_DIMENSIONS: RefCell<Signal<(f32, f32)>> = RefCell::new(Signal::new((1920.0, 1080.0)));
8    static COLOR_SCHEME: RefCell<Signal<ColorScheme>> = RefCell::new(Signal::new(ColorScheme::Dark));
9    static REDUCED_MOTION: RefCell<Signal<bool>> = RefCell::new(Signal::new(false));
10    static CONTRAST_PREFERENCE: RefCell<Signal<ContrastPreference>> = RefCell::new(Signal::new(ContrastPreference::Normal));
11    static ACTIVE_MEDIA_QUERIES: RefCell<Vec<(Vec<MediaCondition>, Signal<bool>)>> = const { RefCell::new(Vec::new()) };
12}
13
14/// Preferred system color scheme.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16pub enum ColorScheme {
17    Light,
18    #[default]
19    Dark,
20}
21
22/// Accessibility contrast preference.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum ContrastPreference {
25    #[default]
26    Normal,
27    High,
28    Low,
29}
30
31/// Helper function to re-evaluate all active media queries when environment changes.
32fn reevaluate_active_queries() {
33    let (width, height) = VIEWPORT_DIMENSIONS.with(|d| d.borrow().get());
34    let cs = COLOR_SCHEME.with(|cs| cs.borrow().get());
35    let rm = REDUCED_MOTION.with(|rm| rm.borrow().get());
36
37    ACTIVE_MEDIA_QUERIES.with(|queries| {
38        for (conditions, sig) in queries.borrow().iter() {
39            let matched = conditions.iter().all(|c| c.evaluate(width, height, cs, rm));
40            sig.set(matched);
41        }
42    });
43}
44
45/// Sets the current viewport dimensions (width, height) in device pixels and updates media queries.
46pub fn set_viewport_dimensions(width: f32, height: f32) {
47    VIEWPORT_DIMENSIONS.with(|dims| {
48        dims.borrow().set((width, height));
49    });
50    reevaluate_active_queries();
51}
52
53/// Updates the active system color scheme and re-evaluates queries.
54pub fn set_system_color_scheme(scheme: ColorScheme) {
55    COLOR_SCHEME.with(|cs| {
56        cs.borrow().set(scheme);
57    });
58    reevaluate_active_queries();
59}
60
61/// Updates the active reduced motion system preference and re-evaluates queries.
62pub fn set_system_reduced_motion(reduced: bool) {
63    REDUCED_MOTION.with(|rm| {
64        rm.borrow().set(reduced);
65    });
66    reevaluate_active_queries();
67}
68
69/// Updates the active contrast system preference.
70pub fn set_system_contrast(contrast: ContrastPreference) {
71    CONTRAST_PREFERENCE.with(|cp| {
72        cp.borrow().set(contrast);
73    });
74}
75
76/// Headless hook returning the active system color scheme (`ColorScheme::Light` or `ColorScheme::Dark`).
77pub fn use_color_scheme() -> Signal<ColorScheme> {
78    COLOR_SCHEME.with(|cs| cs.borrow().clone())
79}
80
81/// Headless hook tracking whether user has requested reduced motion (`prefers-reduced-motion: reduce`).
82pub fn use_reduced_motion() -> Signal<bool> {
83    REDUCED_MOTION.with(|rm| rm.borrow().clone())
84}
85
86/// Headless hook tracking the system contrast preference (`prefers-contrast`).
87pub fn use_contrast() -> Signal<ContrastPreference> {
88    CONTRAST_PREFERENCE.with(|cp| cp.borrow().clone())
89}
90
91/// Parsed CSS media query condition.
92#[derive(Debug, Clone, PartialEq)]
93enum MediaCondition {
94    MinWidth(f32),
95    MaxWidth(f32),
96    MinHeight(f32),
97    MaxHeight(f32),
98    OrientationPortrait,
99    OrientationLandscape,
100    PrefersColorScheme(ColorScheme),
101    PrefersReducedMotion(bool),
102}
103
104impl MediaCondition {
105    fn evaluate(
106        &self,
107        width: f32,
108        height: f32,
109        color_scheme: ColorScheme,
110        reduced_motion: bool,
111    ) -> bool {
112        match self {
113            Self::MinWidth(min) => width >= *min,
114            Self::MaxWidth(max) => width <= *max,
115            Self::MinHeight(min) => height >= *min,
116            Self::MaxHeight(max) => height <= *max,
117            Self::OrientationPortrait => height >= width,
118            Self::OrientationLandscape => width > height,
119            Self::PrefersColorScheme(cs) => color_scheme == *cs,
120            Self::PrefersReducedMotion(rm) => reduced_motion == *rm,
121        }
122    }
123}
124
125/// Parses a simple CSS media query string (e.g. `(min-width: 768px)`, `(max-width: 1024px)`).
126fn parse_media_query(query: &str) -> Vec<MediaCondition> {
127    let mut conditions = Vec::new();
128    let cleaned = query
129        .trim()
130        .trim_start_matches('@')
131        .trim_start_matches("media")
132        .trim();
133
134    for part in cleaned.split("and") {
135        let p = part.trim().trim_matches(|c| c == '(' || c == ')').trim();
136        if let Some((prop, val)) = p.split_once(':') {
137            let prop_name = prop.trim().to_ascii_lowercase();
138            let val_str = val.trim().to_ascii_lowercase();
139            let val_clean = val_str.trim_end_matches("px").trim();
140
141            match prop_name.as_str() {
142                "min-width" => {
143                    if let Ok(num) = val_clean.parse::<f32>() {
144                        conditions.push(MediaCondition::MinWidth(num));
145                    }
146                }
147                "max-width" => {
148                    if let Ok(num) = val_clean.parse::<f32>() {
149                        conditions.push(MediaCondition::MaxWidth(num));
150                    }
151                }
152                "min-height" => {
153                    if let Ok(num) = val_clean.parse::<f32>() {
154                        conditions.push(MediaCondition::MinHeight(num));
155                    }
156                }
157                "max-height" => {
158                    if let Ok(num) = val_clean.parse::<f32>() {
159                        conditions.push(MediaCondition::MaxHeight(num));
160                    }
161                }
162                "orientation" => {
163                    if val_str == "portrait" {
164                        conditions.push(MediaCondition::OrientationPortrait);
165                    } else if val_str == "landscape" {
166                        conditions.push(MediaCondition::OrientationLandscape);
167                    }
168                }
169                "prefers-color-scheme" => {
170                    if val_str == "light" {
171                        conditions.push(MediaCondition::PrefersColorScheme(ColorScheme::Light));
172                    } else if val_str == "dark" {
173                        conditions.push(MediaCondition::PrefersColorScheme(ColorScheme::Dark));
174                    }
175                }
176                "prefers-reduced-motion" => {
177                    if val_str == "reduce" {
178                        conditions.push(MediaCondition::PrefersReducedMotion(true));
179                    } else if val_str == "no-preference" {
180                        conditions.push(MediaCondition::PrefersReducedMotion(false));
181                    }
182                }
183                _ => {}
184            }
185        }
186    }
187
188    conditions
189}
190
191/// Headless hook evaluating a CSS media query against the current reactive viewport and preferences.
192pub fn use_media_query(query: &str) -> Signal<bool> {
193    let conditions = parse_media_query(query);
194    let (w, h) = VIEWPORT_DIMENSIONS.with(|d| d.borrow().get());
195    let cs = COLOR_SCHEME.with(|cs| cs.borrow().get());
196    let rm = REDUCED_MOTION.with(|rm| rm.borrow().get());
197
198    let initial_match = conditions.iter().all(|c| c.evaluate(w, h, cs, rm));
199    let result_sig = Signal::new(initial_match);
200
201    ACTIVE_MEDIA_QUERIES.with(|queries| {
202        queries.borrow_mut().push((conditions, result_sig.clone()));
203    });
204
205    result_sig
206}