ferri-pdf 0.1.0

HTML and CSS to PDF renderer for print, in pure Rust
Documentation
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! Shorthand expansion from match trees. Omitted longhands take their initial value unless the
//! defining specification says otherwise.
use crate::style::{
    StyleError,
    component::Component,
    declaration::{self, Specified},
    grammar::{Keyword, Label, NODES, Node, Production, Property},
    wide_keywords::WideKeyword,
};
use std::sync::Arc;

type Longhands = Vec<(Property, Specified)>;

const TOP: usize = 0;
const RIGHT: usize = 1;
const BOTTOM: usize = 2;
const LEFT: usize = 3;
/// `<line-width> || <line-style> || <color>` slots.
const BORDER_PARTS: usize = 3;
const BORDER_IMAGE: [Property; 5] = [
    Property::BorderImageSource,
    Property::BorderImageSlice,
    Property::BorderImageWidth,
    Property::BorderImageOutset,
    Property::BorderImageRepeat,
];
/// Source, slice with width and outset, and repeat.
const BORDER_IMAGE_SLOTS: usize = 3;
/// `bg-layer` slots; the final layer adds `<'background-color'>` (CSS Backgrounds 3 §3.10).
const LAYER_IMAGE: usize = 0;
const LAYER_POSITION: usize = 1;
const LAYER_REPEAT: usize = 2;
const LAYER_ATTACHMENT: usize = 3;
const LAYER_ORIGIN: usize = 4;
const LAYER_CLIP: usize = 5;
const LAYER_COLOR: usize = 6;
/// CSS Flexbox 1 §7.1.1: `flex: <grow>` means `<grow> 1 0`.
const FLEX_OMITTED_FACTOR: &str = "1";
const FLEX_OMITTED_BASIS: &str = "0%";
const FLEX_NONE: [&str; 3] = ["0", "0", "auto"];
/// CSS Grid 1 §7.8: the auto-flow keyword's side of the slash names the flow axis.
const ROW_FLOW: &str = "row";
const COLUMN_FLOW: &str = "column";
const DENSE: &str = "dense";
const SYNTHESIS_ON: &str = "auto";
const SYNTHESIS_OFF: &str = "none";

