Skip to main content

blitz_dom/
document.rs

1use crate::NodeTree;
2use crate::events::{DragMode, ScrollAnimationState, handle_dom_event};
3use crate::font_metrics::BlitzFontMetricsProvider;
4use crate::layout::construct::ConstructionTask;
5use crate::layout::damage::ALL_DAMAGE;
6use crate::mutator::ViewportMut;
7use crate::net::{
8    Resource, ResourceHandler, ResourceLoadResponse, StylesheetHandler, StylesheetLoader,
9};
10use crate::node::{
11    ImageData, NodeFlags, RasterImageData, SpecialElementData, Status, TextBrush, TextGranularity,
12};
13use crate::selection::TextSelection;
14use crate::stylo_to_cursor_icon::stylo_to_cursor_icon;
15use crate::traversal::TreeTraverser;
16use crate::url::DocumentUrl;
17use crate::util::ImageType;
18use crate::{
19    DEFAULT_CSS, DocumentConfig, DocumentMutator, DummyHtmlParserProvider, ElementData,
20    EventDriver, HtmlParserProvider, Node, NodeData, NoopEventHandler, StyleThreading,
21    TextNodeData,
22};
23use blitz_traits::devtools::DevtoolSettings;
24use blitz_traits::events::{BlitzScrollEvent, DomEvent, DomEventData, HitResult, UiEvent};
25use blitz_traits::navigation::{DummyNavigationProvider, NavigationProvider};
26use blitz_traits::net::{AbortSignal, DummyNetProvider, NetProvider, Request};
27use blitz_traits::node_id::NodeId;
28use blitz_traits::shell::{ColorScheme, DummyShellProvider, ShellProvider, Viewport};
29use cursor_icon::CursorIcon;
30use linebender_resource_handle::Blob;
31use markup5ever::{local_name, ns};
32use parley::{FontContext, PlainEditorDriver};
33use selectors::{Element, matching::QuirksMode};
34use smallvec::SmallVec;
35use std::any::Any;
36use std::cell::RefCell;
37use std::collections::{BTreeMap, Bound, HashMap, HashSet};
38use std::ops::{Deref, DerefMut};
39use std::rc::Rc;
40use std::str::FromStr;
41use std::sync::atomic::{AtomicUsize, Ordering};
42use std::sync::mpsc::{Receiver, Sender, channel};
43use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLockReadGuard, RwLockWriteGuard};
44use std::task::{Context as TaskContext, Waker};
45use style::Atom;
46use style::animation::{AnimationState, DocumentAnimationSet};
47use style::attr::{AttrIdentifier, AttrValue};
48use style::data::{ElementData as StyloElementData, ElementStyles};
49use style::media_queries::MediaType;
50use style::properties::ComputedValues;
51use style::properties::style_structs::Font;
52use style::queries::values::PrefersColorScheme;
53use style::selector_parser::ServoElementSnapshot;
54use style::servo::media_features::PointerCapabilities;
55use style::servo_arc::Arc as ServoArc;
56use style::values::GenericAtomIdent;
57use style::values::computed::ui::CursorKind;
58use style::values::computed::{Overflow, UserSelect};
59use style::values::specified::box_::{DisplayInside, DisplayOutside};
60use style::{
61    device::Device,
62    dom::{TDocument, TNode},
63    media_queries::MediaList,
64    selector_parser::SnapshotMap,
65    shared_lock::{SharedRwLock, StylesheetGuards},
66    stylesheets::{AllowImportRules, DocumentStyleSheet, Origin, Stylesheet},
67    stylist::Stylist,
68};
69use thin_vec::ThinVec;
70use url::Url;
71use web_time::Instant;
72
73#[cfg(feature = "parallel-construct")]
74use thread_local::ThreadLocal;
75
76pub enum DocGuard<'a> {
77    Ref(&'a BaseDocument),
78    RefCell(std::cell::Ref<'a, BaseDocument>),
79    RwLock(RwLockReadGuard<'a, BaseDocument>),
80    Mutex(MutexGuard<'a, BaseDocument>),
81}
82
83impl Deref for DocGuard<'_> {
84    type Target = BaseDocument;
85    #[inline(always)]
86    fn deref(&self) -> &Self::Target {
87        match self {
88            Self::Ref(base_document) => base_document,
89            Self::RefCell(refcell_guard) => refcell_guard,
90            Self::RwLock(rw_lock_read_guard) => rw_lock_read_guard,
91            Self::Mutex(mutex_guard) => mutex_guard,
92        }
93    }
94}
95
96pub enum DocGuardMut<'a> {
97    Ref(&'a mut BaseDocument),
98    RefCell(std::cell::RefMut<'a, BaseDocument>),
99    RwLock(RwLockWriteGuard<'a, BaseDocument>),
100    Mutex(MutexGuard<'a, BaseDocument>),
101}
102
103impl Deref for DocGuardMut<'_> {
104    type Target = BaseDocument;
105    #[inline(always)]
106    fn deref(&self) -> &Self::Target {
107        match self {
108            Self::Ref(base_document) => base_document,
109            Self::RefCell(refcell_guard) => refcell_guard,
110            Self::RwLock(rw_lock_read_guard) => rw_lock_read_guard,
111            Self::Mutex(mutex_guard) => mutex_guard,
112        }
113    }
114}
115
116impl DerefMut for DocGuardMut<'_> {
117    #[inline(always)]
118    fn deref_mut(&mut self) -> &mut Self::Target {
119        match self {
120            Self::Ref(base_document) => base_document,
121            Self::RefCell(refcell_guard) => &mut *refcell_guard,
122            Self::RwLock(rw_lock_read_guard) => &mut *rw_lock_read_guard,
123            Self::Mutex(mutex_guard) => &mut *mutex_guard,
124        }
125    }
126}
127
128/// Abstraction over wrappers around [`BaseDocument`] to allow for them all to
129/// be driven by [`blitz-shell`](https://docs.rs/blitz-shell)
130pub trait Document: Any + 'static {
131    fn inner(&self) -> DocGuard<'_>;
132    fn inner_mut(&mut self) -> DocGuardMut<'_>;
133
134    /// Update the [`Document`] in response to a [`UiEvent`] (click, keypress, etc)
135    fn handle_ui_event(&mut self, event: UiEvent) {
136        let mut doc = self.inner_mut();
137        let mut driver = EventDriver::new(&mut *doc, NoopEventHandler);
138        driver.handle_ui_event(event);
139    }
140
141    /// Poll any pending async operations, and flush changes to the underlying [`BaseDocument`]
142    fn poll(&mut self, task_context: Option<TaskContext>) -> bool {
143        // Default implementation does nothing
144        let _ = task_context;
145        false
146    }
147
148    /// Get the [`Document`]'s id
149    fn id(&self) -> usize {
150        self.inner().id
151    }
152}
153
154pub struct PlainDocument(pub BaseDocument);
155impl Document for PlainDocument {
156    fn inner(&self) -> DocGuard<'_> {
157        DocGuard::Ref(&self.0)
158    }
159    fn inner_mut(&mut self) -> DocGuardMut<'_> {
160        DocGuardMut::Ref(&mut self.0)
161    }
162}
163
164impl Document for BaseDocument {
165    fn inner(&self) -> DocGuard<'_> {
166        DocGuard::Ref(self)
167    }
168    fn inner_mut(&mut self) -> DocGuardMut<'_> {
169        DocGuardMut::Ref(self)
170    }
171}
172
173impl Document for Rc<RefCell<BaseDocument>> {
174    fn inner(&self) -> DocGuard<'_> {
175        DocGuard::RefCell(self.borrow())
176    }
177
178    fn inner_mut(&mut self) -> DocGuardMut<'_> {
179        DocGuardMut::RefCell(self.borrow_mut())
180    }
181}
182
183pub enum DocumentEvent {
184    ResourceLoad(ResourceLoadResponse),
185    /// A navigation originating from within an iframe's sub-document
186    /// (e.g. a link click), to be applied to the iframe identified by `node_id`.
187    NavigateIframe {
188        node_id: NodeId,
189        url: Url,
190    },
191}
192
193/// How urgently a document needs another animation frame.
194#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
195pub enum AnimationPacing {
196    Idle,
197    Caret,
198    SlowCss,
199    Interactive,
200}
201
202pub struct BaseDocument {
203    /// ID of the document
204    id: usize,
205
206    // Config
207    /// Base url for resolving linked resources (stylesheets, images, fonts, etc)
208    pub(crate) url: DocumentUrl,
209    // Devtool settings. Currently used to render debug overlays
210    pub(crate) devtool_settings: DevtoolSettings,
211    // Viewport details such as the dimensions, HiDPI scale, and zoom factor,
212    pub(crate) viewport: Viewport,
213    // Scroll within our viewport
214    pub(crate) viewport_scroll: crate::Point<f64>,
215    /// CSS media type used to evaluate `@media` rules.
216    pub(crate) media_type: MediaType,
217    /// Strategy for Stylo's style traversal during `resolve`.
218    pub(crate) style_threading: StyleThreading,
219    /// Whether incremental layout is enabled for this document.
220    pub(crate) incremental_layout: bool,
221    /// How deeply this document is nested within other documents
222    /// (0 for a root document). Used to limit `<iframe>` nesting depth.
223    pub(crate) subdocument_depth: usize,
224
225    // Events
226    pub(crate) tx: Sender<DocumentEvent>,
227    // rx will always be Some, except temporarily while processing events
228    pub(crate) rx: Option<Receiver<DocumentEvent>>,
229
230    /// A slotmap-backed tree of nodes
231    ///
232    /// We pin the tree to a guarantee to the nodes it creates that the tree is stable in memory.
233    /// There is no way to create the tree - publicly or privately - that would invalidate that invariant.
234    pub(crate) nodes: Box<NodeTree>,
235
236    /// The id of the root node (a Document node)
237    pub(crate) root_node_id: NodeId,
238
239    /// For each `position: fixed` node reparented onto the root element, the
240    /// layout parent it was taken from.
241    ///
242    /// Hoisting gives a fixed node the viewport as its containing block, which
243    /// is what CSS asks for. It must not also decide which stacking context the
244    /// node paints in: that follows the box tree, and the two are independent.
245    /// Without this record the node joins the root's stacking context, so a
246    /// negative z-index fixed layer inside an `isolation: isolate` ancestor
247    /// paints beneath every background between them and disappears.
248    pub(crate) hoisted_fixed_parents: HashMap<NodeId, NodeId>,
249
250    /// Stacking contexts holding a hoisted child that an ancestor clips.
251    ///
252    /// Collected while flushing styles so that `resolve_hoisted_clips` visits
253    /// those contexts alone, rather than scanning every node in the document
254    /// after every layout to find the handful that hoist anything at all.
255    pub(crate) hoisted_clip_hosts: Vec<NodeId>,
256
257    // Stylo
258    /// The Stylo engine
259    pub(crate) stylist: Stylist,
260    pub(crate) animations: DocumentAnimationSet,
261    /// Stylo shared lock
262    pub(crate) guard: SharedRwLock,
263    /// Stylo invalidation map. We insert into this map prior to mutating nodes.
264    pub(crate) snapshots: SnapshotMap,
265
266    // Parley contexts
267    /// A Parley font context
268    pub(crate) font_ctx: Arc<Mutex<parley::FontContext>>,
269    #[cfg(feature = "parallel-construct")]
270    /// Thread-and-document-local copies to the font context
271    pub(crate) thread_font_contexts: ThreadLocal<RefCell<Box<FontContext>>>,
272    /// A Parley layout context
273    pub(crate) layout_ctx: parley::LayoutContext<TextBrush>,
274
275    /// The real (non-anonymous) node which is currently hovered (if any).
276    /// This is never a layout-generated (anonymous) node, so it remains valid
277    /// across box-tree reconstruction.
278    pub(crate) hover_node_id: Option<NodeId>,
279    /// The precise (may be anonymous) layout node under the pointer (if any).
280    /// This can be invalidated by box-tree reconstruction, and is re-resolved against
281    /// fresh layout at the end of every `resolve` pass.
282    pub(crate) hover_hit_node_id: Option<NodeId>,
283    /// Whether the node which is currently hovered is a text node/span
284    pub(crate) hover_node_is_text: bool,
285    /// The last known pointer position in client coordinates (viewport-relative, unscrolled).
286    pub(crate) last_client_pointer_position: Option<taffy::Point<f32>>,
287    /// The node which is currently focussed (if any)
288    pub(crate) focus_node_id: Option<NodeId>,
289    /// The node which is currently active (if any)
290    pub(crate) active_node_id: Option<NodeId>,
291    /// The node which recieved a mousedown event (if any)
292    pub(crate) mousedown_node_id: Option<NodeId>,
293    /// The last time a mousedown was made (for double-click detection)
294    pub(crate) last_mousedown_time: Option<Instant>,
295    /// The position where mousedown occurred (for selection drags and double-click detection)
296    pub(crate) mousedown_position: taffy::Point<f32>,
297    /// How many clicks have been made in quick succession
298    pub(crate) click_count: u16,
299    /// Whether we're currently in a text selection drag (moved 2px+ from mousedown)
300    pub(crate) drag_mode: DragMode,
301    /// The scrollbar thumb currently under the pointer, if any
302    pub(crate) hovered_scrollbar: Option<crate::node::ScrollbarRef>,
303    /// When each scroll container's overlay scrollbars were last shown
304    /// (scrolled, or the pointer left the thumb); drives their fade-out
305    pub(crate) scrollbar_activity: HashMap<NodeId, Instant>,
306    /// Whether and what kind of scroll animation is currently in progress
307    pub(crate) scroll_animation: ScrollAnimationState,
308
309    /// Text selection state (for non-input text)
310    pub(crate) text_selection: TextSelection,
311
312    // TODO: collapse animating state into a bitflags
313    /// Whether there are active CSS animations/transitions (so we should re-render every frame)
314    pub(crate) has_active_animations: bool,
315    /// Whether there is a `<canvas>` element in the DOM (so we should re-render every frame)
316    pub(crate) has_canvas: bool,
317    /// The most urgent animation cadence required by any subdocument.
318    pub(crate) subdoc_animation_pacing: AnimationPacing,
319
320    /// Map of id attribute values to node IDs for fast lookups.
321    /// May contain multiple nodes for the same id: `get_element_by_id`
322    /// returns the first in tree order.
323    pub(crate) nodes_to_id: HashMap<String, SmallVec<[NodeId; 1]>>,
324    /// Map of `<style>` and `<link>` node IDs to their associated stylesheet
325    pub(crate) nodes_to_stylesheet: BTreeMap<NodeId, DocumentStyleSheet>,
326    /// Stylesheets added by the useragent
327    /// where the key is the hashed CSS
328    pub(crate) ua_stylesheets: HashMap<String, DocumentStyleSheet>,
329    /// Map from form control node ID's to their associated forms node ID's
330    pub(crate) controls_to_form: HashMap<NodeId, NodeId>,
331    /// Nodes that contain sub documents
332    pub(crate) sub_document_nodes: HashSet<NodeId>,
333    /// Load state (abort controller and in-flight request id) for each
334    /// `<iframe>` element whose sub-document is loaded automatically
335    pub(crate) iframe_loads: HashMap<NodeId, crate::iframe::IframeLoad>,
336    /// Set of changed nodes for updating the accessibility tree
337    pub(crate) changed_nodes: HashSet<NodeId>,
338    /// Set of changed nodes for updating the accessibility tree
339    pub(crate) deferred_construction_nodes: Vec<ConstructionTask>,
340    /// Which parts of the document differ from the previously painted frame.
341    ///
342    /// Off unless a consumer asks for it, so a document that never questions
343    /// its own frames does not pay to answer. See
344    /// [`set_paint_damage_tracking`](Self::set_paint_damage_tracking).
345    pub(crate) paint_damage: crate::paint_damage::PaintDamageTracker,
346
347    /// Nodes that contain custom widgets
348    #[cfg(feature = "custom-widget")]
349    pub(crate) custom_widget_nodes: HashSet<NodeId>,
350    /// Rendering resources allocated by custom widgets that should be deallocated during the next render
351    #[cfg(feature = "custom-widget")]
352    pub(crate) pending_resource_deallocations: Vec<anyrender::ResourceId>,
353
354    /// Registry of custom element definitions keyed by tag name
355    #[cfg(feature = "shadow-dom")]
356    pub(crate) custom_element_registry: crate::node::CustomElementRegistry,
357    /// Nodes that are shadow hosts (have an attached shadow root)
358    #[cfg(feature = "shadow-dom")]
359    pub(crate) shadow_host_nodes: HashSet<NodeId>,
360    /// Nodes that have an attached custom element controller
361    #[cfg(feature = "shadow-dom")]
362    pub(crate) custom_element_nodes: HashSet<NodeId>,
363
364    /// Cache of loaded images, keyed by URL. Allows reusing images across multiple
365    /// elements without re-fetching from the network.
366    pub(crate) image_cache: HashMap<String, ImageData>,
367
368    /// Tracks in-flight image requests. When an image is being fetched, additional
369    /// requests for the same URL are queued here instead of starting new fetches.
370    /// Value is a list of (node_id, image_type) pairs waiting for the image.
371    pub(crate) pending_images: HashMap<String, Vec<(NodeId, ImageType)>>,
372
373    // Tracks in-flight "critical" resources (e.g. stylesheets linked from the `<head>`),
374    // keyed by request id
375    pub(crate) pending_critical_resources: HashSet<usize>,
376
377    // Service providers
378    /// Network provider. Can be used to fetch assets.
379    pub net_provider: Arc<dyn NetProvider>,
380    /// Navigation provider. Can be used to navigate to a new page (bubbles up the event
381    /// on e.g. clicking a Link)
382    pub navigation_provider: Arc<dyn NavigationProvider>,
383    /// Shell provider. Can be used to request a redraw or set the cursor icon
384    pub shell_provider: Arc<dyn ShellProvider>,
385    /// HTML parser provider. Used to parse HTML for setInnerHTML
386    pub html_parser_provider: Arc<dyn HtmlParserProvider>,
387    /// Carried on every sub-resource `Request` this document issues; aborting
388    /// it cancels all in-flight fetches tied to this document. Set via
389    /// [`DocumentConfig::abort_signal`].
390    pub(crate) abort_signal: Option<AbortSignal>,
391}
392
393pub(crate) fn make_device(
394    viewport: &Viewport,
395    media_type: MediaType,
396    font_ctx: Arc<Mutex<FontContext>>,
397) -> Device {
398    let width = viewport.window_size.0 as f32 / viewport.scale();
399    let height = viewport.window_size.1 as f32 / viewport.scale();
400    let viewport_size = euclid::Size2D::new(width, height);
401    let device_size = euclid::Size2D::new(width, height) * viewport.scale();
402    let device_pixel_ratio = euclid::Scale::new(viewport.scale());
403
404    Device::new(
405        media_type,
406        selectors::matching::QuirksMode::NoQuirks,
407        viewport_size,
408        device_size,
409        device_pixel_ratio,
410        Box::new(BlitzFontMetricsProvider { font_ctx }),
411        ComputedValues::initial_values_with_font_override(Font::initial_values()),
412        match viewport.color_scheme {
413            ColorScheme::Light => PrefersColorScheme::Light,
414            ColorScheme::Dark => PrefersColorScheme::Dark,
415        },
416        PointerCapabilities::default(),
417        PointerCapabilities::default(),
418    )
419}
420
421/// Whether layout reuses its caches, and how that can be overridden at runtime.
422///
423/// Incremental layout is on unless a caller or the environment turns it off.
424///
425/// The environment override exists so a single build can be measured both ways:
426/// with it off every `resolve` clears the Taffy cache and re-shapes every inline
427/// root from scratch, so comparing the two in separate binaries would also
428/// compare two different compilations. `BLITZ_INCREMENTAL=0` forces the old
429/// behaviour, `=1` forces the new one.
430///
431/// This used to fall back to `cfg!(feature = "incremental")`. That feature is
432/// gone, replaced by `DocumentConfig::incremental`, and for a while afterwards
433/// this function was never called at all: the config read
434/// `unwrap_or(true)` directly, so `BLITZ_INCREMENTAL` was accepted and ignored.
435fn incremental_layout_default() -> bool {
436    !matches!(
437        std::env::var("BLITZ_INCREMENTAL").ok().as_deref(),
438        Some("0" | "false" | "off")
439    )
440}
441
442impl BaseDocument {
443    /// Create a new (empty) [`BaseDocument`] with the specified configuration
444    pub fn new(config: DocumentConfig) -> Self {
445        static ID_GENERATOR: AtomicUsize = AtomicUsize::new(1);
446
447        let id = ID_GENERATOR.fetch_add(1, Ordering::SeqCst);
448
449        let font_ctx = config
450            .font_ctx
451            .map(|mut font_ctx| {
452                font_ctx.source_cache.make_shared();
453                // font_ctx.collection.make_shared();
454                font_ctx
455            })
456            .unwrap_or_else(|| {
457                use parley::fontique::{Collection, CollectionOptions, SourceCache};
458                let mut font_ctx = FontContext {
459                    source_cache: SourceCache::new_shared(),
460                    collection: Collection::new(CollectionOptions {
461                        shared: false,
462                        system_fonts: cfg!(all(
463                            feature = "system-fonts",
464                            not(target_arch = "wasm32")
465                        )),
466                    }),
467                };
468                font_ctx
469                    .collection
470                    .register_fonts(Blob::new(Arc::new(crate::BULLET_FONT) as _), None);
471                font_ctx
472            });
473        let font_ctx = Arc::new(Mutex::new(font_ctx));
474
475        // Make sure we turn on stylo features *before* creating the Stylist
476        style_config::set_pref!("layout.grid.enabled", true);
477        style_config::set_pref!("layout.unimplemented", true);
478        style_config::set_pref!("layout.columns.enabled", true);
479        style_config::set_pref!("layout.css.basic-shape-shape.enabled", true);
480        style_config::set_pref!("layout.threads", -1);
481
482        let viewport = config.viewport.unwrap_or_default();
483        let media_type = config.media_type.unwrap_or_else(MediaType::screen);
484        let device = make_device(&viewport, media_type.clone(), font_ctx.clone());
485        let stylist = Stylist::new(device, QuirksMode::NoQuirks);
486        let snapshots = SnapshotMap::new();
487        let nodes = Box::new(NodeTree::new());
488        let guard = SharedRwLock::new();
489        let nodes_to_id = HashMap::new();
490
491        let base_url = config
492            .base_url
493            .and_then(|url| DocumentUrl::from_str(&url).ok())
494            .unwrap_or_default();
495
496        let net_provider = config
497            .net_provider
498            .unwrap_or_else(|| Arc::new(DummyNetProvider));
499        let navigation_provider = config
500            .navigation_provider
501            .unwrap_or_else(|| Arc::new(DummyNavigationProvider));
502        let shell_provider = config
503            .shell_provider
504            .unwrap_or_else(|| Arc::new(DummyShellProvider));
505        let html_parser_provider = config
506            .html_parser_provider
507            .unwrap_or_else(|| Arc::new(DummyHtmlParserProvider));
508
509        let (tx, rx) = channel();
510
511        let mut doc = Self {
512            hoisted_fixed_parents: HashMap::new(),
513            hoisted_clip_hosts: Vec::new(),
514            id,
515            tx,
516            rx: Some(rx),
517
518            guard,
519            nodes,
520            root_node_id: NodeId::default(),
521            stylist,
522            animations: DocumentAnimationSet::default(),
523            snapshots,
524            nodes_to_id,
525            viewport,
526            media_type,
527            style_threading: config.style_threading,
528            incremental_layout: config
529                .incremental
530                .unwrap_or_else(incremental_layout_default),
531            subdocument_depth: config.subdocument_depth,
532            devtool_settings: DevtoolSettings::default(),
533            viewport_scroll: crate::Point::ZERO,
534            url: base_url,
535            ua_stylesheets: HashMap::new(),
536            nodes_to_stylesheet: BTreeMap::new(),
537            font_ctx,
538            #[cfg(feature = "parallel-construct")]
539            thread_font_contexts: ThreadLocal::new(),
540            layout_ctx: parley::LayoutContext::new(),
541
542            hover_node_id: None,
543            hover_hit_node_id: None,
544            hover_node_is_text: false,
545            last_client_pointer_position: None,
546            focus_node_id: None,
547            active_node_id: None,
548            mousedown_node_id: None,
549            has_active_animations: false,
550            subdoc_animation_pacing: AnimationPacing::Idle,
551            has_canvas: false,
552            sub_document_nodes: HashSet::new(),
553            iframe_loads: HashMap::new(),
554
555            #[cfg(feature = "custom-widget")]
556            custom_widget_nodes: HashSet::new(),
557            #[cfg(feature = "custom-widget")]
558            pending_resource_deallocations: Vec::new(),
559
560            #[cfg(feature = "shadow-dom")]
561            custom_element_registry: crate::node::CustomElementRegistry::new(),
562            #[cfg(feature = "shadow-dom")]
563            shadow_host_nodes: HashSet::new(),
564            #[cfg(feature = "shadow-dom")]
565            custom_element_nodes: HashSet::new(),
566
567            changed_nodes: HashSet::new(),
568            deferred_construction_nodes: Vec::new(),
569            paint_damage: Default::default(),
570            image_cache: HashMap::new(),
571            pending_images: HashMap::new(),
572            pending_critical_resources: HashSet::new(),
573            controls_to_form: HashMap::new(),
574            net_provider,
575            navigation_provider,
576            shell_provider,
577            html_parser_provider,
578            abort_signal: config.abort_signal,
579            last_mousedown_time: None,
580            mousedown_position: taffy::Point::ZERO,
581            click_count: 0,
582            drag_mode: DragMode::None,
583            hovered_scrollbar: None,
584            scrollbar_activity: HashMap::new(),
585            scroll_animation: ScrollAnimationState::None,
586            text_selection: TextSelection::default(),
587        };
588
589        // Initialise document with root Document node
590        doc.root_node_id = doc.create_node(NodeData::Document(Box::default()));
591        doc.root_node_mut().flags.insert(NodeFlags::IS_IN_DOCUMENT);
592
593        match config.ua_stylesheets {
594            Some(stylesheets) => {
595                for ss in &stylesheets {
596                    doc.add_user_agent_stylesheet(ss);
597                }
598            }
599            None => doc.add_user_agent_stylesheet(DEFAULT_CSS),
600        }
601
602        // Stylo data on the root node container is needed to render the node
603        let stylo_element_data = StyloElementData {
604            styles: ElementStyles {
605                primary: Some(
606                    ComputedValues::initial_values_with_font_override(Font::initial_values())
607                        .to_arc(),
608                ),
609                ..Default::default()
610            },
611            ..Default::default()
612        };
613        let stylo_data = doc.root_node_mut().stylo_element_data_mut();
614        *stylo_data.ensure_init_mut() = stylo_element_data;
615
616        doc
617    }
618
619    /// Set the Document's networking provider
620    pub fn set_net_provider(&mut self, net_provider: Arc<dyn NetProvider>) {
621        self.net_provider = net_provider;
622    }
623
624    /// Set the Document's navigation provider
625    pub fn set_navigation_provider(&mut self, navigation_provider: Arc<dyn NavigationProvider>) {
626        self.navigation_provider = navigation_provider;
627    }
628
629    /// Set the Document's shell provider
630    pub fn set_shell_provider(&mut self, shell_provider: Arc<dyn ShellProvider>) {
631        self.shell_provider = shell_provider;
632    }
633
634    /// Set the Document's html parser provider
635    pub fn set_html_parser_provider(&mut self, html_parser_provider: Arc<dyn HtmlParserProvider>) {
636        self.html_parser_provider = html_parser_provider;
637    }
638
639    /// Set base url for resolving linked resources (stylesheets, images, fonts, etc)
640    pub fn set_base_url(&mut self, url: &str) {
641        self.url = DocumentUrl::from(Url::parse(url).unwrap());
642    }
643
644    pub fn guard(&self) -> &SharedRwLock {
645        &self.guard
646    }
647
648    pub fn tree(&self) -> &NodeTree {
649        &self.nodes
650    }
651
652    pub fn id(&self) -> usize {
653        self.id
654    }
655
656    /// Wrapper around [`crate::net::stamped_request`]. Use the free function
657    /// when `&self` would conflict with a held `&mut` borrow on a field.
658    pub(crate) fn build_request(&self, url: url::Url) -> Request {
659        crate::net::stamped_request(url, self.abort_signal.as_ref())
660    }
661
662    pub fn favicon_url(&self) -> Option<String> {
663        self.tree().iter().find_map(|(_, node)| {
664            let data = &node.data;
665            if !data.is_element_with_tag_name(&local_name!("link")) {
666                return None;
667            }
668            let rel = data.attr(local_name!("rel"))?;
669            if !rel
670                .split_ascii_whitespace()
671                .any(|v| v.eq_ignore_ascii_case("icon"))
672            {
673                return None;
674            }
675            data.attr(local_name!("href")).map(|s| s.to_string())
676        })
677    }
678
679    pub fn get_node(&self, node_id: NodeId) -> Option<&Node> {
680        self.nodes.get(node_id)
681    }
682
683    pub fn get_node_mut(&mut self, node_id: NodeId) -> Option<&mut Node> {
684        self.nodes.get_mut(node_id)
685    }
686
687    pub fn get_focussed_node_id(&self) -> Option<NodeId> {
688        self.focus_node_id
689            .or(self.try_root_element().map(|el| el.id))
690    }
691
692    pub fn mutate<'doc>(&'doc mut self) -> DocumentMutator<'doc> {
693        DocumentMutator::new(self)
694    }
695
696    pub fn handle_dom_event<F: FnMut(DomEvent)>(
697        &mut self,
698        event: &mut DomEvent,
699        dispatch_event: F,
700    ) {
701        handle_dom_event(self, event, dispatch_event)
702    }
703
704    pub fn as_any_mut(&mut self) -> &mut dyn Any {
705        self
706    }
707
708    /// Find the label's bound input elements:
709    /// the element id referenced by the "for" attribute of a given label element
710    /// or the first input element which is nested in the label
711    /// Note that although there should only be one bound element,
712    /// we return all possibilities instead of just the first
713    /// in order to allow the caller to decide which one is correct
714    pub fn label_bound_input_element(&self, label_node_id: NodeId) -> Option<&Node> {
715        let label_element = self.nodes[label_node_id].element_data()?;
716        if let Some(target_element_dom_id) = label_element.attr(local_name!("for")) {
717            TreeTraverser::new(self)
718                .filter_map(|id| {
719                    let node = self.get_node(id)?;
720                    let element_data = node.element_data()?;
721                    if element_data.name.local != local_name!("input") {
722                        return None;
723                    }
724                    let id = element_data.id.as_ref()?;
725                    if *id == *target_element_dom_id {
726                        Some(node)
727                    } else {
728                        None
729                    }
730                })
731                .next()
732        } else {
733            TreeTraverser::new_with_root(self, label_node_id)
734                .filter_map(|child_id| {
735                    let node = self.get_node(child_id)?;
736                    let element_data = node.element_data()?;
737                    if element_data.name.local == local_name!("input") {
738                        Some(node)
739                    } else {
740                        None
741                    }
742                })
743                .next()
744        }
745    }
746
747    pub fn toggle_checkbox(el: &mut ElementData) -> bool {
748        let Some(is_checked) = el.checkbox_input_checked_mut() else {
749            return false;
750        };
751        *is_checked = !*is_checked;
752
753        *is_checked
754    }
755
756    pub fn toggle_radio(&mut self, radio_set_name: String, target_radio_id: NodeId) {
757        for (i, node) in self.nodes.iter_mut() {
758            if let Some(node_data) = node.data.downcast_element_mut() {
759                if node_data.attr(local_name!("name")) == Some(&radio_set_name) {
760                    let was_clicked = i == target_radio_id;
761                    let Some(is_checked) = node_data.checkbox_input_checked_mut() else {
762                        continue;
763                    };
764                    *is_checked = was_clicked;
765                }
766            }
767        }
768    }
769
770    /// Toggle the `open` attribute of a `<details>` element, expanding or
771    /// collapsing it. This is the default action triggered when the element's
772    /// first `<summary>` child is activated.
773    pub fn toggle_details_open(&mut self, details_id: NodeId) {
774        use crate::qual_name;
775
776        let node = &self.nodes[details_id];
777        if !node.data.is_element_with_tag_name(&local_name!("details")) {
778            return;
779        }
780        let is_open = node.data.has_attr(local_name!("open"));
781
782        // Note: HTML attributes are in the empty (null) namespace, so the
783        // QualName must not use the html namespace here, else it won't match
784        // an `open` attribute created by the HTML parser.
785        let mut mutator = self.mutate();
786        if is_open {
787            mutator.clear_attribute(details_id, qual_name!("open"));
788        } else {
789            mutator.set_attribute(details_id, qual_name!("open"), "");
790        }
791        drop(mutator);
792
793        self.shell_provider.request_redraw();
794    }
795
796    pub fn set_style_property(&mut self, node_id: NodeId, name: &str, value: &str) {
797        let node = &mut self.nodes[node_id];
798        let did_change = node.element_data_mut().unwrap().set_style_property(
799            name,
800            value,
801            &self.guard,
802            self.url.url_extra_data(),
803        );
804        if did_change {
805            node.mark_style_attr_updated();
806        }
807    }
808
809    pub fn remove_style_property(&mut self, node_id: NodeId, name: &str) {
810        let node = &mut self.nodes[node_id];
811        let did_change = node.element_data_mut().unwrap().remove_style_property(
812            name,
813            &self.guard,
814            self.url.url_extra_data(),
815        );
816        if did_change {
817            node.mark_style_attr_updated();
818        }
819    }
820
821    pub fn sub_document_node_ids(&self) -> Vec<NodeId> {
822        self.sub_document_nodes.iter().copied().collect()
823    }
824
825    pub fn set_sub_document(&mut self, node_id: NodeId, sub_document: Box<dyn Document>) {
826        self.nodes[node_id]
827            .element_data_mut()
828            .unwrap()
829            .set_sub_document(sub_document);
830        self.sub_document_nodes.insert(node_id);
831    }
832
833    pub fn remove_sub_document(&mut self, node_id: NodeId) {
834        self.nodes[node_id]
835            .element_data_mut()
836            .unwrap()
837            .remove_sub_document();
838        self.sub_document_nodes.remove(&node_id);
839        if let Some(load) = self.iframe_loads.remove(&node_id) {
840            load.abort_controller.abort();
841        }
842    }
843
844    /// Poll all sub-documents (see [`Document::poll`]), allowing them to make progress
845    /// on any pending async operations (e.g. JavaScript timers). Hosts which poll a
846    /// wrapper around a [`BaseDocument`] should call this from their `poll` implementation.
847    ///
848    /// Returns `true` if any sub-document reported changes.
849    pub fn poll_subdocuments(&mut self, waker: Option<&Waker>) -> bool {
850        let mut has_changes = false;
851        let node_ids: Vec<NodeId> = self.sub_document_nodes.iter().copied().collect();
852        for node_id in node_ids {
853            let Some(sub_doc) = self
854                .nodes
855                .get_mut(node_id)
856                .and_then(|node| node.subdoc_mut())
857            else {
858                continue;
859            };
860            let task_context = waker.map(TaskContext::from_waker);
861            has_changes |= sub_doc.poll(task_context);
862        }
863        has_changes
864    }
865
866    #[cfg(feature = "custom-widget")]
867    pub fn custom_widget_node_ids(&self) -> Vec<NodeId> {
868        self.custom_widget_nodes.iter().copied().collect()
869    }
870
871    #[cfg(feature = "custom-widget")]
872    pub fn take_pending_resource_deallocations(&mut self) -> Vec<anyrender::ResourceId> {
873        std::mem::take(&mut self.pending_resource_deallocations)
874    }
875
876    #[cfg(feature = "custom-widget")]
877    pub fn set_custom_widget(&mut self, node_id: NodeId, widget: Box<dyn crate::Widget>) {
878        self.nodes[node_id]
879            .element_data_mut()
880            .unwrap()
881            .set_custom_widget(widget);
882        self.custom_widget_nodes.insert(node_id);
883    }
884
885    #[cfg(feature = "custom-widget")]
886    pub fn remove_custom_widget(&mut self, node_id: NodeId) {
887        let resources_to_deallocate = self.nodes[node_id]
888            .element_data_mut()
889            .unwrap()
890            .remove_custom_widget();
891        self.pending_resource_deallocations
892            .extend_from_slice(&resources_to_deallocate);
893        self.custom_widget_nodes.remove(&node_id);
894    }
895
896    /// Mutable access to the custom element registry. Use
897    /// [`CustomElementRegistry::define`](crate::node::CustomElementRegistry::define)
898    /// to register custom elements by tag name.
899    #[cfg(feature = "shadow-dom")]
900    pub fn custom_elements_mut(&mut self) -> &mut crate::node::CustomElementRegistry {
901        &mut self.custom_element_registry
902    }
903
904    /// Register a custom element definition against a tag name (analogous to
905    /// `customElements.define`).
906    #[cfg(feature = "shadow-dom")]
907    pub fn define_custom_element(
908        &mut self,
909        name: markup5ever::LocalName,
910        definition: crate::node::CustomElementDefinition,
911    ) {
912        self.custom_element_registry.define(name, definition);
913    }
914
915    /// The node ids of all shadow hosts in the document.
916    #[cfg(feature = "shadow-dom")]
917    pub fn shadow_host_node_ids(&self) -> Vec<NodeId> {
918        self.shadow_host_nodes.iter().copied().collect()
919    }
920
921    /// If `host_id` is a shadow host, returns the node id of its shadow root.
922    #[cfg(feature = "shadow-dom")]
923    pub fn shadow_root_id(&self, host_id: NodeId) -> Option<NodeId> {
924        self.get_node(host_id)
925            .and_then(|node| node.shadow_root_id())
926    }
927
928    /// Attach a shadow root to the given host element, returning the node id of
929    /// the newly-created shadow root. If the host already has a shadow root, its
930    /// existing shadow root id is returned unchanged.
931    #[cfg(feature = "shadow-dom")]
932    pub fn attach_shadow(&mut self, host_id: NodeId, mode: crate::node::ShadowRootMode) -> NodeId {
933        if let Some(existing) = self.nodes[host_id].shadow_root_id() {
934            return existing;
935        }
936
937        let shadow_root_id = self.create_node(NodeData::ShadowRoot(
938            crate::node::ShadowRootData::new(host_id, mode),
939        ));
940
941        // The shadow root's parent is the host. It is *not* added to the host's
942        // `children` list (which holds light-DOM children); it is referenced via
943        // the host's `ElementData::shadow_root` field instead.
944        self.nodes[shadow_root_id].parent = Some(host_id);
945        if self.nodes[host_id].flags.is_in_document() {
946            self.nodes[shadow_root_id]
947                .flags
948                .insert(NodeFlags::IS_IN_DOCUMENT);
949        }
950
951        self.nodes[host_id]
952            .element_data_mut()
953            .expect("Shadow host must be an element")
954            .shadow_root = Some(shadow_root_id);
955        self.shadow_host_nodes.insert(host_id);
956
957        // Host needs its box tree rebuilt to account for the shadow tree.
958        self.nodes[host_id].insert_damage(ALL_DAMAGE);
959        self.nodes[host_id].mark_ancestors_dirty();
960
961        shadow_root_id
962    }
963
964    /// Detach (and drop) the shadow root of the given host element, if any.
965    #[cfg(feature = "shadow-dom")]
966    pub fn detach_shadow(&mut self, host_id: NodeId) {
967        let shadow_root_id = self.nodes[host_id]
968            .element_data_mut()
969            .and_then(|el| el.shadow_root.take());
970        if let Some(shadow_root_id) = shadow_root_id {
971            self.drop_node_ignoring_parent(shadow_root_id);
972            self.shadow_host_nodes.remove(&host_id);
973            self.nodes[host_id].insert_damage(ALL_DAMAGE);
974            self.nodes[host_id].mark_ancestors_dirty();
975        }
976    }
977
978    /// Attach a custom element controller to the given node.
979    #[cfg(feature = "shadow-dom")]
980    pub fn set_custom_element(
981        &mut self,
982        node_id: NodeId,
983        controller: Box<dyn crate::node::CustomElement>,
984    ) {
985        use crate::node::{CustomElementData, SpecialElementData};
986        self.nodes[node_id]
987            .element_data_mut()
988            .expect("Custom element host must be an element")
989            .special_data = SpecialElementData::CustomElement(CustomElementData::new(controller));
990        self.custom_element_nodes.insert(node_id);
991    }
992
993    /// Detach the custom element controller from the given node (without running
994    /// the `disconnected` callback). Returns the controller if present.
995    #[cfg(feature = "shadow-dom")]
996    pub fn take_custom_element(
997        &mut self,
998        node_id: NodeId,
999    ) -> Option<Box<dyn crate::node::CustomElement>> {
1000        use crate::node::SpecialElementData;
1001        self.custom_element_nodes.remove(&node_id);
1002        let element = self.nodes[node_id].element_data_mut()?;
1003        if matches!(element.special_data, SpecialElementData::CustomElement(_)) {
1004            if let SpecialElementData::CustomElement(mut data) = element.special_data.take() {
1005                return data.controller.take();
1006            }
1007        }
1008        None
1009    }
1010
1011    pub fn root_node(&self) -> &Node {
1012        &self.nodes[self.root_node_id]
1013    }
1014
1015    pub fn root_node_mut(&mut self) -> &mut Node {
1016        &mut self.nodes[self.root_node_id]
1017    }
1018
1019    /// Ask this document to work out which regions differ between frames.
1020    ///
1021    /// Off by default. A consumer that turns it on is charged one pass over the
1022    /// node list per [`resolve`](Self::resolve) - a pass `resolve` already makes
1023    /// to clear damage - plus a hash lookup and a rectangle comparison per node.
1024    /// Nothing else in the document reads the result, so leaving it off costs a
1025    /// single branch.
1026    ///
1027    /// The consumer this exists for is a `backdrop-filter` cache. Blurring what
1028    /// is behind an element costs a render pass and a filter every frame, and
1029    /// the only way that stops being permanent is to skip the elements whose
1030    /// input has not changed. Turning this on is what makes that question
1031    /// answerable.
1032    ///
1033    /// The first frame after enabling reports everything as changed, because
1034    /// there is no previous frame to compare against.
1035    pub fn set_paint_damage_tracking(&mut self, enabled: bool) {
1036        self.paint_damage.set_enabled(enabled);
1037    }
1038
1039    /// Whether [`set_paint_damage_tracking`](Self::set_paint_damage_tracking) is on.
1040    pub fn paint_damage_tracking(&self) -> bool {
1041        self.paint_damage.is_enabled()
1042    }
1043
1044    /// What changed since the previously resolved frame.
1045    ///
1046    /// Empty when tracking is off, which is indistinguishable from "nothing
1047    /// changed" and deliberately so: a consumer that has not asked for the
1048    /// question to be answered must not read the empty answer as a licence to
1049    /// reuse a cache. Check
1050    /// [`paint_damage_tracking`](Self::paint_damage_tracking) first.
1051    pub fn paint_damage(&self) -> &crate::paint_damage::PaintDamage {
1052        self.paint_damage.damage()
1053    }
1054
1055    pub fn try_root_element(&self) -> Option<&Node> {
1056        TDocument::as_node(&self.root_node()).first_element_child()
1057    }
1058
1059    pub fn root_element(&self) -> &Node {
1060        TDocument::as_node(&self.root_node())
1061            .first_element_child()
1062            .unwrap()
1063            .as_element()
1064            .unwrap()
1065    }
1066
1067    pub fn create_node(&mut self, node_data: NodeData) -> NodeId {
1068        let tree_ptr = self.nodes.as_mut() as *mut NodeTree;
1069        let guard = self.guard.clone();
1070
1071        let id = self
1072            .nodes
1073            .insert_with_key(|id| Node::new(tree_ptr, id, guard, node_data));
1074
1075        // Mark the new node as changed.
1076        self.changed_nodes.insert(id);
1077        id
1078    }
1079
1080    /// Remove a node from the node tree, clearing any interaction state
1081    /// (hover/active/focus/mousedown/selection/drag/scrollbar) that references
1082    /// it so that stale NodeIds are never dereferenced after the slot is freed.
1083    pub(crate) fn remove_node_from_tree(&mut self, node_id: NodeId) -> Option<Node> {
1084        self.clear_interaction_state_for_removed_node(node_id);
1085        self.nodes.remove(node_id)
1086    }
1087
1088    /// The nearest element ancestor of `node_id` that is still in the
1089    /// document. Used to retarget hover/active state when the node they
1090    /// reference is removed. Tolerates already-removed ancestors (subtree
1091    /// teardown proceeds root-first) by giving up and returning `None`.
1092    fn nearest_surviving_element_ancestor(&self, node_id: NodeId) -> Option<NodeId> {
1093        let mut current = self.get_node(node_id)?.parent;
1094        while let Some(id) = current {
1095            let node = self.get_node(id)?;
1096            if node.is_element() && node.flags.is_in_document() {
1097                return Some(id);
1098            }
1099            current = node.parent;
1100        }
1101        None
1102    }
1103
1104    /// Clear any interaction state (hover/active/focus/mousedown/selection/
1105    /// drag/scrollbar) that references `node_id`, which is being removed from
1106    /// the document, running the usual teardown steps. `node_id` must still be
1107    /// present in the slab.
1108    ///
1109    /// This matches browser semantics (WebKit `hoveredElementDidDetach` /
1110    /// `elementInActiveChainDidDetach`, Blink `HoveredElementDetached` /
1111    /// `ActiveChainNodeDetached`):
1112    /// - Hover and active retarget to the nearest surviving element ancestor
1113    ///   as a *transient bridge*: the HOVER/ACTIVE element-state bits along
1114    ///   the surviving chain stay lit (no one-frame gap in `:hover`/`:active`
1115    ///   styling), and the subsequent hover diff can unset exactly the right
1116    ///   bits. Hover is then re-resolved against the pointer position by
1117    ///   [`Self::refresh_hover`] at the end of the next resolve pass (the
1118    ///   analogue of WebKit's "fake mouse move"), which corrects the bridge
1119    ///   value — including cases where the removed node overflowed its
1120    ///   ancestor's box, so the ancestor was never truly under the pointer.
1121    /// - Focus resets to the body (encoded as `None`), running blur
1122    ///   side-effects (clearing focus element state and disabling IME for
1123    ///   text inputs).
1124    pub(crate) fn clear_interaction_state_for_removed_node(&mut self, node_id: NodeId) {
1125        if !self.nodes.contains_key(node_id) {
1126            return;
1127        }
1128
1129        if self.hover_node_id == Some(node_id) {
1130            self.hover_node_id = self.nearest_surviving_element_ancestor(node_id);
1131            self.hover_node_is_text = false;
1132        }
1133        if self.hover_hit_node_id == Some(node_id) {
1134            self.hover_hit_node_id = None;
1135        }
1136        if self.active_node_id == Some(node_id) {
1137            self.active_node_id = self.nearest_surviving_element_ancestor(node_id);
1138        }
1139        if self.focus_node_id == Some(node_id) {
1140            let shell_provider = self.shell_provider.clone();
1141            self.nodes[node_id].blur(shell_provider);
1142            self.focus_node_id = None;
1143        }
1144        if self.mousedown_node_id == Some(node_id) {
1145            self.mousedown_node_id = None;
1146        }
1147        if self.text_selection.anchor.node_or_parent == Some(node_id)
1148            || self.text_selection.focus.node_or_parent == Some(node_id)
1149        {
1150            self.text_selection.clear();
1151        }
1152        if self
1153            .hovered_scrollbar
1154            .is_some_and(|scrollbar| scrollbar.node_id == node_id)
1155        {
1156            self.hovered_scrollbar = None;
1157        }
1158        let drag_references_node = match &self.drag_mode {
1159            DragMode::Panning(state) => state.target == node_id,
1160            DragMode::ScrollbarDrag(state) => state.scrollbar.node_id == node_id,
1161            DragMode::Selecting | DragMode::None => false,
1162        };
1163        if drag_references_node {
1164            self.drag_mode = DragMode::None;
1165        }
1166        self.scrollbar_activity.remove(&node_id);
1167    }
1168
1169    pub(crate) fn drop_node_ignoring_parent(&mut self, node_id: NodeId) -> Option<Node> {
1170        self.drop_node_ignoring_parent_with(node_id, &mut |_| {})
1171    }
1172
1173    /// Like [`Self::drop_node_ignoring_parent`], but calls `on_drop` with the id of
1174    /// every dropped node (the node itself and all of its descendants).
1175    pub(crate) fn drop_node_ignoring_parent_with(
1176        &mut self,
1177        node_id: NodeId,
1178        on_drop: &mut dyn FnMut(NodeId),
1179    ) -> Option<Node> {
1180        let mut node = self.remove_node_from_tree(node_id);
1181        if let Some(node) = &mut node {
1182            on_drop(node_id);
1183            if let Some(before) = node.before() {
1184                self.drop_node_ignoring_parent_with(before, on_drop);
1185            }
1186            if let Some(after) = node.after() {
1187                self.drop_node_ignoring_parent_with(after, on_drop);
1188            }
1189
1190            for &child in &node.children {
1191                self.drop_node_ignoring_parent_with(child, on_drop);
1192            }
1193
1194            // Anonymous blocks live only in the slab, so deallocate the ones this
1195            // node owns rather than leaking them.
1196            for &anon_id in &node.anonymous_blocks {
1197                self.deallocate_anonymous_block(anon_id);
1198            }
1199
1200            // Drop any attached shadow root (its children are dropped recursively
1201            // via the recursive call below).
1202            #[cfg(feature = "shadow-dom")]
1203            if let Some(shadow_root_id) = node.shadow_root_id() {
1204                self.shadow_host_nodes.remove(&node_id);
1205                self.custom_element_nodes.remove(&node_id);
1206                self.drop_node_ignoring_parent(shadow_root_id);
1207            }
1208        }
1209        node
1210    }
1211
1212    /// Deallocate an anonymous block created in a previous construction
1213    /// round, along with any anonymous blocks nested within it.
1214    pub(crate) fn deallocate_anonymous_block(&mut self, anon_id: NodeId) {
1215        // The block may already have been removed from the slab (e.g. a
1216        // whitespace-only anonymous block dropped during construction).
1217        if !self.nodes.contains_key(anon_id) {
1218            return;
1219        }
1220
1221        // Free any anonymous blocks that this block owns before removing it.
1222        let nested = std::mem::take(&mut self.nodes[anon_id].anonymous_blocks);
1223        for nested_id in nested {
1224            self.deallocate_anonymous_block(nested_id);
1225        }
1226
1227        self.remove_node_from_tree(anon_id);
1228    }
1229
1230    /// Whether the document has been mutated
1231    pub fn has_changes(&self) -> bool {
1232        self.changed_nodes.is_empty()
1233    }
1234
1235    pub fn create_text_node(&mut self, text: &str) -> NodeId {
1236        let content = text.to_string();
1237        let data = NodeData::Text(TextNodeData::new(content));
1238        self.create_node(data)
1239    }
1240
1241    pub fn deep_clone_node(&mut self, node_id: NodeId) -> NodeId {
1242        // Load existing node
1243        let node = &self.nodes[node_id];
1244        let mut data = node.data.clone();
1245
1246        match &mut data {
1247            NodeData::Element(elem) | NodeData::AnonymousBlock(elem) => {
1248                if let Some(arc) = elem.style_attribute.as_mut() {
1249                    let read_guard = self.guard().read();
1250                    let block = arc.read_with(&read_guard);
1251                    *arc = ServoArc::new(self.guard().wrap(block.clone()));
1252                }
1253            }
1254            _ => {}
1255        }
1256
1257        let children = node.children.clone();
1258
1259        // Create new node
1260        let new_node_id = self.create_node(data);
1261
1262        // Recursively clone children
1263        let new_children: ThinVec<NodeId> = children
1264            .into_iter()
1265            .map(|child_id| self.deep_clone_node(child_id))
1266            .collect();
1267        for &child_id in &new_children {
1268            self.nodes[child_id].parent = Some(new_node_id);
1269        }
1270        self.nodes[new_node_id].children = new_children;
1271
1272        new_node_id
1273    }
1274
1275    pub(crate) fn remove_and_drop_pe(&mut self, node_id: NodeId) -> Option<Node> {
1276        fn remove_pe_ignoring_parent(doc: &mut BaseDocument, node_id: NodeId) -> Option<Node> {
1277            let mut node = doc.remove_node_from_tree(node_id);
1278            if let Some(node) = &mut node {
1279                for &child in &node.children {
1280                    remove_pe_ignoring_parent(doc, child);
1281                }
1282                for &anon_id in &node.anonymous_blocks {
1283                    doc.deallocate_anonymous_block(anon_id);
1284                }
1285            }
1286            node
1287        }
1288
1289        let node = remove_pe_ignoring_parent(self, node_id);
1290
1291        // Update child_idx values
1292        if let Some(parent_id) = node.as_ref().and_then(|node| node.parent) {
1293            let parent = &mut self.nodes[parent_id];
1294            parent.children.retain(|id| *id != node_id);
1295        }
1296
1297        node
1298    }
1299
1300    pub(crate) fn resolve_url(&self, raw: &str) -> url::Url {
1301        self.url.resolve_relative(raw).unwrap_or_else(|| {
1302            panic!(
1303                "to be able to resolve {raw} with the base_url: {:?}",
1304                *self.url
1305            )
1306        })
1307    }
1308
1309    pub fn print_tree(&self) {
1310        crate::util::walk_tree(0, self.root_node());
1311    }
1312
1313    pub fn print_subtree(&self, node_id: NodeId) {
1314        crate::util::walk_tree(0, &self.nodes[node_id]);
1315    }
1316
1317    pub fn reload_resource_by_href(&mut self, href_to_reload: &str) {
1318        for &node_id in self.nodes_to_stylesheet.keys() {
1319            let node = &self.nodes[node_id];
1320            let Some(element) = node.element_data() else {
1321                continue;
1322            };
1323
1324            if element.name.local == local_name!("link") {
1325                if let Some(href) = element.attr(local_name!("href")) {
1326                    // println!("Node {node_id} {href} {href_to_reload} {} {}", resolved_href.as_str(), resolved_href.as_str() == url_to_reload);
1327                    if href == href_to_reload {
1328                        let resolved_href = self.resolve_url(href);
1329                        self.net_provider.fetch(
1330                            self.id(),
1331                            self.build_request(resolved_href.clone()),
1332                            ResourceHandler::boxed(
1333                                self.tx.clone(),
1334                                self.id,
1335                                Some(node_id),
1336                                self.shell_provider.clone(),
1337                                StylesheetHandler {
1338                                    source_url: resolved_href,
1339                                    guard: self.guard.clone(),
1340                                    net_provider: self.net_provider.clone(),
1341                                    abort_signal: self.abort_signal.clone(),
1342                                },
1343                            ),
1344                        );
1345                    }
1346                }
1347            }
1348        }
1349    }
1350
1351    pub fn process_style_element(&mut self, target_id: NodeId) {
1352        let css = self.nodes[target_id].text_content();
1353        let css = html_escape::decode_html_entities(&css);
1354        let sheet = self.make_stylesheet(&css, Origin::Author);
1355        self.add_stylesheet_for_node(sheet, target_id);
1356    }
1357
1358    pub fn remove_user_agent_stylesheet(&mut self, contents: &str) {
1359        if let Some(sheet) = self.ua_stylesheets.remove(contents) {
1360            self.stylist.remove_stylesheet(sheet, &self.guard.read());
1361        }
1362    }
1363
1364    /// The document's base URL
1365    pub fn url(&self) -> &url::Url {
1366        &self.url
1367    }
1368
1369    /// Iterate over the author stylesheets (from `<style>` and `<link>` nodes)
1370    /// currently associated with this document
1371    pub fn author_stylesheets(&self) -> impl Iterator<Item = &DocumentStyleSheet> {
1372        self.nodes_to_stylesheet.values()
1373    }
1374
1375    /// Iterate over the user-agent stylesheets currently associated with this document
1376    pub fn useragent_stylesheets(&self) -> impl Iterator<Item = &DocumentStyleSheet> {
1377        self.ua_stylesheets.values()
1378    }
1379
1380    pub fn add_user_agent_stylesheet(&mut self, css: &str) {
1381        let sheet = self.make_stylesheet(css, Origin::UserAgent);
1382        self.ua_stylesheets.insert(css.to_string(), sheet.clone());
1383        self.stylist.append_stylesheet(sheet, &self.guard.read());
1384    }
1385
1386    pub fn make_stylesheet(&self, css: impl AsRef<str>, origin: Origin) -> DocumentStyleSheet {
1387        let data = Stylesheet::from_str(
1388            css.as_ref(),
1389            self.url.url_extra_data(),
1390            origin,
1391            ServoArc::new(self.guard.wrap(MediaList::empty())),
1392            self.guard.clone(),
1393            Some(&StylesheetLoader {
1394                tx: self.tx.clone(),
1395                doc_id: self.id,
1396                net_provider: self.net_provider.clone(),
1397                shell_provider: self.shell_provider.clone(),
1398                abort_signal: self.abort_signal.clone(),
1399            }),
1400            None,
1401            QuirksMode::NoQuirks,
1402            AllowImportRules::Yes,
1403        );
1404
1405        DocumentStyleSheet(ServoArc::new(data))
1406    }
1407
1408    pub fn upsert_stylesheet_for_node(&mut self, node_id: NodeId) {
1409        let raw_styles = self.nodes[node_id].text_content();
1410        let sheet = self.make_stylesheet(raw_styles, Origin::Author);
1411        self.add_stylesheet_for_node(sheet, node_id);
1412    }
1413
1414    pub fn add_stylesheet_for_node(&mut self, stylesheet: DocumentStyleSheet, node_id: NodeId) {
1415        let old = self.nodes_to_stylesheet.insert(node_id, stylesheet.clone());
1416
1417        if let Some(old) = old {
1418            self.stylist.remove_stylesheet(old, &self.guard.read())
1419        }
1420
1421        // Fetch @font-face fonts
1422        crate::net::fetch_font_face(
1423            self.tx.clone(),
1424            self.id,
1425            Some(node_id),
1426            &stylesheet.0,
1427            &self.net_provider,
1428            &self.shell_provider,
1429            &self.guard.read(),
1430            self.abort_signal.as_ref(),
1431        );
1432
1433        // Store data on element
1434        let element = &mut self.nodes[node_id].element_data_mut().unwrap();
1435        element.special_data = SpecialElementData::Stylesheet(stylesheet.clone());
1436
1437        // TODO: Nodes could potentially get reused so ordering by node_id might be wrong.
1438        let insertion_point = self
1439            .nodes_to_stylesheet
1440            .range((Bound::Excluded(node_id), Bound::Unbounded))
1441            .next()
1442            .map(|(_, sheet)| sheet);
1443
1444        if let Some(insertion_point) = insertion_point {
1445            self.stylist.insert_stylesheet_before(
1446                stylesheet,
1447                insertion_point.clone(),
1448                &self.guard.read(),
1449            )
1450        } else {
1451            self.stylist
1452                .append_stylesheet(stylesheet, &self.guard.read())
1453        }
1454    }
1455
1456    pub fn handle_messages(&mut self) {
1457        // Remove event Reciever from the Document so that we can process events
1458        // without holding a borrow to the Document
1459        let rx = self.rx.take().unwrap();
1460
1461        while let Ok(msg) = rx.try_recv() {
1462            self.handle_message(msg);
1463        }
1464
1465        // Put Reciever back
1466        self.rx = Some(rx);
1467    }
1468
1469    pub fn handle_message(&mut self, msg: DocumentEvent) {
1470        match msg {
1471            DocumentEvent::ResourceLoad(resource) => self.load_resource(resource),
1472            DocumentEvent::NavigateIframe { node_id, url } => self.navigate_iframe(node_id, url),
1473        }
1474    }
1475
1476    /// Whether the Document has pending requests for "critical" resources (that should block rendering)
1477    pub fn has_pending_critical_resources(&self) -> bool {
1478        !self.pending_critical_resources.is_empty()
1479    }
1480
1481    /// How many distinct image URLs are still being fetched.
1482    ///
1483    /// Images are deliberately not "critical" resources, so they never block
1484    /// rendering. An embedder that needs a settled page (a screenshot, a test,
1485    /// a print) has no other way to tell an image that is still in flight from
1486    /// one that will never arrive.
1487    pub fn pending_image_count(&self) -> usize {
1488        self.pending_images.len()
1489    }
1490
1491    pub fn load_resource(&mut self, res: ResourceLoadResponse) {
1492        self.pending_critical_resources.remove(&res.request_id);
1493
1494        let resource = match res.result {
1495            Ok(resource) => resource,
1496            Err(err) => {
1497                if let Some(url) = res.resolved_url.as_ref() {
1498                    let waiting_nodes = self.pending_images.remove(url).unwrap_or_default();
1499                    #[cfg(feature = "tracing")]
1500                    tracing::warn!(
1501                        url = url.as_str(),
1502                        waiting_nodes = waiting_nodes.len(),
1503                        error = err.as_str(),
1504                        "Resource load failed"
1505                    );
1506                    #[cfg(not(feature = "tracing"))]
1507                    let _ = (waiting_nodes, err);
1508                } else {
1509                    #[cfg(feature = "tracing")]
1510                    tracing::warn!(error = err.as_str(), "Resource load failed (no url)");
1511                    #[cfg(not(feature = "tracing"))]
1512                    let _ = err;
1513                }
1514                return;
1515            }
1516        };
1517
1518        match resource {
1519            Resource::Css(css) => {
1520                let node_id = res.node_id.unwrap();
1521                self.add_stylesheet_for_node(css, node_id);
1522            }
1523            Resource::Image(_kind, width, height, image_data) => {
1524                // Create the ImageData and cache it
1525                let image = ImageData::Raster(RasterImageData::new(width, height, image_data));
1526
1527                let Some(url) = res.resolved_url.as_ref() else {
1528                    return;
1529                };
1530
1531                self.apply_loaded_image(url, image);
1532            }
1533            #[cfg(feature = "svg")]
1534            Resource::Svg(_kind, svg) => {
1535                // Create the ImageData and cache it
1536                let image = ImageData::Svg(svg);
1537
1538                let Some(url) = res.resolved_url.as_ref() else {
1539                    return;
1540                };
1541
1542                self.apply_loaded_image(url, image);
1543            }
1544            Resource::DocumentSrc(html) => {
1545                let Some(node_id) = res.node_id else {
1546                    return;
1547                };
1548                self.apply_iframe_html(node_id, res.request_id, res.resolved_url, &html);
1549            }
1550            Resource::Font(bytes, overrides) => {
1551                let font = Blob::new(Arc::new(bytes));
1552
1553                // Build a `FontInfoOverride` from the `@font-face` descriptors
1554                // captured during stylesheet parsing. Without this, parley
1555                // reads the family name from the TTF's own metadata, which
1556                // means CSS `font-family: 'Avenir Book'` won't match a font
1557                // file that internally identifies as `Avenir 45 Book`.
1558                let weight_override = overrides.weight.map(parley::fontique::FontWeight::new);
1559                let info_override = parley::fontique::FontInfoOverride {
1560                    family_name: overrides.family_name.as_deref(),
1561                    weight: weight_override,
1562                    style: overrides.style,
1563                    ..Default::default()
1564                };
1565
1566                // TODO: Investigate eliminating double-box
1567                let mut global_font_ctx = self.font_ctx.lock().unwrap();
1568                global_font_ctx
1569                    .collection
1570                    .register_fonts(font.clone(), Some(info_override));
1571
1572                #[cfg(feature = "parallel-construct")]
1573                {
1574                    rayon::broadcast(|_ctx| {
1575                        let mut font_ctx = self
1576                            .thread_font_contexts
1577                            .get_or(|| RefCell::new(Box::new(global_font_ctx.clone())))
1578                            .borrow_mut();
1579                        font_ctx
1580                            .collection
1581                            .register_fonts(font.clone(), Some(info_override));
1582                    });
1583                }
1584                drop(global_font_ctx);
1585
1586                // TODO: see if we can only invalidate if resolved fonts may have changed
1587                self.invalidate_inline_contexts();
1588            }
1589            Resource::None => {
1590                // Do nothing
1591            }
1592        }
1593    }
1594
1595    /// Cache a loaded image and apply it to all nodes waiting on it
1596    /// (`<img>` elements, `background-image` layers and `mask-image` layers).
1597    fn apply_loaded_image(&mut self, url: &str, image: ImageData) {
1598        // Get all nodes waiting for this image
1599        let waiting_nodes = self.pending_images.remove(url).unwrap_or_default();
1600
1601        #[cfg(feature = "tracing")]
1602        tracing::info!(
1603            "Image {url} loaded, applying to {} nodes",
1604            waiting_nodes.len()
1605        );
1606
1607        // Cache the image
1608        self.image_cache.insert(url.to_string(), image.clone());
1609
1610        // Apply to all waiting nodes
1611        for (node_id, image_type) in waiting_nodes {
1612            let Some(node) = self.get_node_mut(node_id) else {
1613                continue;
1614            };
1615
1616            match image_type {
1617                ImageType::Image => {
1618                    node.element_data_mut().unwrap().special_data =
1619                        SpecialElementData::Image(Box::new(image.clone()));
1620
1621                    // Clear layout cache
1622                    node.cache_mut().clear();
1623                    node.insert_damage(ALL_DAMAGE);
1624                }
1625                ImageType::Background(idx) | ImageType::Mask(idx) => {
1626                    let layer_image = node.element_data_mut().and_then(|el| {
1627                        let images = match image_type {
1628                            ImageType::Background(_) => &mut el.background_images,
1629                            ImageType::Mask(_) => &mut el.mask_images,
1630                            ImageType::Image => unreachable!(),
1631                        };
1632                        images.get_mut(idx)
1633                    });
1634                    if let Some(Some(layer_image)) = layer_image {
1635                        layer_image.status = Status::Ok;
1636                        layer_image.image = image.clone();
1637                    }
1638                }
1639            }
1640        }
1641    }
1642
1643    pub fn snapshot_node(&mut self, node_id: NodeId) {
1644        let node = &mut self.nodes[node_id];
1645
1646        // Do not snapshot nodes that have never been styled. A snapshot records an element's
1647        // pre-mutation state so a restyle can diff selector matches then-vs-now. An element
1648        // that has never been styled has no "then" to diff against. Snapshotting it anyway
1649        // makes Stylo's invalidation unwrap its (absent) primary style and panic.
1650        let has_been_styled = node.primary_styles().is_some();
1651        if !has_been_styled {
1652            return;
1653        }
1654
1655        let opaque_node_id = TNode::opaque(&&*node);
1656        node.set_has_snapshot(true);
1657        node.snapshot_handled()
1658            .store(false, std::sync::atomic::Ordering::SeqCst);
1659
1660        // TODO: handle invalidations other than hover
1661        if let Some(_existing_snapshot) = self.snapshots.get_mut(&opaque_node_id) {
1662            // Do nothing
1663            // TODO: update snapshot
1664        } else {
1665            let attrs: Option<Vec<_>> = node.attrs().map(|attrs| {
1666                attrs
1667                    .iter()
1668                    .map(|attr| {
1669                        let ident = AttrIdentifier {
1670                            local_name: GenericAtomIdent(attr.name.local.clone()),
1671                            name: GenericAtomIdent(attr.name.local.clone()),
1672                            namespace: GenericAtomIdent(attr.name.ns.clone()),
1673                            prefix: None,
1674                        };
1675
1676                        let value = if attr.name.local == local_name!("id") {
1677                            AttrValue::Atom(Atom::from(&*attr.value))
1678                        } else if attr.name.local == local_name!("class") {
1679                            let classes = attr
1680                                .value
1681                                .split_ascii_whitespace()
1682                                .map(Atom::from)
1683                                .collect();
1684                            AttrValue::TokenList(OnceLock::from(attr.value.clone()), classes)
1685                        } else {
1686                            AttrValue::String(attr.value.clone())
1687                        };
1688
1689                        (ident, value)
1690                    })
1691                    .collect()
1692            });
1693
1694            let changed_attrs = attrs
1695                .as_ref()
1696                .map(|attrs| attrs.iter().map(|attr| attr.0.name.clone()).collect())
1697                .unwrap_or_default();
1698
1699            self.snapshots.insert(
1700                opaque_node_id,
1701                ServoElementSnapshot {
1702                    state: Some(*node.element_state()),
1703                    attrs,
1704                    changed_attrs,
1705                    class_changed: true,
1706                    id_changed: true,
1707                    other_attributes_changed: true,
1708                },
1709            );
1710        }
1711    }
1712
1713    /// Snapshot a node and act on it, if it is still there.
1714    ///
1715    /// Tolerant of a node that has gone, because the ids reaching this are
1716    /// remembered across events — focus, hover, the last press — and the node
1717    /// they name can be removed between one event and the next. Indexing
1718    /// directly turned that ordinary case into a panic inside an event handler.
1719    pub fn snapshot_node_and(&mut self, node_id: NodeId, cb: impl FnOnce(&mut Node)) {
1720        if !self.nodes.contains_key(node_id) {
1721            return;
1722        }
1723        self.snapshot_node(node_id);
1724        cb(&mut self.nodes[node_id]);
1725    }
1726
1727    // Takes (x, y) co-ordinates (relative to the )
1728    pub fn hit(&self, x: f32, y: f32) -> Option<HitResult> {
1729        self.hit_with_scrollbar(x, y).0
1730    }
1731
1732    /// Walk up the tree to the nearest DOM node whose id is stable across
1733    /// box-tree reconstruction, so canonicalized interaction state never goes
1734    /// stale.
1735    ///
1736    /// Layout-generated nodes (anonymous blocks and `::before`/`::after`
1737    /// pseudo-elements, both stored as anonymous blocks) get new ids on every
1738    /// reconstruction, so we skip any anonymous node *and* a non-anonymous node
1739    /// whose parent is anonymous (the pseudo's text content). The first
1740    /// non-anonymous node with a non-anonymous parent is a real DOM node; the
1741    /// root element's `Document` parent guarantees termination.
1742    ///
1743    /// Returns `None` if `node_id` (or an ancestor) no longer exists.
1744    pub fn nearest_non_anonymous_ancestor(&self, node_id: NodeId) -> Option<NodeId> {
1745        // Recurse up the tree keeping a window of the current node and its
1746        // parent, advancing one step per iteration so each node is looked up
1747        // exactly once.
1748        let mut node = self.get_node(node_id)?;
1749        loop {
1750            let parent = match node.parent {
1751                Some(parent_id) => self.get_node(parent_id)?,
1752                None => return Some(node.id),
1753            };
1754            if !node.is_anonymous() && !parent.is_anonymous() {
1755                return Some(node.id);
1756            }
1757            node = parent;
1758        }
1759    }
1760
1761    pub fn focus_next_node(&mut self) -> Option<NodeId> {
1762        let focussed_node_id = self.get_focussed_node_id()?;
1763        let id = self.next_node(&self.nodes[focussed_node_id], |node| node.is_focussable())?;
1764        self.set_focus_to(id);
1765        Some(id)
1766    }
1767
1768    /// Move focus to the previous focussable node in the document
1769    pub fn focus_prev_node(&mut self) -> Option<NodeId> {
1770        let focussed_node_id = self.get_focussed_node_id()?;
1771        let id = self.prev_node(&self.nodes[focussed_node_id], |node| node.is_focussable())?;
1772        self.set_focus_to(id);
1773        Some(id)
1774    }
1775
1776    /// Clear the focussed node
1777    pub fn clear_focus(&mut self) {
1778        if let Some(id) = self.focus_node_id {
1779            let shell_provider = self.shell_provider.clone();
1780            self.snapshot_node_and(id, |node| node.blur(shell_provider));
1781            self.focus_node_id = None;
1782        }
1783    }
1784
1785    pub fn set_mousedown_node_id(&mut self, node_id: Option<NodeId>) {
1786        self.mousedown_node_id = node_id.and_then(|id| self.nearest_non_anonymous_ancestor(id));
1787    }
1788    pub fn set_focus_to(&mut self, focus_node_id: NodeId) -> bool {
1789        let Some(focus_node_id) = self.nearest_non_anonymous_ancestor(focus_node_id) else {
1790            return false;
1791        };
1792        if Some(focus_node_id) == self.focus_node_id {
1793            return false;
1794        }
1795
1796        #[cfg(feature = "tracing")]
1797        tracing::info!("Focussed node {focus_node_id}");
1798
1799        let shell_provider = self.shell_provider.clone();
1800
1801        // Remove focus from the old node
1802        if let Some(id) = self.focus_node_id {
1803            self.snapshot_node_and(id, |node| node.blur(shell_provider.clone()));
1804        }
1805
1806        // Focus the new node
1807        self.snapshot_node_and(focus_node_id, |node| node.focus(shell_provider));
1808
1809        self.focus_node_id = Some(focus_node_id);
1810
1811        true
1812    }
1813
1814    pub fn active_node(&mut self) -> bool {
1815        let Some(hover_node_id) = self.get_hover_node_id() else {
1816            return false;
1817        };
1818
1819        if let Some(active_node_id) = self.active_node_id {
1820            if active_node_id == hover_node_id {
1821                return true;
1822            }
1823            self.unactive_node();
1824        }
1825
1826        // hover_node_id is canonicalized when stored, so this always holds.
1827        debug_assert!(
1828            self.get_node(hover_node_id)
1829                .is_some_and(|node| !node.is_anonymous()),
1830            "interaction state must reference DOM nodes, not layout-generated nodes"
1831        );
1832        let active_node_id = Some(hover_node_id);
1833
1834        let node_path = self.maybe_node_layout_ancestors(active_node_id);
1835        for &id in node_path.iter() {
1836            self.snapshot_node_and(id, |node| node.active());
1837        }
1838
1839        self.active_node_id = active_node_id;
1840
1841        true
1842    }
1843
1844    pub fn unactive_node(&mut self) -> bool {
1845        let Some(active_node_id) = self.active_node_id.take() else {
1846            return false;
1847        };
1848
1849        let node_path = self.maybe_node_layout_ancestors(Some(active_node_id));
1850        for &id in node_path.iter() {
1851            self.snapshot_node_and(id, |node| node.unactive());
1852        }
1853
1854        true
1855    }
1856
1857    /// The scrollbar thumb currently under the pointer, if any.
1858    pub fn hovered_scrollbar(&self) -> Option<crate::node::ScrollbarRef> {
1859        self.hovered_scrollbar
1860    }
1861
1862    /// The scrollbar thumb currently being dragged, if any.
1863    pub fn scrollbar_drag_target(&self) -> Option<crate::node::ScrollbarRef> {
1864        match &self.drag_mode {
1865            DragMode::ScrollbarDrag(state) => Some(state.scrollbar),
1866            _ => None,
1867        }
1868    }
1869
1870    /// The current opacity of `node_id`'s overlay scrollbars. They show at
1871    /// full opacity on scroll and fade out after a delay (Chromium's overlay
1872    /// timings); the pointer resting on a thumb, or dragging it, holds them
1873    /// visible.
1874    pub fn scrollbar_opacity(&self, node_id: NodeId) -> f32 {
1875        let interacting = |scrollbar: &crate::node::ScrollbarRef| scrollbar.node_id == node_id;
1876        if self.hovered_scrollbar.as_ref().is_some_and(interacting)
1877            || self
1878                .scrollbar_drag_target()
1879                .as_ref()
1880                .is_some_and(interacting)
1881        {
1882            return 1.0;
1883        }
1884        self.scrollbar_activity.get(&node_id).map_or(1.0, |last| {
1885            crate::node::scrollbar::opacity_at(last.elapsed())
1886        })
1887    }
1888
1889    /// Show `node_id`'s overlay scrollbars at full opacity and restart their
1890    /// fade-out delay.
1891    pub(crate) fn show_scrollbars(&mut self, node_id: NodeId) {
1892        if cfg!(feature = "scrollbars") {
1893            self.scrollbar_activity.insert(node_id, Instant::now());
1894        }
1895    }
1896
1897    /// Whether any overlay scrollbars are awaiting or animating their
1898    /// fade-out (so frames must keep rendering until they finish).
1899    fn scrollbars_animating(&self) -> bool {
1900        use crate::node::scrollbar::{FADE_DELAY, FADE_DURATION};
1901        self.scrollbar_activity
1902            .values()
1903            .any(|last| last.elapsed() < FADE_DELAY + FADE_DURATION)
1904    }
1905
1906    /// [`hit`](Self::hit), also resolving the innermost overlay scrollbar
1907    /// thumb under the point (shares the traversal, so it costs nothing
1908    /// extra).
1909    pub(crate) fn hit_with_scrollbar(
1910        &self,
1911        x: f32,
1912        y: f32,
1913    ) -> (Option<HitResult>, Option<crate::node::ScrollbarRef>) {
1914        if TDocument::as_node(&self.root_node())
1915            .first_element_child()
1916            .is_none()
1917        {
1918            #[cfg(feature = "tracing")]
1919            tracing::warn!("No DOM - not resolving hit test");
1920            return (None, None);
1921        }
1922        let mut scrollbar = None;
1923        let hit = self
1924            .root_element()
1925            .hit_inner(x, y, self.viewport().scale_f64(), &mut scrollbar);
1926        (hit, scrollbar)
1927    }
1928
1929    pub fn set_hover_to(&mut self, x: f32, y: f32) -> bool {
1930        // Record the pointer position in client (unscrolled) coordinates so
1931        // that `refresh_hover` can re-resolve hover state after layout or
1932        // scroll changes.
1933        self.last_client_pointer_position = Some(taffy::Point {
1934            x: x - self.viewport_scroll.x as f32,
1935            y: y - self.viewport_scroll.y as f32,
1936        });
1937
1938        let (hit, hovered_scrollbar) = self.hit_with_scrollbar(x, y);
1939        // A faded-out thumb is not interactive: pointer moves never fade
1940        // overlay scrollbars back in (only scrolling shows them).
1941        let hovered_scrollbar =
1942            hovered_scrollbar.filter(|scrollbar| self.scrollbar_opacity(scrollbar.node_id) > 0.0);
1943        // Scrollbar-thumb hover is part of hover state: track it here so a
1944        // pointer crossing a thumb restyles it even when the hit node (the
1945        // content under the overlay thumb) is unchanged.
1946        let scrollbar_changed = hovered_scrollbar != self.hovered_scrollbar;
1947        if scrollbar_changed {
1948            // Entering a thumb restores full opacity mid-fade; leaving one
1949            // restarts the fade-out delay.
1950            for scrollbar in [self.hovered_scrollbar, hovered_scrollbar]
1951                .into_iter()
1952                .flatten()
1953            {
1954                self.show_scrollbars(scrollbar.node_id);
1955            }
1956        }
1957        self.hovered_scrollbar = hovered_scrollbar;
1958
1959        // Store both the precise layout node that was hit (transient: used for
1960        // cursor/style queries) and its canonical DOM target (persistent: must
1961        // not reference layout-generated nodes, whose ids die on box-tree
1962        // reconstruction).
1963        let hit_node_id = hit.map(|hit| hit.node_id);
1964        let hover_node_id = hit_node_id.and_then(|id| self.nearest_non_anonymous_ancestor(id));
1965        let new_is_text = hit.map(|hit| hit.is_text).unwrap_or(false);
1966
1967        let hit_changed =
1968            hit_node_id != self.hover_hit_node_id || new_is_text != self.hover_node_is_text;
1969        self.hover_hit_node_id = hit_node_id;
1970        self.hover_node_is_text = new_is_text;
1971
1972        // Return early if the new node is the same as the already-hovered node
1973        if hover_node_id == self.hover_node_id {
1974            if hit_changed {
1975                // The canonical target is unchanged (so no restyle is needed)
1976                // but the precise hit node changed, which can change the cursor
1977                // (e.g. moving between text and non-text within one element).
1978                self.shell_provider.set_cursor(self.get_cursor());
1979            }
1980            return scrollbar_changed;
1981        }
1982
1983        let old_node_path = self.maybe_node_layout_ancestors(self.hover_node_id);
1984        let new_node_path = self.maybe_node_layout_ancestors(hover_node_id);
1985        let same_count = old_node_path
1986            .iter()
1987            .zip(&new_node_path)
1988            .take_while(|(o, n)| o == n)
1989            .count();
1990        for &id in old_node_path.iter().skip(same_count) {
1991            self.snapshot_node_and(id, |node| node.unhover());
1992        }
1993        for &id in new_node_path.iter().skip(same_count) {
1994            self.snapshot_node_and(id, |node| node.hover());
1995        }
1996
1997        self.hover_node_id = hover_node_id;
1998
1999        // Update the cursor
2000        self.shell_provider.set_cursor(self.get_cursor());
2001
2002        // Request redraw
2003        self.shell_provider.request_redraw();
2004
2005        true
2006    }
2007
2008    pub fn clear_hover(&mut self) -> bool {
2009        // The pointer is no longer over the document, so stop re-resolving
2010        // hover state against it.
2011        self.last_client_pointer_position = None;
2012        self.hover_hit_node_id = None;
2013
2014        let Some(hover_node_id) = self.hover_node_id else {
2015            return false;
2016        };
2017
2018        let old_node_path = self.maybe_node_layout_ancestors(Some(hover_node_id));
2019        for &id in old_node_path.iter() {
2020            self.snapshot_node_and(id, |node| node.unhover());
2021        }
2022
2023        self.hover_node_id = None;
2024        self.hover_node_is_text = false;
2025
2026        // Update the cursor
2027        self.shell_provider.set_cursor(self.get_cursor());
2028
2029        // Request redraw
2030        self.shell_provider.request_redraw();
2031
2032        true
2033    }
2034
2035    /// Re-resolve hover state against the current layout using the last known
2036    /// pointer position.
2037    ///
2038    /// TODO: synthesizing pointerenter/pointerleave DOM events for
2039    /// hover changes caused by layout shifts.
2040    pub fn refresh_hover(&mut self) -> bool {
2041        let Some(pos) = self.last_client_pointer_position else {
2042            return false;
2043        };
2044        let x = pos.x + self.viewport_scroll.x as f32;
2045        let y = pos.y + self.viewport_scroll.y as f32;
2046        self.set_hover_to(x, y)
2047    }
2048
2049    pub fn get_hover_node_id(&self) -> Option<NodeId> {
2050        self.hover_node_id
2051    }
2052
2053    pub fn get_mousedown_node_id(&self) -> Option<NodeId> {
2054        self.mousedown_node_id
2055    }
2056
2057    pub fn set_viewport(&mut self, viewport: Viewport) {
2058        let scale_has_changed = viewport.scale_f64() != self.viewport.scale_f64();
2059        self.viewport = viewport;
2060        self.set_stylist_device(make_device(
2061            &self.viewport,
2062            self.media_type.clone(),
2063            self.font_ctx.clone(),
2064        ));
2065        self.scroll_viewport_by(0.0, 0.0); // Clamp scroll offset
2066
2067        if scale_has_changed {
2068            self.invalidate_inline_contexts();
2069            self.shell_provider.request_redraw();
2070        }
2071    }
2072
2073    /// Returns the current CSS media type used to evaluate `@media` rules.
2074    pub fn media_type(&self) -> &MediaType {
2075        &self.media_type
2076    }
2077
2078    /// Sets the CSS media type used to evaluate `@media` rules (e.g. `screen` or `print`)
2079    /// and rebuilds the stylist device so updated rules apply on the next restyle.
2080    pub fn set_media_type(&mut self, media_type: MediaType) {
2081        if self.media_type == media_type {
2082            return;
2083        }
2084        self.media_type = media_type;
2085        self.set_stylist_device(make_device(
2086            &self.viewport,
2087            self.media_type.clone(),
2088            self.font_ctx.clone(),
2089        ));
2090    }
2091
2092    pub fn viewport(&self) -> &Viewport {
2093        &self.viewport
2094    }
2095
2096    pub fn viewport_mut(&mut self) -> ViewportMut<'_> {
2097        ViewportMut::new(self)
2098    }
2099
2100    pub fn zoom_by(&mut self, increment: f32) {
2101        *self.viewport.zoom_mut() += increment;
2102        self.set_viewport(self.viewport.clone());
2103    }
2104
2105    pub fn zoom_to(&mut self, zoom: f32) {
2106        *self.viewport.zoom_mut() = zoom;
2107        self.set_viewport(self.viewport.clone());
2108    }
2109
2110    pub fn get_viewport(&self) -> Viewport {
2111        self.viewport.clone()
2112    }
2113
2114    /// Returns whether incremental layout is currently enabled for this document.
2115    pub fn incremental_layout(&self) -> bool {
2116        self.incremental_layout
2117    }
2118
2119    /// Enables or disables incremental layout for this document.
2120    pub fn set_incremental_layout(&mut self, enabled: bool) {
2121        self.incremental_layout = enabled;
2122    }
2123
2124    pub fn devtools(&self) -> &DevtoolSettings {
2125        &self.devtool_settings
2126    }
2127
2128    pub fn devtools_mut(&mut self) -> &mut DevtoolSettings {
2129        &mut self.devtool_settings
2130    }
2131
2132    pub fn subdoc(&self, node_id: NodeId) -> Option<&dyn Document> {
2133        self.get_node(node_id)
2134            .and_then(|node| node.element_data())
2135            .and_then(|el| el.sub_doc_data())
2136    }
2137
2138    pub fn subdoc_mut(&mut self, node_id: NodeId) -> Option<&mut dyn Document> {
2139        self.get_node_mut(node_id)
2140            .and_then(|node| node.element_data_mut())
2141            .and_then(|el| el.sub_doc_data_mut())
2142    }
2143
2144    pub fn is_animating(&self) -> bool {
2145        #[cfg(feature = "custom-widget")]
2146        let custom_widget_is_animating = self.custom_widget_nodes.iter().any(|&node_id| {
2147            self.nodes[node_id]
2148                .element_data()
2149                .and_then(|el| el.custom_widget_data())
2150                .is_some_and(|data| data.widget.requires_redraw())
2151        });
2152        #[cfg(not(feature = "custom-widget"))]
2153        let custom_widget_is_animating = false;
2154
2155        let animating = self.has_canvas
2156            | self.has_active_animations
2157            | (self.subdoc_animation_pacing != AnimationPacing::Idle)
2158            | custom_widget_is_animating
2159            | (self.scroll_animation != ScrollAnimationState::None)
2160            | self.scrollbars_animating();
2161
2162        if animating && crate::debug::animation_reasons_enabled() {
2163            crate::debug::report_animation_reasons(
2164                self.id(),
2165                self.has_canvas,
2166                self.has_active_animations,
2167                self.subdoc_animation_pacing != AnimationPacing::Idle,
2168                custom_widget_is_animating,
2169                self.scroll_animation != ScrollAnimationState::None,
2170                self.scrollbars_animating(),
2171                self.animating_node_names().as_deref(),
2172            );
2173        }
2174
2175        animating
2176    }
2177
2178    /// Return the cadence class for the next animation-only frame.
2179    ///
2180    /// CSS animations are commonly decorative and can use a lower cadence.
2181    /// Canvas, scrolling and custom widgets remain at the interactive cadence.
2182    pub fn animation_pacing(&self) -> AnimationPacing {
2183        let focused_text_input = self.focus_node_id.is_some_and(|node_id| {
2184            self.nodes
2185                .get(node_id)
2186                .and_then(|node| node.element_data())
2187                .is_some_and(|element| element.text_input_data().is_some())
2188        });
2189        #[cfg(feature = "custom-widget")]
2190        let custom_widget_is_animating = self.custom_widget_nodes.iter().any(|&node_id| {
2191            self.nodes[node_id]
2192                .element_data()
2193                .and_then(|el| el.custom_widget_data())
2194                .is_some_and(|data| data.widget.requires_redraw())
2195        });
2196        #[cfg(not(feature = "custom-widget"))]
2197        let custom_widget_is_animating = false;
2198
2199        if self.has_canvas
2200            || custom_widget_is_animating
2201            || self.scroll_animation != ScrollAnimationState::None
2202            || self.scrollbars_animating()
2203        {
2204            AnimationPacing::Interactive
2205        } else if self.has_active_animations {
2206            const SLOW_ANIMATION_SECONDS: f64 = 2.0;
2207            let sets = self.animations.sets.read();
2208            let has_fast_animation_or_transition = sets.values().any(|set| {
2209                set.transitions.iter().any(|transition| {
2210                    matches!(
2211                        transition.state,
2212                        AnimationState::Pending | AnimationState::Running
2213                    )
2214                }) || set.animations.iter().any(|animation| {
2215                    matches!(
2216                        animation.state,
2217                        AnimationState::Pending | AnimationState::Running
2218                    ) && animation.duration < SLOW_ANIMATION_SECONDS
2219                })
2220            });
2221            if has_fast_animation_or_transition {
2222                AnimationPacing::Interactive
2223            } else {
2224                AnimationPacing::SlowCss
2225            }
2226        } else if focused_text_input {
2227            AnimationPacing::Caret
2228        } else if self.subdoc_animation_pacing != AnimationPacing::Idle {
2229            self.subdoc_animation_pacing
2230        } else {
2231            AnimationPacing::Idle
2232        }
2233    }
2234
2235    /// Which elements Stylo currently holds animations or transitions for.
2236    ///
2237    /// Only built when the diagnostic is switched on: a frame loop that will
2238    /// not settle is otherwise very hard to attribute, because
2239    /// `has_active_animations` is one bool for the whole document and says
2240    /// nothing about which element is keeping it true.
2241    fn animating_node_names(&self) -> Option<String> {
2242        if !self.has_active_animations {
2243            return None;
2244        }
2245        let sets = self.animations.sets.read();
2246        let mut described: Vec<String> = sets
2247            .iter()
2248            .filter(|(_, state)| state.needs_animation_ticks())
2249            .filter_map(|(key, state)| {
2250                let node_id = NodeId::from_u64(key.node.id() as u64);
2251                let node = self.nodes.get(node_id)?;
2252                let element = node.element_data()?;
2253                let name = element
2254                    .attr(local_name!("id"))
2255                    .map(|id| format!("#{id}"))
2256                    .or_else(|| {
2257                        element
2258                            .attr(local_name!("class"))
2259                            .and_then(|c| c.split_ascii_whitespace().next())
2260                            .map(|c| format!(".{c}"))
2261                    })
2262                    .unwrap_or_else(|| element.name.local.to_string());
2263                Some(format!(
2264                    "{name}(anim={},trans={},in_doc={})",
2265                    state.animations.len(),
2266                    state.transitions.len(),
2267                    node.flags.is_in_document(),
2268                ))
2269            })
2270            .collect();
2271        described.sort();
2272        described.truncate(12);
2273        Some(described.join(" "))
2274    }
2275
2276    /// Update the device and reset the stylist to process the new size
2277    pub fn set_stylist_device(&mut self, device: Device) {
2278        // Seed the new device with the root element's current style and font-relative
2279        // unit state (used to resolve rem/rlh/rex/rch/rcap/ric units). Stylo only
2280        // updates this state when the root element's style *changes* during a restyle,
2281        // so a freshly-built device would otherwise resolve these units against the
2282        // default font-size (16px) until the root's font-size next changes.
2283        let root_styles = self
2284            .try_root_element()
2285            .and_then(|root| root.primary_styles());
2286        if let Some(root_style) = root_styles.as_deref() {
2287            device.set_root_style(root_style);
2288
2289            let font = root_style.get_font();
2290            let font_size = font.clone_font_size().computed_size();
2291            device.set_root_font_size(root_style.effective_zoom.unzoom(font_size.px()));
2292
2293            let line_height = device
2294                .calc_line_height(font, root_style.writing_mode, None)
2295                .0;
2296            device.set_root_line_height(root_style.effective_zoom.unzoom(line_height.px()));
2297        }
2298        drop(root_styles);
2299
2300        let origins = {
2301            let guard = &self.guard;
2302            let guards = StylesheetGuards {
2303                author: &guard.read(),
2304                ua_or_user: &guard.read(),
2305            };
2306            self.stylist.set_device(device, &guards)
2307        };
2308        self.stylist.force_stylesheet_origins_dirty(origins);
2309    }
2310
2311    pub fn stylist_device(&mut self) -> &Device {
2312        self.stylist.device()
2313    }
2314
2315    /// The cursor to show, where `None` means `cursor: none` — hide it.
2316    ///
2317    /// `None` is an answer, not the absence of one. The shell hides the pointer
2318    /// when it sees `None`, so every path that means "nothing to say here" must
2319    /// return `Default` instead. Returning `None` from those made the pointer
2320    /// vanish as it crossed into page content, which is the shape this used to
2321    /// have: three `?`s that each meant "no opinion" and all read as "hide".
2322    pub fn get_cursor(&self) -> Option<CursorIcon> {
2323        // Prefer the precise hit node: `cursor` and `user-select` may be set on
2324        // a pseudo-element or resolved on an anonymous box, and text hits carry
2325        // is_text via the hit node. Fall back to the canonical hover node if
2326        // the hit node has been removed (it is transient across resolves).
2327        let node_id = self
2328            .hover_hit_node_id
2329            .filter(|&id| self.nodes.contains_key(id))
2330            .or(self.get_hover_node_id());
2331        let Some(node_id) = node_id else {
2332            return Some(CursorIcon::Default);
2333        };
2334        let node = &self.nodes[node_id];
2335
2336        if let Some(subdoc) = node.subdoc().map(|doc| doc.inner()) {
2337            // Only delegate when the sub-document has hover state of its own.
2338            // Without this check an embedded document that has not been hovered
2339            // yet answers `None` — meaning "I have no hover node" — and the
2340            // pointer disappears the moment it enters the page area, which is
2341            // every page in a browser built on sub-documents.
2342            if subdoc.hover_hit_node_id.is_some() || subdoc.get_hover_node_id().is_some() {
2343                return subdoc.get_cursor();
2344            }
2345            return Some(CursorIcon::Default);
2346        }
2347
2348        let Some(style) = node.primary_styles() else {
2349            return Some(CursorIcon::Default);
2350        };
2351        let user_select = style.clone_user_select();
2352        let keyword = style.clone_cursor().keyword;
2353
2354        // Return cursor from style if it is non-auto
2355        if keyword != CursorKind::Auto {
2356            return stylo_to_cursor_icon(keyword);
2357        }
2358
2359        // Return text cursor for text inputs
2360        if node
2361            .element_data()
2362            .is_some_and(|e| e.text_input_data().is_some())
2363        {
2364            return Some(CursorIcon::Text);
2365        }
2366
2367        // Use "pointer" cursor if any ancestor is a link
2368        let mut maybe_node = Some(node);
2369        while let Some(node) = maybe_node {
2370            if node.is_link() {
2371                return Some(CursorIcon::Pointer);
2372            }
2373
2374            maybe_node = node.layout_parent.get().map(|node_id| node.with(node_id));
2375        }
2376
2377        // Return text cursor for text nodes
2378        if self.hover_node_is_text {
2379            return Some(match user_select {
2380                UserSelect::Text | UserSelect::All | UserSelect::Auto => CursorIcon::Text,
2381                UserSelect::None => CursorIcon::Default,
2382            });
2383        }
2384
2385        // Else fallback to default cursor
2386        Some(CursorIcon::Default)
2387    }
2388
2389    pub fn scroll_node_by<F: FnMut(DomEvent)>(
2390        &mut self,
2391        node_id: NodeId,
2392        x: f64,
2393        y: f64,
2394        dispatch_event: F,
2395    ) {
2396        self.scroll_node_by_has_changed(node_id, x, y, dispatch_event);
2397    }
2398
2399    /// Scroll a node by given x and y
2400    /// Will bubble scrolling up to parent node once it can no longer scroll further
2401    /// If we're already at the root node, bubbles scrolling up to the viewport
2402    pub fn scroll_node_by_has_changed<F: FnMut(DomEvent)>(
2403        &mut self,
2404        node_id: NodeId,
2405        x: f64,
2406        y: f64,
2407        mut dispatch_event: F,
2408    ) -> bool {
2409        // Per the CSS overflow propagation rules, the root element's overflow (and usually
2410        // the <body>'s) is applied to the viewport, and the element itself must not have
2411        // a scrolling mechanism of its own. So scrolls that reach the root element are
2412        // forwarded to the viewport rather than scrolling the root element itself.
2413        if self.try_root_element().is_some_and(|el| el.id == node_id) {
2414            let has_changed = self.scroll_viewport_by_has_changed(x, y);
2415            if has_changed {
2416                let layout = *self.root_element().final_layout();
2417                let scale = self.viewport.scale() as f64;
2418                let event = BlitzScrollEvent {
2419                    scroll_top: self.viewport_scroll.y,
2420                    scroll_left: self.viewport_scroll.x,
2421                    scroll_width: layout.size.width.max(layout.content_size.width) as i32,
2422                    scroll_height: layout.size.height.max(layout.content_size.height) as i32,
2423                    client_width: (self.viewport.window_size.0 as f64 / scale) as i32,
2424                    client_height: (self.viewport.window_size.1 as f64 / scale) as i32,
2425                };
2426                dispatch_event(DomEvent::new(node_id, DomEventData::Scroll(event)));
2427            }
2428            return has_changed;
2429        }
2430
2431        let Some(node) = self.nodes.get_mut(node_id) else {
2432            return false;
2433        };
2434
2435        // Text inputs scroll their own internal text content rather than using the generic
2436        // overflow mechanism: single-line inputs scroll horizontally, multi-line inputs scroll
2437        // vertically. Any delta the input cannot consume is bubbled up to an ancestor scroller.
2438        if node
2439            .element_data()
2440            .is_some_and(|el| el.text_input_data().is_some())
2441        {
2442            let parent = node.parent;
2443            let content_box_width = node.final_layout().content_box_width();
2444            let content_box_height = node.final_layout().content_box_height();
2445            let input = node
2446                .element_data_mut()
2447                .and_then(|el| el.text_input_data_mut())
2448                .unwrap();
2449
2450            let (bubble_x, bubble_y) = if input.is_multiline {
2451                (
2452                    x,
2453                    input.scroll_by(y as f32, content_box_width, content_box_height) as f64,
2454                )
2455            } else {
2456                (
2457                    input.scroll_by(x as f32, content_box_width, content_box_height) as f64,
2458                    y,
2459                )
2460            };
2461
2462            let has_changed = bubble_x != x || bubble_y != y;
2463
2464            if bubble_x != 0.0 || bubble_y != 0.0 {
2465                let bubbled = if let Some(parent) = parent {
2466                    self.scroll_node_by_has_changed(parent, bubble_x, bubble_y, dispatch_event)
2467                } else {
2468                    self.scroll_viewport_by_has_changed(bubble_x, bubble_y)
2469                };
2470                return bubbled | has_changed;
2471            }
2472
2473            return has_changed;
2474        }
2475
2476        let (can_x_scroll, can_y_scroll) = node
2477            .primary_styles()
2478            .map(|styles| {
2479                (
2480                    matches!(styles.clone_overflow_x(), Overflow::Scroll | Overflow::Auto),
2481                    matches!(styles.clone_overflow_y(), Overflow::Scroll | Overflow::Auto),
2482                )
2483            })
2484            .unwrap_or((false, false));
2485
2486        let initial = *node.scroll_offset();
2487        let new_x = node.scroll_offset().x - x;
2488        let new_y = node.scroll_offset().y - y;
2489
2490        let mut bubble_x = 0.0;
2491        let mut bubble_y = 0.0;
2492
2493        let scroll_width = node.final_layout().scroll_width() as f64;
2494        let scroll_height = node.final_layout().scroll_height() as f64;
2495
2496        // Handle sub document case
2497        if let Some(mut sub_doc) = node.subdoc_mut().map(|doc| doc.inner_mut()) {
2498            let has_changed = if let Some(hover_node_id) = sub_doc.get_hover_node_id() {
2499                sub_doc.scroll_node_by_has_changed(hover_node_id, x, y, dispatch_event)
2500            } else {
2501                sub_doc.scroll_viewport_by_has_changed(x, y)
2502            };
2503
2504            // TODO: propagate remaining scroll to parent
2505            return has_changed;
2506        }
2507
2508        // If we're past our scroll bounds, transfer remainder of scrolling to parent/viewport
2509        if !can_x_scroll {
2510            bubble_x = x
2511        } else if new_x < 0.0 {
2512            bubble_x = -new_x;
2513            node.scroll_offset_mut().x = 0.0;
2514        } else if new_x > scroll_width {
2515            bubble_x = scroll_width - new_x;
2516            node.scroll_offset_mut().x = scroll_width;
2517        } else {
2518            node.scroll_offset_mut().x = new_x;
2519        }
2520
2521        if !can_y_scroll {
2522            bubble_y = y
2523        } else if new_y < 0.0 {
2524            bubble_y = -new_y;
2525            node.scroll_offset_mut().y = 0.0;
2526        } else if new_y > scroll_height {
2527            bubble_y = scroll_height - new_y;
2528            node.scroll_offset_mut().y = scroll_height;
2529        } else {
2530            node.scroll_offset_mut().y = new_y;
2531        }
2532
2533        let has_changed = *node.scroll_offset() != initial;
2534
2535        if has_changed {
2536            let layout = *node.final_layout();
2537            let event = BlitzScrollEvent {
2538                scroll_top: node.scroll_offset().y,
2539                scroll_left: node.scroll_offset().x,
2540                scroll_width: layout.scroll_width() as i32,
2541                scroll_height: layout.scroll_height() as i32,
2542                client_width: layout.size.width as i32,
2543                client_height: layout.size.height as i32,
2544            };
2545
2546            dispatch_event(DomEvent::new(node_id, DomEventData::Scroll(event)));
2547        }
2548
2549        let parent = node.parent;
2550        if has_changed {
2551            self.show_scrollbars(node_id);
2552        }
2553
2554        if bubble_x != 0.0 || bubble_y != 0.0 {
2555            if let Some(parent) = parent {
2556                return self.scroll_node_by_has_changed(parent, bubble_x, bubble_y, dispatch_event)
2557                    | has_changed;
2558            } else {
2559                return self.scroll_viewport_by_has_changed(bubble_x, bubble_y) | has_changed;
2560            }
2561        }
2562
2563        has_changed
2564    }
2565
2566    pub fn scroll_viewport_by(&mut self, x: f64, y: f64) {
2567        self.scroll_viewport_by_has_changed(x, y);
2568    }
2569
2570    /// Scroll the viewport by the given values
2571    pub fn scroll_viewport_by_has_changed(&mut self, x: f64, y: f64) -> bool {
2572        // The viewport scrolls the root element's scrollable overflow, which includes both
2573        // the root element itself and any content which overflows it (e.g. when the root
2574        // element has a fixed height but its content is taller). A document without a root
2575        // element has no scrollable content, so its content size is zero.
2576        let (content_width, content_height) = match self.try_root_element() {
2577            Some(root) => {
2578                let root_layout = root.final_layout();
2579                (
2580                    root_layout.size.width.max(root_layout.content_size.width) as f64,
2581                    root_layout.size.height.max(root_layout.content_size.height) as f64,
2582                )
2583            }
2584            None => (0.0, 0.0),
2585        };
2586        let new_scroll = (self.viewport_scroll.x - x, self.viewport_scroll.y - y);
2587        let window_width = self.viewport.window_size.0 as f64 / self.viewport.scale() as f64;
2588        let window_height = self.viewport.window_size.1 as f64 / self.viewport.scale() as f64;
2589
2590        let initial = self.viewport_scroll;
2591        self.viewport_scroll.x =
2592            f64::max(0.0, f64::min(new_scroll.0, content_width - window_width));
2593        self.viewport_scroll.y =
2594            f64::max(0.0, f64::min(new_scroll.1, content_height - window_height));
2595
2596        self.viewport_scroll != initial
2597    }
2598
2599    pub fn scroll_by(
2600        &mut self,
2601        anchor_node_id: Option<NodeId>,
2602        scroll_x: f64,
2603        scroll_y: f64,
2604        dispatch_event: &mut dyn FnMut(DomEvent),
2605    ) -> bool {
2606        if let Some(anchor_node_id) = anchor_node_id {
2607            self.scroll_node_by_has_changed(anchor_node_id, scroll_x, scroll_y, dispatch_event)
2608        } else {
2609            self.scroll_viewport_by_has_changed(scroll_x, scroll_y)
2610        }
2611    }
2612
2613    pub fn viewport_scroll(&self) -> crate::Point<f64> {
2614        self.viewport_scroll
2615    }
2616
2617    pub fn set_viewport_scroll(&mut self, scroll: crate::Point<f64>) {
2618        self.viewport_scroll = scroll;
2619    }
2620
2621    /// Find the node targeted by a URL fragment (the `#...` part of a URL).
2622    ///
2623    /// Per the HTML spec, this is the element whose `id` matches the fragment, falling
2624    /// back to the first `<a>` element whose `name` attribute matches.
2625    pub fn get_fragment_target(&self, fragment: &str) -> Option<NodeId> {
2626        if let Some(node_id) = self.get_element_by_id(fragment) {
2627            return Some(node_id);
2628        }
2629
2630        // Fall back to a named anchor: `<a name="...">`
2631        self.nodes.iter().find_map(|(id, node)| {
2632            let el = node.element_data()?;
2633            (el.name.local == local_name!("a") && el.attr(local_name!("name")) == Some(fragment))
2634                .then_some(id)
2635        })
2636    }
2637
2638    /// Scroll the viewport so that the given node is aligned with the top of the viewport.
2639    /// Scroll the nearest scroll container at or above `node_id`.
2640    ///
2641    /// "Scroll this panel" is the operation callers actually want, and
2642    /// `scroll_node_by` only moves the node itself, so naming any inner element
2643    /// silently did nothing. Wheel events are no help either: they are
2644    /// delivered to whatever the document last saw hovered, which an injected
2645    /// pointer move does not set, so an automated caller had no way to scroll
2646    /// anything at all.
2647    /// The nearest scroll container at or above `node_id`, if there is one.
2648    pub fn nearest_scroll_container(&self, node_id: NodeId) -> Option<NodeId> {
2649        let mut current = Some(node_id);
2650        for _ in 0..64 {
2651            let id = current?;
2652            let node = self.nodes.get(id)?;
2653            if node.style().overflow.x.is_scroll_container()
2654                || node.style().overflow.y.is_scroll_container()
2655            {
2656                return Some(id);
2657            }
2658            current = node.parent;
2659        }
2660        None
2661    }
2662
2663    pub fn scroll_nearest_container_by(&mut self, node_id: NodeId, x: f64, y: f64) -> bool {
2664        let mut current = Some(node_id);
2665        for _ in 0..64 {
2666            let Some(id) = current else { break };
2667            let Some(node) = self.nodes.get(id) else {
2668                break;
2669            };
2670            let scrolls = node.style().overflow.x.is_scroll_container()
2671                || node.style().overflow.y.is_scroll_container();
2672            if scrolls {
2673                self.scroll_node_by(id, x, y, |_| {});
2674                return true;
2675            }
2676            current = node.parent;
2677        }
2678        self.scroll_viewport_by(x, y);
2679        false
2680    }
2681
2682    pub fn scroll_to_node(&mut self, node_id: NodeId) {
2683        // Every scroll container between the node and the root, innermost
2684        // first. Scrolling only the viewport is not `scrollIntoView`: it does
2685        // nothing at all for a node inside a nested scroller, which is what an
2686        // application's own scrolling panes are.
2687        //
2688        // This was not academic. A transcript pane held its "Show 12 earlier
2689        // messages" button at y=-9463 and neither wheel events, Page Up nor
2690        // this call moved it by a single pixel, so a layout bug that only
2691        // appears further up the thread could not be reached from outside the
2692        // app at all. Every measurement of it had to come from a human
2693        // scrolling by hand and saying "now".
2694        let mut chain = Vec::new();
2695        let mut current = self.nodes.get(node_id).and_then(|node| node.parent);
2696        while let Some(id) = current {
2697            let Some(node) = self.nodes.get(id) else {
2698                break;
2699            };
2700            let scrolls = node.style().overflow.x.is_scroll_container()
2701                || node.style().overflow.y.is_scroll_container();
2702            if scrolls {
2703                chain.push(id);
2704            }
2705            current = node.parent;
2706        }
2707
2708        // Innermost first: scrolling an outer container moves the inner one, so
2709        // the inner offsets have to be settled before the outer ones are
2710        // measured, and each step re-reads the node's position.
2711        for container in chain {
2712            let Some(node) = self.nodes.get(node_id) else {
2713                return;
2714            };
2715            let target = node.absolute_position(0.0, 0.0);
2716            let Some(scroller) = self.nodes.get(container) else {
2717                continue;
2718            };
2719            let box_ = scroller.absolute_position(0.0, 0.0);
2720            let layout = scroller.final_layout();
2721            // Land the node at the top-left of the scrollport. `scroll_node_by`
2722            // takes a delta and subtracts it, so the sign here matches
2723            // `scroll_viewport_by` below.
2724            let dx = f64::from(box_.x - target.x);
2725            let dy = f64::from(box_.y - target.y);
2726            let _ = layout;
2727            self.scroll_node_by(container, dx, dy, |_| {});
2728        }
2729
2730        // `absolute_position` gives the node's position in document space (it does not
2731        // account for the viewport scroll), so it is the scroll offset we want to land on.
2732        let Some(node) = self.nodes.get(node_id) else {
2733            return;
2734        };
2735        let target = node.absolute_position(0.0, 0.0);
2736        let current = self.viewport_scroll;
2737
2738        // `scroll_viewport_by` subtracts the delta from the current scroll offset, so pass
2739        // `current - target` in order to land on `target`.
2740        self.scroll_viewport_by(current.x - target.x as f64, current.y - target.y as f64);
2741    }
2742
2743    /// Scroll to the element targeted by the given URL fragment (the `#...` part of a URL).
2744    ///
2745    /// An empty fragment (or a `top` fragment that matches no element) scrolls to the top
2746    /// of the document, matching browser behaviour. Returns `true` if a scroll target was
2747    /// found.
2748    pub fn scroll_to_fragment(&mut self, fragment: &str) -> bool {
2749        // Fragments are percent-encoded in URLs (e.g. `%20`); decode before matching.
2750        let decoded = percent_encoding::percent_decode_str(fragment)
2751            .decode_utf8_lossy()
2752            .into_owned();
2753
2754        if !decoded.is_empty() {
2755            if let Some(node_id) = self.get_fragment_target(&decoded) {
2756                self.scroll_to_node(node_id);
2757                return true;
2758            }
2759        }
2760
2761        // An empty fragment, or the special "top" fragment when no matching element exists,
2762        // scrolls to the top of the document.
2763        if decoded.is_empty() || decoded.eq_ignore_ascii_case("top") {
2764            let current = self.viewport_scroll;
2765            self.scroll_viewport_by(current.x, current.y);
2766            return true;
2767        }
2768
2769        false
2770    }
2771
2772    /// Computes the size and position of the `Node` relative to the viewport
2773    pub fn get_client_bounding_rect(&self, node_id: NodeId) -> Option<BoundingRect> {
2774        // Non-atomic inline elements have no layout box of their own: return
2775        // the union of their per-line-box fragment rects.
2776        if let Some(rects) = self.inline_fragment_rects(node_id) {
2777            let x0 = rects.iter().map(|r| r.x).fold(f64::INFINITY, f64::min);
2778            let y0 = rects.iter().map(|r| r.y).fold(f64::INFINITY, f64::min);
2779            let x1 = rects
2780                .iter()
2781                .map(|r| r.x + r.width)
2782                .fold(f64::NEG_INFINITY, f64::max);
2783            let y1 = rects
2784                .iter()
2785                .map(|r| r.y + r.height)
2786                .fold(f64::NEG_INFINITY, f64::max);
2787            return match rects.is_empty() {
2788                true => None,
2789                false => Some(BoundingRect {
2790                    x: x0,
2791                    y: y0,
2792                    width: x1 - x0,
2793                    height: y1 - y0,
2794                }),
2795            };
2796        }
2797
2798        let node = self.get_node(node_id)?;
2799        let pos = node.absolute_position(0.0, 0.0);
2800
2801        Some(BoundingRect {
2802            x: pos.x as f64 - self.viewport_scroll.x,
2803            y: pos.y as f64 - self.viewport_scroll.y,
2804            width: node.unrounded_layout().size.width as f64,
2805            height: node.unrounded_layout().size.height as f64,
2806        })
2807    }
2808
2809    /// Computes the sizes and positions of the `Node`'s box fragments relative to the
2810    /// viewport (CSSOM `getClientRects()` semantics). Nodes with their own layout box
2811    /// return a single rect. Non-atomic inline elements (which are laid out as style
2812    /// spans within an inline root's text layout) return one rect per line box.
2813    pub fn node_client_rects(&self, node_id: NodeId) -> Vec<BoundingRect> {
2814        match self.inline_fragment_rects(node_id) {
2815            Some(rects) => rects,
2816            None => self.get_client_bounding_rect(node_id).into_iter().collect(),
2817        }
2818    }
2819
2820    /// Computes per-line-box fragment rects for a non-atomic inline element by walking
2821    /// the containing inline root's text layout. Returns `None` for nodes that have
2822    /// their own layout box (which should use `get_client_bounding_rect` instead).
2823    /// Report inline elements whose fragment rects lie outside the inline root
2824    /// that owns them. `BLITZ_TRACE_INLINE=1`, once per resolve.
2825    ///
2826    /// A non-atomic inline element has no layout box of its own: its geometry
2827    /// is read back out of the containing inline root's text layout on demand.
2828    /// So "the chip is 900px to the right of its block" is a statement about
2829    /// that text layout, and the only way to see it is from in here, with both
2830    /// the fragment and the root in hand. Every earlier attempt to chase this
2831    /// from outside was reading a number the engine computes on the fly and
2832    /// could not say where it came from.
2833    pub(crate) fn trace_escaped_inline_fragments(&self) {
2834        static TRACE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2835        if !*TRACE.get_or_init(|| std::env::var_os("BLITZ_TRACE_INLINE").is_some()) {
2836            return;
2837        }
2838        let mut reported = 0;
2839        for (id, node) in self.nodes.iter() {
2840            if !node.is_element() {
2841                continue;
2842            }
2843            let Some(rects) = self.inline_fragment_rects(id) else {
2844                continue;
2845            };
2846            let Some(root) = node.inline_root_ancestor() else {
2847                continue;
2848            };
2849            let root_layout = root.final_layout();
2850            let root_pos = root.absolute_position(0.0, 0.0);
2851            let root_right =
2852                root_pos.x as f64 + root_layout.size.width as f64 - self.viewport_scroll.x;
2853            for rect in &rects {
2854                if rect.x + rect.width > root_right + 1.0 {
2855                    reported += 1;
2856                    if reported <= 12 {
2857                        eprintln!(
2858                            "escaped-fragment node={id:?} rect=[{:.1},{:.1} {:.1}x{:.1}] \
2859root={:?} root_right={root_right:.1} root_w={:.1} lines={} layout_scale={:.2} vp_scale={:.2} layout_w={:.1}",
2860                            rect.x,
2861                            rect.y,
2862                            rect.width,
2863                            rect.height,
2864                            root.id,
2865                            root_layout.size.width,
2866                            root.element_data()
2867                                .and_then(|e| e.inline_layout_data.as_ref())
2868                                .map(|i| i.layout.len())
2869                                .unwrap_or(0),
2870                            root.element_data()
2871                                .and_then(|e| e.inline_layout_data.as_ref())
2872                                .map(|i| i.layout.scale())
2873                                .unwrap_or(0.0),
2874                            self.viewport.scale(),
2875                            root.element_data()
2876                                .and_then(|e| e.inline_layout_data.as_ref())
2877                                .map(|i| i.layout.width())
2878                                .unwrap_or(0.0),
2879                        );
2880                    }
2881                    break;
2882                }
2883            }
2884        }
2885        if reported > 0 {
2886            eprintln!("escaped-fragment total={reported}");
2887        }
2888
2889        // The opposite failure, and the one that reads as "first load is
2890        // broken": lines broken far narrower than the box they sit in, so a
2891        // paragraph comes out as a column of one or two words inside a
2892        // full-width bubble. Nothing escapes, so the check above never sees it.
2893        let mut narrow = 0;
2894        for (id, node) in self.nodes.iter() {
2895            let Some(inline) = node
2896                .data
2897                .downcast_element()
2898                .and_then(|element| element.inline_layout_data.as_ref())
2899            else {
2900                continue;
2901            };
2902            let box_width = node.final_layout().size.width as f64 * self.viewport.scale() as f64;
2903            let broken_at = inline.layout.width() as f64;
2904            // Only interesting when the text had more to give: a short string
2905            // legitimately measures narrower than its box.
2906            let full = inline.layout.calculate_content_widths().max as f64;
2907            if box_width > 40.0 && broken_at < box_width * 0.6 && full > box_width * 0.9 {
2908                narrow += 1;
2909                if narrow <= 12 {
2910                    eprintln!(
2911                        "narrow-break node={id:?} broken_at={broken_at:.1} box={box_width:.1} \
2912                         max_content={full:.1} lines={} text={:?}",
2913                        inline.layout.len(),
2914                        inline.text.chars().take(40).collect::<String>(),
2915                    );
2916                }
2917            }
2918        }
2919        if narrow > 0 {
2920            eprintln!("narrow-break total={narrow}");
2921        }
2922    }
2923
2924    pub fn inline_fragment_rects(&self, node_id: NodeId) -> Option<Vec<BoundingRect>> {
2925        use parley::PositionedLayoutItem;
2926
2927        let node = self.get_node(node_id)?;
2928
2929        // Only non-atomic inline elements lack their own layout box: they are
2930        // flattened into the containing inline root's text layout as style spans.
2931        if !node.is_element() || node.flags.is_inline_root() {
2932            return None;
2933        }
2934        let display = node.primary_styles()?.clone_display();
2935        if !(display.outside() == DisplayOutside::Inline && display.inside() == DisplayInside::Flow)
2936        {
2937            return None;
2938        }
2939
2940        let inline_root = node.inline_root_ancestor()?;
2941        let inline_layout = inline_root.element_data()?.inline_layout_data.as_ref()?;
2942        let layout = &inline_layout.layout;
2943        let scale = layout.scale() as f64;
2944
2945        // Walk up the DOM parent chain from `id` to check whether it is (or is
2946        // inside) the target node, stopping at the inline root.
2947        let is_in_target = |mut id: NodeId| -> bool {
2948            loop {
2949                if id == node_id {
2950                    return true;
2951                }
2952                if id == inline_root.id {
2953                    return false;
2954                }
2955                match self.get_node(id).and_then(|n| n.parent) {
2956                    Some(parent) => id = parent,
2957                    None => return false,
2958                }
2959            }
2960        };
2961
2962        // Fragment rects are relative to the inline root's content box.
2963        let root_layout = inline_root.final_layout();
2964        let root_pos = inline_root.absolute_position(0.0, 0.0);
2965        let origin_x = root_pos.x as f64
2966            + (root_layout.padding.left + root_layout.border.left) as f64
2967            - self.viewport_scroll.x;
2968        let origin_y = root_pos.y as f64
2969            + (root_layout.padding.top + root_layout.border.top) as f64
2970            - self.viewport_scroll.y;
2971
2972        let mut rects: Vec<BoundingRect> = Vec::new();
2973        for line in layout.lines() {
2974            let line_metrics = line.metrics();
2975            // Union all of the target's fragments on this line into a single rect
2976            let mut line_rect: Option<(f64, f64, f64, f64)> = None;
2977            let mut add = |x0: f64, y0: f64, x1: f64, y1: f64| {
2978                line_rect = Some(match line_rect {
2979                    Some((lx0, ly0, lx1, ly1)) => {
2980                        (lx0.min(x0), ly0.min(y0), lx1.max(x1), ly1.max(y1))
2981                    }
2982                    None => (x0, y0, x1, y1),
2983                });
2984            };
2985
2986            for item in line.items() {
2987                match item {
2988                    PositionedLayoutItem::GlyphRun(glyph_run) => {
2989                        if !is_in_target(glyph_run.style().brush.id) {
2990                            continue;
2991                        }
2992                        let x0 = glyph_run.offset() as f64;
2993                        let x1 = x0 + glyph_run.advance() as f64;
2994                        // Use the line box's block extent rather than the
2995                        // run's font ascent/descent: fonts with small
2996                        // typographic metrics would otherwise produce rects
2997                        // that clip the rendered glyphs. This matches the
2998                        // geometry used for text selection highlights.
2999                        let y0 = line_metrics.block_min_coord as f64;
3000                        let y1 = line_metrics.block_max_coord as f64;
3001                        add(x0, y0, x1, y1);
3002                    }
3003                    PositionedLayoutItem::InlineBox(inline_box) => {
3004                        if !is_in_target(NodeId::from_u64(inline_box.id)) {
3005                            continue;
3006                        }
3007                        let x0 = inline_box.x as f64;
3008                        let y0 = inline_box.y as f64;
3009                        add(
3010                            x0,
3011                            y0,
3012                            x0 + inline_box.width as f64,
3013                            y0 + inline_box.height as f64,
3014                        );
3015                    }
3016                }
3017            }
3018
3019            if let Some((x0, y0, x1, y1)) = line_rect {
3020                rects.push(BoundingRect {
3021                    x: origin_x + x0 / scale,
3022                    y: origin_y + y0 / scale,
3023                    width: (x1 - x0) / scale,
3024                    height: (y1 - y0) / scale,
3025                });
3026            }
3027        }
3028
3029        Some(rects)
3030    }
3031
3032    pub fn find_title_node(&self) -> Option<&Node> {
3033        TreeTraverser::new(self)
3034            .find(|node_id| {
3035                let node = &self.nodes[*node_id];
3036                let Some(element) = node.element_data() else {
3037                    return false;
3038                };
3039                if element.name.ns != ns!(html) || element.name.local != local_name!("title") {
3040                    return false;
3041                }
3042                node.parent
3043                    .and_then(|parent_id| self.nodes.get(parent_id))
3044                    .and_then(Node::element_data)
3045                    .is_some_and(|parent| {
3046                        parent.name.ns == ns!(html) && parent.name.local == local_name!("head")
3047                    })
3048            })
3049            .map(|node_id| &self.nodes[node_id])
3050    }
3051
3052    pub fn with_text_input(
3053        &mut self,
3054        node_id: NodeId,
3055        cb: impl FnOnce(PlainEditorDriver<TextBrush>),
3056    ) {
3057        let Some(node) = self.nodes.get_mut(node_id) else {
3058            return;
3059        };
3060
3061        if let Some(text_input) = node
3062            .element_data_mut()
3063            .and_then(|el| el.text_input_data_mut())
3064        {
3065            let mut font_ctx = self.font_ctx.lock().unwrap();
3066            let layout_ctx = &mut self.layout_ctx;
3067            let driver = text_input.editor.driver(&mut font_ctx, layout_ctx);
3068            cb(driver)
3069        }
3070    }
3071
3072    /// Recompute the scroll offset of the text input at `node_id` (if any) so that its caret
3073    /// remains visible within the input's content box.
3074    pub(crate) fn clamp_text_input_scroll(&mut self, node_id: NodeId) {
3075        let Some(node) = self.nodes.get_mut(node_id) else {
3076            return;
3077        };
3078
3079        let content_box_width = node.final_layout().content_box_width();
3080        let content_box_height = node.final_layout().content_box_height();
3081
3082        if let Some(text_input) = node
3083            .element_data_mut()
3084            .and_then(|el| el.text_input_data_mut())
3085        {
3086            text_input.clamp_scroll_offset(content_box_width, content_box_height);
3087        }
3088    }
3089
3090    pub(crate) fn compute_has_canvas(&self) -> bool {
3091        TreeTraverser::new(self).any(|node_id| {
3092            let node = &self.nodes[node_id];
3093            let Some(element) = node.element_data() else {
3094                return false;
3095            };
3096            if element.name.local == local_name!("canvas") && element.has_attr(local_name!("src")) {
3097                return true;
3098            }
3099
3100            false
3101        })
3102    }
3103
3104    // Text selection methods
3105
3106    /// Find the text position (inline_root_id, byte_offset) at a given point.
3107    /// Uses hit() for proper coordinate transformation, then finds the inline root
3108    /// and byte offset.
3109    pub fn find_text_position(&self, x: f32, y: f32) -> Option<(NodeId, usize)> {
3110        let hit = self.hit(x, y)?;
3111        let hit_node = self.get_node(hit.node_id)?;
3112        let inline_root = hit_node.inline_root_ancestor()?;
3113        let byte_offset = inline_root.text_offset_at_point(hit.x, hit.y)?;
3114        Some((inline_root.id, byte_offset))
3115    }
3116
3117    /// Find the word or line at a point, as `(inline_root_id, start, end)`.
3118    ///
3119    /// The multi-click counterpart of
3120    /// [`find_text_position`](Self::find_text_position): that one answers where
3121    /// a caret goes, this one answers what a double or triple click selects.
3122    pub fn find_text_range(
3123        &self,
3124        x: f32,
3125        y: f32,
3126        granularity: TextGranularity,
3127    ) -> Option<(NodeId, usize, usize)> {
3128        let hit = self.hit(x, y)?;
3129        let hit_node = self.get_node(hit.node_id)?;
3130        let inline_root = hit_node.inline_root_ancestor()?;
3131        let range = inline_root.text_range_at_point(hit.x, hit.y, granularity)?;
3132        Some((inline_root.id, range.start, range.end))
3133    }
3134
3135    /// Set the text selection range (creates a new selection from anchor to focus)
3136    pub fn set_text_selection(
3137        &mut self,
3138        anchor_node: NodeId,
3139        anchor_offset: usize,
3140        focus_node: NodeId,
3141        focus_offset: usize,
3142    ) {
3143        self.text_selection =
3144            TextSelection::new(anchor_node, anchor_offset, focus_node, focus_offset);
3145
3146        // For anonymous blocks, switch to storing parent+sibling_index (stable reference)
3147        if let (Some(parent), Some(idx)) = self.anonymous_block_location(anchor_node) {
3148            self.text_selection
3149                .anchor
3150                .set_anonymous(parent, idx, anchor_offset);
3151        }
3152        if let (Some(parent), Some(idx)) = self.anonymous_block_location(focus_node) {
3153            self.text_selection
3154                .focus
3155                .set_anonymous(parent, idx, focus_offset);
3156        }
3157    }
3158
3159    /// Get the parent ID and sibling index for a node if it's an anonymous block.
3160    /// Returns (None, None) for non-anonymous blocks.
3161    fn anonymous_block_location(&self, node_id: NodeId) -> (Option<NodeId>, Option<usize>) {
3162        let Some(node) = self.get_node(node_id) else {
3163            return (None, None);
3164        };
3165
3166        if !node.is_anonymous() {
3167            return (None, None);
3168        }
3169
3170        let Some(parent_id) = node.parent else {
3171            return (None, None);
3172        };
3173
3174        let Some(parent) = self.get_node(parent_id) else {
3175            return (Some(parent_id), None);
3176        };
3177
3178        let layout_children = parent.layout_children.borrow();
3179        let Some(children) = layout_children.as_ref() else {
3180            return (Some(parent_id), None);
3181        };
3182
3183        // Find the index of this anonymous block among siblings
3184        let mut anon_index = 0;
3185        for &child_id in children.iter() {
3186            if child_id == node_id {
3187                return (Some(parent_id), Some(anon_index));
3188            }
3189            if self.get_node(child_id).is_some_and(|n| n.is_anonymous()) {
3190                anon_index += 1;
3191            }
3192        }
3193
3194        (Some(parent_id), None)
3195    }
3196
3197    /// Clear the text selection
3198    pub fn clear_text_selection(&mut self) {
3199        self.text_selection.clear();
3200    }
3201
3202    /// Update the selection focus point (used during mouse drag to extend selection).
3203    pub fn update_selection_focus(&mut self, focus_node: NodeId, focus_offset: usize) {
3204        // For anonymous blocks, store parent+sibling_index; otherwise store node directly
3205        if let (Some(parent), Some(idx)) = self.anonymous_block_location(focus_node) {
3206            self.text_selection
3207                .focus
3208                .set_anonymous(parent, idx, focus_offset);
3209        } else {
3210            self.text_selection.set_focus(focus_node, focus_offset);
3211        }
3212    }
3213
3214    /// Extend text selection to the given point. Returns true if selection was updated.
3215    /// This is a convenience method that combines find_text_position and update_selection_focus.
3216    pub fn extend_text_selection_to_point(&mut self, x: f32, y: f32) -> bool {
3217        if !self.text_selection.anchor.is_some() {
3218            return false;
3219        }
3220
3221        if let Some((node, offset)) = self.find_text_position(x, y) {
3222            self.update_selection_focus(node, offset);
3223            self.shell_provider.request_redraw();
3224            true
3225        } else {
3226            false
3227        }
3228    }
3229
3230    /// Find the Nth anonymous block under a parent.
3231    fn find_anonymous_block_by_index(
3232        &self,
3233        parent_id: NodeId,
3234        target_index: usize,
3235    ) -> Option<NodeId> {
3236        let parent = self.get_node(parent_id)?;
3237        let layout_children = parent.layout_children.borrow();
3238        let children = layout_children.as_ref()?;
3239
3240        children
3241            .iter()
3242            .filter(|&&child_id| self.get_node(child_id).is_some_and(|n| n.is_anonymous()))
3243            .nth(target_index)
3244            .copied()
3245    }
3246
3247    /// Check if there is an active (non-empty) text selection
3248    pub fn has_text_selection(&self) -> bool {
3249        self.text_selection.is_active()
3250    }
3251
3252    /// Get the selected text content, supporting selection across multiple inline roots.
3253    pub fn get_selected_text(&self) -> Option<String> {
3254        let ranges = self.get_text_selection_ranges();
3255        if ranges.is_empty() {
3256            return None;
3257        }
3258
3259        let mut result = String::new();
3260        for (node_id, start, end) in &ranges {
3261            let node = self.get_node(*node_id)?;
3262            let element_data = node.element_data()?;
3263            let inline_layout = element_data.inline_layout_data.as_ref()?;
3264
3265            if *end > inline_layout.text.len() {
3266                continue;
3267            }
3268
3269            if !result.is_empty() {
3270                result.push(' ');
3271            }
3272            result.push_str(&inline_layout.text[*start..*end]);
3273        }
3274
3275        if result.is_empty() {
3276            None
3277        } else {
3278            Some(result)
3279        }
3280    }
3281
3282    /// Get all selection ranges as Vec<(node_id, start_offset, end_offset)>.
3283    /// Returns empty vec if no selection.
3284    pub fn get_text_selection_ranges(&self) -> Vec<(NodeId, usize, usize)> {
3285        let lookup = |parent_id, idx| self.find_anonymous_block_by_index(parent_id, idx);
3286
3287        let anchor_node = match self.text_selection.anchor.resolve_node_id(lookup) {
3288            Some(id) => id,
3289            None => return Vec::new(),
3290        };
3291        let focus_node = match self.text_selection.focus.resolve_node_id(lookup) {
3292            Some(id) => id,
3293            None => return Vec::new(),
3294        };
3295
3296        // Guard against stale selection endpoints: nodes may have been removed from
3297        // the document (e.g. by script) since the selection was made.
3298        let node_is_in_doc = |node_id: NodeId| {
3299            self.nodes
3300                .get(node_id)
3301                .is_some_and(|node| node.flags.is_in_document())
3302        };
3303        if !node_is_in_doc(anchor_node) || !node_is_in_doc(focus_node) {
3304            return Vec::new();
3305        }
3306
3307        // Single node selection
3308        if anchor_node == focus_node {
3309            let start = self
3310                .text_selection
3311                .anchor
3312                .offset
3313                .min(self.text_selection.focus.offset);
3314            let end = self
3315                .text_selection
3316                .anchor
3317                .offset
3318                .max(self.text_selection.focus.offset);
3319
3320            if start == end {
3321                return Vec::new();
3322            }
3323            return vec![(anchor_node, start, end)];
3324        }
3325
3326        // Multi-node selection: collect all inline roots between anchor and focus
3327        let inline_roots = self.collect_inline_roots_in_range(anchor_node, focus_node);
3328        if inline_roots.is_empty() {
3329            return Vec::new();
3330        }
3331
3332        // Determine document order using the collected inline_roots order
3333        // (inline_roots is already in document order from first to last)
3334        let first_in_roots = inline_roots[0];
3335
3336        let (first_node, first_offset, last_node, last_offset) =
3337            if first_in_roots == anchor_node || (first_in_roots != focus_node) {
3338                // anchor is first (or neither endpoint is in roots, which shouldn't happen)
3339                (
3340                    anchor_node,
3341                    self.text_selection.anchor.offset,
3342                    focus_node,
3343                    self.text_selection.focus.offset,
3344                )
3345            } else {
3346                // focus is first
3347                (
3348                    focus_node,
3349                    self.text_selection.focus.offset,
3350                    anchor_node,
3351                    self.text_selection.anchor.offset,
3352                )
3353            };
3354
3355        let mut ranges = Vec::with_capacity(inline_roots.len());
3356
3357        for &node_id in &inline_roots {
3358            let Some(node) = self.get_node(node_id) else {
3359                continue;
3360            };
3361            let Some(element_data) = node.element_data() else {
3362                continue;
3363            };
3364            let Some(inline_layout) = element_data.inline_layout_data.as_ref() else {
3365                continue;
3366            };
3367
3368            let text_len = inline_layout.text.len();
3369
3370            if node_id == first_node && node_id == last_node {
3371                let start = first_offset.min(last_offset);
3372                let end = first_offset.max(last_offset);
3373                if start < end && end <= text_len {
3374                    ranges.push((node_id, start, end));
3375                }
3376            } else if node_id == first_node {
3377                if first_offset < text_len {
3378                    ranges.push((node_id, first_offset, text_len));
3379                }
3380            } else if node_id == last_node {
3381                if last_offset > 0 && last_offset <= text_len {
3382                    ranges.push((node_id, 0, last_offset));
3383                }
3384            } else if text_len > 0 {
3385                ranges.push((node_id, 0, text_len));
3386            }
3387        }
3388
3389        ranges
3390    }
3391}
3392
3393#[derive(Debug, Clone, Copy, PartialEq)]
3394pub struct BoundingRect {
3395    pub x: f64,
3396    pub y: f64,
3397    pub width: f64,
3398    pub height: f64,
3399}
3400
3401impl AsRef<BaseDocument> for BaseDocument {
3402    fn as_ref(&self) -> &BaseDocument {
3403        self
3404    }
3405}
3406
3407impl AsMut<BaseDocument> for BaseDocument {
3408    fn as_mut(&mut self) -> &mut BaseDocument {
3409        self
3410    }
3411}
3412
3413#[cfg(test)]
3414mod hover_state_tests {
3415    use super::*;
3416    use crate::{Attribute, qual_name};
3417    use blitz_traits::shell::ColorScheme;
3418
3419    /// Build `<html><body style="margin:0"><div style="width:300px">some text
3420    /// <div style="height:50px"></div></div></body></html>` manually (the HTML
3421    /// parser lives in blitz-html, which would be a circular dev-dependency).
3422    /// The bare text next to a block sibling gets wrapped in an anonymous
3423    /// block, which becomes the inline root: text hits report the anonymous
3424    /// block as the hit node.
3425    fn make_doc() -> (BaseDocument, NodeId) {
3426        let mut doc = BaseDocument::new(DocumentConfig {
3427            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
3428            ..Default::default()
3429        });
3430        let root_id = doc.root_node().id;
3431        let style = |value: &str| Attribute {
3432            name: qual_name!("style"),
3433            value: value.to_string(),
3434        };
3435
3436        let mut mutator = doc.mutate();
3437        let html = mutator.create_element(qual_name!("html"), vec![]);
3438        let body = mutator.create_element(qual_name!("body"), vec![style("margin:0")]);
3439        let container = mutator.create_element(qual_name!("div"), vec![style("width:300px")]);
3440        let text = mutator.create_text_node("some text");
3441        let block = mutator.create_element(qual_name!("div"), vec![style("height:50px")]);
3442        mutator.append_children(container, &[text, block]);
3443        mutator.append_children(body, &[container]);
3444        mutator.append_children(html, &[body]);
3445        mutator.append_children(root_id, &[html]);
3446        drop(mutator);
3447
3448        doc.resolve(0.0);
3449        (doc, container)
3450    }
3451
3452    /// Whether text laid out with a real (non-zero-metric) font. Without the
3453    /// `system-fonts` feature text measures 0x0 and text hits are impossible,
3454    /// making these tests vacuous.
3455    fn text_has_size(doc: &BaseDocument, container: NodeId) -> bool {
3456        doc.nodes[container].final_layout().size.height > 50.0
3457    }
3458
3459    /// Regression test: hovering bare text wrapped in an anonymous block must
3460    /// report a text cursor. The hit node for such text is the anonymous
3461    /// inline root itself, while the *stored* hover target is canonicalized to
3462    /// the containing element — the cursor must be derived from the precise
3463    /// hit node, not the canonical target.
3464    #[test]
3465    fn hovering_text_in_anonymous_block_reports_text_cursor() {
3466        let (mut doc, container) = make_doc();
3467        if !text_has_size(&doc, container) {
3468            eprintln!("skipping: no usable font (text measures 0x0)");
3469            return;
3470        }
3471
3472        doc.set_hover_to(5.0, 8.0);
3473        assert!(doc.hover_node_is_text, "expected a text hit");
3474        let hit_id = doc.hover_hit_node_id.expect("expected a hit node");
3475        assert!(
3476            doc.nodes[hit_id].is_anonymous(),
3477            "expected the hit node to be the anonymous inline root"
3478        );
3479        assert_eq!(
3480            doc.get_hover_node_id(),
3481            Some(container),
3482            "expected the stored hover target to be the containing element"
3483        );
3484        assert_eq!(doc.get_cursor(), Some(CursorIcon::Text));
3485    }
3486
3487    /// Hovering the empty region of the anonymous block (right of the text) is
3488    /// not a text hit: default cursor, same canonical hover target.
3489    #[test]
3490    fn hovering_anonymous_block_whitespace_reports_default_cursor() {
3491        let (mut doc, container) = make_doc();
3492        if !text_has_size(&doc, container) {
3493            eprintln!("skipping: no usable font (text measures 0x0)");
3494            return;
3495        }
3496
3497        doc.set_hover_to(250.0, 8.0);
3498        assert!(!doc.hover_node_is_text);
3499        assert_eq!(doc.get_hover_node_id(), Some(container));
3500        assert_eq!(doc.get_cursor(), Some(CursorIcon::Default));
3501    }
3502}
3503
3504#[cfg(test)]
3505mod font_face_override_tests {
3506    use super::*;
3507    use crate::net::{FontFaceOverrides, Resource, ResourceLoadResponse};
3508
3509    /// Regression-pin for the `@font-face` descriptor-honouring fix.
3510    ///
3511    /// The bug was that `Resource::Font` carried only the raw font bytes,
3512    /// so `load_resource` registered fonts with `info_override = None` and
3513    /// parley fell back to the TTF's internal `name` table. After the fix,
3514    /// `Resource::Font` carries `FontFaceOverrides` and `load_resource`
3515    /// builds a `FontInfoOverride` from them — meaning a CSS-declared
3516    /// `font-family` alias wins over the file's own metadata.
3517    ///
3518    /// We drive `load_resource` directly with a fabricated response rather
3519    /// than go through HTML parsing → `fetch_font_face`, because the
3520    /// downstream HTML parser lives in `blitz-html` (would be a circular
3521    /// crate dependency). The mapping from `@font-face` descriptors into
3522    /// `FontFaceOverrides` is covered by the unit tests in `net.rs`; this
3523    /// test pins the load-side of the pipeline.
3524    #[test]
3525    fn font_face_overrides_alias_family_name() {
3526        const ALIAS: &str = "AliasedFamily";
3527
3528        let mut document = BaseDocument::new(DocumentConfig::default());
3529
3530        // Sanity: the alias name is not registered before we feed the font.
3531        {
3532            let mut ctx = document.font_ctx.lock().unwrap();
3533            assert!(
3534                ctx.collection.family_id(ALIAS).is_none(),
3535                "alias must not exist before registration",
3536            );
3537        }
3538
3539        // Drive `load_resource` with a `Resource::Font` whose overrides
3540        // assert the CSS-side family name. We use the bullet font as a
3541        // valid font payload — its internal `name` table is irrelevant to
3542        // the assertion; what matters is whether the override wins.
3543        let response = ResourceLoadResponse {
3544            request_id: 0,
3545            node_id: None,
3546            resolved_url: Some(String::from("test://aliased-family")),
3547            result: Ok(Resource::Font(
3548                blitz_traits::net::Bytes::from_static(crate::BULLET_FONT),
3549                FontFaceOverrides {
3550                    family_name: Some(String::from(ALIAS)),
3551                    weight: Some(800.0),
3552                    style: Some(parley::fontique::FontStyle::Italic),
3553                },
3554            )),
3555        };
3556        document.load_resource(response);
3557
3558        // The override must have taken effect: parley's `Collection` now
3559        // resolves the CSS-declared alias to a registered family.
3560        let mut ctx = document.font_ctx.lock().unwrap();
3561        let family_id = ctx
3562            .collection
3563            .family_id(ALIAS)
3564            .expect("CSS-declared family name should be registered as a family alias");
3565        let resolved_name = ctx
3566            .collection
3567            .family_name(family_id)
3568            .expect("family id should resolve back to a name");
3569        assert_eq!(
3570            resolved_name, ALIAS,
3571            "registered family should report the CSS-declared name, \
3572             not the font file's internal `name` table entry",
3573        );
3574    }
3575}