Skip to main content

layout/
query.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Utilities for querying the layout, as needed by layout.
6use std::borrow::Cow;
7use std::cell::LazyCell;
8use std::ops::Deref;
9use std::rc::Rc;
10use std::sync::Arc;
11
12use app_units::Au;
13use bitflags::bitflags;
14use embedder_traits::UntrustedNodeAddress;
15use euclid::{Point2D, Rect, Size2D};
16use layout_api::{
17    AxesOverflow, BoxAreaType, CSSPixelRectVec, DangerousStyleElementOf, LayoutElement,
18    LayoutElementType, LayoutNode, LayoutNodeType, OffsetParentResponse, ScrollContainerQueryFlags,
19    ScrollContainerResponse,
20};
21use paint_api::display_list::ScrollTree;
22use script::layout_dom::ServoLayoutNode;
23use servo_arc::Arc as ServoArc;
24use servo_base::text::Utf32CodeUnits;
25use servo_geometry::{FastLayoutTransform, au_rect_to_f32_rect, f32_rect_to_au_rect};
26use servo_url::ServoUrl;
27use style::Zero;
28use style::computed_values::display::T as Display;
29use style::computed_values::position::T as Position;
30use style::computed_values::visibility::T as Visibility;
31use style::computed_values::white_space_collapse::T as WhiteSpaceCollapseValue;
32use style::context::{QuirksMode, SharedStyleContext, StyleContext, ThreadLocalStyleContext};
33use style::dom::{NodeInfo, OpaqueNode};
34use style::logical_geometry::WritingMode;
35use style::properties::style_structs::Font;
36use style::properties::{
37    ComputedValues, Importance, LonghandId, PropertyDeclarationBlock, PropertyDeclarationId,
38    PropertyId, ShorthandId, SourcePropertyDeclaration, parse_one_declaration_into,
39};
40use style::selector_parser::PseudoElement;
41use style::shared_lock::SharedRwLock;
42use style::stylesheets::{CssRuleType, Origin, UrlExtraData};
43use style::stylist::RuleInclusion;
44use style::traversal::resolve_style;
45use style::values::computed::transform::Matrix3D;
46use style::values::computed::{Float, Size};
47use style::values::generics::font::LineHeight;
48use style::values::generics::position::AspectRatio;
49use style::values::specified::GenericGridTemplateComponent;
50use style::values::specified::box_::DisplayInside;
51use style_traits::{CSSPixel, ParsingMode, ToCss};
52use webrender_api::units::LayoutPixel;
53
54use crate::cell::RefOrAtomicRef;
55use crate::display_list::{ClosestFragmentSearch, StackingContextTree, au_rect_to_length_rect};
56use crate::dom::NodeExt;
57use crate::flow::inline::text_transform::TextTransformationIterator;
58use crate::fragment_tree::{
59    BoxFragment, Fragment, FragmentFlags, FragmentTree, SpecificLayoutInfo,
60};
61use crate::geom::{AuOrAuto, LengthPercentageOrAuto, PhysicalRect, PhysicalSides};
62use crate::layout_impl::LayoutThread;
63use crate::style_ext::ComputedValuesExt;
64use crate::taffy::SpecificTaffyGridInfo;
65
66/// Calculate the cumulative transform from the root scroll node for `fragments`.
67fn root_transform_for_fragments(
68    scroll_tree: &ScrollTree,
69    fragments: &[Fragment],
70) -> Option<FastLayoutTransform> {
71    let scroll_tree_node_id = fragments.first()?.spatial_tree_node()?;
72    Some(scroll_tree.cumulative_node_to_root_transform(scroll_tree_node_id))
73}
74
75pub(crate) fn process_padding_request(node: ServoLayoutNode<'_>) -> Option<PhysicalSides<Au>> {
76    let fragments = node.fragments_for_pseudo(None);
77    let fragment = fragments.first()?;
78    Some(
79        fragment
80            .retrieve_box_fragment()
81            .map(|box_fragment| box_fragment.padding)
82            .unwrap_or_default(),
83    )
84}
85
86bitflags! {
87    #[derive(Clone, Copy)]
88    pub(crate) struct BoxAreaInclusion: u8 {
89        const Transforms = 1 << 0;
90        const Inlines = 1 << 1;
91    }
92}
93
94pub(crate) fn process_box_area_request(
95    layout_thread: &LayoutThread,
96    stacking_context_tree: &StackingContextTree,
97    node: ServoLayoutNode<'_>,
98    area: BoxAreaType,
99    inclusion: BoxAreaInclusion,
100) -> Option<Rect<Au, CSSPixel>> {
101    // Borrow fragments to avoid cloning on this hot path for accessibility and
102    // `getBoundingClientRect()`.
103    node.with_fragments(|fragments| {
104        let mut rects = fragments
105            .iter()
106            .filter(|fragment| {
107                inclusion.contains(BoxAreaInclusion::Inlines) ||
108                    fragment
109                        .retrieve_box_fragment()
110                        .is_none_or(|fragment| !fragment.with_style().is_inline_box())
111            })
112            .filter_map(|node| node.cumulative_box_area_rect(area, layout_thread.into()))
113            .peekable();
114
115        rects.peek()?;
116        let rect_union = rects.fold(Rect::zero(), |unioned_rect, rect| rect.union(&unioned_rect));
117
118        if !inclusion.contains(BoxAreaInclusion::Transforms) {
119            return Some(rect_union);
120        }
121
122        let Some(transform) =
123            root_transform_for_fragments(&stacking_context_tree.paint_info.scroll_tree, fragments)
124        else {
125            return Some(Rect::new(rect_union.origin, Size2D::zero()));
126        };
127
128        transform_au_rectangle(rect_union, transform)
129    })?
130}
131
132pub(crate) fn process_box_areas_request(
133    layout_thread: &LayoutThread,
134    stacking_context_tree: &StackingContextTree,
135    node: ServoLayoutNode<'_>,
136    area: BoxAreaType,
137) -> CSSPixelRectVec {
138    let fragments = node.fragments_for_pseudo(None);
139    let transform =
140        root_transform_for_fragments(&stacking_context_tree.paint_info.scroll_tree, &fragments);
141
142    let rects = fragments
143        .into_iter()
144        .filter_map(move |fragment| fragment.cumulative_box_area_rect(area, layout_thread.into()));
145
146    let Some(transform) = transform else {
147        return rects
148            .map(|rect| Rect::new(rect.origin, Size2D::zero()))
149            .collect();
150    };
151
152    rects
153        .filter_map(move |rect| transform_au_rectangle(rect, transform))
154        .collect()
155}
156
157pub fn process_client_rect_request(node: ServoLayoutNode<'_>) -> Rect<i32, CSSPixel> {
158    node.fragments_for_pseudo(None)
159        .first()
160        .map(Fragment::client_rect)
161        .unwrap_or_default()
162}
163
164/// Process a query for the current CSS zoom of an element.
165/// <https://drafts.csswg.org/cssom-view/#dom-element-currentcsszoom>
166///
167/// Returns the effective zoom of the element, which is the product of all zoom
168/// values from the element up to the root. Returns 1.0 if the element is not
169/// being rendered (has no associated box).
170pub fn process_current_css_zoom_query(node: ServoLayoutNode<'_>) -> f32 {
171    let Some(layout_data) = node.inner_layout_data() else {
172        return 1.0;
173    };
174    let layout_box = layout_data.self_box.borrow();
175    let Some(layout_box) = layout_box.as_ref() else {
176        return 1.0;
177    };
178    layout_box
179        .with_base(|base| base.style.effective_zoom.value())
180        .unwrap_or(1.0)
181}
182
183/// <https://drafts.csswg.org/cssom-view/#scrolling-area>
184pub fn process_node_scroll_area_request(
185    layout_thread: &LayoutThread,
186    requested_node: Option<ServoLayoutNode<'_>>,
187    fragment_tree: Option<Rc<FragmentTree>>,
188) -> Rect<i32, CSSPixel> {
189    let Some(tree) = fragment_tree else {
190        return Rect::zero();
191    };
192
193    let rect = match requested_node {
194        Some(node) => node
195            .fragments_for_pseudo(None)
196            .first()
197            .map(|fragment| fragment.scrolling_area(layout_thread))
198            .unwrap_or_default(),
199        None => tree
200            .scrollable_overflow()
201            .union(&tree.initial_containing_block),
202    };
203
204    // Note that with `Rect::round()`, the resulting size would depend on
205    // the position (and change when both the origin and size are not whole
206    // integers). To avoid that, round origin and size separately.
207    Rect::new(
208        rect.origin.map(Au::to_f32_px).round(),
209        rect.size.to_vector().map(Au::to_f32_px).to_size().round(),
210    )
211    .to_i32()
212}
213
214/// Return the resolved value of property for a given (pseudo)element.
215/// <https://drafts.csswg.org/cssom/#resolved-value>
216pub fn process_resolved_style_request(
217    context: &SharedStyleContext,
218    initial_containing_block: Option<&PhysicalRect<Au>>,
219    node: ServoLayoutNode<'_>,
220    pseudo: &Option<PseudoElement>,
221    property: &PropertyId,
222) -> String {
223    if node
224        .as_element()
225        .is_none_or(|element| element.style_data().is_none())
226    {
227        return process_resolved_style_request_for_unstyled_node(context, node, pseudo, property);
228    }
229
230    // We call process_resolved_style_request after performing a whole-document
231    // traversal, so in the common case, the element is styled.
232    let layout_element = node.as_element().unwrap();
233    let layout_element = match pseudo {
234        Some(pseudo_element_type) => {
235            match layout_element.with_pseudo(*pseudo_element_type) {
236                Some(layout_element) => layout_element,
237                None => {
238                    // The pseudo doesn't exist, return nothing.  Chrome seems to query
239                    // the element itself in this case, Firefox uses the resolved value.
240                    // https://www.w3.org/Bugs/Public/show_bug.cgi?id=29006
241                    return String::new();
242                },
243            }
244        },
245        None => layout_element,
246    };
247    let node = layout_element.as_node();
248
249    let style = &*layout_element.style(context);
250    let longhand_id = match *property {
251        PropertyId::NonCustom(id) => match id.longhand_or_shorthand() {
252            Ok(longhand_id) => longhand_id,
253            Err(shorthand_id) => return shorthand_to_css_string(shorthand_id, style),
254        },
255        PropertyId::Custom(ref name) => {
256            return style.computed_value_to_string(PropertyDeclarationId::Custom(name));
257        },
258    }
259    .to_physical(style.writing_mode);
260
261    // From <https://drafts.csswg.org/css-transforms-2/#serialization-of-the-computed-value>
262    let serialize_transform_value = |box_fragment: Option<&BoxFragment>| -> Result<String, ()> {
263        let transform_list = &style.get_box().transform;
264
265        // > When the computed value is a <transform-list>, the resolved value is one
266        // > <matrix()> function or one <matrix3d()> function computed by the following
267        // > algorithm:
268        if transform_list.0.is_empty() {
269            return Ok("none".into());
270        }
271
272        // > 1. Let transform be a 4x4 matrix initialized to the identity matrix. The
273        // >    elements m11, m22, m33 and m44 of transform must be set to 1; all other
274        // >    elements of transform must be set to 0.
275        // > 2. Post-multiply all <transform-function>s in <transform-list> to transform.
276        let length_rect = box_fragment
277            .map(|box_fragment| au_rect_to_length_rect(&box_fragment.border_rect()).to_untyped());
278        let (transform, is_3d) = transform_list.to_transform_3d_matrix(length_rect.as_ref())?;
279
280        // > 3. Chose between <matrix()> or <matrix3d()> serialization:
281        // >   ↪ If transform is a 2D matrix: Serialize transform to a <matrix()> function.
282        // >   ↪ Otherwise: Serialize transform to a <matrix3d()> function. Chose between
283        // >     <matrix()> or <matrix3d()> serialization:
284        let matrix = Matrix3D::from(transform);
285        if !is_3d {
286            Ok(matrix.into_2d()?.to_css_string())
287        } else {
288            Ok(matrix.to_css_string())
289        }
290    };
291
292    let computed_style = |fragment: Option<&Fragment>| match longhand_id {
293        LonghandId::MinWidth
294            if style.get_min_width() == &Size::Auto &&
295                !should_honor_min_size_auto(fragment, style) =>
296        {
297            String::from("0px")
298        },
299        LonghandId::MinHeight
300            if style.get_min_height() == &Size::Auto &&
301                !should_honor_min_size_auto(fragment, style) =>
302        {
303            String::from("0px")
304        },
305        LonghandId::Transform => match serialize_transform_value(None) {
306            Ok(value) => value,
307            Err(..) => style.computed_value_to_string(PropertyDeclarationId::Longhand(longhand_id)),
308        },
309        _ => style.computed_value_to_string(PropertyDeclarationId::Longhand(longhand_id)),
310    };
311
312    // https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle
313    // Here we are trying to conform to the specification that says that getComputedStyle
314    // should return the used values in certain circumstances. For size and positional
315    // properties we might need to walk the Fragment tree to figure those out. We always
316    // fall back to returning the computed value.
317
318    // For line height, the resolved value is the computed value if it
319    // is "normal" and the used value otherwise.
320    if longhand_id == LonghandId::LineHeight {
321        let font = style.get_font();
322        let font_size = font.font_size.computed_size();
323        return match font.line_height {
324            // There could be a fragment, but it's only interesting for `min-width` and `min-height`,
325            // so just pass None.
326            LineHeight::Normal => computed_style(None),
327            LineHeight::Number(value) => (font_size * value.0).to_css_string(),
328            LineHeight::Length(value) => value.0.to_css_string(),
329        };
330    }
331
332    // https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle
333    // The properties that we calculate below all resolve to the computed value
334    // when the element is display:none or display:contents.
335    let display = style.get_box().display;
336    if display.is_none() || display.is_contents() {
337        return computed_style(None);
338    }
339
340    let resolve_for_fragment = |fragment: &Fragment| {
341        if let Some(box_fragment) = fragment.retrieve_box_fragment() &&
342            let Some(initial_containing_block) = initial_containing_block &&
343            matches!(
344                longhand_id,
345                LonghandId::Top | LonghandId::Right | LonghandId::Bottom | LonghandId::Left,
346            ) &&
347            let Some(insets) = box_fragment.resolved_insets_for_non_static(
348                node,
349                style,
350                initial_containing_block,
351            )
352        {
353            match longhand_id {
354                LonghandId::Top => return insets.top.to_css_string(),
355                LonghandId::Right => return insets.right.to_css_string(),
356                LonghandId::Bottom => return insets.bottom.to_css_string(),
357                LonghandId::Left => return insets.left.to_css_string(),
358                _ => unreachable!("Should be impossible by matches! above"),
359            }
360        }
361
362        // If we can compute the string do it, but otherwise fallback to a cruder
363        // serialization of the value.
364        if let Some(box_fragment) = fragment.retrieve_box_fragment() &&
365            longhand_id == LonghandId::Transform &&
366            let Ok(string) = serialize_transform_value(Some(&box_fragment))
367        {
368            return string;
369        }
370
371        if !matches!(
372            fragment,
373            Fragment::LayoutRoot(..) | Fragment::Box(..) | Fragment::Positioning(..)
374        ) {
375            return computed_style(Some(fragment));
376        }
377
378        // https://drafts.csswg.org/css-grid/#resolved-track-list
379        // > The grid-template-rows and grid-template-columns properties are
380        // > resolved value special case properties.
381        //
382        // > When an element generates a grid container box...
383        let specific_layout_info = fragment
384            .retrieve_box_fragment()
385            .and_then(|box_fragment| box_fragment.specific_layout_info().as_deref().cloned());
386        if display.inside() == DisplayInside::Grid &&
387            let Some(SpecificLayoutInfo::Grid(info)) = specific_layout_info &&
388            let Some(value) = resolve_grid_template(&info, style, longhand_id)
389        {
390            return value;
391        }
392
393        // https://drafts.csswg.org/cssom/#resolved-value-special-case-property-like-height
394        // > If the property applies to the element or pseudo-element and the resolved value of the
395        // > display property is not none or contents, then the resolved value is the used value.
396        // > Otherwise the resolved value is the computed value.
397        //
398        // However, all browsers ignore that for margin and padding properties, and resolve to a length
399        // even if the property doesn't apply: https://github.com/w3c/csswg-drafts/issues/10391
400        let content_rect =
401            LazyCell::new(|| fragment.base().map(|base| base.rect()).unwrap_or_default());
402        let margins = LazyCell::new(|| {
403            fragment
404                .retrieve_box_fragment()
405                .map(|fragment| fragment.margin)
406                .unwrap_or_default()
407        });
408        let padding = LazyCell::new(|| {
409            fragment
410                .retrieve_box_fragment()
411                .map(|fragment| fragment.padding)
412                .unwrap_or_default()
413        });
414        match longhand_id {
415            LonghandId::Width if resolved_size_should_be_used_value(fragment) => {
416                content_rect.size.width
417            },
418            LonghandId::Height if resolved_size_should_be_used_value(fragment) => {
419                content_rect.size.height
420            },
421            LonghandId::MarginBottom => margins.bottom,
422            LonghandId::MarginTop => margins.top,
423            LonghandId::MarginLeft => margins.left,
424            LonghandId::MarginRight => margins.right,
425            LonghandId::PaddingBottom => padding.bottom,
426            LonghandId::PaddingTop => padding.top,
427            LonghandId::PaddingLeft => padding.left,
428            LonghandId::PaddingRight => padding.right,
429            _ => return computed_style(Some(fragment)),
430        }
431        .to_css_string()
432    };
433
434    node.fragments_for_pseudo(*pseudo)
435        .first()
436        .map(resolve_for_fragment)
437        .unwrap_or_else(|| computed_style(None))
438}
439
440fn resolved_size_should_be_used_value(fragment: &Fragment) -> bool {
441    // https://drafts.csswg.org/css-sizing-3/#preferred-size-properties
442    // > Applies to: all elements except non-replaced inlines
443    match fragment {
444        Fragment::LayoutRoot(layout_root) => {
445            resolved_size_should_be_used_value(&layout_root.inner())
446        },
447        Fragment::Box(box_fragment) => !box_fragment.with_style().is_inline_box(),
448        Fragment::Float(_) |
449        Fragment::Positioning(_) |
450        Fragment::AbsoluteOrFixedPositionedPlaceholder(_) |
451        Fragment::Image(_) |
452        Fragment::IFrame(_) => true,
453        Fragment::Text(_) => false,
454    }
455}
456
457fn should_honor_min_size_auto(fragment: Option<&Fragment>, style: &ComputedValues) -> bool {
458    // <https://drafts.csswg.org/css-sizing-3/#automatic-minimum-size>
459    // For backwards-compatibility, the resolved value of an automatic minimum size is zero
460    // for boxes of all CSS2 display types: block and inline boxes, inline blocks, and all
461    // the table layout boxes. It also resolves to zero when no box is generated.
462    //
463    // <https://github.com/w3c/csswg-drafts/issues/11716>
464    // However, when a box is generated and `aspect-ratio` isn't `auto`, we need to preserve
465    // the automatic minimum size as `auto`.
466    let Some(box_fragment) = fragment.and_then(|fragment| fragment.retrieve_box_fragment()) else {
467        return false;
468    };
469    let flags = box_fragment.base.flags;
470    flags.contains(FragmentFlags::IS_FLEX_OR_GRID_ITEM) ||
471        style.get_aspect_ratio() != &AspectRatio::auto()
472}
473
474fn resolve_grid_template(
475    grid_info: &SpecificTaffyGridInfo,
476    style: &ComputedValues,
477    longhand_id: LonghandId,
478) -> Option<String> {
479    let (track_info, computed_value) = match longhand_id {
480        LonghandId::GridTemplateRows => (
481            &grid_info.info.rows,
482            &style.get_position().grid_template_rows,
483        ),
484        LonghandId::GridTemplateColumns => (
485            &grid_info.info.columns,
486            &style.get_position().grid_template_columns,
487        ),
488        _ => return None,
489    };
490
491    match computed_value {
492        // <https://drafts.csswg.org/css-grid/#resolved-track-list-standalone>
493        // > When an element generates a grid container box, the resolved value of its grid-template-rows or
494        // > grid-template-columns property in a standalone axis is the used value, serialized with:
495        GenericGridTemplateComponent::None | GenericGridTemplateComponent::TrackList(_) => {
496            (!track_info.positions.is_empty()).then(|| track_info.to_track_list_string(1.0))
497        },
498
499        // <https://drafts.csswg.org/css-grid/#resolved-track-list-subgrid>
500        // > When an element generates a grid container box that is a subgrid, the resolved value of the
501        // > grid-template-rows and grid-template-columns properties represents the used number of columns,
502        // > serialized as the subgrid keyword followed by a list representing each of its lines as a
503        // > line name set of all the line’s names explicitly defined on the subgrid (not including those
504        // > adopted from the parent grid), without using the repeat() notation.
505        // TODO: implement subgrid
506        GenericGridTemplateComponent::Subgrid(_) => None,
507    }
508}
509
510#[expect(unsafe_code)]
511pub fn process_resolved_style_request_for_unstyled_node(
512    context: &SharedStyleContext,
513    node: ServoLayoutNode<'_>,
514    pseudo: &Option<PseudoElement>,
515    property: &PropertyId,
516) -> String {
517    // In a display: none subtree. No pseudo-element exists.
518    if pseudo.is_some() {
519        return String::new();
520    }
521
522    let mut tlc = ThreadLocalStyleContext::new();
523    let mut context = StyleContext {
524        shared: context,
525        thread_local: &mut tlc,
526    };
527
528    let element = node.as_element().unwrap();
529    let styles = resolve_style(
530        &mut context,
531        unsafe { element.dangerous_style_element() },
532        RuleInclusion::All,
533        pseudo.as_ref(),
534        None,
535    );
536    let style = styles.primary();
537    let longhand_id = match *property {
538        PropertyId::NonCustom(id) => match id.longhand_or_shorthand() {
539            Ok(longhand_id) => longhand_id,
540            Err(shorthand_id) => return shorthand_to_css_string(shorthand_id, style),
541        },
542        PropertyId::Custom(ref name) => {
543            return style.computed_value_to_string(PropertyDeclarationId::Custom(name));
544        },
545    };
546
547    match longhand_id {
548        // <https://drafts.csswg.org/css-sizing-3/#automatic-minimum-size>
549        // The resolved value of an automatic minimum size is zero when no box is generated.
550        LonghandId::MinWidth if style.get_min_width() == &Size::Auto => String::from("0px"),
551        LonghandId::MinHeight if style.get_min_height() == &Size::Auto => String::from("0px"),
552
553        // No need to care about used values here, since we're on a display: none
554        // subtree, use the computed value.
555        _ => style.computed_value_to_string(PropertyDeclarationId::Longhand(longhand_id)),
556    }
557}
558
559fn shorthand_to_css_string(
560    id: style::properties::ShorthandId,
561    style: &style::properties::ComputedValues,
562) -> String {
563    use style::values::resolved::Context;
564    let mut block = PropertyDeclarationBlock::new();
565    let mut dest = String::new();
566    for longhand in id.longhands() {
567        block.push(
568            style.computed_or_resolved_declaration(
569                longhand,
570                Some(&mut Context {
571                    style,
572                    for_property: PropertyId::NonCustom(longhand.into()),
573                    current_longhand: None,
574                }),
575            ),
576            Importance::Normal,
577        );
578    }
579    match block.shorthand_to_css(id, &mut dest) {
580        Ok(_) => dest,
581        Err(_) => String::new(),
582    }
583}
584
585struct OffsetParentFragments {
586    parent: Arc<BoxFragment>,
587    grandparent: Option<Fragment>,
588}
589
590impl OffsetParentFragments {
591    fn grandparent_box_fragment(&self) -> Option<RefOrAtomicRef<'_, Arc<BoxFragment>>> {
592        self.grandparent
593            .as_ref()
594            .and_then(|grandparent| grandparent.retrieve_box_fragment())
595    }
596}
597/// <https://www.w3.org/TR/2016/WD-cssom-view-1-20160317/#dom-htmlelement-offsetparent>
598#[expect(unsafe_code)]
599fn offset_parent_fragments(node: ServoLayoutNode<'_>) -> Option<OffsetParentFragments> {
600    // 1. If any of the following holds true return null and terminate this algorithm:
601    //  * The element does not have an associated CSS layout box.
602    //  * The element is the root element.
603    //  * The element is the HTML body element.
604    //  * The element’s computed value of the position property is fixed.
605    let fragment = node.fragments_for_pseudo(None).first().cloned()?;
606    let flags = fragment.base()?.flags;
607    if flags.intersects(
608        FragmentFlags::IS_ROOT_ELEMENT | FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT,
609    ) {
610        return None;
611    }
612
613    if fragment
614        .retrieve_box_fragment()
615        .is_some_and(|fragment| fragment.style().get_box().position == Position::Fixed)
616    {
617        return None;
618    }
619
620    // 2.  Return the nearest ancestor element of the element for which at least one of
621    //     the following is true and terminate this algorithm if such an ancestor is found:
622    //  * The computed value of the position property is not static.
623    //  * It is the HTML body element.
624    //  * The computed value of the position property of the element is static and the
625    //    ancestor is one of the following HTML elements: td, th, or table.
626    let mut maybe_parent_node = unsafe { node.dangerous_dom_parent() };
627    while let Some(parent_node) = maybe_parent_node {
628        maybe_parent_node = unsafe { parent_node.dangerous_dom_parent() };
629
630        if let Some(parent_fragment) = parent_node.fragments_for_pseudo(None).first() {
631            let Some(parent_fragment) = parent_fragment.retrieve_box_fragment() else {
632                continue;
633            };
634
635            let grandparent_fragment =
636                maybe_parent_node.and_then(|node| node.fragments_for_pseudo(None).first().cloned());
637
638            if parent_fragment.style().get_box().position != Position::Static {
639                return Some(OffsetParentFragments {
640                    parent: parent_fragment.clone(),
641                    grandparent: grandparent_fragment,
642                });
643            }
644
645            let flags = parent_fragment.base.flags;
646            if flags.intersects(
647                FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT |
648                    FragmentFlags::IS_TABLE_TH_OR_TD_ELEMENT,
649            ) {
650                return Some(OffsetParentFragments {
651                    parent: parent_fragment.clone(),
652                    grandparent: grandparent_fragment,
653                });
654            }
655        }
656    }
657
658    None
659}
660
661#[inline]
662pub fn process_offset_parent_query(
663    layout_thread: &LayoutThread,
664    scroll_tree: &ScrollTree,
665    node: ServoLayoutNode<'_>,
666) -> Option<OffsetParentResponse> {
667    // Only consider the first fragment of the node found as per a
668    // possible interpretation of the specification: "[...] return the
669    // y-coordinate of the top border edge of the first CSS layout box
670    // associated with the element [...]"
671    //
672    // FIXME: Browsers implement this all differently (e.g., [1]) -
673    // Firefox does returns the union of all layout elements of some
674    // sort. Chrome returns the first fragment for a block element (the
675    // same as ours) or the union of all associated fragments in the
676    // first containing block fragment for an inline element. We could
677    // implement Chrome's behavior, but our fragment tree currently
678    // provides insufficient information.
679    //
680    // [1]: https://github.com/w3c/csswg-drafts/issues/4541
681    // > 1. If the element is the HTML body element or does not have any associated CSS
682    //      layout box return zero and terminate this algorithm.
683    let fragment = node.fragments_for_pseudo(None).first().cloned()?;
684    let mut border_box =
685        fragment.cumulative_box_area_rect(BoxAreaType::Border, layout_thread.into())?;
686    let cumulative_sticky_offsets = fragment.spatial_tree_node().map(|node_id| {
687        scroll_tree
688            .cumulative_sticky_offsets(node_id)
689            .map(Au::from_f32_px)
690            .cast_unit()
691    });
692    border_box = border_box.translate(cumulative_sticky_offsets.unwrap_or_default());
693
694    // 2.  If the offsetParent of the element is null return the x-coordinate of the left
695    //     border edge of the first CSS layout box associated with the element, relative to
696    //     the initial containing block origin, ignoring any transforms that apply to the
697    //     element and its ancestors, and terminate this algorithm.
698    let Some(offset_parent_fragment) = offset_parent_fragments(node) else {
699        return Some(OffsetParentResponse {
700            node_address: None,
701            rect: border_box,
702        });
703    };
704
705    let parent_fragment = &offset_parent_fragment.parent;
706    let parent_is_static_body_element = parent_fragment
707        .base
708        .flags
709        .contains(FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT) &&
710        parent_fragment.style().get_box().position == Position::Static;
711
712    // For `offsetLeft`:
713    // 3. Return the result of subtracting the y-coordinate of the top padding edge of the
714    //    first CSS layout box associated with the offsetParent of the element from the
715    //    y-coordinate of the top border edge of the first CSS layout box associated with the
716    //    element, relative to the initial containing block origin, ignoring any transforms
717    //    that apply to the element and its ancestors.
718    //
719    // We generalize this for `offsetRight` as described in the specification.
720    //
721    // The spec (https://www.w3.org/TR/cssom-view-1/#extensions-to-the-htmlelement-interface)
722    // says that offsetTop/offsetLeft are always relative to the padding box of the offsetParent.
723    // However, in practice this is not true in major browsers in the case that the offsetParent is the body
724    // element and the body element is position:static. In that case offsetLeft/offsetTop are computed
725    // relative to the root node's border box.
726    //
727    // See <https://github.com/w3c/csswg-drafts/issues/10549>.
728    let parent_offset_rect = if parent_is_static_body_element {
729        if let Some(grandparent_fragment) = offset_parent_fragment.grandparent_box_fragment() {
730            grandparent_fragment.offset_by_cumulative_content_offset(
731                &grandparent_fragment.border_rect(),
732                layout_thread.into(),
733            )
734        } else {
735            parent_fragment.offset_by_cumulative_content_offset(
736                &parent_fragment.padding_rect(),
737                layout_thread.into(),
738            )
739        }
740    } else {
741        parent_fragment.offset_by_cumulative_content_offset(
742            &parent_fragment.padding_rect(),
743            layout_thread.into(),
744        )
745    }
746    .translate(
747        cumulative_sticky_offsets
748            .and_then(|_| parent_fragment.spatial_tree_node())
749            .map(|node_id| {
750                scroll_tree
751                    .cumulative_sticky_offsets(node_id)
752                    .map(Au::from_f32_px)
753                    .cast_unit()
754            })
755            .unwrap_or_default(),
756    );
757
758    border_box = border_box.translate(-parent_offset_rect.origin.to_vector());
759
760    Some(OffsetParentResponse {
761        node_address: parent_fragment.base.tag.map(|tag| tag.node.into()),
762        rect: border_box,
763    })
764}
765
766fn is_containing_block_for_position(
767    position: Position,
768    ancestor_style: &ServoArc<ComputedValues>,
769    ancestor_flags: FragmentFlags,
770) -> bool {
771    match position {
772        Position::Static | Position::Relative | Position::Sticky => {
773            !ancestor_style.is_inline_box(ancestor_flags)
774        },
775        Position::Absolute => {
776            ancestor_style.establishes_containing_block_for_absolute_descendants(ancestor_flags)
777        },
778        Position::Fixed => {
779            ancestor_style.establishes_containing_block_for_all_descendants(ancestor_flags)
780        },
781    }
782}
783
784fn containing_block_for_node<'a>(node: ServoLayoutNode<'a>) -> Option<ServoLayoutNode<'a>> {
785    let node_style = node.with_layout_box_base(|base| base.style.clone())?;
786    let position = node_style.get_box().position;
787    let mut current_ancestor = node;
788
789    #[expect(unsafe_code)]
790    while let Some(ancestor) =
791        unsafe { current_ancestor.dangerous_flat_tree_parent_considering_pseudos() }
792    {
793        current_ancestor = ancestor;
794
795        let Some((ancestor_style, ancestor_flags)) = ancestor
796            .with_layout_box_base(|base| (base.style.clone(), base.base_fragment_info.flags))
797        else {
798            continue;
799        };
800
801        if is_containing_block_for_position(position, &ancestor_style, ancestor_flags) {
802            return Some(ancestor);
803        }
804    }
805    None
806}
807
808fn containing_block_fragment(
809    node: ServoLayoutNode,
810    fragment: &BoxFragment,
811) -> Option<Arc<BoxFragment>> {
812    let containing_block_node = containing_block_for_node(node)?;
813    containing_block_node.with_layout_box_base(|layout_box_base| {
814        let fragments = layout_box_base.fragments();
815
816        // When there is more than a single fragment the containing block has been fragmented,
817        // so we need to search for the fragment that contains the one we are looking for.
818        if fragments.len() > 1 {
819            for potential_fragment in fragments.iter() {
820                if let Some(potential_box_fragment) = potential_fragment.retrieve_box_fragment() &&
821                    potential_box_fragment
822                        .children
823                        .iter()
824                        .any(|child_fragment| child_fragment.is_box_fragment(fragment))
825                {
826                    return Some(potential_box_fragment.clone());
827                }
828            }
829        }
830
831        // Fall back to the first fragment which is necessary for the case of inline
832        // formatting contexts which establish containing blocks for their nested contents.
833        Some(fragments.first()?.retrieve_box_fragment()?.clone())
834    }).flatten()
835}
836
837/// An implementation of `scrollParent` that can also be used to for `scrollIntoView`:
838/// <https://drafts.csswg.org/cssom-view/#dom-htmlelement-scrollparent>.
839///
840#[inline]
841pub(crate) fn process_scroll_container_query(
842    node: Option<ServoLayoutNode<'_>>,
843    query_flags: ScrollContainerQueryFlags,
844    viewport_overflow: AxesOverflow,
845    viewport_writing_mode: WritingMode,
846) -> Option<ScrollContainerResponse> {
847    let Some(node) = node else {
848        return Some(ScrollContainerResponse::Viewport(
849            viewport_overflow,
850            viewport_writing_mode,
851        ));
852    };
853
854    // 1. If any of the following holds true, return null and terminate this algorithm:
855    //  - The element does not have an associated box.
856    let (style, flags) =
857        node.with_layout_box_base(|base| (base.style.clone(), base.base_fragment_info.flags))?;
858
859    // - The element is the root element.
860    // - The element is the body element.
861    //
862    // Note: We only do this for `scrollParent`, which needs to be null. But `scrollIntoView` on the
863    // `<body>` or root element should still bring it into view by scrolling the viewport.
864    if query_flags.contains(ScrollContainerQueryFlags::ForScrollParent) &&
865        flags.intersects(
866            FragmentFlags::IS_ROOT_ELEMENT | FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT,
867        )
868    {
869        return None;
870    }
871
872    if query_flags.contains(ScrollContainerQueryFlags::Inclusive) &&
873        style.establishes_scroll_container(flags)
874    {
875        return Some(ScrollContainerResponse::Element(
876            node.opaque().into(),
877            style.effective_overflow(flags),
878            style.writing_mode,
879        ));
880    }
881
882    // - The element’s computed value of the position property is fixed and no ancestor
883    //   establishes a fixed position containing block.
884    //
885    // This is handled below in step 2.
886
887    // 2. Let ancestor be the containing block of the element in the flat tree and repeat these substeps:
888    // - If ancestor is the initial containing block, return the scrollingElement for the
889    //   element’s document if it is not closed-shadow-hidden from the element, otherwise
890    //   return null.
891    // - If ancestor is not closed-shadow-hidden from the element, and is a scroll
892    //   container, terminate this algorithm and return ancestor.
893    // - If the computed value of the position property of ancestor is fixed, and no
894    //   ancestor establishes a fixed position containing block, terminate this algorithm
895    //   and return null.
896    // - Let ancestor be the containing block of ancestor in the flat tree.
897    //
898    // Notes: We don't follow the specification exactly below, but we follow the spirit.
899    //
900    // TODO: Handle the situation where the ancestor is "closed-shadow-hidden" from the element.
901    let mut current_position_value = style.get_box().position;
902    let mut current_ancestor = node;
903
904    #[expect(unsafe_code)]
905    while let Some(ancestor) = unsafe { current_ancestor.dangerous_flat_tree_parent() } {
906        current_ancestor = ancestor;
907
908        let Some((ancestor_style, ancestor_flags)) = ancestor
909            .with_layout_box_base(|base| (base.style.clone(), base.base_fragment_info.flags))
910        else {
911            continue;
912        };
913
914        if !is_containing_block_for_position(
915            current_position_value,
916            &ancestor_style,
917            ancestor_flags,
918        ) {
919            continue;
920        }
921
922        if ancestor_style.establishes_scroll_container(ancestor_flags) {
923            return Some(ScrollContainerResponse::Element(
924                ancestor.opaque().into(),
925                ancestor_style.effective_overflow(ancestor_flags),
926                ancestor_style.writing_mode,
927            ));
928        }
929
930        current_position_value = ancestor_style.get_box().position;
931    }
932
933    match current_position_value {
934        Position::Fixed => None,
935        _ => Some(ScrollContainerResponse::Viewport(
936            viewport_overflow,
937            viewport_writing_mode,
938        )),
939    }
940}
941
942/// <https://html.spec.whatwg.org/multipage/#get-the-text-steps>
943pub fn get_the_text_steps(node: ServoLayoutNode<'_>) -> String {
944    // Step 1: If element is not being rendered or if the user agent is a non-CSS user agent, then
945    // return element's descendant text content.
946    // This is taken care of in HTMLElement code
947
948    // Step 2: Let results be a new empty list.
949    let mut results = Vec::new();
950    let mut max_req_line_break_count = 0;
951
952    // Step 3: For each child node node of element:
953    let mut state = Default::default();
954    for child in node.dom_children() {
955        // Step 1: Let current be the list resulting in running the rendered text collection steps with node.
956        let mut current = rendered_text_collection_steps(child, &mut state);
957        // Step 2: For each item item in current, append item to results.
958        results.append(&mut current);
959    }
960
961    let mut output = String::new();
962    for item in results {
963        match item {
964            InnerOrOuterTextItem::Text(s) => {
965                // Step 3.
966                if !s.is_empty() {
967                    if max_req_line_break_count > 0 {
968                        // Step 5.
969                        output.extend(std::iter::repeat_n('\u{000A}', max_req_line_break_count));
970                        max_req_line_break_count = 0;
971                    }
972                    output.push_str(&s);
973                }
974            },
975            InnerOrOuterTextItem::RequiredLineBreakCount(count) => {
976                // Step 4.
977                if output.is_empty() {
978                    // Remove required line break count at the start.
979                    continue;
980                }
981                // Store the count if it's the max of this run, but it may be ignored if no text
982                // item is found afterwards, which means that these are consecutive line breaks at
983                // the end.
984                if count > max_req_line_break_count {
985                    max_req_line_break_count = count;
986                }
987            },
988        }
989    }
990    output
991}
992
993enum InnerOrOuterTextItem {
994    Text(Cow<'static, str>),
995    RequiredLineBreakCount(usize),
996}
997
998#[derive(Clone)]
999struct RenderedTextCollectionState {
1000    /// Used to make sure we don't add a `\n` before the first row
1001    first_table_row: bool,
1002    /// Used to make sure we don't add a `\t` before the first column
1003    first_table_cell: bool,
1004    /// Keeps track of whether we're inside a table, since there are special rules like ommiting everything that's not
1005    /// inside a TableCell/TableCaption
1006    within_table: bool,
1007    /// Determines whether we truncate leading whitespaces for normal nodes or not
1008    may_start_with_whitespace: bool,
1009    /// Is set whenever we truncated a white space char, used to prepend a single space before the next element,
1010    /// that way we truncate trailing white space without having to look ahead
1011    did_truncate_trailing_white_space: bool,
1012    /// Is set to true when we're rendering the children of TableCell/TableCaption elements, that way we render
1013    /// everything inside those as normal, while omitting everything that's in a Table but NOT in a Cell/Caption
1014    within_table_content: bool,
1015}
1016
1017impl Default for RenderedTextCollectionState {
1018    fn default() -> Self {
1019        RenderedTextCollectionState {
1020            first_table_row: true,
1021            first_table_cell: true,
1022            may_start_with_whitespace: true,
1023            did_truncate_trailing_white_space: false,
1024            within_table: false,
1025            within_table_content: false,
1026        }
1027    }
1028}
1029
1030/// <https://html.spec.whatwg.org/multipage/#rendered-text-collection-steps>
1031#[expect(unsafe_code)]
1032fn rendered_text_collection_steps(
1033    node: ServoLayoutNode<'_>,
1034    state: &mut RenderedTextCollectionState,
1035) -> Vec<InnerOrOuterTextItem> {
1036    // Step 1. Let items be the result of running the rendered text collection
1037    // steps with each child node of node in tree order,
1038    // and then concatenating the results to a single list.
1039    let mut items = vec![];
1040    if !node.is_connected() || !(node.is_element() || node.is_text_node()) {
1041        return items;
1042    }
1043
1044    match node.type_id() {
1045        Some(LayoutNodeType::Text) => {
1046            if let Some(parent_node) = unsafe { node.dangerous_dom_parent() } {
1047                match parent_node.type_id() {
1048                    // Any text contained in these elements must be ignored.
1049                    Some(
1050                        LayoutNodeType::Element(LayoutElementType::HTMLCanvasElement) |
1051                        LayoutNodeType::Element(LayoutElementType::HTMLImageElement) |
1052                        LayoutNodeType::Element(LayoutElementType::HTMLIFrameElement) |
1053                        LayoutNodeType::Element(LayoutElementType::HTMLObjectElement) |
1054                        LayoutNodeType::Element(LayoutElementType::HTMLInputElement) |
1055                        LayoutNodeType::Element(LayoutElementType::HTMLTextAreaElement) |
1056                        LayoutNodeType::Element(LayoutElementType::HTMLMediaElement),
1057                    ) => {
1058                        return items;
1059                    },
1060                    // Select/Option/OptGroup elements are handled a bit differently.
1061                    // Basically: a Select can only contain Options or OptGroups, while
1062                    // OptGroups may also contain Options. Everything else gets ignored.
1063                    Some(LayoutNodeType::Element(LayoutElementType::HTMLOptGroupElement)) => {
1064                        if let Some(grandparent_node) =
1065                            unsafe { parent_node.dangerous_dom_parent() }
1066                        {
1067                            // The grandparent might not be an element (for example a `Document`
1068                            // or a shadow root), and layout can't represent those node types,
1069                            // so check for an element before asking for its type.
1070                            let grandparent_is_select = grandparent_node.as_element().is_some() &&
1071                                matches!(
1072                                    grandparent_node.type_id(),
1073                                    Some(LayoutNodeType::Element(
1074                                        LayoutElementType::HTMLSelectElement
1075                                    ))
1076                                );
1077                            if !grandparent_is_select {
1078                                return items;
1079                            }
1080                        } else {
1081                            return items;
1082                        }
1083                    },
1084                    Some(LayoutNodeType::Element(LayoutElementType::HTMLSelectElement)) => {
1085                        return items;
1086                    },
1087                    _ => {},
1088                }
1089
1090                // Tables are also a bit special, mainly by only allowing
1091                // content within TableCell or TableCaption elements once
1092                // we're inside a Table.
1093                if state.within_table && !state.within_table_content {
1094                    return items;
1095                }
1096
1097                let Some(parent_element) = parent_node.as_element() else {
1098                    return items;
1099                };
1100                let Some(style_data) = parent_element.style_data() else {
1101                    return items;
1102                };
1103
1104                let element_data = style_data.element_data.borrow();
1105                let Some(style) = element_data.styles.get_primary() else {
1106                    return items;
1107                };
1108
1109                // Step 2: If node's computed value of 'visibility' is not 'visible', then return items.
1110                //
1111                // We need to do this check here on the Text fragment, if we did it on the element and
1112                // just skipped rendering all child nodes then there'd be no way to override the
1113                // visibility in a child node.
1114                if style.get_inherited_box().visibility != Visibility::Visible {
1115                    return items;
1116                }
1117
1118                // Step 3: If node is not being rendered, then return items. For the purpose of this step,
1119                // the following elements must act as described if the computed value of the 'display'
1120                // property is not 'none':
1121                let display = style.get_box().display;
1122                if display == Display::None {
1123                    match parent_element.type_id() {
1124                        // Even if set to Display::None, Option/OptGroup elements need to
1125                        // be rendered.
1126                        Some(
1127                            LayoutNodeType::Element(LayoutElementType::HTMLOptGroupElement) |
1128                            LayoutNodeType::Element(LayoutElementType::HTMLOptionElement),
1129                        ) => {},
1130                        _ => {
1131                            return items;
1132                        },
1133                    }
1134                }
1135
1136                let text_content = node.text_content();
1137
1138                let white_space_collapse = style.get_white_space_collapse();
1139                let preserve_whitespace =
1140                    white_space_collapse == &WhiteSpaceCollapseValue::Preserve;
1141                let is_inline = matches!(
1142                    display,
1143                    Display::InlineBlock | Display::InlineFlex | Display::InlineGrid
1144                );
1145
1146                // Now we need to decide on whether to remove beginning white space or not, this
1147                // is mainly decided by the elements we rendered before, but may be overwritten by the white-space
1148                // property.
1149                let trim_leading_white_space =
1150                    !preserve_whitespace && (state.may_start_with_whitespace || is_inline);
1151                // FIXME: This assumes the element always start at a word boundary. But can fail:
1152                // a<span style="text-transform: capitalize">b</span>c
1153                let on_word_boundary = true;
1154
1155                // Step 4: If node is a Text node, then for each CSS text box produced by node, in
1156                // content order, compute the text of the box after application of the CSS
1157                // 'white-space' processing rules and 'text-transform' rules, set items to the list
1158                // of the resulting strings, and return items. The CSS 'white-space' processing
1159                // rules are slightly modified: collapsible spaces at the end of lines are always
1160                // collapsed, but they are only removed if the line is the last line of the block,
1161                // or it ends with a br element. Soft hyphens should be preserved.
1162                let mut transformed_text = String::with_capacity(text_content.len());
1163                for iteration in TextTransformationIterator::new(
1164                    &text_content,
1165                    style,
1166                    trim_leading_white_space,
1167                    on_word_boundary,
1168                ) {
1169                    transformed_text.extend(iteration.characters());
1170                }
1171
1172                let is_preformatted_element =
1173                    white_space_collapse == &WhiteSpaceCollapseValue::Preserve;
1174
1175                let is_final_character_whitespace = transformed_text
1176                    .chars()
1177                    .next_back()
1178                    .filter(char::is_ascii_whitespace)
1179                    .is_some();
1180
1181                let is_first_character_whitespace = transformed_text
1182                    .chars()
1183                    .next()
1184                    .filter(char::is_ascii_whitespace)
1185                    .is_some();
1186
1187                // By truncating trailing white space and then adding it back in once we
1188                // encounter another text node we can ensure no trailing white space for
1189                // normal text without having to look ahead
1190                if state.did_truncate_trailing_white_space && !is_first_character_whitespace {
1191                    items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(" ")));
1192                };
1193
1194                if !transformed_text.is_empty() {
1195                    // Here we decide whether to keep or truncate the final white
1196                    // space character, if there is one.
1197                    if is_final_character_whitespace && !is_preformatted_element {
1198                        state.may_start_with_whitespace = false;
1199                        state.did_truncate_trailing_white_space = true;
1200                        transformed_text.pop();
1201                    } else {
1202                        state.may_start_with_whitespace = is_final_character_whitespace;
1203                        state.did_truncate_trailing_white_space = false;
1204                    }
1205                    items.push(InnerOrOuterTextItem::Text(Cow::Owned(transformed_text)));
1206                }
1207            } else {
1208                // If we don't have a parent element then there's no style data available,
1209                // in this (pretty unlikely) case we just return the Text fragment as is.
1210                items.push(InnerOrOuterTextItem::Text(Cow::Owned(
1211                    node.text_content().deref().into(),
1212                )));
1213            }
1214        },
1215        Some(LayoutNodeType::Element(LayoutElementType::HTMLBRElement)) => {
1216            // Step 5: If node is a br element, then append a string containing a single U+000A
1217            // LF code point to items.
1218            state.did_truncate_trailing_white_space = false;
1219            state.may_start_with_whitespace = true;
1220            items.push(InnerOrOuterTextItem::Text(Cow::Borrowed("\u{000A}")));
1221        },
1222        _ => {
1223            // First we need to gather some infos to setup the various flags
1224            // before rendering the child nodes
1225            let Some(element) = node.as_element() else {
1226                return items;
1227            };
1228            let Some(style_data) = element.style_data() else {
1229                return items;
1230            };
1231
1232            let element_data = style_data.element_data.borrow();
1233            let Some(style) = element_data.styles.get_primary() else {
1234                return items;
1235            };
1236            let inherited_box = style.get_inherited_box();
1237
1238            if inherited_box.visibility != Visibility::Visible {
1239                // If the element is not visible, then we'll immediately render all children,
1240                // skipping all other processing.
1241                // We can't just stop here since a child can override a parents visibility.
1242                for child in node.dom_children() {
1243                    items.append(&mut rendered_text_collection_steps(child, state));
1244                }
1245                return items;
1246            }
1247
1248            let style_box = style.get_box();
1249            let display = style_box.display;
1250            let mut surrounding_line_breaks = 0;
1251
1252            // Treat absolutely positioned or floated elements like Block elements
1253            if style_box.position == Position::Absolute || style_box.float != Float::None {
1254                surrounding_line_breaks = 1;
1255            }
1256
1257            // Depending on the display property we have to do various things
1258            // before we can render the child nodes.
1259            match display {
1260                Display::Table => {
1261                    surrounding_line_breaks = 1;
1262                    state.within_table = true;
1263                },
1264                // Step 6: If node's computed value of 'display' is 'table-cell',
1265                // and node's CSS box is not the last 'table-cell' box of its
1266                // enclosing 'table-row' box, then append a string containing
1267                // a single U+0009 TAB code point to items.
1268                Display::TableCell => {
1269                    if !state.first_table_cell {
1270                        items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(
1271                            "\u{0009}", /* tab */
1272                        )));
1273                        // Make sure we don't add a white-space we removed from the previous node
1274                        state.did_truncate_trailing_white_space = false;
1275                    }
1276                    state.first_table_cell = false;
1277                    state.within_table_content = true;
1278                },
1279                // Step 7: If node's computed value of 'display' is 'table-row',
1280                // and node's CSS box is not the last 'table-row' box of the nearest
1281                // ancestor 'table' box, then append a string containing a single U+000A
1282                // LF code point to items.
1283                Display::TableRow => {
1284                    if !state.first_table_row {
1285                        items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(
1286                            "\u{000A}", /* Line Feed */
1287                        )));
1288                        // Make sure we don't add a white-space we removed from the previous node
1289                        state.did_truncate_trailing_white_space = false;
1290                    }
1291                    state.first_table_row = false;
1292                    state.first_table_cell = true;
1293                },
1294                // Step 9: If node's used value of 'display' is block-level or 'table-caption',
1295                // then append 1 (a required line break count) at the beginning and end of items.
1296                Display::Block => {
1297                    surrounding_line_breaks = 1;
1298                },
1299                Display::TableCaption => {
1300                    surrounding_line_breaks = 1;
1301                    state.within_table_content = true;
1302                },
1303                // InlineBlock's are a bit strange, in that they don't produce a Linebreak, yet
1304                // disable white space truncation before and after it, making it one of the few
1305                // cases where one can have multiple white space characters following one another.
1306                Display::InlineFlex | Display::InlineGrid | Display::InlineBlock
1307                    if state.did_truncate_trailing_white_space =>
1308                {
1309                    items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(" ")));
1310                    state.did_truncate_trailing_white_space = false;
1311                    state.may_start_with_whitespace = true;
1312                },
1313                _ => {},
1314            }
1315
1316            match node.type_id() {
1317                // Step 8: If node is a p element, then append 2 (a required line break count) at
1318                // the beginning and end of items.
1319                Some(LayoutNodeType::Element(LayoutElementType::HTMLParagraphElement)) => {
1320                    surrounding_line_breaks = 2;
1321                },
1322                // Option/OptGroup elements should go on separate lines, by treating them like
1323                // Block elements we can achieve that.
1324                Some(
1325                    LayoutNodeType::Element(LayoutElementType::HTMLOptionElement) |
1326                    LayoutNodeType::Element(LayoutElementType::HTMLOptGroupElement),
1327                ) => {
1328                    surrounding_line_breaks = 1;
1329                },
1330                _ => {},
1331            }
1332
1333            if surrounding_line_breaks > 0 {
1334                items.push(InnerOrOuterTextItem::RequiredLineBreakCount(
1335                    surrounding_line_breaks,
1336                ));
1337                state.did_truncate_trailing_white_space = false;
1338                state.may_start_with_whitespace = true;
1339            }
1340
1341            match node.type_id() {
1342                // Any text/content contained in these elements is ignored.
1343                // However we still need to check whether we have to prepend a
1344                // space, since for example <span>asd <input> qwe</span> must
1345                // product "asd  qwe" (note the 2 spaces)
1346                Some(
1347                    LayoutNodeType::Element(LayoutElementType::HTMLCanvasElement) |
1348                    LayoutNodeType::Element(LayoutElementType::HTMLImageElement) |
1349                    LayoutNodeType::Element(LayoutElementType::HTMLIFrameElement) |
1350                    LayoutNodeType::Element(LayoutElementType::HTMLObjectElement) |
1351                    LayoutNodeType::Element(LayoutElementType::HTMLInputElement) |
1352                    LayoutNodeType::Element(LayoutElementType::HTMLTextAreaElement) |
1353                    LayoutNodeType::Element(LayoutElementType::HTMLMediaElement),
1354                ) => {
1355                    if display != Display::Block && state.did_truncate_trailing_white_space {
1356                        items.push(InnerOrOuterTextItem::Text(Cow::Borrowed(" ")));
1357                        state.did_truncate_trailing_white_space = false;
1358                    };
1359                    state.may_start_with_whitespace = false;
1360                },
1361                _ => {
1362                    // Now we can finally iterate over all children, appending whatever
1363                    // they produce to items.
1364                    for child in node.dom_children() {
1365                        items.append(&mut rendered_text_collection_steps(child, state));
1366                    }
1367                },
1368            }
1369
1370            // Depending on the display property we still need to do some
1371            // cleanup after rendering all child nodes
1372            match display {
1373                Display::InlineFlex | Display::InlineGrid | Display::InlineBlock => {
1374                    state.did_truncate_trailing_white_space = false;
1375                    state.may_start_with_whitespace = false;
1376                },
1377                Display::Table => {
1378                    state.within_table = false;
1379                },
1380                Display::TableCell | Display::TableCaption => {
1381                    state.within_table_content = false;
1382                },
1383                _ => {},
1384            }
1385
1386            if surrounding_line_breaks > 0 {
1387                items.push(InnerOrOuterTextItem::RequiredLineBreakCount(
1388                    surrounding_line_breaks,
1389                ));
1390                state.did_truncate_trailing_white_space = false;
1391                state.may_start_with_whitespace = true;
1392            }
1393        },
1394    };
1395    items
1396}
1397
1398pub fn find_character_offset_in_fragment_descendants(
1399    node: &ServoLayoutNode,
1400    stacking_context_tree: &StackingContextTree,
1401    point_in_viewport: Point2D<Au, CSSPixel>,
1402) -> Option<(OpaqueNode, Utf32CodeUnits)> {
1403    let mut search = ClosestFragmentSearch::default();
1404    for fragment in &node.fragments_for_pseudo(None) {
1405        if let Some(point_in_fragment) =
1406            stacking_context_tree.offset_in_fragment(fragment, point_in_viewport)
1407        {
1408            search.collect_relevant_children(fragment, point_in_fragment);
1409        }
1410    }
1411    search.into_dom_position()
1412}
1413
1414pub fn process_containing_block_query(node: ServoLayoutNode) -> Option<UntrustedNodeAddress> {
1415    let containing_block = containing_block_for_node(node);
1416    containing_block.map(|node| node.opaque().into())
1417}
1418
1419pub fn process_containing_block_descendant_query(
1420    possible_ancestor: ServoLayoutNode,
1421    mut possible_descendant: ServoLayoutNode,
1422) -> bool {
1423    while let Some(establishing_node) = containing_block_for_node(possible_descendant) {
1424        if establishing_node == possible_ancestor {
1425            return true;
1426        }
1427        possible_descendant = establishing_node;
1428    }
1429    false
1430}
1431
1432pub fn process_resolved_font_style_query<'dom, E>(
1433    context: &SharedStyleContext,
1434    node: E,
1435    value: &str,
1436    url_data: ServoUrl,
1437    shared_lock: &SharedRwLock,
1438) -> Option<ServoArc<Font>>
1439where
1440    E: LayoutNode<'dom>,
1441{
1442    fn create_font_declaration(
1443        value: &str,
1444        url_data: &ServoUrl,
1445        quirks_mode: QuirksMode,
1446    ) -> Option<PropertyDeclarationBlock> {
1447        let mut declarations = SourcePropertyDeclaration::default();
1448        let result = parse_one_declaration_into(
1449            &mut declarations,
1450            PropertyId::NonCustom(ShorthandId::Font.into()),
1451            value,
1452            Origin::Author,
1453            &UrlExtraData(url_data.get_arc()),
1454            None,
1455            ParsingMode::DEFAULT,
1456            quirks_mode,
1457            CssRuleType::Style,
1458        );
1459        let declarations = match result {
1460            Ok(()) => {
1461                let mut block = PropertyDeclarationBlock::new();
1462                block.extend(declarations.drain(), Importance::Normal);
1463                block
1464            },
1465            Err(_) => return None,
1466        };
1467        // TODO: Force to set line-height property to 'normal' font property.
1468        Some(declarations)
1469    }
1470    fn resolve_for_declarations<'dom, E>(
1471        context: &SharedStyleContext,
1472        parent_style: Option<&ComputedValues>,
1473        declarations: PropertyDeclarationBlock,
1474        shared_lock: &SharedRwLock,
1475    ) -> ServoArc<ComputedValues>
1476    where
1477        E: LayoutNode<'dom>,
1478    {
1479        let parent_style = match parent_style {
1480            Some(parent) => parent,
1481            None => context.stylist.device().default_computed_values(),
1482        };
1483        context
1484            .stylist
1485            .compute_for_declarations::<DangerousStyleElementOf<'dom, E::ConcreteTypeBundle>>(
1486                &context.guards,
1487                parent_style,
1488                ServoArc::new(shared_lock.wrap(declarations)),
1489            )
1490    }
1491
1492    // https://html.spec.whatwg.org/multipage/#dom-context-2d-font
1493    // 1. Parse the given font property value
1494    let quirks_mode = context.quirks_mode();
1495    let declarations = create_font_declaration(value, &url_data, quirks_mode)?;
1496
1497    // TODO: Reject 'inherit' and 'initial' values for the font property.
1498
1499    // 2. Get resolved styles for the parent element
1500    let element = node.as_element().unwrap();
1501    let parent_style = if node.is_connected() {
1502        if element.style_data().is_some() {
1503            element.style(context)
1504        } else {
1505            let mut tlc = ThreadLocalStyleContext::new();
1506            let mut context = StyleContext {
1507                shared: context,
1508                thread_local: &mut tlc,
1509            };
1510            #[expect(unsafe_code)]
1511            let styles = resolve_style(
1512                &mut context,
1513                unsafe { element.dangerous_style_element() },
1514                RuleInclusion::All,
1515                None,
1516                None,
1517            );
1518            styles.primary().clone()
1519        }
1520    } else {
1521        let default_declarations =
1522            create_font_declaration("10px sans-serif", &url_data, quirks_mode).unwrap();
1523        resolve_for_declarations::<E>(context, None, default_declarations, shared_lock)
1524    };
1525
1526    // 3. Resolve the parsed value with resolved styles of the parent element
1527    let computed_values =
1528        resolve_for_declarations::<E>(context, Some(&*parent_style), declarations, shared_lock);
1529
1530    Some(computed_values.clone_font())
1531}
1532
1533pub(crate) fn transform_au_rectangle(
1534    rect_to_transform: Rect<Au, CSSPixel>,
1535    transform: FastLayoutTransform,
1536) -> Option<Rect<Au, CSSPixel>> {
1537    transform_f32_rectangle(
1538        au_rect_to_f32_rect(rect_to_transform).cast_unit(),
1539        transform,
1540    )
1541    .map(|transformed_rect| f32_rect_to_au_rect(transformed_rect).cast_unit())
1542}
1543
1544pub(crate) fn transform_f32_rectangle(
1545    rect_to_transform: Rect<f32, LayoutPixel>,
1546    transform: FastLayoutTransform,
1547) -> Option<Rect<f32, LayoutPixel>> {
1548    match transform {
1549        FastLayoutTransform::Offset(offset) => Some(rect_to_transform.translate(offset)),
1550        FastLayoutTransform::Transform { transform, .. } => {
1551            transform.outer_transformed_rect(&rect_to_transform)
1552        },
1553    }
1554}
1555
1556pub(crate) fn process_effective_overflow_query(node: ServoLayoutNode<'_>) -> Option<AxesOverflow> {
1557    let fragments = node.fragments_for_pseudo(None);
1558    let box_fragment = fragments.first()?.retrieve_box_fragment()?;
1559
1560    Some(
1561        box_fragment
1562            .style()
1563            .effective_overflow(box_fragment.base.flags),
1564    )
1565}
1566
1567impl BoxFragment {
1568    fn resolved_insets_for_non_static(
1569        &self,
1570        node: ServoLayoutNode,
1571        style: &ComputedValues,
1572        initial_containing_block: &PhysicalRect<Au>,
1573    ) -> Option<PhysicalSides<AuOrAuto>> {
1574        match style.get_box().position {
1575            Position::Static => None,
1576            Position::Relative => {
1577                self.resolved_insets_for_relative(node, style, initial_containing_block)
1578            },
1579            Position::Absolute | Position::Fixed => {
1580                self.resolved_insets_for_absolute(node, style, initial_containing_block)
1581            },
1582            Position::Sticky => Some(**self.resolved_sticky_insets()?),
1583        }
1584    }
1585
1586    fn resolved_insets_for_relative(
1587        &self,
1588        node: ServoLayoutNode,
1589        style: &ComputedValues,
1590        initial_containing_block: &PhysicalRect<Au>,
1591    ) -> Option<PhysicalSides<AuOrAuto>> {
1592        let get_resolved_axis =
1593            |start: &LengthPercentageOrAuto, end: &LengthPercentageOrAuto, container_length: Au| {
1594                let start = start.map(|value| value.to_used_value(container_length));
1595                let end = end.map(|value| value.to_used_value(container_length));
1596                match (start.non_auto(), end.non_auto()) {
1597                    (None, None) => (Au::zero(), Au::zero()),
1598                    (None, Some(end)) => (-end, end),
1599                    (Some(start), None) => (start, -start),
1600                    // This is the overconstrained case, for which the resolved insets will
1601                    // simply be the computed insets.
1602                    (Some(start), Some(end)) => (start, end),
1603                }
1604            };
1605
1606        // From <https://drafts.csswg.org/cssom/#resolved-values>:
1607        // "A resolved value special case property like top defined in another
1608        // specification If the property applies to a positioned element and the
1609        // resolved value of the display property is not none or contents, and
1610        // the property is not over-constrained, then the resolved value is the
1611        // used value. Otherwise the resolved value is the computed value."
1612        let insets = style.physical_box_offsets();
1613        let containing_block_rect_size = containing_block_fragment(node, self)
1614            .map(|fragment| fragment.content_rect())
1615            .unwrap_or(*initial_containing_block)
1616            .size;
1617        let (left, right) = get_resolved_axis(
1618            &insets.left,
1619            &insets.right,
1620            containing_block_rect_size.width,
1621        );
1622        let (top, bottom) = get_resolved_axis(
1623            &insets.top,
1624            &insets.bottom,
1625            containing_block_rect_size.height,
1626        );
1627        Some(au_or_auto_sides(PhysicalSides::new(
1628            top, right, bottom, left,
1629        )))
1630    }
1631
1632    fn resolved_insets_for_absolute(
1633        &self,
1634        node: ServoLayoutNode,
1635        style: &ComputedValues,
1636        initial_containing_block: &PhysicalRect<Au>,
1637    ) -> Option<PhysicalSides<AuOrAuto>> {
1638        let insets = style.physical_box_offsets();
1639        let containing_block_rect = containing_block_fragment(node, self)
1640            .map(|fragment| fragment.containing_block_rect_for_absolute(style))
1641            .unwrap_or(*initial_containing_block);
1642
1643        let margin_rect = self.margin_rect();
1644        let (top, bottom) = match (&insets.top, &insets.bottom) {
1645            (
1646                LengthPercentageOrAuto::LengthPercentage(top),
1647                LengthPercentageOrAuto::LengthPercentage(bottom),
1648            ) => (
1649                top.to_used_value(containing_block_rect.size.height),
1650                bottom.to_used_value(containing_block_rect.size.height),
1651            ),
1652            _ => (
1653                margin_rect.min_y() - containing_block_rect.min_y(),
1654                containing_block_rect.max_y() - margin_rect.max_y(),
1655            ),
1656        };
1657        let (left, right) = match (&insets.left, &insets.right) {
1658            (
1659                LengthPercentageOrAuto::LengthPercentage(left),
1660                LengthPercentageOrAuto::LengthPercentage(right),
1661            ) => (
1662                left.to_used_value(containing_block_rect.size.width),
1663                right.to_used_value(containing_block_rect.size.width),
1664            ),
1665            _ => (
1666                margin_rect.min_x() - containing_block_rect.min_x(),
1667                containing_block_rect.max_x() - margin_rect.max_x(),
1668            ),
1669        };
1670
1671        Some(au_or_auto_sides(PhysicalSides::new(
1672            top, right, bottom, left,
1673        )))
1674    }
1675}
1676
1677fn au_or_auto_sides(sides: PhysicalSides<Au>) -> PhysicalSides<AuOrAuto> {
1678    PhysicalSides::new(
1679        AuOrAuto::LengthPercentage(sides.top),
1680        AuOrAuto::LengthPercentage(sides.right),
1681        AuOrAuto::LengthPercentage(sides.bottom),
1682        AuOrAuto::LengthPercentage(sides.left),
1683    )
1684}