spindrift 0.1.0

A HTML/CSS to PDF renderer, targeting spec compliance and efficiency
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
use super::*;

/// Computed `clip-path` support relevant to paint isolation and clipping.
///
/// A basic-shape path establishes a stacking context and clips to the
/// associated geometry box. CSS Masking defines the default geometry box as
/// the border box:
/// <https://www.w3.org/TR/css-masking-1/#the-clip-path>.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ClipPath {
    None,
    Polygon(Vec<ClipPathPolygonPoint>),
    Inset {
        top: ComputedLengthPercentage,
        right: ComputedLengthPercentage,
        bottom: ComputedLengthPercentage,
        left: ComputedLengthPercentage,
    },
    Shape,
    Url,
}

impl ClipPath {
    pub(crate) fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        match self {
            Self::Polygon(points) => {
                for point in points {
                    point.x.resolve_root_font_metric_lengths(basis);
                    point.y.resolve_root_font_metric_lengths(basis);
                }
            }
            Self::Inset {
                top,
                right,
                bottom,
                left,
            } => {
                for value in [top, right, bottom, left] {
                    value.resolve_root_font_metric_lengths(basis);
                }
            }
            Self::None | Self::Shape | Self::Url => {}
        }
    }

    pub(crate) fn requires_root_font_metrics(&self) -> bool {
        match self {
            Self::Polygon(points) => points.iter().any(|point| {
                point.x.requires_root_font_metrics() || point.y.requires_root_font_metrics()
            }),
            Self::Inset {
                top,
                right,
                bottom,
                left,
            } => [top, right, bottom, left]
                .into_iter()
                .any(|value| value.requires_root_font_metrics()),
            Self::None | Self::Shape | Self::Url => false,
        }
    }
}

/// Computed legacy CSS 2 `clip` value for absolutely positioned boxes.
///
/// Unlike `clip-path`, `clip` is a rectangle whose four physical edges are
/// offsets from the box's border edges. Percentages are invalid and `auto`
/// keeps the corresponding generated border-box edge. Keeping the edges
/// typed until paint has the used border box prevents a layout-relative value
/// from escaping into page paint as an untyped scalar.
/// <https://drafts.csswg.org/css2/#propdef-clip>
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum LegacyClip {
    Auto,
    Rect([LegacyClipEdge; 4]),
}

impl LegacyClip {
    pub(crate) const AUTO: Self = Self::Auto;

    pub(crate) fn forces_flattening(&self) -> bool {
        !matches!(self, Self::Auto)
    }

    pub(crate) fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        let Self::Rect(edges) = self else {
            return;
        };
        for edge in edges {
            if let LegacyClipEdge::Length(value) = edge {
                value.resolve_root_font_metric_lengths(basis);
            }
        }
    }

    pub(crate) fn requires_root_font_metrics(&self) -> bool {
        matches!(self, Self::Rect(edges) if edges.iter().any(|edge| {
            matches!(edge, LegacyClipEdge::Length(value) if value.requires_root_font_metrics())
        }))
    }
}

/// One physical edge of a legacy CSS 2 `clip: rect()` value, in top, right,
/// bottom, left order.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum LegacyClipEdge {
    Auto,
    Length(ComputedLengthPercentage),
}

/// One `<length-percentage> <length-percentage>` vertex of `polygon()`.
///
/// Keeping each coordinate as a computed length percentage delays resolution
/// until the relevant `clip-path` geometry box is known.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ClipPathPolygonPoint {
    pub(crate) x: ComputedLengthPercentage,
    pub(crate) y: ComputedLengthPercentage,
}

/// Computed CSS Shapes Level 1 `shape-outside` value.
///
/// Percentages deliberately remain unresolved until float layout has selected
/// the shape reference box. CSS Shapes changes a float's wrapping area, not
/// its margin-box placement or painting:
/// <https://drafts.csswg.org/css-shapes-1/#shape-outside-property>.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ShapeOutside {
    None,
    Box(ShapeBox),
    /// An image alpha contour. CSS Shapes sizes this image as a replaced
    /// element with the float's used content-box dimensions.
    /// <https://drafts.csswg.org/css-shapes-1/#shapes-from-image>
    Image(BackgroundImage),
    Basic {
        shape: BasicShape,
        reference_box: ShapeBox,
    },
}

