css-mediaquery 0.1.1

Parse CSS media queries and test them against a context (width, resolution, orientation, …) — a faithful port of the css-mediaquery npm package. Zero dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! # css-mediaquery — parse and match CSS media queries
//!
//! Parse a CSS media query string into an AST and test it against a context
//! (viewport width, resolution, orientation, …) — a headless `matchMedia` for
//! servers and tooling. A faithful Rust port of the
//! [`css-mediaquery`](https://www.npmjs.com/package/css-mediaquery) npm package.
//!
//! ```
//! use css_mediaquery::{matches, Context};
//!
//! let ctx = Context::new().media_type("screen").width(640.0);
//! assert!(matches("screen and (min-width: 600px)", &ctx));
//! assert!(!matches("screen and (min-width: 800px)", &ctx));
//! ```
//!
//! Lengths in the query are converted to pixels exactly as css-mediaquery does
//! (`1em` = `1rem` = `16px`, `1in` = `96px`, …); resolutions to dpi (`1dppx` =
//! `96dpi`). A feature only matches when the context supplies a (non-zero) value for
//! it — orientation and aspect-ratio are *not* derived from width/height.

#![doc(html_root_url = "https://docs.rs/css-mediaquery/0.1.0")]

// Compile-test the README's examples as part of `cargo test`.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;

/// Whether a feature is compared with `min-`, `max-`, or exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Modifier {
    /// `min-…`: the context value must be `>=` the query value.
    Min,
    /// `max-…`: the context value must be `<=` the query value.
    Max,
}

/// A single `(feature: value)` test within a query.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Expression {
    /// `Some` when the feature was written `min-`/`max-` prefixed.
    pub modifier: Option<Modifier>,
    /// The feature name, lowercased and with any `min-`/`max-` prefix stripped.
    pub feature: String,
    /// The raw value text, or `None` for a boolean feature like `(color)`.
    pub value: Option<String>,
}

/// One comma-separated media query: an optional `not`, a media type, and a list of
/// feature expressions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Query {
    /// `true` when the query was prefixed with `not`.
    pub inverse: bool,
    /// The media type (`screen`, `print`, …), lowercased; `all` when unspecified.
    pub media_type: String,
    /// The `(feature: value)` expressions, in order.
    pub expressions: Vec<Expression>,
}

/// The device/viewport context a query is tested against. Build it with the
/// setters; any feature left unset never matches.
///
/// ```
/// let ctx = css_mediaquery::Context::new().width(800.0).height(600.0).resolution(192.0);
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Context {
    media_type: Option<String>,
    width: Option<f64>,
    height: Option<f64>,
    device_width: Option<f64>,
    device_height: Option<f64>,
    resolution: Option<f64>,
    orientation: Option<String>,
    scan: Option<String>,
    aspect_ratio: Option<f64>,
    device_aspect_ratio: Option<f64>,
    device_pixel_ratio: Option<f64>,
    color: Option<i64>,
    color_index: Option<i64>,
    monochrome: Option<i64>,
    grid: Option<i64>,
}

