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
use crate::values::string::CowArcStr;
use cssparser::*;
use super::Location;
use crate::traits::{Parse, ToCss};
use crate::declaration::DeclarationBlock;
use crate::printer::Printer;
use crate::macros::enum_property;
use crate::error::{ParserError, PrinterError};

/// https://www.w3.org/TR/css-page-3/#typedef-page-selector
#[derive(Debug, PartialEq, Clone)]
pub struct PageSelector<'i> {
  pub name: Option<CowArcStr<'i>>,
  pub pseudo_classes: Vec<PagePseudoClass>
}

enum_property! {
  pub enum PagePseudoClass {
    Left,
    Right,
    First,
    Last,
    Blank,
  }
}

impl<'i> Parse<'i> for PageSelector<'i> {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    let name = input.try_parse(|input| input.expect_ident().map(|x| x.into())).ok();
    let mut pseudo_classes = vec![];
    
    loop {
      // Whitespace is not allowed between pseudo classes
      let state = input.state();
      match input.next_including_whitespace() {
        Ok(Token::Colon) => {
          pseudo_classes.push(PagePseudoClass::parse(input)?);
        }
        _ => {
          input.reset(&state);
          break
        }
      }
    }

    if name.is_none() && pseudo_classes.is_empty() {
      return Err(input.new_custom_error(ParserError::InvalidPageSelector))
    }

    Ok(PageSelector {
      name,
      pseudo_classes
    })
  }
}

#[derive(Debug, PartialEq, Clone)]
pub struct PageRule<'i> {
  pub selectors: Vec<PageSelector<'i>>,
  pub declarations: DeclarationBlock<'i>,
  pub loc: Location
}

impl<'i> ToCss for PageRule<'i> {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    dest.add_mapping(self.loc);
    dest.write_str("@page")?;
    if let Some(first) = self.selectors.first() {
      // Space is only required if the first selector has a name.
      if !dest.minify || first.name.is_some() {
        dest.write_char(' ')?;
      }
      let mut first = true;
      for selector in &self.selectors {
        if first {
          first = false;
        } else {
          dest.delim(',', false)?;
        }
        selector.to_css(dest)?;
      }
    }
    self.declarations.to_css(dest)
  }
}

impl<'i> ToCss for PageSelector<'i> {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
    if let Some(name) = &self.name {
      dest.write_str(&name)?;
    }

    for pseudo in &self.pseudo_classes {
      dest.write_char(':')?;
      pseudo.to_css(dest)?;
    }

    Ok(())
  }
}