Skip to main content

css_mediaquery/
lib.rs

1//! # css-mediaquery — parse and match CSS media queries
2//!
3//! Parse a CSS media query string into an AST and test it against a context
4//! (viewport width, resolution, orientation, …) — a headless `matchMedia` for
5//! servers and tooling. A faithful Rust port of the
6//! [`css-mediaquery`](https://www.npmjs.com/package/css-mediaquery) npm package.
7//!
8//! ```
9//! use css_mediaquery::{matches, Context};
10//!
11//! let ctx = Context::new().media_type("screen").width(640.0);
12//! assert!(matches("screen and (min-width: 600px)", &ctx));
13//! assert!(!matches("screen and (min-width: 800px)", &ctx));
14//! ```
15//!
16//! Lengths in the query are converted to pixels exactly as css-mediaquery does
17//! (`1em` = `1rem` = `16px`, `1in` = `96px`, …); resolutions to dpi (`1dppx` =
18//! `96dpi`). A feature only matches when the context supplies a (non-zero) value for
19//! it — orientation and aspect-ratio are *not* derived from width/height.
20
21#![doc(html_root_url = "https://docs.rs/css-mediaquery/0.1.0")]
22
23// Compile-test the README's examples as part of `cargo test`.
24#[cfg(doctest)]
25#[doc = include_str!("../README.md")]
26struct ReadmeDoctests;
27
28/// Whether a feature is compared with `min-`, `max-`, or exactly.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum Modifier {
31    /// `min-…`: the context value must be `>=` the query value.
32    Min,
33    /// `max-…`: the context value must be `<=` the query value.
34    Max,
35}
36
37/// A single `(feature: value)` test within a query.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Expression {
40    /// `Some` when the feature was written `min-`/`max-` prefixed.
41    pub modifier: Option<Modifier>,
42    /// The feature name, lowercased and with any `min-`/`max-` prefix stripped.
43    pub feature: String,
44    /// The raw value text, or `None` for a boolean feature like `(color)`.
45    pub value: Option<String>,
46}
47
48/// One comma-separated media query: an optional `not`, a media type, and a list of
49/// feature expressions.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Query {
52    /// `true` when the query was prefixed with `not`.
53    pub inverse: bool,
54    /// The media type (`screen`, `print`, …), lowercased; `all` when unspecified.
55    pub media_type: String,
56    /// The `(feature: value)` expressions, in order.
57    pub expressions: Vec<Expression>,
58}
59
60/// The device/viewport context a query is tested against. Build it with the
61/// setters; any feature left unset never matches.
62///
63/// ```
64/// let ctx = css_mediaquery::Context::new().width(800.0).height(600.0).resolution(192.0);
65/// ```
66#[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    /// A context with no features set.
98    #[must_use]
99    pub fn new() -> Self {
100        Self::default()
101    }
102
103    /// Set the media type (`"screen"`, `"print"`, …); stored lowercased.
104    #[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    /// Set the orientation (`"portrait"` or `"landscape"`).
111    #[must_use]
112    pub fn orientation(mut self, value: &str) -> Self {
113        self.orientation = Some(value.into());
114        self
115    }
116
117    /// Set the scan type (`"progressive"` or `"interlace"`).
118    #[must_use]
119    pub fn scan(mut self, value: &str) -> Self {
120        self.scan = Some(value.into());
121        self
122    }
123
124    setter!(/// Set the viewport width, in pixels.
125        width, width, f64);
126    setter!(/// Set the viewport height, in pixels.
127        height, height, f64);
128    setter!(/// Set the device width, in pixels.
129        device_width, device_width, f64);
130    setter!(/// Set the device height, in pixels.
131        device_height, device_height, f64);
132    setter!(/// Set the resolution, in dots per inch (`1dppx` = `96dpi`).
133        resolution, resolution, f64);
134    setter!(/// Set the aspect ratio as a decimal (e.g. `16.0 / 9.0`).
135        aspect_ratio, aspect_ratio, f64);
136    setter!(/// Set the device aspect ratio as a decimal.
137        device_aspect_ratio, device_aspect_ratio, f64);
138    setter!(/// Set the device pixel ratio as a decimal.
139        device_pixel_ratio, device_pixel_ratio, f64);
140    setter!(/// Set the number of bits per color component.
141        color, color, i64);
142    setter!(/// Set the number of entries in the color lookup table.
143        color_index, color_index, i64);
144    setter!(/// Set the number of bits per pixel on a monochrome device.
145        monochrome, monochrome, i64);
146    setter!(/// Set the grid value (`1` for grid devices, `0` otherwise).
147        grid, grid, i64);
148}
149
150/// Parse a media query string into a list of [`Query`] (one per comma).
151///
152/// Parsing never fails; malformed fragments simply yield empty or partial queries.
153///
154/// ```
155/// let q = css_mediaquery::parse("screen and (min-width: 600px)");
156/// assert_eq!(q[0].media_type, "screen");
157/// assert_eq!(q[0].expressions[0].feature, "width");
158/// ```
159#[must_use]
160pub fn parse(query: &str) -> Vec<Query> {
161    query.split(',').map(parse_one).collect()
162}
163
164/// Test whether `query` matches `context`.
165///
166/// ```
167/// let ctx = css_mediaquery::Context::new().resolution(192.0);
168/// assert!(css_mediaquery::matches("(min-resolution: 2dppx)", &ctx));
169/// ```
170#[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    /// Test whether this single query matches `context`.
177    #[must_use]
178    pub fn matches(&self, context: &Context) -> bool {
179        query_matches(self, context)
180    }
181}
182
183// ---------------------------------------------------------------------------
184// Parsing
185// ---------------------------------------------------------------------------
186
187fn 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
202/// Parse the leading `(only|not)? <type>` clause, mirroring css-mediaquery's
203/// `RE_MEDIA_QUERY`: the keyword may be glued to the type (`notscreen`), and a lone
204/// `not`/`only` is itself taken as the type.
205fn 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
220/// `s` with a leading `keyword` removed (ASCII case-insensitive), or `None`.
221fn 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
228/// The leading `[^\s()]+` token of `s` (after skipping whitespace), or `None`.
229fn 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
290// ---------------------------------------------------------------------------
291// Matching
292// ---------------------------------------------------------------------------
293
294fn 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    // Quit early when the type doesn't match, taking `not` into account.
299    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// Exact float equality is intentional here: css-mediaquery compares with `===`.
332#[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    // `parseInt(value, 10) || 1`: missing, unparsable, or zero becomes 1.
356    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
376// ---------------------------------------------------------------------------
377// Unit conversions (verbatim from css-mediaquery, including its quirks)
378// ---------------------------------------------------------------------------
379
380fn 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, // "px" or unitless
390    }
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, // "dpi" or unitless
399    }
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
419/// The matching unit suffix from `units` (checked in order), or `""` if none.
420fn trailing_unit<'a>(s: &str, units: &[&'a str]) -> &'a str {
421    // Case-sensitive, like css-mediaquery's unit regexes: an uppercase suffix such
422    // as `IN` is treated as unitless.
423    let s = s.trim();
424    units.iter().copied().find(|u| s.ends_with(u)).unwrap_or("")
425}
426
427/// Parse the leading number of `s` (like JavaScript's `parseFloat`); `NaN` if none.
428fn 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    // Exponent, like JS `parseFloat`: `[eE][+-]?digits` (a bare trailing `e` is left).
451    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
467/// Parse the leading integer of `s` (like `parseInt`); `None` if none.
468fn 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}