macro_rules! setter {
    ($(#[$m:meta])* $name:ident, $field:ident, $ty:ty) => {
        $(#[$m])*
        #[must_use]
        pub fn $name(mut self, value: $ty) -> Self {
            self.$field = Some(value);
            self
        }
    };
}

impl Context {
    /// A context with no features set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the media type (`"screen"`, `"print"`, …); stored lowercased.
    #[must_use]
    pub fn media_type(mut self, value: &str) -> Self {
        self.media_type = Some(value.to_ascii_lowercase());
        self
    }

    /// Set the orientation (`"portrait"` or `"landscape"`).
    #[must_use]
    pub fn orientation(mut self, value: &str) -> Self {
        self.orientation = Some(value.into());
        self
    }

    /// Set the scan type (`"progressive"` or `"interlace"`).
    #[must_use]
    pub fn scan(mut self, value: &str) -> Self {
        self.scan = Some(value.into());
        self
    }

    setter!(/// Set the viewport width, in pixels.
        width, width, f64);
    setter!(/// Set the viewport height, in pixels.
        height, height, f64);
    setter!(/// Set the device width, in pixels.
        device_width, device_width, f64);
    setter!(/// Set the device height, in pixels.
        device_height, device_height, f64);
    setter!(/// Set the resolution, in dots per inch (`1dppx` = `96dpi`).
        resolution, resolution, f64);
    setter!(/// Set the aspect ratio as a decimal (e.g. `16.0 / 9.0`).
        aspect_ratio, aspect_ratio, f64);
    setter!(/// Set the device aspect ratio as a decimal.
        device_aspect_ratio, device_aspect_ratio, f64);
    setter!(/// Set the device pixel ratio as a decimal.
        device_pixel_ratio, device_pixel_ratio, f64);
    setter!(/// Set the number of bits per color component.
        color, color, i64);
    setter!(/// Set the number of entries in the color lookup table.
        color_index, color_index, i64);
    setter!(/// Set the number of bits per pixel on a monochrome device.
        monochrome, monochrome, i64);
    setter!(/// Set the grid value (`1` for grid devices, `0` otherwise).
        grid, grid, i64);
}

/// Parse a media query string into a list of [`Query`] (one per comma).
///
/// Parsing never fails; malformed fragments simply yield empty or partial queries.
///
/// ```
/// let q = css_mediaquery::parse("screen and (min-width: 600px)");
/// assert_eq!(q[0].media_type, "screen");
/// assert_eq!(q[0].expressions[0].feature, "width");
/// ```
#[must_use]
pub fn parse(query: &str) -> Vec<Query> {
    query.split(',').map(parse_one).collect()
}

/// Test whether `query` matches `context`.
///
/// ```
/// let ctx = css_mediaquery::Context::new().resolution(192.0);
/// assert!(css_mediaquery::matches("(min-resolution: 2dppx)", &ctx));
/// ```
#[must_use]
pub fn matches(query: &str, context: &Context) -> bool {
    parse(query).iter().any(|q| query_matches(q, context))
}

impl Query {
    /// Test whether this single query matches `context`.
    #[must_use]
    pub fn matches(&self, context: &Context) -> bool {
        query_matches(self, context)
    }
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

fn parse_one(query: &str) -> Query {
    let q = query.trim();
    let paren = q.find('(');
    let head = q[..paren.unwrap_or(q.len())].trim();
    let exprs_part = paren.map_or("", |p| &q[p..]);

    let (inverse, media_type) = parse_head(head);

    Query {
        inverse,
        media_type,
        expressions: parse_expressions(exprs_part),
    }
}

/// Parse the leading `(only|not)? <type>` clause, mirroring css-mediaquery's
/// `RE_MEDIA_QUERY`: the keyword may be glued to the type (`notscreen`), and a lone
/// `not`/`only` is itself taken as the type.
fn parse_head(head: &str) -> (bool, String) {
    for (keyword, inverse) in [("not", true), ("only", false)] {
        if let Some(after) = strip_keyword(head, keyword) {
            return match first_token(after) {
                Some(t) => (inverse, t.to_ascii_lowercase()),
                None => (false, keyword.to_string()),
            };
        }
    }
    match first_token(head) {
        Some(t) => (false, t.to_ascii_lowercase()),
        None => (false, String::from("all")),
    }
}

/// `s` with a leading `keyword` removed (ASCII case-insensitive), or `None`.
fn strip_keyword<'a>(s: &'a str, keyword: &str) -> Option<&'a str> {
    let prefix = s.get(..keyword.len())?;
    prefix
        .eq_ignore_ascii_case(keyword)
        .then(|| &s[keyword.len()..])
}

/// The leading `[^\s()]+` token of `s` (after skipping whitespace), or `None`.
fn first_token(s: &str) -> Option<&str> {
    let s = s.trim_start();
    let end = s
        .find(|c: char| c.is_whitespace() || c == '(' || c == ')')
        .unwrap_or(s.len());
    (end != 0).then(|| &s[..end])
}

fn parse_expressions(s: &str) -> Vec<Expression> {
    let mut out = Vec::new();
    let mut rest = s;
    while let Some(open) = rest.find('(') {
        let after = &rest[open + 1..];
        let Some(close) = after.find(')') else { break };
        let inner = &after[..close];
        if !inner.is_empty() {
            if let Some(expr) = parse_expression(inner) {
                out.push(expr);
            }
        }
        rest = &after[close + 1..];
    }
    out
}

fn parse_expression(inner: &str) -> Option<Expression> {
    let s = inner.trim_start();
    let feat_end = s
        .find(|c: char| c.is_whitespace() || c == ':')
        .unwrap_or(s.len());
    let feature_raw = &s[..feat_end];
    if feature_raw.is_empty() {
        return None;
    }

    let rest = s[feat_end..].trim_start();
    let value = rest
        .strip_prefix(':')
        .map(str::trim_start)
        .and_then(|after| {
            let end = after.find(char::is_whitespace).unwrap_or(after.len());
            let v = &after[..end];
            (!v.is_empty()).then(|| v.to_string())
        });

    let lower = feature_raw.to_ascii_lowercase();
    let (modifier, feature) = match lower.strip_prefix("min-").filter(|r| !r.is_empty()) {
        Some(r) => (Some(Modifier::Min), r.to_string()),
        None => match lower.strip_prefix("max-").filter(|r| !r.is_empty()) {
            Some(r) => (Some(Modifier::Max), r.to_string()),
            None => (None, lower),
        },
    };

    Some(Expression {
        modifier,
        feature,
        value,
    })
}

// ---------------------------------------------------------------------------
// Matching
// ---------------------------------------------------------------------------

fn query_matches(q: &Query, ctx: &Context) -> bool {
    let type_match =
        q.media_type == "all" || ctx.media_type.as_deref() == Some(q.media_type.as_str());

    // Quit early when the type doesn't match, taking `not` into account.
    if (type_match && q.inverse) || !(type_match || q.inverse) {
        return false;
    }

    let expressions_match = q.expressions.iter().all(|e| expr_matches(e, ctx));
    (expressions_match && !q.inverse) || (!expressions_match && q.inverse)
}

fn expr_matches(e: &Expression, ctx: &Context) -> bool {
    match e.feature.as_str() {
        "orientation" => string_match(ctx.orientation.as_deref(), e),
        "scan" => string_match(ctx.scan.as_deref(), e),
        "width" => length_match(ctx.width, e),
        "height" => length_match(ctx.height, e),
        "device-width" => length_match(ctx.device_width, e),
        "device-height" => length_match(ctx.device_height, e),
        "resolution" => number_match(ctx.resolution, e, to_dpi),
        "aspect-ratio" => number_match(ctx.aspect_ratio, e, to_decimal),
        "device-aspect-ratio" => number_match(ctx.device_aspect_ratio, e, to_decimal),
        "device-pixel-ratio" => number_match(ctx.device_pixel_ratio, e, to_decimal),
        "color" => count_match(ctx.color, e),
        "color-index" => count_match(ctx.color_index, e),
        "monochrome" => count_match(ctx.monochrome, e),
        "grid" => count_match(ctx.grid, e),
        _ => false,
    }
}

fn length_match(ctx_value: Option<f64>, e: &Expression) -> bool {
    number_match(ctx_value, e, to_px)
}

// Exact float equality is intentional here: css-mediaquery compares with `===`.
#[allow(clippy::float_cmp)]
fn number_match(ctx_value: Option<f64>, e: &Expression, convert: fn(&str) -> f64) -> bool {
    let Some(value) = ctx_value.filter(|&v| v != 0.0) else {
        return false;
    };
    let Some(raw) = e.value.as_deref() else {
        return false;
    };
    let expected = convert(raw);
    if expected.is_nan() {
        return false;
    }
    match e.modifier {
        Some(Modifier::Min) => value >= expected,
        Some(Modifier::Max) => value <= expected,
        None => value == expected,
    }
}

fn count_match(ctx_value: Option<i64>, e: &Expression) -> bool {
    let Some(value) = ctx_value.filter(|&v| v != 0) else {
        return false;
    };
    // `parseInt(value, 10) || 1`: missing, unparsable, or zero becomes 1.
    let expected = match e.value.as_deref().and_then(parse_leading_i64) {
        Some(0) | None => 1,
        Some(x) => x,
    };
    match e.modifier {
        Some(Modifier::Min) => value >= expected,
        Some(Modifier::Max) => value <= expected,
        None => value == expected,
    }
}

fn string_match(ctx_value: Option<&str>, e: &Expression) -> bool {
    let Some(value) = ctx_value.filter(|s| !s.is_empty()) else {
        return false;
    };
    e.value
        .as_deref()
        .is_some_and(|expected| value.eq_ignore_ascii_case(expected))
}

// ---------------------------------------------------------------------------
// Unit conversions (verbatim from css-mediaquery, including its quirks)
// ---------------------------------------------------------------------------

fn to_px(length: &str) -> f64 {
    let value = parse_leading_f64(length);
    match trailing_unit(length, &["rem", "em", "px", "cm", "mm", "in", "pt", "pc"]) {
        "em" | "rem" => value * 16.0,
        "cm" => value * 96.0 / 2.54,
        "mm" => value * 96.0 / 2.54 / 10.0,
        "in" => value * 96.0,
        "pt" => value * 72.0,
        "pc" => value * 72.0 / 12.0,
        _ => value, // "px" or unitless
    }
}

fn to_dpi(resolution: &str) -> f64 {
    let value = parse_leading_f64(resolution);
    match trailing_unit(resolution, &["dpcm", "dppx", "dpi"]) {
        "dpcm" => value / 2.54,
        "dppx" => value * 96.0,
        _ => value, // "dpi" or unitless
    }
}

fn to_decimal(ratio: &str) -> f64 {
    let trimmed = ratio.trim();
    if let Ok(value) = trimmed.parse::<f64>() {
        if value != 0.0 {
            return value;
        }
    }
    if let Some((a, b)) = trimmed.split_once('/') {
        if let (Ok(a), Ok(b)) = (a.trim().parse::<f64>(), b.trim().parse::<f64>()) {
            if b != 0.0 {
                return a / b;
            }
        }
    }
    f64::NAN
}

/// The matching unit suffix from `units` (checked in order), or `""` if none.
fn trailing_unit<'a>(s: &str, units: &[&'a str]) -> &'a str {
    // Case-sensitive, like css-mediaquery's unit regexes: an uppercase suffix such
    // as `IN` is treated as unitless.
    let s = s.trim();
    units.iter().copied().find(|u| s.ends_with(u)).unwrap_or("")
}

