Skip to main content

rspack_lightningcss/properties/
grid.rs

1//! CSS properties related to grid layout.
2
3#![allow(non_upper_case_globals)]
4
5use crate::context::PropertyHandlerContext;
6use crate::declaration::{DeclarationBlock, DeclarationList};
7use crate::error::{Error, ErrorLocation, ParserError, PrinterError, PrinterErrorKind};
8use crate::macros::{define_shorthand, impl_shorthand};
9use crate::properties::{Property, PropertyId};
10use crate::traits::{Parse, PropertyHandler, Shorthand, ToCss};
11use crate::values::ident::CustomIdent;
12use crate::values::length::serialize_dimension;
13use crate::values::number::{CSSInteger, CSSNumber, NonNegative};
14use crate::values::{ident::CustomIdentList, length::LengthPercentage};
15#[cfg(feature = "visitor")]
16use crate::visitor::Visit;
17use bitflags::bitflags;
18use cssparser::*;
19use smallvec::SmallVec;
20
21#[cfg(feature = "serde")]
22use crate::serialization::ValueWrapper;
23
24/// A [track sizing](https://drafts.csswg.org/css-grid-2/#track-sizing) value
25/// for the `grid-template-rows` and `grid-template-columns` properties.
26#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
27#[cfg_attr(feature = "visitor", derive(Visit))]
28#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
29#[cfg_attr(
30  feature = "serde",
31  derive(serde::Serialize, serde::Deserialize),
32  serde(tag = "type", rename_all = "kebab-case")
33)]
34#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
35pub enum TrackSizing<'i> {
36  /// No explicit grid tracks.
37  None,
38  /// A list of grid tracks.
39  #[cfg_attr(feature = "serde", serde(borrow))]
40  TrackList(TrackList<'i>),
41}
42
43/// A [`<track-list>`](https://drafts.csswg.org/css-grid-2/#typedef-track-list) value,
44/// as used in the `grid-template-rows` and `grid-template-columns` properties.
45///
46/// See [TrackSizing](TrackSizing).
47#[derive(Debug, Clone, PartialEq)]
48#[cfg_attr(feature = "visitor", derive(Visit))]
49#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
50#[cfg_attr(
51  feature = "serde",
52  derive(serde::Serialize, serde::Deserialize),
53  serde(rename_all = "camelCase")
54)]
55#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
56pub struct TrackList<'i> {
57  /// A list of line names.
58  #[cfg_attr(feature = "serde", serde(borrow))]
59  pub line_names: Vec<CustomIdentList<'i>>,
60  /// A list of grid track items.
61  pub items: Vec<TrackListItem<'i>>,
62}
63
64/// Either a track size or `repeat()` function.
65///
66/// See [TrackList](TrackList).
67#[derive(Debug, Clone, PartialEq)]
68#[cfg_attr(feature = "visitor", derive(Visit))]
69#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
70#[cfg_attr(
71  feature = "serde",
72  derive(serde::Serialize, serde::Deserialize),
73  serde(tag = "type", content = "value", rename_all = "kebab-case")
74)]
75#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
76pub enum TrackListItem<'i> {
77  /// A track size.
78  TrackSize(TrackSize),
79  /// A `repeat()` function.
80  #[cfg_attr(feature = "serde", serde(borrow))]
81  TrackRepeat(TrackRepeat<'i>),
82}
83
84/// A [`<track-size>`](https://drafts.csswg.org/css-grid-2/#typedef-track-size) value,
85/// as used in the `grid-template-rows` and `grid-template-columns` properties.
86///
87/// See [TrackListItem](TrackListItem).
88#[derive(Debug, Clone, PartialEq)]
89#[cfg_attr(feature = "visitor", derive(Visit))]
90#[cfg_attr(
91  feature = "serde",
92  derive(serde::Serialize, serde::Deserialize),
93  serde(tag = "type", rename_all = "kebab-case")
94)]
95#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
96#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
97pub enum TrackSize {
98  /// An explicit track breadth.
99  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<TrackBreadth>"))]
100  TrackBreadth(TrackBreadth),
101  /// The `minmax()` function.
102  MinMax {
103    /// The minimum value.
104    min: TrackBreadth,
105    /// The maximum value.
106    max: TrackBreadth,
107  },
108  /// The `fit-content()` function.
109  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<NonNegative<LengthPercentage>>"))]
110  FitContent(NonNegative<LengthPercentage>),
111}
112
113impl Default for TrackSize {
114  fn default() -> TrackSize {
115    TrackSize::TrackBreadth(TrackBreadth::Auto)
116  }
117}
118
119/// A [track size list](https://drafts.csswg.org/css-grid-2/#auto-tracks), as used
120/// in the `grid-auto-rows` and `grid-auto-columns` properties.
121#[derive(Debug, Clone, PartialEq, Default)]
122#[cfg_attr(feature = "visitor", derive(Visit))]
123#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
124#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
125#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
126pub struct TrackSizeList(pub SmallVec<[TrackSize; 1]>);
127
128/// A [`<track-breadth>`](https://drafts.csswg.org/css-grid-2/#typedef-track-breadth) value.
129///
130/// See [TrackSize](TrackSize).
131#[derive(Debug, Clone, PartialEq)]
132#[cfg_attr(feature = "visitor", derive(Visit))]
133#[cfg_attr(
134  feature = "serde",
135  derive(serde::Serialize, serde::Deserialize),
136  serde(tag = "type", content = "value", rename_all = "kebab-case")
137)]
138#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
139#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
140pub enum TrackBreadth {
141  /// An explicit length.
142  Length(NonNegative<LengthPercentage>),
143  /// A flex factor.
144  Flex(NonNegative<CSSNumber>),
145  /// The `min-content` keyword.
146  MinContent,
147  /// The `max-content` keyword.
148  MaxContent,
149  /// The `auto` keyword.
150  Auto,
151}
152
153/// A [`<track-repeat>`](https://drafts.csswg.org/css-grid-2/#typedef-track-repeat) value,
154/// representing the `repeat()` function in a track list.
155///
156/// See [TrackListItem](TrackListItem).
157#[derive(Debug, Clone, PartialEq)]
158#[cfg_attr(feature = "visitor", derive(Visit))]
159#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
160#[cfg_attr(
161  feature = "serde",
162  derive(serde::Serialize, serde::Deserialize),
163  serde(rename_all = "camelCase")
164)]
165#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
166pub struct TrackRepeat<'i> {
167  /// The repeat count.
168  pub count: RepeatCount,
169  /// The line names to repeat.
170  #[cfg_attr(feature = "serde", serde(borrow))]
171  pub line_names: Vec<CustomIdentList<'i>>,
172  /// The track sizes to repeat.
173  pub track_sizes: Vec<TrackSize>,
174}
175
176/// A [`<repeat-count>`](https://drafts.csswg.org/css-grid-2/#typedef-track-repeat) value,
177/// used in the `repeat()` function.
178///
179/// See [TrackRepeat](TrackRepeat).
180#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
181#[cfg_attr(feature = "visitor", derive(Visit))]
182#[cfg_attr(
183  feature = "serde",
184  derive(serde::Serialize, serde::Deserialize),
185  serde(tag = "type", content = "value", rename_all = "kebab-case")
186)]
187#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
188#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
189pub enum RepeatCount {
190  /// The number of times to repeat.
191  Number(CSSInteger),
192  /// The `auto-fill` keyword.
193  AutoFill,
194  /// The `auto-fit` keyword.
195  AutoFit,
196}
197
198impl<'i> Parse<'i> for TrackSize {
199  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
200    if let Ok(breadth) = input.try_parse(TrackBreadth::parse) {
201      return Ok(TrackSize::TrackBreadth(breadth));
202    }
203
204    if input.try_parse(|input| input.expect_function_matching("minmax")).is_ok() {
205      return input.parse_nested_block(|input| {
206        let min = TrackBreadth::parse_internal(input, false)?;
207        input.expect_comma()?;
208        Ok(TrackSize::MinMax {
209          min,
210          max: TrackBreadth::parse(input)?,
211        })
212      });
213    }
214
215    input.expect_function_matching("fit-content")?;
216    let len = input.parse_nested_block(NonNegative::<LengthPercentage>::parse)?;
217    Ok(TrackSize::FitContent(len))
218  }
219}
220
221impl ToCss for TrackSize {
222  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
223    match self {
224      TrackSize::TrackBreadth(breadth) => breadth.to_css(dest),
225      TrackSize::MinMax { min, max } => {
226        dest.write_str("minmax(")?;
227        min.to_css(dest)?;
228        dest.delim(',', false)?;
229        max.to_css(dest)?;
230        dest.write_char(')')?;
231        Ok(())
232      }
233      TrackSize::FitContent(len) => {
234        dest.write_str("fit-content(")?;
235        len.to_css(dest)?;
236        dest.write_char(')')?;
237        Ok(())
238      }
239    }
240  }
241}
242
243impl<'i> Parse<'i> for TrackBreadth {
244  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
245    Self::parse_internal(input, true)
246  }
247}
248
249impl TrackBreadth {
250  fn parse_internal<'i, 't>(
251    input: &mut Parser<'i, 't>,
252    allow_flex: bool,
253  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
254    if let Ok(len) = input.try_parse(NonNegative::<LengthPercentage>::parse) {
255      return Ok(TrackBreadth::Length(len));
256    }
257
258    if allow_flex {
259      if let Ok(flex) = input.try_parse(Self::parse_flex) {
260        return Ok(TrackBreadth::Flex(flex));
261      }
262    }
263
264    let location = input.current_source_location();
265    let ident = input.expect_ident()?;
266    match_ignore_ascii_case! { &*ident,
267      "auto" => Ok(TrackBreadth::Auto),
268      "min-content" => Ok(TrackBreadth::MinContent),
269      "max-content" => Ok(TrackBreadth::MaxContent),
270      _ => Err(location.new_unexpected_token_error(
271        cssparser::Token::Ident(ident.clone())
272      ))
273    }
274  }
275
276  fn parse_flex<'i, 't>(
277    input: &mut Parser<'i, 't>,
278  ) -> Result<NonNegative<CSSNumber>, ParseError<'i, ParserError<'i>>> {
279    let location = input.current_source_location();
280    match *input.next()? {
281      Token::Dimension { value, ref unit, .. } if unit.eq_ignore_ascii_case("fr") && value >= 0.0 => {
282        Ok(NonNegative(value))
283      }
284      ref t => Err(location.new_unexpected_token_error(t.clone())),
285    }
286  }
287}
288
289impl ToCss for TrackBreadth {
290  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
291    match self {
292      TrackBreadth::Auto => {
293        dest.write_str("auto")?;
294        Ok(())
295      }
296      TrackBreadth::MinContent => {
297        dest.write_str("min-content")?;
298        Ok(())
299      }
300      TrackBreadth::MaxContent => {
301        dest.write_str("max-content")?;
302        Ok(())
303      }
304      TrackBreadth::Length(len) => len.to_css(dest),
305      TrackBreadth::Flex(flex) => serialize_dimension(flex.0, "fr", dest),
306    }
307  }
308}
309
310impl<'i> Parse<'i> for TrackRepeat<'i> {
311  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
312    input.expect_function_matching("repeat")?;
313    input.parse_nested_block(|input| {
314      let count = RepeatCount::parse(input)?;
315      input.expect_comma()?;
316
317      let mut line_names = Vec::new();
318      let mut track_sizes = Vec::new();
319
320      loop {
321        let line_name = input.try_parse(parse_line_names).unwrap_or_default();
322        line_names.push(line_name);
323
324        if let Ok(track_size) = input.try_parse(TrackSize::parse) {
325          // TODO: error handling
326          track_sizes.push(track_size)
327        } else {
328          break;
329        }
330      }
331
332      Ok(TrackRepeat {
333        count,
334        line_names,
335        track_sizes,
336      })
337    })
338  }
339}
340
341impl<'i> ToCss for TrackRepeat<'i> {
342  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
343    dest.write_str("repeat(")?;
344    self.count.to_css(dest)?;
345    dest.delim(',', false)?;
346
347    let mut track_sizes_iter = self.track_sizes.iter();
348    let mut first = true;
349    for names in self.line_names.iter() {
350      if !names.is_empty() {
351        serialize_line_names(names, dest)?;
352      }
353
354      if let Some(size) = track_sizes_iter.next() {
355        // Whitespace is required if there are no line names.
356        if !names.is_empty() {
357          dest.whitespace()?;
358        } else if !first {
359          dest.write_char(' ')?;
360        }
361        size.to_css(dest)?;
362      }
363
364      first = false;
365    }
366
367    dest.write_char(')')?;
368
369    Ok(())
370  }
371}
372
373fn parse_line_names<'i, 't>(
374  input: &mut Parser<'i, 't>,
375) -> Result<CustomIdentList<'i>, ParseError<'i, ParserError<'i>>> {
376  input.expect_square_bracket_block()?;
377  input.parse_nested_block(|input| {
378    let mut values = SmallVec::new();
379    while let Ok(ident) = input.try_parse(CustomIdent::parse) {
380      values.push(ident)
381    }
382    Ok(values)
383  })
384}
385
386fn serialize_line_names<PrinterT: crate::printer::PrinterTrait>(
387  names: &[CustomIdent],
388  dest: &mut PrinterT,
389) -> Result<(), PrinterError> {
390  dest.write_char('[')?;
391  let mut first = true;
392  for name in names {
393    if first {
394      first = false;
395    } else {
396      dest.write_char(' ')?;
397    }
398    write_ident(&name.0, dest)?;
399  }
400  dest.write_char(']')?;
401  Ok(())
402}
403
404fn write_ident<PrinterT: crate::printer::PrinterTrait>(
405  name: &str,
406  dest: &mut PrinterT,
407) -> Result<(), PrinterError> {
408  let config = dest.css_module_config().filter(|config| config.grid);
409  if let Some(config) = config {
410    if let Some(last) = config.pattern.segments.last() {
411      if !matches!(last, crate::css_modules::Segment::Local) {
412        return Err(Error {
413          kind: PrinterErrorKind::InvalidCssModulesPatternInGrid,
414          loc: Some(ErrorLocation {
415            filename: dest.filename().into(),
416            line: dest.loc().line,
417            column: dest.loc().column,
418          }),
419        });
420      }
421    }
422  }
423  dest.write_ident(name, config.is_some())?;
424  Ok(())
425}
426
427impl<'i> Parse<'i> for TrackList<'i> {
428  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
429    let mut line_names = Vec::new();
430    let mut items = Vec::new();
431
432    loop {
433      let line_name = input.try_parse(parse_line_names).unwrap_or_default();
434      line_names.push(line_name);
435
436      if let Ok(track_size) = input.try_parse(TrackSize::parse) {
437        // TODO: error handling
438        items.push(TrackListItem::TrackSize(track_size));
439      } else if let Ok(repeat) = input.try_parse(TrackRepeat::parse) {
440        // TODO: error handling
441        items.push(TrackListItem::TrackRepeat(repeat))
442      } else {
443        break;
444      }
445    }
446
447    if items.is_empty() {
448      return Err(input.new_custom_error(ParserError::InvalidDeclaration));
449    }
450
451    Ok(TrackList { line_names, items })
452  }
453}
454
455impl<'i> ToCss for TrackList<'i> {
456  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
457    let mut items_iter = self.items.iter();
458    let line_names_iter = self.line_names.iter();
459    let mut first = true;
460
461    for names in line_names_iter {
462      if !names.is_empty() {
463        serialize_line_names(names, dest)?;
464      }
465
466      if let Some(item) = items_iter.next() {
467        // Whitespace is required if there are no line names.
468        if !names.is_empty() {
469          dest.whitespace()?;
470        } else if !first {
471          dest.write_char(' ')?;
472        }
473        match item {
474          TrackListItem::TrackRepeat(repeat) => repeat.to_css(dest)?,
475          TrackListItem::TrackSize(size) => size.to_css(dest)?,
476        };
477      }
478
479      first = false;
480    }
481
482    Ok(())
483  }
484}
485
486impl<'i> TrackList<'i> {
487  fn is_explicit(&self) -> bool {
488    self.items.iter().all(|item| matches!(item, TrackListItem::TrackSize(_)))
489  }
490}
491
492impl<'i> TrackSizing<'i> {
493  fn is_explicit(&self) -> bool {
494    match self {
495      TrackSizing::None => true,
496      TrackSizing::TrackList(list) => list.is_explicit(),
497    }
498  }
499}
500
501impl<'i> Parse<'i> for TrackSizeList {
502  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
503    let mut res = SmallVec::new();
504    while let Ok(size) = input.try_parse(TrackSize::parse) {
505      res.push(size)
506    }
507    if res.len() == 1 && res[0] == TrackSize::default() {
508      res.clear();
509    }
510    Ok(TrackSizeList(res))
511  }
512}
513
514impl ToCss for TrackSizeList {
515  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
516    if self.0.len() == 0 {
517      dest.write_str("auto")?;
518      return Ok(());
519    }
520
521    let mut first = true;
522    for item in &self.0 {
523      if first {
524        first = false;
525      } else {
526        dest.write_char(' ')?;
527      }
528      item.to_css(dest)?;
529    }
530    Ok(())
531  }
532}
533
534/// A value for the [grid-template-areas](https://drafts.csswg.org/css-grid-2/#grid-template-areas-property) property.
535/// none | <string>+
536#[derive(Debug, Clone, PartialEq)]
537#[cfg_attr(feature = "visitor", derive(Visit))]
538#[cfg_attr(
539  feature = "serde",
540  derive(serde::Serialize, serde::Deserialize),
541  serde(tag = "type", rename_all = "kebab-case")
542)]
543#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
544#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
545pub enum GridTemplateAreas {
546  /// No named grid areas.
547  None,
548  /// Defines the list of named grid areas.
549  Areas {
550    /// The number of columns in the grid.
551    columns: u32,
552    /// A flattened list of grid area names.
553    /// Unnamed areas specified by the `.` token are represented as `None`.
554    areas: Vec<Option<String>>,
555  },
556}
557
558impl<'i> Parse<'i> for GridTemplateAreas {
559  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
560    if input.try_parse(|input| input.expect_ident_matching("none")).is_ok() {
561      return Ok(GridTemplateAreas::None);
562    }
563
564    let mut tokens = Vec::new();
565    let mut row = 0;
566    let mut columns = 0;
567    while let Ok(s) = input.try_parse(|input| input.expect_string().map(|s| s.as_ref().to_owned())) {
568      let parsed_columns = Self::parse_string(&s, &mut tokens)
569        .map_err(|()| input.new_error(BasicParseErrorKind::QualifiedRuleInvalid))?;
570
571      if row == 0 {
572        columns = parsed_columns;
573      } else if parsed_columns != columns {
574        return Err(input.new_custom_error(ParserError::InvalidDeclaration));
575      }
576
577      row += 1;
578    }
579
580    Ok(GridTemplateAreas::Areas { columns, areas: tokens })
581  }
582}
583
584impl GridTemplateAreas {
585  fn parse_string(string: &str, tokens: &mut Vec<Option<String>>) -> Result<u32, ()> {
586    let mut string = string;
587    let mut column = 0;
588    loop {
589      let rest = string.trim_start_matches(HTML_SPACE_CHARACTERS);
590      if rest.is_empty() {
591        // Each string must produce a valid token.
592        if column == 0 {
593          return Err(());
594        }
595        break;
596      }
597
598      column += 1;
599
600      if rest.starts_with('.') {
601        string = &rest[rest.find(|c| c != '.').unwrap_or(rest.len())..];
602        tokens.push(None);
603        continue;
604      }
605
606      if !rest.starts_with(is_name_code_point) {
607        return Err(());
608      }
609
610      let token_len = rest.find(|c| !is_name_code_point(c)).unwrap_or(rest.len());
611      let token = &rest[..token_len];
612      tokens.push(Some(token.into()));
613      string = &rest[token_len..];
614    }
615
616    Ok(column)
617  }
618}
619
620static HTML_SPACE_CHARACTERS: &'static [char] = &['\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}'];
621
622fn is_name_code_point(c: char) -> bool {
623  c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '\u{80}' || c == '_' || c >= '0' && c <= '9' || c == '-'
624}
625
626impl ToCss for GridTemplateAreas {
627  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
628    match self {
629      GridTemplateAreas::None => {
630        dest.write_str("none")?;
631        Ok(())
632      }
633      GridTemplateAreas::Areas { areas, .. } => {
634        let mut iter = areas.iter();
635        let mut next = iter.next();
636        let mut first = true;
637        while next.is_some() {
638          if !first && !dest.options().minify {
639            dest.newline()?;
640          }
641
642          self.write_string(dest, &mut iter, &mut next)?;
643
644          if first {
645            first = false;
646            if !dest.options().minify {
647              // Indent by the width of "grid-template-areas: ", so the rows line up.
648              dest.indent_by(21);
649            }
650          }
651        }
652
653        if !dest.options().minify {
654          dest.dedent_by(21);
655        }
656
657        Ok(())
658      }
659    }
660  }
661}
662
663impl GridTemplateAreas {
664  fn write_string<'a, PrinterT: crate::printer::PrinterTrait>(
665    &self,
666    dest: &mut PrinterT,
667    iter: &mut std::slice::Iter<'a, Option<String>>,
668    next: &mut Option<&'a Option<String>>,
669  ) -> Result<(), PrinterError> {
670    let columns = match self {
671      GridTemplateAreas::Areas { columns, .. } => *columns,
672      _ => unreachable!(),
673    };
674
675    dest.write_char('"')?;
676
677    let mut last_was_null = false;
678    for i in 0..columns {
679      if let Some(token) = next {
680        if let Some(string) = token {
681          if i > 0 && (!last_was_null || !dest.options().minify) {
682            dest.write_char(' ')?;
683          }
684          write_ident(string, dest)?;
685          last_was_null = false;
686        } else {
687          if i > 0 && (last_was_null || !dest.options().minify) {
688            dest.write_char(' ')?;
689          }
690          dest.write_char('.')?;
691          last_was_null = true;
692        }
693      }
694
695      *next = iter.next();
696    }
697
698    dest.write_char('"')?;
699
700    Ok(())
701  }
702}
703
704/// A value for the [grid-template](https://drafts.csswg.org/css-grid-2/#explicit-grid-shorthand) shorthand property.
705///
706/// none | [ <'grid-template-rows'> / <'grid-template-columns'> ] | [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
707///
708/// If `areas` is not `None`, then `rows` must also not be `None`.
709#[derive(Debug, Clone, PartialEq)]
710#[cfg_attr(feature = "visitor", derive(Visit))]
711#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
712#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
713#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
714pub struct GridTemplate<'i> {
715  /// The grid template rows.
716  #[cfg_attr(feature = "serde", serde(borrow))]
717  pub rows: TrackSizing<'i>,
718  /// The grid template columns.
719  pub columns: TrackSizing<'i>,
720  /// The named grid areas.
721  pub areas: GridTemplateAreas,
722}
723
724impl<'i> Parse<'i> for GridTemplate<'i> {
725  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
726    if input.try_parse(|input| input.expect_ident_matching("none")).is_ok() {
727      input.expect_exhausted()?;
728      return Ok(GridTemplate {
729        rows: TrackSizing::None,
730        columns: TrackSizing::None,
731        areas: GridTemplateAreas::None,
732      });
733    }
734
735    let start = input.state();
736    let mut line_names: Vec<CustomIdentList<'i>> = Vec::new();
737    let mut items = Vec::new();
738    let mut columns = 0;
739    let mut row = 0;
740    let mut tokens = Vec::new();
741
742    loop {
743      if let Ok(first_names) = input.try_parse(parse_line_names) {
744        if let Some(last_names) = line_names.last_mut() {
745          last_names.extend(first_names);
746        } else {
747          line_names.push(first_names);
748        }
749      }
750
751      if let Ok(string) = input.try_parse(|input| input.expect_string().map(|s| s.as_ref().to_owned())) {
752        let parsed_columns = GridTemplateAreas::parse_string(&string, &mut tokens)
753          .map_err(|()| input.new_custom_error(ParserError::InvalidDeclaration))?;
754
755        if row == 0 {
756          columns = parsed_columns;
757        } else if parsed_columns != columns {
758          return Err(input.new_custom_error(ParserError::InvalidDeclaration));
759        }
760
761        row += 1;
762
763        let track_size = input.try_parse(TrackSize::parse).unwrap_or_default();
764        items.push(TrackListItem::TrackSize(track_size));
765
766        let last_names = input.try_parse(parse_line_names).unwrap_or_default();
767        line_names.push(last_names);
768      } else {
769        break;
770      }
771    }
772
773    if !tokens.is_empty() {
774      if line_names.len() == items.len() {
775        line_names.push(Default::default());
776      }
777
778      let areas = GridTemplateAreas::Areas { columns, areas: tokens };
779      let rows = TrackSizing::TrackList(TrackList { line_names, items });
780      let columns = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
781        let list = TrackList::parse(input)?;
782        if !list.is_explicit() {
783          return Err(input.new_custom_error(ParserError::InvalidDeclaration));
784        }
785        TrackSizing::TrackList(list)
786      } else {
787        TrackSizing::None
788      };
789      Ok(GridTemplate { rows, columns, areas })
790    } else {
791      input.reset(&start);
792      let rows = TrackSizing::parse(input)?;
793      input.expect_delim('/')?;
794      let columns = TrackSizing::parse(input)?;
795      Ok(GridTemplate {
796        rows,
797        columns,
798        areas: GridTemplateAreas::None,
799      })
800    }
801  }
802}
803
804impl ToCss for GridTemplate<'_> {
805  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
806    self.to_css_with_indent(dest, 15)
807  }
808}
809
810impl GridTemplate<'_> {
811  fn to_css_with_indent<PrinterT: crate::printer::PrinterTrait>(
812    &self,
813    dest: &mut PrinterT,
814    indent: u8,
815  ) -> Result<(), PrinterError> {
816    match &self.areas {
817      GridTemplateAreas::None => {
818        if self.rows == TrackSizing::None && self.columns == TrackSizing::None {
819          dest.write_str("none")?;
820        } else {
821          self.rows.to_css(dest)?;
822          dest.delim('/', true)?;
823          self.columns.to_css(dest)?;
824        }
825      }
826      GridTemplateAreas::Areas { areas, .. } => {
827        let track_list = match &self.rows {
828          TrackSizing::TrackList(list) => list,
829          _ => unreachable!(),
830        };
831
832        let mut areas_iter = areas.iter();
833        let mut line_names_iter = track_list.line_names.iter();
834        let mut items_iter = track_list.items.iter();
835
836        let mut next = areas_iter.next();
837        let mut first = true;
838        let mut indented = false;
839        while next.is_some() {
840          macro_rules! newline {
841            () => {
842              if !dest.options().minify {
843                if !indented {
844                  // Indent by the width of "grid-template: ", so the rows line up.
845                  dest.indent_by(indent);
846                  indented = true;
847                }
848                dest.newline()?;
849              }
850            };
851          }
852
853          if let Some(line_names) = line_names_iter.next() {
854            if !line_names.is_empty() {
855              if !dest.options().minify && line_names.len() == 2 {
856                dest.whitespace()?;
857                serialize_line_names(&line_names[0..1], dest)?;
858                newline!();
859                serialize_line_names(&line_names[1..], dest)?;
860              } else {
861                if !first {
862                  newline!();
863                }
864                serialize_line_names(line_names, dest)?;
865              }
866              dest.whitespace()?;
867            } else if !first {
868              newline!();
869            }
870          } else if !first {
871            newline!();
872          }
873
874          self.areas.write_string(dest, &mut areas_iter, &mut next)?;
875
876          if let Some(item) = items_iter.next() {
877            if *item != TrackListItem::TrackSize(TrackSize::default()) {
878              dest.whitespace()?;
879              match item {
880                TrackListItem::TrackSize(size) => size.to_css(dest)?,
881                _ => unreachable!(),
882              }
883            }
884          }
885
886          first = false;
887        }
888
889        if let Some(line_names) = line_names_iter.next() {
890          if !line_names.is_empty() {
891            dest.whitespace()?;
892            serialize_line_names(line_names, dest)?;
893          }
894        }
895
896        if let TrackSizing::TrackList(track_list) = &self.columns {
897          dest.newline()?;
898          dest.delim('/', false)?;
899          track_list.to_css(dest)?;
900        }
901
902        if indented {
903          dest.dedent_by(indent);
904        }
905      }
906    }
907
908    Ok(())
909  }
910}
911
912impl<'i> GridTemplate<'i> {
913  #[inline]
914  fn is_valid(rows: &TrackSizing, columns: &TrackSizing, areas: &GridTemplateAreas) -> bool {
915    // The `grid-template` shorthand supports only explicit track values (i.e. no `repeat()`)
916    // combined with grid-template-areas. If there are no areas, then any track values are allowed.
917    *areas == GridTemplateAreas::None
918      || (*rows != TrackSizing::None && rows.is_explicit() && columns.is_explicit())
919  }
920}
921
922impl_shorthand! {
923  GridTemplate(GridTemplate<'i>) {
924    rows: [GridTemplateRows],
925    columns: [GridTemplateColumns],
926    areas: [GridTemplateAreas],
927  }
928
929  fn is_valid(shorthand) {
930    GridTemplate::is_valid(&shorthand.rows, &shorthand.columns, &shorthand.areas)
931  }
932}
933
934bitflags! {
935  /// A value for the [grid-auto-flow](https://drafts.csswg.org/css-grid-2/#grid-auto-flow-property) property.
936  ///
937  /// [ row | column ] || dense
938  ///
939  /// The `Row` or `Column` flags may be combined with the `Dense` flag, but the `Row` and `Column` flags may
940  /// not be combined.
941  #[cfg_attr(feature = "visitor", derive(Visit))]
942  #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(from = "SerializedGridAutoFlow", into = "SerializedGridAutoFlow"))]
943  #[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
944  #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
945  pub struct GridAutoFlow: u8 {
946    /// The auto-placement algorithm places items by filling each row, adding new rows as necessary.
947    const Row    = 0b00;
948    /// The auto-placement algorithm places items by filling each column, adding new columns as necessary.
949    const Column = 0b01;
950    /// If specified, a dense packing algorithm is used, which fills in holes in the grid.
951    const Dense  = 0b10;
952  }
953}
954
955#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
956#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
957struct SerializedGridAutoFlow {
958  /// The direction of the auto flow.
959  direction: AutoFlowDirection,
960  /// If specified, a dense packing algorithm is used, which fills in holes in the grid.
961  dense: bool,
962}
963
964impl From<GridAutoFlow> for SerializedGridAutoFlow {
965  fn from(flow: GridAutoFlow) -> Self {
966    Self {
967      direction: if flow.contains(GridAutoFlow::Column) {
968        AutoFlowDirection::Column
969      } else {
970        AutoFlowDirection::Row
971      },
972      dense: flow.contains(GridAutoFlow::Dense),
973    }
974  }
975}
976
977impl From<SerializedGridAutoFlow> for GridAutoFlow {
978  fn from(s: SerializedGridAutoFlow) -> GridAutoFlow {
979    let mut flow = match s.direction {
980      AutoFlowDirection::Row => GridAutoFlow::Row,
981      AutoFlowDirection::Column => GridAutoFlow::Column,
982    };
983    if s.dense {
984      flow |= GridAutoFlow::Dense
985    }
986
987    flow
988  }
989}
990
991#[cfg_attr(
992  feature = "serde",
993  derive(serde::Serialize, serde::Deserialize),
994  serde(rename_all = "lowercase")
995)]
996#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
997enum AutoFlowDirection {
998  Row,
999  Column,
1000}
1001
1002#[cfg(feature = "jsonschema")]
1003#[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
1004impl<'a> schemars::JsonSchema for GridAutoFlow {
1005  fn is_referenceable() -> bool {
1006    true
1007  }
1008
1009  fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
1010    SerializedGridAutoFlow::json_schema(gen)
1011  }
1012
1013  fn schema_name() -> String {
1014    "GridAutoFlow".into()
1015  }
1016}
1017
1018impl Default for GridAutoFlow {
1019  fn default() -> GridAutoFlow {
1020    GridAutoFlow::Row
1021  }
1022}
1023
1024impl GridAutoFlow {
1025  fn direction(self) -> GridAutoFlow {
1026    self & GridAutoFlow::Column
1027  }
1028}
1029
1030impl<'i> Parse<'i> for GridAutoFlow {
1031  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1032    let mut flow = GridAutoFlow::Row;
1033
1034    macro_rules! match_dense {
1035      () => {
1036        if input.try_parse(|input| input.expect_ident_matching("dense")).is_ok() {
1037          flow |= GridAutoFlow::Dense;
1038        }
1039      };
1040    }
1041
1042    let location = input.current_source_location();
1043    let ident = input.expect_ident()?;
1044    match_ignore_ascii_case! { &ident,
1045      "row" => {
1046        match_dense!();
1047      },
1048      "column" => {
1049        flow = GridAutoFlow::Column;
1050        match_dense!();
1051      },
1052      "dense" => {
1053        let location = input.current_source_location();
1054        input.try_parse(|input| {
1055          let ident = input.expect_ident()?;
1056          match_ignore_ascii_case! { &ident,
1057            "row" => {},
1058            "column" => {
1059              flow = GridAutoFlow::Column;
1060            },
1061            _ => return Err(location.new_unexpected_token_error(
1062              cssparser::Token::Ident(ident.clone())
1063            ))
1064          }
1065          Ok(())
1066        })?;
1067        flow |= GridAutoFlow::Dense;
1068      },
1069      _ => return Err(location.new_unexpected_token_error(
1070        cssparser::Token::Ident(ident.clone())
1071      ))
1072    }
1073
1074    Ok(flow)
1075  }
1076}
1077
1078impl ToCss for GridAutoFlow {
1079  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1080    let s = if *self == GridAutoFlow::Row {
1081      "row"
1082    } else if *self == GridAutoFlow::Column {
1083      "column"
1084    } else if *self == GridAutoFlow::Row | GridAutoFlow::Dense {
1085      if dest.options().minify {
1086        "dense"
1087      } else {
1088        "row dense"
1089      }
1090    } else if *self == GridAutoFlow::Column | GridAutoFlow::Dense {
1091      "column dense"
1092    } else {
1093      unreachable!();
1094    };
1095
1096    dest.write_str(s)?;
1097
1098    Ok(())
1099  }
1100}
1101
1102/// A value for the [grid](https://drafts.csswg.org/css-grid-2/#grid-shorthand) shorthand property.
1103///
1104/// <'grid-template'> | <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? | [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
1105///
1106/// Explicit and implicit values may not be combined.
1107#[derive(Debug, Clone, PartialEq)]
1108#[cfg_attr(feature = "visitor", derive(Visit))]
1109#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1110#[cfg_attr(
1111  feature = "serde",
1112  derive(serde::Serialize, serde::Deserialize),
1113  serde(rename_all = "camelCase")
1114)]
1115#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1116pub struct Grid<'i> {
1117  /// Explicit grid template rows.
1118  #[cfg_attr(feature = "serde", serde(borrow))]
1119  pub rows: TrackSizing<'i>,
1120  /// Explicit grid template columns.
1121  pub columns: TrackSizing<'i>,
1122  /// Explicit grid template areas.
1123  pub areas: GridTemplateAreas,
1124  /// The grid auto rows.
1125  pub auto_rows: TrackSizeList,
1126  /// The grid auto columns.
1127  pub auto_columns: TrackSizeList,
1128  /// The grid auto flow.
1129  pub auto_flow: GridAutoFlow,
1130}
1131
1132impl<'i> Parse<'i> for Grid<'i> {
1133  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1134    // <'grid-template'>
1135    if let Ok(template) = input.try_parse(GridTemplate::parse) {
1136      Ok(Grid {
1137        rows: template.rows,
1138        columns: template.columns,
1139        areas: template.areas,
1140        auto_rows: TrackSizeList::default(),
1141        auto_columns: TrackSizeList::default(),
1142        auto_flow: GridAutoFlow::default(),
1143      })
1144
1145    // <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>?
1146    } else if let Ok(rows) = input.try_parse(TrackSizing::parse) {
1147      input.expect_delim('/')?;
1148      let auto_flow = parse_grid_auto_flow(input, GridAutoFlow::Column)?;
1149      let auto_columns = TrackSizeList::parse(input).unwrap_or_default();
1150      Ok(Grid {
1151        rows,
1152        columns: TrackSizing::None,
1153        areas: GridTemplateAreas::None,
1154        auto_rows: TrackSizeList::default(),
1155        auto_columns,
1156        auto_flow,
1157      })
1158
1159    // [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
1160    } else {
1161      let auto_flow = parse_grid_auto_flow(input, GridAutoFlow::Row)?;
1162      let auto_rows = input.try_parse(TrackSizeList::parse).unwrap_or_default();
1163      input.expect_delim('/')?;
1164      let columns = TrackSizing::parse(input)?;
1165      Ok(Grid {
1166        rows: TrackSizing::None,
1167        columns,
1168        areas: GridTemplateAreas::None,
1169        auto_rows,
1170        auto_columns: TrackSizeList::default(),
1171        auto_flow,
1172      })
1173    }
1174  }
1175}
1176
1177fn parse_grid_auto_flow<'i, 't>(
1178  input: &mut Parser<'i, 't>,
1179  flow: GridAutoFlow,
1180) -> Result<GridAutoFlow, ParseError<'i, ParserError<'i>>> {
1181  if input.try_parse(|input| input.expect_ident_matching("auto-flow")).is_ok() {
1182    if input.try_parse(|input| input.expect_ident_matching("dense")).is_ok() {
1183      Ok(flow | GridAutoFlow::Dense)
1184    } else {
1185      Ok(flow)
1186    }
1187  } else if input.try_parse(|input| input.expect_ident_matching("dense")).is_ok() {
1188    input.expect_ident_matching("auto-flow")?;
1189    Ok(flow | GridAutoFlow::Dense)
1190  } else {
1191    Err(input.new_error_for_next_token())
1192  }
1193}
1194
1195impl ToCss for Grid<'_> {
1196  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1197    let is_auto_initial = self.auto_rows == TrackSizeList::default()
1198      && self.auto_columns == TrackSizeList::default()
1199      && self.auto_flow == GridAutoFlow::default();
1200
1201    // Handle the case where areas is set but rows is None (auto-flow syntax).
1202    // In this case, output "auto-flow / columns" format.
1203    if self.areas != GridTemplateAreas::None && self.rows == TrackSizing::None {
1204      dest.write_str("auto-flow")?;
1205      if self.auto_flow.contains(GridAutoFlow::Dense) {
1206        dest.write_str(" dense")?;
1207      }
1208      if self.auto_rows != TrackSizeList::default() {
1209        dest.write_char(' ')?;
1210        self.auto_rows.to_css(dest)?;
1211      }
1212      dest.delim('/', true)?;
1213      self.columns.to_css(dest)?;
1214      return Ok(());
1215    }
1216
1217    // Handle the case where areas is set but columns is None (auto-flow column syntax).
1218    // In this case, output "rows / auto-flow" format.
1219    if self.areas != GridTemplateAreas::None
1220      && self.columns == TrackSizing::None
1221      && self.auto_flow.direction() == GridAutoFlow::Column
1222    {
1223      self.rows.to_css(dest)?;
1224      dest.delim('/', true)?;
1225      dest.write_str("auto-flow")?;
1226      if self.auto_flow.contains(GridAutoFlow::Dense) {
1227        dest.write_str(" dense")?;
1228      }
1229      if self.auto_columns != TrackSizeList::default() {
1230        dest.write_char(' ')?;
1231        self.auto_columns.to_css(dest)?;
1232      }
1233      return Ok(());
1234    }
1235
1236    if self.areas != GridTemplateAreas::None
1237      || (self.rows != TrackSizing::None && self.columns != TrackSizing::None)
1238      || (self.areas == GridTemplateAreas::None && is_auto_initial)
1239    {
1240      if !is_auto_initial {
1241        unreachable!("invalid grid shorthand: mixed implicit and explicit values");
1242      }
1243      let template = GridTemplate {
1244        rows: self.rows.clone(),
1245        columns: self.columns.clone(),
1246        areas: self.areas.clone(),
1247      };
1248      template.to_css_with_indent(dest, 6)?;
1249    } else if self.auto_flow.direction() == GridAutoFlow::Column {
1250      if self.columns != TrackSizing::None || self.auto_rows != TrackSizeList::default() {
1251        unreachable!("invalid grid shorthand: mixed implicit and explicit values");
1252      }
1253      self.rows.to_css(dest)?;
1254      dest.delim('/', true)?;
1255      dest.write_str("auto-flow")?;
1256      if self.auto_flow.contains(GridAutoFlow::Dense) {
1257        dest.write_str(" dense")?;
1258      }
1259      if self.auto_columns != TrackSizeList::default() {
1260        dest.write_char(' ')?;
1261        self.auto_columns.to_css(dest)?;
1262      }
1263    } else {
1264      if self.rows != TrackSizing::None || self.auto_columns != TrackSizeList::default() {
1265        unreachable!("invalid grid shorthand: mixed implicit and explicit values");
1266      }
1267      dest.write_str("auto-flow")?;
1268      if self.auto_flow.contains(GridAutoFlow::Dense) {
1269        dest.write_str(" dense")?;
1270      }
1271      if self.auto_rows != TrackSizeList::default() {
1272        dest.write_char(' ')?;
1273        self.auto_rows.to_css(dest)?;
1274      }
1275      dest.delim('/', true)?;
1276      self.columns.to_css(dest)?;
1277    }
1278
1279    Ok(())
1280  }
1281}
1282
1283impl<'i> Grid<'i> {
1284  #[inline]
1285  fn is_valid(
1286    rows: &TrackSizing,
1287    columns: &TrackSizing,
1288    areas: &GridTemplateAreas,
1289    auto_rows: &TrackSizeList,
1290    auto_columns: &TrackSizeList,
1291    auto_flow: &GridAutoFlow,
1292  ) -> bool {
1293    let default_track_size_list = TrackSizeList::default();
1294
1295    // When areas is set but rows is None (auto-flow syntax like "grid: auto-flow / 1fr"),
1296    // we can output the auto-flow shorthand along with "grid-template-areas" separately.
1297    // ⚠️ The case of `grid: 1fr / auto-flow` does not require such handling.
1298    if *areas != GridTemplateAreas::None && *rows == TrackSizing::None {
1299      return auto_flow.direction() == GridAutoFlow::Row;
1300    }
1301
1302    // The `grid` shorthand can either be fully explicit (e.g. same as `grid-template`),
1303    // or explicit along a single axis. If there are auto rows, then there cannot be explicit rows, for example.
1304    let is_template = GridTemplate::is_valid(rows, columns, areas);
1305    let is_explicit = *auto_rows == default_track_size_list
1306      && *auto_columns == default_track_size_list
1307      && *auto_flow == GridAutoFlow::default();
1308    // grid-auto-flow: row shorthand syntax:
1309    // [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
1310    let is_auto_rows = auto_flow.direction() == GridAutoFlow::Row
1311      && *rows == TrackSizing::None
1312      && *auto_columns == default_track_size_list;
1313    // grid-auto-flow: column shorthand syntax:
1314    // <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>?
1315    let is_auto_columns = auto_flow.direction() == GridAutoFlow::Column
1316      && *columns == TrackSizing::None
1317      && *auto_rows == default_track_size_list;
1318
1319    (is_template && is_explicit) || is_auto_rows || is_auto_columns
1320  }
1321}
1322
1323// TODO: shorthand `grid: auto-flow 1fr / 100px` https://drafts.csswg.org/css-grid/#example-dec34e0f
1324impl_shorthand! {
1325  Grid(Grid<'i>) {
1326    rows: [GridTemplateRows],
1327    columns: [GridTemplateColumns],
1328    areas: [GridTemplateAreas],
1329    auto_rows: [GridAutoRows],
1330    auto_columns: [GridAutoColumns],
1331    auto_flow: [GridAutoFlow],
1332  }
1333
1334  fn is_valid(grid) {
1335    Grid::is_valid(&grid.rows, &grid.columns, &grid.areas, &grid.auto_rows, &grid.auto_columns, &grid.auto_flow)
1336  }
1337}
1338
1339/// A [`<grid-line>`](https://drafts.csswg.org/css-grid-2/#typedef-grid-row-start-grid-line) value,
1340/// used in the `grid-row-start`, `grid-row-end`, `grid-column-start`, and `grid-column-end` properties.
1341#[derive(Debug, Clone, PartialEq)]
1342#[cfg_attr(feature = "visitor", derive(Visit))]
1343#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1344#[cfg_attr(
1345  feature = "serde",
1346  derive(serde::Serialize, serde::Deserialize),
1347  serde(tag = "type", rename_all = "kebab-case")
1348)]
1349#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1350pub enum GridLine<'i> {
1351  /// Automatic placement.
1352  Auto,
1353  /// A named grid area name (automatically postfixed by `-start` or `-end`), or and explicit grid line name.
1354  Area {
1355    /// A grid area name.
1356    name: CustomIdent<'i>,
1357  },
1358  /// The Nth grid line, optionally filtered by line name. Negative numbers count backwards from the end.
1359  Line {
1360    /// A line number.
1361    index: CSSInteger,
1362    /// A line name to filter by.
1363    #[cfg_attr(feature = "serde", serde(borrow))]
1364    name: Option<CustomIdent<'i>>,
1365  },
1366  /// A grid span based on the Nth grid line from the opposite edge, optionally filtered by line name.
1367  Span {
1368    /// A line number.
1369    index: CSSInteger,
1370    /// A line name to filter by.
1371    name: Option<CustomIdent<'i>>,
1372  },
1373}
1374
1375impl<'i> Parse<'i> for GridLine<'i> {
1376  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1377    if input.try_parse(|input| input.expect_ident_matching("auto")).is_ok() {
1378      return Ok(GridLine::Auto);
1379    }
1380
1381    if input.try_parse(|input| input.expect_ident_matching("span")).is_ok() {
1382      // TODO: is calc() supported here??
1383      let (index, name) = if let Ok(line_number) = input.try_parse(CSSInteger::parse) {
1384        let ident = input.try_parse(CustomIdent::parse).ok();
1385        (line_number, ident)
1386      } else if let Ok(ident) = input.try_parse(CustomIdent::parse) {
1387        let line_number = input.try_parse(CSSInteger::parse).unwrap_or(1);
1388        (line_number, Some(ident))
1389      } else {
1390        return Err(input.new_custom_error(ParserError::InvalidDeclaration));
1391      };
1392
1393      if index == 0 {
1394        return Err(input.new_custom_error(ParserError::InvalidDeclaration));
1395      }
1396
1397      return Ok(GridLine::Span { index, name });
1398    }
1399
1400    if let Ok(index) = input.try_parse(CSSInteger::parse) {
1401      if index == 0 {
1402        return Err(input.new_custom_error(ParserError::InvalidDeclaration));
1403      }
1404      let name = input.try_parse(CustomIdent::parse).ok();
1405      return Ok(GridLine::Line { index, name });
1406    }
1407
1408    let name = CustomIdent::parse(input)?;
1409    if let Ok(index) = input.try_parse(CSSInteger::parse) {
1410      if index == 0 {
1411        return Err(input.new_custom_error(ParserError::InvalidDeclaration));
1412      }
1413      return Ok(GridLine::Line {
1414        index,
1415        name: Some(name),
1416      });
1417    }
1418
1419    Ok(GridLine::Area { name })
1420  }
1421}
1422
1423impl ToCss for GridLine<'_> {
1424  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1425    match self {
1426      GridLine::Auto => {
1427        dest.write_str("auto")?;
1428        Ok(())
1429      }
1430      GridLine::Area { name } => write_ident(&name.0, dest),
1431      GridLine::Line { index, name } => {
1432        index.to_css(dest)?;
1433        if let Some(id) = name {
1434          dest.write_char(' ')?;
1435          write_ident(&id.0, dest)?;
1436        }
1437        Ok(())
1438      }
1439      GridLine::Span { index, name } => {
1440        dest.write_str("span ")?;
1441        if *index != 1 || name.is_none() {
1442          index.to_css(dest)?;
1443          if name.is_some() {
1444            dest.write_char(' ')?;
1445          }
1446        }
1447
1448        if let Some(id) = name {
1449          write_ident(&id.0, dest)?;
1450        }
1451        Ok(())
1452      }
1453    }
1454  }
1455}
1456
1457impl<'i> GridLine<'i> {
1458  fn default_end_value(&self) -> GridLine<'i> {
1459    if matches!(self, GridLine::Area { .. }) {
1460      self.clone()
1461    } else {
1462      GridLine::Auto
1463    }
1464  }
1465
1466  fn can_omit_end(&self, end: &GridLine) -> bool {
1467    if let GridLine::Area { name: start_id } = &self {
1468      matches!(end, GridLine::Area { name: end_id } if end_id == start_id)
1469    } else if matches!(end, GridLine::Auto) {
1470      true
1471    } else {
1472      false
1473    }
1474  }
1475}
1476
1477macro_rules! impl_grid_placement {
1478  ($name: ident) => {
1479    impl<'i> Parse<'i> for $name<'i> {
1480      fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1481        let start = GridLine::parse(input)?;
1482        let end = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
1483          GridLine::parse(input)?
1484        } else {
1485          start.default_end_value()
1486        };
1487
1488        Ok($name { start, end })
1489      }
1490    }
1491
1492    impl ToCss for $name<'_> {
1493      fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1494        self.start.to_css(dest)?;
1495
1496        if !self.start.can_omit_end(&self.end) {
1497          dest.delim('/', true)?;
1498          self.end.to_css(dest)?;
1499        }
1500        Ok(())
1501      }
1502    }
1503  };
1504}
1505
1506define_shorthand! {
1507  /// A value for the [grid-row](https://drafts.csswg.org/css-grid-2/#propdef-grid-row) shorthand property.
1508  /// <grid-line> [ / <grid-line> ]?
1509  pub struct GridRow<'i> {
1510    /// The starting line.
1511    #[cfg_attr(feature = "serde", serde(borrow))]
1512    start: GridRowStart(GridLine<'i>),
1513    /// The ending line.
1514    end: GridRowEnd(GridLine<'i>),
1515  }
1516}
1517
1518define_shorthand! {
1519  /// A value for the [grid-column](https://drafts.csswg.org/css-grid-2/#propdef-grid-column) shorthand property.
1520  /// <grid-line> [ / <grid-line> ]?
1521  pub struct GridColumn<'i> {
1522    /// The starting line.
1523    #[cfg_attr(feature = "serde", serde(borrow))]
1524    start: GridColumnStart(GridLine<'i>),
1525    /// The ending line.
1526    end: GridColumnEnd(GridLine<'i>),
1527  }
1528}
1529
1530impl_grid_placement!(GridRow);
1531impl_grid_placement!(GridColumn);
1532
1533define_shorthand! {
1534  /// A value for the [grid-area](https://drafts.csswg.org/css-grid-2/#propdef-grid-area) shorthand property.
1535  /// <grid-line> [ / <grid-line> ]{0,3}
1536  pub struct GridArea<'i> {
1537    /// The grid row start placement.
1538    #[cfg_attr(feature = "serde", serde(borrow))]
1539    row_start: GridRowStart(GridLine<'i>),
1540    /// The grid column start placement.
1541    column_start: GridColumnStart(GridLine<'i>),
1542    /// The grid row end placement.
1543    row_end: GridRowEnd(GridLine<'i>),
1544    /// The grid column end placement.
1545    column_end: GridColumnEnd(GridLine<'i>),
1546  }
1547}
1548
1549impl<'i> Parse<'i> for GridArea<'i> {
1550  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1551    let row_start = GridLine::parse(input)?;
1552    let column_start = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
1553      GridLine::parse(input)?
1554    } else {
1555      let opposite = row_start.default_end_value();
1556      return Ok(GridArea {
1557        row_start,
1558        column_start: opposite.clone(),
1559        row_end: opposite.clone(),
1560        column_end: opposite,
1561      });
1562    };
1563
1564    let row_end = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
1565      GridLine::parse(input)?
1566    } else {
1567      let row_end = row_start.default_end_value();
1568      let column_end = column_start.default_end_value();
1569      return Ok(GridArea {
1570        row_start,
1571        column_start,
1572        row_end,
1573        column_end,
1574      });
1575    };
1576
1577    let column_end = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
1578      GridLine::parse(input)?
1579    } else {
1580      let column_end = column_start.default_end_value();
1581      return Ok(GridArea {
1582        row_start,
1583        column_start,
1584        row_end,
1585        column_end,
1586      });
1587    };
1588
1589    Ok(GridArea {
1590      row_start,
1591      column_start,
1592      row_end,
1593      column_end,
1594    })
1595  }
1596}
1597
1598impl ToCss for GridArea<'_> {
1599  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1600    self.row_start.to_css(dest)?;
1601
1602    let can_omit_column_end = self.column_start.can_omit_end(&self.column_end);
1603    let can_omit_row_end = can_omit_column_end && self.row_start.can_omit_end(&self.row_end);
1604    let can_omit_column_start = can_omit_row_end && self.row_start.can_omit_end(&self.column_start);
1605
1606    if !can_omit_column_start {
1607      dest.delim('/', true)?;
1608      self.column_start.to_css(dest)?;
1609    }
1610
1611    if !can_omit_row_end {
1612      dest.delim('/', true)?;
1613      self.row_end.to_css(dest)?;
1614    }
1615
1616    if !can_omit_column_end {
1617      dest.delim('/', true)?;
1618      self.column_end.to_css(dest)?;
1619    }
1620
1621    Ok(())
1622  }
1623}
1624
1625#[derive(Default, Debug)]
1626pub(crate) struct GridHandler<'i> {
1627  rows: Option<TrackSizing<'i>>,
1628  columns: Option<TrackSizing<'i>>,
1629  areas: Option<GridTemplateAreas>,
1630  auto_rows: Option<TrackSizeList>,
1631  auto_columns: Option<TrackSizeList>,
1632  auto_flow: Option<GridAutoFlow>,
1633  row_start: Option<GridLine<'i>>,
1634  column_start: Option<GridLine<'i>>,
1635  row_end: Option<GridLine<'i>>,
1636  column_end: Option<GridLine<'i>>,
1637  has_any: bool,
1638}
1639
1640impl<'i> PropertyHandler<'i> for GridHandler<'i> {
1641  fn handle_property(
1642    &mut self,
1643    property: &Property<'i>,
1644    dest: &mut DeclarationList<'i>,
1645    context: &mut PropertyHandlerContext<'i, '_>,
1646  ) -> bool {
1647    use Property::*;
1648
1649    match property {
1650      GridTemplateColumns(columns) => self.columns = Some(columns.clone()),
1651      GridTemplateRows(rows) => self.rows = Some(rows.clone()),
1652      GridTemplateAreas(areas) => self.areas = Some(areas.clone()),
1653      GridAutoColumns(auto_columns) => self.auto_columns = Some(auto_columns.clone()),
1654      GridAutoRows(auto_rows) => self.auto_rows = Some(auto_rows.clone()),
1655      GridAutoFlow(auto_flow) => self.auto_flow = Some(auto_flow.clone()),
1656      GridTemplate(template) => {
1657        self.rows = Some(template.rows.clone());
1658        self.columns = Some(template.columns.clone());
1659        self.areas = Some(template.areas.clone());
1660      }
1661      Grid(grid) => {
1662        self.rows = Some(grid.rows.clone());
1663        self.columns = Some(grid.columns.clone());
1664        self.areas = Some(grid.areas.clone());
1665        self.auto_rows = Some(grid.auto_rows.clone());
1666        self.auto_columns = Some(grid.auto_columns.clone());
1667        self.auto_flow = Some(grid.auto_flow.clone());
1668      }
1669      GridRowStart(row_start) => self.row_start = Some(row_start.clone()),
1670      GridRowEnd(row_end) => self.row_end = Some(row_end.clone()),
1671      GridColumnStart(column_start) => self.column_start = Some(column_start.clone()),
1672      GridColumnEnd(column_end) => self.column_end = Some(column_end.clone()),
1673      GridRow(row) => {
1674        self.row_start = Some(row.start.clone());
1675        self.row_end = Some(row.end.clone());
1676      }
1677      GridColumn(column) => {
1678        self.column_start = Some(column.start.clone());
1679        self.column_end = Some(column.end.clone());
1680      }
1681      GridArea(area) => {
1682        self.row_start = Some(area.row_start.clone());
1683        self.row_end = Some(area.row_end.clone());
1684        self.column_start = Some(area.column_start.clone());
1685        self.column_end = Some(area.column_end.clone());
1686      }
1687      Unparsed(val) if is_grid_property(&val.property_id) => {
1688        self.finalize(dest, context);
1689        dest.push(property.clone());
1690      }
1691      _ => return false,
1692    }
1693
1694    self.has_any = true;
1695    true
1696  }
1697
1698  fn finalize(&mut self, dest: &mut DeclarationList<'i>, _: &mut PropertyHandlerContext<'i, '_>) {
1699    if !self.has_any {
1700      return;
1701    }
1702
1703    self.has_any = false;
1704
1705    let mut rows = std::mem::take(&mut self.rows);
1706    let mut columns = std::mem::take(&mut self.columns);
1707    let mut areas = std::mem::take(&mut self.areas);
1708    let mut auto_rows = std::mem::take(&mut self.auto_rows);
1709    let mut auto_columns = std::mem::take(&mut self.auto_columns);
1710    let mut auto_flow = std::mem::take(&mut self.auto_flow);
1711    let mut row_start = std::mem::take(&mut self.row_start);
1712    let mut row_end = std::mem::take(&mut self.row_end);
1713    let mut column_start = std::mem::take(&mut self.column_start);
1714    let mut column_end = std::mem::take(&mut self.column_end);
1715
1716    if let (Some(rows_val), Some(columns_val), Some(areas_val)) = (&rows, &columns, &areas) {
1717      let mut has_template = true;
1718      if let (Some(auto_rows_val), Some(auto_columns_val), Some(auto_flow_val)) =
1719        (&auto_rows, &auto_columns, &auto_flow)
1720      {
1721        // The `grid` shorthand can either be fully explicit (e.g. same as `grid-template`),
1722        // or explicit along a single axis. If there are auto rows, then there cannot be explicit rows, for example.
1723        if Grid::is_valid(
1724          rows_val,
1725          columns_val,
1726          areas_val,
1727          auto_rows_val,
1728          auto_columns_val,
1729          auto_flow_val,
1730        ) {
1731          let needs_separate_areas = *areas_val != GridTemplateAreas::None
1732            && ((*rows_val == TrackSizing::None && auto_flow_val.direction() == GridAutoFlow::Row)
1733              || (*columns_val == TrackSizing::None && auto_flow_val.direction() == GridAutoFlow::Column));
1734
1735          // Pad areas with "." for missing rows. But don't pad if we're using auto-flow syntax,
1736          // because grid-template-areas should remain as-is in that case.
1737          // Use tuple to avoid double cloning when needs_separate_areas is true.
1738          let (areas_for_grid, areas_for_output) = if needs_separate_areas {
1739            // Take the original areas directly to avoid cloning when needs_separate_areas is true
1740            (areas_val.clone(), Some(areas_val.clone()))
1741          } else {
1742            (GridHandler::pad_grid_template_areas(rows_val, areas_val.clone()), None)
1743          };
1744
1745          dest.push(Property::Grid(Grid {
1746            rows: rows_val.clone(),
1747            columns: columns_val.clone(),
1748            areas: areas_for_grid,
1749            auto_rows: auto_rows_val.clone(),
1750            auto_columns: auto_columns_val.clone(),
1751            auto_flow: auto_flow_val.clone(),
1752          }));
1753
1754          has_template = false;
1755          auto_rows = None;
1756          auto_columns = None;
1757          auto_flow = None;
1758
1759          // When areas is set but rows/columns is None (auto-flow syntax), also output
1760          // grid-template-areas separately since grid shorthand can't represent this combination.
1761          if let Some(areas) = areas_for_output {
1762            dest.push(Property::GridTemplateAreas(areas));
1763          }
1764        }
1765      }
1766
1767      // The `grid-template` shorthand supports only explicit track values (i.e. no `repeat()`)
1768      // combined with grid-template-areas. If there are no areas, then any track values are allowed.
1769      if has_template && GridTemplate::is_valid(rows_val, columns_val, areas_val) {
1770        // Pad areas with "." for missing rows
1771        let padded_areas = GridHandler::pad_grid_template_areas(rows_val, areas_val.clone());
1772
1773        dest.push(Property::GridTemplate(GridTemplate {
1774          rows: rows_val.clone(),
1775          columns: columns_val.clone(),
1776          areas: padded_areas,
1777        }));
1778
1779        has_template = false;
1780      }
1781
1782      if !has_template {
1783        rows = None;
1784        columns = None;
1785        areas = None;
1786      }
1787    }
1788
1789    if row_start.is_some() && row_end.is_some() && column_start.is_some() && column_end.is_some() {
1790      dest.push(Property::GridArea(GridArea {
1791        row_start: std::mem::take(&mut row_start).unwrap(),
1792        row_end: std::mem::take(&mut row_end).unwrap(),
1793        column_start: std::mem::take(&mut column_start).unwrap(),
1794        column_end: std::mem::take(&mut column_end).unwrap(),
1795      }))
1796    } else {
1797      if row_start.is_some() && row_end.is_some() {
1798        dest.push(Property::GridRow(GridRow {
1799          start: std::mem::take(&mut row_start).unwrap(),
1800          end: std::mem::take(&mut row_end).unwrap(),
1801        }))
1802      }
1803
1804      if column_start.is_some() && column_end.is_some() {
1805        dest.push(Property::GridColumn(GridColumn {
1806          start: std::mem::take(&mut column_start).unwrap(),
1807          end: std::mem::take(&mut column_end).unwrap(),
1808        }))
1809      }
1810    }
1811
1812    macro_rules! single_property {
1813      ($prop: ident, $key: ident) => {
1814        if let Some(val) = $key {
1815          dest.push(Property::$prop(val))
1816        }
1817      };
1818    }
1819
1820    single_property!(GridTemplateRows, rows);
1821    single_property!(GridTemplateColumns, columns);
1822    single_property!(GridTemplateAreas, areas);
1823    single_property!(GridAutoRows, auto_rows);
1824    single_property!(GridAutoColumns, auto_columns);
1825    single_property!(GridAutoFlow, auto_flow);
1826    single_property!(GridRowStart, row_start);
1827    single_property!(GridRowEnd, row_end);
1828    single_property!(GridColumnStart, column_start);
1829    single_property!(GridColumnEnd, column_end);
1830  }
1831}
1832
1833/// Pads grid template areas with "." (None) for missing rows.
1834/// All the remaining unnamed areas in a grid can be referred using null cell
1835/// tokens. A null cell token is a sequence of one or more . (U+002E FULL STOP)
1836/// characters, e.g., ., ..., or ..... etc. A null cell token can be used to
1837/// create empty spaces in the grid.
1838/// Spec: https://drafts.csswg.org/css-grid/#ref-for-string-value①
1839impl GridHandler<'_> {
1840  fn pad_grid_template_areas(rows: &TrackSizing, areas: GridTemplateAreas) -> GridTemplateAreas {
1841    match (rows, areas) {
1842      (TrackSizing::TrackList(rows_list), GridTemplateAreas::Areas { columns, areas }) => {
1843        let rows_count = rows_list.items.len();
1844        let areas_rows_count = areas.len() / columns as usize;
1845        if areas_rows_count < rows_count {
1846          let mut padded_areas = areas;
1847          // Fill each missing row with "." (represented as None)
1848          for _ in areas_rows_count..rows_count {
1849            for _ in 0..columns {
1850              padded_areas.push(None);
1851            }
1852          }
1853          GridTemplateAreas::Areas {
1854            columns,
1855            areas: padded_areas,
1856          }
1857        } else {
1858          GridTemplateAreas::Areas { columns, areas }
1859        }
1860      }
1861      (_, areas) => areas,
1862    }
1863  }
1864}
1865
1866#[inline]
1867fn is_grid_property(property_id: &PropertyId) -> bool {
1868  match property_id {
1869    PropertyId::GridTemplateColumns
1870    | PropertyId::GridTemplateRows
1871    | PropertyId::GridTemplateAreas
1872    | PropertyId::GridAutoColumns
1873    | PropertyId::GridAutoRows
1874    | PropertyId::GridAutoFlow
1875    | PropertyId::GridTemplate
1876    | PropertyId::Grid
1877    | PropertyId::GridRowStart
1878    | PropertyId::GridRowEnd
1879    | PropertyId::GridColumnStart
1880    | PropertyId::GridColumnEnd
1881    | PropertyId::GridRow
1882    | PropertyId::GridColumn
1883    | PropertyId::GridArea => true,
1884    _ => false,
1885  }
1886}