pub(crate) fn expand(shorthand: Property, value: Component) -> Result<Longhands, StyleError> {
    use Property as P;
    Ok(match shorthand {
        P::Margin => edges(
            &value,
            [P::MarginTop, P::MarginRight, P::MarginBottom, P::MarginLeft],
        ),
        P::Padding => edges(
            &value,
            [
                P::PaddingTop,
                P::PaddingRight,
                P::PaddingBottom,
                P::PaddingLeft,
            ],
        ),
        P::Inset => edges(&value, [P::Top, P::Right, P::Bottom, P::Left]),
        P::BorderWidth => edges(
            &value,
            [
                P::BorderTopWidth,
                P::BorderRightWidth,
                P::BorderBottomWidth,
                P::BorderLeftWidth,
            ],
        ),
        P::BorderStyle => edges(
            &value,
            [
                P::BorderTopStyle,
                P::BorderRightStyle,
                P::BorderBottomStyle,
                P::BorderLeftStyle,
            ],
        ),
        P::BorderColor => edges(
            &value,
            [
                P::BorderTopColor,
                P::BorderRightColor,
                P::BorderBottomColor,
                P::BorderLeftColor,
            ],
        ),
        P::BorderRadius => radius(&value),
        // CSS Backgrounds 3 §4.4: `border` also resets `border-image`.
        P::Border => border(&value, &[TOP, RIGHT, BOTTOM, LEFT])
            .into_iter()
            .chain(BORDER_IMAGE.map(|property| (property, initial())))
            .collect(),
        P::BorderImage => border_image(&value),
        P::Columns => columns(&value),
        P::BorderTop => border(&value, &[TOP]),
        P::BorderRight => border(&value, &[RIGHT]),
        P::BorderBottom => border(&value, &[BOTTOM]),
        P::BorderLeft => border(&value, &[LEFT]),
        P::Overflow => pair(&value, [P::OverflowX, P::OverflowY]),
        P::Gap | P::GridGap => pair(&value, [P::RowGap, P::ColumnGap]),
        P::GridRowGap => alias(&value, P::RowGap),
        P::GridColumnGap => alias(&value, P::ColumnGap),
        P::GridRow => grid_lines(&value, [P::GridRowStart, P::GridRowEnd]),
        P::GridColumn => grid_lines(&value, [P::GridColumnStart, P::GridColumnEnd]),
        P::GridArea => grid_area(&value),
        P::GridTemplate => grid_template(&value),
        P::Grid => grid(&value)?,
        P::PlaceContent => pair(&value, [P::AlignContent, P::JustifyContent]),
        P::PlaceItems => pair(&value, [P::AlignItems, P::JustifyItems]),
        P::PlaceSelf => pair(&value, [P::AlignSelf, P::JustifySelf]),
        P::Flex => flex(&value)?,
        P::Font => crate::style::font_values::expand_font(&value)?,
        P::FontStretch => alias(value.unwrap(), P::FontWidth),
        P::FontVariant if value.keyword() == Some(Keyword::Normal) => {
            declaration::wide(P::FontVariant, WideKeyword::Initial)
        }
        P::FontVariant if crate::style::font_values::is_small_caps(&value) => {
            let mut values = declaration::wide(P::FontVariant, WideKeyword::Initial);
            values
                .iter_mut()
                .find(|(property, _)| *property == P::FontVariantCaps)
                .expect("font-variant metadata contains caps")
                .1 = longhand(P::FontVariantCaps, &Component::Keyword(Keyword::SmallCaps));
            values
        }
        P::FontSynthesis => font_synthesis(&value)?,
        P::Background => background(&value),
        P::PageBreakBefore => legacy_break(&value, P::BreakBefore)?,
        P::PageBreakAfter => legacy_break(&value, P::BreakAfter)?,
        P::PageBreakInside => legacy_break(&value, P::BreakInside)?,
        P::WordWrap => alias(&value, P::OverflowWrap),
        _ => {
            if let Some(longhands) = unordered_references(shorthand, &value)? {
                longhands
            } else {
                let value = Arc::new(value);
                declaration::longhands(shorthand)
                    .map(|longhand| (longhand, Specified::Unexpanded(shorthand, value.clone())))
                    .collect()
            }
        }
    })
}

/// A component as the value of `longhand`, shaped as parsing it directly would be.
pub(super) fn longhand(longhand: Property, component: &Component) -> Specified {
    let inner = match component {
        Component::Reference(Label::Property(_), inner) => inner.as_ref().clone(),
        other => other.clone(),
    };
    Specified::Value(Arc::new(Component::Reference(
        Label::Property(longhand),
        Box::new(inner),
    )))
}

fn initial() -> Specified {
    Specified::Wide(WideKeyword::Initial)
}

/// A value the shorthand's specification gives for omitted longhands.
fn literal(property: Property, source: &str) -> Result<Specified, StyleError> {
    declaration::value(property, source, &mut 0)?
        .map(|value| Specified::Value(Arc::new(value)))
        .ok_or_else(|| StyleError::Invalid(format!("{source} is not a {}", property.name())))
}

/// CSS Backgrounds 3 §4.1: one to four values for top, right, bottom and left.
fn edges(value: &Component, sides: [Property; 4]) -> Longhands {
    let items = value.items();
    let index = |side: usize| match (items.len(), side) {
        (1, _) => 0,
        (2 | 3, LEFT) => 1,
        (2, BOTTOM) => 0,
        _ => side,
    };
    sides
        .iter()
        .enumerate()
        .map(|(side, property)| (*property, longhand(*property, &items[index(side)])))
        .collect()
}

/// Two values where an omitted second copies the first.
fn pair(value: &Component, properties: [Property; 2]) -> Longhands {
    let items: Vec<&Component> = match value.unwrap() {
        Component::Group(items) => items
            .iter()
            .flat_map(|item| match item {
                Component::Group(nested) => nested.iter().collect(),
                single => vec![single],
            })
            .collect(),
        single => vec![single],
    };
    let first = items[0];
    let second = items.get(1).copied().unwrap_or(first);
    vec![
        (properties[0], longhand(properties[0], first)),
        (properties[1], longhand(properties[1], second)),
    ]
}

