blitz-dom 0.3.0-beta.4

Blitz DOM implementation
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
796
797
//! Computation of *resolved* CSS property values, as exposed to JavaScript by
//! `getComputedStyle()`.
//!
//! For most properties the resolved value is the stylo computed value. For
//! layout-dependent properties (`width`/`height`, margins, padding, insets,
//! `transform-origin`, grid track sizes) it is the *used* value, computed from
//! the most recent layout.

use cssparser::Parser;
use selectors::matching::QuirksMode;
use style::computed_values::box_sizing::T as BoxSizing;
use style::computed_values::position::T as Position;
use style::parser::ParserContext;
use style::properties::declaration_block::{Importance, parse_style_attribute};
use style::properties::{
    ComputedValues, NonCustomPropertyId, PropertyDeclaration, PropertyDeclarationBlock,
    PropertyDeclarationId, PropertyId, ShorthandId, SourcePropertyDeclaration,
    parse_one_declaration_into,
};
use style::servo_arc::Arc as ServoArc;
use style::stylesheets::supports_rule::parse_condition_or_declaration;
use style::stylesheets::{CssRuleType, Origin, OriginSet, UrlExtraData};
use style::stylist::RegisterCustomPropertyResult;
use style::values::computed::length::CSSPixelLength;
use style::values::computed::{GridTemplateAreas, GridTemplateComponent, LengthPercentage};
use style::values::generics::position::{Inset as GenericInset, PreferredRatio};
use style::values::resolved;
use style::values::specified::box_::{DisplayInside, DisplayOutside};
use style_traits::{CssStringWriter, ParsingMode, ToCss};

use blitz_traits::node_id::NodeId;
use url::Url;

use crate::BaseDocument;
use crate::layout::replaced::is_replaced_element;
use crate::local_name;

/// Serialize a used length (in CSS pixels) the way stylo serializes computed lengths
fn format_px(px: f32) -> String {
    CSSPixelLength::new(px).to_css_string()
}

/// Resolve a computed inset value to CSS pixels against the given percentage
/// basis. Returns `None` for `auto` (and unsupported anchor functions).
fn resolve_inset<P>(val: &GenericInset<P, LengthPercentage>, basis: f32) -> Option<f32> {
    match val {
        GenericInset::LengthPercentage(lp) => Some(lp.resolve(CSSPixelLength::new(basis)).px()),
        _ => None,
    }
}

/// Serialize a transform matrix component rounded to 6 decimal places (as
/// browsers do when serializing resolved transform matrices)
fn format_matrix_component(v: f64) -> String {
    let rounded = (v * 1e6).round() / 1e6;
    // Avoid "-0"
    let rounded = if rounded == 0.0 { 0.0 } else { rounded };
    format!("{rounded}")
}

/// Serialize a used transform matrix the way `getComputedStyle()` does
/// (`matrix(...)` for 2D transforms, `matrix3d(...)` otherwise).
fn format_matrix(m: &euclid::default::Transform3D<f64>, is_3d: bool) -> String {
    let c = format_matrix_component;
    if is_3d {
        format!(
            "matrix3d({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})",
            c(m.m11),
            c(m.m12),
            c(m.m13),
            c(m.m14),
            c(m.m21),
            c(m.m22),
            c(m.m23),
            c(m.m24),
            c(m.m31),
            c(m.m32),
            c(m.m33),
            c(m.m34),
            c(m.m41),
            c(m.m42),
            c(m.m43),
            c(m.m44)
        )
    } else {
        format!(
            "matrix({}, {}, {}, {}, {}, {})",
            c(m.m11),
            c(m.m12),
            c(m.m21),
            c(m.m22),
            c(m.m41),
            c(m.m42)
        )
    }
}

/// Check whether `name` names a CSS property supported by the style engine.
/// Custom properties (`--*`) are not considered "supported" here, matching the
/// behaviour of the `in` operator on `CSSStyleDeclaration` objects in browsers.
pub fn css_property_is_supported(name: &str) -> bool {
    matches!(
        PropertyId::parse_enabled_for_all_content(name),
        Ok(property_id) if !matches!(property_id, PropertyId::Custom(_))
    )
}