impl ShapeOutside {
    pub(crate) const NONE: Self = Self::None;

    pub(crate) fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        match self {
            Self::Image(image) => image.resolve_root_font_metric_lengths(basis),
            Self::Basic { shape, .. } => shape.resolve_root_font_metric_lengths(basis),
            Self::None | Self::Box(_) => {}
        }
    }

    pub(crate) fn requires_root_font_metrics(&self) -> bool {
        match self {
            Self::Image(image) => image.requires_root_font_metrics(),
            Self::Basic { shape, .. } => shape.requires_root_font_metrics(),
            Self::None | Self::Box(_) => false,
        }
    }
}

/// The reference box used by CSS Shapes float-area geometry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ShapeBox {
    Margin,
    Border,
    Padding,
    Content,
}

/// CSS Shapes basic shapes. Coordinates remain typed through cascade so the
/// reference box selected by float layout supplies their percentage bases.
/// <https://drafts.csswg.org/css-shapes/#basic-shape-functions>
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BasicShape {
    Inset(ShapeInset),
    Circle(ShapeCircle),
    Ellipse(ShapeEllipse),
    Polygon(ShapePolygon),
    Path(ShapePath),
    Shape(ShapeFunction),
}

impl BasicShape {
    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        match self {
            Self::Inset(shape) => {
                for value in [
                    &mut shape.top,
                    &mut shape.right,
                    &mut shape.bottom,
                    &mut shape.left,
                ] {
                    value.resolve_root_font_metric_lengths(basis);
                }
                shape.radii.resolve_root_font_metric_lengths(basis);
            }
            Self::Circle(shape) => {
                shape.radius.resolve_root_font_metric_lengths(basis);
                shape.position.resolve_root_font_metric_lengths(basis);
            }
            Self::Ellipse(shape) => {
                shape
                    .horizontal_radius
                    .resolve_root_font_metric_lengths(basis);
                shape
                    .vertical_radius
                    .resolve_root_font_metric_lengths(basis);
                shape.position.resolve_root_font_metric_lengths(basis);
            }
            Self::Polygon(shape) => {
                for point in &mut shape.vertices {
                    point.x.resolve_root_font_metric_lengths(basis);
                    point.y.resolve_root_font_metric_lengths(basis);
                }
            }
            Self::Path(_) => {}
            Self::Shape(shape) => shape.resolve_root_font_metric_lengths(basis),
        }
    }

    fn requires_root_font_metrics(&self) -> bool {
        match self {
            Self::Inset(shape) => {
                [&shape.top, &shape.right, &shape.bottom, &shape.left]
                    .into_iter()
                    .any(|value| value.requires_root_font_metrics())
                    || shape.radii.requires_root_font_metrics()
            }
            Self::Circle(shape) => {
                shape.radius.requires_root_font_metrics()
                    || shape.position.requires_root_font_metrics()
            }
            Self::Ellipse(shape) => {
                shape.horizontal_radius.requires_root_font_metrics()
                    || shape.vertical_radius.requires_root_font_metrics()
                    || shape.position.requires_root_font_metrics()
            }
            Self::Polygon(shape) => shape.vertices.iter().any(|point| {
                point.x.requires_root_font_metrics() || point.y.requires_root_font_metrics()
            }),
            Self::Path(_) => false,
            Self::Shape(shape) => shape.requires_root_font_metrics(),
        }
    }
}

impl ShapeCircleRadius {
    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        if let Self::LengthPercentage(value) = self {
            value.resolve_root_font_metric_lengths(basis);
        }
    }

    fn requires_root_font_metrics(&self) -> bool {
        matches!(self, Self::LengthPercentage(value) if value.requires_root_font_metrics())
    }
}

