1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! CSS properties related to display.

use super::custom::UnparsedProperty;
use super::{Property, PropertyId};
use crate::context::PropertyHandlerContext;
use crate::declaration::DeclarationList;
use crate::error::{ParserError, PrinterError};
use crate::macros::enum_property;
use crate::prefixes::{is_flex_2009, Feature};
use crate::printer::Printer;
use crate::targets::Browsers;
use crate::traits::{Parse, PropertyHandler, ToCss};
use crate::vendor_prefix::VendorPrefix;
use cssparser::*;

enum_property! {
  /// A [`<display-outside>`](https://drafts.csswg.org/css-display-3/#typedef-display-outside) value.
  #[allow(missing_docs)]
  pub enum DisplayOutside {
    "block": Block,
    "inline": Inline,
    "run-in": RunIn,
  }
}

/// A [`<display-inside>`](https://drafts.csswg.org/css-display-3/#typedef-display-inside) value.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(rename_all = "kebab-case")
)]
#[allow(missing_docs)]
pub enum DisplayInside {
  Flow,
  FlowRoot,
  Table,
  Flex(VendorPrefix),
  Box(VendorPrefix),
  Grid,
  Ruby,
}

impl<'i> Parse<'i> for DisplayInside {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    let location = input.current_source_location();
    let ident = input.expect_ident()?;
    match_ignore_ascii_case! { &*ident,
      "flow" => Ok(DisplayInside::Flow),
      "flow-root" => Ok(DisplayInside::FlowRoot),
      "table" => Ok(DisplayInside::Table),
      "flex" => Ok(DisplayInside::Flex(VendorPrefix::None)),
      "-webkit-flex" => Ok(DisplayInside::Flex(VendorPrefix::WebKit)),
      "-ms-flexbox" => Ok(DisplayInside::Flex(VendorPrefix::Ms)),
      "-webkit-box" => Ok(DisplayInside::Box(VendorPrefix::WebKit)),
      "-moz-box" => Ok(DisplayInside::Box(VendorPrefix::Moz)),
      "grid" => Ok(DisplayInside::Grid),
      "ruby" => Ok(DisplayInside::Ruby),
      _ => Err(location.new_unexpected_token_error(
        cssparser::Token::Ident(ident.clone())
      ))
    }
  }
}

impl ToCss for DisplayInside {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      DisplayInside::Flow => dest.write_str("flow"),
      DisplayInside::FlowRoot => dest.write_str("flow-root"),
      DisplayInside::Table => dest.write_str("table"),
      DisplayInside::Flex(prefix) => {
        prefix.to_css(dest)?;
        if *prefix == VendorPrefix::Ms {
          dest.write_str("flexbox")
        } else {
          dest.write_str("flex")
        }
      }
      DisplayInside::Box(prefix) => {
        prefix.to_css(dest)?;
        dest.write_str("box")
      }
      DisplayInside::Grid => dest.write_str("grid"),
      DisplayInside::Ruby => dest.write_str("ruby"),
    }
  }
}

impl DisplayInside {
  fn is_equivalent(&self, other: &DisplayInside) -> bool {
    match (self, other) {
      (DisplayInside::Flex(_), DisplayInside::Flex(_)) => true,
      (DisplayInside::Box(_), DisplayInside::Box(_)) => true,
      (DisplayInside::Flex(_), DisplayInside::Box(_)) => true,
      (DisplayInside::Box(_), DisplayInside::Flex(_)) => true,
      _ => self == other,
    }
  }
}

/// A pair of inside and outside display values, as used in the `display` property.
///
/// See [Display](Display).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DisplayPair {
  /// The outside display value.
  pub outside: DisplayOutside,
  /// The inside display value.
  pub inside: DisplayInside,
  /// Whether this is a list item.
  pub is_list_item: bool,
}

impl<'i> Parse<'i> for DisplayPair {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    let mut list_item = false;
    let mut outside = None;
    let mut inside = None;

    loop {
      if input.try_parse(|input| input.expect_ident_matching("list-item")).is_ok() {
        list_item = true;
        continue;
      }

      if outside.is_none() {
        if let Ok(o) = input.try_parse(DisplayOutside::parse) {
          outside = Some(o);
          continue;
        }
      }

      if inside.is_none() {
        if let Ok(i) = input.try_parse(DisplayInside::parse) {
          inside = Some(i);
          continue;
        }
      }

      break;
    }