/// Parse a CSS `transform` list into a 4x4 matrix, as required by the
/// `DOMMatrix(DOMString)` constructor and `DOMMatrix.setMatrixValue()`
/// (<https://drafts.fxtf.org/geometry/#parse-a-string-into-an-abstract-matrix>).
///
/// Returns the 16 matrix components in column-major order (`m11, m12, ...,
/// m44`) and whether the list contained only 2D transform functions.
/// Returns `None` if the string fails to parse as a transform list or uses
/// relative lengths (which cannot be resolved without a context).
pub fn parse_transform_matrix(value: &str) -> Option<([f64; 16], bool)> {
    use style::properties::longhands::transform;
    // Transform lists cannot contain URLs, so any base URL will do
    let url_data = UrlExtraData(ServoArc::new(Url::parse("about:blank").unwrap()));
    let context = ParserContext::new(
        Origin::Author,
        &url_data,
        Some(CssRuleType::Style),
        ParsingMode::DEFAULT,
        QuirksMode::NoQuirks,
        Default::default(),
        None,
        None,
        Default::default(),
    );
    let mut parser = Parser::new(value);
    let transform = parser
        .parse_entirely(|t| transform::parse(&context, t))
        .ok()?;
    let (m, is_3d) = transform.to_transform_3d_matrix_f64(None).ok()?;
    Some((
        [
            m.m11, m.m12, m.m13, m.m14, m.m21, m.m22, m.m23, m.m24, m.m31, m.m32, m.m33, m.m34,
            m.m41, m.m42, m.m43, m.m44,
        ],
        !is_3d,
    ))
}

/// The names of the properties exposed by the `CSSStyleDeclaration` returned
/// from `getComputedStyle()` (its indexed properties): every enabled longhand,
/// sorted alphabetically.
pub fn resolved_style_property_names() -> &'static [&'static str] {
    static NAMES: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
    NAMES.get_or_init(|| {
        let mut names: Vec<&'static str> = NonCustomPropertyId::iter()
            .filter_map(|id| id.as_longhand())
            .map(|longhand| longhand.name())
            .filter(|name| PropertyId::parse_enabled_for_all_content(name).is_ok())
            .collect();
        names.sort_unstable();
        names
    })
}

impl BaseDocument {
    /// Check whether `value` is a valid value for the CSS property `property`.
    /// Used by CSSOM APIs (`element.style.setProperty` and friends), which must
    /// ignore invalid declarations.
    pub fn css_declaration_is_valid(&self, property: &str, value: &str) -> bool {
        let Ok(property_id) = PropertyId::parse_enabled_for_all_content(property) else {
            return false;
        };
        let mut declarations = SourcePropertyDeclaration::default();
        parse_one_declaration_into(
            &mut declarations,
            property_id,
            value,
            Origin::Author,
            &self.url.url_extra_data(),
            None,
            ParsingMode::DEFAULT,
            QuirksMode::NoQuirks,
            CssRuleType::Style,
        )
        .is_ok()
    }

    /// Parse a `style` attribute string into a [`PropertyDeclarationBlock`].
    /// Invalid declarations are dropped (per CSS error recovery).
    fn parse_style_attr_block(&self, style_attr: &str) -> PropertyDeclarationBlock {
        parse_style_attribute(
            style_attr,
            &self.url.url_extra_data(),
            None,
            QuirksMode::NoQuirks,
            CssRuleType::Style,
        )
    }

    /// The canonical CSSOM serialization of a `style` attribute string
    /// (`CSSStyleDeclaration.cssText` getter).
    pub fn style_attr_serialize(&self, style_attr: &str) -> String {
        let block = self.parse_style_attr_block(style_attr);
        let mut css = CssStringWriter::new();
        let _ = block.to_css(&mut css);
        css
    }

    /// The canonical serialization of `property`'s value in a `style` attribute
    /// string (`CSSStyleDeclaration.getPropertyValue()`). Handles shorthands.
    /// Returns an empty string if the property is not set or not recognised.
    pub fn style_attr_get_property(&self, style_attr: &str, property: &str) -> String {
        let Ok(property_id) = PropertyId::parse_enabled_for_all_content(property) else {
            return String::new();
        };
        let block = self.parse_style_attr_block(style_attr);
        let mut css = CssStringWriter::new();
        let _ = block.property_value_to_css(&property_id, &mut css);
        css
    }