/// `<length-percentage>{1,4} [ / <length-percentage>{1,4} ]?`; an omitted vertical list
/// repeats the horizontal one.
fn radius(value: &Component) -> Longhands {
    let [horizontal, vertical] = match value.unwrap() {
        Component::Group(parts) => [
            parts[0].items(),
            parts[1]
                .items()
                .first()
                .and_then(|slash| slash.items().get(1))
                .map_or(&[][..], Component::items),
        ],
        single => [std::slice::from_ref(single), &[][..]],
    };
    let corner = |values: &[Component], index: usize| match (values.len(), index) {
        (1, _) => 0,
        (2 | 3, 3) => 1,
        (2, 2) => 0,
        _ => index,
    };
    [
        Property::BorderTopLeftRadius,
        Property::BorderTopRightRadius,
        Property::BorderBottomRightRadius,
        Property::BorderBottomLeftRadius,
    ]
    .iter()
    .enumerate()
    .map(|(index, property)| {
        let mut radii = vec![horizontal[corner(horizontal, index)].clone()];
        if !vertical.is_empty() {
            radii.push(vertical[corner(vertical, index)].clone());
        }
        (*property, longhand(*property, &Component::Group(radii)))
    })
    .collect()
}

/// `<line-width> || <line-style> || <color>` for each side.
fn border(value: &Component, sides: &[usize]) -> Longhands {
    const PARTS: [[Property; BORDER_PARTS]; 4] = [
        [
            Property::BorderTopWidth,
            Property::BorderTopStyle,
            Property::BorderTopColor,
        ],
        [
            Property::BorderRightWidth,
            Property::BorderRightStyle,
            Property::BorderRightColor,
        ],
        [
            Property::BorderBottomWidth,
            Property::BorderBottomStyle,
            Property::BorderBottomColor,
        ],
        [
            Property::BorderLeftWidth,
            Property::BorderLeftStyle,
            Property::BorderLeftColor,
        ],
    ];
    sides
        .iter()
        .flat_map(|side| {
            PARTS[*side].iter().enumerate().map(|(part, property)| {
                let specified = value
                    .slot(part)
                    .map_or_else(initial, |slot| longhand(*property, slot));
                (*property, specified)
            })
        })
        .collect()
}

/// `<'border-image-source'> || <'border-image-slice'> [ / <'border-image-width'> |
/// / <'border-image-width'>? / <'border-image-outset'> ]? || <'border-image-repeat'>`.
fn border_image(value: &Component) -> Longhands {
    BORDER_IMAGE
        .iter()
        .map(|property| {
            let found = (0..BORDER_IMAGE_SLOTS)
                .filter_map(|slot| value.slot(slot))
                .find_map(|slot| slot.find(Label::Property(*property)));
            (
                *property,
                found.map_or_else(initial, |component| longhand(*property, component)),
            )
        })
        .collect()
}

/// `[ <'column-width'> || <'column-count'> ] [ / <'column-height'> ]?`.
fn columns(value: &Component) -> Longhands {
    [
        Property::ColumnWidth,
        Property::ColumnCount,
        Property::ColumnHeight,
    ]
    .iter()
    .map(|property| {
        (
            *property,
            value
                .find(Label::Property(*property))
                .map_or_else(initial, |component| longhand(*property, component)),
        )
    })
    .collect()
}

fn flex(value: &Component) -> Result<Longhands, StyleError> {
    let properties = [
        Property::FlexGrow,
        Property::FlexShrink,
        Property::FlexBasis,
    ];
    if value.keyword() == Some(Keyword::None) {
        return properties
            .iter()
            .zip(FLEX_NONE)
            .map(|(property, source)| Ok((*property, literal(*property, source)?)))
            .collect();
    }
    let factors = value.slot(0);
    let grow = factors.and_then(|factors| factors.find(Label::Property(Property::FlexGrow)));
    let shrink = factors.and_then(|factors| factors.find(Label::Property(Property::FlexShrink)));
    let basis = value.slot(1);
    let resolve = |property: Property, found: Option<&Component>, omitted: &str| {
        found.map_or_else(
            || literal(property, omitted),
            |component| Ok(longhand(property, component)),
        )
    };
    Ok(vec![
        (
            Property::FlexGrow,
            resolve(Property::FlexGrow, grow, FLEX_OMITTED_FACTOR)?,
        ),
        (
            Property::FlexShrink,
            resolve(Property::FlexShrink, shrink, FLEX_OMITTED_FACTOR)?,
        ),
        (
            Property::FlexBasis,
            resolve(Property::FlexBasis, basis, FLEX_OMITTED_BASIS)?,
        ),
    ])
}

