Skip to main content

rspack_lightningcss/properties/
align.rs

1//! CSS properties related to box alignment.
2
3use super::flex::{BoxAlign, BoxPack, FlexAlign, FlexItemAlign, FlexLinePack, FlexPack};
4use super::{Property, PropertyId};
5use crate::compat;
6use crate::context::PropertyHandlerContext;
7use crate::declaration::{DeclarationBlock, DeclarationList};
8use crate::error::{ParserError, PrinterError};
9use crate::macros::*;
10use crate::prefixes::{is_flex_2009, Feature};
11use crate::traits::{FromStandard, Parse, PropertyHandler, Shorthand, ToCss};
12use crate::values::length::LengthPercentage;
13use crate::values::number::NonNegative;
14use crate::vendor_prefix::VendorPrefix;
15#[cfg(feature = "visitor")]
16use crate::visitor::Visit;
17use cssparser::*;
18
19#[cfg(feature = "serde")]
20use crate::serialization::ValueWrapper;
21
22/// A [`<baseline-position>`](https://www.w3.org/TR/css-align-3/#typedef-baseline-position) value,
23/// as used in the alignment properties.
24#[derive(Debug, Clone, PartialEq)]
25#[cfg_attr(feature = "visitor", derive(Visit))]
26#[cfg_attr(
27  feature = "serde",
28  derive(serde::Serialize, serde::Deserialize),
29  serde(rename_all = "kebab-case")
30)]
31#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
32pub enum BaselinePosition {
33  /// The first baseline.
34  First,
35  /// The last baseline.
36  Last,
37}
38
39impl<'i> Parse<'i> for BaselinePosition {
40  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
41    let location = input.current_source_location();
42    let ident = input.expect_ident()?;
43    match_ignore_ascii_case! { &*ident,
44      "baseline" => Ok(BaselinePosition::First),
45      "first" => {
46        input.expect_ident_matching("baseline")?;
47        Ok(BaselinePosition::First)
48      },
49      "last" => {
50        input.expect_ident_matching("baseline")?;
51        Ok(BaselinePosition::Last)
52      },
53      _ => Err(location.new_unexpected_token_error(
54        cssparser::Token::Ident(ident.clone())
55      ))
56    }
57  }
58}
59
60impl ToCss for BaselinePosition {
61  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
62    match self {
63      BaselinePosition::First => dest.write_str("baseline")?,
64      BaselinePosition::Last => dest.write_str("last baseline")?,
65    };
66    Ok(())
67  }
68}
69
70enum_property! {
71  /// A [`<content-distribution>`](https://www.w3.org/TR/css-align-3/#typedef-content-distribution) value.
72  pub enum ContentDistribution {
73    /// Items are spaced evenly, with the first and last items against the edge of the container.
74    SpaceBetween,
75    /// Items are spaced evenly, with half-size spaces at the start and end.
76    SpaceAround,
77    /// Items are spaced evenly, with full-size spaces at the start and end.
78    SpaceEvenly,
79    /// Items are stretched evenly to fill free space.
80    Stretch,
81  }
82}
83
84enum_property! {
85  /// An [`<overflow-position>`](https://www.w3.org/TR/css-align-3/#typedef-overflow-position) value.
86  pub enum OverflowPosition {
87    /// If the size of the alignment subject overflows the alignment container,
88    /// the alignment subject is instead aligned as if the alignment mode were start.
89    Safe,
90    /// Regardless of the relative sizes of the alignment subject and alignment
91    /// container, the given alignment value is honored.
92    Unsafe,
93  }
94}
95
96enum_property! {
97  /// A [`<content-position>`](https://www.w3.org/TR/css-align-3/#typedef-content-position) value.
98  pub enum ContentPosition {
99    /// Content is centered within the container.
100    Center,
101    /// Content is aligned to the start of the container.
102    Start,
103    /// Content is aligned to the end of the container.
104    End,
105    /// Same as `start` when within a flexbox container.
106    FlexStart,
107    /// Same as `end` when within a flexbox container.
108    FlexEnd,
109  }
110}
111
112/// A value for the [align-content](https://www.w3.org/TR/css-align-3/#propdef-align-content) property.
113#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
114#[cfg_attr(feature = "visitor", derive(Visit))]
115#[cfg_attr(
116  feature = "serde",
117  derive(serde::Serialize, serde::Deserialize),
118  serde(tag = "type", rename_all = "kebab-case")
119)]
120#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
121#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
122pub enum AlignContent {
123  /// Default alignment.
124  Normal,
125  /// A baseline position.
126  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<BaselinePosition>"))]
127  BaselinePosition(BaselinePosition),
128  /// A content distribution keyword.
129  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<ContentDistribution>"))]
130  ContentDistribution(ContentDistribution),
131  /// A content position keyword.
132  ContentPosition {
133    /// An overflow alignment mode.
134    overflow: Option<OverflowPosition>,
135    /// A content position keyword.
136    value: ContentPosition,
137  },
138}
139
140/// A value for the [justify-content](https://www.w3.org/TR/css-align-3/#propdef-justify-content) property.
141#[derive(Debug, Clone, PartialEq)]
142#[cfg_attr(feature = "visitor", derive(Visit))]
143#[cfg_attr(
144  feature = "serde",
145  derive(serde::Serialize, serde::Deserialize),
146  serde(tag = "type", rename_all = "kebab-case")
147)]
148#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
149#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
150pub enum JustifyContent {
151  /// Default justification.
152  Normal,
153  /// A content distribution keyword.
154  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<ContentDistribution>"))]
155  ContentDistribution(ContentDistribution),
156  /// A content position keyword.
157  ContentPosition {
158    /// A content position keyword.
159    value: ContentPosition,
160    /// An overflow alignment mode.
161    overflow: Option<OverflowPosition>,
162  },
163  /// Justify to the left.
164  Left {
165    /// An overflow alignment mode.
166    overflow: Option<OverflowPosition>,
167  },
168  /// Justify to the right.
169  Right {
170    /// An overflow alignment mode.
171    overflow: Option<OverflowPosition>,
172  },
173}
174
175impl<'i> Parse<'i> for JustifyContent {
176  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
177    if input.try_parse(|input| input.expect_ident_matching("normal")).is_ok() {
178      return Ok(JustifyContent::Normal);
179    }
180
181    if let Ok(val) = input.try_parse(ContentDistribution::parse) {
182      return Ok(JustifyContent::ContentDistribution(val));
183    }
184
185    let overflow = input.try_parse(OverflowPosition::parse).ok();
186    if let Ok(content_position) = input.try_parse(ContentPosition::parse) {
187      return Ok(JustifyContent::ContentPosition {
188        overflow,
189        value: content_position,
190      });
191    }
192
193    let location = input.current_source_location();
194    let ident = input.expect_ident()?;
195    match_ignore_ascii_case! { &*ident,
196      "left" => Ok(JustifyContent::Left { overflow }),
197      "right" => Ok(JustifyContent::Right { overflow }),
198      _ => Err(location.new_unexpected_token_error(
199        cssparser::Token::Ident(ident.clone())
200      ))
201    }
202  }
203}
204
205impl ToCss for JustifyContent {
206  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
207    match self {
208      JustifyContent::Normal => dest.write_str("normal")?,
209      JustifyContent::ContentDistribution(value) => value.to_css(dest)?,
210      JustifyContent::ContentPosition { overflow, value } => {
211        if let Some(overflow) = overflow {
212          overflow.to_css(dest)?;
213          dest.write_str(" ")?;
214        }
215
216        value.to_css(dest)?;
217      }
218      JustifyContent::Left { overflow } => {
219        if let Some(overflow) = overflow {
220          overflow.to_css(dest)?;
221          dest.write_str(" ")?;
222        }
223
224        dest.write_str("left")?;
225      }
226      JustifyContent::Right { overflow } => {
227        if let Some(overflow) = overflow {
228          overflow.to_css(dest)?;
229          dest.write_str(" ")?;
230        }
231
232        dest.write_str("right")?;
233      }
234    };
235    Ok(())
236  }
237}
238
239define_shorthand! {
240  /// A value for the [place-content](https://www.w3.org/TR/css-align-3/#place-content) shorthand property.
241  pub struct PlaceContent {
242    /// The content alignment.
243    align: AlignContent(AlignContent, VendorPrefix),
244    /// The content justification.
245    justify: JustifyContent(JustifyContent, VendorPrefix),
246  }
247}
248
249impl<'i> Parse<'i> for PlaceContent {
250  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
251    let align = AlignContent::parse(input)?;
252    let justify = match input.try_parse(JustifyContent::parse) {
253      Ok(j) => j,
254      Err(_) => {
255        // The second value is assigned to justify-content; if omitted, it is copied
256        // from the first value, unless that value is a <baseline-position> in which
257        // case it is defaulted to start.
258        match align {
259          AlignContent::BaselinePosition(_) => JustifyContent::ContentPosition {
260            overflow: None,
261            value: ContentPosition::Start,
262          },
263          AlignContent::Normal => JustifyContent::Normal,
264          AlignContent::ContentDistribution(value) => JustifyContent::ContentDistribution(value.clone()),
265          AlignContent::ContentPosition { overflow, value } => JustifyContent::ContentPosition {
266            overflow: overflow.clone(),
267            value: value.clone(),
268          },
269        }
270      }
271    };
272
273    Ok(PlaceContent { align, justify })
274  }
275}
276
277impl ToCss for PlaceContent {
278  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
279    self.align.to_css(dest)?;
280    let is_equal = match self.justify {
281      JustifyContent::Normal if self.align == AlignContent::Normal => true,
282      JustifyContent::ContentDistribution(d) if matches!(self.align, AlignContent::ContentDistribution(d2) if d == d2) => {
283        true
284      }
285      JustifyContent::ContentPosition { overflow: o, value: c } if matches!(self.align, AlignContent::ContentPosition { overflow: o2, value: c2 } if o == o2 && c == c2) => {
286        true
287      }
288      _ => false,
289    };
290
291    if !is_equal {
292      dest.write_str(" ")?;
293      self.justify.to_css(dest)?;
294    }
295
296    Ok(())
297  }
298}
299
300enum_property! {
301  /// A [`<self-position>`](https://www.w3.org/TR/css-align-3/#typedef-self-position) value.
302  pub enum SelfPosition {
303    /// Item is centered within the container.
304    Center,
305    /// Item is aligned to the start of the container.
306    Start,
307    /// Item is aligned to the end of the container.
308    End,
309    /// Item is aligned to the edge of the container corresponding to the start side of the item.
310    SelfStart,
311    /// Item is aligned to the edge of the container corresponding to the end side of the item.
312    SelfEnd,
313    /// Item  is aligned to the start of the container, within flexbox layouts.
314    FlexStart,
315    /// Item  is aligned to the end of the container, within flexbox layouts.
316    FlexEnd,
317  }
318}
319
320/// A value for the [align-self](https://www.w3.org/TR/css-align-3/#align-self-property) property.
321#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
322#[cfg_attr(feature = "visitor", derive(Visit))]
323#[cfg_attr(
324  feature = "serde",
325  derive(serde::Serialize, serde::Deserialize),
326  serde(tag = "type", rename_all = "kebab-case")
327)]
328#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
329#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
330pub enum AlignSelf {
331  /// Automatic alignment.
332  Auto,
333  /// Default alignment.
334  Normal,
335  /// Item is stretched.
336  Stretch,
337  /// A baseline position keyword.
338  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<BaselinePosition>"))]
339  BaselinePosition(BaselinePosition),
340  /// A self position keyword.
341  SelfPosition {
342    /// An overflow alignment mode.
343    overflow: Option<OverflowPosition>,
344    /// A self position keyword.
345    value: SelfPosition,
346  },
347}
348
349/// A value for the [justify-self](https://www.w3.org/TR/css-align-3/#justify-self-property) property.
350#[derive(Debug, Clone, PartialEq)]
351#[cfg_attr(feature = "visitor", derive(Visit))]
352#[cfg_attr(
353  feature = "serde",
354  derive(serde::Serialize, serde::Deserialize),
355  serde(tag = "type", rename_all = "kebab-case")
356)]
357#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
358#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
359pub enum JustifySelf {
360  /// Automatic justification.
361  Auto,
362  /// Default justification.
363  Normal,
364  /// Item is stretched.
365  Stretch,
366  /// A baseline position keyword.
367  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<BaselinePosition>"))]
368  BaselinePosition(BaselinePosition),
369  /// A self position keyword.
370  SelfPosition {
371    /// A self position keyword.
372    value: SelfPosition,
373    /// An overflow alignment mode.
374    overflow: Option<OverflowPosition>,
375  },
376  /// Item is justified to the left.
377  Left {
378    /// An overflow alignment mode.
379    overflow: Option<OverflowPosition>,
380  },
381  /// Item is justified to the right.
382  Right {
383    /// An overflow alignment mode.
384    overflow: Option<OverflowPosition>,
385  },
386}
387
388impl<'i> Parse<'i> for JustifySelf {
389  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
390    if input.try_parse(|input| input.expect_ident_matching("auto")).is_ok() {
391      return Ok(JustifySelf::Auto);
392    }
393
394    if input.try_parse(|input| input.expect_ident_matching("normal")).is_ok() {
395      return Ok(JustifySelf::Normal);
396    }
397
398    if input.try_parse(|input| input.expect_ident_matching("stretch")).is_ok() {
399      return Ok(JustifySelf::Stretch);
400    }
401
402    if let Ok(val) = input.try_parse(BaselinePosition::parse) {
403      return Ok(JustifySelf::BaselinePosition(val));
404    }
405
406    let overflow = input.try_parse(OverflowPosition::parse).ok();
407    if let Ok(value) = input.try_parse(SelfPosition::parse) {
408      return Ok(JustifySelf::SelfPosition { overflow, value });
409    }
410
411    let location = input.current_source_location();
412    let ident = input.expect_ident()?;
413    match_ignore_ascii_case! { &*ident,
414      "left" => Ok(JustifySelf::Left { overflow }),
415      "right" => Ok(JustifySelf::Right { overflow }),
416      _ => Err(location.new_unexpected_token_error(
417        cssparser::Token::Ident(ident.clone())
418      ))
419    }
420  }
421}
422
423impl ToCss for JustifySelf {
424  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
425    match self {
426      JustifySelf::Auto => dest.write_str("auto")?,
427      JustifySelf::Normal => dest.write_str("normal")?,
428      JustifySelf::Stretch => dest.write_str("stretch")?,
429      JustifySelf::BaselinePosition(val) => val.to_css(dest)?,
430      JustifySelf::SelfPosition { overflow, value } => {
431        if let Some(overflow) = overflow {
432          overflow.to_css(dest)?;
433          dest.write_str(" ")?;
434        }
435
436        value.to_css(dest)?;
437      }
438      JustifySelf::Left { overflow } => {
439        if let Some(overflow) = overflow {
440          overflow.to_css(dest)?;
441          dest.write_str(" ")?;
442        }
443
444        dest.write_str("left")?;
445      }
446      JustifySelf::Right { overflow } => {
447        if let Some(overflow) = overflow {
448          overflow.to_css(dest)?;
449          dest.write_str(" ")?;
450        }
451
452        dest.write_str("right")?;
453      }
454    };
455    Ok(())
456  }
457}
458
459define_shorthand! {
460  /// A value for the [place-self](https://www.w3.org/TR/css-align-3/#place-self-property) shorthand property.
461  pub struct PlaceSelf {
462    /// The item alignment.
463    align: AlignSelf(AlignSelf, VendorPrefix),
464    /// The item justification.
465    justify: JustifySelf(JustifySelf),
466  }
467}
468
469impl<'i> Parse<'i> for PlaceSelf {
470  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
471    let align = AlignSelf::parse(input)?;
472    let justify = match input.try_parse(JustifySelf::parse) {
473      Ok(j) => j,
474      Err(_) => {
475        // The second value is assigned to justify-self; if omitted, it is copied from the first value.
476        match &align {
477          AlignSelf::Auto => JustifySelf::Auto,
478          AlignSelf::Normal => JustifySelf::Normal,
479          AlignSelf::Stretch => JustifySelf::Stretch,
480          AlignSelf::BaselinePosition(p) => JustifySelf::BaselinePosition(p.clone()),
481          AlignSelf::SelfPosition { overflow, value } => JustifySelf::SelfPosition {
482            overflow: overflow.clone(),
483            value: value.clone(),
484          },
485        }
486      }
487    };
488
489    Ok(PlaceSelf { align, justify })
490  }
491}
492
493impl ToCss for PlaceSelf {
494  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
495    self.align.to_css(dest)?;
496    let is_equal = match &self.justify {
497      JustifySelf::Auto => true,
498      JustifySelf::Normal => self.align == AlignSelf::Normal,
499      JustifySelf::Stretch => self.align == AlignSelf::Normal,
500      JustifySelf::BaselinePosition(p) if matches!(&self.align, AlignSelf::BaselinePosition(p2) if p == p2) => {
501        true
502      }
503      JustifySelf::SelfPosition { overflow: o, value: c } if matches!(&self.align, AlignSelf::SelfPosition  { overflow: o2, value: c2 } if o == o2 && c == c2) => {
504        true
505      }
506      _ => false,
507    };
508
509    if !is_equal {
510      dest.write_str(" ")?;
511      self.justify.to_css(dest)?;
512    }
513
514    Ok(())
515  }
516}
517
518/// A value for the [align-items](https://www.w3.org/TR/css-align-3/#align-items-property) property.
519#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
520#[cfg_attr(feature = "visitor", derive(Visit))]
521#[cfg_attr(
522  feature = "serde",
523  derive(serde::Serialize, serde::Deserialize),
524  serde(tag = "type", rename_all = "kebab-case")
525)]
526#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
527#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
528pub enum AlignItems {
529  /// Default alignment.
530  Normal,
531  /// Items are stretched.
532  Stretch,
533  /// A baseline position keyword.
534  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<BaselinePosition>"))]
535  BaselinePosition(BaselinePosition),
536  /// A self position keyword.
537  SelfPosition {
538    /// An overflow alignment mode.
539    overflow: Option<OverflowPosition>,
540    /// A self position keyword.
541    value: SelfPosition,
542  },
543}
544
545/// A legacy justification keyword, as used in the `justify-items` property.
546#[derive(Debug, Clone, PartialEq)]
547#[cfg_attr(feature = "visitor", derive(Visit))]
548#[cfg_attr(
549  feature = "serde",
550  derive(serde::Serialize, serde::Deserialize),
551  serde(rename_all = "kebab-case")
552)]
553#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
554pub enum LegacyJustify {
555  /// Left justify.
556  Left,
557  /// Right justify.
558  Right,
559  /// Centered.
560  Center,
561}
562
563impl<'i> Parse<'i> for LegacyJustify {
564  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
565    let location = input.current_source_location();
566    let ident = input.expect_ident()?;
567    match_ignore_ascii_case! { &*ident,
568      "legacy" => {
569        let location = input.current_source_location();
570        let ident = input.expect_ident()?;
571        match_ignore_ascii_case! { &*ident,
572          "left" => Ok(LegacyJustify::Left),
573          "right" => Ok(LegacyJustify::Right),
574          "center" => Ok(LegacyJustify::Center),
575          _ => Err(location.new_unexpected_token_error(
576            cssparser::Token::Ident(ident.clone())
577          ))
578        }
579      },
580      "left" => {
581        input.expect_ident_matching("legacy")?;
582        Ok(LegacyJustify::Left)
583      },
584      "right" => {
585        input.expect_ident_matching("legacy")?;
586        Ok(LegacyJustify::Right)
587      },
588      "center" => {
589        input.expect_ident_matching("legacy")?;
590        Ok(LegacyJustify::Center)
591      },
592      _ => Err(location.new_unexpected_token_error(
593        cssparser::Token::Ident(ident.clone())
594      ))
595    }
596  }
597}
598
599impl ToCss for LegacyJustify {
600  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
601    dest.write_str("legacy ")?;
602    match self {
603      LegacyJustify::Left => dest.write_str("left")?,
604      LegacyJustify::Right => dest.write_str("right")?,
605      LegacyJustify::Center => dest.write_str("center")?,
606    };
607    Ok(())
608  }
609}
610
611/// A value for the [justify-items](https://www.w3.org/TR/css-align-3/#justify-items-property) property.
612#[derive(Debug, Clone, PartialEq)]
613#[cfg_attr(feature = "visitor", derive(Visit))]
614#[cfg_attr(
615  feature = "serde",
616  derive(serde::Serialize, serde::Deserialize),
617  serde(tag = "type", rename_all = "kebab-case")
618)]
619#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
620#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
621pub enum JustifyItems {
622  /// Default justification.
623  Normal,
624  /// Items are stretched.
625  Stretch,
626  /// A baseline position keyword.
627  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<BaselinePosition>"))]
628  BaselinePosition(BaselinePosition),
629  /// A self position keyword, with optional overflow position.
630  SelfPosition {
631    /// A self position keyword.
632    value: SelfPosition,
633    /// An overflow alignment mode.
634    overflow: Option<OverflowPosition>,
635  },
636  /// Items are justified to the left, with an optional overflow position.
637  Left {
638    /// An overflow alignment mode.
639    overflow: Option<OverflowPosition>,
640  },
641  /// Items are justified to the right, with an optional overflow position.
642  Right {
643    /// An overflow alignment mode.
644    overflow: Option<OverflowPosition>,
645  },
646  /// A legacy justification keyword.
647  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<LegacyJustify>"))]
648  Legacy(LegacyJustify),
649}
650
651impl<'i> Parse<'i> for JustifyItems {
652  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
653    if input.try_parse(|input| input.expect_ident_matching("normal")).is_ok() {
654      return Ok(JustifyItems::Normal);
655    }
656
657    if input.try_parse(|input| input.expect_ident_matching("stretch")).is_ok() {
658      return Ok(JustifyItems::Stretch);
659    }
660
661    if let Ok(val) = input.try_parse(BaselinePosition::parse) {
662      return Ok(JustifyItems::BaselinePosition(val));
663    }
664
665    if let Ok(val) = input.try_parse(LegacyJustify::parse) {
666      return Ok(JustifyItems::Legacy(val));
667    }
668
669    let overflow = input.try_parse(OverflowPosition::parse).ok();
670    if let Ok(value) = input.try_parse(SelfPosition::parse) {
671      return Ok(JustifyItems::SelfPosition { overflow, value });
672    }
673
674    let location = input.current_source_location();
675    let ident = input.expect_ident()?;
676    match_ignore_ascii_case! { &*ident,
677      "left" => Ok(JustifyItems::Left { overflow }),
678      "right" => Ok(JustifyItems::Right { overflow }),
679      _ => Err(location.new_unexpected_token_error(
680        cssparser::Token::Ident(ident.clone())
681      ))
682    }
683  }
684}
685
686impl ToCss for JustifyItems {
687  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
688    match self {
689      JustifyItems::Normal => dest.write_str("normal")?,
690      JustifyItems::Stretch => dest.write_str("stretch")?,
691      JustifyItems::BaselinePosition(val) => val.to_css(dest)?,
692      JustifyItems::Legacy(val) => val.to_css(dest)?,
693      JustifyItems::SelfPosition { overflow, value } => {
694        if let Some(overflow) = overflow {
695          overflow.to_css(dest)?;
696          dest.write_str(" ")?;
697        }
698
699        value.to_css(dest)?;
700      }
701      JustifyItems::Left { overflow } => {
702        if let Some(overflow) = overflow {
703          overflow.to_css(dest)?;
704          dest.write_str(" ")?;
705        }
706
707        dest.write_str("left")?;
708      }
709      JustifyItems::Right { overflow } => {
710        if let Some(overflow) = overflow {
711          overflow.to_css(dest)?;
712          dest.write_str(" ")?;
713        }
714
715        dest.write_str("right")?;
716      }
717    };
718    Ok(())
719  }
720}
721
722define_shorthand! {
723  /// A value for the [place-items](https://www.w3.org/TR/css-align-3/#place-items-property) shorthand property.
724  pub struct PlaceItems {
725    /// The item alignment.
726    align: AlignItems(AlignItems, VendorPrefix),
727    /// The item justification.
728    justify: JustifyItems(JustifyItems),
729  }
730}
731
732impl<'i> Parse<'i> for PlaceItems {
733  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
734    let align = AlignItems::parse(input)?;
735    let justify = match input.try_parse(JustifyItems::parse) {
736      Ok(j) => j,
737      Err(_) => {
738        // The second value is assigned to justify-items; if omitted, it is copied from the first value.
739        match &align {
740          AlignItems::Normal => JustifyItems::Normal,
741          AlignItems::Stretch => JustifyItems::Stretch,
742          AlignItems::BaselinePosition(p) => JustifyItems::BaselinePosition(p.clone()),
743          AlignItems::SelfPosition { overflow, value } => JustifyItems::SelfPosition {
744            overflow: overflow.clone(),
745            value: value.clone(),
746          },
747        }
748      }
749    };
750
751    Ok(PlaceItems { align, justify })
752  }
753}
754
755impl ToCss for PlaceItems {
756  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
757    self.align.to_css(dest)?;
758    let is_equal = match &self.justify {
759      JustifyItems::Normal => self.align == AlignItems::Normal,
760      JustifyItems::Stretch => self.align == AlignItems::Normal,
761      JustifyItems::BaselinePosition(p) if matches!(&self.align, AlignItems::BaselinePosition(p2) if p == p2) => {
762        true
763      }
764      JustifyItems::SelfPosition { overflow: o, value: c } if matches!(&self.align, AlignItems::SelfPosition { overflow: o2, value: c2 } if o == o2 && c == c2) => {
765        true
766      }
767      _ => false,
768    };
769
770    if !is_equal {
771      dest.write_str(" ")?;
772      self.justify.to_css(dest)?;
773    }
774
775    Ok(())
776  }
777}
778
779/// A [gap](https://www.w3.org/TR/css-align-3/#column-row-gap) value, as used in the
780/// `column-gap` and `row-gap` properties.
781#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
782#[cfg_attr(feature = "visitor", derive(Visit))]
783#[cfg_attr(
784  feature = "serde",
785  derive(serde::Serialize, serde::Deserialize),
786  serde(tag = "type", content = "value", rename_all = "kebab-case")
787)]
788#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
789#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
790pub enum GapValue {
791  /// Equal to `1em` for multi-column containers, and zero otherwise.
792  Normal,
793  /// An explicit length.
794  LengthPercentage(NonNegative<LengthPercentage>),
795}
796
797define_shorthand! {
798  /// A value for the [gap](https://www.w3.org/TR/css-align-3/#gap-shorthand) shorthand property.
799  pub struct Gap {
800    /// The row gap.
801    row: RowGap(GapValue),
802    /// The column gap.
803    column: ColumnGap(GapValue),
804  }
805}
806
807impl<'i> Parse<'i> for Gap {
808  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
809    let row = GapValue::parse(input)?;
810    let column = input.try_parse(GapValue::parse).unwrap_or(row.clone());
811    Ok(Gap { row, column })
812  }
813}
814
815impl ToCss for Gap {
816  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
817    self.row.to_css(dest)?;
818    if self.column != self.row {
819      dest.write_str(" ")?;
820      self.column.to_css(dest)?;
821    }
822    Ok(())
823  }
824}
825
826#[derive(Default, Debug)]
827pub(crate) struct AlignHandler {
828  align_content: Option<(AlignContent, VendorPrefix)>,
829  flex_line_pack: Option<(FlexLinePack, VendorPrefix)>,
830  justify_content: Option<(JustifyContent, VendorPrefix)>,
831  box_pack: Option<(BoxPack, VendorPrefix)>,
832  flex_pack: Option<(FlexPack, VendorPrefix)>,
833  align_self: Option<(AlignSelf, VendorPrefix)>,
834  flex_item_align: Option<(FlexItemAlign, VendorPrefix)>,
835  justify_self: Option<JustifySelf>,
836  align_items: Option<(AlignItems, VendorPrefix)>,
837  box_align: Option<(BoxAlign, VendorPrefix)>,
838  flex_align: Option<(FlexAlign, VendorPrefix)>,
839  justify_items: Option<JustifyItems>,
840  row_gap: Option<GapValue>,
841  column_gap: Option<GapValue>,
842  has_any: bool,
843}
844
845impl<'i> PropertyHandler<'i> for AlignHandler {
846  fn handle_property(
847    &mut self,
848    property: &Property<'i>,
849    dest: &mut DeclarationList<'i>,
850    context: &mut PropertyHandlerContext<'i, '_>,
851  ) -> bool {
852    use Property::*;
853
854    macro_rules! maybe_flush {
855      ($prop: ident, $val: expr, $vp: expr) => {{
856        // If two vendor prefixes for the same property have different
857        // values, we need to flush what we have immediately to preserve order.
858        if let Some((val, prefixes)) = &self.$prop {
859          if val != $val && !prefixes.contains(*$vp) {
860            self.flush(dest, context);
861          }
862        }
863      }};
864    }
865
866    macro_rules! property {
867      ($prop: ident, $val: expr, $vp: expr) => {{
868        maybe_flush!($prop, $val, $vp);
869
870        // Otherwise, update the value and add the prefix.
871        if let Some((val, prefixes)) = &mut self.$prop {
872          *val = $val.clone();
873          *prefixes |= *$vp;
874        } else {
875          self.$prop = Some(($val.clone(), *$vp));
876          self.has_any = true;
877        }
878      }};
879    }
880
881    match property {
882      AlignContent(val, vp) => {
883        self.flex_line_pack = None;
884        property!(align_content, val, vp);
885      }
886      FlexLinePack(val, vp) => property!(flex_line_pack, val, vp),
887      JustifyContent(val, vp) => {
888        self.box_pack = None;
889        self.flex_pack = None;
890        property!(justify_content, val, vp);
891      }
892      BoxPack(val, vp) => property!(box_pack, val, vp),
893      FlexPack(val, vp) => property!(flex_pack, val, vp),
894      PlaceContent(val) => {
895        self.flex_line_pack = None;
896        self.box_pack = None;
897        self.flex_pack = None;
898        maybe_flush!(align_content, &val.align, &VendorPrefix::None);
899        maybe_flush!(justify_content, &val.justify, &VendorPrefix::None);
900        property!(align_content, &val.align, &VendorPrefix::None);
901        property!(justify_content, &val.justify, &VendorPrefix::None);
902      }
903      AlignSelf(val, vp) => {
904        self.flex_item_align = None;
905        property!(align_self, val, vp);
906      }
907      FlexItemAlign(val, vp) => property!(flex_item_align, val, vp),
908      JustifySelf(val) => {
909        self.justify_self = Some(val.clone());
910        self.has_any = true;
911      }
912      PlaceSelf(val) => {
913        self.flex_item_align = None;
914        property!(align_self, &val.align, &VendorPrefix::None);
915        self.justify_self = Some(val.justify.clone());
916      }
917      AlignItems(val, vp) => {
918        self.box_align = None;
919        self.flex_align = None;
920        property!(align_items, val, vp);
921      }
922      BoxAlign(val, vp) => property!(box_align, val, vp),
923      FlexAlign(val, vp) => property!(flex_align, val, vp),
924      JustifyItems(val) => {
925        self.justify_items = Some(val.clone());
926        self.has_any = true;
927      }
928      PlaceItems(val) => {
929        self.box_align = None;
930        self.flex_align = None;
931        property!(align_items, &val.align, &VendorPrefix::None);
932        self.justify_items = Some(val.justify.clone());
933      }
934      RowGap(val) => {
935        self.row_gap = Some(val.clone());
936        self.has_any = true;
937      }
938      ColumnGap(val) => {
939        self.column_gap = Some(val.clone());
940        self.has_any = true;
941      }
942      Gap(val) => {
943        self.row_gap = Some(val.row.clone());
944        self.column_gap = Some(val.column.clone());
945        self.has_any = true;
946      }
947      Unparsed(val) if is_align_property(&val.property_id) => {
948        self.flush(dest, context);
949        dest.push(property.clone()) // TODO: prefix?
950      }
951      _ => return false,
952    }
953
954    true
955  }
956
957  fn finalize(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
958    self.flush(dest, context);
959  }
960}
961
962impl AlignHandler {
963  fn flush<'i>(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
964    if !self.has_any {
965      return;
966    }
967
968    self.has_any = false;
969
970    let mut align_content = std::mem::take(&mut self.align_content);
971    let mut justify_content = std::mem::take(&mut self.justify_content);
972    let mut align_self = std::mem::take(&mut self.align_self);
973    let mut justify_self = std::mem::take(&mut self.justify_self);
974    let mut align_items = std::mem::take(&mut self.align_items);
975    let mut justify_items = std::mem::take(&mut self.justify_items);
976    let row_gap = std::mem::take(&mut self.row_gap);
977    let column_gap = std::mem::take(&mut self.column_gap);
978    let box_align = std::mem::take(&mut self.box_align);
979    let box_pack = std::mem::take(&mut self.box_pack);
980    let flex_line_pack = std::mem::take(&mut self.flex_line_pack);
981    let flex_pack = std::mem::take(&mut self.flex_pack);
982    let flex_align = std::mem::take(&mut self.flex_align);
983    let flex_item_align = std::mem::take(&mut self.flex_item_align);
984
985    // Gets prefixes for standard properties.
986    macro_rules! prefixes {
987      ($prop: ident) => {{
988        let mut prefix = context.targets.prefixes(VendorPrefix::None, Feature::$prop);
989        // Firefox only implemented the 2009 spec prefixed.
990        // Microsoft only implemented the 2012 spec prefixed.
991        prefix.remove(VendorPrefix::Moz | VendorPrefix::Ms);
992        prefix
993      }};
994    }
995
996    macro_rules! standard_property {
997      ($prop: ident, $key: ident) => {
998        if let Some((val, prefix)) = $key {
999          // If we have an unprefixed property, override necessary prefixes.
1000          let prefix = if prefix.contains(VendorPrefix::None) {
1001            prefixes!($prop)
1002          } else {
1003            prefix
1004          };
1005          dest.push(Property::$prop(val, prefix))
1006        }
1007      };
1008    }
1009
1010    macro_rules! legacy_property {
1011      ($prop: ident, $key: ident, $( $prop_2009: ident )?, $prop_2012: ident) => {
1012        if let Some((val, prefix)) = &$key {
1013          // If we have an unprefixed standard property, generate legacy prefixed versions.
1014          let mut prefix = context.targets.prefixes(*prefix, Feature::$prop);
1015
1016          if prefix.contains(VendorPrefix::None) {
1017            $(
1018              // 2009 spec, implemented by webkit and firefox.
1019              if let Some(targets) = context.targets.browsers {
1020                let mut prefixes_2009 = VendorPrefix::empty();
1021                if is_flex_2009(targets) {
1022                  prefixes_2009 |= VendorPrefix::WebKit;
1023                }
1024                if prefix.contains(VendorPrefix::Moz) {
1025                  prefixes_2009 |= VendorPrefix::Moz;
1026                }
1027                if !prefixes_2009.is_empty() {
1028                  if let Some(v) = $prop_2009::from_standard(&val) {
1029                    dest.push(Property::$prop_2009(v, prefixes_2009));
1030                  }
1031                }
1032              }
1033            )?
1034          }
1035
1036          // 2012 spec, implemented by microsoft.
1037          if prefix.contains(VendorPrefix::Ms) {
1038            if let Some(v) = $prop_2012::from_standard(&val) {
1039              dest.push(Property::$prop_2012(v, VendorPrefix::Ms));
1040            }
1041          }
1042
1043          // Remove Firefox and IE from standard prefixes.
1044          prefix.remove(VendorPrefix::Moz | VendorPrefix::Ms);
1045        }
1046      };
1047    }
1048
1049    macro_rules! prefixed_property {
1050      ($prop: ident, $key: expr) => {
1051        if let Some((val, prefix)) = $key {
1052          dest.push(Property::$prop(val, prefix))
1053        }
1054      };
1055    }
1056
1057    macro_rules! unprefixed_property {
1058      ($prop: ident, $key: expr) => {
1059        if let Some(val) = $key {
1060          dest.push(Property::$prop(val))
1061        }
1062      };
1063    }
1064
1065    macro_rules! shorthand {
1066      ($prop: ident, $align_prop: ident, $align: ident, $justify: ident $(, $justify_prop: ident )?) => {
1067        if let (Some((align, align_prefix)), Some(justify)) = (&mut $align, &mut $justify) {
1068          let intersection = *align_prefix $( & {
1069            // Hack for conditional compilation. Have to use a variable.
1070            #[allow(non_snake_case)]
1071            let $justify_prop = justify.1;
1072            $justify_prop
1073          })?;
1074
1075          // Only use shorthand if unprefixed.
1076          if intersection.contains(VendorPrefix::None) {
1077            // Add prefixed longhands if needed.
1078            *align_prefix = prefixes!($align_prop);
1079            align_prefix.remove(VendorPrefix::None);
1080            if !align_prefix.is_empty() {
1081              dest.push(Property::$align_prop(align.clone(), *align_prefix))
1082            }
1083
1084            $(
1085              let (justify, justify_prefix) = justify;
1086              *justify_prefix = prefixes!($justify_prop);
1087              justify_prefix.remove(VendorPrefix::None);
1088
1089              if !justify_prefix.is_empty() {
1090                dest.push(Property::$justify_prop(justify.clone(), *justify_prefix))
1091              }
1092            )?
1093
1094            // Add shorthand.
1095            dest.push(Property::$prop($prop {
1096              align: align.clone(),
1097              justify: justify.clone()
1098            }));
1099
1100            $align = None;
1101            $justify = None;
1102          }
1103        }
1104      };
1105    }
1106
1107    // 2009 properties
1108    prefixed_property!(BoxAlign, box_align);
1109    prefixed_property!(BoxPack, box_pack);
1110
1111    // 2012 properties
1112    prefixed_property!(FlexPack, flex_pack);
1113    prefixed_property!(FlexAlign, flex_align);
1114    prefixed_property!(FlexItemAlign, flex_item_align);
1115    prefixed_property!(FlexLinePack, flex_line_pack);
1116
1117    legacy_property!(AlignContent, align_content, , FlexLinePack);
1118    legacy_property!(JustifyContent, justify_content, BoxPack, FlexPack);
1119    if context.targets.is_compatible(compat::Feature::PlaceContent) {
1120      shorthand!(
1121        PlaceContent,
1122        AlignContent,
1123        align_content,
1124        justify_content,
1125        JustifyContent
1126      );
1127    }
1128    standard_property!(AlignContent, align_content);
1129    standard_property!(JustifyContent, justify_content);
1130
1131    legacy_property!(AlignSelf, align_self, , FlexItemAlign);
1132    if context.targets.is_compatible(compat::Feature::PlaceSelf) {
1133      shorthand!(PlaceSelf, AlignSelf, align_self, justify_self);
1134    }
1135    standard_property!(AlignSelf, align_self);
1136    unprefixed_property!(JustifySelf, justify_self);
1137
1138    legacy_property!(AlignItems, align_items, BoxAlign, FlexAlign);
1139    if context.targets.is_compatible(compat::Feature::PlaceItems) {
1140      shorthand!(PlaceItems, AlignItems, align_items, justify_items);
1141    }
1142    standard_property!(AlignItems, align_items);
1143    unprefixed_property!(JustifyItems, justify_items);
1144
1145    if row_gap.is_some() && column_gap.is_some() {
1146      dest.push(Property::Gap(Gap {
1147        row: row_gap.unwrap(),
1148        column: column_gap.unwrap(),
1149      }))
1150    } else {
1151      if let Some(gap) = row_gap {
1152        dest.push(Property::RowGap(gap))
1153      }
1154
1155      if let Some(gap) = column_gap {
1156        dest.push(Property::ColumnGap(gap))
1157      }
1158    }
1159  }
1160}
1161
1162#[inline]
1163fn is_align_property(property_id: &PropertyId) -> bool {
1164  match property_id {
1165    PropertyId::AlignContent(_)
1166    | PropertyId::FlexLinePack(_)
1167    | PropertyId::JustifyContent(_)
1168    | PropertyId::BoxPack(_)
1169    | PropertyId::FlexPack(_)
1170    | PropertyId::PlaceContent
1171    | PropertyId::AlignSelf(_)
1172    | PropertyId::FlexItemAlign(_)
1173    | PropertyId::JustifySelf
1174    | PropertyId::PlaceSelf
1175    | PropertyId::AlignItems(_)
1176    | PropertyId::BoxAlign(_)
1177    | PropertyId::FlexAlign(_)
1178    | PropertyId::JustifyItems
1179    | PropertyId::PlaceItems
1180    | PropertyId::RowGap
1181    | PropertyId::ColumnGap
1182    | PropertyId::Gap => true,
1183    _ => false,
1184  }
1185}