    /// Set `property` to `value` in a `style` attribute string
    /// (`CSSStyleDeclaration.setProperty()`), expanding shorthands.
    ///
    /// Returns the new (canonically serialized) style attribute, or `None` if
    /// the declaration was invalid (in which case the style is unchanged, per
    /// CSSOM). An empty `value` removes the property.
    pub fn style_attr_set_property(
        &self,
        style_attr: &str,
        property: &str,
        value: &str,
        important: bool,
    ) -> Option<String> {
        let property_id = PropertyId::parse_enabled_for_all_content(property).ok()?;
        let mut block = self.parse_style_attr_block(style_attr);

        if value.trim().is_empty() {
            if let Some(first_declaration) = block.first_declaration_to_remove(&property_id) {
                block.remove_property(&property_id, first_declaration);
            }
        } else {
            let mut source = SourcePropertyDeclaration::default();
            parse_one_declaration_into(
                &mut source,
                property_id,
                value,
                Origin::Author,
                &self.url.url_extra_data(),
                None,
                ParsingMode::DEFAULT,
                QuirksMode::NoQuirks,
                CssRuleType::Style,
            )
            .ok()?;
            let importance = if important {
                Importance::Important
            } else {
                Importance::Normal
            };
            block.extend(source.drain(), importance);
        }

        let mut css = CssStringWriter::new();
        let _ = block.to_css(&mut css);
        Some(css)
    }

    /// Remove `property` from a `style` attribute string
    /// (`CSSStyleDeclaration.removeProperty()`), removing all longhands if it
    /// is a shorthand.
    ///
    /// Returns the new (canonically serialized) style attribute and the removed
    /// property's previous serialized value.
    pub fn style_attr_remove_property(
        &self,
        style_attr: &str,
        property: &str,
    ) -> Option<(String, String)> {
        let property_id = PropertyId::parse_enabled_for_all_content(property).ok()?;
        let mut block = self.parse_style_attr_block(style_attr);

        let mut removed_value = CssStringWriter::new();
        let _ = block.property_value_to_css(&property_id, &mut removed_value);
        if let Some(first_declaration) = block.first_declaration_to_remove(&property_id) {
            block.remove_property(&property_id, first_declaration);
        }

        let mut css = CssStringWriter::new();
        let _ = block.to_css(&mut css);
        Some((css, removed_value))
    }

    /// Evaluate a `@supports` condition (e.g. `(display: grid)`,
    /// `selector(:hover)`) or a bare declaration (e.g. `display: grid`), as
    /// used by the CSSOM `CSS.supports(conditionText)` API. Returns `false`
    /// for unparseable conditions.
    pub fn css_supports_condition(&self, condition: &str) -> bool {
        let mut parser = Parser::new(condition);
        let Ok(condition) = parser.parse_entirely(parse_condition_or_declaration) else {
            return false;
        };

        let url_data = self.url.url_extra_data();
        let context = ParserContext::new(
            Origin::Author,
            &url_data,
            Some(CssRuleType::Style),
            ParsingMode::DEFAULT,
            QuirksMode::NoQuirks,
            Default::default(),
            None,
            None,
            Default::default(),
        );
        condition.eval(&context)
    }

    /// Register a custom property via script (`CSS.registerProperty()`).
    /// On success all styles are invalidated so that declarations of the
    /// property are re-parsed against the new registration.
    pub fn register_custom_property(
        &mut self,
        name: &str,
        syntax: &str,
        inherits: bool,
        initial_value: Option<&str>,
    ) -> RegisterCustomPropertyResult {
        let url_data = self.url.url_extra_data();
        let result =
            self.stylist
                .register_custom_property(&url_data, name, syntax, inherits, initial_value);
        if matches!(result, RegisterCustomPropertyResult::SuccessfullyRegistered) {
            self.stylist
                .force_stylesheet_origins_dirty(OriginSet::all());
        }
        result
    }

