1#![doc(html_root_url = "https://docs.rs/css-mediaquery/0.1.0")]
22
23#[cfg(doctest)]
25#[doc = include_str!("../README.md")]
26struct ReadmeDoctests;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum Modifier {
31 Min,
33 Max,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Expression {
40 pub modifier: Option<Modifier>,
42 pub feature: String,
44 pub value: Option<String>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Query {
52 pub inverse: bool,
54 pub media_type: String,
56 pub expressions: Vec<Expression>,
58}
59
60#[derive(Debug, Clone, Default, PartialEq)]
67pub struct Context {
68 media_type: Option<String>,
69 width: Option<f64>,
70 height: Option<f64>,
71 device_width: Option<f64>,
72 device_height: Option<f64>,
73 resolution: Option<f64>,
74 orientation: Option<String>,
75 scan: Option<String>,
76 aspect_ratio: Option<f64>,
77 device_aspect_ratio: Option<f64>,
78 device_pixel_ratio: Option<f64>,
79 color: Option<i64>,
80 color_index: Option<i64>,
81 monochrome: Option<i64>,
82 grid: Option<i64>,
83}
84
85macro_rules! setter {
86 ($(#[$m:meta])* $name:ident, $field:ident, $ty:ty) => {
87 $(#[$m])*
88 #[must_use]
89 pub fn $name(mut self, value: $ty) -> Self {
90 self.$field = Some(value);
91 self
92 }
93 };
94}
95
96impl Context {
97 #[must_use]
99 pub fn new() -> Self {
100 Self::default()
101 }
102
103 #[must_use]
105 pub fn media_type(mut self, value: &str) -> Self {
106 self.media_type = Some(value.to_ascii_lowercase());
107 self
108 }
109
110 #[must_use]
112 pub fn orientation(mut self, value: &str) -> Self {
113 self.orientation = Some(value.into());
114 self
115 }
116
117 #[must_use]
119 pub fn scan(mut self, value: &str) -> Self {
120 self.scan = Some(value.into());
121 self
122 }
123
124 setter!(width, width, f64);
126 setter!(height, height, f64);
128 setter!(device_width, device_width, f64);
130 setter!(device_height, device_height, f64);
132 setter!(resolution, resolution, f64);
134 setter!(aspect_ratio, aspect_ratio, f64);
136 setter!(device_aspect_ratio, device_aspect_ratio, f64);
138 setter!(device_pixel_ratio, device_pixel_ratio, f64);
140 setter!(color, color, i64);
142 setter!(color_index, color_index, i64);
144 setter!(monochrome, monochrome, i64);
146 setter!(grid, grid, i64);
148}
149
150#[must_use]
160pub fn parse(query: &str) -> Vec<Query> {
161 query.split(',').map(parse_one).collect()
162}
163
164#[must_use]
171pub fn matches(query: &str, context: &Context) -> bool {
172 parse(query).iter().any(|q| query_matches(q, context))
173}
174
175impl Query {
176 #[must_use]
178 pub fn matches(&self, context: &Context) -> bool {
179 query_matches(self, context)
180 }
181}
182
183fn parse_one(query: &str) -> Query {
188 let q = query.trim();
189 let paren = q.find('(');
190 let head = q[..paren.unwrap_or(q.len())].trim();
191 let exprs_part = paren.map_or("", |p| &q[p..]);
192
193 let (inverse, media_type) = parse_head(head);
194
195 Query {
196 inverse,
197 media_type,
198 expressions: parse_expressions(exprs_part),
199 }
200}
201
202fn parse_head(head: &str) -> (bool, String) {
206 for (keyword, inverse) in [("not", true), ("only", false)] {
207 if let Some(after) = strip_keyword(head, keyword) {
208 return match first_token(after) {
209 Some(t) => (inverse, t.to_ascii_lowercase()),
210 None => (false, keyword.to_string()),
211 };
212 }
213 }
214 match first_token(head) {
215 Some(t) => (false, t.to_ascii_lowercase()),
216 None => (false, String::from("all")),
217 }
218}
219
220fn strip_keyword<'a>(s: &'a str, keyword: &str) -> Option<&'a str> {
222 let prefix = s.get(..keyword.len())?;
223 prefix
224 .eq_ignore_ascii_case(keyword)
225 .then(|| &s[keyword.len()..])
226}
227
228fn first_token(s: &str) -> Option<&str> {
230 let s = s.trim_start();
231 let end = s
232 .find(|c: char| c.is_whitespace() || c == '(' || c == ')')
233 .unwrap_or(s.len());
234 (end != 0).then(|| &s[..end])
235}
236
237fn parse_expressions(s: &str) -> Vec<Expression> {
238 let mut out = Vec::new();
239 let mut rest = s;
240 while let Some(open) = rest.find('(') {
241 let after = &rest[open + 1..];
242 let Some(close) = after.find(')') else { break };
243 let inner = &after[..close];
244 if !inner.is_empty() {
245 if let Some(expr) = parse_expression(inner) {
246 out.push(expr);
247 }
248 }
249 rest = &after[close + 1..];
250 }
251 out
252}
253
254fn parse_expression(inner: &str) -> Option<Expression> {
255 let s = inner.trim_start();
256 let feat_end = s
257 .find(|c: char| c.is_whitespace() || c == ':')
258 .unwrap_or(s.len());
259 let feature_raw = &s[..feat_end];
260 if feature_raw.is_empty() {
261 return None;
262 }
263
264 let rest = s[feat_end..].trim_start();
265 let value = rest
266 .strip_prefix(':')
267 .map(str::trim_start)
268 .and_then(|after| {
269 let end = after.find(char::is_whitespace).unwrap_or(after.len());
270 let v = &after[..end];
271 (!v.is_empty()).then(|| v.to_string())
272 });
273
274 let lower = feature_raw.to_ascii_lowercase();
275 let (modifier, feature) = match lower.strip_prefix("min-").filter(|r| !r.is_empty()) {
276 Some(r) => (Some(Modifier::Min), r.to_string()),
277 None => match lower.strip_prefix("max-").filter(|r| !r.is_empty()) {
278 Some(r) => (Some(Modifier::Max), r.to_string()),
279 None => (None, lower),
280 },
281 };
282
283 Some(Expression {
284 modifier,
285 feature,
286 value,
287 })
288}
289
290fn query_matches(q: &Query, ctx: &Context) -> bool {
295 let type_match =
296 q.media_type == "all" || ctx.media_type.as_deref() == Some(q.media_type.as_str());
297
298 if (type_match && q.inverse) || !(type_match || q.inverse) {
300 return false;
301 }
302
303 let expressions_match = q.expressions.iter().all(|e| expr_matches(e, ctx));
304 (expressions_match && !q.inverse) || (!expressions_match && q.inverse)
305}
306
307fn expr_matches(e: &Expression, ctx: &Context) -> bool {
308 match e.feature.as_str() {
309 "orientation" => string_match(ctx.orientation.as_deref(), e),
310 "scan" => string_match(ctx.scan.as_deref(), e),
311 "width" => length_match(ctx.width, e),
312 "height" => length_match(ctx.height, e),
313 "device-width" => length_match(ctx.device_width, e),
314 "device-height" => length_match(ctx.device_height, e),
315 "resolution" => number_match(ctx.resolution, e, to_dpi),
316 "aspect-ratio" => number_match(ctx.aspect_ratio, e, to_decimal),
317 "device-aspect-ratio" => number_match(ctx.device_aspect_ratio, e, to_decimal),
318 "device-pixel-ratio" => number_match(ctx.device_pixel_ratio, e, to_decimal),
319 "color" => count_match(ctx.color, e),
320 "color-index" => count_match(ctx.color_index, e),
321 "monochrome" => count_match(ctx.monochrome, e),
322 "grid" => count_match(ctx.grid, e),
323 _ => false,
324 }
325}
326
327fn length_match(ctx_value: Option<f64>, e: &Expression) -> bool {
328 number_match(ctx_value, e, to_px)
329}
330
331#[allow(clippy::float_cmp)]
333fn number_match(ctx_value: Option<f64>, e: &Expression, convert: fn(&str) -> f64) -> bool {
334 let Some(value) = ctx_value.filter(|&v| v != 0.0) else {
335 return false;
336 };
337 let Some(raw) = e.value.as_deref() else {
338 return false;
339 };
340 let expected = convert(raw);
341 if expected.is_nan() {
342 return false;
343 }
344 match e.modifier {
345 Some(Modifier::Min) => value >= expected,
346 Some(Modifier::Max) => value <= expected,
347 None => value == expected,
348 }
349}
350
351fn count_match(ctx_value: Option<i64>, e: &Expression) -> bool {
352 let Some(value) = ctx_value.filter(|&v| v != 0) else {
353 return false;
354 };
355 let expected = match e.value.as_deref().and_then(parse_leading_i64) {
357 Some(0) | None => 1,
358 Some(x) => x,
359 };
360 match e.modifier {
361 Some(Modifier::Min) => value >= expected,
362 Some(Modifier::Max) => value <= expected,
363 None => value == expected,
364 }
365}
366
367fn string_match(ctx_value: Option<&str>, e: &Expression) -> bool {
368 let Some(value) = ctx_value.filter(|s| !s.is_empty()) else {
369 return false;
370 };
371 e.value
372 .as_deref()
373 .is_some_and(|expected| value.eq_ignore_ascii_case(expected))
374}
375
376fn to_px(length: &str) -> f64 {
381 let value = parse_leading_f64(length);
382 match trailing_unit(length, &["rem", "em", "px", "cm", "mm", "in", "pt", "pc"]) {
383 "em" | "rem" => value * 16.0,
384 "cm" => value * 96.0 / 2.54,
385 "mm" => value * 96.0 / 2.54 / 10.0,
386 "in" => value * 96.0,
387 "pt" => value * 72.0,
388 "pc" => value * 72.0 / 12.0,
389 _ => value, }
391}
392
393fn to_dpi(resolution: &str) -> f64 {
394 let value = parse_leading_f64(resolution);
395 match trailing_unit(resolution, &["dpcm", "dppx", "dpi"]) {
396 "dpcm" => value / 2.54,
397 "dppx" => value * 96.0,
398 _ => value, }
400}
401
402fn to_decimal(ratio: &str) -> f64 {
403 let trimmed = ratio.trim();
404 if let Ok(value) = trimmed.parse::<f64>() {
405 if value != 0.0 {
406 return value;
407 }
408 }
409 if let Some((a, b)) = trimmed.split_once('/') {
410 if let (Ok(a), Ok(b)) = (a.trim().parse::<f64>(), b.trim().parse::<f64>()) {
411 if b != 0.0 {
412 return a / b;
413 }
414 }
415 }
416 f64::NAN
417}
418
419fn trailing_unit<'a>(s: &str, units: &[&'a str]) -> &'a str {
421 let s = s.trim();
424 units.iter().copied().find(|u| s.ends_with(u)).unwrap_or("")
425}
426
427fn parse_leading_f64(s: &str) -> f64 {
429 let s = s.trim_start();
430 let bytes = s.as_bytes();
431 let mut i = 0;
432 if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
433 i += 1;
434 }
435 let mut seen_digit = false;
436 while i < bytes.len() && bytes[i].is_ascii_digit() {
437 i += 1;
438 seen_digit = true;
439 }
440 if i < bytes.len() && bytes[i] == b'.' {
441 i += 1;
442 while i < bytes.len() && bytes[i].is_ascii_digit() {
443 i += 1;
444 seen_digit = true;
445 }
446 }
447 if !seen_digit {
448 return f64::NAN;
449 }
450 if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
452 let mut j = i + 1;
453 if j < bytes.len() && (bytes[j] == b'+' || bytes[j] == b'-') {
454 j += 1;
455 }
456 let exp_start = j;
457 while j < bytes.len() && bytes[j].is_ascii_digit() {
458 j += 1;
459 }
460 if j > exp_start {
461 i = j;
462 }
463 }
464 s[..i].parse::<f64>().unwrap_or(f64::NAN)
465}
466
467fn parse_leading_i64(s: &str) -> Option<i64> {
469 let s = s.trim_start();
470 let bytes = s.as_bytes();
471 let mut i = 0;
472 if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
473 i += 1;
474 }
475 let start_digits = i;
476 while i < bytes.len() && bytes[i].is_ascii_digit() {
477 i += 1;
478 }
479 if i == start_digits {
480 return None;
481 }
482 s[..i].parse::<i64>().ok()
483}