Skip to main content

rspack_lightningcss/properties/
flex.rs

1//! CSS properties related to flexbox layout.
2
3use super::align::{
4  AlignContent, AlignItems, AlignSelf, ContentDistribution, ContentPosition, JustifyContent, SelfPosition,
5};
6use super::{Property, PropertyId};
7use crate::context::PropertyHandlerContext;
8use crate::declaration::{DeclarationBlock, DeclarationList};
9use crate::error::{ParserError, PrinterError};
10use crate::macros::*;
11use crate::prefixes::{is_flex_2009, Feature};
12use crate::traits::{FromStandard, Parse, PropertyHandler, Shorthand, ToCss, Zero};
13use crate::values::number::{CSSInteger, CSSNumber, NonNegative};
14use crate::values::{
15  length::{LengthPercentage, LengthPercentageOrAuto},
16  percentage::Percentage,
17};
18use crate::vendor_prefix::VendorPrefix;
19#[cfg(feature = "visitor")]
20use crate::visitor::Visit;
21use cssparser::*;
22
23enum_property! {
24  /// A value for the [flex-direction](https://www.w3.org/TR/2018/CR-css-flexbox-1-20181119/#propdef-flex-direction) property.
25  pub enum FlexDirection {
26    /// Flex items are laid out in a row.
27    Row,
28    /// Flex items are laid out in a row, and reversed.
29    RowReverse,
30    /// Flex items are laid out in a column.
31    Column,
32    /// Flex items are laid out in a column, and reversed.
33    ColumnReverse,
34  }
35}
36
37impl Default for FlexDirection {
38  fn default() -> FlexDirection {
39    FlexDirection::Row
40  }
41}
42
43enum_property! {
44  /// A value for the [flex-wrap](https://www.w3.org/TR/2018/CR-css-flexbox-1-20181119/#flex-wrap-property) property.
45  pub enum FlexWrap {
46    /// The flex items do not wrap.
47    "nowrap": NoWrap,
48    /// The flex items wrap.
49    "wrap": Wrap,
50    /// The flex items wrap, in reverse.
51    "wrap-reverse": WrapReverse,
52  }
53}
54
55impl Default for FlexWrap {
56  fn default() -> FlexWrap {
57    FlexWrap::NoWrap
58  }
59}
60
61impl FromStandard<FlexWrap> for FlexWrap {
62  fn from_standard(wrap: &FlexWrap) -> Option<FlexWrap> {
63    Some(wrap.clone())
64  }
65}
66
67define_shorthand! {
68  /// A value for the [flex-flow](https://www.w3.org/TR/2018/CR-css-flexbox-1-20181119/#flex-flow-property) shorthand property.
69  pub struct FlexFlow(VendorPrefix) {
70    /// The direction that flex items flow.
71    direction: FlexDirection(FlexDirection, VendorPrefix),
72    /// How the flex items wrap.
73    wrap: FlexWrap(FlexWrap, VendorPrefix),
74  }
75}
76
77impl<'i> Parse<'i> for FlexFlow {
78  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
79    let mut direction = None;
80    let mut wrap = None;
81    loop {
82      if direction.is_none() {
83        if let Ok(value) = input.try_parse(FlexDirection::parse) {
84          direction = Some(value);
85          continue;
86        }
87      }
88      if wrap.is_none() {
89        if let Ok(value) = input.try_parse(FlexWrap::parse) {
90          wrap = Some(value);
91          continue;
92        }
93      }
94      break;
95    }
96
97    Ok(FlexFlow {
98      direction: direction.unwrap_or_default(),
99      wrap: wrap.unwrap_or_default(),
100    })
101  }
102}
103
104impl ToCss for FlexFlow {
105  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
106    let mut needs_space = false;
107    if self.direction != FlexDirection::default() || self.wrap == FlexWrap::default() {
108      self.direction.to_css(dest)?;
109      needs_space = true;
110    }
111
112    if self.wrap != FlexWrap::default() {
113      if needs_space {
114        dest.write_str(" ")?;
115      }
116      self.wrap.to_css(dest)?;
117    }
118
119    Ok(())
120  }
121}
122
123define_shorthand! {
124/// A value for the [flex](https://www.w3.org/TR/2018/CR-css-flexbox-1-20181119/#flex-property) shorthand property.
125  pub struct Flex(VendorPrefix) {
126    /// The flex grow factor.
127    grow: FlexGrow(NonNegative<CSSNumber>, VendorPrefix),
128    /// The flex shrink factor.
129    shrink: FlexShrink(NonNegative<CSSNumber>, VendorPrefix),
130    /// The flex basis.
131    basis: FlexBasis(NonNegative<LengthPercentageOrAuto>, VendorPrefix),
132  }
133}
134
135impl<'i> Parse<'i> for Flex {
136  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
137    if input.try_parse(|input| input.expect_ident_matching("none")).is_ok() {
138      return Ok(Flex {
139        grow: NonNegative(0.0),
140        shrink: NonNegative(0.0),
141        basis: NonNegative(LengthPercentageOrAuto::Auto),
142      });
143    }
144
145    let mut grow = None;
146    let mut shrink = None;
147    let mut basis = None;
148
149    loop {
150      if grow.is_none() {
151        if let Ok(val) = input.try_parse(NonNegative::<CSSNumber>::parse) {
152          grow = Some(val);
153          shrink = input.try_parse(NonNegative::<CSSNumber>::parse).ok();
154          continue;
155        }
156      }
157
158      if basis.is_none() {
159        if let Ok(val) = input.try_parse(NonNegative::<LengthPercentageOrAuto>::parse) {
160          basis = Some(val);
161          continue;
162        }
163      }
164
165      break;
166    }
167
168    Ok(Flex {
169      grow: grow.unwrap_or(NonNegative(1.0)),
170      shrink: shrink.unwrap_or(NonNegative(1.0)),
171      basis: basis.unwrap_or(NonNegative(LengthPercentageOrAuto::LengthPercentage(
172        LengthPercentage::Percentage(Percentage(0.0)),
173      ))),
174    })
175  }
176}
177
178impl ToCss for Flex {
179  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
180    if self.grow.0 == 0.0 && self.shrink.0 == 0.0 && self.basis.0 == LengthPercentageOrAuto::Auto {
181      dest.write_str("none")?;
182      return Ok(());
183    }
184
185    #[derive(PartialEq)]
186    enum ZeroKind {
187      NonZero,
188      Length,
189      Percentage,
190    }
191
192    // If the basis is unitless 0, we must write all three components to disambiguate.
193    // If the basis is 0%, we can omit the basis.
194    let basis_kind = match &self.basis.0 {
195      LengthPercentageOrAuto::LengthPercentage(lp) => match lp {
196        LengthPercentage::Dimension(l) if l.is_zero() => ZeroKind::Length,
197        LengthPercentage::Percentage(p) if p.is_zero() => ZeroKind::Percentage,
198        _ => ZeroKind::NonZero,
199      },
200      _ => ZeroKind::NonZero,
201    };
202
203    if self.grow.0 != 1.0 || self.shrink.0 != 1.0 || basis_kind != ZeroKind::NonZero {
204      self.grow.to_css(dest)?;
205      if self.shrink.0 != 1.0 || basis_kind == ZeroKind::Length {
206        dest.write_str(" ")?;
207        self.shrink.to_css(dest)?;
208      }
209    }
210
211    if basis_kind != ZeroKind::Percentage {
212      if self.grow.0 != 1.0 || self.shrink.0 != 1.0 || basis_kind == ZeroKind::Length {
213        dest.write_str(" ")?;
214      }
215      self.basis.to_css(dest)?;
216    }
217
218    Ok(())
219  }
220}
221
222// Old flex (2009): https://www.w3.org/TR/2009/WD-css3-flexbox-20090723/
223
224enum_property! {
225  /// A value for the legacy (prefixed) [box-orient](https://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#orientation) property.
226  /// Partially equivalent to `flex-direction` in the standard syntax.
227  pub enum BoxOrient {
228    /// Items are laid out horizontally.
229    Horizontal,
230    /// Items are laid out vertically.
231    Vertical,
232    /// Items are laid out along the inline axis, according to the writing direction.
233    InlineAxis,
234    /// Items are laid out along the block axis, according to the writing direction.
235    BlockAxis,
236  }
237}
238
239impl FlexDirection {
240  fn to_2009(&self) -> (BoxOrient, BoxDirection) {
241    match self {
242      FlexDirection::Row => (BoxOrient::Horizontal, BoxDirection::Normal),
243      FlexDirection::Column => (BoxOrient::Vertical, BoxDirection::Normal),
244      FlexDirection::RowReverse => (BoxOrient::Horizontal, BoxDirection::Reverse),
245      FlexDirection::ColumnReverse => (BoxOrient::Vertical, BoxDirection::Reverse),
246    }
247  }
248}
249
250enum_property! {
251  /// A value for the legacy (prefixed) [box-direction](https://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#displayorder) property.
252  /// Partially equivalent to the `flex-direction` property in the standard syntax.
253  pub enum BoxDirection {
254    /// Items flow in the natural direction.
255    Normal,
256    /// Items flow in the reverse direction.
257    Reverse,
258  }
259}
260
261enum_property! {
262  /// A value for the legacy (prefixed) [box-align](https://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#alignment) property.
263  /// Equivalent to the `align-items` property in the standard syntax.
264  pub enum BoxAlign {
265    /// Items are aligned to the start.
266    Start,
267    /// Items are aligned to the end.
268    End,
269    /// Items are centered.
270    Center,
271    /// Items are aligned to the baseline.
272    Baseline,
273    /// Items are stretched.
274    Stretch,
275  }
276}
277
278impl FromStandard<AlignItems> for BoxAlign {
279  fn from_standard(align: &AlignItems) -> Option<BoxAlign> {
280    match align {
281      AlignItems::SelfPosition { overflow: None, value } => match value {
282        SelfPosition::Start | SelfPosition::FlexStart => Some(BoxAlign::Start),
283        SelfPosition::End | SelfPosition::FlexEnd => Some(BoxAlign::End),
284        SelfPosition::Center => Some(BoxAlign::Center),
285        _ => None,
286      },
287      AlignItems::Stretch => Some(BoxAlign::Stretch),
288      _ => None,
289    }
290  }
291}
292
293enum_property! {
294  /// A value for the legacy (prefixed) [box-pack](https://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#packing) property.
295  /// Equivalent to the `justify-content` property in the standard syntax.
296  pub enum BoxPack {
297    /// Items are justified to the start.
298    Start,
299    /// Items are justified to the end.
300    End,
301    /// Items are centered.
302    Center,
303    /// Items are justified to the start and end.
304    Justify,
305  }
306}
307
308impl FromStandard<JustifyContent> for BoxPack {
309  fn from_standard(justify: &JustifyContent) -> Option<BoxPack> {
310    match justify {
311      JustifyContent::ContentDistribution(cd) => match cd {
312        ContentDistribution::SpaceBetween => Some(BoxPack::Justify),
313        _ => None,
314      },
315      JustifyContent::ContentPosition { overflow: None, value } => match value {
316        ContentPosition::Start | ContentPosition::FlexStart => Some(BoxPack::Start),
317        ContentPosition::End | ContentPosition::FlexEnd => Some(BoxPack::End),
318        ContentPosition::Center => Some(BoxPack::Center),
319      },
320      _ => None,
321    }
322  }
323}
324
325enum_property! {
326  /// A value for the legacy (prefixed) [box-lines](https://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#multiple) property.
327  /// Equivalent to the `flex-wrap` property in the standard syntax.
328  pub enum BoxLines {
329    /// Items are laid out in a single line.
330    Single,
331    /// Items may wrap into multiple lines.
332    Multiple,
333  }
334}
335
336impl FromStandard<FlexWrap> for BoxLines {
337  fn from_standard(wrap: &FlexWrap) -> Option<BoxLines> {
338    match wrap {
339      FlexWrap::NoWrap => Some(BoxLines::Single),
340      FlexWrap::Wrap => Some(BoxLines::Multiple),
341      _ => None,
342    }
343  }
344}
345
346type BoxOrdinalGroup = CSSInteger;
347impl FromStandard<CSSInteger> for BoxOrdinalGroup {
348  fn from_standard(order: &CSSInteger) -> Option<BoxOrdinalGroup> {
349    Some(*order)
350  }
351}
352
353// Old flex (2012): https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/
354
355enum_property! {
356  /// A value for the legacy (prefixed) [flex-pack](https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-pack) property.
357  /// Equivalent to the `justify-content` property in the standard syntax.
358  pub enum FlexPack {
359    /// Items are justified to the start.
360    Start,
361    /// Items are justified to the end.
362    End,
363    /// Items are centered.
364    Center,
365    /// Items are justified to the start and end.
366    Justify,
367    /// Items are distributed evenly, with half size spaces on either end.
368    Distribute,
369  }
370}
371
372impl FromStandard<JustifyContent> for FlexPack {
373  fn from_standard(justify: &JustifyContent) -> Option<FlexPack> {
374    match justify {
375      JustifyContent::ContentDistribution(cd) => match cd {
376        ContentDistribution::SpaceBetween => Some(FlexPack::Justify),
377        ContentDistribution::SpaceAround => Some(FlexPack::Distribute),
378        _ => None,
379      },
380      JustifyContent::ContentPosition { overflow: None, value } => match value {
381        ContentPosition::Start | ContentPosition::FlexStart => Some(FlexPack::Start),
382        ContentPosition::End | ContentPosition::FlexEnd => Some(FlexPack::End),
383        ContentPosition::Center => Some(FlexPack::Center),
384      },
385      _ => None,
386    }
387  }
388}
389
390/// A value for the legacy (prefixed) [flex-align](https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-align) property.
391pub type FlexAlign = BoxAlign;
392
393enum_property! {
394  /// A value for the legacy (prefixed) [flex-item-align](https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-align) property.
395  /// Equivalent to the `align-self` property in the standard syntax.
396  pub enum FlexItemAlign {
397    /// Equivalent to the value of `flex-align`.
398    Auto,
399    /// The item is aligned to the start.
400    Start,
401    /// The item is aligned to the end.
402    End,
403    /// The item is centered.
404    Center,
405    /// The item is aligned to the baseline.
406    Baseline,
407    /// The item is stretched.
408    Stretch,
409  }
410}
411
412impl FromStandard<AlignSelf> for FlexItemAlign {
413  fn from_standard(justify: &AlignSelf) -> Option<FlexItemAlign> {
414    match justify {
415      AlignSelf::Auto => Some(FlexItemAlign::Auto),
416      AlignSelf::Stretch => Some(FlexItemAlign::Stretch),
417      AlignSelf::SelfPosition { overflow: None, value } => match value {
418        SelfPosition::Start | SelfPosition::FlexStart => Some(FlexItemAlign::Start),
419        SelfPosition::End | SelfPosition::FlexEnd => Some(FlexItemAlign::End),
420        SelfPosition::Center => Some(FlexItemAlign::Center),
421        _ => None,
422      },
423      _ => None,
424    }
425  }
426}
427
428enum_property! {
429  /// A value for the legacy (prefixed) [flex-line-pack](https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-line-pack) property.
430  /// Equivalent to the `align-content` property in the standard syntax.
431  pub enum FlexLinePack {
432    /// Content is aligned to the start.
433    Start,
434    /// Content is aligned to the end.
435    End,
436    /// Content is centered.
437    Center,
438    /// Content is justified.
439    Justify,
440    /// Content is distributed evenly, with half size spaces on either end.
441    Distribute,
442    /// Content is stretched.
443    Stretch,
444  }
445}
446
447impl FromStandard<AlignContent> for FlexLinePack {
448  fn from_standard(justify: &AlignContent) -> Option<FlexLinePack> {
449    match justify {
450      AlignContent::ContentDistribution(cd) => match cd {
451        ContentDistribution::SpaceBetween => Some(FlexLinePack::Justify),
452        ContentDistribution::SpaceAround => Some(FlexLinePack::Distribute),
453        ContentDistribution::Stretch => Some(FlexLinePack::Stretch),
454        _ => None,
455      },
456      AlignContent::ContentPosition { overflow: None, value } => match value {
457        ContentPosition::Start | ContentPosition::FlexStart => Some(FlexLinePack::Start),
458        ContentPosition::End | ContentPosition::FlexEnd => Some(FlexLinePack::End),
459        ContentPosition::Center => Some(FlexLinePack::Center),
460      },
461      _ => None,
462    }
463  }
464}
465
466#[derive(Default, Debug)]
467pub(crate) struct FlexHandler {
468  direction: Option<(FlexDirection, VendorPrefix)>,
469  box_orient: Option<(BoxOrient, VendorPrefix)>,
470  box_direction: Option<(BoxDirection, VendorPrefix)>,
471  wrap: Option<(FlexWrap, VendorPrefix)>,
472  box_lines: Option<(BoxLines, VendorPrefix)>,
473  grow: Option<(NonNegative<CSSNumber>, VendorPrefix)>,
474  box_flex: Option<(NonNegative<CSSNumber>, VendorPrefix)>,
475  flex_positive: Option<(NonNegative<CSSNumber>, VendorPrefix)>,
476  shrink: Option<(NonNegative<CSSNumber>, VendorPrefix)>,
477  flex_negative: Option<(NonNegative<CSSNumber>, VendorPrefix)>,
478  basis: Option<(NonNegative<LengthPercentageOrAuto>, VendorPrefix)>,
479  preferred_size: Option<(NonNegative<LengthPercentageOrAuto>, VendorPrefix)>,
480  order: Option<(CSSInteger, VendorPrefix)>,
481  box_ordinal_group: Option<(BoxOrdinalGroup, VendorPrefix)>,
482  flex_order: Option<(CSSInteger, VendorPrefix)>,
483  has_any: bool,
484}
485
486impl<'i> PropertyHandler<'i> for FlexHandler {
487  fn handle_property(
488    &mut self,
489    property: &Property<'i>,
490    dest: &mut DeclarationList<'i>,
491    context: &mut PropertyHandlerContext<'i, '_>,
492  ) -> bool {
493    use Property::*;
494
495    macro_rules! maybe_flush {
496      ($prop: ident, $val: expr, $vp: ident) => {{
497        // If two vendor prefixes for the same property have different
498        // values, we need to flush what we have immediately to preserve order.
499        if let Some((val, prefixes)) = &self.$prop {
500          if val != $val && !prefixes.contains(*$vp) {
501            self.flush(dest, context);
502          }
503        }
504      }};
505    }
506
507    macro_rules! property {
508      ($prop: ident, $val: expr, $vp: ident) => {{
509        maybe_flush!($prop, $val, $vp);
510
511        // Otherwise, update the value and add the prefix.
512        if let Some((val, prefixes)) = &mut self.$prop {
513          *val = $val.clone();
514          *prefixes |= *$vp;
515        } else {
516          self.$prop = Some(($val.clone(), *$vp));
517          self.has_any = true;
518        }
519      }};
520    }
521
522    match property {
523      FlexDirection(val, vp) => {
524        if context.targets.browsers.is_some() {
525          self.box_direction = None;
526          self.box_orient = None;
527        }
528        property!(direction, val, vp);
529      }
530      BoxOrient(val, vp) => property!(box_orient, val, vp),
531      BoxDirection(val, vp) => property!(box_direction, val, vp),
532      FlexWrap(val, vp) => {
533        if context.targets.browsers.is_some() {
534          self.box_lines = None;
535        }
536        property!(wrap, val, vp);
537      }
538      BoxLines(val, vp) => property!(box_lines, val, vp),
539      FlexFlow(val, vp) => {
540        if context.targets.browsers.is_some() {
541          self.box_direction = None;
542          self.box_orient = None;
543        }
544        property!(direction, &val.direction, vp);
545        property!(wrap, &val.wrap, vp);
546      }
547      FlexGrow(val, vp) => {
548        if context.targets.browsers.is_some() {
549          self.box_flex = None;
550          self.flex_positive = None;
551        }
552        property!(grow, val, vp);
553      }
554      BoxFlex(val, vp) => property!(box_flex, val, vp),
555      FlexPositive(val, vp) => property!(flex_positive, val, vp),
556      FlexShrink(val, vp) => {
557        if context.targets.browsers.is_some() {
558          self.flex_negative = None;
559        }
560        property!(shrink, val, vp);
561      }
562      FlexNegative(val, vp) => property!(flex_negative, val, vp),
563      FlexBasis(val, vp) => {
564        if context.targets.browsers.is_some() {
565          self.preferred_size = None;
566        }
567        property!(basis, val, vp);
568      }
569      FlexPreferredSize(val, vp) => property!(preferred_size, val, vp),
570      Flex(val, vp) => {
571        if context.targets.browsers.is_some() {
572          self.box_flex = None;
573          self.flex_positive = None;
574          self.flex_negative = None;
575          self.preferred_size = None;
576        }
577        maybe_flush!(grow, &val.grow, vp);
578        maybe_flush!(shrink, &val.shrink, vp);
579        maybe_flush!(basis, &val.basis, vp);
580        property!(grow, &val.grow, vp);
581        property!(shrink, &val.shrink, vp);
582        property!(basis, &val.basis, vp);
583      }
584      Order(val, vp) => {
585        if context.targets.browsers.is_some() {
586          self.box_ordinal_group = None;
587          self.flex_order = None;
588        }
589        property!(order, val, vp);
590      }
591      BoxOrdinalGroup(val, vp) => property!(box_ordinal_group, val, vp),
592      FlexOrder(val, vp) => property!(flex_order, val, vp),
593      Unparsed(val) if is_flex_property(&val.property_id) => {
594        self.flush(dest, context);
595        dest.push(property.clone()) // TODO: prefix?
596      }
597      _ => return false,
598    }
599
600    true
601  }
602
603  fn finalize(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
604    self.flush(dest, context);
605  }
606}
607
608impl FlexHandler {
609  fn flush<'i>(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
610    if !self.has_any {
611      return;
612    }
613
614    self.has_any = false;
615
616    let mut direction = std::mem::take(&mut self.direction);
617    let mut wrap = std::mem::take(&mut self.wrap);
618    let mut grow = std::mem::take(&mut self.grow);
619    let mut shrink = std::mem::take(&mut self.shrink);
620    let mut basis = std::mem::take(&mut self.basis);
621    let box_orient = std::mem::take(&mut self.box_orient);
622    let box_direction = std::mem::take(&mut self.box_direction);
623    let box_flex = std::mem::take(&mut self.box_flex);
624    let box_ordinal_group = std::mem::take(&mut self.box_ordinal_group);
625    let box_lines = std::mem::take(&mut self.box_lines);
626    let flex_positive = std::mem::take(&mut self.flex_positive);
627    let flex_negative = std::mem::take(&mut self.flex_negative);
628    let preferred_size = std::mem::take(&mut self.preferred_size);
629    let order = std::mem::take(&mut self.order);
630    let flex_order = std::mem::take(&mut self.flex_order);
631
632    macro_rules! single_property {
633      ($prop: ident, $key: ident $(, 2012: $prop_2012: ident )? $(, 2009: $prop_2009: ident )?) => {
634        if let Some((val, prefix)) = $key {
635          if !prefix.is_empty() {
636            let mut prefix = context.targets.prefixes(prefix, Feature::$prop);
637            if prefix.contains(VendorPrefix::None) {
638              $(
639                // 2009 spec, implemented by webkit and firefox.
640                if let Some(targets) = context.targets.browsers {
641                  let mut prefixes_2009 = VendorPrefix::empty();
642                  if is_flex_2009(targets) {
643                    prefixes_2009 |= VendorPrefix::WebKit;
644                  }
645                  if prefix.contains(VendorPrefix::Moz) {
646                    prefixes_2009 |= VendorPrefix::Moz;
647                  }
648                  if !prefixes_2009.is_empty() {
649                    if let Some(v) = $prop_2009::from_standard(&val) {
650                      dest.push(Property::$prop_2009(v, prefixes_2009));
651                    }
652                  }
653                }
654              )?
655            }
656
657            $(
658              let mut ms = true;
659              if prefix.contains(VendorPrefix::Ms) {
660                dest.push(Property::$prop_2012(val.clone(), VendorPrefix::Ms));
661                ms = false;
662              }
663              if !ms {
664                prefix.remove(VendorPrefix::Ms);
665              }
666            )?
667
668            // Firefox only implemented the 2009 spec prefixed.
669            prefix.remove(VendorPrefix::Moz);
670            dest.push(Property::$prop(val, prefix))
671          }
672        }
673      };
674    }
675
676    macro_rules! legacy_property {
677      ($prop: ident, $key: expr) => {
678        if let Some((val, prefix)) = $key {
679          if !prefix.is_empty() {
680            dest.push(Property::$prop(val, prefix))
681          }
682        }
683      };
684    }
685
686    // Legacy properties. These are only set if the final standard properties were unset.
687    legacy_property!(BoxOrient, box_orient);
688    legacy_property!(BoxDirection, box_direction);
689    legacy_property!(BoxOrdinalGroup, box_ordinal_group);
690    legacy_property!(BoxFlex, box_flex);
691    legacy_property!(BoxLines, box_lines);
692    legacy_property!(FlexPositive, flex_positive);
693    legacy_property!(FlexNegative, flex_negative);
694    legacy_property!(FlexPreferredSize, preferred_size.clone());
695    legacy_property!(FlexOrder, flex_order.clone());
696
697    if let Some((direction, _)) = direction {
698      if let Some(targets) = context.targets.browsers {
699        let prefixes = context.targets.prefixes(VendorPrefix::None, Feature::FlexDirection);
700        let mut prefixes_2009 = VendorPrefix::empty();
701        if is_flex_2009(targets) {
702          prefixes_2009 |= VendorPrefix::WebKit;
703        }
704        if prefixes.contains(VendorPrefix::Moz) {
705          prefixes_2009 |= VendorPrefix::Moz;
706        }
707        if !prefixes_2009.is_empty() {
708          let (orient, dir) = direction.to_2009();
709          dest.push(Property::BoxOrient(orient, prefixes_2009));
710          dest.push(Property::BoxDirection(dir, prefixes_2009));
711        }
712      }
713    }
714
715    if let (Some((direction, dir_prefix)), Some((wrap, wrap_prefix))) = (&mut direction, &mut wrap) {
716      let intersection = *dir_prefix & *wrap_prefix;
717      if !intersection.is_empty() {
718        let mut prefix = context.targets.prefixes(intersection, Feature::FlexFlow);
719        // Firefox only implemented the 2009 spec prefixed.
720        prefix.remove(VendorPrefix::Moz);
721        dest.push(Property::FlexFlow(
722          FlexFlow {
723            direction: *direction,
724            wrap: *wrap,
725          },
726          prefix,
727        ));
728        dir_prefix.remove(intersection);
729        wrap_prefix.remove(intersection);
730      }
731    }
732
733    single_property!(FlexDirection, direction);
734    single_property!(FlexWrap, wrap, 2009: BoxLines);
735
736    if let Some(targets) = context.targets.browsers {
737      if let Some((grow, _)) = grow {
738        let prefixes = context.targets.prefixes(VendorPrefix::None, Feature::FlexGrow);
739        let mut prefixes_2009 = VendorPrefix::empty();
740        if is_flex_2009(targets) {
741          prefixes_2009 |= VendorPrefix::WebKit;
742        }
743        if prefixes.contains(VendorPrefix::Moz) {
744          prefixes_2009 |= VendorPrefix::Moz;
745        }
746        if !prefixes_2009.is_empty() {
747          dest.push(Property::BoxFlex(grow, prefixes_2009));
748        }
749      }
750    }
751
752    if let (Some((grow, grow_prefix)), Some((shrink, shrink_prefix)), Some((basis, basis_prefix))) =
753      (&mut grow, &mut shrink, &mut basis)
754    {
755      let intersection = *grow_prefix & *shrink_prefix & *basis_prefix;
756      if !intersection.is_empty() {
757        let mut prefix = context.targets.prefixes(intersection, Feature::Flex);
758        // Firefox only implemented the 2009 spec prefixed.
759        prefix.remove(VendorPrefix::Moz);
760        dest.push(Property::Flex(
761          Flex {
762            grow: *grow,
763            shrink: *shrink,
764            basis: basis.clone(),
765          },
766          prefix,
767        ));
768        grow_prefix.remove(intersection);
769        shrink_prefix.remove(intersection);
770        basis_prefix.remove(intersection);
771      }
772    }
773
774    single_property!(FlexGrow, grow, 2012: FlexPositive);
775    single_property!(FlexShrink, shrink, 2012: FlexNegative);
776    single_property!(FlexBasis, basis, 2012: FlexPreferredSize);
777    single_property!(Order, order, 2012: FlexOrder, 2009: BoxOrdinalGroup);
778  }
779}
780
781#[inline]
782fn is_flex_property(property_id: &PropertyId) -> bool {
783  match property_id {
784    PropertyId::FlexDirection(_)
785    | PropertyId::BoxOrient(_)
786    | PropertyId::BoxDirection(_)
787    | PropertyId::FlexWrap(_)
788    | PropertyId::BoxLines(_)
789    | PropertyId::FlexFlow(_)
790    | PropertyId::FlexGrow(_)
791    | PropertyId::BoxFlex(_)
792    | PropertyId::FlexPositive(_)
793    | PropertyId::FlexShrink(_)
794    | PropertyId::FlexNegative(_)
795    | PropertyId::FlexBasis(_)
796    | PropertyId::FlexPreferredSize(_)
797    | PropertyId::Flex(_)
798    | PropertyId::Order(_)
799    | PropertyId::BoxOrdinalGroup(_)
800    | PropertyId::FlexOrder(_) => true,
801    _ => false,
802  }
803}