impl ShapeEllipseRadius {
    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        if let Self::LengthPercentage(value) = self {
            value.resolve_root_font_metric_lengths(basis);
        }
    }

    fn requires_root_font_metrics(&self) -> bool {
        matches!(self, Self::LengthPercentage(value) if value.requires_root_font_metrics())
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ShapeInset {
    pub(crate) top: ComputedLengthPercentage,
    pub(crate) right: ComputedLengthPercentage,
    pub(crate) bottom: ComputedLengthPercentage,
    pub(crate) left: ComputedLengthPercentage,
    pub(crate) radii: BorderRadius,
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ShapeCircle {
    pub(crate) radius: ShapeCircleRadius,
    pub(crate) position: ShapePosition,
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ShapeCircleRadius {
    LengthPercentage(ComputedLengthPercentage),
    ClosestSide,
    FarthestSide,
    ClosestCorner,
    FarthestCorner,
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ShapeEllipse {
    pub(crate) horizontal_radius: ShapeEllipseRadius,
    pub(crate) vertical_radius: ShapeEllipseRadius,
    pub(crate) position: ShapePosition,
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ShapeEllipseRadius {
    LengthPercentage(ComputedLengthPercentage),
    ClosestSide,
    FarthestSide,
}

/// Typed CSS Shapes Level 1 `polygon()` contour.
///
/// Vertices retain their independent percentage bases until float layout has
/// resolved the selected shape reference box:
/// <https://drafts.csswg.org/css-shapes-1/#funcdef-polygon>.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ShapePolygon {
    pub(crate) fill_rule: ShapeFillRule,
    pub(crate) vertices: Vec<ShapePolygonPoint>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ShapeFillRule {
    NonZero,
    EvenOdd,
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ShapePolygonPoint {
    pub(crate) x: ComputedLengthPercentage,
    pub(crate) y: ComputedLengthPercentage,
}

/// The SVG path data accepted by CSS Shapes `path()`. The SVG parser validates
/// it at cascade time; retaining its authored coordinate stream keeps CSS-px
/// coordinates distinct from reference-box-relative CSS lengths.
/// <https://drafts.csswg.org/css-shapes/#funcdef-path>
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ShapePath {
    pub(crate) fill_rule: ShapeFillRule,
    pub(crate) data: String,
}

/// CSS Shapes Level 2 `shape()` value.
/// <https://drafts.csswg.org/css-shapes-2/#shape-function>
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ShapeFunction {
    pub(crate) fill_rule: ShapeFillRule,
    pub(crate) origin: ShapePosition,
    pub(crate) commands: Vec<ShapeCommand>,
}

impl ShapeFunction {
    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        self.origin.resolve_root_font_metric_lengths(basis);
        for command in &mut self.commands {
            command.resolve_root_font_metric_lengths(basis);
        }
    }

    fn requires_root_font_metrics(&self) -> bool {
        self.origin.requires_root_font_metrics()
            || self
                .commands
                .iter()
                .any(ShapeCommand::requires_root_font_metrics)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ShapeCommandDirection {
    To,
    By,
}

/// A shape command keeps its direction rather than eagerly converting `by`
/// into an absolute point: a percentage displacement is resolved against the
/// used reference box independently on each physical axis.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ShapeCommand {
    Move {
        direction: ShapeCommandDirection,
        point: ShapePosition,
    },
    Line {
        direction: ShapeCommandDirection,
        point: ShapePosition,
    },
    HorizontalLine {
        direction: ShapeCommandDirection,
        value: ComputedLengthPercentage,
    },
    VerticalLine {
        direction: ShapeCommandDirection,
        value: ComputedLengthPercentage,
    },
    Curve {
        direction: ShapeCommandDirection,
        point: ShapePosition,
        control_start: ShapePosition,
        control_end: ShapePosition,
    },
    Smooth {
        direction: ShapeCommandDirection,
        point: ShapePosition,
        control_end: ShapePosition,
    },
    Arc {
        direction: ShapeCommandDirection,
        point: ShapePosition,
        radius_x: ComputedLengthPercentage,
        radius_y: ComputedLengthPercentage,
        rotation_radians: f32,
        large: bool,
        clockwise: bool,
    },
    Close,
}

impl ShapeCommand {
    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        let resolve_point =
            |point: &mut ShapePosition| point.resolve_root_font_metric_lengths(basis);
        match self {
            Self::Move { point, .. } | Self::Line { point, .. } => resolve_point(point),
            Self::HorizontalLine { value, .. } | Self::VerticalLine { value, .. } => {
                value.resolve_root_font_metric_lengths(basis)
            }
            Self::Curve {
                point,
                control_start,
                control_end,
                ..
            } => {
                resolve_point(point);
                resolve_point(control_start);
                resolve_point(control_end);
            }
            Self::Smooth {
                point, control_end, ..
            } => {
                resolve_point(point);
                resolve_point(control_end);
            }
            Self::Arc {
                point,
                radius_x,
                radius_y,
                ..
            } => {
                resolve_point(point);
                radius_x.resolve_root_font_metric_lengths(basis);
                radius_y.resolve_root_font_metric_lengths(basis);
            }
            Self::Close => {}
        }
    }

    fn requires_root_font_metrics(&self) -> bool {
        let point_requires = |point: &ShapePosition| point.requires_root_font_metrics();
        match self {
            Self::Move { point, .. } | Self::Line { point, .. } => point_requires(point),
            Self::HorizontalLine { value, .. } | Self::VerticalLine { value, .. } => {
                value.requires_root_font_metrics()
            }
            Self::Curve {
                point,
                control_start,
                control_end,
                ..
            } => {
                point_requires(point)
                    || point_requires(control_start)
                    || point_requires(control_end)
            }
            Self::Smooth {
                point, control_end, ..
            } => point_requires(point) || point_requires(control_end),
            Self::Arc {
                point,
                radius_x,
                radius_y,
                ..
            } => {
                point_requires(point)
                    || radius_x.requires_root_font_metrics()
                    || radius_y.requires_root_font_metrics()
            }
            Self::Close => false,
        }
    }
}

/// A basic-shape center expressed as coordinates in its reference box.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ShapePosition {
    pub(crate) x: ComputedLengthPercentage,
    pub(crate) y: ComputedLengthPercentage,
}

impl ShapePosition {
    pub(crate) fn center() -> Self {
        Self {
            x: ComputedLengthPercentage::from_percent(0.5),
            y: ComputedLengthPercentage::from_percent(0.5),
        }
    }

    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        self.x.resolve_root_font_metric_lengths(basis);
        self.y.resolve_root_font_metric_lengths(basis);
    }

    fn requires_root_font_metrics(&self) -> bool {
        self.x.requires_root_font_metrics() || self.y.requires_root_font_metrics()
    }
}

/// Computed CSS Borders 4 `border-shape` value.
///
/// `border-shape` changes only painting and overflow clipping; it does not
/// alter box layout. Basic-shape coordinates stay as typed computed lengths
/// until their selected geometry box is available during paint:
/// <https://drafts.csswg.org/css-borders-4/#border-shape>.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BorderShape {
    None,
    Circle(BorderShapeCircle),
    Ellipse(BorderShapeEllipse),
    Path(BorderShapePath),
    Inset(BorderShapeInset),
    Polygon(BorderShapePolygon),
    /// The outer and inner contours of a CSS Borders 4 `border-shape`.
    ///
    /// Keeping the pair heterogeneous avoids encoding an artificial
    /// same-primitive restriction in the computed value: the grammar permits
    /// any two basic shapes, each with its own geometry box.
    Pair {
        outer: Box<BorderShape>,
        inner: Box<BorderShape>,
    },
}

impl BorderShape {
    /// Assign the geometry box parsed immediately after this basic shape.
    /// A pair is not a single basic shape and cannot receive one.
    pub(crate) fn set_geometry_box(&mut self, geometry_box: BorderShapeGeometryBox) -> Option<()> {
        match self {
            Self::Circle(shape) => shape.geometry_box = geometry_box,
            Self::Ellipse(shape) => shape.geometry_box = geometry_box,
            Self::Path(shape) => shape.geometry_box = geometry_box,
            Self::Inset(shape) => shape.geometry_box = geometry_box,
            Self::Polygon(shape) => shape.geometry_box = geometry_box,
            Self::None | Self::Pair { .. } => return None,
        }
        Some(())
    }

    /// Apply the distinct default geometry boxes for the outer and inner
    /// basic shapes of a `border-shape` pair.
    pub(crate) fn replace_half_border_box(&mut self, geometry_box: BorderShapeGeometryBox) {
        let current = match self {
            Self::Circle(shape) => &mut shape.geometry_box,
            Self::Ellipse(shape) => &mut shape.geometry_box,
            Self::Path(shape) => &mut shape.geometry_box,
            Self::Inset(shape) => &mut shape.geometry_box,
            Self::Polygon(shape) => &mut shape.geometry_box,
            Self::None | Self::Pair { .. } => return,
        };
        if *current == BorderShapeGeometryBox::HalfBorder {
            *current = geometry_box;
        }
    }

    pub(crate) fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        match self {
            Self::Circle(shape) => {
                shape.radius.resolve_root_font_metric_lengths(basis);
                shape.position.resolve_root_font_metric_lengths(basis);
            }
            Self::Ellipse(shape) => {
                shape
                    .horizontal_radius
                    .resolve_root_font_metric_lengths(basis);
                shape
                    .vertical_radius
                    .resolve_root_font_metric_lengths(basis);
                shape.position.resolve_root_font_metric_lengths(basis);
            }
            Self::Path(shape) => {
                for vertex in &mut shape.vertices {
                    vertex.resolve_root_font_metric_lengths(basis);
                }
            }
            Self::Inset(shape) => {
                for value in [
                    &mut shape.top,
                    &mut shape.right,
                    &mut shape.bottom,
                    &mut shape.left,
                ] {
                    value.resolve_root_font_metric_lengths(basis);
                }
                if let Some(radius) = &mut shape.corner_radius {
                    radius.resolve_root_font_metric_lengths(basis);
                }
            }
            Self::Polygon(shape) => {
                for vertex in &mut shape.vertices {
                    vertex.resolve_root_font_metric_lengths(basis);
                }
            }
            Self::Pair { outer, inner } => {
                outer.resolve_root_font_metric_lengths(basis);
                inner.resolve_root_font_metric_lengths(basis);
            }
            Self::None => {}
        }
    }

    pub(crate) fn requires_root_font_metrics(&self) -> bool {
        match self {
            Self::Circle(shape) => {
                shape.radius.requires_root_font_metrics()
                    || shape.position.requires_root_font_metrics()
            }
            Self::Ellipse(shape) => {
                shape.horizontal_radius.requires_root_font_metrics()
                    || shape.vertical_radius.requires_root_font_metrics()
                    || shape.position.requires_root_font_metrics()
            }
            Self::Path(shape) => shape
                .vertices
                .iter()
                .any(BorderShapePosition::requires_root_font_metrics),
            Self::Polygon(shape) => shape
                .vertices
                .iter()
                .any(BorderShapePosition::requires_root_font_metrics),
            Self::Inset(shape) => {
                [&shape.top, &shape.right, &shape.bottom, &shape.left]
                    .into_iter()
                    .any(|value| value.requires_root_font_metrics())
                    || shape
                        .corner_radius
                        .as_ref()
                        .is_some_and(ComputedLengthPercentage::requires_root_font_metrics)
            }
            Self::Pair { outer, inner } => {
                outer.requires_root_font_metrics() || inner.requires_root_font_metrics()
            }
            Self::None => false,
        }
    }
}

/// A closed line-only CSS basic shape retained for `border-shape` painting.
///
/// Each vertex remains a typed computed length percentage until its geometry
/// box is known, matching the percentage-resolution boundary for the other
/// border-shape primitives:
/// <https://drafts.csswg.org/css-shapes-2/#shape-function>.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct BorderShapePath {
    pub(crate) vertices: Vec<BorderShapePosition>,
    pub(crate) geometry_box: BorderShapeGeometryBox,
}

