strata_dom/hooks/
media.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16pub enum ColorScheme {
17 Light,
18 #[default]
19 Dark,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum ContrastPreference {
25 #[default]
26 Normal,
27 High,
28 Low,
29}
30
31fn 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
45pub 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
53pub fn set_system_color_scheme(scheme: ColorScheme) {
55 COLOR_SCHEME.with(|cs| {
56 cs.borrow().set(scheme);
57 });
58 reevaluate_active_queries();
59}
60
61pub fn set_system_reduced_motion(reduced: bool) {
63 REDUCED_MOTION.with(|rm| {
64 rm.borrow().set(reduced);
65 });
66 reevaluate_active_queries();
67}
68
69pub fn set_system_contrast(contrast: ContrastPreference) {
71 CONTRAST_PREFERENCE.with(|cp| {
72 cp.borrow().set(contrast);
73 });
74}
75
76pub fn use_color_scheme() -> Signal<ColorScheme> {
78 COLOR_SCHEME.with(|cs| cs.borrow().clone())
79}
80
81pub fn use_reduced_motion() -> Signal<bool> {
83 REDUCED_MOTION.with(|rm| rm.borrow().clone())
84}
85
86pub fn use_contrast() -> Signal<ContrastPreference> {
88 CONTRAST_PREFERENCE.with(|cp| cp.borrow().clone())
89}
90
91#[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
125fn 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
191pub 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}