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