/// Typed inset distances for a CSS `inset()` border shape.
///
/// Percentages resolve against their respective geometry-box axes at paint
/// time, so this deliberately stores physical sides rather than an eagerly
/// resolved rectangle:
/// <https://drafts.csswg.org/css-shapes-1/#funcdef-inset>.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct BorderShapeInset {
    pub(crate) top: ComputedLengthPercentage,
    pub(crate) right: ComputedLengthPercentage,
    pub(crate) bottom: ComputedLengthPercentage,
    pub(crate) left: ComputedLengthPercentage,
    /// Uniform `round <length-percentage>` radius, retained for paint-time
    /// resolution against the inset rectangle's axes.
    pub(crate) corner_radius: Option<ComputedLengthPercentage>,
    pub(crate) geometry_box: BorderShapeGeometryBox,
}

/// Typed vertices of the CSS `polygon()` basic shape for `border-shape`.
///
/// The fill rule is intentionally not represented yet: values that request a
/// non-default rule are rejected by the parser until paint can preserve that
/// choice. Coordinates stay typed through percentage resolution.
/// <https://drafts.csswg.org/css-shapes-1/#funcdef-polygon>
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct BorderShapePolygon {
    pub(crate) vertices: Vec<BorderShapePosition>,
    pub(crate) geometry_box: BorderShapeGeometryBox,
}

