Skip to main content

blitz_dom/
document.rs

1use crate::NodeTree;
2use crate::deferred_font_context::DeferredFontContext;
3use crate::events::{DragMode, ScrollAnimationState, handle_dom_event};
4use crate::font_metrics::BlitzFontMetricsProvider;
5use crate::layout::construct::ConstructionTask;
6use crate::layout::damage::ALL_DAMAGE;
7use crate::mutator::ViewportMut;
8use crate::net::{
9    Resource, ResourceHandler, ResourceLoadResponse, StylesheetHandler, StylesheetLoader,
10};
11use crate::node::{
12    ImageData, NodeFlags, RasterImageData, SpecialElementData, Status, TextBrush, TextGranularity,
13};
14use crate::selection::TextSelection;
15use crate::stylo_to_cursor_icon::stylo_to_cursor_icon;
16use crate::traversal::TreeTraverser;
17use crate::url::DocumentUrl;
18use crate::util::ImageType;
19use crate::{
20    DEFAULT_CSS, DocumentConfig, DocumentMutator, DummyHtmlParserProvider, ElementData,
21    EventDriver, HtmlParserProvider, Node, NodeData, NoopEventHandler, StyleThreading,
22    TextNodeData,
23};
24use blitz_traits::devtools::DevtoolSettings;
25use blitz_traits::events::{BlitzScrollEvent, DomEvent, DomEventData, HitResult, UiEvent};
26use blitz_traits::handoff::{EventQueue, EventTarget};
27use blitz_traits::navigation::{DummyNavigationProvider, NavigationProvider};
28use blitz_traits::net::{AbortSignal, DummyNetProvider, NetProvider, Request, RequestDestination};
29use blitz_traits::node_id::NodeId;
30use blitz_traits::shell::{ColorScheme, DummyShellProvider, ShellProvider, Viewport};
31use cursor_icon::CursorIcon;
32use linebender_resource_handle::Blob;
33use markup5ever::{local_name, ns};
34use parley::PlainEditorDriver;
35use rustc_hash::FxHashSet;
36use selectors::{Element, matching::QuirksMode};
37use smallvec::SmallVec;
38use std::any::Any;
39use std::cell::RefCell;
40use std::collections::{BTreeMap, Bound, HashMap, HashSet};
41use std::ops::{Deref, DerefMut};
42use std::rc::Rc;
43use std::str::FromStr;
44use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
45use std::sync::{Arc, MutexGuard, OnceLock, RwLockReadGuard, RwLockWriteGuard};
46use std::task::{Context as TaskContext, Waker};
47use style::Atom;
48use style::animation::{AnimationState, DocumentAnimationSet};
49use style::attr::{AttrIdentifier, AttrValue};
50use style::data::{ElementData as StyloElementData, ElementStyles};
51use style::invalidation::element::restyle_hints::RestyleHint;
52use style::media_queries::MediaType;
53use style::properties::ComputedValues;
54use style::properties::style_structs::Font;
55use style::queries::values::PrefersColorScheme;
56use style::selector_parser::ServoElementSnapshot;
57use style::servo::media_features::PointerCapabilities;
58use style::servo_arc::Arc as ServoArc;
59use style::values::GenericAtomIdent;
60use style::values::computed::ui::CursorKind;
61use style::values::computed::{Overflow, UserSelect};
62use style::values::specified::box_::{DisplayInside, DisplayOutside};
63use style::{
64    device::Device,
65    dom::{TDocument, TNode},
66    media_queries::MediaList,
67    selector_parser::SnapshotMap,
68    shared_lock::{SharedRwLock, StylesheetGuards},
69    stylesheets::{AllowImportRules, DocumentStyleSheet, Origin, Stylesheet},
70    stylist::Stylist,
71};
72use url::Url;
73use web_time::Instant;
74
75static DEFAULT_CSS_TEMPLATE: OnceLock<Stylesheet> = OnceLock::new();
76
77#[cfg(feature = "parallel-construct")]
78use thread_local::ThreadLocal;
79
80pub enum DocGuard<'a> {
81    Ref(&'a BaseDocument),
82    RefCell(std::cell::Ref<'a, BaseDocument>),
83    RwLock(RwLockReadGuard<'a, BaseDocument>),
84    Mutex(MutexGuard<'a, BaseDocument>),
85}
86
87impl Deref for DocGuard<'_> {
88    type Target = BaseDocument;
89    #[inline(always)]
90    fn deref(&self) -> &Self::Target {
91        match self {
92            Self::Ref(base_document) => base_document,
93            Self::RefCell(refcell_guard) => refcell_guard,
94            Self::RwLock(rw_lock_read_guard) => rw_lock_read_guard,
95            Self::Mutex(mutex_guard) => mutex_guard,
96        }
97    }
98}
99
100pub enum DocGuardMut<'a> {
101    Ref(&'a mut BaseDocument),
102    RefCell(std::cell::RefMut<'a, BaseDocument>),
103    RwLock(RwLockWriteGuard<'a, BaseDocument>),
104    Mutex(MutexGuard<'a, BaseDocument>),
105}
106
107impl Deref for DocGuardMut<'_> {
108    type Target = BaseDocument;
109    #[inline(always)]
110    fn deref(&self) -> &Self::Target {
111        match self {
112            Self::Ref(base_document) => base_document,
113            Self::RefCell(refcell_guard) => refcell_guard,
114            Self::RwLock(rw_lock_read_guard) => rw_lock_read_guard,
115            Self::Mutex(mutex_guard) => mutex_guard,
116        }
117    }
118}
119
120impl DerefMut for DocGuardMut<'_> {
121    #[inline(always)]
122    fn deref_mut(&mut self) -> &mut Self::Target {
123        match self {
124            Self::Ref(base_document) => base_document,
125            Self::RefCell(refcell_guard) => &mut *refcell_guard,
126            Self::RwLock(rw_lock_read_guard) => &mut *rw_lock_read_guard,
127            Self::Mutex(mutex_guard) => &mut *mutex_guard,
128        }
129    }
130}
131
132/// Abstraction over wrappers around [`BaseDocument`] to allow for them all to
133/// be driven by [`blitz-shell`](https://docs.rs/blitz-shell)
134pub trait Document: Any + 'static {
135    fn inner(&self) -> DocGuard<'_>;
136    fn inner_mut(&mut self) -> DocGuardMut<'_>;
137
138    /// Update the [`Document`] in response to a [`UiEvent`] (click, keypress, etc)
139    fn handle_ui_event(&mut self, event: UiEvent) {
140        if self.inner().page_frozen || self.inner().page_retiring || self.inner().page_input_blocked
141        {
142            return;
143        }
144        let mut doc = self.inner_mut();
145        let mut driver = EventDriver::new(&mut *doc, NoopEventHandler);
146        driver.handle_ui_event(event);
147    }
148
149    /// Poll any pending async operations, and flush changes to the underlying [`BaseDocument`]
150    fn poll(&mut self, task_context: Option<TaskContext>) -> bool {
151        // Default implementation does nothing
152        let _ = task_context;
153        false
154    }
155
156    /// Drain immediate work for a host's settle loop.
157    ///
158    /// Pass `run_timers = true` only on the first pass to allow one batch of
159    /// due timer and animation callbacks. Subsequent passes must leave those
160    /// callbacks scheduled while draining scripts and microtasks.
161    ///
162    /// Documents that execute timers must override this method. Wrappers that
163    /// poll child documents must propagate the policy to their children.
164    fn poll_for_settle(&mut self, task_context: Option<TaskContext>, run_timers: bool) -> bool {
165        let _ = run_timers;
166        self.poll(task_context)
167    }
168
169    /// Revoke child work before ownership is dropped. Completion is separate.
170    fn prepare_teardown(&mut self) {
171        self.inner_mut().prepare_teardown();
172    }
173
174    fn dispose(mut self: Box<Self>) -> Arc<crate::release::Teardown> {
175        self.prepare_teardown();
176        let receipt = Arc::clone(&self.inner().teardown);
177        drop(self);
178        receipt
179    }
180
181    fn set_page_visible(&mut self, visible: bool) {
182        self.inner_mut().page_visible = visible;
183    }
184    fn freeze(&mut self) {
185        self.inner_mut().page_frozen = true;
186    }
187    fn finish_restore(&mut self) {
188        self.inner_mut().page_input_blocked = false;
189    }
190    fn resume(&mut self) {
191        self.inner_mut().page_frozen = false;
192    }
193
194    /// Get the [`Document`]'s id
195    fn id(&self) -> usize {
196        self.inner().id
197    }
198}
199
200/// What the pre-click activation steps changed, so a cancelled click can put
201/// it back. Produced by [`BaseDocument::run_pre_click_activation`].
202#[derive(Debug, Clone, PartialEq)]
203pub struct PreClickActivation {
204    /// Every node whose checkedness moved, paired with the value it held.
205    previous: Vec<(NodeId, bool)>,
206    pub(crate) notification_target: Option<NodeId>,
207}
208
209/// Escape text for inclusion in an HTML clipboard payload.
210///
211/// The five characters that would otherwise be read as markup. A selection is
212/// document text, so a paragraph containing `a < b` must arrive as `a &lt; b`
213/// rather than opening a tag in whatever receives the paste.
214fn escape_html(text: &str) -> String {
215    let mut out = String::with_capacity(text.len());
216    for ch in text.chars() {
217        match ch {
218            '&' => out.push_str("&amp;"),
219            '<' => out.push_str("&lt;"),
220            '>' => out.push_str("&gt;"),
221            '"' => out.push_str("&quot;"),
222            _ => out.push(ch),
223        }
224    }
225    out
226}
227
228pub struct PlainDocument(pub BaseDocument);
229impl Document for PlainDocument {
230    fn inner(&self) -> DocGuard<'_> {
231        DocGuard::Ref(&self.0)
232    }
233    fn inner_mut(&mut self) -> DocGuardMut<'_> {
234        DocGuardMut::Ref(&mut self.0)
235    }
236}
237
238impl Document for BaseDocument {
239    fn inner(&self) -> DocGuard<'_> {
240        DocGuard::Ref(self)
241    }
242    fn inner_mut(&mut self) -> DocGuardMut<'_> {
243        DocGuardMut::Ref(self)
244    }
245}
246
247impl Document for Rc<RefCell<BaseDocument>> {
248    fn inner(&self) -> DocGuard<'_> {
249        DocGuard::RefCell(self.borrow())
250    }
251
252    fn inner_mut(&mut self) -> DocGuardMut<'_> {
253        DocGuardMut::RefCell(self.borrow_mut())
254    }
255}
256
257pub enum DocumentEvent {
258    ResourceLoad(ResourceLoadResponse),
259    /// A navigation originating from within an iframe's sub-document
260    /// (e.g. a link click), to be applied to the iframe identified by `node_id`.
261    NavigateIframe {
262        node_id: NodeId,
263        url: Url,
264    },
265}
266
267/// How urgently a document needs another animation frame.
268#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
269pub enum AnimationPacing {
270    Idle,
271    Caret,
272    SlowCss,
273    Interactive,
274}
275
276pub struct BaseDocument {
277    /// ID of the document
278    id: usize,
279
280    // Config
281    /// Base url for resolving linked resources (stylesheets, images, fonts, etc)
282    pub(crate) url: DocumentUrl,
283    pub(crate) selector_cache: RefCell<crate::query_selector::SelectorCache>,
284    // Devtool settings. Currently used to render debug overlays
285    pub(crate) devtool_settings: DevtoolSettings,
286    // Viewport details such as the dimensions, HiDPI scale, and zoom factor,
287    pub(crate) viewport: Viewport,
288    // Scroll within our viewport
289    pub(crate) viewport_scroll: crate::Point<f64>,
290    /// Changes recorded for a script's `MutationObserver`, or `None` while no
291    /// observer is registered. See [`crate::DomMutation`].
292    pub(crate) mutation_log: Option<Vec<crate::DomMutation>>,
293    /// Content handler changes, independent of MutationObserver recording.
294    inline_handler_changes: Vec<(NodeId, crate::QualName, Option<crate::node::AttrAtom>)>,
295    /// Weak registrations make pages without live ranges pay only a branch.
296    pub(crate) live_ranges: Vec<crate::range::WeakRange>,
297    /// Script Selection shares the same live range object as getRangeAt().
298    pub dom_selection: Option<crate::LiveRange>,
299    /// CSS media type used to evaluate `@media` rules.
300    pub(crate) media_type: MediaType,
301    /// Strategy for Stylo's style traversal during `resolve`.
302    pub(crate) style_threading: StyleThreading,
303    /// Whether incremental layout is enabled for this document.
304    pub(crate) incremental_layout: bool,
305    /// How deeply this document is nested within other documents
306    /// (0 for a root document). Used to limit `<iframe>` nesting depth.
307    pub(crate) subdocument_depth: usize,
308
309    // Events
310    pub(crate) tx: EventTarget<DocumentEvent>,
311    pub(crate) rx: EventQueue<DocumentEvent>,
312
313    /// A slotmap-backed tree of nodes
314    ///
315    /// We pin the tree to a guarantee to the nodes it creates that the tree is stable in memory.
316    /// There is no way to create the tree - publicly or privately - that would invalidate that invariant.
317    pub(crate) nodes: Box<NodeTree>,
318
319    /// Batch cache invalidation across recursive subtree teardown.
320    node_drop_depth: usize,
321    /// Active mutation scopes defer redraw until the outermost scope ends.
322    pub(crate) mutator_depth: usize,
323    pub(crate) mutator_redraw_pending: bool,
324    /// `<details>` elements whose `open` attribute appeared or disappeared since the script
325    /// runtime last took them, each with whether it was open before its first change. The
326    /// HTML toggle task coalesces per element, so an element is listed once.
327    details_toggles: Vec<(NodeId, bool)>,
328    /// Bumped whenever the stylist device changes (viewport size, scale or colour scheme),
329    /// so script can skip re-evaluating media queries while it stays the same.
330    viewport_generation: u64,
331    /// Bumped each time a Stylo traversal restyles the tree. A resolve that
332    /// finds nothing to restyle leaves it alone, so an inspector can tell a
333    /// style change from an idle frame.
334    pub(crate) style_revision: u64,
335    /// Bumped each time layout is computed. An incremental resolve that keeps
336    /// every box leaves it alone.
337    layout_revision: u64,
338    /// The inert document that owns every `<template>`'s contents, made on first use. It
339    /// has no browsing context, so nothing in it is upgraded as a custom element.
340    template_contents_owner: Option<NodeId>,
341    dropped_node_ids: FxHashSet<NodeId>,
342    dropped_node_parents: FxHashSet<NodeId>,
343    /// Survivors that can still point at an id freed by this batch.
344    ///
345    /// Recorded while the node is still in the slab. The purge runs after a
346    /// subtree drop has already removed those nodes, so the links have to be
347    /// captured first.
348    dropped_reference_owners: FxHashSet<NodeId>,
349
350    /// The id of the root node (a Document node)
351    pub(crate) root_node_id: NodeId,
352
353    /// For each `position: fixed` node reparented onto the root element, the
354    /// layout parent it was taken from.
355    ///
356    /// Hoisting gives a fixed node the viewport as its containing block, which
357    /// is what CSS asks for. It must not also decide which stacking context the
358    /// node paints in: that follows the box tree, and the two are independent.
359    /// Without this record the node joins the root's stacking context, so a
360    /// negative z-index fixed layer inside an `isolation: isolate` ancestor
361    /// paints beneath every background between them and disappears.
362    pub(crate) hoisted_fixed_parents: HashMap<NodeId, NodeId>,
363
364    /// Authored child slots restored temporarily for static-position layout.
365    pub(crate) hoisted_fixed_indices: HashMap<NodeId, usize>,
366
367    /// Escaped absolute boxes whose explicit axes follow a containing block.
368    pub(crate) abspos_placements: Vec<crate::layout::abspos::AbsposPlacement>,
369
370    /// Maintained during the existing fixed/sticky walk on style or tree changes.
371    pub(crate) abspos_candidates: Vec<crate::layout::abspos::AbsposCandidate>,
372    pub(crate) abspos_candidate_ids: HashSet<NodeId>,
373    pub(crate) abspos_inputs: HashMap<NodeId, crate::layout::abspos::AbsposInputs>,
374    /// Candidates whose hypothetical layouts or styles were written this pass.
375    pub(crate) abspos_written: HashSet<NodeId>,
376    pub(crate) abspos_candidates_dirty: bool,
377    pub(crate) abspos_layout_dirty: bool,
378    /// Whether the normal root layout missed its PerformLayout cache.
379    pub(crate) abspos_normal_layout: bool,
380
381    /// Every `position: fixed` node whose containing block is the viewport,
382    /// which is every one of them except those under a transformed ancestor.
383    ///
384    /// Collected by the walk that hoists them, and used by
385    /// `resolve_fixed_positions` to hold them still while the page scrolls.
386    pub(crate) fixed_nodes: Vec<NodeId>,
387
388    /// The viewport scroll currently baked into those nodes' locations.
389    ///
390    /// One value for the whole document rather than one per node: the pin is
391    /// the same displacement for every fixed box, because they all share the
392    /// viewport as their containing block. Reset by `resolve_layout`, which
393    /// rewrites the locations it was added to.
394    pub(crate) fixed_scroll_offset: crate::Point<f64>,
395
396    /// Every `position: sticky` node in the document, in tree order.
397    ///
398    /// Collected by the same walk that hoists fixed nodes, because both need
399    /// one pre-order pass over the box tree and a second one would cost the
400    /// same on every frame of every document, sticky or not. Tree order matters:
401    /// a sticky box inside another sticky box is adjusted on top of its
402    /// ancestor's adjustment, so the ancestor has to be settled first.
403    pub(crate) sticky_nodes: Vec<NodeId>,
404
405    /// For each sticky node, the offset currently baked into its
406    /// `final_layout().location`.
407    ///
408    /// The adjustment is written into the box itself so that paint, hit testing
409    /// and `absolute_position` cannot disagree about where the box is. That
410    /// makes the pass non-idempotent unless it can recover the flow position it
411    /// started from, which is what this records. Cleared by `resolve_layout`,
412    /// which rewrites every location from taffy and so discards the offsets
413    /// along with them.
414    pub(crate) sticky_offsets: HashMap<NodeId, taffy::Point<f32>>,
415
416    /// Stacking contexts holding a hoisted child that an ancestor clips.
417    ///
418    /// Collected while flushing styles so that `resolve_hoisted_clips` visits
419    /// those contexts alone, rather than scanning every node in the document
420    /// after every layout to find the handful that hoist anything at all.
421    pub(crate) hoisted_clip_hosts: HashSet<NodeId>,
422
423    /// Contexts with hoisted paint children, maintained by the style flush.
424    pub(crate) hoisted_position_hosts: HashSet<NodeId>,
425
426    // Stylo
427    /// The Stylo engine
428    pub(crate) stylist: Stylist,
429    pub(crate) animations: DocumentAnimationSet,
430    /// Monotonic animation clock used by the most recent resolve.
431    ///
432    /// Embedders may inspect or capture between window frames. A diagnostic
433    /// caller historically passed `0.0` and rewound every CSS transition in
434    /// the document; retaining the high-water mark makes that impossible at
435    /// the document boundary.
436    pub(crate) last_resolve_animation_time: f64,
437    /// Stylo shared lock
438    pub(crate) guard: SharedRwLock,
439    /// Stylo invalidation map. We insert into this map prior to mutating nodes.
440    pub(crate) snapshots: SnapshotMap,
441
442    // Parley contexts
443    /// A Parley font context
444    pub(crate) font_ctx: Arc<DeferredFontContext>,
445    #[cfg(feature = "parallel-construct")]
446    /// Thread-and-document-local copies to the font context
447    pub(crate) thread_font_contexts: ThreadLocal<RefCell<Box<parley::FontContext>>>,
448    /// A Parley layout context
449    pub(crate) layout_ctx: parley::LayoutContext<TextBrush>,
450
451    /// The real (non-anonymous) node which is currently hovered (if any).
452    /// This is never a layout-generated (anonymous) node, so it remains valid
453    /// across box-tree reconstruction.
454    pub(crate) hover_node_id: Option<NodeId>,
455    /// The precise (may be anonymous) layout node under the pointer (if any).
456    /// This can be invalidated by box-tree reconstruction, and is re-resolved against
457    /// fresh layout at the end of every `resolve` pass.
458    pub(crate) hover_hit_node_id: Option<NodeId>,
459    /// Whether the node which is currently hovered is a text node/span
460    pub(crate) hover_node_is_text: bool,
461    /// The last known pointer position in client coordinates (viewport-relative, unscrolled).
462    pub(crate) last_client_pointer_position: Option<taffy::Point<f32>>,
463    /// Exact DOM target selected by semantic automation.
464    ///
465    /// Window pointers leave this empty and are re-hit-tested after layout.
466    /// An inspector already resolved identity, so re-hit-testing its synthetic
467    /// centre coordinate would silently replace that target with an overlap.
468    pub(crate) semantic_hover_node_id: Option<NodeId>,
469    /// The node which is currently focussed (if any)
470    pub(crate) focus_node_id: Option<NodeId>,
471    /// The node which is currently active (if any)
472    pub(crate) active_node_id: Option<NodeId>,
473    /// The node which recieved a mousedown event (if any)
474    pub(crate) mousedown_node_id: Option<NodeId>,
475    /// The last time a mousedown was made (for double-click detection)
476    pub(crate) last_mousedown_time: Option<Instant>,
477    /// The position where mousedown occurred (for selection drags and double-click detection)
478    pub(crate) mousedown_position: taffy::Point<f32>,
479    /// How many clicks have been made in quick succession
480    pub(crate) click_count: u16,
481    /// Whether we're currently in a text selection drag (moved 2px+ from mousedown)
482    pub(crate) drag_mode: DragMode,
483    /// The scrollbar thumb currently under the pointer, if any
484    pub(crate) hovered_scrollbar: Option<crate::node::ScrollbarRef>,
485    /// When each scroll container's overlay scrollbars were last shown
486    /// (scrolled, or the pointer left the thumb); drives their fade-out
487    pub(crate) scrollbar_activity: HashMap<NodeId, Instant>,
488    /// Whether and what kind of scroll animation is currently in progress
489    pub(crate) scroll_animation: ScrollAnimationState,
490
491    /// Text selection state (for non-input text)
492    pub(crate) text_selection: TextSelection,
493
494    // TODO: collapse animating state into a bitflags
495    /// Whether there are active CSS animations/transitions (so we should re-render every frame)
496    pub(crate) has_active_animations: bool,
497    /// Host permission to tick CSS animations and transitions.
498    pub(crate) css_animation_ticks_enabled: bool,
499    /// Whether there is a `<canvas>` element in the DOM (so we should re-render every frame)
500    pub(crate) has_canvas: bool,
501    /// The most urgent animation cadence required by any subdocument.
502    pub(crate) subdoc_animation_pacing: AnimationPacing,
503
504    /// Map of id attribute values to node IDs for fast lookups.
505    /// May contain multiple nodes for the same id: `get_element_by_id`
506    /// returns the first in tree order.
507    pub(crate) nodes_to_id: HashMap<String, SmallVec<[NodeId; 1]>>,
508    /// Map of `<style>` and `<link>` node IDs to their associated stylesheet
509    pub(crate) nodes_to_stylesheet: BTreeMap<NodeId, DocumentStyleSheet>,
510    /// `<style>`/`<link>` nodes whose sheet is in the document Stylist. Shadow
511    /// tree sheets live elsewhere, and Stylo panics on removing a sheet it
512    /// does not hold.
513    pub(crate) document_sheet_nodes: HashSet<NodeId>,
514    /// The shadow root each shadow-tree `<style>`/`<link>` sheet was installed
515    /// into. Unloading happens after the node is detached, when its root can
516    /// no longer be found by walking up, so the owner is remembered here.
517    #[cfg(feature = "shadow-dom")]
518    pub(crate) shadow_sheet_roots: HashMap<NodeId, NodeId>,
519    /// Stylesheets added by the useragent
520    /// where the key is the hashed CSS
521    pub(crate) ua_stylesheets: HashMap<String, DocumentStyleSheet>,
522    /// Whether the built-in user-agent stylesheet has not yet been created or installed.
523    pub(crate) default_ua_stylesheet_pending: bool,
524    /// Enumeration can initialize the document-owned sheet before insertion.
525    default_ua_stylesheet_cache: OnceLock<DocumentStyleSheet>,
526    /// Constructor-owned insertion anchor, stable until the first UA mutation.
527    default_ua_stylesheet_before: Option<DocumentStyleSheet>,
528    /// Map from form control node ID's to their associated forms node ID's
529    pub(crate) controls_to_form: HashMap<NodeId, NodeId>,
530    /// Nodes that contain sub documents
531    pub(crate) sub_document_nodes: HashSet<NodeId>,
532    pub stash_policy: crate::stash_policy::StashPolicy,
533    pub teardown: Arc<crate::release::Teardown>,
534    _dom_lease: crate::release::ReleaseLease,
535    pub page_visible: bool,
536    pub page_frozen: bool,
537    pub page_input_blocked: bool,
538    pub page_retiring: bool,
539    pub was_discarded: bool,
540    pub paint_revision: std::cell::Cell<u64>,
541    pub stash_paint: bool,
542    pub restore_scroll: Option<crate::Point<f64>>,
543    #[cfg(feature = "custom-widget")]
544    retired_resources: Vec<crate::release::ResourceRetirement>,
545    /// Load state (abort controller and in-flight request id) for each
546    /// `<iframe>` element whose sub-document is loaded automatically
547    pub(crate) iframe_loads: HashMap<NodeId, crate::iframe::IframeLoad>,
548    /// Nodes whose layout construction is waiting for a later pass.
549    pub(crate) deferred_construction_nodes: Vec<ConstructionTask>,
550    /// Which parts of the document differ from the previously painted frame.
551    ///
552    /// Off unless a consumer asks for it, so a document that never questions
553    /// its own frames does not pay to answer. See
554    /// [`set_paint_damage_tracking`](Self::set_paint_damage_tracking).
555    pub(crate) paint_damage: crate::paint_damage::PaintDamageTracker,
556
557    /// Nodes that contain custom widgets
558    #[cfg(feature = "custom-widget")]
559    pub(crate) custom_widget_nodes: HashSet<NodeId>,
560    /// Rendering resources allocated by custom widgets that should be deallocated during the next render
561    #[cfg(feature = "custom-widget")]
562    pub(crate) pending_resource_deallocations: Vec<anyrender::ResourceId>,
563
564    /// Registry of custom element definitions keyed by tag name
565    #[cfg(feature = "shadow-dom")]
566    pub(crate) custom_element_registry: crate::node::CustomElementRegistry,
567    /// Nodes that are shadow hosts (have an attached shadow root)
568    #[cfg(feature = "shadow-dom")]
569    pub(crate) shadow_host_nodes: HashSet<NodeId>,
570    #[cfg(feature = "shadow-dom")]
571    pub(crate) dirty_shadow_hosts: HashSet<NodeId>,
572    #[cfg(feature = "shadow-dom")]
573    pub(crate) pending_slot_changes: Vec<NodeId>,
574    #[cfg(feature = "shadow-dom")]
575    pub(crate) signaled_slots: HashSet<NodeId>,
576    #[cfg(feature = "shadow-dom")]
577    pub(crate) adopted_stylesheets: HashMap<NodeId, Vec<DocumentStyleSheet>>,
578    /// Nodes that have an attached custom element controller
579    #[cfg(feature = "shadow-dom")]
580    pub(crate) custom_element_nodes: HashSet<NodeId>,
581    /// Template element -> declarative shadow root, while that template is open
582    /// on the parser stack. Stored here because each streaming sink call builds
583    /// a new parser.
584    #[cfg(feature = "shadow-dom")]
585    pub(crate) declarative_template_shadows: HashMap<NodeId, NodeId>,
586
587    /// Native candidate index and mutation reactions for JavaScript custom elements.
588    pub(crate) script_custom_elements: crate::node::script_custom_element::Registry,
589
590    /// Cache of loaded images, keyed by URL. Allows reusing images across multiple
591    /// elements without re-fetching from the network.
592    pub(crate) image_cache: HashMap<String, ImageData>,
593
594    /// Tracks in-flight image requests. When an image is being fetched, additional
595    /// requests for the same URL are queued here instead of starting new fetches.
596    /// Value is a list of (node_id, image_type) pairs waiting for the image.
597    pub(crate) pending_images: HashMap<String, Vec<(NodeId, ImageType)>>,
598
599    /// Latest image request identity for script-visible `<img>` elements.
600    image_load_states: HashMap<NodeId, (String, u64)>,
601    image_load_outcomes: Vec<(NodeId, u64, bool)>,
602
603    // Tracks in-flight "critical" resources (e.g. stylesheets linked from the `<head>`),
604    // keyed by request id
605    pub(crate) pending_critical_resources: HashSet<usize>,
606
607    pub(crate) web_fonts: Vec<Arc<crate::net::web_fonts::WebFont>>,
608    pub(crate) font_epoch: usize,
609    document_referrer: String,
610    document_content_type: String,
611    document_window_focused: bool,
612
613    // Service providers
614    /// Network provider. Can be used to fetch assets.
615    pub net_provider: Arc<dyn NetProvider>,
616    /// Navigation provider. Can be used to navigate to a new page (bubbles up the event
617    /// on e.g. clicking a Link)
618    pub navigation_provider: Arc<dyn NavigationProvider>,
619    /// Shell provider. Can be used to request a redraw or set the cursor icon
620    pub shell_provider: Arc<dyn ShellProvider>,
621    /// HTML parser provider. Used to parse HTML for setInnerHTML
622    pub html_parser_provider: Arc<dyn HtmlParserProvider>,
623    /// Carried on every sub-resource `Request` this document issues; aborting
624    /// it cancels all in-flight fetches tied to this document. Set via
625    /// [`DocumentConfig::abort_signal`].
626    pub(crate) abort_signal: Option<AbortSignal>,
627}
628
629const MAX_PENDING_IMAGE_OUTCOMES: usize = 4096;
630
631pub(crate) fn make_device(
632    viewport: &Viewport,
633    media_type: MediaType,
634    font_ctx: Arc<DeferredFontContext>,
635) -> Device {
636    let width = viewport.window_size.0 as f32 / viewport.scale();
637    let height = viewport.window_size.1 as f32 / viewport.scale();
638    let viewport_size = euclid::Size2D::new(width, height);
639    let device_size = euclid::Size2D::new(width, height) * viewport.scale();
640    let device_pixel_ratio = euclid::Scale::new(viewport.scale());
641
642    Device::new(
643        media_type,
644        selectors::matching::QuirksMode::NoQuirks,
645        viewport_size,
646        device_size,
647        device_pixel_ratio,
648        Box::new(BlitzFontMetricsProvider { font_ctx }),
649        ComputedValues::initial_values_with_font_override(Font::initial_values()),
650        match viewport.color_scheme {
651            ColorScheme::Light => PrefersColorScheme::Light,
652            ColorScheme::Dark => PrefersColorScheme::Dark,
653        },
654        PointerCapabilities::default(),
655        PointerCapabilities::default(),
656    )
657}
658
659/// Whether layout reuses its caches, and how that can be overridden at runtime.
660///
661/// Incremental layout is on unless a caller or the environment turns it off.
662///
663/// The environment override exists so a single build can be measured both ways:
664/// with it off every `resolve` clears the Taffy cache and re-shapes every inline
665/// root from scratch, so comparing the two in separate binaries would also
666/// compare two different compilations. `BLITZ_INCREMENTAL=0` forces the old
667/// behaviour, `=1` forces the new one.
668///
669/// This used to fall back to `cfg!(feature = "incremental")`. That feature is
670/// gone, replaced by `DocumentConfig::incremental`, and for a while afterwards
671/// this function was never called at all: the config read
672/// `unwrap_or(true)` directly, so `BLITZ_INCREMENTAL` was accepted and ignored.
673fn incremental_layout_default() -> bool {
674    !matches!(
675        std::env::var("BLITZ_INCREMENTAL").ok().as_deref(),
676        Some("0" | "false" | "off")
677    )
678}
679
680impl BaseDocument {
681    /// Create a new (empty) [`BaseDocument`] with the specified configuration
682    pub fn new(config: DocumentConfig) -> Self {
683        #[cfg(feature = "log-phase-times")]
684        let mut timer =
685            debug_timer::RealDebugTimer::init_if(blitz_traits::profiling::deep_profiling_enabled());
686        #[cfg(not(feature = "log-phase-times"))]
687        let mut timer = debug_timer::DummyDebugTimer::init();
688
689        static ID_GENERATOR: AtomicUsize = AtomicUsize::new(1);
690
691        let id = ID_GENERATOR.fetch_add(1, Ordering::SeqCst);
692        let teardown = config
693            .teardown
694            .unwrap_or_else(crate::release::Teardown::new);
695
696        let defer_system_fonts = config.defer_system_fonts;
697        let (font_ctx, use_system_font_template) = match config.font_ctx {
698            Some(mut font_ctx) => {
699                font_ctx.source_cache.make_shared();
700                // font_ctx.collection.make_shared();
701                (font_ctx, false)
702            }
703            None => {
704                let system_fonts = cfg!(all(feature = "system-fonts", not(target_arch = "wasm32")))
705                    && !defer_system_fonts;
706                (crate::build_font_context(system_fonts), defer_system_fonts)
707            }
708        };
709        let font_ctx = Arc::new(DeferredFontContext::new(
710            font_ctx,
711            defer_system_fonts,
712            use_system_font_template,
713        ));
714        if let Some(fallback) = config.family_fallback {
715            crate::font_fallback::set(fallback);
716        }
717        timer.record_time("fonts");
718
719        // Make sure we turn on stylo features *before* creating the Stylist
720        style_config::set_pref!("layout.grid.enabled", true);
721        style_config::set_pref!("layout.unimplemented", true);
722        style_config::set_pref!("layout.columns.enabled", true);
723        style_config::set_pref!("layout.css.basic-shape-shape.enabled", true);
724        style_config::set_pref!("layout.threads", -1);
725
726        let default_ua_stylesheet_pending = config.ua_stylesheets.is_none();
727        let viewport = config.viewport.unwrap_or_default();
728        let media_type = config.media_type.unwrap_or_else(MediaType::screen);
729        let device = make_device(&viewport, media_type.clone(), font_ctx.clone());
730        let stylist = Stylist::new(device, QuirksMode::NoQuirks);
731        timer.record_time("device-stylist");
732        let snapshots = SnapshotMap::new();
733        let nodes = Box::new(NodeTree::new());
734        let guard = SharedRwLock::new();
735        let nodes_to_id = HashMap::new();
736
737        let base_url = config
738            .base_url
739            .and_then(|url| DocumentUrl::from_str(&url).ok())
740            .unwrap_or_default();
741
742        let net_provider = config
743            .net_provider
744            .unwrap_or_else(|| Arc::new(DummyNetProvider));
745        let navigation_provider = config
746            .navigation_provider
747            .unwrap_or_else(|| Arc::new(DummyNavigationProvider));
748        let shell_provider = config
749            .shell_provider
750            .unwrap_or_else(|| Arc::new(DummyShellProvider));
751        let html_parser_provider = config
752            .html_parser_provider
753            .unwrap_or_else(|| Arc::new(DummyHtmlParserProvider));
754
755        let wake_shell = Arc::clone(&shell_provider);
756        let rx = EventQueue::new(move || wake_shell.request_redraw());
757        let tx = rx.target();
758
759        let mut doc = Self {
760            node_drop_depth: 0,
761            mutator_depth: 0,
762            mutator_redraw_pending: false,
763            details_toggles: Vec::new(),
764            viewport_generation: 0,
765            style_revision: 0,
766            layout_revision: 0,
767            template_contents_owner: None,
768            dropped_node_ids: FxHashSet::default(),
769            dropped_node_parents: FxHashSet::default(),
770            dropped_reference_owners: FxHashSet::default(),
771            hoisted_fixed_parents: HashMap::new(),
772            hoisted_fixed_indices: HashMap::new(),
773            abspos_placements: Vec::new(),
774            abspos_candidates: Vec::new(),
775            abspos_candidate_ids: HashSet::new(),
776            abspos_inputs: HashMap::new(),
777            abspos_written: HashSet::new(),
778            abspos_candidates_dirty: true,
779            abspos_layout_dirty: true,
780            abspos_normal_layout: false,
781            fixed_nodes: Vec::new(),
782            fixed_scroll_offset: crate::Point::ZERO,
783            sticky_nodes: Vec::new(),
784            sticky_offsets: HashMap::new(),
785            hoisted_clip_hosts: HashSet::new(),
786            hoisted_position_hosts: HashSet::new(),
787            id,
788            tx,
789            rx,
790
791            guard,
792            nodes,
793            root_node_id: NodeId::default(),
794            stylist,
795            animations: DocumentAnimationSet::default(),
796            last_resolve_animation_time: 0.0,
797            snapshots,
798            nodes_to_id,
799            viewport,
800            media_type,
801            style_threading: config.style_threading,
802            incremental_layout: config
803                .incremental
804                .unwrap_or_else(incremental_layout_default),
805            subdocument_depth: config.subdocument_depth,
806            devtool_settings: DevtoolSettings::default(),
807            viewport_scroll: crate::Point::ZERO,
808            mutation_log: None,
809            inline_handler_changes: Vec::new(),
810            live_ranges: Vec::new(),
811            dom_selection: None,
812            url: base_url,
813            selector_cache: RefCell::new(crate::query_selector::SelectorCache::default()),
814            ua_stylesheets: HashMap::new(),
815            default_ua_stylesheet_pending,
816            default_ua_stylesheet_cache: OnceLock::new(),
817            default_ua_stylesheet_before: None,
818            nodes_to_stylesheet: BTreeMap::new(),
819            document_sheet_nodes: HashSet::new(),
820            #[cfg(feature = "shadow-dom")]
821            shadow_sheet_roots: HashMap::new(),
822            font_ctx,
823            #[cfg(feature = "parallel-construct")]
824            thread_font_contexts: ThreadLocal::new(),
825            layout_ctx: parley::LayoutContext::new(),
826
827            hover_node_id: None,
828            hover_hit_node_id: None,
829            hover_node_is_text: false,
830            last_client_pointer_position: None,
831            semantic_hover_node_id: None,
832            focus_node_id: None,
833            active_node_id: None,
834            mousedown_node_id: None,
835            has_active_animations: false,
836            css_animation_ticks_enabled: true,
837            subdoc_animation_pacing: AnimationPacing::Idle,
838            has_canvas: false,
839            sub_document_nodes: HashSet::new(),
840            stash_policy: Default::default(),
841            teardown: Arc::clone(&teardown),
842            _dom_lease: teardown.lease(),
843            page_visible: false,
844            page_frozen: false,
845            page_input_blocked: false,
846            page_retiring: false,
847            was_discarded: false,
848            paint_revision: std::cell::Cell::new(0),
849            stash_paint: false,
850            restore_scroll: None,
851            #[cfg(feature = "custom-widget")]
852            retired_resources: Vec::new(),
853            iframe_loads: HashMap::new(),
854
855            #[cfg(feature = "custom-widget")]
856            custom_widget_nodes: HashSet::new(),
857            #[cfg(feature = "custom-widget")]
858            pending_resource_deallocations: Vec::new(),
859
860            #[cfg(feature = "shadow-dom")]
861            custom_element_registry: crate::node::CustomElementRegistry::new(),
862            #[cfg(feature = "shadow-dom")]
863            shadow_host_nodes: HashSet::new(),
864            #[cfg(feature = "shadow-dom")]
865            dirty_shadow_hosts: HashSet::new(),
866            #[cfg(feature = "shadow-dom")]
867            pending_slot_changes: Vec::new(),
868            #[cfg(feature = "shadow-dom")]
869            signaled_slots: HashSet::new(),
870            #[cfg(feature = "shadow-dom")]
871            adopted_stylesheets: HashMap::new(),
872            #[cfg(feature = "shadow-dom")]
873            custom_element_nodes: HashSet::new(),
874            #[cfg(feature = "shadow-dom")]
875            declarative_template_shadows: HashMap::new(),
876
877            deferred_construction_nodes: Vec::new(),
878            paint_damage: Default::default(),
879            script_custom_elements: Default::default(),
880            image_cache: HashMap::new(),
881            pending_images: HashMap::new(),
882            image_load_states: HashMap::new(),
883            image_load_outcomes: Vec::new(),
884            pending_critical_resources: HashSet::new(),
885            web_fonts: Vec::new(),
886            font_epoch: 0,
887            document_referrer: String::new(),
888            document_content_type: String::from("text/html"),
889            document_window_focused: false,
890            controls_to_form: HashMap::new(),
891            net_provider,
892            navigation_provider,
893            shell_provider,
894            html_parser_provider,
895            abort_signal: config.abort_signal,
896            last_mousedown_time: None,
897            mousedown_position: taffy::Point::ZERO,
898            click_count: 0,
899            drag_mode: DragMode::None,
900            hovered_scrollbar: None,
901            scrollbar_activity: HashMap::new(),
902            scroll_animation: ScrollAnimationState::None,
903            text_selection: TextSelection::default(),
904        };
905        timer.record_time("core-state");
906
907        // Initialise document with root Document node
908        doc.root_node_id = doc.create_node(NodeData::Document(Box::default()));
909        doc.root_node_mut().flags.insert(NodeFlags::IS_IN_DOCUMENT);
910
911        // The built-in sheet is parsed and installed on the first style query
912        // or resolution. Explicit sheets retain their insertion order.
913        if let Some(stylesheets) = config.ua_stylesheets {
914            for ss in &stylesheets {
915                if ss == DEFAULT_CSS
916                    && !doc.default_ua_stylesheet_pending
917                    && !doc.ua_stylesheets.contains_key(DEFAULT_CSS)
918                {
919                    doc.default_ua_stylesheet_pending = true;
920                } else if ss == DEFAULT_CSS {
921                    // Repeated defaults preserve their original separate sheet
922                    // identities and positions, just like explicit additions.
923                    doc.add_user_agent_stylesheet(ss);
924                } else {
925                    let sheet = doc.append_user_agent_stylesheet(ss);
926                    if doc.default_ua_stylesheet_pending
927                        && doc.default_ua_stylesheet_before.is_none()
928                    {
929                        doc.default_ua_stylesheet_before = Some(sheet);
930                    }
931                }
932            }
933        }
934        timer.record_time("ua-sheet");
935
936        // Stylo data on the root node container is needed to render the node
937        let stylo_element_data = StyloElementData {
938            styles: ElementStyles {
939                primary: Some(
940                    ComputedValues::initial_values_with_font_override(Font::initial_values())
941                        .to_arc(),
942                ),
943                ..Default::default()
944            },
945            ..Default::default()
946        };
947        let stylo_data = doc.root_node_mut().stylo_element_data_mut();
948        *stylo_data.ensure_init_mut() = stylo_element_data;
949        timer.record_time("root-style");
950        timer.print_times("[blitz] document construction ");
951
952        doc
953    }
954
955    /// Set the Document's networking provider
956    pub fn set_net_provider(&mut self, net_provider: Arc<dyn NetProvider>) {
957        self.net_provider = net_provider;
958    }
959
960    /// Set the Document's navigation provider
961    pub fn set_navigation_provider(&mut self, navigation_provider: Arc<dyn NavigationProvider>) {
962        self.navigation_provider = navigation_provider;
963    }
964
965    /// Set the Document's shell provider
966    pub fn set_shell_provider(&mut self, shell_provider: Arc<dyn ShellProvider>) {
967        self.shell_provider = shell_provider;
968    }
969
970    /// Set the Document's html parser provider
971    pub fn set_html_parser_provider(&mut self, html_parser_provider: Arc<dyn HtmlParserProvider>) {
972        self.html_parser_provider = html_parser_provider;
973    }
974
975    /// Set base url for resolving linked resources (stylesheets, images, fonts, etc)
976    pub fn set_base_url(&mut self, url: &str) {
977        self.url = DocumentUrl::from(Url::parse(url).unwrap());
978        self.selector_cache.borrow_mut().clear();
979    }
980
981    pub fn guard(&self) -> &SharedRwLock {
982        &self.guard
983    }
984
985    pub fn tree(&self) -> &NodeTree {
986        &self.nodes
987    }
988
989    pub fn id(&self) -> usize {
990        self.id
991    }
992
993    /// Wrapper around [`crate::net::stamped_request`]. Use the free function
994    /// when `&self` would conflict with a held `&mut` borrow on a field.
995    pub(crate) fn build_request(&self, url: url::Url) -> Request {
996        crate::net::with_referrer(
997            crate::net::stamped_request(url, self.abort_signal.as_ref()),
998            self.url(),
999        )
1000    }
1001
1002    pub fn favicon_url(&self) -> Option<String> {
1003        self.tree().iter().find_map(|(_, node)| {
1004            let data = &node.data;
1005            if !data.is_element_with_tag_name(&local_name!("link")) {
1006                return None;
1007            }
1008            let rel = data.attr(local_name!("rel"))?;
1009            if !rel
1010                .split_ascii_whitespace()
1011                .any(|v| v.eq_ignore_ascii_case("icon"))
1012            {
1013                return None;
1014            }
1015            data.attr(local_name!("href")).map(|s| s.to_string())
1016        })
1017    }
1018
1019    pub fn get_node(&self, node_id: NodeId) -> Option<&Node> {
1020        self.nodes.get(node_id)
1021    }
1022
1023    pub fn get_node_mut(&mut self, node_id: NodeId) -> Option<&mut Node> {
1024        self.nodes.get_mut(node_id)
1025    }
1026
1027    pub fn get_focussed_node_id(&self) -> Option<NodeId> {
1028        self.focus_node_id
1029            .or(self.try_root_element().map(|el| el.id))
1030    }
1031
1032    pub fn mutate<'doc>(&'doc mut self) -> DocumentMutator<'doc> {
1033        DocumentMutator::new(self)
1034    }
1035
1036    pub fn handle_dom_event<F: FnMut(DomEvent)>(
1037        &mut self,
1038        event: &mut DomEvent,
1039        dispatch_event: F,
1040    ) {
1041        handle_dom_event(self, event, dispatch_event)
1042    }
1043
1044    pub fn as_any_mut(&mut self) -> &mut dyn Any {
1045        self
1046    }
1047
1048    /// Find the label's bound input elements:
1049    /// the element id referenced by the "for" attribute of a given label element
1050    /// or the first input element which is nested in the label
1051    /// Note that although there should only be one bound element,
1052    /// we return all possibilities instead of just the first
1053    /// in order to allow the caller to decide which one is correct
1054    pub fn label_bound_input_element(&self, label_node_id: NodeId) -> Option<&Node> {
1055        let label_element = self.nodes[label_node_id].element_data()?;
1056        if let Some(target_element_dom_id) = label_element.attr(local_name!("for")) {
1057            TreeTraverser::new(self)
1058                .filter_map(|id| {
1059                    let node = self.get_node(id)?;
1060                    let element_data = node.element_data()?;
1061                    if element_data.name.local != local_name!("input") {
1062                        return None;
1063                    }
1064                    let id = element_data.id.as_ref()?;
1065                    if *id == *target_element_dom_id {
1066                        Some(node)
1067                    } else {
1068                        None
1069                    }
1070                })
1071                .next()
1072        } else {
1073            TreeTraverser::new_with_root(self, label_node_id)
1074                .filter_map(|child_id| {
1075                    let node = self.get_node(child_id)?;
1076                    let element_data = node.element_data()?;
1077                    if element_data.name.local == local_name!("input") {
1078                        Some(node)
1079                    } else {
1080                        None
1081                    }
1082                })
1083                .next()
1084        }
1085    }
1086
1087    /// The checkedness a click changed, kept so the click's *canceled
1088    /// activation steps* can put it back when a listener calls
1089    /// `preventDefault()`.
1090    ///
1091    /// A radio carries its whole set, because selecting one clears the others.
1092    pub fn run_pre_click_activation(&mut self, target: NodeId) -> Option<PreClickActivation> {
1093        let node_id = crate::events::pointer::checkable_activation_target(self, target)?;
1094        let el = self.get_node(node_id)?.data.downcast_element()?;
1095        let is_radio = el.attr(local_name!("type")) == Some("radio");
1096        let was_checked = el.checkbox_input_checked()?;
1097        let notification_target = (!is_radio || !was_checked).then_some(node_id);
1098
1099        if !is_radio {
1100            let el = self.get_node_mut(node_id)?.data.downcast_element_mut()?;
1101            Self::toggle_checkbox(el);
1102            return Some(PreClickActivation {
1103                previous: vec![(node_id, was_checked)],
1104                notification_target,
1105            });
1106        }
1107
1108        let radio_set = el.attr(local_name!("name")).map(str::to_string);
1109        let Some(radio_set) = radio_set else {
1110            let el = self.get_node_mut(node_id)?.data.downcast_element_mut()?;
1111            *el.checkbox_input_checked_mut()? = true;
1112            return Some(PreClickActivation {
1113                previous: vec![(node_id, was_checked)],
1114                notification_target,
1115            });
1116        };
1117
1118        // Recorded *while* selecting rather than before it. Selecting one radio
1119        // clears every other in the set, so cancelling has to restore all of
1120        // them, and reading them first meant walking the whole arena twice for
1121        // one press. The membership test is `toggle_radio`'s, deliberately: two
1122        // predicates that disagreed would restore a different set than the one
1123        // that changed.
1124        //
1125        // That predicate is name plus "has checkbox state", which is neither
1126        // scoped to `type=radio` nor to a form owner. Wrong per HTML, and
1127        // longstanding; matching it here keeps this change to the ordering it
1128        // is about.
1129        let mut previous: Vec<(NodeId, bool)> = Vec::new();
1130        for (id, node) in self.nodes.iter_mut() {
1131            let Some(el) = node.data.downcast_element_mut() else {
1132                continue;
1133            };
1134            if el.attr(local_name!("name")) != Some(&*radio_set) {
1135                continue;
1136            }
1137            let Some(is_checked) = el.checkbox_input_checked_mut() else {
1138                continue;
1139            };
1140            previous.push((id, *is_checked));
1141            *is_checked = id == node_id;
1142        }
1143        Some(PreClickActivation {
1144            previous,
1145            notification_target,
1146        })
1147    }
1148
1149    /// Undo [`Self::run_pre_click_activation`]. The click's *canceled
1150    /// activation steps*.
1151    pub fn undo_pre_click_activation(&mut self, activation: PreClickActivation) {
1152        for (node_id, was_checked) in activation.previous {
1153            let Some(node) = self.get_node_mut(node_id) else {
1154                continue;
1155            };
1156            let Some(el) = node.data.downcast_element_mut() else {
1157                continue;
1158            };
1159            if let Some(is_checked) = el.checkbox_input_checked_mut() {
1160                *is_checked = was_checked;
1161            }
1162        }
1163    }
1164
1165    pub fn toggle_checkbox(el: &mut ElementData) -> bool {
1166        let Some(is_checked) = el.checkbox_input_checked_mut() else {
1167            return false;
1168        };
1169        *is_checked = !*is_checked;
1170
1171        *is_checked
1172    }
1173
1174    pub fn toggle_radio(&mut self, radio_set_name: String, target_radio_id: NodeId) {
1175        for (i, node) in self.nodes.iter_mut() {
1176            if let Some(node_data) = node.data.downcast_element_mut() {
1177                if node_data.attr(local_name!("name")) == Some(&radio_set_name) {
1178                    let was_clicked = i == target_radio_id;
1179                    let Some(is_checked) = node_data.checkbox_input_checked_mut() else {
1180                        continue;
1181                    };
1182                    *is_checked = was_clicked;
1183                }
1184            }
1185        }
1186    }
1187
1188    /// Toggle the `open` attribute of a `<details>` element, expanding or
1189    /// collapsing it. This is the default action triggered when the element's
1190    /// first `<summary>` child is activated.
1191    pub fn toggle_details_open(&mut self, details_id: NodeId) {
1192        use crate::qual_name;
1193
1194        let node = &self.nodes[details_id];
1195        if !node.data.is_element_with_tag_name(&local_name!("details")) {
1196            return;
1197        }
1198        let is_open = node.data.has_attr(local_name!("open"));
1199
1200        // Note: HTML attributes are in the empty (null) namespace, so the
1201        // QualName must not use the html namespace here, else it won't match
1202        // an `open` attribute created by the HTML parser.
1203        let mut mutator = self.mutate();
1204        if is_open {
1205            mutator.clear_attribute(details_id, qual_name!("open"));
1206        } else {
1207            mutator.set_attribute(details_id, qual_name!("open"), "");
1208        }
1209        drop(mutator);
1210
1211        self.shell_provider.request_redraw();
1212    }
1213
1214    pub fn set_style_property(&mut self, node_id: NodeId, name: &str, value: &str) {
1215        let node = &mut self.nodes[node_id];
1216        let did_change = node.element_data_mut().unwrap().set_style_property(
1217            name,
1218            value,
1219            &self.guard,
1220            self.url.url_extra_data(),
1221        );
1222        if did_change {
1223            node.mark_style_attr_updated();
1224        }
1225    }
1226
1227    pub fn remove_style_property(&mut self, node_id: NodeId, name: &str) {
1228        let node = &mut self.nodes[node_id];
1229        let did_change = node.element_data_mut().unwrap().remove_style_property(
1230            name,
1231            &self.guard,
1232            self.url.url_extra_data(),
1233        );
1234        if did_change {
1235            node.mark_style_attr_updated();
1236        }
1237    }
1238
1239    pub fn sub_document_node_ids(&self) -> Vec<NodeId> {
1240        self.sub_document_nodes.iter().copied().collect()
1241    }
1242
1243    /// Install the effective navigation referrer and response MIME type.
1244    pub fn set_navigation_metadata(&mut self, request: &Request, content_type: Option<&str>) {
1245        self.document_referrer = request
1246            .headers
1247            .get(blitz_traits::net::http::header::REFERER)
1248            .and_then(|value| value.to_str().ok())
1249            .and_then(|value| Url::parse(value).ok())
1250            .map(|mut url| {
1251                let _ = url.set_username("");
1252                let _ = url.set_password(None);
1253                url.set_fragment(None);
1254                url.to_string()
1255            })
1256            .unwrap_or_default();
1257        self.document_content_type = content_type
1258            .and_then(|value| value.split(';').next())
1259            .map(str::trim)
1260            .filter(|value| !value.is_empty())
1261            .unwrap_or("text/html")
1262            .to_ascii_lowercase();
1263    }
1264
1265    pub fn referrer(&self) -> &str {
1266        &self.document_referrer
1267    }
1268
1269    pub fn content_type(&self) -> &str {
1270        &self.document_content_type
1271    }
1272
1273    /// Control CSS frame ticks without freezing scripts or resource loading.
1274    pub fn set_css_animation_ticks_enabled(&mut self, enabled: bool) {
1275        self.css_animation_ticks_enabled = enabled;
1276        for id in self.sub_document_node_ids() {
1277            if let Some(child) = self.subdoc_mut(id) {
1278                child.inner_mut().set_css_animation_ticks_enabled(enabled);
1279            }
1280        }
1281    }
1282
1283    pub fn window_focused(&self) -> bool {
1284        self.document_window_focused
1285    }
1286
1287    /// Hosts must deliver focus changes on the document's owning thread.
1288    pub fn set_window_focused(&mut self, focused: bool) {
1289        self.document_window_focused = focused;
1290        for id in self.sub_document_node_ids() {
1291            if let Some(child) = self
1292                .get_node_mut(id)
1293                .and_then(|node| node.element_data_mut())
1294                .and_then(|element| element.sub_doc_data_mut())
1295            {
1296                child.inner_mut().set_window_focused(focused);
1297            }
1298        }
1299    }
1300
1301    /// 0 is standards, 1 is limited quirks, and 2 is quirks.
1302    pub fn set_document_quirks_mode(&mut self, mode: u8) {
1303        if let NodeData::Document(data) = &mut self.root_node_mut().data {
1304            data.quirks_mode = mode;
1305        }
1306    }
1307
1308    pub fn compat_mode(&self) -> &'static str {
1309        if matches!(&self.root_node().data, NodeData::Document(data) if data.quirks_mode == 2) {
1310            "BackCompat"
1311        } else {
1312            "CSS1Compat"
1313        }
1314    }
1315
1316    pub fn begin_document_stream(&mut self) {
1317        self.reset_web_fonts();
1318        self.pending_critical_resources.clear();
1319        self.pending_images.clear();
1320        self.image_load_states.clear();
1321        self.image_load_outcomes.clear();
1322        self.set_document_quirks_mode(0);
1323    }
1324
1325    pub fn set_sub_document(&mut self, node_id: NodeId, mut sub_document: Box<dyn Document>) {
1326        sub_document
1327            .inner_mut()
1328            .set_window_focused(self.document_window_focused);
1329        if !self.css_animation_ticks_enabled {
1330            sub_document
1331                .inner_mut()
1332                .set_css_animation_ticks_enabled(false);
1333        }
1334        self.nodes[node_id]
1335            .element_data_mut()
1336            .unwrap()
1337            .set_sub_document(sub_document);
1338        self.sub_document_nodes.insert(node_id);
1339    }
1340
1341    pub fn prepare_teardown(&mut self) {
1342        if self.page_retiring {
1343            return;
1344        }
1345        self.page_retiring = true;
1346        if let Some(signal) = &self.abort_signal {
1347            blitz_traits::net::AbortController {
1348                signal: signal.clone(),
1349            }
1350            .abort();
1351        }
1352        self.page_visible = false;
1353        self.page_frozen = true;
1354        let nodes: Vec<_> = self.sub_document_nodes.iter().copied().collect();
1355        let mut children = Vec::new();
1356        for id in nodes {
1357            if let Some(receipt) = self.retire_sub_document(id) {
1358                children.push(receipt);
1359            }
1360        }
1361        #[cfg(feature = "custom-widget")]
1362        self.destroy_surfaces();
1363        for (_, load) in std::mem::take(&mut self.iframe_loads) {
1364            load.abort_controller.abort();
1365        }
1366        self.teardown.retire(children);
1367    }
1368
1369    /// Detach the complete owner, rather than leaving a frozen runtime mounted.
1370    pub fn take_sub_document(&mut self, node_id: NodeId) -> Option<Box<dyn Document>> {
1371        let element = self.nodes.get_mut(node_id)?.element_data_mut()?;
1372        let crate::node::SpecialElementData::SubDocument(document) = element.special_data.take()
1373        else {
1374            return None;
1375        };
1376        self.sub_document_nodes.remove(&node_id);
1377        if let Some(load) = self.iframe_loads.remove(&node_id) {
1378            load.abort_controller.abort();
1379        }
1380        Some(document)
1381    }
1382
1383    pub fn retire_sub_document(
1384        &mut self,
1385        node_id: NodeId,
1386    ) -> Option<Arc<crate::release::Teardown>> {
1387        let mut document = self.take_sub_document(node_id)?;
1388        document.prepare_teardown();
1389        #[cfg(feature = "custom-widget")]
1390        {
1391            let receipt = Arc::clone(&document.inner().teardown);
1392            let (resources, mut leases) = document.inner_mut().retire_render_resources();
1393            if !resources.is_empty() {
1394                leases.push(receipt.lease());
1395                self.retired_resources
1396                    .push(crate::release::ResourceRetirement { resources, leases });
1397            }
1398        }
1399        Some(document.dispose())
1400    }
1401
1402    #[cfg(feature = "custom-widget")]
1403    fn retire_render_resources(
1404        &mut self,
1405    ) -> (
1406        Vec<anyrender::ResourceId>,
1407        Vec<crate::release::ReleaseLease>,
1408    ) {
1409        let mut resources = self.take_pending_resource_deallocations();
1410        let mut leases = Vec::new();
1411        for retirement in self.retired_resources.drain(..) {
1412            resources.extend(retirement.resources);
1413            leases.extend(retirement.leases);
1414        }
1415        for id in self.custom_widget_nodes.iter().copied() {
1416            if let Some(data) = self
1417                .nodes
1418                .get_mut(id)
1419                .and_then(|node| node.element_data_mut())
1420                .and_then(|el| el.custom_widget_data_mut())
1421            {
1422                resources.append(&mut data.active_resource_ids);
1423            }
1424        }
1425        for id in self.sub_document_nodes.iter().copied() {
1426            if let Some(document) = self.nodes.get_mut(id).and_then(|node| node.subdoc_mut()) {
1427                let (child_resources, child_leases) =
1428                    document.inner_mut().retire_render_resources();
1429                resources.extend(child_resources);
1430                leases.extend(child_leases);
1431            }
1432        }
1433        (resources, leases)
1434    }
1435
1436    #[cfg(feature = "custom-widget")]
1437    pub fn take_retired_resources(&mut self) -> Vec<crate::release::ResourceRetirement> {
1438        std::mem::take(&mut self.retired_resources)
1439    }
1440
1441    pub fn remove_sub_document(&mut self, node_id: NodeId) {
1442        let _ = self.retire_sub_document(node_id);
1443    }
1444
1445    /// Poll all sub-documents (see [`Document::poll`]), allowing them to make progress
1446    /// on any pending async operations (e.g. JavaScript timers). Hosts which poll a
1447    /// wrapper around a [`BaseDocument`] should call this from their `poll` implementation.
1448    ///
1449    /// Returns `true` if any sub-document reported changes.
1450    pub fn poll_subdocuments(&mut self, waker: Option<&Waker>) -> bool {
1451        self.poll_subdocuments_inner(waker, None)
1452    }
1453
1454    /// Propagate a settle pass's timer policy to every child document.
1455    pub fn poll_subdocuments_for_settle(
1456        &mut self,
1457        waker: Option<&Waker>,
1458        run_timers: bool,
1459    ) -> bool {
1460        self.poll_subdocuments_inner(waker, Some(run_timers))
1461    }
1462
1463    fn poll_subdocuments_inner(
1464        &mut self,
1465        waker: Option<&Waker>,
1466        settle_timers: Option<bool>,
1467    ) -> bool {
1468        let mut has_changes = false;
1469        let node_ids: Vec<NodeId> = self.sub_document_nodes.iter().copied().collect();
1470        for node_id in node_ids {
1471            let Some(sub_doc) = self
1472                .nodes
1473                .get_mut(node_id)
1474                .and_then(|node| node.subdoc_mut())
1475            else {
1476                continue;
1477            };
1478            let task_context = waker.map(TaskContext::from_waker);
1479            has_changes |= match settle_timers {
1480                Some(run_timers) => sub_doc.poll_for_settle(task_context, run_timers),
1481                None => sub_doc.poll(task_context),
1482            };
1483        }
1484        has_changes
1485    }
1486
1487    #[cfg(feature = "custom-widget")]
1488    pub fn custom_widget_node_ids(&self) -> Vec<NodeId> {
1489        self.custom_widget_nodes.iter().copied().collect()
1490    }
1491
1492    #[cfg(feature = "custom-widget")]
1493    pub fn take_pending_resource_deallocations(&mut self) -> Vec<anyrender::ResourceId> {
1494        std::mem::take(&mut self.pending_resource_deallocations)
1495    }
1496
1497    #[cfg(feature = "custom-widget")]
1498    pub fn set_custom_widget(&mut self, node_id: NodeId, widget: Box<dyn crate::Widget>) {
1499        self.nodes[node_id]
1500            .element_data_mut()
1501            .unwrap()
1502            .set_custom_widget(widget);
1503        self.custom_widget_nodes.insert(node_id);
1504    }
1505
1506    #[cfg(feature = "custom-widget")]
1507    pub fn remove_custom_widget(&mut self, node_id: NodeId) {
1508        let resources_to_deallocate = self.nodes[node_id]
1509            .element_data_mut()
1510            .unwrap()
1511            .remove_custom_widget();
1512        self.pending_resource_deallocations
1513            .extend_from_slice(&resources_to_deallocate);
1514        self.custom_widget_nodes.remove(&node_id);
1515    }
1516
1517    /// Mutable access to the custom element registry. Use
1518    /// [`CustomElementRegistry::define`](crate::node::CustomElementRegistry::define)
1519    /// to register custom elements by tag name.
1520    #[cfg(feature = "shadow-dom")]
1521    pub fn custom_elements_mut(&mut self) -> &mut crate::node::CustomElementRegistry {
1522        &mut self.custom_element_registry
1523    }
1524
1525    /// Register a custom element definition against a tag name (analogous to
1526    /// `customElements.define`).
1527    #[cfg(feature = "shadow-dom")]
1528    pub fn define_custom_element(
1529        &mut self,
1530        name: markup5ever::LocalName,
1531        definition: crate::node::CustomElementDefinition,
1532    ) {
1533        self.custom_element_registry.define(name, definition);
1534    }
1535
1536    /// The node ids of all shadow hosts in the document.
1537    #[cfg(feature = "shadow-dom")]
1538    pub fn shadow_host_node_ids(&self) -> Vec<NodeId> {
1539        self.shadow_host_nodes.iter().copied().collect()
1540    }
1541
1542    /// If `host_id` is a shadow host, returns the node id of its shadow root.
1543    #[cfg(feature = "shadow-dom")]
1544    pub fn shadow_root_id(&self, host_id: NodeId) -> Option<NodeId> {
1545        self.get_node(host_id)
1546            .and_then(|node| node.shadow_root_id())
1547    }
1548
1549    /// Attach a shadow root to the given host element, returning the node id of
1550    /// the newly-created shadow root. If the host already has a shadow root, its
1551    /// existing shadow root id is returned unchanged.
1552    #[cfg(feature = "shadow-dom")]
1553    pub fn attach_shadow(&mut self, host_id: NodeId, mode: crate::node::ShadowRootMode) -> NodeId {
1554        if let Some(existing) = self.nodes[host_id].shadow_root_id() {
1555            return existing;
1556        }
1557
1558        let shadow_root_id = self.create_node(NodeData::ShadowRoot(
1559            crate::node::ShadowRootData::new(host_id, mode),
1560        ));
1561
1562        // The shadow root's parent is the host. It is *not* added to the host's
1563        // `children` list (which holds light-DOM children); it is referenced via
1564        // the host's `ElementData::shadow_root` field instead.
1565        self.nodes[shadow_root_id].parent = Some(host_id);
1566        self.nodes[shadow_root_id].owner_document = self.nodes[host_id].owner_document;
1567        if self.nodes[host_id].flags.is_in_document() {
1568            self.nodes[shadow_root_id]
1569                .flags
1570                .insert(NodeFlags::IS_IN_DOCUMENT);
1571        }
1572
1573        self.nodes[host_id]
1574            .element_data_mut()
1575            .expect("Shadow host must be an element")
1576            .shadow_root = Some(shadow_root_id);
1577        self.shadow_host_nodes.insert(host_id);
1578        self.dirty_shadow_hosts.insert(host_id);
1579        self.nodes[host_id].set_restyle_hint(
1580            style::invalidation::element::restyle_hints::RestyleHint::restyle_subtree(),
1581        );
1582
1583        // Host needs its box tree rebuilt to account for the shadow tree.
1584        self.nodes[host_id].insert_damage(ALL_DAMAGE);
1585        self.nodes[host_id].mark_ancestors_dirty();
1586
1587        shadow_root_id
1588    }
1589
1590    /// HTML elements that `Element.attachShadow` accepts.
1591    ///
1592    /// Hyphenated names are included, matching the existing script binding.
1593    /// `template` is not a host.
1594    #[cfg(feature = "shadow-dom")]
1595    pub fn element_can_be_shadow_host(element: &ElementData) -> bool {
1596        let tag = element.name.local.as_ref();
1597        element.name.ns == ns!(html)
1598            && (tag.contains('-')
1599                || matches!(
1600                    tag,
1601                    "article"
1602                        | "aside"
1603                        | "blockquote"
1604                        | "body"
1605                        | "div"
1606                        | "footer"
1607                        | "h1"
1608                        | "h2"
1609                        | "h3"
1610                        | "h4"
1611                        | "h5"
1612                        | "h6"
1613                        | "header"
1614                        | "main"
1615                        | "nav"
1616                        | "p"
1617                        | "section"
1618                        | "span"
1619                ))
1620    }
1621
1622    /// Attach a declarative shadow root, or return false and leave the template
1623    /// as a normal template.
1624    ///
1625    /// Failure is the host being missing, not a shadow host, or already having
1626    /// a root. Success records the template so parsed children land in the root.
1627    #[cfg(feature = "shadow-dom")]
1628    pub fn try_attach_declarative_shadow(
1629        &mut self,
1630        host_id: NodeId,
1631        template_id: NodeId,
1632        mode: crate::node::ShadowRootMode,
1633        clonable: bool,
1634        serializable: bool,
1635        delegates_focus: bool,
1636    ) -> bool {
1637        let can_attach = self.nodes.get(host_id).is_some_and(|node| {
1638            node.element_data().is_some_and(|element| {
1639                Self::element_can_be_shadow_host(element) && element.shadow_root.is_none()
1640            })
1641        });
1642        if !can_attach {
1643            return false;
1644        }
1645        let root_id = self.attach_shadow(host_id, mode);
1646        if let Some(root) = self.nodes[root_id].shadow_root_data_mut() {
1647            root.declarative = true;
1648            root.clonable = clonable;
1649            root.serializable = serializable;
1650            root.delegates_focus = delegates_focus;
1651        }
1652        self.declarative_template_shadows
1653            .insert(template_id, root_id);
1654        true
1655    }
1656
1657    /// Detach (and drop) the shadow root of the given host element, if any.
1658    #[cfg(feature = "shadow-dom")]
1659    pub fn detach_shadow(&mut self, host_id: NodeId) {
1660        let shadow_root_id = self.nodes[host_id]
1661            .element_data_mut()
1662            .and_then(|el| el.shadow_root.take());
1663        if let Some(shadow_root_id) = shadow_root_id {
1664            self.drop_node_ignoring_parent(shadow_root_id);
1665            self.shadow_host_nodes.remove(&host_id);
1666            self.dirty_shadow_hosts.remove(&host_id);
1667            self.nodes[host_id].flattened_children = None;
1668            self.nodes[host_id].set_restyle_hint(
1669                style::invalidation::element::restyle_hints::RestyleHint::restyle_subtree(),
1670            );
1671            self.nodes[host_id].insert_damage(ALL_DAMAGE);
1672            self.nodes[host_id].mark_ancestors_dirty();
1673        }
1674    }
1675
1676    /// Attach a custom element controller to the given node.
1677    #[cfg(feature = "shadow-dom")]
1678    pub fn set_custom_element(
1679        &mut self,
1680        node_id: NodeId,
1681        controller: Box<dyn crate::node::CustomElement>,
1682    ) {
1683        use crate::node::{CustomElementData, SpecialElementData};
1684        self.nodes[node_id]
1685            .element_data_mut()
1686            .expect("Custom element host must be an element")
1687            .special_data = SpecialElementData::CustomElement(CustomElementData::new(controller));
1688        self.custom_element_nodes.insert(node_id);
1689    }
1690
1691    /// Detach the custom element controller from the given node (without running
1692    /// the `disconnected` callback). Returns the controller if present.
1693    #[cfg(feature = "shadow-dom")]
1694    pub fn take_custom_element(
1695        &mut self,
1696        node_id: NodeId,
1697    ) -> Option<Box<dyn crate::node::CustomElement>> {
1698        use crate::node::SpecialElementData;
1699        self.custom_element_nodes.remove(&node_id);
1700        let element = self.nodes[node_id].element_data_mut()?;
1701        if matches!(element.special_data, SpecialElementData::CustomElement(_)) {
1702            if let SpecialElementData::CustomElement(mut data) = element.special_data.take() {
1703                return data.controller.take();
1704            }
1705        }
1706        None
1707    }
1708
1709    pub fn root_node(&self) -> &Node {
1710        &self.nodes[self.root_node_id]
1711    }
1712
1713    pub fn root_node_mut(&mut self) -> &mut Node {
1714        &mut self.nodes[self.root_node_id]
1715    }
1716
1717    /// Ask this document to work out which regions differ between frames.
1718    ///
1719    /// Off by default. A consumer that turns it on is charged one pass over the
1720    /// node list per [`resolve`](Self::resolve) - a pass `resolve` already makes
1721    /// to clear damage - plus a hash lookup and a rectangle comparison per node.
1722    /// Nothing else in the document reads the result, so leaving it off costs a
1723    /// single branch.
1724    ///
1725    /// The consumer this exists for is a `backdrop-filter` cache. Blurring what
1726    /// is behind an element costs a render pass and a filter every frame, and
1727    /// the only way that stops being permanent is to skip the elements whose
1728    /// input has not changed. Turning this on is what makes that question
1729    /// answerable.
1730    ///
1731    /// The first frame after enabling reports everything as changed, because
1732    /// there is no previous frame to compare against.
1733    pub fn set_paint_damage_tracking(&mut self, enabled: bool) {
1734        self.paint_damage.set_enabled(enabled);
1735    }
1736
1737    /// Whether [`set_paint_damage_tracking`](Self::set_paint_damage_tracking) is on.
1738    pub fn paint_damage_tracking(&self) -> bool {
1739        self.paint_damage.is_enabled()
1740    }
1741
1742    /// What changed since the previously resolved frame.
1743    ///
1744    /// Empty when tracking is off, which is indistinguishable from "nothing
1745    /// changed" and deliberately so: a consumer that has not asked for the
1746    /// question to be answered must not read the empty answer as a licence to
1747    /// reuse a cache. Check
1748    /// [`paint_damage_tracking`](Self::paint_damage_tracking) first.
1749    pub fn paint_damage(&self) -> &crate::paint_damage::PaintDamage {
1750        self.paint_damage.damage()
1751    }
1752
1753    pub fn try_root_element(&self) -> Option<&Node> {
1754        TDocument::as_node(&self.root_node()).first_element_child()
1755    }
1756
1757    pub fn root_element(&self) -> &Node {
1758        TDocument::as_node(&self.root_node())
1759            .first_element_child()
1760            .unwrap()
1761            .as_element()
1762            .unwrap()
1763    }
1764
1765    pub fn create_node(&mut self, node_data: NodeData) -> NodeId {
1766        let tree_ptr = self.nodes.as_mut() as *mut NodeTree;
1767        let guard = self.guard.clone();
1768        let is_document = matches!(node_data, NodeData::Document(_));
1769        let id = self
1770            .nodes
1771            .insert_with_key(|id| Node::new(tree_ptr, id, guard, node_data));
1772        if !is_document {
1773            self.nodes[id].owner_document = Some(self.root_node_id);
1774        }
1775        self.register_script_custom_element(id);
1776        if let Some(attributes) = self.nodes[id]
1777            .element_data()
1778            .and_then(|element| element.inline_event_attributes.as_deref())
1779        {
1780            self.inline_handler_changes.extend(
1781                attributes
1782                    .iter()
1783                    .map(|attr| (id, attr.name.clone(), Some(attr.value.clone()))),
1784            );
1785        }
1786        id
1787    }
1788
1789    pub fn add_to_document_id_map(&mut self, document_id: NodeId, id: &str, node_id: NodeId) {
1790        if document_id == self.root_node_id || id.is_empty() {
1791            return;
1792        }
1793        let Some(node) = self.get_node_mut(document_id) else {
1794            return;
1795        };
1796        let NodeData::Document(data) = &mut node.data else {
1797            return;
1798        };
1799        let candidates = data.ids.entry(id.to_owned()).or_default();
1800        if !candidates.contains(&node_id) {
1801            candidates.push(node_id);
1802        }
1803    }
1804
1805    pub fn remove_from_document_id_map(&mut self, document_id: NodeId, id: &str, node_id: NodeId) {
1806        if document_id == self.root_node_id {
1807            return;
1808        }
1809        let Some(node) = self.get_node_mut(document_id) else {
1810            return;
1811        };
1812        let NodeData::Document(data) = &mut node.data else {
1813            return;
1814        };
1815        if let Some(candidates) = data.ids.get_mut(id) {
1816            candidates.retain(|candidate| *candidate != node_id);
1817            if candidates.is_empty() {
1818                data.ids.remove(id);
1819            }
1820        }
1821    }
1822
1823    /// Indexed lookup scoped to one document. Parent child-list membership
1824    /// excludes removed nodes, template contents, and shadow trees.
1825    pub fn get_element_by_id_in(&self, document_id: NodeId, id: &str) -> Option<NodeId> {
1826        if document_id == self.root_node_id {
1827            return self.get_element_by_id(id);
1828        }
1829        if id.is_empty() {
1830            return None;
1831        }
1832        let NodeData::Document(data) = &self.get_node(document_id)?.data else {
1833            return None;
1834        };
1835        data.ids
1836            .get(id)?
1837            .iter()
1838            .filter_map(|candidate| {
1839                let mut current = *candidate;
1840                let mut path = Vec::new();
1841                while current != document_id {
1842                    let node = self.get_node(current)?;
1843                    let parent_id = node.parent?;
1844                    let parent = self.get_node(parent_id)?;
1845                    path.push(parent.index_of_child(current)?);
1846                    current = parent_id;
1847                }
1848                path.reverse();
1849                Some((path, *candidate))
1850            })
1851            .min_by(|left, right| left.0.cmp(&right.0))
1852            .map(|(_, node_id)| node_id)
1853    }
1854
1855    /// Nodes that still hold a link to `node_id` after it leaves the document.
1856    ///
1857    /// Direct parents are recorded separately and force reconstruction. This
1858    /// collects everyone else the old document-wide pass would have mutated:
1859    /// surviving layout children (their `layout_parent` still points here),
1860    /// anonymous blocks that list the id without being its DOM parent, shadow
1861    /// slots and hosts, the authored parent of a hoisted fixed box, and
1862    /// ancestors whose inline layout, list marker, table grid, or stacking
1863    /// context stores a descendant id. Ancestors inside `removed` are not
1864    /// walked; detachment does not clean lists on nodes that are themselves
1865    /// going away.
1866    fn collect_live_reference_owners(
1867        nodes: &NodeTree,
1868        hoisted_fixed_parents: &HashMap<NodeId, NodeId>,
1869        removed: &FxHashSet<NodeId>,
1870        node_id: NodeId,
1871        candidates: &mut FxHashSet<NodeId>,
1872    ) {
1873        fn push_survivor(
1874            removed: &FxHashSet<NodeId>,
1875            candidates: &mut FxHashSet<NodeId>,
1876            id: NodeId,
1877        ) {
1878            if !removed.contains(&id) {
1879                candidates.insert(id);
1880            }
1881        }
1882
1883        let (removed_is_text, dom_parent, layout_parent, seeds) = {
1884            let Some(node) = nodes.get(node_id) else {
1885                return;
1886            };
1887            let mut seeds: SmallVec<[NodeId; 8]> = SmallVec::new();
1888            {
1889                let borrowed = node.layout_children.borrow();
1890                if let Some(children) = borrowed.as_ref() {
1891                    seeds.extend(children.iter().copied());
1892                }
1893            }
1894            seeds.extend(node.children.iter().copied());
1895            seeds.extend(node.anonymous_blocks.iter().copied());
1896            seeds.extend(node.before());
1897            seeds.extend(node.after());
1898            #[cfg(feature = "shadow-dom")]
1899            {
1900                seeds.extend(node.assigned_slot);
1901                seeds.extend(
1902                    node.element_data()
1903                        .and_then(|element| element.assigned_slot),
1904                );
1905                if let Some(assigned) = node.assigned_nodes.as_ref() {
1906                    seeds.extend(assigned.iter().copied());
1907                }
1908                if let Some(root) = node.shadow_root_data() {
1909                    seeds.push(root.host);
1910                }
1911            }
1912            (
1913                node.is_text_node(),
1914                node.parent,
1915                node.layout_parent.get(),
1916                seeds,
1917            )
1918        };
1919
1920        for parent_id in [dom_parent, layout_parent].into_iter().flatten() {
1921            let Some(parent) = nodes.get(parent_id) else {
1922                continue;
1923            };
1924            let anons: SmallVec<[NodeId; 4]> = parent.anonymous_blocks.iter().copied().collect();
1925            for anon in anons {
1926                let Some(anon_node) = nodes.get(anon) else {
1927                    continue;
1928                };
1929                let listed = anon_node
1930                    .children
1931                    .iter()
1932                    .any(|child| removed.contains(child))
1933                    || anon_node
1934                        .layout_children
1935                        .borrow()
1936                        .as_ref()
1937                        .is_some_and(|children| {
1938                            children.iter().any(|child| removed.contains(child))
1939                        });
1940                if listed {
1941                    push_survivor(removed, candidates, anon);
1942                }
1943            }
1944        }
1945        for id in seeds {
1946            push_survivor(removed, candidates, id);
1947        }
1948
1949        let mut stack: SmallVec<[NodeId; 16]> = SmallVec::new();
1950        if let Some(id) = dom_parent {
1951            if !removed.contains(&id) {
1952                stack.push(id);
1953            }
1954        }
1955        if let Some(id) = layout_parent {
1956            if !removed.contains(&id) {
1957                stack.push(id);
1958            }
1959        }
1960        if let Some(origin) = hoisted_fixed_parents.get(&node_id).copied() {
1961            // Hoist drops the layout edge before paint children are rebuilt, so
1962            // the authored parent can still name the fixed box.
1963            push_survivor(removed, candidates, origin);
1964            if !removed.contains(&origin) {
1965                stack.push(origin);
1966            }
1967        }
1968
1969        let mut seen: SmallVec<[NodeId; 16]> = SmallVec::new();
1970        seen.push(node_id);
1971        while let Some(id) = stack.pop() {
1972            if seen.contains(&id) {
1973                continue;
1974            }
1975            seen.push(id);
1976            let Some(ancestor) = nodes.get(id) else {
1977                continue;
1978            };
1979            let stacking = ancestor.stacking_context.as_ref().is_some_and(|context| {
1980                context.children.iter().any(|child| {
1981                    removed.contains(&child.node_id)
1982                        || child
1983                            .clip_ancestors
1984                            .iter()
1985                            .any(|clip| removed.contains(clip))
1986                })
1987            });
1988            let inline_or_list = ancestor.element_data().is_some_and(|element| {
1989                element.inline_layout_data.is_some() || element.list_item_data.is_some()
1990            });
1991            // Table grids store cells, rows, and row groups, never text nodes.
1992            let table_root = !removed_is_text && ancestor.flags.is_table_root();
1993            #[cfg(feature = "shadow-dom")]
1994            let shadow_hit = {
1995                let mut hit = ancestor
1996                    .flattened_children
1997                    .as_ref()
1998                    .is_some_and(|children| children.iter().any(|child| removed.contains(child)))
1999                    || ancestor.assigned_nodes.as_ref().is_some_and(|assigned| {
2000                        assigned.iter().any(|child| removed.contains(child))
2001                    });
2002                if let Some(root) = ancestor.shadow_root_data() {
2003                    let host = root.host;
2004                    hit = hit
2005                        || root.slots.iter().any(|slot| removed.contains(slot))
2006                        || root
2007                            .slottables
2008                            .iter()
2009                            .any(|slottable| removed.contains(slottable))
2010                        || root
2011                            .stylesheet_nodes
2012                            .iter()
2013                            .any(|sheet| removed.contains(sheet));
2014                    stack.push(host);
2015                }
2016                hit
2017            };
2018            #[cfg(not(feature = "shadow-dom"))]
2019            let shadow_hit = false;
2020            if stacking || inline_or_list || table_root || shadow_hit {
2021                push_survivor(removed, candidates, id);
2022            }
2023            if let Some(parent) = ancestor.parent {
2024                stack.push(parent);
2025            }
2026            if let Some(parent) = ancestor.layout_parent.get() {
2027                stack.push(parent);
2028            }
2029        }
2030    }
2031
2032    /// Stacking-context hosts are few, and a fixed box can paint in one that
2033    /// is not a layout ancestor of its current parent. Visit a host only when
2034    /// its hoisted list actually names a removed id.
2035    fn collect_stacking_context_owners(
2036        nodes: &NodeTree,
2037        position_hosts: &HashSet<NodeId>,
2038        clip_hosts: &HashSet<NodeId>,
2039        removed: &FxHashSet<NodeId>,
2040        candidates: &mut FxHashSet<NodeId>,
2041    ) {
2042        for host in position_hosts.iter().chain(clip_hosts.iter()).copied() {
2043            if removed.contains(&host) {
2044                continue;
2045            }
2046            let Some(node) = nodes.get(host) else {
2047                continue;
2048            };
2049            let Some(context) = node.stacking_context.as_ref() else {
2050                continue;
2051            };
2052            let references = context.children.iter().any(|child| {
2053                removed.contains(&child.node_id)
2054                    || child
2055                        .clip_ancestors
2056                        .iter()
2057                        .any(|clip| removed.contains(clip))
2058            });
2059            if references {
2060                candidates.insert(host);
2061            }
2062        }
2063    }
2064
2065    /// Remove detached or freed ids from every persistent rendering cache.
2066    ///
2067    /// DOM ancestry alone cannot find the owners: fixed boxes can belong to
2068    /// the root's layout list and another ancestor's stacking context, while
2069    /// inline boxes and table cells have additional flattened representations.
2070    /// Invalidate those owners before this mutation returns. Hidden subtrees
2071    /// retain caches, so leaving cleanup until resolve is insufficient.
2072    ///
2073    /// Only those owners are visited. A pass over every node made each
2074    /// `textContent` write rescan the whole document.
2075    pub(crate) fn invalidate_node_references(
2076        &mut self,
2077        removed: &FxHashSet<NodeId>,
2078        mut parents: FxHashSet<NodeId>,
2079        extra_owners: FxHashSet<NodeId>,
2080    ) {
2081        if removed.is_empty() {
2082            return;
2083        }
2084
2085        fn layout_references_removed(
2086            layout: &parley::Layout<TextBrush>,
2087            removed: &FxHashSet<NodeId>,
2088        ) -> bool {
2089            layout
2090                .inline_boxes()
2091                .iter()
2092                .any(|ibox| removed.contains(&NodeId::from_u64(ibox.id)))
2093                || layout.styles().iter().any(|style| {
2094                    removed.contains(&style.brush.id)
2095                        || style
2096                            .brush
2097                            .text_node
2098                            .is_some_and(|id| removed.contains(&id))
2099                })
2100        }
2101
2102        // An anonymous origin can disappear while its hoisted fixed box
2103        // survives. Reconstruct the root edge too, so construction can give
2104        // that box a current authored origin.
2105        for (&id, &origin) in &self.hoisted_fixed_parents {
2106            if removed.contains(&id) || removed.contains(&origin) {
2107                if let Some(node) = self.nodes.get(id) {
2108                    parents.extend(node.layout_parent.get());
2109                }
2110            }
2111        }
2112
2113        let mut candidates: FxHashSet<NodeId> = FxHashSet::with_capacity_and_hasher(
2114            parents.len() + extra_owners.len() + removed.len(),
2115            Default::default(),
2116        );
2117        for &id in &parents {
2118            if !removed.contains(&id) {
2119                candidates.insert(id);
2120            }
2121        }
2122        for id in extra_owners {
2123            if !removed.contains(&id) {
2124                candidates.insert(id);
2125            }
2126        }
2127        for &id in removed {
2128            let detach = self
2129                .nodes
2130                .get(id)
2131                .and_then(|node| node.layout_parent.get())
2132                .is_some_and(|parent| !removed.contains(&parent));
2133            if detach {
2134                candidates.insert(id);
2135            }
2136            if self.nodes.contains_key(id) {
2137                Self::collect_live_reference_owners(
2138                    &self.nodes,
2139                    &self.hoisted_fixed_parents,
2140                    removed,
2141                    id,
2142                    &mut candidates,
2143                );
2144            }
2145        }
2146        Self::collect_stacking_context_owners(
2147            &self.nodes,
2148            &self.hoisted_position_hosts,
2149            &self.hoisted_clip_hosts,
2150            removed,
2151            &mut candidates,
2152        );
2153
2154        self.fixed_nodes.retain(|id| !removed.contains(id));
2155        self.sticky_nodes.retain(|id| !removed.contains(id));
2156        self.sticky_offsets.retain(|id, _| !removed.contains(id));
2157        self.hoisted_fixed_parents
2158            .retain(|id, origin| !removed.contains(id) && !removed.contains(origin));
2159        let fixed_parents = &self.hoisted_fixed_parents;
2160        self.hoisted_fixed_indices
2161            .retain(|id, _| fixed_parents.contains_key(id));
2162        self.hoisted_clip_hosts.retain(|id| !removed.contains(id));
2163        self.hoisted_position_hosts
2164            .retain(|id| !removed.contains(id));
2165
2166        // These snapshots contain both box ids and containing-block/parent
2167        // ids. Discard the complete snapshots rather than retaining inputs
2168        // computed against a box tree that has just changed.
2169        self.abspos_placements.clear();
2170        self.abspos_candidates.clear();
2171        self.abspos_candidate_ids.clear();
2172        self.abspos_inputs.clear();
2173        self.abspos_written.clear();
2174        self.abspos_candidates_dirty = true;
2175        self.abspos_layout_dirty = true;
2176
2177        let mut dirty = FxHashSet::default();
2178        for id in candidates {
2179            let Some(node) = self.nodes.get_mut(id) else {
2180                continue;
2181            };
2182            // Detached nodes still owned by script keep their internal box
2183            // tree, but must lose any edge back into the live layout tree.
2184            if removed.contains(&id) {
2185                if node
2186                    .layout_parent
2187                    .get()
2188                    .is_some_and(|parent| !removed.contains(&parent))
2189                {
2190                    node.layout_parent.set(None);
2191                }
2192                continue;
2193            }
2194
2195            let mut reconstruct = parents.contains(&id);
2196            reconstruct |= node
2197                .layout_children
2198                .get_mut()
2199                .as_ref()
2200                .is_some_and(|children| children.iter().any(|id| removed.contains(id)));
2201            let mut repaint = node
2202                .paint_children
2203                .get_mut()
2204                .as_ref()
2205                .is_some_and(|children| children.iter().any(|id| removed.contains(id)));
2206
2207            let old_anonymous_count = node.anonymous_blocks.len();
2208            node.anonymous_blocks.retain(|id| !removed.contains(id));
2209            reconstruct |= old_anonymous_count != node.anonymous_blocks.len();
2210            if node.is_anonymous() {
2211                let old_child_count = node.children.len();
2212                node.children.retain(|id| !removed.contains(id));
2213                reconstruct |= old_child_count != node.children.len();
2214            }
2215            if node
2216                .layout_parent
2217                .get()
2218                .is_some_and(|parent| removed.contains(&parent))
2219            {
2220                node.layout_parent.set(None);
2221                reconstruct = true;
2222            }
2223
2224            if let Some(context) = node.stacking_context.as_mut() {
2225                let old_count = context.children.len();
2226                context.children.retain(|child| {
2227                    !removed.contains(&child.node_id)
2228                        && !child.clip_ancestors.iter().any(|id| removed.contains(id))
2229                });
2230                if old_count != context.children.len() {
2231                    // Filtering changes the split between negative and
2232                    // non-negative children as well as the content bounds.
2233                    context.sort();
2234                    context.content_area = taffy::Rect::ZERO;
2235                    repaint = true;
2236                }
2237            }
2238
2239            #[cfg(feature = "shadow-dom")]
2240            {
2241                for children in [
2242                    node.flattened_children.as_mut(),
2243                    node.assigned_nodes.as_mut(),
2244                ]
2245                .into_iter()
2246                .flatten()
2247                {
2248                    let old_count = children.len();
2249                    children.retain(|id| !removed.contains(id));
2250                    reconstruct |= old_count != children.len();
2251                }
2252                if node.assigned_slot.is_some_and(|id| removed.contains(&id)) {
2253                    node.assigned_slot = None;
2254                    reconstruct = true;
2255                }
2256                if let Some(root) = node.shadow_root_data_mut() {
2257                    let old_count = root.slots.len() + root.slottables.len();
2258                    root.slots.retain(|id| !removed.contains(id));
2259                    root.slottables.retain(|id| !removed.contains(id));
2260                    root.stylesheet_nodes.retain(|id| !removed.contains(id));
2261                    reconstruct |= old_count != root.slots.len() + root.slottables.len();
2262                }
2263            }
2264
2265            let mut table_removed = false;
2266            if let Some(element) = node.data.downcast_element_mut() {
2267                for pseudo in [&mut element.before, &mut element.after] {
2268                    if pseudo.is_some_and(|id| removed.contains(&id)) {
2269                        *pseudo = None;
2270                        reconstruct = true;
2271                    }
2272                }
2273                if element
2274                    .inline_layout_data
2275                    .as_ref()
2276                    .is_some_and(|inline| layout_references_removed(&inline.layout, removed))
2277                {
2278                    element.inline_layout_data = None;
2279                    reconstruct = true;
2280                }
2281                if element
2282                    .list_item_data
2283                    .as_ref()
2284                    .is_some_and(|item| match &item.position {
2285                        crate::node::ListItemLayoutPosition::Outside(layout) => {
2286                            layout_references_removed(layout, removed)
2287                        }
2288                        crate::node::ListItemLayoutPosition::Inside => false,
2289                    })
2290                {
2291                    element.list_item_data = None;
2292                    reconstruct = true;
2293                }
2294                if let SpecialElementData::TableRoot(context) = &element.special_data {
2295                    table_removed = context.references_removed_nodes(removed);
2296                }
2297                if table_removed {
2298                    element.special_data = SpecialElementData::None;
2299                    reconstruct = true;
2300                }
2301                #[cfg(feature = "shadow-dom")]
2302                if element
2303                    .assigned_slot
2304                    .is_some_and(|id| removed.contains(&id))
2305                {
2306                    element.assigned_slot = None;
2307                    reconstruct = true;
2308                }
2309            }
2310            if table_removed {
2311                node.flags.remove(NodeFlags::IS_TABLE_ROOT);
2312            }
2313
2314            if reconstruct || repaint {
2315                node.layout_children.get_mut().take();
2316                node.paint_children.get_mut().take();
2317                if let Some(element) = node.data.downcast_element_mut() {
2318                    element.inline_layout_data = None;
2319                }
2320                dirty.insert(id);
2321            }
2322        }
2323
2324        // Clear ancestor layout caches immediately, including ancestors that
2325        // the next incremental traversal would otherwise skip. Follow both
2326        // trees and tolerate parents already freed by a root-first drop.
2327        let mut stack: Vec<NodeId> = dirty.iter().copied().collect();
2328        let mut visited = FxHashSet::default();
2329        while let Some(id) = stack.pop() {
2330            if !visited.insert(id) || removed.contains(&id) {
2331                continue;
2332            }
2333            let Some(node) = self.nodes.get_mut(id) else {
2334                continue;
2335            };
2336            stack.extend(node.parent);
2337            stack.extend(node.layout_parent.get());
2338            #[cfg(feature = "shadow-dom")]
2339            {
2340                stack.extend(node.assigned_slot);
2341                if let Some(root) = node.shadow_root_data() {
2342                    stack.push(root.host);
2343                }
2344            }
2345            node.set_dirty_descendants();
2346            if node.stylo_element_data_opt().is_some() {
2347                node.insert_damage(if dirty.contains(&id) {
2348                    ALL_DAMAGE
2349                } else {
2350                    crate::layout::damage::ONLY_RELAYOUT
2351                        | style::selector_parser::RestyleDamage::REPAINT
2352                });
2353                node.cache_mut().clear();
2354            }
2355            if let Some(inline) = node
2356                .data
2357                .downcast_element_mut()
2358                .and_then(|element| element.inline_layout_data.as_mut())
2359            {
2360                inline.content_widths = None;
2361            }
2362        }
2363
2364        #[cfg(feature = "shadow-dom")]
2365        {
2366            let nodes = &self.nodes;
2367            self.shadow_host_nodes.retain(|id| nodes.contains_key(*id));
2368            self.dirty_shadow_hosts.retain(|id| nodes.contains_key(*id));
2369            self.pending_slot_changes
2370                .retain(|id| nodes.contains_key(*id));
2371            self.signaled_slots.retain(|id| nodes.contains_key(*id));
2372            self.dirty_shadow_hosts
2373                .extend(self.shadow_host_nodes.iter().copied());
2374        }
2375
2376        self.controls_to_form
2377            .retain(|control, form| !removed.contains(control) && !removed.contains(form));
2378        // Detached owners still need their caches cleared, but cannot affect
2379        // the frame. Live owners share the surrounding mutator's redraw.
2380        if dirty.iter().any(|id| {
2381            self.nodes
2382                .get(*id)
2383                .is_some_and(|node| node.flags.is_in_document())
2384        }) {
2385            if self.mutator_depth == 0 {
2386                self.shell_provider.request_redraw();
2387            } else {
2388                self.mutator_redraw_pending = true;
2389            }
2390        }
2391
2392        // PaintDamage deliberately keeps old rectangles until resolve so
2393        // pixels formerly occupied by removed boxes are included in damage.
2394    }
2395
2396    fn purge_dropped_node_references(&mut self) {
2397        if self.node_drop_depth != 0 || self.dropped_node_ids.is_empty() {
2398            return;
2399        }
2400        let removed = std::mem::take(&mut self.dropped_node_ids);
2401        let parents = std::mem::take(&mut self.dropped_node_parents);
2402        let owners = std::mem::take(&mut self.dropped_reference_owners);
2403        self.invalidate_node_references(&removed, parents, owners);
2404    }
2405
2406    /// Remove a node from the node tree, clearing interaction state and
2407    /// invalidating rendering references before the surrounding drop returns.
2408    pub(crate) fn remove_node_from_tree(&mut self, node_id: NodeId) -> Option<Node> {
2409        self.clear_interaction_state_for_removed_node(node_id);
2410        let indexed = self.get_node(node_id).and_then(|node| {
2411            Some((
2412                node.owner_document?,
2413                node.element_data()?.id.as_ref()?.to_string(),
2414            ))
2415        });
2416        if let Some((document_id, id)) = indexed {
2417            self.remove_from_document_id_map(document_id, &id, node_id);
2418        }
2419        self.forget_script_custom_element(node_id);
2420        if self.nodes.contains_key(node_id) {
2421            self.dropped_node_ids.insert(node_id);
2422            let mut owners = FxHashSet::default();
2423            Self::collect_live_reference_owners(
2424                &self.nodes,
2425                &self.hoisted_fixed_parents,
2426                &self.dropped_node_ids,
2427                node_id,
2428                &mut owners,
2429            );
2430            self.dropped_reference_owners.extend(owners);
2431        }
2432        let node = self.nodes.remove(node_id);
2433        if let Some(node) = &node {
2434            self.dropped_node_parents.extend(
2435                [node.parent, node.layout_parent.get()]
2436                    .into_iter()
2437                    .flatten(),
2438            );
2439            self.purge_dropped_node_references();
2440        }
2441        node
2442    }
2443
2444    /// The nearest element ancestor of `node_id` that is still in the
2445    /// document. Used to retarget hover/active state when the node they
2446    /// reference is removed. Tolerates already-removed ancestors (subtree
2447    /// teardown proceeds root-first) by giving up and returning `None`.
2448    fn nearest_surviving_element_ancestor(&self, node_id: NodeId) -> Option<NodeId> {
2449        let mut current = self.get_node(node_id)?.parent;
2450        while let Some(id) = current {
2451            let node = self.get_node(id)?;
2452            if node.is_element() && node.flags.is_in_document() {
2453                return Some(id);
2454            }
2455            current = node.parent;
2456        }
2457        None
2458    }
2459
2460    /// Clear any interaction state (hover/active/focus/mousedown/selection/
2461    /// drag/scrollbar) that references `node_id`, which is being removed from
2462    /// the document, running the usual teardown steps. `node_id` must still be
2463    /// present in the slab.
2464    ///
2465    /// This matches browser semantics (WebKit `hoveredElementDidDetach` /
2466    /// `elementInActiveChainDidDetach`, Blink `HoveredElementDetached` /
2467    /// `ActiveChainNodeDetached`):
2468    /// - Hover and active retarget to the nearest surviving element ancestor
2469    ///   as a *transient bridge*: the HOVER/ACTIVE element-state bits along
2470    ///   the surviving chain stay lit (no one-frame gap in `:hover`/`:active`
2471    ///   styling), and the subsequent hover diff can unset exactly the right
2472    ///   bits. Hover is then re-resolved against the pointer position by
2473    ///   [`Self::refresh_hover`] at the end of the next resolve pass (the
2474    ///   analogue of WebKit's "fake mouse move"), which corrects the bridge
2475    ///   value — including cases where the removed node overflowed its
2476    ///   ancestor's box, so the ancestor was never truly under the pointer.
2477    /// - Focus resets to the body (encoded as `None`), running blur
2478    ///   side-effects (clearing focus element state and disabling IME for
2479    ///   text inputs).
2480    pub(crate) fn clear_interaction_state_for_removed_node(&mut self, node_id: NodeId) {
2481        if !self.nodes.contains_key(node_id) {
2482            return;
2483        }
2484
2485        if self.hover_node_id == Some(node_id) {
2486            self.hover_node_id = self.nearest_surviving_element_ancestor(node_id);
2487            self.hover_node_is_text = false;
2488        }
2489        if self.hover_hit_node_id == Some(node_id) {
2490            self.hover_hit_node_id = None;
2491        }
2492        if self.semantic_hover_node_id == Some(node_id) {
2493            self.semantic_hover_node_id = None;
2494        }
2495        if self.active_node_id == Some(node_id) {
2496            self.active_node_id = self.nearest_surviving_element_ancestor(node_id);
2497        }
2498        if self.focus_node_id == Some(node_id) {
2499            let shell_provider = self.shell_provider.clone();
2500            self.nodes[node_id].blur(shell_provider);
2501            self.focus_node_id = None;
2502        }
2503        if self.mousedown_node_id == Some(node_id) {
2504            self.mousedown_node_id = None;
2505        }
2506        if self.text_selection.anchor.node_or_parent == Some(node_id)
2507            || self.text_selection.focus.node_or_parent == Some(node_id)
2508        {
2509            self.text_selection.clear();
2510        }
2511        if self
2512            .hovered_scrollbar
2513            .is_some_and(|scrollbar| scrollbar.node_id == node_id)
2514        {
2515            self.hovered_scrollbar = None;
2516        }
2517        let drag_references_node = match &self.drag_mode {
2518            DragMode::Panning(state) => state.target == node_id,
2519            DragMode::ScrollbarDrag(state) => state.scrollbar.node_id == node_id,
2520            DragMode::Selecting | DragMode::None => false,
2521        };
2522        if drag_references_node {
2523            self.drag_mode = DragMode::None;
2524        }
2525        if matches!(
2526            &self.scroll_animation,
2527            ScrollAnimationState::Fling(state) if state.target == node_id
2528        ) {
2529            self.scroll_animation = ScrollAnimationState::None;
2530        }
2531        self.scrollbar_activity.remove(&node_id);
2532
2533        // The form-owner map is keyed by control id and was never pruned, so a
2534        // page that re-renders its fields grew an entry per render, every one
2535        // of them a freed slot. Nothing dereferences those any more, but an
2536        // unbounded map keyed on dead ids is a leak either way.
2537        self.controls_to_form.remove(&node_id);
2538    }
2539
2540    pub(crate) fn drop_node_ignoring_parent(&mut self, node_id: NodeId) -> Option<Node> {
2541        self.drop_node_ignoring_parent_with(node_id, &mut |_| {})
2542    }
2543
2544    /// Like [`Self::drop_node_ignoring_parent`], but calls `on_drop` with the id of
2545    /// every dropped node (the node itself and all of its descendants).
2546    pub(crate) fn drop_node_ignoring_parent_with(
2547        &mut self,
2548        node_id: NodeId,
2549        on_drop: &mut dyn FnMut(NodeId),
2550    ) -> Option<Node> {
2551        self.node_drop_depth += 1;
2552        let mut node = self.remove_node_from_tree(node_id);
2553        if let Some(node) = &mut node {
2554            on_drop(node_id);
2555            if let Some(before) = node.before() {
2556                self.drop_node_ignoring_parent_with(before, on_drop);
2557            }
2558            if let Some(after) = node.after() {
2559                self.drop_node_ignoring_parent_with(after, on_drop);
2560            }
2561
2562            for &child in &node.children {
2563                self.drop_node_ignoring_parent_with(child, on_drop);
2564            }
2565            if let Some(contents) = node
2566                .element_data()
2567                .and_then(|element| element.template_contents)
2568            {
2569                self.drop_node_ignoring_parent_with(contents, on_drop);
2570            }
2571
2572            // Anonymous blocks live only in the slab, so deallocate the ones this
2573            // node owns rather than leaking them.
2574            for &anon_id in &node.anonymous_blocks {
2575                self.deallocate_anonymous_block(anon_id);
2576            }
2577
2578            // Drop any attached shadow root (its children are dropped recursively
2579            // via the recursive call below).
2580            #[cfg(feature = "shadow-dom")]
2581            if let Some(shadow_root_id) = node.shadow_root_id() {
2582                self.shadow_host_nodes.remove(&node_id);
2583                self.dirty_shadow_hosts.remove(&node_id);
2584                self.custom_element_nodes.remove(&node_id);
2585                self.drop_node_ignoring_parent_with(shadow_root_id, on_drop);
2586            }
2587        }
2588        self.node_drop_depth -= 1;
2589        self.purge_dropped_node_references();
2590        node
2591    }
2592
2593    /// Deallocate an anonymous block created in a previous construction
2594    /// round, along with any anonymous blocks nested within it.
2595    pub(crate) fn deallocate_anonymous_block(&mut self, anon_id: NodeId) {
2596        // The block may already have been removed from the slab (e.g. a
2597        // whitespace-only anonymous block dropped during construction).
2598        if !self.nodes.contains_key(anon_id) {
2599            return;
2600        }
2601
2602        // Free any anonymous blocks that this block owns before removing it.
2603        self.node_drop_depth += 1;
2604        let nested = std::mem::take(&mut self.nodes[anon_id].anonymous_blocks);
2605        for nested_id in nested {
2606            self.deallocate_anonymous_block(nested_id);
2607        }
2608
2609        self.remove_node_from_tree(anon_id);
2610        self.node_drop_depth -= 1;
2611        self.purge_dropped_node_references();
2612    }
2613
2614    pub fn create_text_node(&mut self, text: &str) -> NodeId {
2615        self.create_text_node_owned(text.to_string())
2616    }
2617
2618    /// Create a text node using an existing string allocation.
2619    pub fn create_text_node_owned(&mut self, content: String) -> NodeId {
2620        let data = NodeData::Text(TextNodeData::new(content));
2621        self.create_node(data)
2622    }
2623
2624    pub fn deep_clone_node(&mut self, node_id: NodeId) -> NodeId {
2625        // Load existing node
2626        let node = &self.nodes[node_id];
2627        let mut data = node.data.clone();
2628
2629        match &mut data {
2630            NodeData::Element(elem) | NodeData::AnonymousBlock(elem) => {
2631                if let Some(arc) = elem.style_attribute.as_mut() {
2632                    let read_guard = self.guard().read();
2633                    let block = arc.read_with(&read_guard);
2634                    *arc = ServoArc::new(self.guard().wrap(block.clone()));
2635                }
2636            }
2637            _ => {}
2638        }
2639
2640        let mut children = node.children.clone();
2641        #[cfg(feature = "shadow-dom")]
2642        let shadow_source = node.shadow_root_id();
2643        let template_contents = node
2644            .element_data()
2645            .and_then(|element| element.template_contents);
2646        let owner_document = node.owner_document;
2647        let markup = node.markup.clone();
2648        let inert_script = node
2649            .flags
2650            .contains(crate::node::NodeFlags::IS_PARSER_INERT_SCRIPT);
2651
2652        // Create new node
2653        let new_node_id = self.create_node(data);
2654        self.inherit_stash_classification(node_id, new_node_id);
2655        self.nodes[new_node_id].owner_document = owner_document;
2656        self.nodes[new_node_id].markup = markup;
2657        self.nodes[new_node_id]
2658            .flags
2659            .set(crate::node::NodeFlags::IS_PARSER_INERT_SCRIPT, inert_script);
2660        if let Some(document_id) = owner_document {
2661            let id = self.nodes[new_node_id]
2662                .element_data()
2663                .and_then(|element| element.id.as_ref())
2664                .map(ToString::to_string);
2665            if let Some(id) = id {
2666                self.add_to_document_id_map(document_id, &id, new_node_id);
2667            }
2668        }
2669        if let Some(contents) = template_contents {
2670            let cloned_contents = self.deep_clone_node(contents);
2671            self.nodes[new_node_id]
2672                .element_data_mut()
2673                .expect("template clone must be an element")
2674                .template_contents = Some(cloned_contents);
2675        }
2676
2677        // Recursively clone children
2678        for child_id in &mut children {
2679            *child_id = self.deep_clone_node(*child_id);
2680        }
2681        for &child_id in &children {
2682            self.nodes[child_id].parent = Some(new_node_id);
2683            self.attach_script_custom_element_subtree(child_id, new_node_id);
2684        }
2685        self.nodes[new_node_id].children = children;
2686
2687        // Only a shadow root that opted into `clonable` is copied. Imperative
2688        // roots keep the previous behavior of not cloning.
2689        #[cfg(feature = "shadow-dom")]
2690        if let Some(source_root) = shadow_source {
2691            let clonable = self
2692                .nodes
2693                .get(source_root)
2694                .and_then(|node| node.shadow_root_data())
2695                .is_some_and(|root| root.clonable);
2696            if clonable {
2697                let mode = self.nodes[source_root].shadow_root_data().unwrap().mode;
2698                let serializable = self.nodes[source_root]
2699                    .shadow_root_data()
2700                    .unwrap()
2701                    .serializable;
2702                let delegates_focus = self.nodes[source_root]
2703                    .shadow_root_data()
2704                    .unwrap()
2705                    .delegates_focus;
2706                let declarative = self.nodes[source_root]
2707                    .shadow_root_data()
2708                    .unwrap()
2709                    .declarative;
2710                let mut shadow_children = self.nodes[source_root].children.clone();
2711                let new_root = self.attach_shadow(new_node_id, mode);
2712                if let Some(root) = self.nodes[new_root].shadow_root_data_mut() {
2713                    root.clonable = true;
2714                    root.serializable = serializable;
2715                    root.delegates_focus = delegates_focus;
2716                    root.declarative = declarative;
2717                }
2718                for child_id in &mut shadow_children {
2719                    *child_id = self.deep_clone_node(*child_id);
2720                }
2721                for &child_id in &shadow_children {
2722                    self.nodes[child_id].parent = Some(new_root);
2723                    self.attach_script_custom_element_subtree(child_id, new_root);
2724                }
2725                self.nodes[new_root].children = shadow_children;
2726            }
2727        }
2728
2729        new_node_id
2730    }
2731
2732    pub(crate) fn remove_and_drop_pe(&mut self, node_id: NodeId) -> Option<Node> {
2733        fn remove_pe_ignoring_parent(doc: &mut BaseDocument, node_id: NodeId) -> Option<Node> {
2734            let mut node = doc.remove_node_from_tree(node_id);
2735            if let Some(node) = &mut node {
2736                for &child in &node.children {
2737                    remove_pe_ignoring_parent(doc, child);
2738                }
2739                for &anon_id in &node.anonymous_blocks {
2740                    doc.deallocate_anonymous_block(anon_id);
2741                }
2742            }
2743            node
2744        }
2745
2746        self.node_drop_depth += 1;
2747        let node = remove_pe_ignoring_parent(self, node_id);
2748
2749        // Update child_idx values
2750        if let Some(parent_id) = node.as_ref().and_then(|node| node.parent) {
2751            let parent = &mut self.nodes[parent_id];
2752            parent.children.retain(|id| *id != node_id);
2753        }
2754
2755        self.node_drop_depth -= 1;
2756        self.purge_dropped_node_references();
2757        node
2758    }
2759
2760    pub(crate) fn resolve_url(&self, raw: &str) -> url::Url {
2761        self.url.resolve_relative(raw).unwrap_or_else(|| {
2762            panic!(
2763                "to be able to resolve {raw} with the base_url: {:?}",
2764                *self.url
2765            )
2766        })
2767    }
2768
2769    /// Navigate to `raw`, resolved against this document's base URL.
2770    ///
2771    /// The same route a link click takes, exposed so that script can reach it:
2772    /// `location.assign`, `location.replace` and `location.reload` had nowhere
2773    /// to go, because `resolve_url` and the navigation provider are both
2774    /// internal to this crate. Returns `false` when `raw` will not resolve,
2775    /// so the caller can report that rather than navigate somewhere wrong.
2776    pub fn navigate_to_url(&self, raw: &str) -> bool {
2777        let Some(url) = self.url.resolve_relative(raw) else {
2778            return false;
2779        };
2780        self.navigation_provider
2781            .navigate_to(blitz_traits::navigation::NavigationOptions::new(
2782                url,
2783                None,
2784                self.id(),
2785            ));
2786        true
2787    }
2788
2789    /// This document's URL, as a page's `location.href` reads it.
2790    pub fn current_url(&self) -> String {
2791        self.url.to_string()
2792    }
2793
2794    pub fn print_tree(&self) {
2795        crate::util::walk_tree(0, self.root_node());
2796    }
2797
2798    pub fn print_subtree(&self, node_id: NodeId) {
2799        crate::util::walk_tree(0, &self.nodes[node_id]);
2800    }
2801
2802    pub fn reload_resource_by_href(&mut self, href_to_reload: &str) {
2803        for &node_id in self.nodes_to_stylesheet.keys() {
2804            let node = &self.nodes[node_id];
2805            let Some(element) = node.element_data() else {
2806                continue;
2807            };
2808
2809            if element.name.local == local_name!("link") {
2810                if let Some(href) = element.attr(local_name!("href")) {
2811                    // println!("Node {node_id} {href} {href_to_reload} {} {}", resolved_href.as_str(), resolved_href.as_str() == url_to_reload);
2812                    if href == href_to_reload {
2813                        let resolved_href = self.resolve_url(href);
2814                        self.net_provider.fetch(
2815                            self.id(),
2816                            self.build_request(resolved_href.clone())
2817                                .destination(RequestDestination::Style),
2818                            ResourceHandler::boxed(
2819                                self.tx.clone(),
2820                                self.id,
2821                                Some(node_id),
2822                                self.shell_provider.clone(),
2823                                StylesheetHandler {
2824                                    source_url: resolved_href,
2825                                    guard: self.guard.clone(),
2826                                    net_provider: self.net_provider.clone(),
2827                                    abort_signal: self.abort_signal.clone(),
2828                                },
2829                            ),
2830                        );
2831                    }
2832                }
2833            }
2834        }
2835    }
2836
2837    pub fn process_style_element(&mut self, target_id: NodeId) {
2838        let css = self.nodes[target_id].text_content();
2839        let css = html_escape::decode_html_entities(&css);
2840        let sheet = self.make_stylesheet(&css, Origin::Author);
2841        self.add_stylesheet_for_node(sheet, target_id);
2842    }
2843
2844    pub fn remove_user_agent_stylesheet(&mut self, contents: &str) {
2845        if contents == DEFAULT_CSS && self.default_ua_stylesheet_pending {
2846            self.default_ua_stylesheet_pending = false;
2847            self.default_ua_stylesheet_cache.take();
2848            self.default_ua_stylesheet_before = None;
2849            return;
2850        }
2851        // Install before an explicit mutation can remove the insertion anchor.
2852        self.ensure_default_ua_stylesheet();
2853        if let Some(sheet) = self.ua_stylesheets.remove(contents) {
2854            self.stylist.remove_stylesheet(sheet, &self.guard.read());
2855        }
2856        if contents == DEFAULT_CSS {
2857            self.default_ua_stylesheet_cache.take();
2858        }
2859    }
2860
2861    /// Whether ranges or selection endpoints can observe text replacement.
2862    pub fn has_live_text_references(&self) -> bool {
2863        self.dom_selection.is_some()
2864            || self.text_selection.anchor.is_some()
2865            || self.text_selection.focus.is_some()
2866            || self
2867                .live_ranges
2868                .iter()
2869                .any(|range| range.strong_count() != 0)
2870    }
2871
2872    /// The document's base URL
2873    pub fn url(&self) -> &url::Url {
2874        &self.url
2875    }
2876
2877    /// Iterate over the author stylesheets (from `<style>` and `<link>` nodes)
2878    /// currently associated with this document
2879    pub fn author_stylesheets(&self) -> impl Iterator<Item = &DocumentStyleSheet> {
2880        self.nodes_to_stylesheet.values()
2881    }
2882
2883    /// Iterate over the user-agent stylesheets currently associated with this document
2884    pub fn useragent_stylesheets(&self) -> impl Iterator<Item = &DocumentStyleSheet> {
2885        let pending = self.default_ua_stylesheet_pending.then(|| {
2886            self.default_ua_stylesheet_cache
2887                .get_or_init(|| self.default_css_stylesheet())
2888        });
2889        self.ua_stylesheets.values().chain(pending)
2890    }
2891
2892    pub fn add_user_agent_stylesheet(&mut self, css: &str) {
2893        self.ensure_default_ua_stylesheet();
2894        self.append_user_agent_stylesheet(css);
2895    }
2896
2897    fn append_user_agent_stylesheet(&mut self, css: &str) -> DocumentStyleSheet {
2898        let sheet = if css == DEFAULT_CSS {
2899            self.default_css_stylesheet()
2900        } else {
2901            self.make_stylesheet(css, Origin::UserAgent)
2902        };
2903        self.ua_stylesheets.insert(css.to_string(), sheet.clone());
2904        self.stylist
2905            .append_stylesheet(sheet.clone(), &self.guard.read());
2906        sheet
2907    }
2908
2909    pub(crate) fn ensure_default_ua_stylesheet(&mut self) {
2910        if !self.default_ua_stylesheet_pending {
2911            return;
2912        }
2913
2914        let sheet = self
2915            .default_ua_stylesheet_cache
2916            .get_or_init(|| self.default_css_stylesheet())
2917            .clone();
2918        self.ua_stylesheets
2919            .insert(DEFAULT_CSS.to_string(), sheet.clone());
2920        if let Some(before) = self.default_ua_stylesheet_before.take() {
2921            self.stylist
2922                .insert_stylesheet_before(sheet, before, &self.guard.read());
2923        } else {
2924            self.stylist.append_stylesheet(sheet, &self.guard.read());
2925        }
2926        self.default_ua_stylesheet_pending = false;
2927    }
2928
2929    fn default_css_stylesheet(&self) -> DocumentStyleSheet {
2930        let template = DEFAULT_CSS_TEMPLATE.get_or_init(|| {
2931            let template_lock = SharedRwLock::new();
2932            let neutral_url = DocumentUrl::default();
2933            // DEFAULT_CSS uses absolute namespace URLs and a data: font source,
2934            // with no relative URLs or imports, so the cached parse is document-neutral.
2935            Stylesheet::from_str(
2936                DEFAULT_CSS,
2937                neutral_url.url_extra_data(),
2938                Origin::UserAgent,
2939                ServoArc::new(template_lock.wrap(MediaList::empty())),
2940                template_lock,
2941                None,
2942                None,
2943                QuirksMode::NoQuirks,
2944                AllowImportRules::No,
2945            )
2946        });
2947
2948        let template_guard = template.shared_lock.read();
2949        let url_data = self.url.url_extra_data();
2950        let contents = template.contents.read_with(&template_guard).deep_clone(
2951            &self.guard,
2952            Some(&url_data),
2953            &template_guard,
2954        );
2955        let media = template.media.read_with(&template_guard).clone();
2956
2957        DocumentStyleSheet(ServoArc::new(Stylesheet {
2958            contents: self.guard.wrap(contents),
2959            media: ServoArc::new(self.guard.wrap(media)),
2960            shared_lock: self.guard.clone(),
2961            disabled: AtomicBool::new(false),
2962        }))
2963    }
2964
2965    pub fn make_stylesheet(&self, css: impl AsRef<str>, origin: Origin) -> DocumentStyleSheet {
2966        let data = Stylesheet::from_str(
2967            css.as_ref(),
2968            self.url.url_extra_data(),
2969            origin,
2970            ServoArc::new(self.guard.wrap(MediaList::empty())),
2971            self.guard.clone(),
2972            Some(&StylesheetLoader {
2973                tx: self.tx.clone(),
2974                doc_id: self.id,
2975                net_provider: self.net_provider.clone(),
2976                shell_provider: self.shell_provider.clone(),
2977                abort_signal: self.abort_signal.clone(),
2978            }),
2979            None,
2980            QuirksMode::NoQuirks,
2981            AllowImportRules::Yes,
2982        );
2983
2984        DocumentStyleSheet(ServoArc::new(data))
2985    }
2986
2987    pub fn upsert_stylesheet_for_node(&mut self, node_id: NodeId) {
2988        let raw_styles = self.nodes[node_id].text_content();
2989        let sheet = self.make_stylesheet(raw_styles, Origin::Author);
2990        self.add_stylesheet_for_node(sheet, node_id);
2991    }
2992
2993    pub fn add_stylesheet_for_node(&mut self, stylesheet: DocumentStyleSheet, node_id: NodeId) {
2994        self.platform_initial_sheet_media(&stylesheet, node_id);
2995        #[cfg(feature = "shadow-dom")]
2996        if let Some(root_id) = self.containing_shadow_root(node_id) {
2997            // A sheet that moved from the document into a shadow tree leaves
2998            // the document Stylist first.
2999            if self.document_sheet_nodes.remove(&node_id)
3000                && let Some(old) = self.nodes_to_stylesheet.get(&node_id).cloned()
3001            {
3002                self.stylist.remove_stylesheet(old, &self.guard.read());
3003            }
3004            self.install_shadow_stylesheet(root_id, node_id, stylesheet);
3005            return;
3006        }
3007
3008        let old = self.nodes_to_stylesheet.insert(node_id, stylesheet.clone());
3009
3010        if let Some(old) = old
3011            && self.document_sheet_nodes.contains(&node_id)
3012        {
3013            self.stylist.remove_stylesheet(old, &self.guard.read())
3014        }
3015        self.document_sheet_nodes.insert(node_id);
3016
3017        // Fetch @font-face fonts
3018        crate::net::fetch_font_face(
3019            self.tx.clone(),
3020            self.id,
3021            Some(node_id),
3022            &stylesheet.0,
3023            &self.net_provider,
3024            &self.shell_provider,
3025            &self.guard.read(),
3026            self.abort_signal.as_ref(),
3027            &mut self.web_fonts,
3028            self.font_epoch,
3029        );
3030
3031        // Store data on element
3032        let element = &mut self.nodes[node_id].element_data_mut().unwrap();
3033        element.special_data = SpecialElementData::Stylesheet(stylesheet.clone());
3034
3035        // TODO: Nodes could potentially get reused so ordering by node_id might be wrong.
3036        // Only sheets the document Stylist holds can be an insertion point: shadow-root sheets are
3037        // in `nodes_to_stylesheet` too, and stylo panics on a `before` sheet it does not have.
3038        let insertion_point = self
3039            .nodes_to_stylesheet
3040            .range((Bound::Excluded(node_id), Bound::Unbounded))
3041            .find(|(id, _)| self.document_sheet_nodes.contains(id))
3042            .map(|(_, sheet)| sheet);
3043
3044        if let Some(insertion_point) = insertion_point {
3045            self.stylist.insert_stylesheet_before(
3046                stylesheet,
3047                insertion_point.clone(),
3048                &self.guard.read(),
3049            )
3050        } else {
3051            self.stylist
3052                .append_stylesheet(stylesheet, &self.guard.read())
3053        }
3054    }
3055
3056    pub fn handle_messages(&mut self) {
3057        let messages = self.rx.take_pending();
3058        for msg in messages {
3059            let msg =
3060                Arc::try_unwrap(msg).unwrap_or_else(|_| panic!("document event has one consumer"));
3061            self.handle_message(msg);
3062        }
3063    }
3064
3065    pub fn handle_message(&mut self, msg: DocumentEvent) {
3066        match msg {
3067            DocumentEvent::ResourceLoad(resource) => self.load_resource(resource),
3068            DocumentEvent::NavigateIframe { node_id, url } => self.navigate_iframe(node_id, url),
3069        }
3070    }
3071
3072    /// Whether the Document has pending requests for "critical" resources (that should block rendering)
3073    pub fn has_pending_critical_resources(&self) -> bool {
3074        !self.pending_critical_resources.is_empty()
3075    }
3076
3077    /// How many distinct image URLs are still being fetched.
3078    ///
3079    /// Images are deliberately not "critical" resources, so they never block
3080    /// rendering. An embedder that needs a settled page (a screenshot, a test,
3081    /// a print) has no other way to tell an image that is still in flight from
3082    /// one that will never arrive.
3083    pub fn pending_image_count(&self) -> usize {
3084        self.pending_images.len()
3085    }
3086
3087    /// Take decoded image outcomes since the previous call.
3088    pub fn take_image_load_outcomes(&mut self) -> Vec<(NodeId, u64, bool)> {
3089        std::mem::take(&mut self.image_load_outcomes)
3090            .into_iter()
3091            .filter(|(node, generation, _)| {
3092                self.image_load_states
3093                    .get(node)
3094                    .is_some_and(|(_, current)| current == generation)
3095            })
3096            .collect::<Vec<_>>()
3097    }
3098
3099    pub(crate) fn begin_image_load(&mut self, node: NodeId, source: String) -> u64 {
3100        let generation = self
3101            .image_load_states
3102            .get(&node)
3103            .map_or(1, |(_, generation)| generation.wrapping_add(1).max(1));
3104        self.image_load_states.insert(node, (source, generation));
3105        generation
3106    }
3107
3108    pub(crate) fn cancel_image_load(&mut self, node: NodeId) {
3109        self.image_load_states.remove(&node);
3110    }
3111
3112    pub(crate) fn finish_image_load(&mut self, node: NodeId, source: &str, loaded: bool) {
3113        if let Some((current_source, generation)) = self.image_load_states.get(&node)
3114            && current_source == source
3115            && self.image_load_outcomes.len() < MAX_PENDING_IMAGE_OUTCOMES
3116            && !self
3117                .image_load_outcomes
3118                .iter()
3119                .any(|(queued_node, queued_generation, _)| {
3120                    *queued_node == node && queued_generation == generation
3121                })
3122        {
3123            self.image_load_outcomes.push((node, *generation, loaded));
3124        }
3125    }
3126
3127    pub fn load_resource(&mut self, res: ResourceLoadResponse) {
3128        self.pending_critical_resources.remove(&res.request_id);
3129
3130        let resource = match res.result {
3131            Ok(resource) => resource,
3132            Err(err) => {
3133                if let Some(node_id) = res.node_id {
3134                    self.clear_failed_iframe_load(node_id, res.request_id);
3135                }
3136                if let Some(url) = res.resolved_url.as_ref() {
3137                    let waiting_nodes = self.pending_images.remove(url).unwrap_or_default();
3138                    for (node, image_type) in waiting_nodes.iter() {
3139                        if matches!(image_type, ImageType::Image) {
3140                            self.finish_image_load(*node, url, false);
3141                        }
3142                    }
3143                    #[cfg(feature = "tracing")]
3144                    tracing::warn!(
3145                        url = url.as_str(),
3146                        waiting_nodes = waiting_nodes.len(),
3147                        error = err.as_str(),
3148                        "Resource load failed"
3149                    );
3150                    #[cfg(not(feature = "tracing"))]
3151                    let _ = (waiting_nodes, err);
3152                } else {
3153                    #[cfg(feature = "tracing")]
3154                    tracing::warn!(error = err.as_str(), "Resource load failed (no url)");
3155                    #[cfg(not(feature = "tracing"))]
3156                    let _ = err;
3157                }
3158                return;
3159            }
3160        };
3161
3162        let (resource, font_ticket) = match resource {
3163            Resource::TrackedFont(bytes, overrides, ticket) => {
3164                if ticket.css && ticket.epoch != self.font_epoch {
3165                    ticket.finish(false);
3166                    return;
3167                }
3168                (Resource::Font(bytes, overrides), Some(ticket))
3169            }
3170            resource => (resource, None),
3171        };
3172        if matches!(&resource, Resource::Css(_) | Resource::Font(_, _))
3173            && res.node_id.is_some_and(|id| {
3174                self.get_node(id)
3175                    .is_none_or(|node| !node.flags.is_in_document())
3176            })
3177        {
3178            if let Some(ticket) = font_ticket {
3179                ticket.finish(false);
3180            }
3181            return;
3182        }
3183
3184        match resource {
3185            Resource::Css(css) => {
3186                let node_id = res.node_id.unwrap();
3187                self.add_stylesheet_for_node(css, node_id);
3188            }
3189            Resource::ImportSheet(import_rule, sheet) => {
3190                // The write that used to happen on the network worker. Here it
3191                // is on the thread that owns styling, so it cannot collide
3192                // with a concurrent read of the same lock.
3193                //
3194                // Scoped, because the `@font-face` scan below needs a read of
3195                // the same lock and this is an `AtomicRefCell`: holding the
3196                // write across it would deadlock against itself rather than
3197                // wait.
3198                {
3199                    let mut guard = self.guard.write();
3200                    import_rule.write_with(&mut guard).stylesheet =
3201                        style::stylesheets::import_rule::ImportSheet::Sheet(sheet.clone());
3202                }
3203
3204                // The same scan `add_stylesheet_for_node` does for a top-level
3205                // sheet. An imported sheet may declare fonts too, and until now
3206                // nothing fetched them from a thread allowed to read the lock.
3207                crate::net::fetch_font_face(
3208                    self.tx.clone(),
3209                    self.id,
3210                    res.node_id,
3211                    &sheet,
3212                    &self.net_provider,
3213                    &self.shell_provider,
3214                    &self.guard.read(),
3215                    self.abort_signal.as_ref(),
3216                    &mut self.web_fonts,
3217                    self.font_epoch,
3218                );
3219            }
3220            Resource::Image(_kind, width, height, image_data) => {
3221                // Create the ImageData and cache it
3222                let image = ImageData::Raster(RasterImageData::new(width, height, image_data));
3223
3224                let Some(url) = res.resolved_url.as_ref() else {
3225                    return;
3226                };
3227
3228                self.apply_loaded_image(url, image);
3229            }
3230            #[cfg(feature = "image-formats")]
3231            Resource::JxlImage(_kind, image) => {
3232                if let Some(url) = res.resolved_url.as_ref() {
3233                    self.apply_loaded_image(url, ImageData::Raster(image));
3234                }
3235            }
3236            #[cfg(feature = "svg")]
3237            Resource::Svg(_kind, svg) => {
3238                // Create the ImageData and cache it
3239                let image = ImageData::Svg(svg);
3240
3241                let Some(url) = res.resolved_url.as_ref() else {
3242                    return;
3243                };
3244
3245                self.apply_loaded_image(url, image);
3246            }
3247            Resource::DocumentSrc(html) => {
3248                let Some(node_id) = res.node_id else {
3249                    return;
3250                };
3251                self.apply_iframe_html(node_id, res.request_id, res.resolved_url, &html);
3252            }
3253            Resource::Font(bytes, overrides) => {
3254                let font = Blob::new(Arc::new(bytes));
3255
3256                // Build a `FontInfoOverride` from the `@font-face` descriptors
3257                // captured during stylesheet parsing. Without this, parley
3258                // reads the family name from the TTF's own metadata, which
3259                // means CSS `font-family: 'Avenir Book'` won't match a font
3260                // file that internally identifies as `Avenir 45 Book`.
3261                let weight_override = overrides.weight.map(parley::fontique::FontWeight::new);
3262                let info_override = parley::fontique::FontInfoOverride {
3263                    family_name: overrides.family_name.as_deref(),
3264                    weight: weight_override,
3265                    style: overrides.style,
3266                    ..Default::default()
3267                };
3268
3269                // TODO: Investigate eliminating double-box
3270                let mut global_font_ctx = self.font_ctx.lock().unwrap();
3271                let registered = global_font_ctx
3272                    .collection
3273                    .register_fonts(font.clone(), Some(info_override));
3274                let registered = !registered.is_empty();
3275
3276                #[cfg(feature = "parallel-construct")]
3277                {
3278                    rayon::broadcast(|_ctx| {
3279                        let mut font_ctx = self
3280                            .thread_font_contexts
3281                            .get_or(|| RefCell::new(Box::new(global_font_ctx.clone())))
3282                            .borrow_mut();
3283                        font_ctx
3284                            .collection
3285                            .register_fonts(font.clone(), Some(info_override));
3286                    });
3287                }
3288                drop(global_font_ctx);
3289
3290                // TODO: see if we can only invalidate if resolved fonts may have changed
3291                self.invalidate_inline_contexts();
3292                if let Some(ticket) = font_ticket {
3293                    ticket.finish(registered);
3294                }
3295            }
3296            Resource::TrackedFont(..) => unreachable!("tracked font was normalized"),
3297            Resource::None => {
3298                // Do nothing
3299            }
3300        }
3301    }
3302
3303    /// Cache a loaded image and apply it to all nodes waiting on it
3304    /// (`<img>` elements, `background-image` layers and `mask-image` layers).
3305    fn apply_loaded_image(&mut self, url: &str, image: ImageData) {
3306        // Get all nodes waiting for this image
3307        let waiting_nodes = self.pending_images.remove(url).unwrap_or_default();
3308
3309        #[cfg(feature = "tracing")]
3310        tracing::info!(
3311            "Image {url} loaded, applying to {} nodes",
3312            waiting_nodes.len()
3313        );
3314
3315        // Cache the image
3316        self.image_cache.insert(url.to_string(), image.clone());
3317
3318        // Apply to all waiting nodes
3319        for (node_id, image_type) in waiting_nodes {
3320            if matches!(image_type, ImageType::Image) {
3321                if !self
3322                    .image_load_states
3323                    .get(&node_id)
3324                    .is_some_and(|(current_source, _)| current_source == url)
3325                {
3326                    continue;
3327                }
3328                self.finish_image_load(node_id, url, true);
3329            }
3330            let Some(node) = self.get_node_mut(node_id) else {
3331                continue;
3332            };
3333
3334            match image_type {
3335                ImageType::Image => {
3336                    node.element_data_mut().unwrap().special_data =
3337                        SpecialElementData::Image(Box::new(image.clone()));
3338
3339                    // Clear layout cache
3340                    node.cache_mut().clear();
3341                    node.insert_damage(ALL_DAMAGE);
3342                }
3343                ImageType::Background(idx) | ImageType::Mask(idx) => {
3344                    let layer_image = node.element_data_mut().and_then(|el| {
3345                        let images = match image_type {
3346                            ImageType::Background(_) => &mut el.background_images,
3347                            ImageType::Mask(_) => &mut el.mask_images,
3348                            ImageType::Image => unreachable!(),
3349                        };
3350                        images.get_mut(idx)
3351                    });
3352                    if let Some(Some(layer_image)) = layer_image {
3353                        layer_image.status = Status::Ok;
3354                        layer_image.image = image.clone();
3355                    }
3356                }
3357            }
3358        }
3359    }
3360
3361    pub fn snapshot_node(&mut self, node_id: NodeId) {
3362        let node = &mut self.nodes[node_id];
3363
3364        // Do not snapshot nodes that have never been styled. A snapshot records an element's
3365        // pre-mutation state so a restyle can diff selector matches then-vs-now. An element
3366        // that has never been styled has no "then" to diff against. Snapshotting it anyway
3367        // makes Stylo's invalidation unwrap its (absent) primary style and panic.
3368        let has_been_styled = node.primary_styles().is_some();
3369        if !has_been_styled {
3370            return;
3371        }
3372
3373        let opaque_node_id = TNode::opaque(&&*node);
3374        node.set_has_snapshot(true);
3375        node.snapshot_handled()
3376            .store(false, std::sync::atomic::Ordering::SeqCst);
3377
3378        // TODO: handle invalidations other than hover
3379        if let Some(_existing_snapshot) = self.snapshots.get_mut(&opaque_node_id) {
3380            // Do nothing
3381            // TODO: update snapshot
3382        } else {
3383            let attrs: Option<Vec<_>> = node.attrs().map(|attrs| {
3384                attrs
3385                    .iter()
3386                    .map(|attr| {
3387                        let ident = AttrIdentifier {
3388                            local_name: GenericAtomIdent(attr.name.local.clone()),
3389                            name: GenericAtomIdent(attr.name.local.clone()),
3390                            namespace: GenericAtomIdent(attr.name.ns.clone()),
3391                            prefix: None,
3392                        };
3393
3394                        let value = if attr.name.local == local_name!("id") {
3395                            AttrValue::Atom(Atom::from(&*attr.value))
3396                        } else if attr.name.local == local_name!("class") {
3397                            let classes = attr
3398                                .value
3399                                .split_ascii_whitespace()
3400                                .map(Atom::from)
3401                                .collect();
3402                            // Stylo's `AttrValue` owns a `String`, so the atom
3403                            // is materialised here. This is the one place
3404                            // interning is paid back out, and it is bounded:
3405                            // once per snapshotted attribute, not per element
3406                            // per frame.
3407                            AttrValue::TokenList(OnceLock::from(attr.value.to_string()), classes)
3408                        } else {
3409                            AttrValue::String(attr.value.to_string())
3410                        };
3411
3412                        (ident, value)
3413                    })
3414                    .collect()
3415            });
3416
3417            self.snapshots.insert(
3418                opaque_node_id,
3419                ServoElementSnapshot {
3420                    state: Some(*node.element_state()),
3421                    attrs,
3422                    changed_attrs: Vec::new(),
3423                    class_changed: false,
3424                    id_changed: false,
3425                    other_attributes_changed: false,
3426                },
3427            );
3428        }
3429    }
3430
3431    /// Preserve the original attributes and accumulate names changed before traversal.
3432    pub(crate) fn snapshot_attribute(&mut self, node_id: NodeId, name: &markup5ever::LocalName) {
3433        self.snapshot_node(node_id);
3434        let opaque_node_id = TNode::opaque(&&self.nodes[node_id]);
3435        if let Some(snapshot) = self.snapshots.get_mut(&opaque_node_id) {
3436            let changed_attr = GenericAtomIdent(name.clone());
3437            if !snapshot.changed_attrs.contains(&changed_attr) {
3438                snapshot.changed_attrs.extend(std::iter::once(changed_attr));
3439            }
3440            if name == &local_name!("id") {
3441                snapshot.id_changed = true;
3442            } else if name == &local_name!("class") {
3443                snapshot.class_changed = true;
3444            } else {
3445                snapshot.other_attributes_changed = true;
3446            }
3447        }
3448    }
3449
3450    /// Snapshot a node and act on it, if it is still there.
3451    ///
3452    /// Tolerant of a node that has gone, because the ids reaching this are
3453    /// remembered across events — focus, hover, the last press — and the node
3454    /// they name can be removed between one event and the next. Indexing
3455    /// directly turned that ordinary case into a panic inside an event handler.
3456    pub fn snapshot_node_and(&mut self, node_id: NodeId, cb: impl FnOnce(&mut Node)) {
3457        if !self.nodes.contains_key(node_id) {
3458            return;
3459        }
3460        self.snapshot_node(node_id);
3461        cb(&mut self.nodes[node_id]);
3462    }
3463
3464    // Takes (x, y) co-ordinates (relative to the )
3465    pub fn hit(&self, x: f32, y: f32) -> Option<HitResult> {
3466        self.hit_with_scrollbar(x, y).0
3467    }
3468
3469    /// Walk up the tree to the nearest DOM node whose id is stable across
3470    /// box-tree reconstruction, so canonicalized interaction state never goes
3471    /// stale.
3472    ///
3473    /// Layout-generated nodes (anonymous blocks and `::before`/`::after`
3474    /// pseudo-elements, both stored as anonymous blocks) get new ids on every
3475    /// reconstruction, so we skip any anonymous node *and* a non-anonymous node
3476    /// whose parent is anonymous (the pseudo's text content). The first
3477    /// non-anonymous node with a non-anonymous parent is a real DOM node; the
3478    /// root element's `Document` parent guarantees termination.
3479    ///
3480    /// Returns `None` if `node_id` (or an ancestor) no longer exists.
3481    pub fn nearest_non_anonymous_ancestor(&self, node_id: NodeId) -> Option<NodeId> {
3482        // Recurse up the tree keeping a window of the current node and its
3483        // parent, advancing one step per iteration so each node is looked up
3484        // exactly once.
3485        let mut node = self.get_node(node_id)?;
3486        loop {
3487            let parent = match node.parent {
3488                Some(parent_id) => self.get_node(parent_id)?,
3489                None => return Some(node.id),
3490            };
3491            if !node.is_anonymous() && !parent.is_anonymous() {
3492                return Some(node.id);
3493            }
3494            node = parent;
3495        }
3496    }
3497
3498    pub fn focus_next_node(&mut self) -> Option<NodeId> {
3499        let focussed_node_id = self.get_focussed_node_id()?;
3500        let id = self.next_node(&self.nodes[focussed_node_id], |node| node.is_focussable())?;
3501        self.set_focus_to(id);
3502        Some(id)
3503    }
3504
3505    /// Move focus to the previous focussable node in the document
3506    pub fn focus_prev_node(&mut self) -> Option<NodeId> {
3507        let focussed_node_id = self.get_focussed_node_id()?;
3508        let id = self.prev_node(&self.nodes[focussed_node_id], |node| node.is_focussable())?;
3509        self.set_focus_to(id);
3510        Some(id)
3511    }
3512
3513    /// Clear the focussed node
3514    pub fn clear_focus(&mut self) {
3515        if let Some(id) = self.focus_node_id {
3516            let shell_provider = self.shell_provider.clone();
3517            self.snapshot_node_and(id, |node| node.blur(shell_provider));
3518            self.focus_node_id = None;
3519        }
3520    }
3521
3522    pub fn set_mousedown_node_id(&mut self, node_id: Option<NodeId>) {
3523        self.mousedown_node_id = node_id.and_then(|id| self.nearest_non_anonymous_ancestor(id));
3524    }
3525    pub fn set_focus_to(&mut self, focus_node_id: NodeId) -> bool {
3526        let Some(focus_node_id) = self.nearest_non_anonymous_ancestor(focus_node_id) else {
3527            return false;
3528        };
3529        if Some(focus_node_id) == self.focus_node_id {
3530            return false;
3531        }
3532
3533        #[cfg(feature = "tracing")]
3534        tracing::info!("Focussed node {focus_node_id}");
3535
3536        let shell_provider = self.shell_provider.clone();
3537
3538        // Remove focus from the old node
3539        if let Some(id) = self.focus_node_id {
3540            self.snapshot_node_and(id, |node| node.blur(shell_provider.clone()));
3541        }
3542
3543        // Focus the new node
3544        self.snapshot_node_and(focus_node_id, |node| node.focus(shell_provider));
3545
3546        self.focus_node_id = Some(focus_node_id);
3547
3548        true
3549    }
3550
3551    pub fn active_node(&mut self) -> bool {
3552        let Some(hover_node_id) = self.get_hover_node_id() else {
3553            return false;
3554        };
3555
3556        if let Some(active_node_id) = self.active_node_id {
3557            if active_node_id == hover_node_id {
3558                return true;
3559            }
3560            self.unactive_node();
3561        }
3562
3563        // hover_node_id is canonicalized when stored, so this always holds.
3564        debug_assert!(
3565            self.get_node(hover_node_id)
3566                .is_some_and(|node| !node.is_anonymous()),
3567            "interaction state must reference DOM nodes, not layout-generated nodes"
3568        );
3569        let active_node_id = Some(hover_node_id);
3570
3571        let node_path = self.maybe_node_layout_ancestors(active_node_id);
3572        for &id in node_path.iter() {
3573            self.snapshot_node_and(id, |node| node.active());
3574        }
3575
3576        self.active_node_id = active_node_id;
3577
3578        true
3579    }
3580
3581    pub fn unactive_node(&mut self) -> bool {
3582        let Some(active_node_id) = self.active_node_id.take() else {
3583            return false;
3584        };
3585
3586        let node_path = self.maybe_node_layout_ancestors(Some(active_node_id));
3587        for &id in node_path.iter() {
3588            self.snapshot_node_and(id, |node| node.unactive());
3589        }
3590
3591        true
3592    }
3593
3594    /// The scrollbar thumb currently under the pointer, if any.
3595    pub fn hovered_scrollbar(&self) -> Option<crate::node::ScrollbarRef> {
3596        self.hovered_scrollbar
3597    }
3598
3599    /// The scrollbar thumb currently being dragged, if any.
3600    pub fn scrollbar_drag_target(&self) -> Option<crate::node::ScrollbarRef> {
3601        match &self.drag_mode {
3602            DragMode::ScrollbarDrag(state) => Some(state.scrollbar),
3603            _ => None,
3604        }
3605    }
3606
3607    /// The current opacity of `node_id`'s overlay scrollbars. They show at
3608    /// full opacity on scroll and fade out after a delay (Chromium's overlay
3609    /// timings); the pointer resting on a thumb, or dragging it, holds them
3610    /// visible.
3611    pub fn scrollbar_opacity(&self, node_id: NodeId) -> f32 {
3612        let interacting = |scrollbar: &crate::node::ScrollbarRef| scrollbar.node_id == node_id;
3613        if self.hovered_scrollbar.as_ref().is_some_and(interacting)
3614            || self
3615                .scrollbar_drag_target()
3616                .as_ref()
3617                .is_some_and(interacting)
3618        {
3619            return 1.0;
3620        }
3621        self.scrollbar_activity.get(&node_id).map_or(1.0, |last| {
3622            crate::node::scrollbar::opacity_at(last.elapsed())
3623        })
3624    }
3625
3626    /// Show `node_id`'s overlay scrollbars at full opacity and restart their
3627    /// fade-out delay.
3628    pub(crate) fn show_scrollbars(&mut self, node_id: NodeId) {
3629        if cfg!(feature = "scrollbars") {
3630            self.scrollbar_activity.insert(node_id, Instant::now());
3631        }
3632    }
3633
3634    /// Whether any overlay scrollbars are awaiting or animating their
3635    /// fade-out (so frames must keep rendering until they finish).
3636    fn scrollbars_animating(&self) -> bool {
3637        use crate::node::scrollbar::{FADE_DELAY, FADE_DURATION};
3638        self.scrollbar_activity
3639            .values()
3640            .any(|last| last.elapsed() < FADE_DELAY + FADE_DURATION)
3641    }
3642
3643    /// [`hit`](Self::hit), also resolving the innermost overlay scrollbar
3644    /// thumb under the point (shares the traversal, so it costs nothing
3645    /// extra).
3646    pub(crate) fn hit_with_scrollbar(
3647        &self,
3648        x: f32,
3649        y: f32,
3650    ) -> (Option<HitResult>, Option<crate::node::ScrollbarRef>) {
3651        if TDocument::as_node(&self.root_node())
3652            .first_element_child()
3653            .is_none()
3654        {
3655            #[cfg(feature = "tracing")]
3656            tracing::warn!("No DOM - not resolving hit test");
3657            return (None, None);
3658        }
3659        let mut scrollbar = None;
3660        let hit = self
3661            .root_element()
3662            .hit_inner(x, y, self.viewport().scale_f64(), &mut scrollbar);
3663        (hit, scrollbar)
3664    }
3665
3666    pub fn set_hover_to(&mut self, x: f32, y: f32) -> bool {
3667        self.semantic_hover_node_id = None;
3668        // Record the pointer position in client (unscrolled) coordinates so
3669        // that `refresh_hover` can re-resolve hover state after layout or
3670        // scroll changes.
3671        self.last_client_pointer_position = Some(taffy::Point {
3672            x: x - self.viewport_scroll.x as f32,
3673            y: y - self.viewport_scroll.y as f32,
3674        });
3675
3676        let (hit, hovered_scrollbar) = self.hit_with_scrollbar(x, y);
3677        // A faded-out thumb is not interactive: pointer moves never fade
3678        // overlay scrollbars back in (only scrolling shows them).
3679        let hovered_scrollbar =
3680            hovered_scrollbar.filter(|scrollbar| self.scrollbar_opacity(scrollbar.node_id) > 0.0);
3681        // Scrollbar-thumb hover is part of hover state: track it here so a
3682        // pointer crossing a thumb restyles it even when the hit node (the
3683        // content under the overlay thumb) is unchanged.
3684        let scrollbar_changed = hovered_scrollbar != self.hovered_scrollbar;
3685        if scrollbar_changed {
3686            // Entering a thumb restores full opacity mid-fade; leaving one
3687            // restarts the fade-out delay.
3688            for scrollbar in [self.hovered_scrollbar, hovered_scrollbar]
3689                .into_iter()
3690                .flatten()
3691            {
3692                self.show_scrollbars(scrollbar.node_id);
3693            }
3694        }
3695        self.hovered_scrollbar = hovered_scrollbar;
3696
3697        // Store both the precise layout node that was hit (transient: used for
3698        // cursor/style queries) and its canonical DOM target (persistent: must
3699        // not reference layout-generated nodes, whose ids die on box-tree
3700        // reconstruction).
3701        let hit_node_id = hit.map(|hit| hit.node_id);
3702        let hover_node_id = hit_node_id.and_then(|id| self.nearest_non_anonymous_ancestor(id));
3703        let new_is_text = hit.map(|hit| hit.is_text).unwrap_or(false);
3704
3705        self.apply_hover_target(hit_node_id, hover_node_id, new_is_text, scrollbar_changed)
3706    }
3707
3708    /// Move the authored hover state to an already-resolved DOM node.
3709    ///
3710    /// Semantic automation has selected a node by identity already. Repeating
3711    /// hit testing at its centre can choose an overlapping child or overlay,
3712    /// especially inside nested scrollers, and makes `Hover { node_id }`
3713    /// target something other than the requested node. Pointer coordinates are
3714    /// still recorded for event payloads and later layout refreshes.
3715    pub fn set_hover_to_node(&mut self, node_id: NodeId, x: f32, y: f32) -> bool {
3716        self.semantic_hover_node_id = Some(node_id);
3717        self.last_client_pointer_position = Some(taffy::Point {
3718            x: x - self.viewport_scroll.x as f32,
3719            y: y - self.viewport_scroll.y as f32,
3720        });
3721
3722        let hovered_scrollbar = self.hovered_scrollbar.take();
3723        let scrollbar_changed = hovered_scrollbar.is_some();
3724        if let Some(scrollbar) = hovered_scrollbar {
3725            self.show_scrollbars(scrollbar.node_id);
3726        }
3727        let hover_node_id = self.nearest_non_anonymous_ancestor(node_id);
3728        self.apply_hover_target(Some(node_id), hover_node_id, false, scrollbar_changed)
3729    }
3730
3731    fn apply_hover_target(
3732        &mut self,
3733        hit_node_id: Option<NodeId>,
3734        hover_node_id: Option<NodeId>,
3735        new_is_text: bool,
3736        scrollbar_changed: bool,
3737    ) -> bool {
3738        let hit_changed =
3739            hit_node_id != self.hover_hit_node_id || new_is_text != self.hover_node_is_text;
3740        self.hover_hit_node_id = hit_node_id;
3741        self.hover_node_is_text = new_is_text;
3742
3743        // Return early if the new node is the same as the already-hovered node
3744        if hover_node_id == self.hover_node_id {
3745            if hit_changed {
3746                // The canonical target is unchanged (so no restyle is needed)
3747                // but the precise hit node changed, which can change the cursor
3748                // (e.g. moving between text and non-text within one element).
3749                self.shell_provider.set_cursor(self.get_cursor());
3750            }
3751            return scrollbar_changed;
3752        }
3753
3754        let old_node_path = self.maybe_node_layout_ancestors(self.hover_node_id);
3755        let new_node_path = self.maybe_node_layout_ancestors(hover_node_id);
3756        let same_count = old_node_path
3757            .iter()
3758            .zip(&new_node_path)
3759            .take_while(|(o, n)| o == n)
3760            .count();
3761        for &id in old_node_path.iter().skip(same_count) {
3762            self.snapshot_node_and(id, |node| node.unhover());
3763        }
3764        for &id in new_node_path.iter().skip(same_count) {
3765            self.snapshot_node_and(id, |node| node.hover());
3766        }
3767
3768        self.hover_node_id = hover_node_id;
3769
3770        // Update the cursor
3771        self.shell_provider.set_cursor(self.get_cursor());
3772
3773        // Request redraw
3774        self.shell_provider.request_redraw();
3775
3776        true
3777    }
3778
3779    pub fn clear_hover(&mut self) -> bool {
3780        // The pointer is no longer over the document, so stop re-resolving
3781        // hover state against it.
3782        self.last_client_pointer_position = None;
3783        self.semantic_hover_node_id = None;
3784        self.hover_hit_node_id = None;
3785
3786        let Some(hover_node_id) = self.hover_node_id else {
3787            return false;
3788        };
3789
3790        let old_node_path = self.maybe_node_layout_ancestors(Some(hover_node_id));
3791        for &id in old_node_path.iter() {
3792            self.snapshot_node_and(id, |node| node.unhover());
3793        }
3794
3795        self.hover_node_id = None;
3796        self.hover_node_is_text = false;
3797
3798        // Update the cursor
3799        self.shell_provider.set_cursor(self.get_cursor());
3800
3801        // Request redraw
3802        self.shell_provider.request_redraw();
3803
3804        true
3805    }
3806
3807    /// Re-resolve hover state against the current layout using the last known
3808    /// pointer position.
3809    ///
3810    /// TODO: synthesizing pointerenter/pointerleave DOM events for
3811    /// hover changes caused by layout shifts.
3812    pub fn refresh_hover(&mut self) -> bool {
3813        if let Some(node_id) = self.semantic_hover_node_id {
3814            if self.get_node(node_id).is_some() {
3815                let hover_node_id = self.nearest_non_anonymous_ancestor(node_id);
3816                return self.apply_hover_target(Some(node_id), hover_node_id, false, false);
3817            }
3818            self.semantic_hover_node_id = None;
3819        }
3820        let Some(pos) = self.last_client_pointer_position else {
3821            return false;
3822        };
3823        let x = pos.x + self.viewport_scroll.x as f32;
3824        let y = pos.y + self.viewport_scroll.y as f32;
3825        self.set_hover_to(x, y)
3826    }
3827
3828    pub fn get_hover_node_id(&self) -> Option<NodeId> {
3829        self.hover_node_id
3830    }
3831
3832    pub fn get_mousedown_node_id(&self) -> Option<NodeId> {
3833        self.mousedown_node_id
3834    }
3835
3836    pub fn set_viewport(&mut self, viewport: Viewport) {
3837        let scale_has_changed = viewport.scale_f64() != self.viewport.scale_f64();
3838        self.viewport = viewport;
3839        self.set_stylist_device(make_device(
3840            &self.viewport,
3841            self.media_type.clone(),
3842            self.font_ctx.clone(),
3843        ));
3844        self.scroll_viewport_by(0.0, 0.0); // Clamp scroll offset
3845
3846        if scale_has_changed {
3847            self.invalidate_inline_contexts();
3848            self.shell_provider.request_redraw();
3849        }
3850    }
3851
3852    /// Returns the current CSS media type used to evaluate `@media` rules.
3853    pub fn media_type(&self) -> &MediaType {
3854        &self.media_type
3855    }
3856
3857    /// Sets the CSS media type used to evaluate `@media` rules (e.g. `screen` or `print`)
3858    /// and rebuilds the stylist device so updated rules apply on the next restyle.
3859    pub fn set_media_type(&mut self, media_type: MediaType) {
3860        if self.media_type == media_type {
3861            return;
3862        }
3863        self.media_type = media_type;
3864        self.set_stylist_device(make_device(
3865            &self.viewport,
3866            self.media_type.clone(),
3867            self.font_ctx.clone(),
3868        ));
3869    }
3870
3871    pub fn viewport(&self) -> &Viewport {
3872        &self.viewport
3873    }
3874
3875    pub fn viewport_mut(&mut self) -> ViewportMut<'_> {
3876        ViewportMut::new(self)
3877    }
3878
3879    pub fn zoom_by(&mut self, increment: f32) {
3880        let mut viewport = self.viewport.clone();
3881        viewport.zoom_by(increment);
3882        self.set_viewport(viewport);
3883    }
3884
3885    pub fn zoom_to(&mut self, zoom: f32) {
3886        let mut viewport = self.viewport.clone();
3887        viewport.set_zoom(zoom);
3888        self.set_viewport(viewport);
3889    }
3890
3891    pub fn get_viewport(&self) -> Viewport {
3892        self.viewport.clone()
3893    }
3894
3895    /// Returns whether incremental layout is currently enabled for this document.
3896    pub fn incremental_layout(&self) -> bool {
3897        self.incremental_layout
3898    }
3899
3900    /// Enables or disables incremental layout for this document.
3901    pub fn set_incremental_layout(&mut self, enabled: bool) {
3902        self.incremental_layout = enabled;
3903    }
3904
3905    pub fn devtools(&self) -> &DevtoolSettings {
3906        &self.devtool_settings
3907    }
3908
3909    pub fn devtools_mut(&mut self) -> &mut DevtoolSettings {
3910        &mut self.devtool_settings
3911    }
3912
3913    pub fn subdoc(&self, node_id: NodeId) -> Option<&dyn Document> {
3914        self.get_node(node_id)
3915            .and_then(|node| node.element_data())
3916            .and_then(|el| el.sub_doc_data())
3917    }
3918
3919    pub fn subdoc_mut(&mut self, node_id: NodeId) -> Option<&mut dyn Document> {
3920        self.get_node_mut(node_id)
3921            .and_then(|node| node.element_data_mut())
3922            .and_then(|el| el.sub_doc_data_mut())
3923    }
3924
3925    pub fn is_animating(&self) -> bool {
3926        #[cfg(feature = "custom-widget")]
3927        let custom_widget_is_animating = self.custom_widget_nodes.iter().any(|&node_id| {
3928            self.nodes[node_id]
3929                .element_data()
3930                .and_then(|el| el.custom_widget_data())
3931                .is_some_and(|data| data.widget.requires_redraw())
3932        });
3933        #[cfg(not(feature = "custom-widget"))]
3934        let custom_widget_is_animating = false;
3935
3936        let animating = self.has_canvas
3937            | (self.css_animation_ticks_enabled && self.has_active_animations)
3938            | (self.subdoc_animation_pacing != AnimationPacing::Idle)
3939            | custom_widget_is_animating
3940            | (self.scroll_animation != ScrollAnimationState::None)
3941            | self.scrollbars_animating();
3942
3943        if animating && crate::debug::animation_reasons_enabled() {
3944            crate::debug::report_animation_reasons(
3945                self.id(),
3946                self.has_canvas,
3947                self.has_active_animations,
3948                self.subdoc_animation_pacing != AnimationPacing::Idle,
3949                custom_widget_is_animating,
3950                self.scroll_animation != ScrollAnimationState::None,
3951                self.scrollbars_animating(),
3952                self.animating_node_names().as_deref(),
3953            );
3954        }
3955
3956        animating
3957    }
3958
3959    /// Return the cadence class for the next animation-only frame.
3960    ///
3961    /// CSS animations are commonly decorative and can use a lower cadence.
3962    /// Canvas, scrolling and custom widgets remain at the interactive cadence.
3963    pub fn animation_pacing(&self) -> AnimationPacing {
3964        let focused_text_input = self.focus_node_id.is_some_and(|node_id| {
3965            self.nodes
3966                .get(node_id)
3967                .and_then(|node| node.element_data())
3968                .is_some_and(|element| element.text_input_data().is_some())
3969        });
3970        #[cfg(feature = "custom-widget")]
3971        let custom_widget_is_animating = self.custom_widget_nodes.iter().any(|&node_id| {
3972            self.nodes[node_id]
3973                .element_data()
3974                .and_then(|el| el.custom_widget_data())
3975                .is_some_and(|data| data.widget.requires_redraw())
3976        });
3977        #[cfg(not(feature = "custom-widget"))]
3978        let custom_widget_is_animating = false;
3979
3980        if self.has_canvas
3981            || custom_widget_is_animating
3982            || self.scroll_animation != ScrollAnimationState::None
3983            || self.scrollbars_animating()
3984        {
3985            AnimationPacing::Interactive
3986        } else if self.css_animation_ticks_enabled && self.has_active_animations {
3987            const SLOW_ANIMATION_SECONDS: f64 = 2.0;
3988            let sets = self.animations.sets.read();
3989            let has_fast_animation_or_transition = sets.values().any(|set| {
3990                set.transitions.iter().any(|transition| {
3991                    matches!(
3992                        transition.state,
3993                        AnimationState::Pending | AnimationState::Running
3994                    )
3995                }) || set.animations.iter().any(|animation| {
3996                    matches!(
3997                        animation.state,
3998                        AnimationState::Pending | AnimationState::Running
3999                    ) && animation.duration < SLOW_ANIMATION_SECONDS
4000                })
4001            });
4002            if has_fast_animation_or_transition {
4003                AnimationPacing::Interactive
4004            } else {
4005                AnimationPacing::SlowCss
4006            }
4007        } else if focused_text_input {
4008            AnimationPacing::Caret
4009        } else if self.subdoc_animation_pacing != AnimationPacing::Idle {
4010            self.subdoc_animation_pacing
4011        } else {
4012            AnimationPacing::Idle
4013        }
4014    }
4015
4016    /// Which elements Stylo currently holds animations or transitions for.
4017    ///
4018    /// Only built when the diagnostic is switched on: a frame loop that will
4019    /// not settle is otherwise very hard to attribute, because
4020    /// `has_active_animations` is one bool for the whole document and says
4021    /// nothing about which element is keeping it true.
4022    fn animating_node_names(&self) -> Option<String> {
4023        if !self.has_active_animations {
4024            return None;
4025        }
4026        let sets = self.animations.sets.read();
4027        let mut described: Vec<String> = sets
4028            .iter()
4029            .filter(|(_, state)| state.needs_animation_ticks())
4030            .filter_map(|(key, state)| {
4031                let node_id = NodeId::from_u64(key.node.id() as u64);
4032                let node = self.nodes.get(node_id)?;
4033                let element = node.element_data()?;
4034                let name = element
4035                    .attr(local_name!("id"))
4036                    .map(|id| format!("#{id}"))
4037                    .or_else(|| {
4038                        element
4039                            .attr(local_name!("class"))
4040                            .and_then(|c| c.split_ascii_whitespace().next())
4041                            .map(|c| format!(".{c}"))
4042                    })
4043                    .unwrap_or_else(|| element.name.local.to_string());
4044                Some(format!(
4045                    "{name}(anim={},trans={},in_doc={})",
4046                    state.animations.len(),
4047                    state.transitions.len(),
4048                    node.flags.is_in_document(),
4049                ))
4050            })
4051            .collect();
4052        described.sort();
4053        described.truncate(12);
4054        Some(described.join(" "))
4055    }
4056
4057    /// Update the device and reset the stylist to process the new size
4058    pub fn set_stylist_device(&mut self, device: Device) {
4059        self.viewport_generation = self.viewport_generation.wrapping_add(1);
4060        // Viewport units become pixels at cascade time, from this device.
4061        // Compare before `device` is moved into the stylist.
4062        let previous_viewport = self.stylist.device().au_viewport_size();
4063        let next_viewport = device.au_viewport_size();
4064
4065        // Seed the new device with the root element's current style and font-relative
4066        // unit state (used to resolve rem/rlh/rex/rch/rcap/ric units). Stylo only
4067        // updates this state when the root element's style *changes* during a restyle,
4068        // so a freshly-built device would otherwise resolve these units against the
4069        // default font-size (16px) until the root's font-size next changes.
4070        let root_styles = self
4071            .try_root_element()
4072            .and_then(|root| root.primary_styles());
4073        if let Some(root_style) = root_styles.as_deref() {
4074            device.set_root_style(root_style);
4075
4076            let font = root_style.get_font();
4077            let font_size = font.clone_font_size().computed_size();
4078            device.set_root_font_size(root_style.effective_zoom.unzoom(font_size.px()));
4079
4080            let line_height = device
4081                .calc_line_height(font, root_style.writing_mode, None)
4082                .0;
4083            device.set_root_line_height(root_style.effective_zoom.unzoom(line_height.px()));
4084        }
4085        drop(root_styles);
4086
4087        let origins = {
4088            let guard = &self.guard;
4089            let guards = StylesheetGuards {
4090                author: &guard.read(),
4091                ua_or_user: &guard.read(),
4092            };
4093            self.stylist.set_device(device, &guards)
4094        };
4095        self.stylist.force_stylesheet_origins_dirty(origins);
4096        #[cfg(feature = "shadow-dom")]
4097        for host_id in self.shadow_host_node_ids() {
4098            if let Some(root_id) = self.shadow_root_id(host_id) {
4099                self.invalidate_shadow_styles(root_id);
4100            }
4101        }
4102
4103        // Recascade through normal style traversal, which skips hidden subtrees.
4104        // Allocated element data does not guarantee a computed primary style.
4105        if let Some(root_id) = self.try_root_element().map(|root| root.id) {
4106            self.nodes[root_id].set_restyle_hint(RestyleHint::recascade_subtree());
4107            self.shell_provider.request_redraw();
4108        }
4109        if previous_viewport != next_viewport {
4110            self.abspos_layout_dirty = true;
4111        }
4112    }
4113
4114    pub fn stylist_device(&mut self) -> &Device {
4115        self.stylist.device()
4116    }
4117
4118    /// The cursor to show, where `None` means `cursor: none` — hide it.
4119    ///
4120    /// `None` is an answer, not the absence of one. The shell hides the pointer
4121    /// when it sees `None`, so every path that means "nothing to say here" must
4122    /// return `Default` instead. Returning `None` from those made the pointer
4123    /// vanish as it crossed into page content, which is the shape this used to
4124    /// have: three `?`s that each meant "no opinion" and all read as "hide".
4125    pub fn get_cursor(&self) -> Option<CursorIcon> {
4126        // Prefer the precise hit node: `cursor` and `user-select` may be set on
4127        // a pseudo-element or resolved on an anonymous box, and text hits carry
4128        // is_text via the hit node. Fall back to the canonical hover node if
4129        // the hit node has been removed (it is transient across resolves).
4130        let node_id = self
4131            .hover_hit_node_id
4132            .filter(|&id| self.nodes.contains_key(id))
4133            .or(self.get_hover_node_id());
4134        let Some(node_id) = node_id else {
4135            return Some(CursorIcon::Default);
4136        };
4137        let node = &self.nodes[node_id];
4138
4139        if let Some(subdoc) = node.subdoc().map(|doc| doc.inner()) {
4140            // Only delegate when the sub-document has hover state of its own.
4141            // Without this check an embedded document that has not been hovered
4142            // yet answers `None` — meaning "I have no hover node" — and the
4143            // pointer disappears the moment it enters the page area, which is
4144            // every page in a browser built on sub-documents.
4145            if subdoc.hover_hit_node_id.is_some() || subdoc.get_hover_node_id().is_some() {
4146                return subdoc.get_cursor();
4147            }
4148            return Some(CursorIcon::Default);
4149        }
4150
4151        let Some(style) = node.primary_styles() else {
4152            return Some(CursorIcon::Default);
4153        };
4154        let user_select = style.clone_user_select();
4155        let keyword = style.clone_cursor().keyword;
4156
4157        // Return cursor from style if it is non-auto
4158        if keyword != CursorKind::Auto {
4159            return stylo_to_cursor_icon(keyword);
4160        }
4161
4162        // Return text cursor for text inputs
4163        if node
4164            .element_data()
4165            .is_some_and(|e| e.text_input_data().is_some())
4166        {
4167            return Some(CursorIcon::Text);
4168        }
4169
4170        // Use "pointer" cursor if any ancestor is a link
4171        let mut maybe_node = Some(node);
4172        while let Some(node) = maybe_node {
4173            if node.is_link() {
4174                return Some(CursorIcon::Pointer);
4175            }
4176
4177            maybe_node = node.layout_parent.get().map(|node_id| node.with(node_id));
4178        }
4179
4180        // Return text cursor for text nodes
4181        if self.hover_node_is_text {
4182            return Some(match user_select {
4183                UserSelect::Text | UserSelect::All | UserSelect::Auto => CursorIcon::Text,
4184                UserSelect::None => CursorIcon::Default,
4185            });
4186        }
4187
4188        // Else fallback to default cursor
4189        Some(CursorIcon::Default)
4190    }
4191
4192    pub fn scroll_node_by<F: FnMut(DomEvent)>(
4193        &mut self,
4194        node_id: NodeId,
4195        x: f64,
4196        y: f64,
4197        dispatch_event: F,
4198    ) {
4199        self.scroll_node_by_has_changed(node_id, x, y, dispatch_event);
4200    }
4201
4202    /// Scroll a node by given x and y
4203    /// Will bubble scrolling up to parent node once it can no longer scroll further
4204    /// If we're already at the root node, bubbles scrolling up to the viewport
4205    ///
4206    /// A `position: sticky` box is held against the edge of the scrollport it
4207    /// lives in, so the boxes have to be re-adjusted here rather than only in
4208    /// `resolve`: a wheel event does not necessarily produce a style and layout
4209    /// pass, and a header that only unstuck on the next restyle is a header
4210    /// that visibly lags the scroll.
4211    pub fn scroll_node_by_has_changed<F: FnMut(DomEvent)>(
4212        &mut self,
4213        node_id: NodeId,
4214        x: f64,
4215        y: f64,
4216        dispatch_event: F,
4217    ) -> bool {
4218        let has_changed = self.scroll_node_by_inner(node_id, x, y, dispatch_event);
4219        if has_changed {
4220            self.resolve_positioned_scroll();
4221        }
4222        has_changed
4223    }
4224
4225    fn scroll_node_by_inner<F: FnMut(DomEvent)>(
4226        &mut self,
4227        node_id: NodeId,
4228        x: f64,
4229        y: f64,
4230        mut dispatch_event: F,
4231    ) -> bool {
4232        // Per the CSS overflow propagation rules, the root element's overflow (and usually
4233        // the <body>'s) is applied to the viewport, and the element itself must not have
4234        // a scrolling mechanism of its own. So scrolls that reach the root element are
4235        // forwarded to the viewport rather than scrolling the root element itself.
4236        if self.try_root_element().is_some_and(|el| el.id == node_id) {
4237            let has_changed = self.scroll_viewport_by_has_changed(x, y);
4238            if has_changed {
4239                let layout = *self.root_element().final_layout();
4240                let scale = self.viewport.scale() as f64;
4241                let event = BlitzScrollEvent {
4242                    scroll_top: self.viewport_scroll.y,
4243                    scroll_left: self.viewport_scroll.x,
4244                    scroll_width: layout.size.width.max(layout.content_size.width) as i32,
4245                    scroll_height: layout.size.height.max(layout.content_size.height) as i32,
4246                    client_width: (self.viewport.window_size.0 as f64 / scale) as i32,
4247                    client_height: (self.viewport.window_size.1 as f64 / scale) as i32,
4248                };
4249                dispatch_event(DomEvent::new(node_id, DomEventData::Scroll(event)));
4250            }
4251            return has_changed;
4252        }
4253
4254        let Some(node) = self.nodes.get_mut(node_id) else {
4255            return false;
4256        };
4257
4258        // Text inputs scroll their own internal text content rather than using the generic
4259        // overflow mechanism: single-line inputs scroll horizontally, multi-line inputs scroll
4260        // vertically. Any delta the input cannot consume is bubbled up to an ancestor scroller.
4261        if node
4262            .element_data()
4263            .is_some_and(|el| el.text_input_data().is_some())
4264        {
4265            let parent = node.parent;
4266            let content_box_width = node.final_layout().content_box_width();
4267            let content_box_height = node.final_layout().content_box_height();
4268            let input = node
4269                .element_data_mut()
4270                .and_then(|el| el.text_input_data_mut())
4271                .unwrap();
4272
4273            let (bubble_x, bubble_y) = if input.is_multiline {
4274                (
4275                    x,
4276                    input.scroll_by(y as f32, content_box_width, content_box_height) as f64,
4277                )
4278            } else {
4279                (
4280                    input.scroll_by(x as f32, content_box_width, content_box_height) as f64,
4281                    y,
4282                )
4283            };
4284
4285            let has_changed = bubble_x != x || bubble_y != y;
4286
4287            if bubble_x != 0.0 || bubble_y != 0.0 {
4288                let bubbled = if let Some(parent) = parent {
4289                    self.scroll_node_by_inner(parent, bubble_x, bubble_y, dispatch_event)
4290                } else {
4291                    self.scroll_viewport_by_has_changed(bubble_x, bubble_y)
4292                };
4293                return bubbled | has_changed;
4294            }
4295
4296            return has_changed;
4297        }
4298
4299        let (can_x_scroll, can_y_scroll) = node
4300            .primary_styles()
4301            .map(|styles| {
4302                (
4303                    matches!(styles.clone_overflow_x(), Overflow::Scroll | Overflow::Auto),
4304                    matches!(styles.clone_overflow_y(), Overflow::Scroll | Overflow::Auto),
4305                )
4306            })
4307            .unwrap_or((false, false));
4308
4309        let initial = *node.scroll_offset();
4310        let new_x = node.scroll_offset().x - x;
4311        let new_y = node.scroll_offset().y - y;
4312
4313        let mut bubble_x = 0.0;
4314        let mut bubble_y = 0.0;
4315
4316        let scroll_width = node.final_layout().scroll_width() as f64;
4317        let scroll_height = node.final_layout().scroll_height() as f64;
4318
4319        // Handle sub document case
4320        if let Some(mut sub_doc) = node.subdoc_mut().map(|doc| doc.inner_mut()) {
4321            let has_changed = if let Some(hover_node_id) = sub_doc.get_hover_node_id() {
4322                sub_doc.scroll_node_by_has_changed(hover_node_id, x, y, dispatch_event)
4323            } else {
4324                sub_doc.scroll_viewport_by_has_changed(x, y)
4325            };
4326
4327            // TODO: propagate remaining scroll to parent
4328            return has_changed;
4329        }
4330
4331        // If we're past our scroll bounds, transfer remainder of scrolling to parent/viewport
4332        if !can_x_scroll {
4333            bubble_x = x
4334        } else if new_x < 0.0 {
4335            bubble_x = -new_x;
4336            node.scroll_offset_mut().x = 0.0;
4337        } else if new_x > scroll_width {
4338            bubble_x = scroll_width - new_x;
4339            node.scroll_offset_mut().x = scroll_width;
4340        } else {
4341            node.scroll_offset_mut().x = new_x;
4342        }
4343
4344        if !can_y_scroll {
4345            bubble_y = y
4346        } else if new_y < 0.0 {
4347            bubble_y = -new_y;
4348            node.scroll_offset_mut().y = 0.0;
4349        } else if new_y > scroll_height {
4350            bubble_y = scroll_height - new_y;
4351            node.scroll_offset_mut().y = scroll_height;
4352        } else {
4353            node.scroll_offset_mut().y = new_y;
4354        }
4355
4356        let has_changed = *node.scroll_offset() != initial;
4357
4358        if has_changed {
4359            let layout = *node.final_layout();
4360            let event = BlitzScrollEvent {
4361                scroll_top: node.scroll_offset().y,
4362                scroll_left: node.scroll_offset().x,
4363                scroll_width: layout.scroll_width() as i32,
4364                scroll_height: layout.scroll_height() as i32,
4365                client_width: layout.size.width as i32,
4366                client_height: layout.size.height as i32,
4367            };
4368
4369            dispatch_event(DomEvent::new(node_id, DomEventData::Scroll(event)));
4370        }
4371
4372        let parent = node.parent;
4373        if has_changed {
4374            self.show_scrollbars(node_id);
4375        }
4376
4377        if bubble_x != 0.0 || bubble_y != 0.0 {
4378            if let Some(parent) = parent {
4379                return self.scroll_node_by_inner(parent, bubble_x, bubble_y, dispatch_event)
4380                    | has_changed;
4381            } else {
4382                return self.scroll_viewport_by_has_changed(bubble_x, bubble_y) | has_changed;
4383            }
4384        }
4385
4386        has_changed
4387    }
4388
4389    pub fn scroll_viewport_by(&mut self, x: f64, y: f64) {
4390        self.scroll_viewport_by_has_changed(x, y);
4391    }
4392
4393    /// Scroll the viewport by the given values
4394    pub fn scroll_viewport_by_has_changed(&mut self, x: f64, y: f64) -> bool {
4395        // The viewport scrolls the root element's scrollable overflow, which includes both
4396        // the root element itself and any content which overflows it (e.g. when the root
4397        // element has a fixed height but its content is taller). A document without a root
4398        // element has no scrollable content, so its content size is zero.
4399        let (content_width, content_height) = match self.try_root_element() {
4400            Some(root) => {
4401                let root_layout = root.final_layout();
4402                (
4403                    root_layout.size.width.max(root_layout.content_size.width) as f64,
4404                    root_layout.size.height.max(root_layout.content_size.height) as f64,
4405                )
4406            }
4407            None => (0.0, 0.0),
4408        };
4409        let new_scroll = (self.viewport_scroll.x - x, self.viewport_scroll.y - y);
4410        let window_width = self.viewport.window_size.0 as f64 / self.viewport.scale() as f64;
4411        let window_height = self.viewport.window_size.1 as f64 / self.viewport.scale() as f64;
4412
4413        let initial = self.viewport_scroll;
4414        self.viewport_scroll.x =
4415            f64::max(0.0, f64::min(new_scroll.0, content_width - window_width));
4416        self.viewport_scroll.y =
4417            f64::max(0.0, f64::min(new_scroll.1, content_height - window_height));
4418
4419        let has_changed = self.viewport_scroll != initial;
4420        if has_changed {
4421            // The viewport is the scrollport a page-level sticky box is held
4422            // against, and the containing block a fixed box is pinned to, so
4423            // both move with this and not with the next relayout. See
4424            // `resolve_sticky_positions` and `resolve_fixed_positions`.
4425            self.resolve_positioned_scroll();
4426        }
4427        has_changed
4428    }
4429
4430    pub fn scroll_by(
4431        &mut self,
4432        anchor_node_id: Option<NodeId>,
4433        scroll_x: f64,
4434        scroll_y: f64,
4435        dispatch_event: &mut dyn FnMut(DomEvent),
4436    ) -> bool {
4437        if let Some(anchor_node_id) = anchor_node_id {
4438            self.scroll_node_by_has_changed(anchor_node_id, scroll_x, scroll_y, dispatch_event)
4439        } else {
4440            self.scroll_viewport_by_has_changed(scroll_x, scroll_y)
4441        }
4442    }
4443
4444    pub fn viewport_scroll(&self) -> crate::Point<f64> {
4445        self.viewport_scroll
4446    }
4447
4448    pub fn set_viewport_scroll(&mut self, scroll: crate::Point<f64>) {
4449        self.viewport_scroll = scroll;
4450    }
4451
4452    /// Find the node targeted by a URL fragment (the `#...` part of a URL).
4453    ///
4454    /// Per the HTML spec, this is the element whose `id` matches the fragment, falling
4455    /// back to the first `<a>` element whose `name` attribute matches.
4456    pub fn get_fragment_target(&self, fragment: &str) -> Option<NodeId> {
4457        if let Some(node_id) = self.get_element_by_id(fragment) {
4458            return Some(node_id);
4459        }
4460
4461        // Fall back to a named anchor: `<a name="...">`
4462        self.nodes.iter().find_map(|(id, node)| {
4463            let el = node.element_data()?;
4464            (el.name.local == local_name!("a") && el.attr(local_name!("name")) == Some(fragment))
4465                .then_some(id)
4466        })
4467    }
4468
4469    /// Scroll the viewport so that the given node is aligned with the top of the viewport.
4470    /// Scroll the nearest scroll container at or above `node_id`.
4471    ///
4472    /// "Scroll this panel" is the operation callers actually want, and
4473    /// `scroll_node_by` only moves the node itself, so naming any inner element
4474    /// silently did nothing. Wheel events are no help either: they are
4475    /// delivered to whatever the document last saw hovered, which an injected
4476    /// pointer move does not set, so an automated caller had no way to scroll
4477    /// anything at all.
4478    /// The nearest scroll container at or above `node_id`, if there is one.
4479    pub fn nearest_scroll_container(&self, node_id: NodeId) -> Option<NodeId> {
4480        let mut current = Some(node_id);
4481        for _ in 0..64 {
4482            let id = current?;
4483            let node = self.nodes.get(id)?;
4484            if node.style().overflow.x.is_scroll_container()
4485                || node.style().overflow.y.is_scroll_container()
4486            {
4487                return Some(id);
4488            }
4489            current = node.parent;
4490        }
4491        None
4492    }
4493
4494    pub fn scroll_nearest_container_by(&mut self, node_id: NodeId, x: f64, y: f64) -> bool {
4495        self.scroll_nearest_container_by_with_events(node_id, x, y, |_| {})
4496    }
4497
4498    pub fn scroll_nearest_container_by_with_events<F: FnMut(DomEvent)>(
4499        &mut self,
4500        node_id: NodeId,
4501        x: f64,
4502        y: f64,
4503        mut dispatch_event: F,
4504    ) -> bool {
4505        let mut current = Some(node_id);
4506        for _ in 0..64 {
4507            let Some(id) = current else { break };
4508            let Some(node) = self.nodes.get(id) else {
4509                break;
4510            };
4511            let scrolls = node.style().overflow.x.is_scroll_container()
4512                || node.style().overflow.y.is_scroll_container();
4513            if scrolls {
4514                self.scroll_node_by(id, x, y, &mut dispatch_event);
4515                return true;
4516            }
4517            current = node.parent;
4518        }
4519        self.scroll_viewport_by(x, y);
4520        false
4521    }
4522
4523    pub fn scroll_to_node(&mut self, node_id: NodeId) {
4524        self.scroll_to_node_with_events(node_id, |_| {});
4525    }
4526
4527    pub fn scroll_to_node_with_events<F: FnMut(DomEvent)>(
4528        &mut self,
4529        node_id: NodeId,
4530        dispatch_event: F,
4531    ) {
4532        self.scroll_to_node_aligned_with_events(node_id, false, dispatch_event);
4533    }
4534
4535    /// Reveal a node near the centre of each scrollport and the viewport.
4536    ///
4537    /// Semantic input uses this placement so fixed or sticky chrome cannot
4538    /// cover the point an automation client will drive. Ordinary DOM
4539    /// `scrollIntoView` and fragment navigation retain their start alignment.
4540    pub fn scroll_to_node_centered_with_events<F: FnMut(DomEvent)>(
4541        &mut self,
4542        node_id: NodeId,
4543        dispatch_event: F,
4544    ) {
4545        self.scroll_to_node_aligned_with_events(node_id, true, dispatch_event);
4546    }
4547
4548    fn scroll_to_node_aligned_with_events<F: FnMut(DomEvent)>(
4549        &mut self,
4550        node_id: NodeId,
4551        centered: bool,
4552        mut dispatch_event: F,
4553    ) {
4554        // Semantic snapshots expose visible text as addressable nodes, but a
4555        // text node does not own a Taffy layout box. `absolute_position` and
4556        // the scrolling calculations below require one, so resolve such a
4557        // target to its nearest layout ancestor first. Without this, asking an
4558        // automation client to reveal a label panics the entire host at
4559        // `Node::final_layout` instead of scrolling the label's box into view.
4560        let mut scroll_target = Some(node_id);
4561        let node_id = loop {
4562            let Some(candidate) = scroll_target else {
4563                return;
4564            };
4565            let Some(node) = self.nodes.get(candidate) else {
4566                return;
4567            };
4568            if matches!(
4569                node.data,
4570                NodeData::Element(_) | NodeData::AnonymousBlock(_) | NodeData::Document(_)
4571            ) {
4572                break candidate;
4573            }
4574            scroll_target = node.layout_parent.get().or(node.parent);
4575        };
4576
4577        // Every scroll container between the node and the root, innermost
4578        // first. Scrolling only the viewport is not `scrollIntoView`: it does
4579        // nothing at all for a node inside a nested scroller, which is what an
4580        // application's own scrolling panes are.
4581        //
4582        // This was not academic. A transcript pane held its "Show 12 earlier
4583        // messages" button at y=-9463 and neither wheel events, Page Up nor
4584        // this call moved it by a single pixel, so a layout bug that only
4585        // appears further up the thread could not be reached from outside the
4586        // app at all. Every measurement of it had to come from a human
4587        // scrolling by hand and saying "now".
4588        let mut chain = Vec::new();
4589        let mut current = self.nodes.get(node_id).and_then(|node| node.parent);
4590        while let Some(id) = current {
4591            let Some(node) = self.nodes.get(id) else {
4592                break;
4593            };
4594            let scrolls = node.style().overflow.x.is_scroll_container()
4595                || node.style().overflow.y.is_scroll_container();
4596            if scrolls {
4597                chain.push(id);
4598            }
4599            current = node.parent;
4600        }
4601
4602        // Innermost first: scrolling an outer container moves the inner one, so
4603        // the inner offsets have to be settled before the outer ones are
4604        // measured, and each step re-reads the node's position.
4605        for container in chain {
4606            let Some(node) = self.nodes.get(node_id) else {
4607                return;
4608            };
4609            let target = node.absolute_position(0.0, 0.0);
4610            let Some(scroller) = self.nodes.get(container) else {
4611                continue;
4612            };
4613            let box_ = scroller.absolute_position(0.0, 0.0);
4614            let layout = scroller.final_layout();
4615            let target_layout = node.final_layout();
4616            // `scroll_node_by` subtracts its delta from the offset. Semantic
4617            // automation centres the target to avoid chrome; DOM behavior
4618            // keeps its historical start alignment.
4619            let (dx, dy) = if centered {
4620                (
4621                    f64::from(
4622                        box_.x + layout.size.width / 2.0
4623                            - (target.x + target_layout.size.width / 2.0),
4624                    ),
4625                    f64::from(
4626                        box_.y + layout.size.height / 2.0
4627                            - (target.y + target_layout.size.height / 2.0),
4628                    ),
4629                )
4630            } else {
4631                (f64::from(box_.x - target.x), f64::from(box_.y - target.y))
4632            };
4633            self.scroll_node_by(container, dx, dy, &mut dispatch_event);
4634        }
4635
4636        // `absolute_position` gives the node's position in document space (it does not
4637        // account for the viewport scroll), so it is the scroll offset we want to land on.
4638        let Some(node) = self.nodes.get(node_id) else {
4639            return;
4640        };
4641        let target = node.absolute_position(0.0, 0.0);
4642        let current = self.viewport_scroll;
4643        let (desired_x, desired_y) = if centered {
4644            let target_layout = node.final_layout();
4645            let scale = self.viewport.scale();
4646            let viewport_width = self.viewport.window_size.0 as f32 / scale;
4647            let viewport_height = self.viewport.window_size.1 as f32 / scale;
4648            (
4649                f64::from(target.x + target_layout.size.width / 2.0 - viewport_width / 2.0)
4650                    .max(0.0),
4651                f64::from(target.y + target_layout.size.height / 2.0 - viewport_height / 2.0)
4652                    .max(0.0),
4653            )
4654        } else {
4655            (f64::from(target.x), f64::from(target.y))
4656        };
4657
4658        // `scroll_viewport_by` subtracts the delta from the current scroll
4659        // offset, so pass current minus the centred destination.
4660        let dx = current.x - desired_x;
4661        let dy = current.y - desired_y;
4662        if let Some(root) = self.try_root_element().map(|element| element.id) {
4663            self.scroll_node_by(root, dx, dy, dispatch_event);
4664        } else {
4665            self.scroll_viewport_by(dx, dy);
4666        }
4667    }
4668
4669    /// Scroll to the element targeted by the given URL fragment (the `#...` part of a URL).
4670    ///
4671    /// An empty fragment (or a `top` fragment that matches no element) scrolls to the top
4672    /// of the document, matching browser behaviour. Returns `true` if a scroll target was
4673    /// found.
4674    pub fn scroll_to_fragment(&mut self, fragment: &str) -> bool {
4675        // Fragments are percent-encoded in URLs (e.g. `%20`); decode before matching.
4676        let decoded = percent_encoding::percent_decode_str(fragment)
4677            .decode_utf8_lossy()
4678            .into_owned();
4679
4680        if !decoded.is_empty() {
4681            if let Some(node_id) = self.get_fragment_target(&decoded) {
4682                self.scroll_to_node(node_id);
4683                return true;
4684            }
4685        }
4686
4687        // An empty fragment, or the special "top" fragment when no matching element exists,
4688        // scrolls to the top of the document.
4689        if decoded.is_empty() || decoded.eq_ignore_ascii_case("top") {
4690            let current = self.viewport_scroll;
4691            self.scroll_viewport_by(current.x, current.y);
4692            return true;
4693        }
4694
4695        false
4696    }
4697
4698    /// SVG graphics bounds in the element's user coordinate system.
4699    /// Callers must flush layout before reading, as for client rectangles.
4700    pub fn get_svg_bbox(&self, node_id: NodeId) -> Option<BoundingRect> {
4701        #[cfg(feature = "svg")]
4702        {
4703            self.svg_user_bbox(node_id)
4704        }
4705        #[cfg(not(feature = "svg"))]
4706        {
4707            let _ = node_id;
4708            None
4709        }
4710    }
4711
4712    /// Geometry, ancestor clipping and computed visibility, in CSS viewport units.
4713    pub fn surface_on_screen(&self, id: NodeId) -> bool {
4714        use style::computed_values::visibility::T as Visibility;
4715        let Some(rect) = self.get_client_bounding_rect(id) else {
4716            return false;
4717        };
4718        let viewport = self.viewport();
4719        let scale = viewport.scale_f64();
4720        let mut x0 = rect.x.max(0.0);
4721        let mut y0 = rect.y.max(0.0);
4722        let mut x1 = (rect.x + rect.width).min(viewport.window_size.0 as f64 / scale);
4723        let mut y1 = (rect.y + rect.height).min(viewport.window_size.1 as f64 / scale);
4724        let mut cursor = Some(id);
4725        while let Some(node_id) = cursor {
4726            let Some(node) = self.get_node(node_id) else {
4727                return false;
4728            };
4729            if matches!(node.style().display, taffy::Display::None) {
4730                return false;
4731            }
4732            if let Some(styles) = node.primary_styles() {
4733                if styles.clone_visibility() != Visibility::Visible
4734                    || styles.get_effects().opacity == 0.0
4735                {
4736                    return false;
4737                }
4738                if node_id != id
4739                    && let Some(clip) = self.get_client_bounding_rect(node_id)
4740                {
4741                    if styles.get_box().overflow_x != Overflow::Visible {
4742                        x0 = x0.max(clip.x);
4743                        x1 = x1.min(clip.x + clip.width);
4744                    }
4745                    if styles.get_box().overflow_y != Overflow::Visible {
4746                        y0 = y0.max(clip.y);
4747                        y1 = y1.min(clip.y + clip.height);
4748                    }
4749                }
4750            }
4751            cursor = node.parent;
4752        }
4753        x1 > x0 && y1 > y0
4754    }
4755
4756    /// Computes the size and position of the `Node` relative to the viewport
4757    pub fn get_client_bounding_rect(&self, node_id: NodeId) -> Option<BoundingRect> {
4758        #[cfg(feature = "svg")]
4759        if let Some(root) = self.svg_geometry_root(node_id) {
4760            return self.svg_client_rect(root, node_id);
4761        }
4762
4763        // Non-atomic inline elements have no layout box of their own: return
4764        // the union of their per-line-box fragment rects.
4765        if let Some(rects) = self.inline_fragment_rects(node_id) {
4766            let rects: Vec<_> = rects
4767                .into_iter()
4768                .map(|rect| self.transformed_client_rect(node_id, rect))
4769                .collect();
4770            let x0 = rects.iter().map(|r| r.x).fold(f64::INFINITY, f64::min);
4771            let y0 = rects.iter().map(|r| r.y).fold(f64::INFINITY, f64::min);
4772            let x1 = rects
4773                .iter()
4774                .map(|r| r.x + r.width)
4775                .fold(f64::NEG_INFINITY, f64::max);
4776            let y1 = rects
4777                .iter()
4778                .map(|r| r.y + r.height)
4779                .fold(f64::NEG_INFINITY, f64::max);
4780            return match rects.is_empty() {
4781                true => None,
4782                false => Some(BoundingRect {
4783                    x: x0,
4784                    y: y0,
4785                    width: x1 - x0,
4786                    height: y1 - y0,
4787                }),
4788            };
4789        }
4790
4791        let node = self.get_node(node_id)?;
4792        if !matches!(
4793            node.data,
4794            NodeData::Element(_) | NodeData::AnonymousBlock(_) | NodeData::Document(_)
4795        ) {
4796            return None;
4797        }
4798        let pos = node.absolute_position(0.0, 0.0);
4799
4800        Some(self.transformed_client_rect(
4801            node_id,
4802            BoundingRect {
4803                x: pos.x as f64 - self.viewport_scroll.x,
4804                y: pos.y as f64 - self.viewport_scroll.y,
4805                width: node.unrounded_layout().size.width as f64,
4806                height: node.unrounded_layout().size.height as f64,
4807            },
4808        ))
4809    }
4810
4811    /// Map the layout rectangle through the same two-dimensional transforms as paint.
4812    /// Layout coordinates deliberately exclude transforms; CSSOM client rectangles do not.
4813    pub(crate) fn transformed_client_rect(
4814        &self,
4815        node_id: NodeId,
4816        rect: BoundingRect,
4817    ) -> BoundingRect {
4818        let mut matrix = kurbo::Affine::IDENTITY;
4819        let mut current = self.get_node(node_id);
4820        let scale = self.viewport.scale_f64();
4821        while let Some(node) = current {
4822            if matches!(
4823                node.data,
4824                NodeData::Element(_) | NodeData::AnonymousBlock(_) | NodeData::Document(_)
4825            ) && let Some(transform) = *node.transform()
4826            {
4827                let [a, b, c, d, e, f] = transform.as_coeffs();
4828                let css_transform = kurbo::Affine::new([a, b, c, d, e / scale, f / scale]);
4829                let origin = node.absolute_position(0.0, 0.0);
4830                let translate = kurbo::Affine::translate((
4831                    origin.x as f64 - self.viewport_scroll.x,
4832                    origin.y as f64 - self.viewport_scroll.y,
4833                ));
4834                matrix = translate * css_transform * translate.inverse() * matrix;
4835            }
4836            current = node
4837                .layout_parent
4838                .get()
4839                .or(node.parent)
4840                .and_then(|id| self.get_node(id));
4841        }
4842        let transformed = matrix.transform_rect_bbox(kurbo::Rect::new(
4843            rect.x,
4844            rect.y,
4845            rect.x + rect.width,
4846            rect.y + rect.height,
4847        ));
4848        BoundingRect {
4849            x: transformed.x0,
4850            y: transformed.y0,
4851            width: transformed.width(),
4852            height: transformed.height(),
4853        }
4854    }
4855
4856    /// Computes the sizes and positions of the `Node`'s box fragments relative to the
4857    /// viewport (CSSOM `getClientRects()` semantics). Nodes with their own layout box
4858    /// return a single rect. Non-atomic inline elements (which are laid out as style
4859    /// spans within an inline root's text layout) return one rect per line box.
4860    pub fn node_client_rects(&self, node_id: NodeId) -> Vec<BoundingRect> {
4861        #[cfg(feature = "svg")]
4862        if self.svg_geometry_root(node_id).is_some() {
4863            return self.get_client_bounding_rect(node_id).into_iter().collect();
4864        }
4865        match self.inline_fragment_rects(node_id) {
4866            Some(rects) => rects
4867                .into_iter()
4868                .map(|rect| self.transformed_client_rect(node_id, rect))
4869                .collect(),
4870            None => self.get_client_bounding_rect(node_id).into_iter().collect(),
4871        }
4872    }
4873
4874    /// Computes per-line-box fragment rects for a non-atomic inline element by walking
4875    /// the containing inline root's text layout. Returns `None` for nodes that have
4876    /// their own layout box (which should use `get_client_bounding_rect` instead).
4877    /// Report inline elements whose fragment rects lie outside the inline root
4878    /// that owns them. `BLITZ_TRACE_INLINE=1`, once per resolve.
4879    ///
4880    /// A non-atomic inline element has no layout box of its own: its geometry
4881    /// is read back out of the containing inline root's text layout on demand.
4882    /// So "the chip is 900px to the right of its block" is a statement about
4883    /// that text layout, and the only way to see it is from in here, with both
4884    /// the fragment and the root in hand. Every earlier attempt to chase this
4885    /// from outside was reading a number the engine computes on the fly and
4886    /// could not say where it came from.
4887    pub(crate) fn trace_escaped_inline_fragments(&self) {
4888        static TRACE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4889        if !*TRACE.get_or_init(|| std::env::var_os("BLITZ_TRACE_INLINE").is_some()) {
4890            return;
4891        }
4892        let mut reported = 0;
4893        for (id, node) in self.nodes.iter() {
4894            if !node.is_element() {
4895                continue;
4896            }
4897            let Some(rects) = self.inline_fragment_rects(id) else {
4898                continue;
4899            };
4900            let Some(root) = node.inline_root_ancestor() else {
4901                continue;
4902            };
4903            let root_layout = root.final_layout();
4904            let root_pos = root.absolute_position(0.0, 0.0);
4905            let root_right =
4906                root_pos.x as f64 + root_layout.size.width as f64 - self.viewport_scroll.x;
4907            for rect in &rects {
4908                if rect.x + rect.width > root_right + 1.0 {
4909                    reported += 1;
4910                    if reported <= 12 {
4911                        eprintln!(
4912                            "escaped-fragment node={id:?} rect=[{:.1},{:.1} {:.1}x{:.1}] \
4913root={:?} root_right={root_right:.1} root_w={:.1} lines={} layout_scale={:.2} vp_scale={:.2} layout_w={:.1}",
4914                            rect.x,
4915                            rect.y,
4916                            rect.width,
4917                            rect.height,
4918                            root.id,
4919                            root_layout.size.width,
4920                            root.element_data()
4921                                .and_then(|e| e.inline_layout_data.as_ref())
4922                                .map(|i| i.layout.len())
4923                                .unwrap_or(0),
4924                            root.element_data()
4925                                .and_then(|e| e.inline_layout_data.as_ref())
4926                                .map(|i| i.layout.scale())
4927                                .unwrap_or(0.0),
4928                            self.viewport.scale(),
4929                            root.element_data()
4930                                .and_then(|e| e.inline_layout_data.as_ref())
4931                                .map(|i| i.layout.width())
4932                                .unwrap_or(0.0),
4933                        );
4934                    }
4935                    break;
4936                }
4937            }
4938        }
4939        if reported > 0 {
4940            eprintln!("escaped-fragment total={reported}");
4941        }
4942
4943        // The opposite failure, and the one that reads as "first load is
4944        // broken": lines broken far narrower than the box they sit in, so a
4945        // paragraph comes out as a column of one or two words inside a
4946        // full-width bubble. Nothing escapes, so the check above never sees it.
4947        let mut narrow = 0;
4948        for (id, node) in self.nodes.iter() {
4949            let Some(inline) = node
4950                .data
4951                .downcast_element()
4952                .and_then(|element| element.inline_layout_data.as_ref())
4953            else {
4954                continue;
4955            };
4956            let box_width = node.final_layout().size.width as f64 * self.viewport.scale() as f64;
4957            let broken_at = inline.layout.width() as f64;
4958            // Only interesting when the text had more to give: a short string
4959            // legitimately measures narrower than its box.
4960            let full = inline.layout.calculate_content_widths().max as f64;
4961            if box_width > 40.0 && broken_at < box_width * 0.6 && full > box_width * 0.9 {
4962                narrow += 1;
4963                if narrow <= 12 {
4964                    eprintln!(
4965                        "narrow-break node={id:?} broken_at={broken_at:.1} box={box_width:.1} \
4966                         max_content={full:.1} lines={} text={:?}",
4967                        inline.layout.len(),
4968                        inline.text.chars().take(40).collect::<String>(),
4969                    );
4970                }
4971            }
4972        }
4973        if narrow > 0 {
4974            eprintln!("narrow-break total={narrow}");
4975        }
4976    }
4977
4978    pub fn inline_fragment_rects(&self, node_id: NodeId) -> Option<Vec<BoundingRect>> {
4979        use parley::PositionedLayoutItem;
4980
4981        let node = self.get_node(node_id)?;
4982
4983        // Text and non-atomic inline elements live in the inline root's glyph
4984        // runs rather than owning layout boxes.
4985        let is_text = node.is_text_node();
4986        if !is_text {
4987            if !node.is_element() || node.flags.is_inline_root() {
4988                return None;
4989            }
4990            let display = node.primary_styles()?.clone_display();
4991            if !(display.outside() == DisplayOutside::Inline
4992                && display.inside() == DisplayInside::Flow)
4993            {
4994                return None;
4995            }
4996        }
4997
4998        let inline_root = node.inline_root_ancestor()?;
4999        let inline_layout = inline_root.element_data()?.inline_layout_data.as_ref()?;
5000        let layout = &inline_layout.layout;
5001        let scale = layout.scale() as f64;
5002
5003        // Walk up the DOM parent chain from `id` to check whether it is (or is
5004        // inside) the target node, stopping at the inline root.
5005        let is_in_target = |mut id: NodeId| -> bool {
5006            loop {
5007                if id == node_id {
5008                    return true;
5009                }
5010                if id == inline_root.id {
5011                    return false;
5012                }
5013                match self.get_node(id).and_then(|n| n.parent) {
5014                    Some(parent) => id = parent,
5015                    None => return false,
5016                }
5017            }
5018        };
5019
5020        // Fragment rects are relative to the inline root's content box.
5021        let root_layout = inline_root.final_layout();
5022        let root_pos = inline_root.absolute_position(0.0, 0.0);
5023        let origin_x = root_pos.x as f64
5024            + (root_layout.padding.left + root_layout.border.left) as f64
5025            - self.viewport_scroll.x;
5026        let origin_y = root_pos.y as f64
5027            + (root_layout.padding.top + root_layout.border.top) as f64
5028            - self.viewport_scroll.y;
5029
5030        let mut rects: Vec<BoundingRect> = Vec::new();
5031        for line in layout.lines() {
5032            let line_metrics = line.metrics();
5033            // Union all of the target's fragments on this line into a single rect
5034            let mut line_rect: Option<(f64, f64, f64, f64)> = None;
5035            let mut add = |x0: f64, y0: f64, x1: f64, y1: f64| {
5036                line_rect = Some(match line_rect {
5037                    Some((lx0, ly0, lx1, ly1)) => {
5038                        (lx0.min(x0), ly0.min(y0), lx1.max(x1), ly1.max(y1))
5039                    }
5040                    None => (x0, y0, x1, y1),
5041                });
5042            };
5043
5044            for item in line.items() {
5045                match item {
5046                    PositionedLayoutItem::GlyphRun(glyph_run) => {
5047                        let brush = glyph_run.style().brush;
5048                        let matches = if is_text {
5049                            brush.text_node == Some(node_id)
5050                        } else {
5051                            is_in_target(brush.id)
5052                        };
5053                        if !matches {
5054                            continue;
5055                        }
5056                        let x0 = glyph_run.offset() as f64;
5057                        let x1 = x0 + glyph_run.advance() as f64;
5058                        // Use the line box's block extent rather than the
5059                        // run's font ascent/descent: fonts with small
5060                        // typographic metrics would otherwise produce rects
5061                        // that clip the rendered glyphs. This matches the
5062                        // geometry used for text selection highlights.
5063                        let y0 = line_metrics.block_min_coord as f64;
5064                        let y1 = line_metrics.block_max_coord as f64;
5065                        add(x0, y0, x1, y1);
5066                    }
5067                    PositionedLayoutItem::InlineBox(inline_box) => {
5068                        if is_text || !is_in_target(NodeId::from_u64(inline_box.id)) {
5069                            continue;
5070                        }
5071                        let x0 = inline_box.x as f64;
5072                        let y0 = inline_box.y as f64;
5073                        add(
5074                            x0,
5075                            y0,
5076                            x0 + inline_box.width as f64,
5077                            y0 + inline_box.height as f64,
5078                        );
5079                    }
5080                }
5081            }
5082
5083            if let Some((x0, y0, x1, y1)) = line_rect {
5084                rects.push(BoundingRect {
5085                    x: origin_x + x0 / scale,
5086                    y: origin_y + y0 / scale,
5087                    width: (x1 - x0) / scale,
5088                    height: (y1 - y0) / scale,
5089                });
5090            }
5091        }
5092
5093        Some(rects)
5094    }
5095
5096    pub fn find_title_node(&self) -> Option<&Node> {
5097        TreeTraverser::new(self)
5098            .find(|node_id| {
5099                let node = &self.nodes[*node_id];
5100                let Some(element) = node.element_data() else {
5101                    return false;
5102                };
5103                if element.name.ns != ns!(html) || element.name.local != local_name!("title") {
5104                    return false;
5105                }
5106                node.parent
5107                    .and_then(|parent_id| self.nodes.get(parent_id))
5108                    .and_then(Node::element_data)
5109                    .is_some_and(|parent| {
5110                        parent.name.ns == ns!(html) && parent.name.local == local_name!("head")
5111                    })
5112            })
5113            .map(|node_id| &self.nodes[node_id])
5114    }
5115
5116    pub fn with_text_input(
5117        &mut self,
5118        node_id: NodeId,
5119        cb: impl FnOnce(PlainEditorDriver<TextBrush>),
5120    ) {
5121        let Some(node) = self.nodes.get_mut(node_id) else {
5122            return;
5123        };
5124
5125        if let Some(text_input) = node
5126            .element_data_mut()
5127            .and_then(|el| el.text_input_data_mut())
5128        {
5129            let mut font_ctx = self.font_ctx.lock().unwrap();
5130            let layout_ctx = &mut self.layout_ctx;
5131            let driver = text_input.editor.driver(&mut font_ctx, layout_ctx);
5132            cb(driver)
5133        }
5134    }
5135
5136    /// Recompute the scroll offset of the text input at `node_id` (if any) so that its caret
5137    /// remains visible within the input's content box.
5138    pub(crate) fn clamp_text_input_scroll(&mut self, node_id: NodeId) {
5139        let Some(node) = self.nodes.get_mut(node_id) else {
5140            return;
5141        };
5142
5143        let content_box_width = node.final_layout().content_box_width();
5144        let content_box_height = node.final_layout().content_box_height();
5145
5146        if let Some(text_input) = node
5147            .element_data_mut()
5148            .and_then(|el| el.text_input_data_mut())
5149        {
5150            text_input.clamp_scroll_offset(content_box_width, content_box_height);
5151        }
5152    }
5153
5154    pub(crate) fn compute_has_canvas(&self) -> bool {
5155        TreeTraverser::new(self).any(|node_id| {
5156            let node = &self.nodes[node_id];
5157            let Some(element) = node.element_data() else {
5158                return false;
5159            };
5160            if element.name.local == local_name!("canvas") && element.has_attr(local_name!("src")) {
5161                return true;
5162            }
5163
5164            false
5165        })
5166    }
5167
5168    // Text selection methods
5169
5170    /// Find the text position (inline_root_id, byte_offset) at a given point.
5171    /// Uses hit() for proper coordinate transformation, then finds the inline root
5172    /// and byte offset.
5173    pub fn find_text_position(&self, x: f32, y: f32) -> Option<(NodeId, usize)> {
5174        let hit = self.hit(x, y)?;
5175        let hit_node = self.get_node(hit.node_id)?;
5176        let inline_root = hit_node.inline_root_ancestor()?;
5177        let byte_offset = inline_root.text_offset_at_point(hit.x, hit.y)?;
5178        Some((inline_root.id, byte_offset))
5179    }
5180
5181    /// Find the word or line at a point, as `(inline_root_id, start, end)`.
5182    ///
5183    /// The multi-click counterpart of
5184    /// [`find_text_position`](Self::find_text_position): that one answers where
5185    /// a caret goes, this one answers what a double or triple click selects.
5186    pub fn find_text_range(
5187        &self,
5188        x: f32,
5189        y: f32,
5190        granularity: TextGranularity,
5191    ) -> Option<(NodeId, usize, usize)> {
5192        let hit = self.hit(x, y)?;
5193        let hit_node = self.get_node(hit.node_id)?;
5194        let inline_root = hit_node.inline_root_ancestor()?;
5195        let range = inline_root.text_range_at_point(hit.x, hit.y, granularity)?;
5196        Some((inline_root.id, range.start, range.end))
5197    }
5198
5199    /// Set the text selection range (creates a new selection from anchor to focus)
5200    pub fn set_text_selection(
5201        &mut self,
5202        anchor_node: NodeId,
5203        anchor_offset: usize,
5204        focus_node: NodeId,
5205        focus_offset: usize,
5206    ) {
5207        self.dom_selection = None;
5208        self.text_selection =
5209            TextSelection::new(anchor_node, anchor_offset, focus_node, focus_offset);
5210
5211        // For anonymous blocks, switch to storing parent+sibling_index (stable reference)
5212        if let (Some(parent), Some(idx)) = self.anonymous_block_location(anchor_node) {
5213            self.text_selection
5214                .anchor
5215                .set_anonymous(parent, idx, anchor_offset);
5216        }
5217        if let (Some(parent), Some(idx)) = self.anonymous_block_location(focus_node) {
5218            self.text_selection
5219                .focus
5220                .set_anonymous(parent, idx, focus_offset);
5221        }
5222    }
5223
5224    /// Get the parent ID and sibling index for a node if it's an anonymous block.
5225    /// Returns (None, None) for non-anonymous blocks.
5226    fn anonymous_block_location(&self, node_id: NodeId) -> (Option<NodeId>, Option<usize>) {
5227        let Some(node) = self.get_node(node_id) else {
5228            return (None, None);
5229        };
5230
5231        if !node.is_anonymous() {
5232            return (None, None);
5233        }
5234
5235        let Some(parent_id) = node.parent else {
5236            return (None, None);
5237        };
5238
5239        let Some(parent) = self.get_node(parent_id) else {
5240            return (Some(parent_id), None);
5241        };
5242
5243        let layout_children = parent.layout_children.borrow();
5244        let Some(children) = layout_children.as_ref() else {
5245            return (Some(parent_id), None);
5246        };
5247
5248        // Find the index of this anonymous block among siblings
5249        let mut anon_index = 0;
5250        for &child_id in children.iter() {
5251            if child_id == node_id {
5252                return (Some(parent_id), Some(anon_index));
5253            }
5254            if self.get_node(child_id).is_some_and(|n| n.is_anonymous()) {
5255                anon_index += 1;
5256            }
5257        }
5258
5259        (Some(parent_id), None)
5260    }
5261
5262    /// Clear the text selection
5263    pub fn clear_text_selection(&mut self) {
5264        self.dom_selection = None;
5265        self.text_selection.clear();
5266    }
5267
5268    /// Update the selection focus point (used during mouse drag to extend selection).
5269    pub fn update_selection_focus(&mut self, focus_node: NodeId, focus_offset: usize) {
5270        self.dom_selection = None;
5271        // For anonymous blocks, store parent+sibling_index; otherwise store node directly
5272        if let (Some(parent), Some(idx)) = self.anonymous_block_location(focus_node) {
5273            self.text_selection
5274                .focus
5275                .set_anonymous(parent, idx, focus_offset);
5276        } else {
5277            self.text_selection.set_focus(focus_node, focus_offset);
5278        }
5279    }
5280
5281    /// Extend text selection to the given point. Returns true if selection was updated.
5282    /// This is a convenience method that combines find_text_position and update_selection_focus.
5283    pub fn extend_text_selection_to_point(&mut self, x: f32, y: f32) -> bool {
5284        if !self.text_selection.anchor.is_some() {
5285            return false;
5286        }
5287
5288        if let Some((node, offset)) = self.find_text_position(x, y) {
5289            self.update_selection_focus(node, offset);
5290            self.shell_provider.request_redraw();
5291            true
5292        } else {
5293            false
5294        }
5295    }
5296
5297    /// Find the Nth anonymous block under a parent.
5298    fn find_anonymous_block_by_index(
5299        &self,
5300        parent_id: NodeId,
5301        target_index: usize,
5302    ) -> Option<NodeId> {
5303        let parent = self.get_node(parent_id)?;
5304        let layout_children = parent.layout_children.borrow();
5305        let children = layout_children.as_ref()?;
5306
5307        children
5308            .iter()
5309            .filter(|&&child_id| self.get_node(child_id).is_some_and(|n| n.is_anonymous()))
5310            .nth(target_index)
5311            .copied()
5312    }
5313
5314    /// Check if there is an active (non-empty) text selection
5315    pub fn has_text_selection(&self) -> bool {
5316        self.dom_selection.as_ref().map_or_else(
5317            || self.text_selection.is_active(),
5318            |range| !range.bounds().collapsed(),
5319        )
5320    }
5321
5322    /// Get the selected text content, supporting selection across multiple inline roots.
5323    pub fn get_selected_text(&self) -> Option<String> {
5324        if let Some(range) = &self.dom_selection {
5325            let text = self.range_string(range.bounds());
5326            return (!text.is_empty()).then_some(text);
5327        }
5328        let ranges = self.get_text_selection_ranges();
5329        if ranges.is_empty() {
5330            return None;
5331        }
5332
5333        let mut result = String::new();
5334        for (node_id, start, end) in &ranges {
5335            let node = self.get_node(*node_id)?;
5336            let element_data = node.element_data()?;
5337            let inline_layout = element_data.inline_layout_data.as_ref()?;
5338
5339            if *end > inline_layout.text.len() {
5340                continue;
5341            }
5342
5343            if !result.is_empty() {
5344                result.push(' ');
5345            }
5346            result.push_str(&inline_layout.text[*start..*end]);
5347        }
5348
5349        if result.is_empty() {
5350            None
5351        } else {
5352            Some(result)
5353        }
5354    }
5355
5356    /// The selection as HTML, for a clipboard that can carry formatting.
5357    ///
5358    /// The same ranges [`Self::get_selected_text`] walks, with each one wrapped
5359    /// in the tag of the element it came from, so bold stays bold and a code
5360    /// span stays a code span when it lands in another application. Pasting
5361    /// formatted text out of a Blitz window was impossible before this: plain
5362    /// text was the only payload ever written.
5363    ///
5364    /// Only the element's own tag is reproduced, not its ancestors or its
5365    /// styles. That is deliberate: a paste should carry the structure the author
5366    /// wrote, not this window's theme, and dragging a `class` into another
5367    /// application's document would reference styles that do not exist there.
5368    pub fn get_selected_html(&self) -> Option<String> {
5369        let ranges = self.get_text_selection_ranges();
5370        if ranges.is_empty() {
5371            return None;
5372        }
5373
5374        let mut result = String::new();
5375        for (node_id, start, end) in &ranges {
5376            let Some(node) = self.get_node(*node_id) else {
5377                continue;
5378            };
5379            let Some(element_data) = node.element_data() else {
5380                continue;
5381            };
5382            let Some(inline_layout) = element_data.inline_layout_data.as_ref() else {
5383                continue;
5384            };
5385            if *end > inline_layout.text.len() {
5386                continue;
5387            }
5388
5389            if !result.is_empty() {
5390                result.push(' ');
5391            }
5392
5393            let tag = element_data.name.local.as_ref();
5394            let fragment = escape_html(&inline_layout.text[*start..*end]);
5395            // A block tag around a fragment of a paragraph would be wrong: the
5396            // range is a run of text, and the element it belongs to may be only
5397            // partly selected. Inline tags carry meaning a paste should keep;
5398            // anything else contributes its text and nothing more.
5399            if matches!(
5400                tag,
5401                "b" | "strong" | "i" | "em" | "code" | "kbd" | "mark" | "s" | "u" | "sub" | "sup"
5402            ) {
5403                result.push_str(&format!("<{tag}>{fragment}</{tag}>"));
5404            } else {
5405                result.push_str(&fragment);
5406            }
5407        }
5408
5409        if result.is_empty() {
5410            None
5411        } else {
5412            Some(result)
5413        }
5414    }
5415
5416    /// Get all selection ranges as Vec<(node_id, start_offset, end_offset)>.
5417    /// Returns empty vec if no selection.
5418    pub fn get_text_selection_ranges(&self) -> Vec<(NodeId, usize, usize)> {
5419        if let Some(range) = &self.dom_selection {
5420            return self.range_layout_ranges(range.bounds());
5421        }
5422        let lookup = |parent_id, idx| self.find_anonymous_block_by_index(parent_id, idx);
5423
5424        let anchor_node = match self.text_selection.anchor.resolve_node_id(lookup) {
5425            Some(id) => id,
5426            None => return Vec::new(),
5427        };
5428        let focus_node = match self.text_selection.focus.resolve_node_id(lookup) {
5429            Some(id) => id,
5430            None => return Vec::new(),
5431        };
5432
5433        // Guard against stale selection endpoints: nodes may have been removed from
5434        // the document (e.g. by script) since the selection was made.
5435        let node_is_in_doc = |node_id: NodeId| {
5436            self.nodes
5437                .get(node_id)
5438                .is_some_and(|node| node.flags.is_in_document())
5439        };
5440        if !node_is_in_doc(anchor_node) || !node_is_in_doc(focus_node) {
5441            return Vec::new();
5442        }
5443
5444        // Single node selection
5445        if anchor_node == focus_node {
5446            let start = self
5447                .text_selection
5448                .anchor
5449                .offset
5450                .min(self.text_selection.focus.offset);
5451            let end = self
5452                .text_selection
5453                .anchor
5454                .offset
5455                .max(self.text_selection.focus.offset);
5456
5457            if start == end {
5458                return Vec::new();
5459            }
5460            return vec![(anchor_node, start, end)];
5461        }
5462
5463        // Multi-node selection: collect all inline roots between anchor and focus
5464        let inline_roots = self.collect_inline_roots_in_range(anchor_node, focus_node);
5465        if inline_roots.is_empty() {
5466            return Vec::new();
5467        }
5468
5469        // Determine document order using the collected inline_roots order
5470        // (inline_roots is already in document order from first to last)
5471        let first_in_roots = inline_roots[0];
5472
5473        let (first_node, first_offset, last_node, last_offset) =
5474            if first_in_roots == anchor_node || (first_in_roots != focus_node) {
5475                // anchor is first (or neither endpoint is in roots, which shouldn't happen)
5476                (
5477                    anchor_node,
5478                    self.text_selection.anchor.offset,
5479                    focus_node,
5480                    self.text_selection.focus.offset,
5481                )
5482            } else {
5483                // focus is first
5484                (
5485                    focus_node,
5486                    self.text_selection.focus.offset,
5487                    anchor_node,
5488                    self.text_selection.anchor.offset,
5489                )
5490            };
5491
5492        let mut ranges = Vec::with_capacity(inline_roots.len());
5493
5494        for &node_id in &inline_roots {
5495            let Some(node) = self.get_node(node_id) else {
5496                continue;
5497            };
5498            let Some(element_data) = node.element_data() else {
5499                continue;
5500            };
5501            let Some(inline_layout) = element_data.inline_layout_data.as_ref() else {
5502                continue;
5503            };
5504
5505            let text_len = inline_layout.text.len();
5506
5507            if node_id == first_node && node_id == last_node {
5508                let start = first_offset.min(last_offset);
5509                let end = first_offset.max(last_offset);
5510                if start < end && end <= text_len {
5511                    ranges.push((node_id, start, end));
5512                }
5513            } else if node_id == first_node {
5514                if first_offset < text_len {
5515                    ranges.push((node_id, first_offset, text_len));
5516                }
5517            } else if node_id == last_node {
5518                if last_offset > 0 && last_offset <= text_len {
5519                    ranges.push((node_id, 0, last_offset));
5520                }
5521            } else if text_len > 0 {
5522                ranges.push((node_id, 0, text_len));
5523            }
5524        }
5525
5526        ranges
5527    }
5528}
5529
5530#[derive(Debug, Clone, Copy, PartialEq)]
5531pub struct BoundingRect {
5532    pub x: f64,
5533    pub y: f64,
5534    pub width: f64,
5535    pub height: f64,
5536}
5537
5538/// The record of changes a script's `MutationObserver` reads. See
5539/// [`crate::DomMutation`] for what is recorded and why.
5540impl BaseDocument {
5541    /// Note a `<details open>` presence change for the toggle event. `present` is whether the
5542    /// attribute exists after this write.
5543    pub(crate) fn record_details_open(
5544        &mut self,
5545        node_id: NodeId,
5546        name: &markup5ever::QualName,
5547        present: bool,
5548    ) {
5549        if name.local != local_name!("open") || !name.ns.is_empty() {
5550            return;
5551        }
5552        let Some(element) = self.nodes[node_id].element_data() else {
5553            return;
5554        };
5555        if element.name.local != local_name!("details") || element.name.ns != ns!(html) {
5556            return;
5557        }
5558        let was_open = element.attr(local_name!("open")).is_some();
5559        if was_open != present && !self.details_toggles.iter().any(|(id, _)| *id == node_id) {
5560            self.details_toggles.push((node_id, was_open));
5561        }
5562    }
5563
5564    /// The inert document template contents belong to.
5565    pub(crate) fn template_contents_owner(&mut self) -> NodeId {
5566        if let Some(owner) = self.template_contents_owner {
5567            return owner;
5568        }
5569        let mut data = crate::node::DocumentData::default();
5570        data.content_type = "text/html";
5571        let owner = self.create_node(NodeData::Document(Box::new(data)));
5572        self.template_contents_owner = Some(owner);
5573        owner
5574    }
5575
5576    /// How many Stylo traversals have restyled this document.
5577    pub fn style_revision(&self) -> u64 {
5578        self.style_revision
5579    }
5580
5581    /// How many times layout has been computed for this document.
5582    pub fn layout_revision(&self) -> u64 {
5583        self.layout_revision
5584    }
5585
5586    pub(crate) fn note_layout_resolved(&mut self) {
5587        self.layout_revision = self.layout_revision.wrapping_add(1);
5588    }
5589
5590    /// Changes whenever the device media queries are evaluated against changes.
5591    pub fn viewport_generation(&self) -> u64 {
5592        self.viewport_generation
5593    }
5594
5595    /// The `<details>` toggles recorded since the last call, each with its old open state.
5596    pub fn take_details_toggles(&mut self) -> Vec<(NodeId, bool)> {
5597        std::mem::take(&mut self.details_toggles)
5598    }
5599
5600    /// Update the raw content handler state at the attribute mutation boundary.
5601    /// Equal-value writes still replace a compiled or script-assigned handler.
5602    pub(crate) fn record_inline_handler_attribute(
5603        &mut self,
5604        node_id: NodeId,
5605        name: &crate::QualName,
5606        value: Option<&str>,
5607    ) {
5608        if name.ns != markup5ever::ns!() || !name.local.as_ref().starts_with("on") {
5609            return;
5610        }
5611        let Some(element) = self
5612            .nodes
5613            .get_mut(node_id)
5614            .and_then(|node| node.element_data_mut())
5615        else {
5616            return;
5617        };
5618        let value = value.map(crate::node::AttrAtom::from);
5619        if let Some(value) = &value {
5620            let attributes = element
5621                .inline_event_attributes
5622                .get_or_insert_with(|| Box::new(Vec::new()));
5623            if let Some(attribute) = attributes
5624                .iter_mut()
5625                .find(|attribute| attribute.name.local == name.local)
5626            {
5627                attribute.name = name.clone();
5628                attribute.value = value.clone();
5629            } else {
5630                attributes.push(crate::node::Attribute {
5631                    name: name.clone(),
5632                    value: value.clone(),
5633                });
5634            }
5635        } else {
5636            let Some(attributes) = element.inline_event_attributes.as_mut() else {
5637                return;
5638            };
5639            let Some(index) = attributes
5640                .iter()
5641                .position(|attribute| attribute.name.local == name.local)
5642            else {
5643                return;
5644            };
5645            attributes.remove(index);
5646            if attributes.is_empty() {
5647                element.inline_event_attributes = None;
5648            }
5649        }
5650        self.inline_handler_changes
5651            .push((node_id, name.clone(), value));
5652    }
5653
5654    /// Take content handler changes in mutation order.
5655    pub fn take_inline_handler_changes(
5656        &mut self,
5657    ) -> Vec<(NodeId, crate::QualName, Option<crate::node::AttrAtom>)> {
5658        std::mem::take(&mut self.inline_handler_changes)
5659    }
5660
5661    /// Start or stop recording changes. Stopping discards what was recorded
5662    /// and not yet taken.
5663    pub fn set_recording_mutations(&mut self, recording: bool) {
5664        match (recording, self.mutation_log.is_some()) {
5665            (true, false) => self.mutation_log = Some(Vec::new()),
5666            (false, true) => self.mutation_log = None,
5667            _ => {}
5668        }
5669    }
5670
5671    /// Whether changes are being recorded.
5672    pub fn is_recording_mutations(&self) -> bool {
5673        self.mutation_log.is_some()
5674    }
5675    /// Whether observer delivery still has recorded changes to consume.
5676    pub fn has_pending_mutations(&self) -> bool {
5677        self.mutation_log
5678            .as_ref()
5679            .is_some_and(|records| !records.is_empty())
5680    }
5681
5682    /// Take every change recorded since the last call, oldest first.
5683    pub fn take_mutations(&mut self) -> Vec<crate::DomMutation> {
5684        self.mutation_log
5685            .as_mut()
5686            .map(std::mem::take)
5687            .unwrap_or_default()
5688    }
5689
5690    pub(crate) fn record_mutation(&mut self, mutation: crate::DomMutation) {
5691        if let Some(log) = self.mutation_log.as_mut() {
5692            if log.len() < crate::mutation_record::MUTATION_LOG_CAP {
5693                log.push(mutation);
5694            }
5695        }
5696    }
5697
5698    /// Where `node_id` sits among its siblings: its parent and the siblings on
5699    /// either side, as a child-list record reports them.
5700    pub(crate) fn sibling_context(
5701        &self,
5702        node_id: NodeId,
5703    ) -> Option<(NodeId, Option<NodeId>, Option<NodeId>)> {
5704        let parent_id = self.nodes.get(node_id)?.parent?;
5705        let siblings = &self.nodes.get(parent_id)?.children;
5706        let index = siblings.iter().position(|id| *id == node_id)?;
5707        let previous = index.checked_sub(1).map(|i| siblings[i]);
5708        let next = siblings.get(index + 1).copied();
5709        Some((parent_id, previous, next))
5710    }
5711}
5712
5713impl AsRef<BaseDocument> for BaseDocument {
5714    fn as_ref(&self) -> &BaseDocument {
5715        self
5716    }
5717}
5718
5719impl AsMut<BaseDocument> for BaseDocument {
5720    fn as_mut(&mut self) -> &mut BaseDocument {
5721        self
5722    }
5723}
5724
5725#[cfg(test)]
5726mod hover_state_tests {
5727    use super::*;
5728    use crate::{Attribute, qual_name};
5729    use blitz_traits::shell::ColorScheme;
5730
5731    /// Build `<html><body style="margin:0"><div style="width:300px">some text
5732    /// <div style="height:50px"></div></div></body></html>` manually (the HTML
5733    /// parser lives in blitz-html, which would be a circular dev-dependency).
5734    /// The bare text next to a block sibling gets wrapped in an anonymous
5735    /// block, which becomes the inline root: text hits report the anonymous
5736    /// block as the hit node.
5737    fn make_doc() -> (BaseDocument, NodeId) {
5738        let mut doc = BaseDocument::new(DocumentConfig {
5739            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
5740            ..Default::default()
5741        });
5742        let root_id = doc.root_node().id;
5743        let style = |value: &str| Attribute {
5744            name: qual_name!("style"),
5745            value: value.into(),
5746        };
5747
5748        let mut mutator = doc.mutate();
5749        let html = mutator.create_element(qual_name!("html"), vec![]);
5750        let body = mutator.create_element(qual_name!("body"), vec![style("margin:0")]);
5751        let container = mutator.create_element(qual_name!("div"), vec![style("width:300px")]);
5752        let text = mutator.create_text_node("some text");
5753        let block = mutator.create_element(qual_name!("div"), vec![style("height:50px")]);
5754        mutator.append_children(container, &[text, block]);
5755        mutator.append_children(body, &[container]);
5756        mutator.append_children(html, &[body]);
5757        mutator.append_children(root_id, &[html]);
5758        drop(mutator);
5759
5760        doc.resolve(0.0);
5761        (doc, container)
5762    }
5763
5764    /// Whether text laid out with a real (non-zero-metric) font. Without the
5765    /// `system-fonts` feature text measures 0x0 and text hits are impossible,
5766    /// making these tests vacuous.
5767    fn text_has_size(doc: &BaseDocument, container: NodeId) -> bool {
5768        doc.nodes[container].final_layout().size.height > 50.0
5769    }
5770
5771    /// Regression test: hovering bare text wrapped in an anonymous block must
5772    /// report a text cursor. The hit node for such text is the anonymous
5773    /// inline root itself, while the *stored* hover target is canonicalized to
5774    /// the containing element — the cursor must be derived from the precise
5775    /// hit node, not the canonical target.
5776    #[test]
5777    fn hovering_text_in_anonymous_block_reports_text_cursor() {
5778        let (mut doc, container) = make_doc();
5779        if !text_has_size(&doc, container) {
5780            eprintln!("skipping: no usable font (text measures 0x0)");
5781            return;
5782        }
5783
5784        doc.set_hover_to(5.0, 8.0);
5785        assert!(doc.hover_node_is_text, "expected a text hit");
5786        let hit_id = doc.hover_hit_node_id.expect("expected a hit node");
5787        assert!(
5788            doc.nodes[hit_id].is_anonymous(),
5789            "expected the hit node to be the anonymous inline root"
5790        );
5791        assert_eq!(
5792            doc.get_hover_node_id(),
5793            Some(container),
5794            "expected the stored hover target to be the containing element"
5795        );
5796        assert_eq!(doc.get_cursor(), Some(CursorIcon::Text));
5797    }
5798
5799    #[test]
5800    fn semantic_hover_keeps_the_resolved_node_instead_of_hit_testing_again() {
5801        let (mut doc, container) = make_doc();
5802
5803        // This coordinate is outside the 300px-wide container. A coordinate
5804        // hit test therefore cannot select it, but semantic automation has
5805        // already selected the container by id and must preserve that target.
5806        doc.set_hover_to_node(container, 350.0, 250.0);
5807
5808        assert_eq!(doc.get_hover_node_id(), Some(container));
5809        assert_eq!(doc.hover_hit_node_id, Some(container));
5810
5811        doc.resolve(0.0);
5812        assert_eq!(
5813            doc.get_hover_node_id(),
5814            Some(container),
5815            "a resolve must not turn semantic identity back into a coordinate hit"
5816        );
5817    }
5818
5819    /// Hovering the empty region of the anonymous block (right of the text) is
5820    /// not a text hit: default cursor, same canonical hover target.
5821    #[test]
5822    fn hovering_anonymous_block_whitespace_reports_default_cursor() {
5823        let (mut doc, container) = make_doc();
5824        if !text_has_size(&doc, container) {
5825            eprintln!("skipping: no usable font (text measures 0x0)");
5826            return;
5827        }
5828
5829        doc.set_hover_to(250.0, 8.0);
5830        assert!(!doc.hover_node_is_text);
5831        assert_eq!(doc.get_hover_node_id(), Some(container));
5832        assert_eq!(doc.get_cursor(), Some(CursorIcon::Default));
5833    }
5834}
5835
5836#[cfg(test)]
5837mod control_scroll_tests {
5838    use super::*;
5839    use crate::{Attribute, qual_name};
5840    use blitz_traits::shell::ColorScheme;
5841
5842    #[test]
5843    fn controlled_scroll_dispatches_the_dom_scroll_event() {
5844        let mut doc = BaseDocument::new(DocumentConfig {
5845            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
5846            ..Default::default()
5847        });
5848        let root_id = doc.root_node().id;
5849        let style = |value: &str| Attribute {
5850            name: qual_name!("style"),
5851            value: value.into(),
5852        };
5853
5854        let mut mutator = doc.mutate();
5855        let html = mutator.create_element(qual_name!("html"), vec![]);
5856        let body = mutator.create_element(qual_name!("body"), vec![style("margin:0")]);
5857        let scroller = mutator.create_element(
5858            qual_name!("div"),
5859            vec![style("width:200px;height:100px;overflow-y:scroll")],
5860        );
5861        let spacer = mutator.create_element(qual_name!("div"), vec![style("height:400px")]);
5862        let target = mutator.create_element(qual_name!("button"), vec![style("height:40px")]);
5863        let target_text = mutator.create_text_node("Reveal me");
5864        mutator.append_children(target, &[target_text]);
5865        mutator.append_children(scroller, &[spacer, target]);
5866        mutator.append_children(body, &[scroller]);
5867        mutator.append_children(html, &[body]);
5868        mutator.append_children(root_id, &[html]);
5869        drop(mutator);
5870        doc.resolve(0.0);
5871
5872        // The manual mutator deliberately bypasses the HTML/style parser used
5873        // by loaded documents. Give the fixture explicit post-layout geometry
5874        // so this unit test isolates event forwarding rather than CSS parsing.
5875        doc.nodes[html].final_layout_mut().size.height = 300.0;
5876        doc.nodes[html].final_layout_mut().content_size.height = 600.0;
5877        doc.nodes[target].final_layout_mut().location.y = 400.0;
5878
5879        let mut events = Vec::new();
5880        // A semantic client may target the exposed text rather than its
5881        // element. Text has no `final_layout`, so this also pins the host-crash
5882        // regression from revealing a named label.
5883        doc.scroll_to_node_centered_with_events(target_text, |event| events.push(event));
5884
5885        assert!(
5886            (doc.viewport_scroll.y - 270.0).abs() < 0.1,
5887            "the 40px target should be centred in the 300px viewport"
5888        );
5889        assert!(
5890            events
5891                .iter()
5892                .any(|event| { event.target == html && event.name() == "scroll" })
5893        );
5894    }
5895}
5896
5897#[cfg(test)]
5898mod font_face_override_tests {
5899    use super::*;
5900    use crate::net::{FontFaceOverrides, Resource, ResourceLoadResponse};
5901
5902    /// Regression-pin for the `@font-face` descriptor-honouring fix.
5903    ///
5904    /// The bug was that `Resource::Font` carried only the raw font bytes,
5905    /// so `load_resource` registered fonts with `info_override = None` and
5906    /// parley fell back to the TTF's internal `name` table. After the fix,
5907    /// `Resource::Font` carries `FontFaceOverrides` and `load_resource`
5908    /// builds a `FontInfoOverride` from them — meaning a CSS-declared
5909    /// `font-family` alias wins over the file's own metadata.
5910    ///
5911    /// We drive `load_resource` directly with a fabricated response rather
5912    /// than go through HTML parsing → `fetch_font_face`, because the
5913    /// downstream HTML parser lives in `blitz-html` (would be a circular
5914    /// crate dependency). The mapping from `@font-face` descriptors into
5915    /// `FontFaceOverrides` is covered by the unit tests in `net.rs`; this
5916    /// test pins the load-side of the pipeline.
5917    #[test]
5918    fn font_face_overrides_alias_family_name() {
5919        const ALIAS: &str = "AliasedFamily";
5920
5921        let mut document = BaseDocument::new(DocumentConfig::default());
5922
5923        // Sanity: the alias name is not registered before we feed the font.
5924        {
5925            let mut ctx = document.font_ctx.lock().unwrap();
5926            assert!(
5927                ctx.collection.family_id(ALIAS).is_none(),
5928                "alias must not exist before registration",
5929            );
5930        }
5931
5932        // Drive `load_resource` with a `Resource::Font` whose overrides
5933        // assert the CSS-side family name. We use the bullet font as a
5934        // valid font payload — its internal `name` table is irrelevant to
5935        // the assertion; what matters is whether the override wins.
5936        let response = ResourceLoadResponse {
5937            request_id: 0,
5938            node_id: None,
5939            resolved_url: Some(String::from("test://aliased-family")),
5940            result: Ok(Resource::Font(
5941                blitz_traits::net::Bytes::from_static(crate::BULLET_FONT),
5942                FontFaceOverrides {
5943                    family_name: Some(String::from(ALIAS)),
5944                    weight: Some(800.0),
5945                    style: Some(parley::fontique::FontStyle::Italic),
5946                },
5947            )),
5948        };
5949        document.load_resource(response);
5950
5951        // The override must have taken effect: parley's `Collection` now
5952        // resolves the CSS-declared alias to a registered family.
5953        let mut ctx = document.font_ctx.lock().unwrap();
5954        let family_id = ctx
5955            .collection
5956            .family_id(ALIAS)
5957            .expect("CSS-declared family name should be registered as a family alias");
5958        let resolved_name = ctx
5959            .collection
5960            .family_name(family_id)
5961            .expect("family id should resolve back to a name");
5962        assert_eq!(
5963            resolved_name, ALIAS,
5964            "registered family should report the CSS-declared name, \
5965             not the font file's internal `name` table entry",
5966        );
5967    }
5968}
5969
5970#[cfg(test)]
5971mod clipboard_html_tests {
5972    use super::escape_html;
5973
5974    /// A selection is document text, so markup characters in it are content.
5975    /// Unescaped, `a < b` opens a tag in whatever receives the paste.
5976    #[test]
5977    fn markup_characters_in_a_selection_are_escaped() {
5978        assert_eq!(
5979            escape_html("a < b && c > d"),
5980            "a &lt; b &amp;&amp; c &gt; d"
5981        );
5982    }
5983
5984    /// The ampersand has to go first, or escaping the others re-escapes the
5985    /// entities just written and `<` arrives as `&amp;lt;`.
5986    #[test]
5987    fn an_ampersand_is_not_double_escaped() {
5988        assert_eq!(escape_html("&lt;"), "&amp;lt;");
5989    }
5990
5991    /// Ordinary prose is left exactly as it is, including the apostrophes and
5992    /// quotes that a paste should carry through unchanged.
5993    #[test]
5994    fn prose_is_untouched() {
5995        assert_eq!(escape_html("it's \"fine\""), "it's &quot;fine&quot;");
5996    }
5997}