Skip to main content

lewp_css/domain/at_rules/document/
document_condition.rs

1// This file is part of css. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/css/master/COPYRIGHT. No part of predicator, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
2// Copyright © 2017 The developers of css. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/css/master/COPYRIGHT.
3
4use {
5    super::{Document, UrlMatchingFunction},
6    crate::{parsers::ParserContext, CustomParseError},
7    cssparser::{ParseError, Parser, ToCss},
8    std::fmt,
9};
10
11/// A `@document` rule's condition.
12///
13/// <https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document>
14///
15/// The `@document` rule's condition is written as a comma-separated list of URL matching functions, and the condition evaluates to true whenever any one of those functions evaluates to true.
16#[derive(Clone, Debug)]
17pub struct DocumentCondition(pub Vec<UrlMatchingFunction>);
18
19impl ToCss for DocumentCondition {
20    fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
21        let mut iter = self.0.iter();
22        let first = iter.next().expect("Empty DocumentCondition, should contain at least one URL matching function");
23        first.to_css(dest)?;
24        for url_matching_function in iter {
25            dest.write_str(", ")?;
26            url_matching_function.to_css(dest)?;
27        }
28        Ok(())
29    }
30}
31
32impl DocumentCondition {
33    /// Parse a document condition.
34    pub(crate) fn parse<'i, 't>(
35        context: &ParserContext,
36        input: &mut Parser<'i, 't>,
37    ) -> Result<Self, ParseError<'i, CustomParseError<'i>>> {
38        input
39            .parse_comma_separated(|input| {
40                UrlMatchingFunction::parse(context, input)
41            })
42            .map(DocumentCondition)
43    }
44
45    /// Evaluate a document condition.
46    pub fn evaluate<D: Document>(&self, document: &D) -> bool {
47        self.0.iter().any(|url_matching_function| {
48            url_matching_function.evaluate(document)
49        })
50    }
51}