Skip to main content

script/dom/
selection.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::{Cell, LazyCell};
6use std::cmp::Ordering;
7
8use atomic_refcell::{AtomicRef, AtomicRefCell};
9use bitflags::bitflags;
10use dom_struct::dom_struct;
11use js::context::{JSContext, NoGC};
12use layout_api::QueryMsg;
13use rustc_hash::{FxHashMap, FxHashSet};
14use script_bindings::cell::DomRefCell;
15use script_bindings::codegen::GenericBindings::ShadowRootBinding::ShadowRootMethods;
16use script_bindings::dom::UnrootedDom;
17use script_bindings::reflector::{Reflector, reflect_dom_object};
18use servo_base::text::{
19    AssumeUnder4GB, RangeAny, Utf16CodeUnits, Utf32CodeUnits, Utf32CodeUnitsOrNodeOffset,
20};
21
22use crate::dom::abstractrange::bp_position;
23use crate::dom::bindings::cell::AtomicSafeBorrowMut;
24use crate::dom::bindings::codegen::Bindings::NodeBinding::{GetRootNodeOptions, NodeMethods};
25use crate::dom::bindings::codegen::Bindings::RangeBinding::RangeMethods;
26use crate::dom::bindings::codegen::Bindings::SelectionBinding::{
27    GetComposedRangesOptions, SelectionMethods,
28};
29use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
30use crate::dom::bindings::inheritance::Castable;
31use crate::dom::bindings::refcounted::Trusted;
32use crate::dom::bindings::reflector::DomGlobal;
33use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
34use crate::dom::bindings::str::DOMString;
35use crate::dom::comparator::compare_dom_positions;
36use crate::dom::document::Document;
37use crate::dom::eventtarget::EventTarget;
38use crate::dom::iterators::{PrePostIteration, UnrootedFollowingFlatTreeNodesTraversal};
39use crate::dom::range::Range;
40use crate::dom::selection_range::{RootedSelectionBoundary, SelectionBoundary, SelectionRange};
41use crate::dom::staticrange::StaticRange;
42use crate::dom::traversal::FlatTreeForSelectionNoGcTraversal;
43use crate::dom::types::{HTMLInputElement, HTMLTextAreaElement, ShadowRoot};
44use crate::dom::{
45    CharacterData, Element, FlatTreeParent, Node, NodeDamage, NodeFlags, NodeTraits, StartOrEnd,
46};
47
48/// Used value of [`user-select`](https://drafts.csswg.org/css-ui-4/#propdef-user-select):
49/// like the computed value but excludes `auto`.
50#[derive(Copy, Clone, PartialEq)]
51pub(crate) enum UsedUserSelect {
52    Text,
53    None,
54    Contain,
55    All,
56}
57
58#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
59pub(crate) enum Direction {
60    Forwards,
61    Backwards,
62    Directionless,
63}
64
65/// <https://w3c.github.io/selection-api/#dfn-selection>
66#[dom_struct]
67pub(crate) struct Selection {
68    reflector_: Reflector,
69    document: Dom<Document>,
70    /// A range that holds the start and end of this selection, which may potentially
71    /// cross shadow roots.
72    range: DomRefCell<Option<SelectionRange>>,
73    /// The live range version of this selection, which will never cross shadow roots.
74    live_range: MutNullableDom<Range>,
75    /// This is like [`Range`], but in the flat tree, which means that:
76    ///
77    /// * It is `None` if the selection is unrenderable.
78    /// * Boundaries are in flat tree order.
79    #[custom_trace]
80    visible_range: AtomicRefCell<Option<SelectionRange>>,
81    /// Whether or not a blinking caret needs to be rendered for this selection when it
82    /// is 0-length.
83    paints_caret: Cell<bool>,
84    /// The [`Direction`] of this [`Selection`] which determines which endpoint of
85    /// [`Self::range`] is the anchor and which is the focus.
86    direction: Cell<Direction>,
87    /// <https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event>
88    has_scheduled_selectionchange_event: Cell<bool>,
89    /// Whether or not this [`Selection`] needs to remark DOM nodes with selection flags
90    /// after a change to its underlying [`Range`].
91    visible_selection_dirty: Cell<bool>,
92}
93
94impl Selection {
95    fn new_inherited(document: &Document) -> Selection {
96        Selection {
97            reflector_: Reflector::new(),
98            document: Dom::from_ref(document),
99            range: Default::default(),
100            live_range: MutNullableDom::new(None),
101            visible_range: Default::default(),
102            paints_caret: Cell::new(false),
103            direction: Cell::new(Direction::Directionless),
104            has_scheduled_selectionchange_event: Cell::new(false),
105            visible_selection_dirty: Cell::new(false),
106        }
107    }
108
109    pub(crate) fn new(cx: &mut JSContext, document: &Document) -> DomRoot<Selection> {
110        reflect_dom_object(
111            cx,
112            Box::new(Selection::new_inherited(document)),
113            &*document.global(),
114        )
115    }
116
117    pub(crate) fn visible_selection_dirty(&self) -> bool {
118        self.visible_selection_dirty.get()
119    }
120
121    pub(crate) fn collapsed(&self) -> bool {
122        self.range
123            .borrow()
124            .as_ref()
125            .is_none_or(|range| range.collapsed())
126    }
127
128    fn clear_cached_live_range(&self) {
129        if let Some(old_range) = self.live_range.take() {
130            old_range.disassociate_selection(self);
131        }
132    }
133
134    /// Clear this entire [`Selection`] if the [`Document`] of its live range has changed
135    /// or its boundaries are no longer connected. Returns true if the selection was
136    /// cleared or false otherwise.
137    pub(crate) fn clear_selection_if_live_range_document_changed(
138        &self,
139        no_gc: &NoGC,
140        range: &Range,
141    ) -> bool {
142        // The live range might be in an intermediate state where its boundaries
143        // are in different documents, so this must check both ends.
144        let range_start_container = range.start_container();
145        let range_end_container = range.end_container();
146        if self.is_in_composed_tree_of_document_and_is_not_ua_widget(&range_start_container) &&
147            self.is_in_composed_tree_of_document_and_is_not_ua_widget(&range_end_container)
148        {
149            return false;
150        }
151
152        self.set_range(no_gc, None);
153        true
154    }
155
156    /// Update the start of end boundary of this [`Selection`] based on a change to the
157    /// given associated [`Range`]. While the behavior here isn't totally specified yet,
158    /// it follows other browsers. If the change would change the direction of the
159    /// [`Selection`] it is collapsed at the newly-set boundary.
160    pub(crate) fn set_start_or_end_from_live_range(
161        &self,
162        no_gc: &NoGC,
163        start_or_end: StartOrEnd,
164        live_range: &Range,
165    ) -> bool {
166        let mut range = self.range.borrow_mut();
167        let range = range
168            .as_mut()
169            .expect("A live range implies a selection range");
170
171        let (container, offset) = match start_or_end {
172            StartOrEnd::Start if range.start != *live_range.start() => {
173                (live_range.start_container(), live_range.start_offset())
174            },
175            StartOrEnd::End if range.end != *live_range.end() => {
176                (live_range.end_container(), live_range.end_offset())
177            },
178            _ => return false,
179        };
180
181        let would_invert = match start_or_end {
182            StartOrEnd::Start => {
183                compare_shadow_including_dom_positions(
184                    no_gc,
185                    &container,
186                    offset,
187                    &range.end.container,
188                    range.end.offset,
189                ) == Ordering::Greater
190            },
191            StartOrEnd::End => {
192                compare_shadow_including_dom_positions(
193                    no_gc,
194                    &range.start.container,
195                    range.start.offset,
196                    &container,
197                    offset,
198                ) == Ordering::Greater
199            },
200        };
201
202        if would_invert {
203            *range = SelectionRange::collapsed_at(SelectionBoundary::new(&container, offset));
204        } else {
205            match start_or_end {
206                StartOrEnd::Start => range.start = SelectionBoundary::new(&container, offset),
207                StartOrEnd::End => range.end = SelectionBoundary::new(&container, offset),
208            }
209        }
210        true
211    }
212
213    pub(crate) fn update_from_live_range(
214        &self,
215        no_gc: &NoGC,
216        live_range: &Range,
217        notification: SelectionLiveRangeNotification,
218    ) {
219        debug_assert!(Some(live_range) == self.live_range.get().as_deref());
220        let start_changed = notification.contains(SelectionLiveRangeNotification::Start) &&
221            self.set_start_or_end_from_live_range(no_gc, StartOrEnd::Start, live_range);
222        let end_changed = notification.contains(SelectionLiveRangeNotification::End) &&
223            self.set_start_or_end_from_live_range(no_gc, StartOrEnd::End, live_range);
224        if start_changed || end_changed {
225            self.selection_boundaries_changed();
226        }
227    }
228
229    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
230    fn set_range(&self, _no_gc: &NoGC, new_range: Option<SelectionRange>) -> bool {
231        let changed;
232        {
233            let mut range = self.range.borrow_mut();
234            changed = *range != new_range;
235            *range = new_range;
236
237            if range.is_none() {
238                self.direction.set(Direction::Directionless);
239            }
240        }
241
242        // Any changes must unconditionally install a new live range.
243        self.clear_cached_live_range();
244
245        if changed {
246            self.selection_boundaries_changed();
247            #[cfg(debug_assertions)]
248            self.assert_valid_selection(_no_gc);
249        }
250
251        changed
252    }
253
254    pub(crate) fn set_live_range(&self, no_gc: &NoGC, new_range: Option<&Range>) {
255        if new_range == self.live_range.get().as_deref() {
256            return;
257        }
258
259        let boundaries_changed = self.set_range(no_gc, new_range.map(|new_range| new_range.into()));
260
261        // It's possible that `set_range` was a no-op, but still in that case we need to
262        // replace the live range per-specification.
263        if let Some(old_range) = self.live_range.take() {
264            old_range.disassociate_selection(self);
265        }
266        if let Some(new_range) = new_range {
267            self.live_range.set(Some(new_range));
268            new_range.associate_selection(self);
269        }
270
271        // From <https://w3c.github.io/selection-api/#selectionchange-event>:
272        // > When the selection is dissociated with its range, associated with a new
273        // > range, or the associated range's boundary point is mutated either by the user
274        // > or the content script, the user agent must schedule a selectionchange event on
275        // > document.
276        //
277        // This means we should fire the event even if the boundaries themselves did not change. A
278        // change to the range object is enough. Normally, this happens in `set_range`, but
279        // only when the boundaries changed. In this case the call to `set_range` above did
280        // not queue the task.
281        if !boundaries_changed {
282            self.queue_selectionchange_task();
283        }
284    }
285
286    fn selection_boundaries_changed(&self) {
287        self.set_visible_selection_dirty();
288        self.queue_selectionchange_task();
289
290        // See:
291        //  - <https://w3c.github.io/editing/docs/execCommand/#state-override> and
292        //  - <https://w3c.github.io/editing/docs/execCommand/#value-override>
293        //
294        // > Whenever the number of ranges in the selection changes to something
295        // > different, and whenever a boundary point of the range at a given index in the
296        // > selection changes to something different, the state override and value
297        // > override must be unset for every command.
298        self.document.clear_command_overrides();
299    }
300
301    fn iter_nodes_with_overlaps_document_selection_flag<'no_gc>(
302        &self,
303        no_gc: &'no_gc NoGC,
304    ) -> impl Iterator<Item = UnrootedDom<'no_gc, Node>> {
305        let mut traversal = self
306            .document
307            .upcast::<Node>()
308            .following_flat_tree_nodes_unrooted(no_gc);
309        let mut next = traversal.next();
310        std::iter::from_fn(move || {
311            while let Some(node) = next.take() {
312                match node {
313                    PrePostIteration::Enter(node) => {
314                        if node.get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION) {
315                            next = traversal.next();
316                            return Some(node);
317                        } else {
318                            // This relies on flags being set consistently: this node
319                            // with the flag unset claims that no part of it overlaps selection,
320                            // which implies that none of its descendant either have any part
321                            // of them overlapping selection, meaning none of them have the flag
322                            next = traversal.next_skipping_subtree();
323                        }
324                    },
325                    PrePostIteration::Leave(_) => next = traversal.next(),
326                }
327            }
328            None
329        })
330    }
331
332    fn set_visible_range(&self, no_gc: &NoGC, flat_tree_selection: Option<FlatTreeSelection>) {
333        *self.visible_range.safe_borrow_mut(no_gc) = flat_tree_selection.map(|selection| {
334            SelectionRange::new(
335                SelectionBoundary::new(&selection.start.container, selection.start.offset),
336                SelectionBoundary::new(&selection.end.container, selection.end.offset),
337            )
338        });
339    }
340
341    pub(crate) fn update_overlaps_document_selection_flags(&self, no_gc: &NoGC) {
342        if !self.visible_selection_dirty.take() {
343            return;
344        }
345
346        self.paints_caret.set(
347            self.range
348                .borrow()
349                .as_ref()
350                .is_some_and(|range| self.should_paint_caret(range, no_gc)),
351        );
352
353        let previously_flagged_nodes = self
354            .iter_nodes_with_overlaps_document_selection_flag(no_gc)
355            .collect();
356        let flat_tree_selection = FlatTreeSelection::from_selection_if_renderable(no_gc, self);
357        VisibleSelectionFlagUpdate::run(
358            no_gc,
359            previously_flagged_nodes,
360            flat_tree_selection.as_ref(),
361            &self.document,
362            self.paints_caret.get(),
363        );
364        self.set_visible_range(no_gc, flat_tree_selection);
365    }
366
367    fn should_paint_caret(&self, range: &SelectionRange, no_gc: &NoGC) -> bool {
368        if let Some(shadow_root) = range.end.container.containing_shadow_root() {
369            let host = shadow_root.host_unrooted(no_gc);
370            if host.is::<HTMLInputElement>() || host.is::<HTMLTextAreaElement>() {
371                // This is the case where, if `selection_for_text_node` returns a selection
372                // it is a `TextInput` selection
373                return true;
374            }
375        }
376        // This is the case where, if `selection_for_text_node` returns a selection,
377        // it is a document selection.
378        servo_config::pref!(dom_exec_command_enabled) &&
379            range.collapsed() &&
380            self.document
381                .focus_handler()
382                .focused_area()
383                .element()
384                .is_some_and(|focused_element| {
385                    Some(focused_element.upcast::<Node>()) ==
386                        range.end.container.editing_host_of().as_deref()
387                })
388    }
389
390    /// <https://w3c.github.io/selection-api/#dfn-schedule-a-selectionchange-event>
391    pub(crate) fn queue_selectionchange_task(&self) {
392        // Step 1. If target's has scheduled selectionchange event is true, abort these steps.
393        if self.has_scheduled_selectionchange_event.get() {
394            return;
395        }
396        // Step 2. Set target's has scheduled selectionchange event to true.
397        self.has_scheduled_selectionchange_event.set(true);
398        // Step 3. Queue a task on the user interaction task source to fire a
399        // selectionchange event on target.
400        let this = Trusted::new(self);
401        self.document
402            .owner_global()
403            .task_manager()
404            .user_interaction_task_source() // w3c/selection-api#117
405            .queue(
406                // https://w3c.github.io/selection-api/#firing-selectionchange-event
407                task!(selectionchange_task_steps: move |cx| {
408                    let this = this.root();
409                    // Step 1. Set target's has scheduled selectionchange event to false.
410                    this.has_scheduled_selectionchange_event.set(false);
411                    // Step 2. If target is an element, fire an event named
412                    // selectionchange, which bubbles and not cancelable, at target.
413                    //
414                    // n/a
415
416                    // Step 3. Otherwise, if target is a document, fire an event named
417                    // selectionchange, which does not bubble and not cancelable, at
418                    // target.
419                    this.document.upcast::<EventTarget>().fire_event(cx, atom!("selectionchange"));
420                }),
421            );
422    }
423
424    fn is_in_composed_tree_of_document_and_is_not_ua_widget(&self, node: &Node) -> bool {
425        &*node.GetRootNode(&GetRootNodeOptions { composed: true }) == self.document.upcast::<Node>() &&
426            !node.is_in_ua_widget()
427    }
428
429    pub(crate) fn start_boundary(&self, cx: &mut JSContext) -> (DomRoot<Node>, u32) {
430        let range = self.expect_active_range(cx);
431        (range.start_container(), range.start_offset())
432    }
433
434    pub(crate) fn end_boundary(&self, cx: &mut JSContext) -> (DomRoot<Node>, u32) {
435        let range = self.expect_active_range(cx);
436        (range.end_container(), range.end_offset())
437    }
438
439    #[cfg(debug_assertions)]
440    fn assert_valid_selection(&self, no_gc: &NoGC) {
441        let range_borrow = self.range.borrow();
442        let Some(range) = range_borrow.as_ref() else {
443            return;
444        };
445        debug_assert_eq!(
446            range
447                .start
448                .container
449                .GetRootNode(&GetRootNodeOptions { composed: true }),
450            range
451                .end
452                .container
453                .GetRootNode(&GetRootNodeOptions { composed: true })
454        );
455        debug_assert!(
456            compare_shadow_including_dom_positions(
457                no_gc,
458                &range.start.container,
459                range.start.offset,
460                &range.end.container,
461                range.end.offset
462            ) != Ordering::Greater
463        );
464    }
465
466    #[cfg(debug_assertions)]
467    fn assert_valid_selection_and_live_range(&self, no_gc: &NoGC) {
468        self.assert_valid_selection(no_gc);
469
470        let Some(active_range) = self.live_range.get() else {
471            return;
472        };
473        debug_assert!(
474            bp_position(
475                no_gc,
476                &active_range.start_container(),
477                active_range.start_offset(),
478                &active_range.end_container(),
479                active_range.end_offset()
480            ) != Ordering::Greater
481        );
482    }
483
484    /// <https://w3c.github.io/editing/docs/execCommand/#active-range>
485    ///
486    /// > The active range is the range of the selection given by calling
487    /// > getSelection() on the context object. (Thus the active range may be null.)
488    pub(crate) fn active_range(&self, cx: &mut JSContext) -> Option<DomRoot<Range>> {
489        #[cfg(debug_assertions)]
490        self.assert_valid_selection_and_live_range(cx.no_gc());
491
492        if let Some(active_range) = self.live_range.get() {
493            return Some(active_range);
494        }
495
496        let live_range = {
497            let range = self.range.borrow();
498            let range = range.as_ref()?;
499            let live_range = Range::new(
500                cx,
501                &self.document,
502                &range.start.container,
503                range.start.offset,
504                &range.start.container,
505                range.start.offset,
506            );
507            live_range
508                .SetEnd(cx.no_gc(), &range.end.container, range.end.offset)
509                .expect("New end boundary should always be valid");
510            live_range
511        };
512
513        self.live_range.set(Some(&live_range));
514        live_range.associate_selection(self);
515        Some(live_range)
516    }
517
518    pub(crate) fn expect_active_range(&self, cx: &mut JSContext) -> DomRoot<Range> {
519        self.active_range(cx)
520            .expect("Should always have an active range")
521    }
522
523    pub(crate) fn set_visible_selection_dirty(&self) {
524        self.visible_selection_dirty.set(true);
525    }
526
527    pub(crate) fn composed_anchor_position(&self) -> Option<RootedSelectionBoundary> {
528        let range = self.range.borrow();
529        let range = range.as_ref()?;
530        let (container, offset) = match self.direction.get() {
531            Direction::Forwards => (range.start.container.as_rooted(), range.start.offset),
532            _ => (range.end.container.as_rooted(), range.end.offset),
533        };
534        Some(RootedSelectionBoundary::new_with_utf16_offset(
535            container, offset,
536        ))
537    }
538
539    /// <https://w3c.github.io/selection-api/#dfn-anchor>
540    fn live_anchor_node(&self, cx: &mut JSContext) -> Option<DomRoot<Node>> {
541        self.active_range(cx)
542            .map(|range| match self.direction.get() {
543                Direction::Forwards => range.start_container(),
544                _ => range.end_container(),
545            })
546    }
547
548    /// <https://w3c.github.io/selection-api/#dfn-anchor>
549    fn live_anchor_offset(&self, cx: &mut JSContext) -> u32 {
550        self.active_range(cx)
551            .map_or(0, |range| match self.direction.get() {
552                Direction::Forwards => range.start_offset(),
553                _ => range.end_offset(),
554            })
555    }
556
557    /// <https://w3c.github.io/selection-api/#dfn-focus>
558    fn live_focus_node(&self, cx: &mut JSContext) -> Option<DomRoot<Node>> {
559        self.active_range(cx)
560            .map(|range| match self.direction.get() {
561                Direction::Forwards => range.end_container(),
562                _ => range.start_container(),
563            })
564    }
565
566    /// <https://w3c.github.io/selection-api/#dfn-focus>
567    fn live_focus_offset(&self, cx: &mut JSContext) -> u32 {
568        self.active_range(cx)
569            .map_or(0, |range| match self.direction.get() {
570                Direction::Forwards => range.end_offset(),
571                _ => range.start_offset(),
572            })
573    }
574
575    /// <https://dom.spec.whatwg.org/#concept-node-insert> steps 5.1-5.2
576    /// and
577    /// <https://dom.spec.whatwg.org/#move> steps 17.1-17.2
578    /// adapted for selections.
579    pub(crate) fn insert_steps(&self, parent: &Node, child: &Node, count: u32) {
580        let mut range_borrow = self.range.borrow_mut();
581        let Some(range) = &mut *range_borrow else {
582            return;
583        };
584        let child_index = LazyCell::new(|| child.index());
585        // Step 5.1: For each live range whose start node is parent and start offset is
586        // greater than child’s index: increase its start offset by count.
587        if range.start.container == parent && range.start.offset > *child_index {
588            range.start.offset += count;
589            self.selection_boundaries_changed();
590        }
591        // Step 5.2: For each live range whose end node is parent and end offset is
592        // greater than child’s index: increase its end offset by count.
593        if range.end.container == parent && range.end.offset > *child_index {
594            range.end.offset += count;
595            self.selection_boundaries_changed();
596        }
597    }
598
599    /// <https://dom.spec.whatwg.org/#live-range-pre-remove-steps> steps 4-7
600    /// adapted for selections.
601    pub(crate) fn pre_remove_steps(
602        &self,
603        removed_node: &Node,           // "node" in the specification
604        parent_of_removed_node: &Node, // "parent" in the specification
605        index_of_removed_node: &mut dyn FnMut() -> u32, // "index" in the specification
606    ) {
607        let mut range_borrow = self.range.borrow_mut();
608        let Some(range) = &mut *range_borrow else {
609            return;
610        };
611
612        // Step 4: For each live range whose start node is an inclusive descendant of
613        // node, set its start to (parent, index).
614        if removed_node.is_shadow_including_inclusive_ancestor_of(&range.start.container) {
615            range.start = SelectionBoundary::new(parent_of_removed_node, index_of_removed_node());
616            self.selection_boundaries_changed();
617        }
618        // Step 5: For each live range whose end node is an inclusive descendant of node,
619        // set its end to (parent, index).
620        if removed_node.is_shadow_including_inclusive_ancestor_of(&range.end.container) {
621            range.end = SelectionBoundary::new(parent_of_removed_node, index_of_removed_node());
622            self.selection_boundaries_changed();
623        }
624        // Step 6: For each live range whose start node is parent and start offset is
625        // greater than index, decrease its start offset by 1.
626        if range.start.container == parent_of_removed_node &&
627            range.start.offset > index_of_removed_node()
628        {
629            range.start.offset -= 1;
630            self.selection_boundaries_changed();
631        }
632        // Step 7: For each live range whose end node is parent and end offset is greater than
633        // index, decrease its end offset by 1.
634        if range.end.container == parent_of_removed_node &&
635            range.end.offset > index_of_removed_node()
636        {
637            range.end.offset -= 1;
638            self.selection_boundaries_changed();
639        }
640    }
641
642    /// <https://dom.spec.whatwg.org/#dom-node-normalize> Steps 6.1-6.4 adapted for selections.
643    ///
644    /// - `parent`: The parent of both other node arguments.
645    /// - `node`: The node that text is being merged into.
646    /// - `current_node`: The node which has text being merged into `node` and will be
647    ///   removed from the DOM.
648    /// - `length`: The length of the text content that was merged into `node` from
649    ///   siblings before `current_node`.
650    pub(crate) fn normalization_steps(
651        &self,
652        parent: &Node,
653        node: &Node,
654        current_node: &Node,
655        current_node_index: &dyn Fn() -> u32,
656        length: u32,
657    ) {
658        let mut range_borrow = self.range.borrow_mut();
659        let Some(range) = &mut *range_borrow else {
660            return;
661        };
662        // Step 6.1: For each live range whose start node is currentNode: add length to its start
663        // offset and set its start node to node.
664        if range.start.container == current_node {
665            range.start.offset += length;
666            range.start.container = Dom::from_ref(node);
667            self.selection_boundaries_changed();
668        }
669        // Step 6.2 For each live range whose end node is currentNode: add length to its end offset
670        // and set its end node to node.
671        if range.end.container == current_node {
672            range.end.offset += length;
673            range.end.container = Dom::from_ref(node);
674            self.selection_boundaries_changed();
675        }
676        // Step 6.3: For each live range whose start node is currentNode’s parent and start
677        // offset is currentNode’s index: set its start node to node and its start offset
678        // to length.
679        if range.start.container == parent && range.start.offset == current_node_index() {
680            range.start.container = Dom::from_ref(node);
681            range.start.offset = length;
682            self.selection_boundaries_changed();
683        }
684        // Step 6.4: For each live range whose end node is currentNode’s parent and end offset is
685        // currentNode’s index: set its end node to node and its end offset to length.
686        if range.end.container == parent && range.end.offset == current_node_index() {
687            range.end.container = Dom::from_ref(node);
688            range.end.offset = length;
689            self.selection_boundaries_changed();
690        }
691    }
692
693    /// <https://dom.spec.whatwg.org/#concept-cd-replace> steps 8-11
694    /// adapted for selections.
695    pub(crate) fn replace_data_steps(
696        &self,
697        node: &Node,
698        offset: u32,
699        removed_code_units: u32,
700        added_code_units: &mut dyn FnMut() -> u32,
701    ) {
702        let mut range_borrow = self.range.borrow_mut();
703        let Some(range) = &mut *range_borrow else {
704            return;
705        };
706        // Step 8: For each live range whose start node is node and start offset is
707        // greater than offset but less than or equal to offset + count: set its start
708        // offset to offset.
709        let start_container = &range.start.container;
710        let start_offset = range.start.offset;
711        if &**start_container == node &&
712            start_offset > offset &&
713            start_offset <= offset + removed_code_units
714        {
715            range.start.offset = offset;
716            self.selection_boundaries_changed();
717        }
718        // Step 9: For each live range whose end node is node and end offset is
719        // greater than offset but less than or equal to offset + count: set its end
720        // offset to offset.
721        let end_container = &range.end.container;
722        let end_offset = range.end.offset;
723        if &**end_container == node &&
724            end_offset > offset &&
725            end_offset <= offset + removed_code_units
726        {
727            range.end.offset = offset;
728            self.selection_boundaries_changed();
729        }
730        // Step 10: For each live range whose start node is node and start offset is
731        // greater than offset + count: increase its start offset by data’s length and
732        // decrease it by count.
733        if &**start_container == node && start_offset > offset + removed_code_units {
734            range.start.offset = start_offset + added_code_units() - removed_code_units;
735            self.selection_boundaries_changed();
736        }
737        // Step 11: For each live range whose end node is node and end offset is
738        // greater than offset + count: increase its end offset by data’s length and
739        // decrease it by count.
740        if &**end_container == node && end_offset > offset + removed_code_units {
741            range.end.offset = end_offset + added_code_units() - removed_code_units;
742            self.selection_boundaries_changed();
743        }
744    }
745
746    /// <https://dom.spec.whatwg.org/#concept-text-split> steps 7.2-7.3
747    /// adapted for selections.
748    pub(crate) fn text_split_steps(
749        &self,
750        node: &Node,
751        offset: u32,
752        parent_node: &Node,
753        new_node: &Node,
754    ) {
755        let mut range_borrow = self.range.borrow_mut();
756        let Some(range) = &mut *range_borrow else {
757            return;
758        };
759        // Step 7.2: For each live range whose start node is node and start offset is
760        // greater than offset, set its start node to newNode and decrease its start
761        // offset by offset.
762        if range.start.container == node && range.start.offset > offset {
763            range.start.container = Dom::from_ref(new_node);
764            range.start.offset -= offset;
765            self.selection_boundaries_changed();
766        }
767        // Step 7.3: For each live range whose end node is node and end offset is greater
768        // than offset, set its end node to newNode and decrease its end offset by offset.
769        if range.end.container == node && range.end.offset > offset {
770            range.end.container = Dom::from_ref(new_node);
771            range.end.offset -= offset;
772            self.selection_boundaries_changed();
773        }
774        // Step 7.4: For each live range whose start node is parent and start offset is
775        // equal to the index of node plus 1, increase its start offset by 1.
776        let node_index = LazyCell::new(|| node.index());
777        if range.start.container == parent_node && range.start.offset == *node_index + 1 {
778            range.start.offset += 1;
779            self.selection_boundaries_changed();
780        }
781        // Step 7.5: For each live range whose end node is parent and end offset is equal
782        // to the index of node plus 1, increase its end offset by 1.
783        if range.end.container == parent_node && range.end.offset == *node_index + 1 {
784            range.end.offset += 1;
785            self.selection_boundaries_changed();
786        }
787    }
788
789    pub(crate) fn collapse_to_dom_position(
790        &self,
791        cx: &mut JSContext,
792        boundary: &RootedSelectionBoundary,
793    ) {
794        let _ = self.Collapse(cx, Some(&boundary.container), boundary.offset);
795    }
796
797    pub(crate) fn collapse_or_extend_to_dom_position(
798        &self,
799        cx: &mut JSContext,
800        boundary: &RootedSelectionBoundary,
801    ) {
802        let is_anchor = self
803            .composed_anchor_position()
804            .is_some_and(|anchor| anchor == *boundary);
805
806        if self.range.borrow().is_none() || is_anchor {
807            let _ = self.Collapse(cx, Some(&boundary.container), boundary.offset);
808        } else {
809            let _ = self.Extend(cx, &boundary.container, boundary.offset);
810        }
811    }
812
813    /// Call [`Selection::SetBaseAndExtent`] with the given `anchor` and `focus`
814    /// arguments. Like `SetBaseAndExtent` the selection direction is determined by the
815    /// order of `anchor` and `focus` in the DOM.
816    pub(crate) fn set_anchor_and_focus(
817        &self,
818        cx: &mut JSContext,
819        anchor: &RootedSelectionBoundary,
820        focus: &RootedSelectionBoundary,
821    ) {
822        let _ = self.SetBaseAndExtent(
823            cx,
824            &anchor.container,
825            anchor.offset,
826            &focus.container,
827            focus.offset,
828        );
829    }
830}
831
832impl SelectionMethods<crate::DomTypeHolder> for Selection {
833    /// <https://w3c.github.io/selection-api/#dom-selection-anchornode>
834    fn GetAnchorNode(&self, cx: &mut JSContext) -> Option<DomRoot<Node>> {
835        // > The attribute must return the anchor node of this, or null if the anchor is
836        // > null or anchor is not in the document tree.
837        //
838        // See <https://github.com/w3c/selection-api/issues/361> for why we don't
839        // do the document tree check (other browsers don't either).
840        self.live_anchor_node(cx)
841    }
842
843    /// <https://w3c.github.io/selection-api/#dom-selection-anchoroffset>
844    fn AnchorOffset(&self, cx: &mut JSContext) -> u32 {
845        // > The attribute must return the anchor offset of this, or 0 if the anchor is null
846        // > or anchor is not in the document tree.
847        //
848        // See <https://github.com/w3c/selection-api/issues/361> for why we don't
849        // do the document tree check (other browsers don't either).
850        self.live_anchor_offset(cx)
851    }
852
853    /// <https://w3c.github.io/selection-api/#dom-selection-focusnode>
854    fn GetFocusNode(&self, cx: &mut JSContext) -> Option<DomRoot<Node>> {
855        // > The attribute must return the focus node of this, or null if the focus is
856        // > null or focus is not in the document tree.
857        //
858        // See <https://github.com/w3c/selection-api/issues/361> for why we don't
859        // do the document tree check (other browsers don't either).
860        self.live_focus_node(cx)
861    }
862
863    /// <https://w3c.github.io/selection-api/#dom-selection-focusoffset>
864    fn FocusOffset(&self, cx: &mut JSContext) -> u32 {
865        // > The attribute must return the focus offset of this, or 0 if the focus is null
866        // > or focus is not in the document tree.
867        //
868        // See <https://github.com/w3c/selection-api/issues/361> for why we don't
869        // do the document tree check (other browsers don't either).
870        self.live_focus_offset(cx)
871    }
872
873    /// <https://w3c.github.io/selection-api/#dom-selection-iscollapsed>
874    fn IsCollapsed(&self, cx: &mut JSContext) -> bool {
875        // > The attribute must return true if and only if the anchor and focus are the
876        // > same (including if both are null). Otherwise it must return false.
877        self.active_range(cx).is_none_or(|range| range.collapsed())
878    }
879
880    /// <https://w3c.github.io/selection-api/#dom-selection-rangecount>
881    fn RangeCount(&self) -> u32 {
882        // > The attribute must return 0 if this is empty or either focus or anchor is not
883        // > in the document tree, and must return 1 otherwise.
884        //
885        // See <https://github.com/w3c/selection-api/issues/361> for why we don't
886        // do the document tree check (other browsers don't either).
887        if self.range.borrow().is_none() {
888            return 0;
889        }
890        1
891    }
892
893    /// <https://w3c.github.io/selection-api/#dom-selection-type>
894    fn Type(&self) -> DOMString {
895        // > The attribute must return "None" if this is empty or either focus or anchor
896        // > is not in the document tree, "Caret" if this's range is collapsed, and "Range"
897        // > otherwise.
898        //
899        // See <https://github.com/w3c/selection-api/issues/361> for why we don't
900        // do the document tree check (other browsers don't either).
901        let range = self.range.borrow();
902        let Some(range) = range.as_ref() else {
903            return DOMString::from_static("None");
904        };
905        if range.collapsed() {
906            DOMString::from_static("Caret")
907        } else {
908            DOMString::from_static("Range")
909        }
910    }
911
912    /// <https://w3c.github.io/selection-api/#dom-selection-direction>
913    fn Direction(&self) -> DOMString {
914        // > The attribute must return "none" if this is empty or this selection is
915        // > directionless. "forward" if this selection's direction is forwards and
916        // > "backward" if this selection's direction is backwards.
917        match self.direction.get() {
918            Direction::Directionless => DOMString::from_static("none"),
919            Direction::Forwards => DOMString::from_static("forward"),
920            Direction::Backwards => DOMString::from_static("backward"),
921        }
922    }
923
924    /// <https://w3c.github.io/selection-api/#dom-selection-getrangeat>
925    fn GetRangeAt(&self, cx: &mut JSContext, index: u32) -> Fallible<DomRoot<Range>> {
926        // > The method must throw an IndexSizeError exception if index is not 0, or if this
927        // > is empty or either focus or anchor is not in the document tree. Otherwise, it
928        // > must return a reference to (not a copy of) this's range.
929        //
930        // See <https://github.com/w3c/selection-api/issues/361> for why we don't
931        // do the document tree check (other browsers don't either).
932        if index != 0 {
933            return Err(Error::IndexSize(Some("Index must be zero".into())));
934        }
935
936        let Some(range) = self.active_range(cx) else {
937            return Err(Error::IndexSize(Some("Selection is empty".into())));
938        };
939
940        Ok(range)
941    }
942
943    /// <https://w3c.github.io/selection-api/#dom-selection-addrange>
944    fn AddRange(&self, no_gc: &NoGC, range: &Range) {
945        // Step 1. If the root of the range's boundary points are not the document
946        // associated with this, abort these steps.
947        if !self.is_in_composed_tree_of_document_and_is_not_ua_widget(&range.start_container()) {
948            return;
949        }
950
951        // Step 2. If rangeCount is not 0, abort these steps.
952        if self.RangeCount() != 0 {
953            return;
954        }
955
956        // Step 3. Set this's range to range by a strong reference (not by making a copy).
957        self.set_live_range(no_gc, Some(range));
958
959        // Are we supposed to set Direction here? w3c/selection-api#116
960        self.direction.set(Direction::Forwards);
961    }
962
963    /// <https://w3c.github.io/selection-api/#dom-selection-removerange>
964    fn RemoveRange(&self, no_gc: &NoGC, range: &Range) -> ErrorResult {
965        // > The method must make this empty by disassociating its range if this's range
966        // > is range. Otherwise, it must throw a NotFoundError.
967        if let Some(own_range) = self.live_range.get() &&
968            &*own_range == range
969        {
970            self.set_range(no_gc, None);
971            return Ok(());
972        }
973        Err(Error::NotFound(Some(
974            "Range is not the selection's range".into(),
975        )))
976    }
977
978    /// <https://w3c.github.io/selection-api/#dom-selection-removeallranges>
979    fn RemoveAllRanges(&self, no_gc: &NoGC) {
980        // > The method must make this empty by disassociating its range if this has an
981        // > associated range.
982        self.set_range(no_gc, None);
983    }
984
985    /// <https://w3c.github.io/selection-api/#dom-selection-empty>
986    fn Empty(&self, no_gc: &NoGC) {
987        // > The method must be an alias, and behave identically, to removeAllRanges().
988        self.RemoveAllRanges(no_gc);
989    }
990
991    /// <https://w3c.github.io/selection-api/#dom-selection-getcomposedranges>
992    fn GetComposedRanges(
993        &self,
994        cx: &mut JSContext,
995        options: &GetComposedRangesOptions,
996    ) -> Vec<DomRoot<StaticRange>> {
997        // Step 1. If this is empty, return an empty array.
998        let borrowed_range = self.range.borrow();
999        let Some(range) = borrowed_range.as_ref() else {
1000            return Vec::new();
1001        };
1002
1003        // Step 2. Otherwise, let startNode be start node of the range associated with
1004        // this, and let startOffset be start offset of the range.
1005        let mut start_node = range.start.container.as_rooted();
1006        let mut start_offset = range.start.offset;
1007
1008        let is_ancestor_of_provided_shadow_roots = |shadow_root: &ShadowRoot| {
1009            let shadow_root_node = shadow_root.upcast::<Node>();
1010            options.shadowRoots.iter().any(|option_shadow_root| {
1011                shadow_root_node
1012                    .is_shadow_including_inclusive_ancestor_of(option_shadow_root.upcast())
1013            })
1014        };
1015
1016        // Step 3. While startNode is a node, startNode's root is a shadow root, and
1017        // startNode's root is not a shadow-including inclusive ancestor of any of
1018        // options["shadowRoots"], repeat these steps:
1019        while let Some(containing_shadow_root) = start_node.containing_shadow_root() &&
1020            !is_ancestor_of_provided_shadow_roots(&containing_shadow_root)
1021        {
1022            // Step 3.1. Set startOffset to index of startNode's root's host.
1023            let host = DomRoot::upcast::<Node>(containing_shadow_root.Host());
1024            start_offset = host.index();
1025
1026            // Step 3.2. Set startNode to startNode's root's host's parent.
1027            // See <https://github.com/w3c/selection-api/issues/161> for why
1028            // we always know that the start_node is a node.
1029            let Some(new_start_node) = host.GetParentNode() else {
1030                return Vec::new();
1031            };
1032            start_node = new_start_node;
1033        }
1034
1035        // Step 4. Let endNode be end node of the range associated with this, and let
1036        // endOffset be end offset of the range.
1037        let mut end_node = range.end.container.as_rooted();
1038        let mut end_offset = range.end.offset;
1039
1040        // Step 5. While endNode is a node, endNode's root is a shadow root, and endNode's
1041        // root is not a shadow-including inclusive ancestor of any of
1042        // options["shadowRoots"], repeat these steps:
1043        while let Some(containing_shadow_root) = end_node.containing_shadow_root() &&
1044            !is_ancestor_of_provided_shadow_roots(&containing_shadow_root)
1045        {
1046            // Step 5.1. Set endOffset to index of endNode's root's host plus 1.
1047            let host = DomRoot::upcast::<Node>(containing_shadow_root.Host());
1048            end_offset = host.index() + 1;
1049
1050            // Step 5.2. Set endNode to endNode's root's host's parent.
1051            // See <https://github.com/w3c/selection-api/issues/161> for why
1052            // we always know that the end_node is a node.
1053            let Some(new_end_node) = host.GetParentNode() else {
1054                return Vec::new();
1055            };
1056            end_node = new_end_node;
1057        }
1058
1059        drop(borrowed_range);
1060
1061        // Step 6. Return an array consisting of new StaticRange whose start node is
1062        // startNode, start offset is startOffset, end node is endNode, and end offset is
1063        // endOffset.
1064        vec![DomRoot::from_ref(&StaticRange::new(
1065            cx,
1066            &self.document,
1067            &start_node,
1068            start_offset,
1069            &end_node,
1070            end_offset,
1071        ))]
1072    }
1073
1074    /// <https://w3c.github.io/selection-api/#dom-selection-collapse>
1075    fn Collapse(&self, cx: &mut JSContext, node: Option<&Node>, offset: u32) -> ErrorResult {
1076        // Step 1. If node is null, this method must behave identically as
1077        // removeAllRanges() and abort these steps.
1078        let Some(node) = node else {
1079            self.set_range(cx.no_gc(), None);
1080            return Ok(());
1081        };
1082
1083        // Step 2. If node is a DocumentType, throw an InvalidNodeTypeError exception and
1084        // abort these steps.
1085        if node.is_doctype() {
1086            return Err(Error::InvalidNodeType(Some("Node is a doctype".into())));
1087        }
1088
1089        // Step 3. The method must throw an IndexSizeError exception if offset is longer
1090        // than node's length and abort these steps.
1091        if offset > node.len() {
1092            return Err(Error::IndexSize(Some(
1093                "Offset is greater than the node's length".into(),
1094            )));
1095        }
1096
1097        // Step 4. If document associated with this is not a shadow-including inclusive
1098        // ancestor of node, abort these steps.
1099        if !self.is_in_composed_tree_of_document_and_is_not_ua_widget(node) {
1100            return Ok(());
1101        }
1102
1103        // Step 5. Otherwise, let newRange be a new range.
1104        // Step 6. Set the start the start and the end of newRange to (node, offset).
1105        // Step 7. Set this's range to newRange.
1106        self.set_range(
1107            cx.no_gc(),
1108            Some(SelectionRange::collapsed_at(SelectionBoundary::new(
1109                node, offset,
1110            ))),
1111        );
1112
1113        // Are we supposed to set Direction here? w3c/selection-api#116
1114        self.direction.set(Direction::Forwards);
1115
1116        Ok(())
1117    }
1118
1119    /// <https://w3c.github.io/selection-api/#dom-selection-setposition>
1120    fn SetPosition(&self, cx: &mut JSContext, node: Option<&Node>, offset: u32) -> ErrorResult {
1121        // > The method must be an alias, and behave identically, to collapse().
1122        self.Collapse(cx, node, offset)
1123    }
1124
1125    /// <https://w3c.github.io/selection-api/#dom-selection-collapsetostart>
1126    fn CollapseToStart(&self, cx: &mut JSContext) -> ErrorResult {
1127        // > The method must throw InvalidStateError exception if the this is empty.
1128        // > Otherwise, it must create a new range, set the start both its start and end to
1129        // > the start of this's range, and then set this's range to the newly-created
1130        // > range.
1131        let Some((start_container, start_offset)) = self
1132            .range
1133            .borrow()
1134            .as_ref()
1135            .map(|range| (range.start.container.as_rooted(), range.start.offset))
1136        else {
1137            return Err(Error::InvalidState(Some("Selection is empty".into())));
1138        };
1139        self.Collapse(cx, Some(&*start_container), start_offset)
1140    }
1141
1142    /// <https://w3c.github.io/selection-api/#dom-selection-collapsetoend>
1143    fn CollapseToEnd(&self, cx: &mut JSContext) -> ErrorResult {
1144        // > The method must throw InvalidStateError exception if the this is empty.
1145        // > Otherwise, it must create a new range, set the start both its start and end to
1146        // > the end of this's range, and then set this's range to the newly-created range.
1147        let Some((end_container, end_offset)) = self
1148            .range
1149            .borrow()
1150            .as_ref()
1151            .map(|range| (range.end.container.as_rooted(), range.end.offset))
1152        else {
1153            return Err(Error::InvalidState(Some("Selection is empty".into())));
1154        };
1155        self.Collapse(cx, Some(&*end_container), end_offset)
1156    }
1157
1158    /// <https://w3c.github.io/selection-api/#dom-selection-extend>
1159    fn Extend(&self, cx: &mut JSContext, node: &Node, offset: u32) -> ErrorResult {
1160        // Step 1. If the document associated with this is not a shadow-including
1161        // inclusive ancestor of node, abort these steps.
1162        if !self.is_in_composed_tree_of_document_and_is_not_ua_widget(node) {
1163            return Ok(());
1164        }
1165
1166        // Step 2. If this is empty, throw an InvalidStateError exception and abort these steps.
1167        let range_borrow = self.range.borrow();
1168        let Some(range) = range_borrow.as_ref() else {
1169            return Err(Error::InvalidState(Some("Selection is empty".into())));
1170        };
1171
1172        // This isn't specified, but it appears to be implementation behavior of other
1173        // browsers. See w3c/selection-api#118.
1174        if node.is_doctype() {
1175            return Err(Error::InvalidNodeType(Some("Node is a doctype".into())));
1176        }
1177
1178        // As with is_doctype, this is not explicit in the selection specification steps
1179        // here but implied by which exceptions are thrown in WPT tests.
1180        if offset > node.len() {
1181            return Err(Error::IndexSize(Some(
1182                "Offset is greater than the node's length".into(),
1183            )));
1184        }
1185
1186        // Step 3. Let oldAnchor and oldFocus be the this's anchor and focus, and let
1187        // newFocus be the boundary point (node, offset).
1188        //
1189        // Note: oldFocus is unused, so we do not set it here.
1190        let old_anchor = self
1191            .composed_anchor_position()
1192            .expect("has range, therefore has anchor node");
1193
1194        // Step 4. Let newRange be a new range.
1195        // Note: Set directly to satisfy crown.
1196        let direction;
1197
1198        // Step 5. If node's root is not the same as the this's range's root, set the
1199        // start newRange's start and end to newFocus.
1200        let in_different_roots = !nodes_have_same_shadow_root(&range.start.container, node);
1201        drop(range_borrow);
1202
1203        if in_different_roots {
1204            self.set_range(
1205                cx.no_gc(),
1206                Some(SelectionRange::collapsed_at(SelectionBoundary::new(
1207                    node, offset,
1208                ))),
1209            );
1210            direction = Direction::Forwards;
1211        } else {
1212            let is_old_anchor_before_or_equal = matches!(
1213                compare_shadow_including_dom_positions(
1214                    cx.no_gc(),
1215                    &old_anchor.container,
1216                    old_anchor.offset,
1217                    node,
1218                    offset
1219                ),
1220                Ordering::Less | Ordering::Equal
1221            );
1222            if is_old_anchor_before_or_equal {
1223                // Step 6. Otherwise, if oldAnchor is before or equal to newFocus, set the start
1224                // newRange's start to oldAnchor, then set its end to newFocus.
1225                self.set_range(
1226                    cx.no_gc(),
1227                    Some(SelectionRange::new(
1228                        SelectionBoundary::new(&old_anchor.container, old_anchor.offset),
1229                        SelectionBoundary::new(node, offset),
1230                    )),
1231                );
1232                direction = Direction::Forwards;
1233            } else {
1234                // Step 7. Otherwise, set the start newRange's start to newFocus, then set
1235                // its end to oldAnchor.
1236                self.set_range(
1237                    cx.no_gc(),
1238                    Some(SelectionRange::new(
1239                        SelectionBoundary::new(node, offset),
1240                        SelectionBoundary::new(&old_anchor.container, old_anchor.offset),
1241                    )),
1242                );
1243                direction = Direction::Backwards;
1244            }
1245        }
1246
1247        // Step 8. Set this's range to newRange.
1248        // Note: Done above to satisfy crown.
1249
1250        // Step 9. If newFocus is before oldAnchor, set this's direction to backwards.
1251        // Otherwise, set it to forwards.
1252        self.direction.set(direction);
1253
1254        Ok(())
1255    }
1256
1257    /// <https://w3c.github.io/selection-api/#dom-selection-setbaseandextent>
1258    fn SetBaseAndExtent(
1259        &self,
1260        cx: &mut JSContext,
1261        anchor_node: &Node,
1262        anchor_offset: u32,
1263        focus_node: &Node,
1264        focus_offset: u32,
1265    ) -> ErrorResult {
1266        // This isn't specified, but it appears to be implementation behavior of other
1267        // browsers. See w3c/selection-api#118.
1268        if anchor_node.is_doctype() || focus_node.is_doctype() {
1269            return Err(Error::InvalidNodeType(Some("Node is a doctype".into())));
1270        }
1271
1272        // Step 1. If anchorOffset is longer than anchorNode's length or if focusOffset is
1273        // longer than focusNode's length, throw an IndexSizeError exception and abort
1274        // these steps.
1275        if anchor_offset > anchor_node.len() || focus_offset > focus_node.len() {
1276            return Err(Error::IndexSize(Some(
1277                "Offset is greater than the node's length".into(),
1278            )));
1279        }
1280
1281        // Step 2. If document associated with this is not a shadow-including inclusive
1282        // ancestor of anchorNode or focusNode, abort these steps.
1283        if !self.is_in_composed_tree_of_document_and_is_not_ua_widget(anchor_node) ||
1284            !self.is_in_composed_tree_of_document_and_is_not_ua_widget(focus_node)
1285        {
1286            return Ok(());
1287        }
1288
1289        // Step 3. Let anchor be the boundary point (anchorNode, anchorOffset) and let
1290        // focus be the boundary point (focusNode, focusOffset).
1291        //
1292        // Note: We do not model the boundary point in this way.
1293
1294        // Step 4. Let newRange be a new range.
1295        // Note: We set the range directly to satisfy crown.
1296
1297        // Step 5. If anchor is before focus, set the start the newRange's start to anchor
1298        // and its end to focus. Otherwise, set the start them to focus and anchor
1299        // respectively.
1300        let ordering = compare_shadow_including_dom_positions(
1301            cx.no_gc(),
1302            anchor_node,
1303            anchor_offset,
1304            focus_node,
1305            focus_offset,
1306        );
1307        if ordering == Ordering::Less {
1308            self.set_range(
1309                cx.no_gc(),
1310                Some(SelectionRange::new(
1311                    SelectionBoundary::new(anchor_node, anchor_offset),
1312                    SelectionBoundary::new(focus_node, focus_offset),
1313                )),
1314            );
1315        } else {
1316            self.set_range(
1317                cx.no_gc(),
1318                Some(SelectionRange::new(
1319                    SelectionBoundary::new(focus_node, focus_offset),
1320                    SelectionBoundary::new(anchor_node, anchor_offset),
1321                )),
1322            );
1323        };
1324
1325        // Step 6. Set this's range to newRange.
1326        // Note: Done above to satisfy crown.
1327
1328        // Step 7. If focus is before anchor, set this's direction to backwards.
1329        // Otherwise, set it to forwards
1330        if ordering == Ordering::Greater {
1331            self.direction.set(Direction::Backwards);
1332        } else {
1333            self.direction.set(Direction::Forwards);
1334        }
1335
1336        Ok(())
1337    }
1338
1339    /// <https://w3c.github.io/selection-api/#dom-selection-selectallchildren>
1340    fn SelectAllChildren(&self, cx: &mut JSContext, node: &Node) -> ErrorResult {
1341        // Step 1. If node is a DocumentType, throw an InvalidNodeTypeError exception and
1342        // abort these steps.
1343        if node.is_doctype() {
1344            return Err(Error::InvalidNodeType(Some("Node is a doctype".into())));
1345        }
1346
1347        // Step 2. If node's root is not the document associated with this, abort these
1348        // steps.
1349        if !self.is_in_composed_tree_of_document_and_is_not_ua_widget(node) {
1350            return Ok(());
1351        }
1352
1353        // Let newRange be a new range and childCount be the number of children of node.
1354        let child_count = node.children_count();
1355
1356        // Step 4. Set newRange's start to (node, 0).
1357        // Step 5. Set newRange's end to (node, childCount).
1358        // Step 6. Set this's range to newRange.
1359        self.set_range(
1360            cx.no_gc(),
1361            Some(SelectionRange::new(
1362                SelectionBoundary::new(node, 0),
1363                SelectionBoundary::new(node, child_count),
1364            )),
1365        );
1366
1367        // Step 7. Set this's direction to forwards.
1368        self.direction.set(Direction::Forwards);
1369
1370        Ok(())
1371    }
1372
1373    /// <https://w3c.github.io/selection-api/#dom-selection-deletecontents>
1374    fn DeleteFromDocument(&self, cx: &mut JSContext) -> ErrorResult {
1375        // > The method must invoke deleteContents() on this's range if this is not empty
1376        // > and both focus and anchor are in the document tree. Otherwise the method must
1377        // > do nothing.
1378        let Some(active_range) = self
1379            .active_range(cx)
1380            .filter(|range| range.start_and_end_are_in_document_tree())
1381        else {
1382            return Ok(());
1383        };
1384
1385        active_range.DeleteContents(cx)
1386    }
1387
1388    /// <https://w3c.github.io/selection-api/#dom-selection-containsnode>
1389    fn ContainsNode(&self, no_gc: &NoGC, node: &Node, allow_partial_containment: bool) -> bool {
1390        // > The method must return false if this is empty or if node's root is not the document
1391        // > associated with this.
1392        // >
1393        // > Otherwise, if allowPartialContainment is false, the method must return true if and only
1394        // > if start of its range is before or visually equivalent to the first boundary point in
1395        // > the node *and* end of its range is after or visually equivalent to the last boundary
1396        // > point in the node.
1397        // >
1398        // > If allowPartialContainment is true, the method must return true if and only if start of
1399        // > its range is before or visually equivalent to the last boundary point in the node *and*
1400        // > end of its range is after or visually equivalent to the first boundary point in the
1401        // > node.
1402        if !self.is_in_composed_tree_of_document_and_is_not_ua_widget(node) {
1403            return false;
1404        }
1405        let range = self.range.borrow();
1406        let Some(range) = range.as_ref() else {
1407            return false;
1408        };
1409        let start_node = &*range.start.container;
1410        if !self.is_in_composed_tree_of_document_and_is_not_ua_widget(start_node) {
1411            return false;
1412        }
1413        let end_node = &*range.end.container;
1414
1415        let first_offset = 0;
1416        let last_offset = node.len();
1417        let (compare_start_to, compare_end_to) = if allow_partial_containment {
1418            (last_offset, first_offset)
1419        } else {
1420            (first_offset, last_offset)
1421        };
1422
1423        // TODO: find out what "visually equivalent" means for boundary points and implement it.
1424        // https://github.com/w3c/selection-api/issues/6
1425        //
1426        // For now it is simplified to "node is in the flat tree" and "position is equal".
1427        if !node.is_in_flat_tree(no_gc) {
1428            return false;
1429        }
1430
1431        matches!(
1432            compare_shadow_including_dom_positions(
1433                no_gc,
1434                start_node,
1435                range.start.offset,
1436                node,
1437                compare_start_to
1438            ),
1439            Ordering::Less | Ordering::Equal
1440        ) && matches!(
1441            compare_shadow_including_dom_positions(
1442                no_gc,
1443                end_node,
1444                range.end.offset,
1445                node,
1446                compare_end_to
1447            ),
1448            Ordering::Greater | Ordering::Equal
1449        )
1450    }
1451
1452    /// <https://w3c.github.io/selection-api/#dom-selection-stringifier>
1453    fn Stringifier(&self, cx: &mut JSContext) -> DOMString {
1454        // Flush all layout before stringifying so that rendered text is up-to-date.
1455        self.document
1456            .window()
1457            .layout_reflow(cx, QueryMsg::StyleQuery);
1458
1459        // > The stringification must return the string, which is the concatenation of the
1460        // > rendered text if there is a range associated with this.
1461        // >
1462        // > If the selection is within a textarea or input element, it must return the
1463        // > selected substring in its value.
1464        let Some(visible_selection) =
1465            FlatTreeSelection::from_selection_if_renderable(cx.no_gc(), self)
1466        else {
1467            return DOMString::new();
1468        };
1469
1470        let mut user_select_cache = Default::default();
1471        let mut string = DOMString::new();
1472        for node in visible_selection.traversal() {
1473            let Some(character_data) = node.downcast::<CharacterData>() else {
1474                continue;
1475            };
1476
1477            if node.used_user_select(cx.no_gc(), &mut user_select_cache) == UsedUserSelect::None {
1478                continue;
1479            }
1480
1481            let range = visible_selection.range_for_character_data(character_data);
1482            let Some(text) = character_data.rendered_text(range) else {
1483                continue;
1484            };
1485            string.push_str(&text);
1486        }
1487
1488        string
1489    }
1490}
1491
1492impl<'dom> LayoutDom<'dom, Selection> {
1493    pub(crate) fn range_for_layout(&self) -> Option<AtomicRef<'dom, SelectionRange>> {
1494        AtomicRef::filter_map(self.unsafe_get().visible_range.borrow(), Option::as_ref)
1495    }
1496
1497    pub(crate) fn paints_caret_for_layout(&self) -> bool {
1498        self.unsafe_get().paints_caret.get()
1499    }
1500}
1501
1502enum FlatTreeNodePosition {
1503    Before(DomRoot<Node>),
1504    Inside(DomRoot<Node>),
1505    After(DomRoot<Node>),
1506}
1507
1508impl FlatTreeNodePosition {
1509    fn node(&self) -> &Node {
1510        match self {
1511            FlatTreeNodePosition::Before(node) => node,
1512            FlatTreeNodePosition::Inside(node) => node,
1513            FlatTreeNodePosition::After(node) => node,
1514        }
1515    }
1516}
1517
1518/// Find the position of a node and offset in the flat tree for the purposes of selection
1519/// boundaries. This projects the given position onto the flat tree, accounting for origin
1520/// nodes that may not actually be in the flat tree at all.
1521fn position_in_flat_tree_for_selection(
1522    no_gc: &NoGC,
1523    boundary: &FlatTreeBoundary,
1524) -> FlatTreeNodePosition {
1525    if boundary.container.is::<CharacterData>() {
1526        return FlatTreeNodePosition::Inside(boundary.container.as_rooted());
1527    }
1528
1529    let shadow_host_or_node = |node: &Node| {
1530        boundary
1531            .container
1532            .downcast::<ShadowRoot>()
1533            .map(|shadow_root| DomRoot::upcast(shadow_root.Host()))
1534            .unwrap_or(DomRoot::from_ref(node))
1535    };
1536
1537    if let Some(child) = boundary.container.children().nth(boundary.offset as usize) {
1538        if let FlatTreeParent::Parent(_) = child.parent_in_flat_tree(no_gc) {
1539            return FlatTreeNodePosition::Before(child);
1540        }
1541    } else if let Some(last_child) = boundary.container.GetLastChild() &&
1542        let FlatTreeParent::Parent(_) = last_child.parent_in_flat_tree(no_gc)
1543    {
1544        return FlatTreeNodePosition::After(shadow_host_or_node(&boundary.container.as_rooted()));
1545    }
1546
1547    // The container has no child in the flat tree or the child indicated by the index
1548    // isn't in the flat tree, so just return a position inside that container.
1549    FlatTreeNodePosition::Inside(shadow_host_or_node(&boundary.container.as_rooted()))
1550}
1551
1552impl Node {
1553    /// Get the `Utf16CodeUnits` offset for the given offset if `self` is a
1554    /// `CharacterData` or else return the offset in the child list.
1555    pub(crate) fn to_sibling_or_utf16_offset(&self, offset: Utf32CodeUnitsOrNodeOffset) -> u32 {
1556        if let Some(character_data) = self.downcast::<CharacterData>() {
1557            // TODO: ensure that each `CharacterData` holds no more than 4 GiB?
1558            offset
1559                .to_utf16_code_units_in(AssumeUnder4GB, &character_data.data())
1560                .0
1561        } else {
1562            offset.0
1563        }
1564    }
1565
1566    /// Get the `Utf32CodeUnitsOrNodeOffset` for `self` and the given UTF-16 offset if
1567    /// `self` is `CharacterData` or else return the offset in the child list.
1568    pub(crate) fn to_sibling_or_utf32_offset(&self, offset: u32) -> Utf32CodeUnitsOrNodeOffset {
1569        Utf32CodeUnitsOrNodeOffset(
1570            if let Some(character_data) = self.downcast::<CharacterData>() {
1571                // TODO: ensure that each `CharacterData` holds no more than 4 GiB?
1572                Utf16CodeUnits(offset)
1573                    .to_utf32_code_units_in(&character_data.data())
1574                    .0
1575            } else {
1576                offset
1577            },
1578        )
1579    }
1580}
1581
1582bitflags! {
1583    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1584    pub(crate) struct SelectionLiveRangeNotification: u8 {
1585        const Start = 1 << 0;
1586        const End = 1 << 1;
1587    }
1588}
1589
1590fn nodes_have_same_shadow_root(a: &Node, b: &Node) -> bool {
1591    a.is_connected() && b.is_connected() && a.containing_shadow_root() == b.containing_shadow_root()
1592}
1593
1594/// Project the position given by `container_a` and `offset_a` into a root that also
1595/// contains `target`. If `target` is not supplied then project the position into the
1596/// `Document` root.
1597///
1598/// This does something very similar to GetComposedRanges, but doesn't have special
1599/// handling for start and end nodes.
1600fn project_into_shared_tree<'a>(
1601    no_gc: &'a NoGC,
1602    container_a: &Node,
1603    mut offset_a: u32,
1604    target: Option<&Node>,
1605) -> (UnrootedDom<'a, Node>, u32) {
1606    let mut start_node = UnrootedDom::from_ref(container_a, no_gc);
1607    while let Some(containing_shadow_root) = start_node.containing_shadow_root_unrooted(no_gc) &&
1608        target.is_none_or(|target| {
1609            !containing_shadow_root
1610                .upcast::<Node>()
1611                .is_shadow_including_inclusive_ancestor_of(target)
1612        })
1613    {
1614        let host = DomRoot::upcast::<Node>(containing_shadow_root.Host());
1615        offset_a = host.index();
1616        start_node = host
1617            .get_parent_node_unrooted(no_gc)
1618            .expect("Should only be called on nodes in the same tree");
1619    }
1620
1621    (start_node, offset_a)
1622}
1623
1624/// Compare two shadow-including DOM positions by first projecting them into
1625/// a shared root and then comparing the two positions. This function assumes
1626/// that the two positions share a [`Document`].
1627pub(crate) fn compare_shadow_including_dom_positions(
1628    no_gc: &NoGC,
1629    container_a: &Node,
1630    offset_a: u32,
1631    container_b: &Node,
1632    offset_b: u32,
1633) -> Ordering {
1634    let (projected_container_a, projected_offset_a) =
1635        project_into_shared_tree(no_gc, container_a, offset_a, Some(container_b));
1636    let (projected_container_b, projected_offset_b) =
1637        project_into_shared_tree(no_gc, container_b, offset_b, Some(container_a));
1638
1639    let a_was_projected = &**projected_container_a != container_a;
1640    let b_was_projected = &**projected_container_b != container_b;
1641
1642    match bp_position(
1643        no_gc,
1644        &projected_container_a,
1645        projected_offset_a,
1646        &projected_container_b,
1647        projected_offset_b,
1648    ) {
1649        Ordering::Equal if a_was_projected && !b_was_projected => Ordering::Greater,
1650        Ordering::Equal if !a_was_projected && b_was_projected => Ordering::Less,
1651        ordering => ordering,
1652    }
1653}
1654
1655struct FlatTreeBoundary<'no_gc> {
1656    container: UnrootedDom<'no_gc, Node>,
1657    offset: u32,
1658}
1659
1660struct FlatTreeSelection<'no_gc> {
1661    no_gc: &'no_gc NoGC,
1662    start: FlatTreeBoundary<'no_gc>,
1663    end: FlatTreeBoundary<'no_gc>,
1664}
1665
1666impl<'no_gc> FlatTreeSelection<'no_gc> {
1667    /// Get the [`FlatTreeSelection`] for this [`Selection`], returning `None` if the [`Selection`]
1668    /// doesn't have a range or if that flat tree range is unrenderable (for instance, because one
1669    /// or both of the endpoints is not in the flat tree).
1670    fn from_selection_if_renderable(no_gc: &'no_gc NoGC, selection: &Selection) -> Option<Self> {
1671        let range = selection.range.borrow();
1672        let range = range.as_ref()?;
1673
1674        let mut start_container = range.start.container.as_unrooted(no_gc);
1675        let mut start_offset = range.start.offset;
1676        let mut end_container = range.end.container.as_unrooted(no_gc);
1677        let mut end_offset = range.end.offset;
1678
1679        if !start_container.is_in_flat_tree(no_gc) {
1680            return None;
1681        }
1682        if !end_container.is_in_flat_tree(no_gc) {
1683            return None;
1684        }
1685
1686        // Compare the position of the two nodes in the flat tree, considering the
1687        // condition when they don't share a common ancestor to be an unrenderable
1688        // selection.
1689        let ordering = compare_dom_positions::<FlatTreeForSelectionNoGcTraversal>(
1690            no_gc,
1691            &range.start.container,
1692            range.start.offset,
1693            &range.end.container,
1694            range.end.offset,
1695        )
1696        .0?;
1697
1698        // If the visible selection is inverted relative to the composed tree range, swap
1699        // the boundaries.
1700        if ordering == Ordering::Greater {
1701            std::mem::swap(&mut start_container, &mut end_container);
1702            std::mem::swap(&mut start_offset, &mut end_offset);
1703        }
1704
1705        Some(FlatTreeSelection {
1706            no_gc,
1707            start: FlatTreeBoundary {
1708                container: start_container,
1709                offset: start_offset,
1710            },
1711            end: FlatTreeBoundary {
1712                container: end_container,
1713                offset: end_offset,
1714            },
1715        })
1716    }
1717
1718    fn is_collapsed(&self) -> bool {
1719        self.start.container == self.end.container && self.start.offset == self.end.offset
1720    }
1721
1722    fn range_for_character_data(&self, character_data: &CharacterData) -> RangeAny<Utf32CodeUnits> {
1723        let text = character_data.data();
1724        let node: &Node = character_data.upcast();
1725        RangeAny::new(
1726            (node == &**self.start.container)
1727                .then(|| Utf16CodeUnits(self.start.offset).to_utf32_code_units_in(&text)),
1728            (node == &**self.end.container)
1729                .then(|| Utf16CodeUnits(self.end.offset).to_utf32_code_units_in(&text)),
1730        )
1731    }
1732
1733    fn traversal(&self) -> VisibleSelectionTraversal<'no_gc> {
1734        let start_position = position_in_flat_tree_for_selection(self.no_gc, &self.start);
1735        let end_position = position_in_flat_tree_for_selection(self.no_gc, &self.end);
1736        VisibleSelectionTraversal {
1737            following: start_position
1738                .node()
1739                .following_flat_tree_nodes_unrooted(self.no_gc),
1740            start: start_position,
1741            end: end_position,
1742            finished: false,
1743            skip_subtree: false,
1744        }
1745    }
1746}
1747
1748struct VisibleSelectionTraversal<'no_gc> {
1749    following: UnrootedFollowingFlatTreeNodesTraversal<'no_gc>,
1750    start: FlatTreeNodePosition,
1751    end: FlatTreeNodePosition,
1752    finished: bool,
1753    skip_subtree: bool,
1754}
1755
1756impl<'no_gc> Iterator for VisibleSelectionTraversal<'no_gc> {
1757    type Item = UnrootedDom<'no_gc, Node>;
1758
1759    fn next(&mut self) -> Option<Self::Item> {
1760        while !self.finished {
1761            let following = if std::mem::take(&mut self.skip_subtree) {
1762                self.following.next_skipping_subtree()?
1763            } else {
1764                self.following.next()?
1765            };
1766
1767            match following {
1768                PrePostIteration::Enter(node) => {
1769                    // If the traversal ends right before the final node and this is the
1770                    // final node, just finish now.
1771                    if &**node == self.end.node() &&
1772                        matches!(self.end, FlatTreeNodePosition::Before(_))
1773                    {
1774                        self.finished = true;
1775                        break;
1776                    }
1777                    // If the selection starts after the first node, do not set any flags
1778                    // on that nodes descendants.
1779                    if &**node == self.start.node() &&
1780                        matches!(self.start, FlatTreeNodePosition::After(_))
1781                    {
1782                        self.skip_subtree = true;
1783                    }
1784
1785                    if let Some(element) = node.downcast::<Element>() &&
1786                        let Some(shadow_root) = element.shadow_root() &&
1787                        shadow_root.is_user_agent_widget()
1788                    {
1789                        self.skip_subtree = true;
1790                    }
1791                    return Some(node);
1792                },
1793                PrePostIteration::Leave(node) => {
1794                    self.finished = &**node == self.end.node();
1795                },
1796            }
1797        }
1798
1799        None
1800    }
1801}
1802
1803struct VisibleSelectionFlagUpdate<'no_gc> {
1804    no_gc: &'no_gc NoGC,
1805    /// The nodes that previously had the OVERLAPS_DOCUMENT_SELECTION set on them before
1806    /// this flag update.
1807    ///
1808    /// Hash keys are pointer addresses which are not directly controlled by web content
1809    /// so we don’t need HashDoS resistance and can use a faster hasher than `std`’s default
1810    previously_flagged_nodes: FxHashSet<UnrootedDom<'no_gc, Node>>,
1811    /// Cache shared between calls to [`Node::used_user_select`]
1812    used_user_select_cache: FxHashMap<UnrootedDom<'no_gc, Node>, UsedUserSelect>,
1813    /// Whether or not this update requires a display list update.
1814    needs_new_display_list: bool,
1815    /// Whether or not the caret needs to be painted for the visible selection.
1816    paints_caret: bool,
1817}
1818
1819impl<'no_gc> VisibleSelectionFlagUpdate<'no_gc> {
1820    fn run(
1821        no_gc: &'no_gc NoGC,
1822        previously_flagged_nodes: FxHashSet<UnrootedDom<'no_gc, Node>>,
1823        flat_tree_selection: Option<&FlatTreeSelection<'_>>,
1824        document: &Document,
1825        paints_caret: bool,
1826    ) {
1827        let mut update = Self {
1828            no_gc,
1829            previously_flagged_nodes,
1830            used_user_select_cache: Default::default(),
1831            needs_new_display_list: false,
1832            paints_caret,
1833        };
1834
1835        if let Some(flat_tree_selection) = flat_tree_selection {
1836            let traversal = flat_tree_selection.traversal();
1837            for ancestor in traversal
1838                .start
1839                .node()
1840                .ancestors_in_flat_tree_unrooted(no_gc)
1841            {
1842                update.set(&ancestor, flat_tree_selection);
1843            }
1844            for node in traversal {
1845                update.set(&node, flat_tree_selection);
1846            }
1847        }
1848
1849        update.finish(document);
1850    }
1851
1852    fn set(&mut self, node: &UnrootedDom<'no_gc, Node>, flat_tree_selection: &FlatTreeSelection) {
1853        if !node.get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION) {
1854            node.set_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION, true);
1855            debug_assert!(!self.previously_flagged_nodes.contains(node));
1856        } else {
1857            self.previously_flagged_nodes.remove(node);
1858        }
1859
1860        // TODO: We should ensure that the style is up-to-date before reading the
1861        // `user-select` property and changes to `user-select` should trigger new visual
1862        // selection updates. Not doing this means that the calculations here are one
1863        // layout old and are never run again until the selection changes.
1864        let user_select = node.used_user_select(self.no_gc, &mut self.used_user_select_cache);
1865        let inhibited = user_select == UsedUserSelect::None;
1866        node.set_flag(NodeFlags::SELECTION_INHIBITED, inhibited);
1867
1868        self.set_node_selection(node, (!inhibited).then_some(flat_tree_selection));
1869    }
1870
1871    fn clear(&mut self, node: &Node) {
1872        node.set_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION, false);
1873        node.set_flag(NodeFlags::SELECTION_INHIBITED, false);
1874        self.set_node_selection(node, None);
1875    }
1876
1877    fn set_character_data_selection(
1878        &mut self,
1879        character_data: &CharacterData,
1880        range: Option<RangeAny<Utf32CodeUnits>>,
1881    ) {
1882        if character_data.set_text_run_selection(range, self.paints_caret) {
1883            self.needs_new_display_list = true;
1884        } else {
1885            // Note: This isn't just necessary when the `CharacterData` doesn't have a
1886            // corresponding box tree node, but *also* for properly handling `:first-letter`
1887            // at the moment. This cannot be removed until `:first-letter` is represented
1888            // properly in the box tree.
1889            character_data
1890                .upcast::<Node>()
1891                .dirty(self.no_gc, NodeDamage::ContentOrHeritage);
1892        }
1893    }
1894
1895    fn set_node_selection(&mut self, node: &Node, flat_tree_selection: Option<&FlatTreeSelection>) {
1896        if let Some(character_data) = node.downcast::<CharacterData>() {
1897            let range = flat_tree_selection.map(|flat_tree_selection| {
1898                flat_tree_selection.range_for_character_data(character_data)
1899            });
1900            self.set_character_data_selection(character_data, range);
1901        } else if node.set_element_selection(
1902            flat_tree_selection.is_some_and(|selection| !selection.is_collapsed()),
1903        ) {
1904            self.needs_new_display_list = true;
1905        }
1906    }
1907
1908    fn finish(mut self, document: &Document) {
1909        for node in std::mem::take(&mut self.previously_flagged_nodes) {
1910            self.clear(&node);
1911        }
1912        if self.needs_new_display_list {
1913            document.window().layout().set_needs_new_display_list();
1914        }
1915    }
1916}