/// CSS Fonts 4 §3.9: each listed feature may be synthesized; the rest may not.
fn font_synthesis(value: &Component) -> Result<Longhands, StyleError> {
    [
        Property::FontSynthesisWeight,
        Property::FontSynthesisStyle,
        Property::FontSynthesisSmallCaps,
        Property::FontSynthesisPosition,
    ]
    .iter()
    .enumerate()
    .map(|(index, property)| {
        let allowed = value.slot(index).is_some();
        Ok((
            *property,
            literal(
                *property,
                if allowed { SYNTHESIS_ON } else { SYNTHESIS_OFF },
            )?,
        ))
    })
    .collect()
}

/// CSS Fragmentation 3 §3.1: legacy `page-break-*` map `always` to `page`.
fn legacy_break(value: &Component, property: Property) -> Result<Longhands, StyleError> {
    let keyword = match value.keyword() {
        Some(Keyword::Always) => Keyword::Page,
        Some(keyword) => keyword,
        None => return Err(StyleError::Invalid(format!("legacy break {value}"))),
    };
    Ok(vec![(property, literal(property, keyword.name())?)])
}

/// A legacy name alias sharing the value of the property it names.
fn alias(value: &Component, property: Property) -> Longhands {
    vec![(property, longhand(property, value))]
}

/// Per-layer longhand lists from `[ <bg-layer> , ]* <final-bg-layer>`.
fn background(value: &Component) -> Longhands {
    let mut layers = Vec::new();
    value.unwrap().references(
        &[
            Label::Production(Production::BgLayer),
            Label::Production(Production::FinalBgLayer),
        ],
        &mut layers,
    );
    let layers: Vec<&Component> = layers.into_iter().map(|(_, layer)| layer).collect();
    let position = |layer: &Component| {
        layer
            .slot(LAYER_POSITION)
            .and_then(|slot| slot.find(Label::Production(Production::BgPosition)))
            .map(|found| {
                Component::Reference(
                    Label::Production(Production::BgPosition),
                    Box::new(found.clone()),
                )
            })
    };
    let size = |layer: &Component| {
        layer
            .slot(LAYER_POSITION)
            .and_then(|slot| slot.find(Label::Production(Production::BgSize)))
            .map(|found| {
                Component::Reference(
                    Label::Production(Production::BgSize),
                    Box::new(found.clone()),
                )
            })
    };
    let slot = |index: usize| move |layer: &Component| layer.slot(index).cloned();
    let clip = |layer: &Component| {
        layer
            .slot(LAYER_CLIP)
            .or_else(|| layer.slot(LAYER_ORIGIN))
            .map(|visual_box| {
                Component::Reference(
                    Label::Production(Production::BgClip),
                    Box::new(visual_box.clone()),
                )
            })
    };
    let mut longhands = vec![
        layered(Property::BackgroundImage, &layers, &slot(LAYER_IMAGE)),
        layered(Property::BackgroundPosition, &layers, &position),
        layered(Property::BackgroundSize, &layers, &size),
        layered(Property::BackgroundRepeat, &layers, &slot(LAYER_REPEAT)),
        layered(
            Property::BackgroundAttachment,
            &layers,
            &slot(LAYER_ATTACHMENT),
        ),
        layered(Property::BackgroundOrigin, &layers, &slot(LAYER_ORIGIN)),
        layered(Property::BackgroundClip, &layers, &clip),
    ];
    let color = layers
        .last()
        .and_then(|layer| layer.slot(LAYER_COLOR))
        .map_or_else(initial, |color| longhand(Property::BackgroundColor, color));
    longhands.push((Property::BackgroundColor, color));
    longhands
}