    /// Compute the resolved value of a CSS property for the given node, as exposed
    /// by `getComputedStyle()`. Returns an empty string for unknown properties and
    /// for nodes without styles.
    ///
    /// Layout-dependent properties (`width`/`height`, margins, padding, insets,
    /// `transform-origin`, `grid-template-rows`/`columns`) resolve to *used* values, so [`resolve`](Self::resolve) should be called
    /// before this method to ensure layout is up to date.
    pub fn resolved_style_value(&self, node_id: NodeId, property_name: &str) -> String {
        let Some(node) = self.get_node(node_id) else {
            return String::new();
        };
        // The computed style of an element that is not in the document is empty
        if !node.flags.is_in_document() {
            return String::new();
        }
        // Elements inside a `display: none` subtree are skipped by the style
        // traversal, so their style has to be computed on demand.
        let undisplayed_styles;
        let stored_styles = node.primary_styles();
        let styles: &ComputedValues = match &stored_styles {
            Some(styles) => styles,
            None => match self.resolve_undisplayed_style(node_id) {
                Some(styles) => {
                    undisplayed_styles = styles;
                    &undisplayed_styles
                }
                None => return String::new(),
            },
        };

        let display = styles.clone_display();
        // Non-atomic inline elements are laid out as style spans within their
        // inline root's text layout rather than as boxes of their own, so their
        // layout-dependent properties resolve to computed (not used) values.
        let is_non_atomic_inline = display.outside() == DisplayOutside::Inline
            && display.inside() == DisplayInside::Flow
            && !node.flags.is_inline_root()
            && node.element_data().is_none_or(|data| {
                let tag = &data.name.local;
                !(is_replaced_element(tag)
                    || *tag == local_name!("input")
                    || *tag == local_name!("textarea")
                    || *tag == local_name!("button"))
            });
        let generates_box =
            node.flags.is_in_document() && !display.is_none() && stored_styles.is_some();
        let has_layout_box = generates_box && !is_non_atomic_inline;

        let Ok(property_id) = PropertyId::parse_enabled_for_all_content(property_name) else {
            return String::new();
        };
        // Logical longhands resolve as the physical longhand they map to
        let property_name = match property_id.as_shorthand() {
            Err(PropertyDeclarationId::Longhand(longhand)) => {
                longhand.to_physical(styles.writing_mode).name()
            }
            _ => property_name,
        };

        // Used lengths are serialized unzoomed, like computed lengths
        let zoom = styles.effective_zoom.value();
        let format_used_px = |px: f32| format_px(px / zoom);

        // Layout-dependent "used value" special cases
        match property_name {
            // Shorthands of longhands that resolve to used values
            "margin" | "margin-block" | "margin-inline" | "padding" | "padding-block"
            | "padding-inline" | "inset" | "inset-block" | "inset-inline"
                if has_layout_box =>
            {
                if let Ok(shorthand) = property_id.as_shorthand() {
                    let sides: Vec<String> = shorthand
                        .longhands()
                        .map(|longhand| self.resolved_style_value(node_id, longhand.name()))
                        .collect();
                    return serialize_sides(&sides);
                }
            }
            "grid-template-columns" | "grid-template-rows"
                if display.inside() == DisplayInside::Grid =>
            {
                if let Some(info) =
                    node.element_data()
                        .and_then(|data| match &data.detailed_layout_info {
                            taffy::DetailedLayoutInfo::Grid(info) => Some(info),
                            _ => None,
                        })
                {
                    return if property_name == "grid-template-columns" {
                        info.grid_template_columns(zoom)
                    } else {
                        info.grid_template_rows(zoom)
                    };
                }
            }
            // Browsers serialize the `grid-template` shorthand from the computed
            // track lists, except that a `none` track list on a grid container
            // is replaced by the used (implicit) track sizes.
            "grid-template" if display.inside() == DisplayInside::Grid => {
                let pos_styles = styles.get_position();
                let rows_are_none =
                    matches!(pos_styles.grid_template_rows, GridTemplateComponent::None);
                let columns_are_none = matches!(
                    pos_styles.grid_template_columns,
                    GridTemplateComponent::None
                );
                let info = node
                    .element_data()
                    .and_then(|data| match &data.detailed_layout_info {
                        taffy::DetailedLayoutInfo::Grid(info) => Some(info),
                        _ => None,
                    });
                if let Some(info) = info
                    && (rows_are_none || columns_are_none)
                    && matches!(pos_styles.grid_template_areas, GridTemplateAreas::None)
                {
                    let rows = if rows_are_none {
                        info.grid_template_rows(zoom)
                    } else {
                        pos_styles.grid_template_rows.to_css_string()
                    };
                    let columns = if columns_are_none {
                        info.grid_template_columns(zoom)
                    } else {
                        pos_styles.grid_template_columns.to_css_string()
                    };
                    return format!("{rows} / {columns}");
                }
            }
            "width" | "height" if has_layout_box => {
                // Used value: the layout size interpreted according to `box-sizing`
                // (border-box size for `border-box`, content-box size for `content-box`)
                let layout = node.final_layout();
                let border_box = styles.get_position().box_sizing == BoxSizing::BorderBox;
                let size = if property_name == "width" {
                    if border_box {
                        layout.size.width
                    } else {
                        layout.size.width
                            - layout.border.left
                            - layout.border.right
                            - layout.padding.left
                            - layout.padding.right
                    }
                } else if border_box {
                    layout.size.height
                } else {
                    layout.size.height
                        - layout.border.top
                        - layout.border.bottom
                        - layout.padding.top
                        - layout.padding.bottom
                };
                return format_used_px(size.max(0.0));
            }
            "margin-top" | "margin-right" | "margin-bottom" | "margin-left" if has_layout_box => {
                // Used value: the margin resolved by layout (percentages and
                // `auto` margins resolved to lengths)
                let layout = node.final_layout();
                let margin = match property_name {
                    "margin-top" => layout.margin.top,
                    "margin-right" => layout.margin.right,
                    "margin-bottom" => layout.margin.bottom,
                    "margin-left" => layout.margin.left,
                    _ => unreachable!(),
                };
                return format_used_px(margin);
            }
            "padding-top" | "padding-right" | "padding-bottom" | "padding-left"
                if has_layout_box =>
            {
                // Used value: the padding resolved by layout (percentages
                // resolved to lengths)
                let layout = self.physical_unrounded_geometry(node_id).1;
                let padding = match property_name {
                    "padding-top" => layout.padding.top,
                    "padding-right" => layout.padding.right,
                    "padding-bottom" => layout.padding.bottom,
                    "padding-left" => layout.padding.left,
                    _ => unreachable!(),
                };
                return format_used_px(padding);
            }
            "transform-origin" | "perspective-origin" if has_layout_box => {
                // Used value: percentages resolved against the border box
                let layout = self.physical_unrounded_geometry(node_id).1;
                let resolve = |value: &LengthPercentage, basis: f32| {
                    format_used_px(value.resolve(CSSPixelLength::new(basis)).px())
                };
                let box_styles = styles.get_box();
                return if property_name == "transform-origin" {
                    let origin = &box_styles.transform_origin;
                    let x = resolve(&origin.horizontal, layout.size.width);
                    let y = resolve(&origin.vertical, layout.size.height);
                    if origin.depth.px() == 0.0 {
                        format!("{x} {y}")
                    } else {
                        format!("{x} {y} {}", format_used_px(origin.depth.px()))
                    }
                } else {
                    let origin = &box_styles.perspective_origin;
                    let x = resolve(&origin.horizontal, layout.size.width);
                    let y = resolve(&origin.vertical, layout.size.height);
                    format!("{x} {y}")
                };
            }
            "top" | "right" | "bottom" | "left" if has_layout_box => {
                let position = styles.clone_position();
                let parent_layout = node
                    .containing_block()
                    .and_then(|id| self.get_node(id))
                    .map(|parent| *parent.final_layout());

                match position {
                    // Used value: the relative offset. An `auto` side resolves
                    // to the negation of the opposite side. When both sides
                    // are set the axis is overconstrained and each side
                    // resolves to its computed value instead.
                    Position::Relative => {
                        let (cb_width, cb_height) = parent_layout
                            .map(|pl| {
                                (
                                    pl.size.width
                                        - pl.border.left
                                        - pl.border.right
                                        - pl.padding.left
                                        - pl.padding.right,
                                    pl.size.height
                                        - pl.border.top
                                        - pl.border.bottom
                                        - pl.padding.top
                                        - pl.padding.bottom,
                                )
                            })
                            .unwrap_or((0.0, 0.0));
                        let pos_styles = styles.get_position();
                        let is_vertical = matches!(property_name, "top" | "bottom");
                        let basis = if is_vertical { cb_height } else { cb_width };
                        let (start, end) = if is_vertical {
                            (
                                resolve_inset(&pos_styles.top, basis),
                                resolve_inset(&pos_styles.bottom, basis),
                            )
                        } else {
                            (
                                resolve_inset(&pos_styles.left, basis),
                                resolve_inset(&pos_styles.right, basis),
                            )
                        };
                        let is_start = matches!(property_name, "top" | "left");
                        let used = match (start, end) {
                            (Some(start), Some(end)) => {
                                if is_start {
                                    start
                                } else {
                                    end
                                }
                            }
                            (Some(start), None) => {
                                if is_start {
                                    start
                                } else {
                                    -start
                                }
                            }
                            (None, Some(end)) => {
                                if is_start {
                                    -end
                                } else {
                                    end
                                }
                            }
                            (None, None) => 0.0,
                        };
                        return format_used_px(used);
                    }
                    // A specified (non-`auto`) inset resolves as-is (with
                    // percentages resolved against the containing block), even
                    // when overconstrained. An `auto` inset resolves to the
                    // used distance between the box's margin edge and the
                    // corresponding edge of the containing block's padding box.
                    Position::Absolute | Position::Fixed => {
                        if let Some(pl) = parent_layout {
                            let cb_width = pl.size.width - pl.border.left - pl.border.right;
                            let cb_height = pl.size.height - pl.border.top - pl.border.bottom;

                            let pos_styles = styles.get_position();
                            let (inset, basis) = match property_name {
                                "top" => (&pos_styles.top, cb_height),
                                "bottom" => (&pos_styles.bottom, cb_height),
                                "left" => (&pos_styles.left, cb_width),
                                "right" => (&pos_styles.right, cb_width),
                                _ => unreachable!(),
                            };
                            if let Some(value) = resolve_inset(inset, basis) {
                                return format_used_px(value);
                            }

                            let layout = node.final_layout();
                            let margin_box_top =
                                layout.location.y - layout.margin.top - pl.border.top;
                            let margin_box_left =
                                layout.location.x - layout.margin.left - pl.border.left;
                            let margin_box_width =
                                layout.margin.left + layout.size.width + layout.margin.right;
                            let margin_box_height =
                                layout.margin.top + layout.size.height + layout.margin.bottom;
                            let used = match property_name {
                                "top" => margin_box_top,
                                "bottom" => cb_height - margin_box_top - margin_box_height,
                                "left" => margin_box_left,
                                "right" => cb_width - margin_box_left - margin_box_width,
                                _ => unreachable!(),
                            };
                            return format_used_px(used);
                        }
                    }
                    // `static` and `sticky` boxes resolve to the computed value
                    _ => {}
                }
            }
            // `min-width: auto` / `min-height: auto` resolve to `auto` only for
            // boxes with a preferred aspect ratio and for flex and grid items;
            // otherwise (including when no box is generated) they resolve to `0px`
            "min-width" | "min-height" => {
                let pos_styles = styles.get_position();
                let is_auto = if property_name == "min-width" {
                    pos_styles.min_width.is_auto()
                } else {
                    pos_styles.min_height.is_auto()
                };
                let has_aspect_ratio =
                    !matches!(pos_styles.aspect_ratio.ratio, PreferredRatio::None);
                let preserves_auto =
                    generates_box && (has_aspect_ratio || self.is_flex_or_grid_item(node_id));
                if is_auto && !preserves_auto {
                    return format_px(0.0);
                }
            }
            "transform" if has_layout_box => {
                let transform = &styles.get_box().transform;
                if !transform.0.is_empty() {
                    // Used value: the transform list resolved to a matrix, with
                    // percentages resolved against the border box
                    let layout = node.final_layout();
                    let reference_box = euclid::Rect::new(
                        euclid::Point2D::new(CSSPixelLength::new(0.0), CSSPixelLength::new(0.0)),
                        euclid::Size2D::new(
                            CSSPixelLength::new(layout.size.width),
                            CSSPixelLength::new(layout.size.height),
                        ),
                    );
                    if let Ok((matrix, is_3d)) =
                        transform.to_transform_3d_matrix_f64(Some(&reference_box))
                    {
                        return format_matrix(&matrix, is_3d);
                    }
                }
            }
            _ => {}
        }

        // General case: serialize the stylo computed value
        let css = match property_id.as_shorthand() {
            // Serialize shorthands from the resolved values of their longhands
            Ok(shorthand) => serialize_resolved_shorthand(styles, shorthand),
            Err(declaration_id) => styles.computed_value_to_string(declaration_id),
        };
        canonicalize_computed_alignment(property_name, css)
    }