    if list_item || inside.is_some() || outside.is_some() {
      let inside = inside.unwrap_or(DisplayInside::Flow);
      let outside = outside.unwrap_or(match inside {
        // "If <display-outside> is omitted, the element’s outside display type
        // defaults to block — except for ruby, which defaults to inline."
        // https://drafts.csswg.org/css-display/#inside-model
        DisplayInside::Ruby => DisplayOutside::Inline,
        _ => DisplayOutside::Block,
      });

      if list_item && !matches!(inside, DisplayInside::Flow | DisplayInside::FlowRoot) {
        return Err(input.new_custom_error(ParserError::InvalidDeclaration));
      }

      return Ok(DisplayPair {
        outside,
        inside,
        is_list_item: list_item,
      });
    }

    let location = input.current_source_location();
    let ident = input.expect_ident()?;
    match_ignore_ascii_case! { &*ident,
      "inline-block" => Ok(DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::FlowRoot,
        is_list_item: false
      }),
      "inline-table" => Ok(DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Table,
        is_list_item: false
      }),
      "inline-flex" => Ok(DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Flex(VendorPrefix::None),
        is_list_item: false
      }),
      "-webkit-inline-flex" => Ok(DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Flex(VendorPrefix::WebKit),
        is_list_item: false
      }),
      "-ms-inline-flexbox" => Ok(DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Flex(VendorPrefix::Ms),
        is_list_item: false
      }),
      "-webkit-inline-box" => Ok(DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Box(VendorPrefix::WebKit),
        is_list_item: false
      }),
      "-moz-inline-box" => Ok(DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Box(VendorPrefix::Moz),
        is_list_item: false
      }),
      "inline-grid" => Ok(DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Grid,
        is_list_item: false
      }),
      _ => Err(location.new_unexpected_token_error(
        cssparser::Token::Ident(ident.clone())
      ))
    }
  }
}

impl ToCss for DisplayPair {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::FlowRoot,
        is_list_item: false,
      } => dest.write_str("inline-block"),
      DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Table,
        is_list_item: false,
      } => dest.write_str("inline-table"),
      DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Flex(prefix),
        is_list_item: false,
      } => {
        prefix.to_css(dest)?;
        if *prefix == VendorPrefix::Ms {
          dest.write_str("inline-flexbox")
        } else {
          dest.write_str("inline-flex")
        }
      }
      DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Box(prefix),
        is_list_item: false,
      } => {
        prefix.to_css(dest)?;
        dest.write_str("inline-box")
      }
      DisplayPair {
        outside: DisplayOutside::Inline,
        inside: DisplayInside::Grid,
        is_list_item: false,
      } => dest.write_str("inline-grid"),
      DisplayPair {
        outside,
        inside,
        is_list_item,
      } => {
        let default_outside = match inside {
          DisplayInside::Ruby => DisplayOutside::Inline,
          _ => DisplayOutside::Block,
        };

        let mut needs_space = false;
        if *outside != default_outside || (*inside == DisplayInside::Flow && !*is_list_item) {
          outside.to_css(dest)?;
          needs_space = true;
        }

        if *inside != DisplayInside::Flow {
          if needs_space {
            dest.write_char(' ')?;
          }
          inside.to_css(dest)?;
          needs_space = true;
        }

        if *is_list_item {
          if needs_space {
            dest.write_char(' ')?;
          }
          dest.write_str("list-item")?;
        }

        Ok(())
      }
    }
  }
}

enum_property! {
  /// A `display` keyword.
  ///
  /// See [Display](Display).
  #[allow(missing_docs)]
  pub enum DisplayKeyword {
    "none": None,
    "contents": Contents,
    "table-row-group": TableRowGroup,
    "table-header-group": TableHeaderGroup,
    "table-footer-group": TableFooterGroup,
    "table-row": TableRow,
    "table-cell": TableCell,
    "table-column-group": TableColumnGroup,
    "table-column": TableColumn,
    "table-caption": TableCaption,
    "ruby-base": RubyBase,
    "ruby-text": RubyText,
    "ruby-base-container": RubyBaseContainer,
    "ruby-text-container": RubyTextContainer,
  }
}

/// A value for the [display](https://drafts.csswg.org/css-display-3/#the-display-properties) property.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
  feature = "serde",
  derive(serde::Serialize, serde::Deserialize),
  serde(tag = "type", content = "value", rename_all = "kebab-case")
)]
pub enum Display {
  /// A display keyword.
  Keyword(DisplayKeyword),
  /// The inside and outside display values.
  Pair(DisplayPair),
}

impl<'i> Parse<'i> for Display {
  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
    if let Ok(pair) = input.try_parse(DisplayPair::parse) {
      return Ok(Display::Pair(pair));
    }