/// One list item per layer; layers that omit it repeat the longhand's initial item.
fn layered(
    property: Property,
    layers: &[&Component],
    item: &dyn Fn(&Component) -> Option<Component>,
) -> (Property, Specified) {
    let items: Vec<Option<Component>> = layers.iter().map(|layer| item(layer)).collect();
    if items.iter().all(Option::is_none) {
        return (property, initial());
    }
    let fallback = declaration::initial(property)
        .and_then(|initial| initial.items().first())
        .cloned();
    let items = items
        .into_iter()
        .map(|item| item.or_else(|| fallback.clone()))
        .collect::<Option<Vec<_>>>();
    match items {
        Some(items) => (property, longhand(property, &Component::Group(items))),
        None => (property, initial()),
    }
}

/// Shorthands whose grammar is `<'a'> || <'b'> …` (or `&&`) over their own longhands: each
/// slot is its longhand's value and omitted longhands are initial.
fn unordered_references(
    shorthand: Property,
    value: &Component,
) -> Result<Option<Longhands>, StyleError> {
    let Node::Reference(_, target) = NODES[usize::from(shorthand.data().root)] else {
        return Ok(None);
    };
    let (Node::AnyOf(alternatives) | Node::AllOf(alternatives)) = &NODES[usize::from(target)]
    else {
        return Ok(None);
    };
    let direct = shorthand.longhands();
    let Some(properties) = alternatives
        .iter()
        .map(|alternative| match NODES[usize::from(*alternative)] {
            Node::Reference(Label::Property(property), _) if direct.contains(&property) => {
                Some(property)
            }
            _ => None,
        })
        .collect::<Option<Vec<_>>>()
    else {
        return Ok(None);
    };
    if direct.iter().any(|longhand| !properties.contains(longhand)) {
        return Ok(None);
    }
    let mut longhands = Longhands::new();
    for (index, property) in properties.into_iter().enumerate() {
        match value.slot(index) {
            Some(slot) if !property.longhands().is_empty() => {
                longhands.extend(expand(property, slot.clone())?);
            }
            Some(slot) => longhands.push((property, longhand(property, slot))),
            None => longhands.extend(declaration::longhands(property).map(|l| (l, initial()))),
        }
    }
    Ok(Some(longhands))
}

/// A bare `<custom-ident>`, which omitted grid lines copy (CSS Grid 1 §8.4).
fn bare_name(line: &Component) -> bool {
    matches!(line.unwrap(), Component::Ident(_))
}

/// `grid-row` and `grid-column`: `<grid-line> [ / <grid-line> ]?`.
fn grid_lines(value: &Component, properties: [Property; 2]) -> Longhands {
    grid_placement(value, &properties, &[None, Some(0)])
}

/// `grid-area`: row start, column start, row end and column end. Omitted ends copy their
/// start; an omitted column start copies the row start.
fn grid_area(value: &Component) -> Longhands {
    grid_placement(
        value,
        &[
            Property::GridRowStart,
            Property::GridColumnStart,
            Property::GridRowEnd,
            Property::GridColumnEnd,
        ],
        &[None, Some(0), Some(0), Some(1)],
    )
}

/// Placement longhands from the written lines; an omitted one copies the line at its
/// `sources` index when that is a bare name, and is `auto` otherwise.
fn grid_placement(
    value: &Component,
    properties: &[Property],
    sources: &[Option<usize>],
) -> Longhands {
    let mut lines = Vec::new();
    value.references(&[Label::Production(Production::GridLine)], &mut lines);
    let mut resolved: Vec<Option<&Component>> = Vec::with_capacity(properties.len());
    for (index, source) in sources.iter().enumerate() {
        let line = lines.get(index).map(|(_, line)| *line).or_else(|| {
            source
                .and_then(|source| resolved[source])
                .filter(|line| bare_name(line))
        });
        resolved.push(line);
    }
    properties
        .iter()
        .zip(resolved)
        .map(|(property, line)| {
            (
                *property,
                line.map_or_else(initial, |line| longhand(*property, line)),
            )
        })
        .collect()
}