/// One currently-supported circular basic shape in `border-shape`.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct BorderShapeCircle {
    pub(crate) radius: BorderShapeCircleRadius,
    pub(crate) position: BorderShapePosition,
    pub(crate) geometry_box: BorderShapeGeometryBox,
}

/// Circle radius syntax retained until geometry-box resolution.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BorderShapeCircleRadius {
    LengthPercentage(ComputedLengthPercentage),
    ClosestSide,
    FarthestSide,
    ClosestCorner,
    FarthestCorner,
}

impl BorderShapeCircleRadius {
    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        if let Self::LengthPercentage(value) = self {
            value.resolve_root_font_metric_lengths(basis);
        }
    }

    fn requires_root_font_metrics(&self) -> bool {
        matches!(self, Self::LengthPercentage(value) if value.requires_root_font_metrics())
    }
}

/// One currently-supported elliptical basic shape in `border-shape`.
///
/// Ellipse radii are preserved independently because CSS percentage radii
/// resolve against their respective geometry-box axes:
/// <https://drafts.csswg.org/css-shapes-1/#funcdef-ellipse>.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct BorderShapeEllipse {
    pub(crate) horizontal_radius: BorderShapeEllipseRadius,
    pub(crate) vertical_radius: BorderShapeEllipseRadius,
    pub(crate) position: BorderShapePosition,
    pub(crate) geometry_box: BorderShapeGeometryBox,
}