    /// Whether the node's box is a flex or grid item, i.e. its nearest ancestor
    /// that generates a box (skipping `display: contents` ancestors) is a flex
    /// or grid container.
    fn is_flex_or_grid_item(&self, node_id: NodeId) -> bool {
        let mut parent_id = self.get_node(node_id).and_then(|node| node.parent);
        while let Some(parent) = parent_id.and_then(|id| self.get_node(id)) {
            let Some(parent_styles) = parent.primary_styles() else {
                return false;
            };
            let display = parent_styles.clone_display();
            if display.is_contents() {
                parent_id = parent.parent;
                continue;
            }
            return matches!(display.inside(), DisplayInside::Flex | DisplayInside::Grid);
        }
        false
    }
}

/// Serialize the values of a two-sided (start, end) or four-sided (top, right,
/// bottom, left) shorthand, omitting sides that repeat the opposite side.
fn serialize_sides(sides: &[String]) -> String {
    let len = match sides {
        [start, end] if start == end => 1,
        [top, right, bottom, left] if right == left => {
            if top != bottom {
                3
            } else if top != right {
                2
            } else {
                1
            }
        }
        _ => sides.len(),
    };
    sides[..len].join(" ")
}

/// Serialize the resolved value of a shorthand property by resolving each of
/// its longhands and re-serializing them as the shorthand (as
/// `getComputedStyle()` does for shorthands). Returns an empty string if the
/// longhand values cannot be represented as the shorthand.
fn serialize_resolved_shorthand(styles: &ComputedValues, shorthand: ShorthandId) -> String {
    // `all` cannot be serialized from longhands
    if shorthand == ShorthandId::All {
        return String::new();
    }

    let declarations: Vec<PropertyDeclaration> = shorthand
        .longhands()
        .map(|longhand| {
            let mut context = resolved::Context {
                style: styles,
                for_property: PropertyId::NonCustom(longhand.into()),
                current_longhand: Some(longhand),
            };
            styles.computed_or_resolved_declaration(longhand, Some(&mut context))
        })
        .collect();
    let declaration_refs: Vec<&PropertyDeclaration> = declarations.iter().collect();

    let mut css = CssStringWriter::new();
    let _ = shorthand.longhands_to_css(&declaration_refs, &mut css);
    css
}

/// Canonicalize the computed value of an alignment property the way css-align-3
/// now requires: `flex-start`/`flex-end` compute to `flow-start`/`flow-end`
/// (e.g. `align-self: flex-start` resolves to `flow-start`, `safe flex-end` to
/// `safe flow-end`). Stylo does not yet do this, so patch the serialized value
/// here until it does (see https://github.com/servo/stylo).
fn canonicalize_computed_alignment(property_name: &str, value: String) -> String {
    const ALIGNMENT_PROPERTIES: [&str; 9] = [
        "align-content",
        "align-items",
        "align-self",
        "justify-content",
        "justify-items",
        "justify-self",
        "place-content",
        "place-items",
        "place-self",
    ];
    if !ALIGNMENT_PROPERTIES.contains(&property_name) || !value.contains("flex-") {
        return value;
    }
    value
        .replace("flex-start", "flow-start")
        .replace("flex-end", "flow-end")
}