#![doc(html_root_url = "https://docs.rs/css-mediaquery/0.1.0")]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Modifier {
Min,
Max,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Expression {
pub modifier: Option<Modifier>,
pub feature: String,
pub value: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Query {
pub inverse: bool,
pub media_type: String,
pub expressions: Vec<Expression>,
}
#[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 {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn media_type(mut self, value: &str) -> Self {
self.media_type = Some(value.to_ascii_lowercase());
self
}
#[must_use]
pub fn orientation(mut self, value: &str) -> Self {
self.orientation = Some(value.into());
self
}
#[must_use]
pub fn scan(mut self, value: &str) -> Self {
self.scan = Some(value.into());
self
}
setter!( width, width, f64);
setter!( height, height, f64);
setter!( device_width, device_width, f64);
setter!( device_height, device_height, f64);
setter!( resolution, resolution, f64);
setter!( aspect_ratio, aspect_ratio, f64);
setter!( device_aspect_ratio, device_aspect_ratio, f64);
setter!( device_pixel_ratio, device_pixel_ratio, f64);
setter!( color, color, i64);
setter!( color_index, color_index, i64);
setter!( monochrome, monochrome, i64);
setter!( grid, grid, i64);
}
#[must_use]
pub fn parse(query: &str) -> Vec<Query> {
query.split(',').map(parse_one).collect()
}
#[must_use]
pub fn matches(query: &str, context: &Context) -> bool {
parse(query).iter().any(|q| query_matches(q, context))
}
impl Query {
#[must_use]
pub fn matches(&self, context: &Context) -> bool {
query_matches(self, context)
}
}
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),
}
}
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")),
}
}
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()..])
}
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,
})
}
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());
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)
}
#[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;
};
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))
}
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, }
}
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, }
}
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
}
fn trailing_unit<'a>(s: &str, units: &[&'a str]) -> &'a str {
let s = s.trim();
units.iter().copied().find(|u| s.ends_with(u)).unwrap_or("")
}
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;
}
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)
}
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()
}