    let keyword = DisplayKeyword::parse(input)?;
    Ok(Display::Keyword(keyword))
  }
}

impl ToCss for Display {
  fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
  where
    W: std::fmt::Write,
  {
    match self {
      Display::Keyword(keyword) => keyword.to_css(dest),
      Display::Pair(pair) => pair.to_css(dest),
    }
  }
}

enum_property! {
  /// A value for the [visibility](https://drafts.csswg.org/css-display-3/#visibility) property.
  pub enum Visibility {
    /// The element is visible.
    Visible,
    /// The element is hidden.
    Hidden,
    /// The element is collapsed.
    Collapse,
  }
}

#[derive(Default)]
pub(crate) struct DisplayHandler<'i> {
  targets: Option<Browsers>,
  decls: Vec<Property<'i>>,
  display: Option<Display>,
}

impl<'i> DisplayHandler<'i> {
  pub fn new(targets: Option<Browsers>) -> Self {
    DisplayHandler {
      targets,
      ..DisplayHandler::default()
    }
  }
}

impl<'i> PropertyHandler<'i> for DisplayHandler<'i> {
  fn handle_property(
    &mut self,
    property: &Property<'i>,
    dest: &mut DeclarationList<'i>,
    context: &mut PropertyHandlerContext<'i, '_>,
  ) -> bool {
    if let Property::Display(display) = property {
      match (&self.display, display) {
        (Some(Display::Pair(cur)), Display::Pair(new)) => {
          // If the new value is different but equivalent (e.g. different vendor prefix),
          // we need to preserve multiple values.
          if cur.outside == new.outside
            && cur.is_list_item == new.is_list_item
            && cur.inside != new.inside
            && cur.inside.is_equivalent(&new.inside)
          {
            // If we have targets, and there is no vendor prefix, clear the existing
            // declarations. The prefixes will be filled in later. Otherwise, if there
            // are no targets, or there is a vendor prefix, add a new declaration.
            if self.targets.is_some() && new.inside == DisplayInside::Flex(VendorPrefix::None) {
              self.decls.clear();
            } else if self.targets.is_none() || cur.inside != DisplayInside::Flex(VendorPrefix::None) {
              self.decls.push(Property::Display(self.display.clone().unwrap()));
            }
          }
        }
        _ => {}
      }

      self.display = Some(display.clone());
      return true;
    }

    if matches!(
      property,
      Property::Unparsed(UnparsedProperty {
        property_id: PropertyId::Display,
        ..
      })
    ) {
      self.finalize(dest, context);
      dest.push(property.clone());
      return true;
    }

    false
  }

  fn finalize(&mut self, dest: &mut DeclarationList<'i>, _: &mut PropertyHandlerContext<'i, '_>) {
    if self.display.is_none() {
      return;
    }

    dest.extend(self.decls.drain(..));

    if let Some(display) = std::mem::take(&mut self.display) {
      // If we have an unprefixed `flex` value, then add the necessary prefixed values.
      if let Display::Pair(DisplayPair {
        inside: DisplayInside::Flex(VendorPrefix::None),
        outside,
        ..
      }) = display
      {
        if let Some(targets) = self.targets {
          let prefixes = Feature::DisplayFlex.prefixes_for(targets);

          // Handle legacy -webkit-box/-moz-box values if needed.
          if is_flex_2009(targets) {
            if prefixes.contains(VendorPrefix::WebKit) {
              dest.push(Property::Display(Display::Pair(DisplayPair {
                inside: DisplayInside::Box(VendorPrefix::WebKit),
                outside: outside.clone(),
                is_list_item: false,
              })));
            }

            if prefixes.contains(VendorPrefix::Moz) {
              dest.push(Property::Display(Display::Pair(DisplayPair {
                inside: DisplayInside::Box(VendorPrefix::Moz),
                outside: outside.clone(),
                is_list_item: false,
              })));
            }
          }

          if prefixes.contains(VendorPrefix::WebKit) {
            dest.push(Property::Display(Display::Pair(DisplayPair {
              inside: DisplayInside::Flex(VendorPrefix::WebKit),
              outside: outside.clone(),
              is_list_item: false,
            })));
          }

          if prefixes.contains(VendorPrefix::Ms) {
            dest.push(Property::Display(Display::Pair(DisplayPair {
              inside: DisplayInside::Flex(VendorPrefix::Ms),
              outside: outside.clone(),
              is_list_item: false,
            })));
          }
        }
      }

      dest.push(Property::Display(display))
    }
  }
}