rspack_lightningcss/rules/
page.rs1use 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#[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 #[cfg_attr(feature = "serde", serde(borrow))]
29 pub name: Option<CowArcStr<'i>>,
30 pub pseudo_classes: Vec<PagePseudoClass>,
32}
33
34enum_property! {
35 pub enum PagePseudoClass {
39 Left,
41 Right,
43 First,
45 Last,
47 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 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 pub enum PageMarginBox {
82 TopLeftCorner,
84 TopLeft,
86 TopCenter,
89 TopRight,
91 TopRightCorner,
93 LeftTop,
95 LeftMiddle,
98 LeftBottom,
100 RightTop,
102 RightMiddle,
105 RightBottom,
107 BottomLeftCorner,
109 BottomLeft,
111 BottomCenter,
114 BottomRight,
116 BottomRightCorner,
118 }
119}
120
121#[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 pub margin_box: PageMarginBox,
134 #[cfg_attr(feature = "serde", serde(borrow))]
136 pub declarations: DeclarationBlock<'i>,
137 #[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#[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 #[cfg_attr(feature = "serde", serde(borrow))]
161 #[cfg_attr(feature = "visitor", skip_visit)]
162 pub selectors: Vec<PageSelector<'i>>,
163 pub declarations: DeclarationBlock<'i>,
165 pub rules: Vec<PageMarginRule<'i>>,
167 #[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 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}