/// Parse the leading number of `s` (like JavaScript's `parseFloat`); `NaN` if none.
fn parse_leading_f64(s: &str) -> f64 {
    let s = s.trim_start();
    let bytes = s.as_bytes();
    let mut i = 0;
    if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
        i += 1;
    }
    let mut seen_digit = false;
    while i < bytes.len() && bytes[i].is_ascii_digit() {
        i += 1;
        seen_digit = true;
    }
    if i < bytes.len() && bytes[i] == b'.' {
        i += 1;
        while i < bytes.len() && bytes[i].is_ascii_digit() {
            i += 1;
            seen_digit = true;
        }
    }
    if !seen_digit {
        return f64::NAN;
    }
    // Exponent, like JS `parseFloat`: `[eE][+-]?digits` (a bare trailing `e` is left).
    if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
        let mut j = i + 1;
        if j < bytes.len() && (bytes[j] == b'+' || bytes[j] == b'-') {
            j += 1;
        }
        let exp_start = j;
        while j < bytes.len() && bytes[j].is_ascii_digit() {
            j += 1;
        }
        if j > exp_start {
            i = j;
        }
    }
    s[..i].parse::<f64>().unwrap_or(f64::NAN)
}

/// Parse the leading integer of `s` (like `parseInt`); `None` if none.
fn parse_leading_i64(s: &str) -> Option<i64> {
    let s = s.trim_start();
    let bytes = s.as_bytes();
    let mut i = 0;
    if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
        i += 1;
    }
    let start_digits = i;
    while i < bytes.len() && bytes[i].is_ascii_digit() {
        i += 1;
    }
    if i == start_digits {
        return None;
    }
    s[..i].parse::<i64>().ok()
}