/// `auto`, the track size a template row without one takes.
fn auto_track() -> Component {
    Component::Reference(
        Label::Production(Production::TrackSize),
        Box::new(Component::Reference(
            Label::Production(Production::TrackBreadth),
            Box::new(Component::Keyword(Keyword::Auto)),
        )),
    )
}

/// `grid-template`: `none`, `<rows> / <columns>`, or area strings with row sizes and names.
fn grid_template(value: &Component) -> Longhands {
    let properties = [
        Property::GridTemplateRows,
        Property::GridTemplateColumns,
        Property::GridTemplateAreas,
    ];
    if value.keyword() == Some(Keyword::None) {
        return properties
            .iter()
            .map(|property| (*property, initial()))
            .collect();
    }
    if let Some(rows) = value.find(Label::Property(Property::GridTemplateRows)) {
        let columns = value.find(Label::Property(Property::GridTemplateColumns));
        return vec![
            (properties[0], longhand(properties[0], rows)),
            (
                properties[1],
                columns.map_or_else(initial, |columns| longhand(properties[1], columns)),
            ),
            (properties[2], initial()),
        ];
    }
    let parts = value.items();
    let rows = parts.first().map_or(&[][..], Component::items);
    let mut tracks = Vec::new();
    let mut strings = Vec::new();
    for row in rows {
        let [before, string, size, after] = row.items() else {
            continue;
        };
        tracks.extend(before.items().iter().cloned());
        strings.push(string.clone());
        tracks.push(size.items().first().cloned().unwrap_or_else(auto_track));
        tracks.extend(after.items().iter().cloned());
    }
    let columns = parts
        .get(1)
        .and_then(|tail| tail.find(Label::Production(Production::ExplicitTrackList)));
    vec![
        (
            properties[0],
            longhand(properties[0], &Component::Group(tracks)),
        ),
        (
            properties[1],
            columns.map_or_else(initial, |columns| longhand(properties[1], columns)),
        ),
        (
            properties[2],
            longhand(properties[2], &Component::Group(strings)),
        ),
    ]
}

/// `grid`: a template, or explicit tracks on one axis and auto-flow tracks on the other.
fn grid(value: &Component) -> Result<Longhands, StyleError> {
    let template = match value {
        Component::Reference(Label::Property(Property::Grid), inner) => inner.as_ref(),
        other => other,
    };
    let mut implicit = vec![
        (Property::GridAutoRows, initial()),
        (Property::GridAutoColumns, initial()),
        (Property::GridAutoFlow, initial()),
    ];
    if matches!(
        template,
        Component::Reference(Label::Property(Property::GridTemplate), _)
    ) {
        let mut longhands = grid_template(template);
        longhands.append(&mut implicit);
        return Ok(longhands);
    }
    let mut keywords = Vec::new();
    value.keywords(&mut keywords);
    let dense = keywords.contains(&Keyword::Dense);
    let rows = value.find(Label::Property(Property::GridTemplateRows));
    let (template, auto, flow) = match rows {
        Some(rows) => (
            (Property::GridTemplateRows, rows),
            Property::GridAutoColumns,
            COLUMN_FLOW,
        ),
        None => (
            (
                Property::GridTemplateColumns,
                value
                    .find(Label::Property(Property::GridTemplateColumns))
                    .ok_or_else(|| StyleError::Invalid(format!("grid: {value}")))?,
            ),
            Property::GridAutoRows,
            ROW_FLOW,
        ),
    };
    let flow = if dense {
        format!("{flow} {DENSE}")
    } else {
        flow.to_owned()
    };
    let mut longhands = vec![
        (Property::GridTemplateRows, initial()),
        (Property::GridTemplateColumns, initial()),
        (Property::GridTemplateAreas, initial()),
        (Property::GridAutoRows, initial()),
        (Property::GridAutoColumns, initial()),
        (
            Property::GridAutoFlow,
            literal(Property::GridAutoFlow, &flow)?,
        ),
    ];
    for (property, specified) in &mut longhands {
        if *property == template.0 {
            *specified = longhand(*property, template.1);
        } else if *property == auto
            && let Some(sizes) = value.find(Label::Property(auto))
        {
            *specified = longhand(*property, sizes);
        }
    }
    Ok(longhands)
}