Skip to main content

rspack_lightningcss/rules/
page.rs

1//! The `@page` rule.
2
3use super::Location;
4use crate::declaration::{parse_declaration, DeclarationBlock};
5use crate::error::{ParserError, PrinterError};
6use crate::macros::enum_property;
7use crate::stylesheet::ParserOptions;
8use crate::traits::{Parse, ToCss};
9use crate::values::string::CowArcStr;
10#[cfg(feature = "visitor")]
11use crate::visitor::Visit;
12use cssparser::*;
13
14/// A [page selector](https://www.w3.org/TR/css-page-3/#typedef-page-selector)
15/// within a `@page` rule.
16///
17/// Either a name or at least one pseudo class is required.
18#[derive(Debug, PartialEq, Clone)]
19#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
20#[cfg_attr(
21  feature = "serde",
22  derive(serde::Serialize, serde::Deserialize),
23  serde(rename_all = "camelCase")
24)]
25#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
26pub struct PageSelector<'i> {
27  /// An optional named page type.
28  #[cfg_attr(feature = "serde", serde(borrow))]
29  pub name: Option<CowArcStr<'i>>,
30  /// A list of page pseudo classes.
31  pub pseudo_classes: Vec<PagePseudoClass>,
32}
33
34enum_property! {
35  /// A page pseudo class within an `@page` selector.
36  ///
37  /// See [PageSelector](PageSelector).
38  pub enum PagePseudoClass {
39    /// The `:left` pseudo class.
40    Left,
41    /// The `:right` pseudo class.
42    Right,
43    /// The `:first` pseudo class.
44    First,
45    /// The `:last` pseudo class.
46    Last,
47    /// The `:blank` pseudo class.
48    Blank,
49  }
50}
51
52impl<'i> Parse<'i> for PageSelector<'i> {
53  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
54    let name = input.try_parse(|input| input.expect_ident().map(|x| x.into())).ok();
55    let mut pseudo_classes = vec![];
56
57    loop {
58      // Whitespace is not allowed between pseudo classes
59      let state = input.state();
60      match input.next_including_whitespace() {
61        Ok(Token::Colon) => {
62          pseudo_classes.push(PagePseudoClass::parse(input)?);
63        }
64        _ => {
65          input.reset(&state);
66          break;
67        }
68      }
69    }
70
71    if name.is_none() && pseudo_classes.is_empty() {
72      return Err(input.new_custom_error(ParserError::InvalidPageSelector));
73    }
74
75    Ok(PageSelector { name, pseudo_classes })
76  }
77}
78
79enum_property! {
80  /// A [page margin box](https://www.w3.org/TR/css-page-3/#margin-boxes).
81  pub enum PageMarginBox {
82    /// A fixed-size box defined by the intersection of the top and left margins of the page box.
83    TopLeftCorner,
84    /// A variable-width box filling the top page margin between the top-left-corner and top-center page-margin boxes.
85    TopLeft,
86    /// A variable-width box centered horizontally between the page’s left and right border edges and filling the
87    /// page top margin between the top-left and top-right page-margin boxes.
88    TopCenter,
89    /// A variable-width box filling the top page margin between the top-center and top-right-corner page-margin boxes.
90    TopRight,
91    /// A fixed-size box defined by the intersection of the top and right margins of the page box.
92    TopRightCorner,
93    /// A variable-height box filling the left page margin between the top-left-corner and left-middle page-margin boxes.
94    LeftTop,
95    /// A variable-height box centered vertically between the page’s top and bottom border edges and filling the
96    /// left page margin between the left-top and left-bottom page-margin boxes.
97    LeftMiddle,
98    /// A variable-height box filling the left page margin between the left-middle and bottom-left-corner page-margin boxes.
99    LeftBottom,
100    /// A variable-height box filling the right page margin between the top-right-corner and right-middle page-margin boxes.
101    RightTop,
102    /// A variable-height box centered vertically between the page’s top and bottom border edges and filling the right
103    /// page margin between the right-top and right-bottom page-margin boxes.
104    RightMiddle,
105    /// A variable-height box filling the right page margin between the right-middle and bottom-right-corner page-margin boxes.
106    RightBottom,
107    /// A fixed-size box defined by the intersection of the bottom and left margins of the page box.
108    BottomLeftCorner,
109    /// A variable-width box filling the bottom page margin between the bottom-left-corner and bottom-center page-margin boxes.
110    BottomLeft,
111    /// A variable-width box centered horizontally between the page’s left and right border edges and filling the bottom
112    /// page margin between the bottom-left and bottom-right page-margin boxes.
113    BottomCenter,
114    /// A variable-width box filling the bottom page margin between the bottom-center and bottom-right-corner page-margin boxes.
115    BottomRight,
116    /// A fixed-size box defined by the intersection of the bottom and right margins of the page box.
117    BottomRightCorner,
118  }
119}
120
121/// A [page margin rule](https://www.w3.org/TR/css-page-3/#margin-at-rules) rule.
122#[derive(Debug, PartialEq, Clone)]
123#[cfg_attr(feature = "visitor", derive(Visit))]
124#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
125#[cfg_attr(
126  feature = "serde",
127  derive(serde::Serialize, serde::Deserialize),
128  serde(rename_all = "camelCase")
129)]
130#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
131pub struct PageMarginRule<'i> {
132  /// The margin box identifier for this rule.
133  pub margin_box: PageMarginBox,
134  /// The declarations within the rule.
135  #[cfg_attr(feature = "serde", serde(borrow))]
136  pub declarations: DeclarationBlock<'i>,
137  /// The location of the rule in the source file.
138  #[cfg_attr(feature = "visitor", skip_visit)]
139  pub loc: Location,
140}
141
142impl<'i> ToCss for PageMarginRule<'i> {
143  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
144    #[cfg(feature = "custom_sourcemap")]
145    dest.add_mapping(self.loc);
146    dest.write_char('@')?;
147    self.margin_box.to_css(dest)?;
148    self.declarations.to_css_block(dest)
149  }
150}
151
152/// A [@page](https://www.w3.org/TR/css-page-3/#at-page-rule) rule.
153#[derive(Debug, PartialEq, Clone)]
154#[cfg_attr(feature = "visitor", derive(Visit))]
155#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
156#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
157#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
158pub struct PageRule<'i> {
159  /// A list of page selectors.
160  #[cfg_attr(feature = "serde", serde(borrow))]
161  #[cfg_attr(feature = "visitor", skip_visit)]
162  pub selectors: Vec<PageSelector<'i>>,
163  /// The declarations within the `@page` rule.
164  pub declarations: DeclarationBlock<'i>,
165  /// The nested margin rules.
166  pub rules: Vec<PageMarginRule<'i>>,
167  /// The location of the rule in the source file.
168  #[cfg_attr(feature = "visitor", skip_visit)]
169  pub loc: Location,
170}
171
172impl<'i> PageRule<'i> {
173  pub(crate) fn parse<'t, 'o>(
174    selectors: Vec<PageSelector<'i>>,
175    input: &mut Parser<'i, 't>,
176    loc: Location,
177    options: &ParserOptions<'i>,
178  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
179    let mut declarations = DeclarationBlock::new();
180    let mut rules = Vec::new();
181    let mut rule_parser = PageRuleParser {
182      declarations: &mut declarations,
183      rules: &mut rules,
184      options: &options,
185    };
186    let mut parser = RuleBodyParser::new(input, &mut rule_parser);
187
188    while let Some(decl) = parser.next() {
189      if let Err((err, _)) = decl {
190        if parser.parser.options.error_recovery {
191          parser.parser.options.warn(err);
192          continue;
193        }
194        return Err(err);
195      }
196    }
197
198    Ok(PageRule {
199      selectors,
200      declarations,
201      rules,
202      loc,
203    })
204  }
205}
206
207impl<'i> ToCss for PageRule<'i> {
208  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
209    #[cfg(feature = "custom_sourcemap")]
210    dest.add_mapping(self.loc);
211    dest.write_str("@page")?;
212    if let Some(first) = self.selectors.first() {
213      // Space is only required if the first selector has a name.
214      if !dest.options().minify || first.name.is_some() {
215        dest.write_char(' ')?;
216      }
217      let mut first = true;
218      for selector in &self.selectors {
219        if first {
220          first = false;
221        } else {
222          dest.delim(',', false)?;
223        }
224        selector.to_css(dest)?;
225      }
226    }
227
228    dest.whitespace()?;
229    dest.write_char('{')?;
230    dest.indent();
231
232    let mut i = 0;
233    let len = self.declarations.len() + self.rules.len();
234
235    macro_rules! write {
236      ($decls: expr, $important: literal) => {
237        for decl in &$decls {
238          dest.newline()?;
239          decl.to_css(dest, $important)?;
240          if i != len - 1 || !dest.options().minify {
241            dest.write_char(';')?;
242          }
243          i += 1;
244        }
245      };
246    }
247
248    write!(self.declarations.declarations, false);
249    write!(self.declarations.important_declarations, true);
250
251    if !self.rules.is_empty() {
252      if !dest.options().minify && self.declarations.len() > 0 {
253        dest.write_char('\n')?;
254      }
255      dest.newline()?;
256
257      let mut first = true;
258      for rule in &self.rules {
259        if first {
260          first = false;
261        } else {
262          if !dest.options().minify {
263            dest.write_char('\n')?;
264          }
265          dest.newline()?;
266        }
267        rule.to_css(dest)?;
268      }
269    }
270
271    dest.dedent();
272    dest.newline()?;
273    dest.write_char('}')?;
274    Ok(())
275  }
276}
277
278impl<'i> ToCss for PageSelector<'i> {
279  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
280    if let Some(name) = &self.name {
281      dest.write_str(&name)?;
282    }
283
284    for pseudo in &self.pseudo_classes {
285      dest.write_char(':')?;
286      pseudo.to_css(dest)?;
287    }
288
289    Ok(())
290  }
291}
292
293struct PageRuleParser<'a, 'i> {
294  declarations: &'a mut DeclarationBlock<'i>,
295  rules: &'a mut Vec<PageMarginRule<'i>>,
296  options: &'a ParserOptions<'i>,
297}
298
299impl<'a, 'o, 'i> cssparser::DeclarationParser<'i> for PageRuleParser<'a, 'i> {
300  type Declaration = ();
301  type Error = ParserError<'i>;
302
303  fn parse_value<'t>(
304    &mut self,
305    name: CowRcStr<'i>,
306    input: &mut cssparser::Parser<'i, 't>,
307    _declaration_start: &ParserState,
308  ) -> Result<Self::Declaration, cssparser::ParseError<'i, Self::Error>> {
309    parse_declaration(
310      name,
311      input,
312      &mut self.declarations.declarations,
313      &mut self.declarations.important_declarations,
314      &self.options,
315    )
316  }
317}
318
319impl<'a, 'i> AtRuleParser<'i> for PageRuleParser<'a, 'i> {
320  type Prelude = PageMarginBox;
321  type AtRule = ();
322  type Error = ParserError<'i>;
323
324  fn parse_prelude<'t>(
325    &mut self,
326    name: CowRcStr<'i>,
327    input: &mut Parser<'i, 't>,
328  ) -> Result<Self::Prelude, ParseError<'i, Self::Error>> {
329    let loc = input.current_source_location();
330    PageMarginBox::parse_string(&name)
331      .map_err(|_| loc.new_custom_error(ParserError::AtRuleInvalid(name.clone().into())))
332  }
333
334  fn parse_block<'t>(
335    &mut self,
336    prelude: Self::Prelude,
337    start: &ParserState,
338    input: &mut Parser<'i, 't>,
339  ) -> Result<Self::AtRule, ParseError<'i, Self::Error>> {
340    let loc = start.source_location();
341    let declarations = DeclarationBlock::parse(input, self.options)?;
342    self.rules.push(PageMarginRule {
343      margin_box: prelude,
344      declarations,
345      loc: Location {
346        source_index: self.options.source_index,
347        line: loc.line,
348        column: loc.column,
349      },
350    });
351    Ok(())
352  }
353}
354
355impl<'a, 'i> QualifiedRuleParser<'i> for PageRuleParser<'a, 'i> {
356  type Prelude = ();
357  type QualifiedRule = ();
358  type Error = ParserError<'i>;
359}
360
361impl<'a, 'i> RuleBodyItemParser<'i, (), ParserError<'i>> for PageRuleParser<'a, 'i> {
362  fn parse_qualified(&self) -> bool {
363    false
364  }
365
366  fn parse_declarations(&self) -> bool {
367    true
368  }
369}