/// One axis radius of a CSS `ellipse()` basic shape.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BorderShapeEllipseRadius {
    LengthPercentage(ComputedLengthPercentage),
    ClosestSide,
    FarthestSide,
    ClosestCorner,
    FarthestCorner,
}

impl BorderShapeEllipseRadius {
    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        if let Self::LengthPercentage(value) = self {
            value.resolve_root_font_metric_lengths(basis);
        }
    }

    fn requires_root_font_metrics(&self) -> bool {
        matches!(self, Self::LengthPercentage(value) if value.requires_root_font_metrics())
    }
}

/// Basic-shape center relative to its selected geometry box.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct BorderShapePosition {
    pub(crate) x: ComputedLengthPercentage,
    pub(crate) y: ComputedLengthPercentage,
}

impl BorderShapePosition {
    pub(crate) fn center() -> Self {
        Self {
            x: ComputedLengthPercentage::from_percent(0.5),
            y: ComputedLengthPercentage::from_percent(0.5),
        }
    }

    fn resolve_root_font_metric_lengths(&mut self, basis: RootFontMetricLengthBasis) {
        self.x.resolve_root_font_metric_lengths(basis);
        self.y.resolve_root_font_metric_lengths(basis);
    }

    fn requires_root_font_metrics(&self) -> bool {
        self.x.requires_root_font_metrics() || self.y.requires_root_font_metrics()
    }
}

/// Reference rectangle for a `border-shape` basic shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BorderShapeGeometryBox {
    Border,
    Padding,
    Content,
    Margin,
    HalfBorder,
}