Skip to main content

script/dom/range/
range.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::LazyCell;
6use std::cmp::Ordering;
7use std::iter;
8use std::rc::Rc;
9
10use app_units::Au;
11use dom_struct::dom_struct;
12use euclid::Rect;
13use js::context::{JSContext, NoGC};
14use js::jsapi::JSTracer;
15use js::rust::HandleObject;
16use script_bindings::cell::DomRefCell;
17use script_bindings::dom::{MutDom, UnrootedDom};
18use script_bindings::reflector::reflect_weak_referenceable_dom_object_with_proto;
19use smallvec::SmallVec;
20use style_traits::CSSPixel;
21
22use crate::dom::abstractrange::{AbstractRange, BoundaryPoint, bp_position};
23use crate::dom::bindings::codegen::Bindings::AbstractRangeBinding::AbstractRangeMethods;
24use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
25use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
26use crate::dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
27use crate::dom::bindings::codegen::Bindings::RangeBinding::{RangeConstants, RangeMethods};
28use crate::dom::bindings::codegen::Bindings::TextBinding::TextMethods;
29use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
30use crate::dom::bindings::codegen::UnionTypes::TrustedHTMLOrString;
31use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
32use crate::dom::bindings::inheritance::{Castable, CharacterDataTypeId, NodeTypeId};
33use crate::dom::bindings::root::{Dom, DomRoot};
34use crate::dom::bindings::str::DOMString;
35use crate::dom::bindings::trace::JSTraceable;
36use crate::dom::bindings::weakref::{WeakRef, WeakRefVec};
37use crate::dom::characterdata::CharacterData;
38use crate::dom::document::Document;
39use crate::dom::documentfragment::DocumentFragment;
40use crate::dom::domrect::DOMRect;
41use crate::dom::domrectlist::DOMRectList;
42use crate::dom::element::Element;
43use crate::dom::html::htmlscriptelement::HTMLScriptElement;
44use crate::dom::iterators::ShadowIncluding;
45use crate::dom::node::{Node, NodeTraits};
46use crate::dom::selection::{Selection, SelectionLiveRangeNotification};
47use crate::dom::text::Text;
48use crate::dom::trustedtypes::trustedhtml::TrustedHTML;
49use crate::dom::window::Window;
50
51#[dom_struct]
52pub(crate) struct Range {
53    abstract_range: AbstractRange,
54    /// The [`Document`] that this range belongs to i.e. the owner [`Document`]
55    /// of its two nodes. [`Range`] is written to ensure that both ends share
56    /// a root, so this should always be the same for both ends.
57    document: MutDom<Document>,
58    // A range that belongs to a Selection needs to know about it
59    // so selectionchange can fire when the range changes.
60    // A range shouldn't belong to more than one Selection at a time,
61    // but from the spec as of Feb 1 2020 I can't rule out a corner case like:
62    // * Select a range R in document A, from node X to Y
63    // * Insert everything from X to Y into document B
64    // * Set B's selection's range to R
65    // which leaves R technically, and observably, associated with A even though
66    // it will fail the same-root-node check on many of A's selection's methods.
67    associated_selections: DomRefCell<Vec<Dom<Selection>>>,
68}
69
70pub(crate) struct ContainedChildren {
71    pub(crate) first_partially_contained_child: Option<DomRoot<Node>>,
72    pub(crate) last_partially_contained_child: Option<DomRoot<Node>>,
73    pub(crate) contained_children: Vec<DomRoot<Node>>,
74}
75
76impl Range {
77    fn new_inherited(
78        start_container: &Node,
79        start_offset: u32,
80        end_container: &Node,
81        end_offset: u32,
82        start_container_document: &Document,
83    ) -> Self {
84        debug_assert!(start_offset <= start_container.len());
85        debug_assert!(end_offset <= end_container.len());
86        Self {
87            abstract_range: AbstractRange::new_inherited(
88                start_container,
89                start_offset,
90                end_container,
91                end_offset,
92            ),
93            document: MutDom::new(start_container_document),
94            associated_selections: DomRefCell::new(vec![]),
95        }
96    }
97
98    pub(crate) fn new_with_doc(
99        cx: &mut JSContext,
100        document: &Document,
101        proto: Option<HandleObject>,
102    ) -> DomRoot<Self> {
103        let root = document.upcast();
104        Self::new_with_proto(cx, document, proto, root, 0, root, 0)
105    }
106
107    pub(crate) fn new(
108        cx: &mut JSContext,
109        document: &Document,
110        start_container: &Node,
111        start_offset: u32,
112        end_container: &Node,
113        end_offset: u32,
114    ) -> DomRoot<Range> {
115        Self::new_with_proto(
116            cx,
117            document,
118            None,
119            start_container,
120            start_offset,
121            end_container,
122            end_offset,
123        )
124    }
125
126    fn new_with_proto(
127        cx: &mut JSContext,
128        document_to_reflect_into: &Document,
129        proto: Option<HandleObject>,
130        start_container: &Node,
131        start_offset: u32,
132        end_container: &Node,
133        end_offset: u32,
134    ) -> DomRoot<Range> {
135        let start_container_document = start_container.owner_document();
136        let range = reflect_weak_referenceable_dom_object_with_proto(
137            cx,
138            Rc::new(Self::new_inherited(
139                start_container,
140                start_offset,
141                end_container,
142                end_offset,
143                &start_container_document,
144            )),
145            document_to_reflect_into.window(),
146            proto,
147        );
148
149        start_container_document
150            .live_ranges()
151            .push(WeakRef::new(&range));
152
153        range
154    }
155
156    /// <https://dom.spec.whatwg.org/#concept-range-root>
157    ///
158    /// > The root of a live range is the root of its start node.
159    pub(crate) fn root(&self) -> DomRoot<Node> {
160        self.start_container().GetRootNode(&Default::default())
161    }
162
163    /// <https://dom.spec.whatwg.org/#contained>
164    pub(crate) fn contains(&self, no_gc: &NoGC, node: &Node) -> bool {
165        // > A node node is contained in a live range range if node’s root is range’s root,
166        // > and (node, 0) is after range’s start, and (node, node’s length) is before range’s end.
167        node.GetRootNode(&Default::default()) == self.root() &&
168            matches!(
169                (
170                    bp_position(no_gc, node, 0, &self.start_container(), self.start_offset()),
171                    bp_position(
172                        no_gc,
173                        node,
174                        node.len(),
175                        &self.end_container(),
176                        self.end_offset()
177                    ),
178                ),
179                (Ordering::Greater, Ordering::Less)
180            )
181    }
182
183    /// <https://dom.spec.whatwg.org/#partially-contained>
184    fn partially_contains(&self, node: &Node) -> bool {
185        // > A node is partially contained in a live range if it’s an inclusive ancestor
186        // > of the live range’s start node but not its end node, or vice versa.
187        self.start_container()
188            .inclusive_ancestors(ShadowIncluding::No)
189            .any(|n| &*n == node) !=
190            self.end_container()
191                .inclusive_ancestors(ShadowIncluding::No)
192                .any(|n| &*n == node)
193    }
194
195    /// <https://dom.spec.whatwg.org/#concept-range-clone>
196    pub(crate) fn contained_children(&self, no_gc: &NoGC) -> Fallible<ContainedChildren> {
197        let start_node = self.start_container();
198        let end_node = self.end_container();
199        // Steps 5-6.
200        let common_ancestor = self.CommonAncestorContainer();
201
202        let first_partially_contained_child = if start_node.is_inclusive_ancestor_of(&end_node) {
203            // Step 7.
204            None
205        } else {
206            // Step 8.
207            common_ancestor
208                .children()
209                .find(|node| Range::partially_contains(self, node))
210        };
211
212        let last_partially_contained_child = if end_node.is_inclusive_ancestor_of(&start_node) {
213            // Step 9.
214            None
215        } else {
216            // Step 10.
217            common_ancestor
218                .rev_children()
219                .find(|node| Range::partially_contains(self, node))
220        };
221
222        // Step 11.
223        let contained_children: Vec<DomRoot<Node>> = common_ancestor
224            .children()
225            .filter(|n| self.contains(no_gc, n))
226            .collect();
227
228        // Step 12.
229        if contained_children.iter().any(|n| n.is_doctype()) {
230            return Err(Error::HierarchyRequest(Some(
231                "Range contains a doctype node".into(),
232            )));
233        }
234
235        Ok(ContainedChildren {
236            first_partially_contained_child,
237            last_partially_contained_child,
238            contained_children,
239        })
240    }
241
242    /// <https://dom.spec.whatwg.org/#concept-range-bp-set>
243    pub(crate) fn set_start(&self, no_gc: &NoGC, node: &Node, offset: u32) {
244        if self.set_start_without_reporting(node, offset) {
245            self.report_change(no_gc, SelectionLiveRangeNotification::Start);
246        }
247    }
248
249    pub(crate) fn set_start_without_reporting(&self, node: &Node, offset: u32) -> bool {
250        if self.start().node() == node && self.start_offset() == offset {
251            return false;
252        }
253        self.start().set(node, offset);
254        true
255    }
256
257    /// <https://dom.spec.whatwg.org/#concept-range-bp-set>
258    pub(crate) fn set_end(&self, no_gc: &NoGC, node: &Node, offset: u32) {
259        if self.set_end_without_reporting(node, offset) {
260            self.report_change(no_gc, SelectionLiveRangeNotification::End);
261        }
262    }
263
264    pub(crate) fn set_end_without_reporting(&self, node: &Node, offset: u32) -> bool {
265        if self.end().node() == node && self.end_offset() == offset {
266            return false;
267        }
268        self.end().set(node, offset);
269        true
270    }
271
272    /// <https://dom.spec.whatwg.org/#dom-range-comparepointnode-offset>
273    fn compare_point(&self, no_gc: &NoGC, node: &Node, offset: u32) -> Fallible<Ordering> {
274        // Step 1. If node’s root is not this’s root, then throw a "WrongDocumentError"
275        // DOMException.
276        if node.GetRootNode(&Default::default()) != self.root() {
277            return Err(Error::WrongDocument(Some(
278                "Node is not in the same tree as the range".into(),
279            )));
280        }
281        // Step 2. If node is a doctype, then throw an "InvalidNodeTypeError"
282        // DOMException.
283        if node.is_doctype() {
284            return Err(Error::InvalidNodeType(Some("Node is a doctype".into())));
285        }
286        // Step 3. If offset is greater than node’s length, then throw an "IndexSizeError"
287        // DOMException.
288        if offset > node.len() {
289            return Err(Error::IndexSize(Some(
290                "Offset is greater than the node's length".into(),
291            )));
292        }
293        // Step 4. If (node, offset) is before start, then return −1.
294        let start_node = self.start_container();
295        if let Ordering::Less = bp_position(no_gc, node, offset, &start_node, self.start_offset()) {
296            return Ok(Ordering::Less);
297        }
298        // Step 5. If (node, offset) is after end, then return 1.
299        if let Ordering::Greater = bp_position(
300            no_gc,
301            node,
302            offset,
303            &self.end_container(),
304            self.end_offset(),
305        ) {
306            return Ok(Ordering::Greater);
307        }
308        // Step 6. Return 0.
309        Ok(Ordering::Equal)
310    }
311
312    pub(crate) fn associate_selection(&self, selection: &Selection) {
313        let mut selections = self.associated_selections.borrow_mut();
314        if !selections.iter().any(|s| &**s == selection) {
315            selections.push(Dom::from_ref(selection));
316        }
317    }
318
319    pub(crate) fn disassociate_selection(&self, selection: &Selection) {
320        self.associated_selections
321            .borrow_mut()
322            .retain(|s| &**s != selection);
323    }
324
325    pub(crate) fn report_change(&self, no_gc: &NoGC, notification: SelectionLiveRangeNotification) {
326        if notification.is_empty() {
327            return;
328        }
329
330        // Clearing the selection might, in turn, call `Self::disassociate_selection`, so
331        // a `SmallVec` is necessary here to avoid a borrow hazard.
332        let selections: SmallVec<[DomRoot<Selection>; 1]> = self
333            .associated_selections
334            .borrow()
335            .iter()
336            .map(Dom::as_rooted)
337            .collect();
338        for selection in selections {
339            if !selection.clear_selection_if_live_range_document_changed(no_gc, self) {
340                selection.update_from_live_range(no_gc, self, notification);
341            }
342        }
343    }
344
345    fn abstract_range(&self) -> &AbstractRange {
346        &self.abstract_range
347    }
348
349    pub(crate) fn start(&self) -> &BoundaryPoint {
350        self.abstract_range().start()
351    }
352
353    pub(crate) fn end(&self) -> &BoundaryPoint {
354        self.abstract_range().end()
355    }
356
357    pub(crate) fn start_container(&self) -> DomRoot<Node> {
358        self.abstract_range().StartContainer()
359    }
360
361    pub(crate) fn start_offset(&self) -> u32 {
362        self.abstract_range().StartOffset()
363    }
364
365    pub(crate) fn end_container(&self) -> DomRoot<Node> {
366        self.abstract_range().EndContainer()
367    }
368
369    pub(crate) fn end_offset(&self) -> u32 {
370        self.abstract_range().EndOffset()
371    }
372
373    pub(crate) fn collapsed(&self) -> bool {
374        self.abstract_range().Collapsed()
375    }
376
377    /// <https://drafts.csswg.org/cssom-view/#dom-range-getclientrects>
378    fn client_rects(&self, cx: &mut JSContext) -> Vec<Rect<Au, CSSPixel>> {
379        // FIXME: For text nodes that are only partially selected, this should return the client
380        // rect of the selected part, not the whole text node.
381        let start = self.start_container();
382        let end = self.end_container();
383        // > The getClientRects() method, when invoked, must return an empty DOMRectList
384        // > object if the range is not in the document.
385        if !start.is_connected() || !end.is_connected() {
386            return vec![];
387        }
388
389        // Per the spec, only Text nodes contribute rects when the range is collapsed
390        // (including when the boundary points are identical).
391        if self.collapsed() {
392            if start.is::<CharacterData>() {
393                return start.border_boxes(cx);
394            } else {
395                return vec![];
396            }
397        }
398
399        let document = start.owner_doc();
400        let nodes: Vec<DomRoot<Node>> = {
401            let unrooted_end = end.as_unrooted(cx.no_gc());
402            start
403                .following_nodes_unrooted(
404                    cx.no_gc(),
405                    document.upcast::<Node>(),
406                    ShadowIncluding::No,
407                )
408                .take_while(|node| *node != *end)
409                .chain(iter::once(unrooted_end))
410                .map(|node| node.as_rooted())
411                .collect()
412        };
413
414        nodes
415            .iter()
416            .flat_map(move |node| node.border_boxes(cx))
417            .collect()
418    }
419
420    /// <https://dom.spec.whatwg.org/#concept-range-bp-set>
421    fn set_the_start_or_end(
422        &self,
423        no_gc: &NoGC,
424        node: &Node,
425        offset: u32,
426        start_or_end: StartOrEnd,
427    ) -> ErrorResult {
428        // Step 1. If node is a doctype, then throw an "InvalidNodeTypeError"
429        // DOMException.
430        if node.is_doctype() {
431            return Err(Error::InvalidNodeType(Some("Node is a doctype".into())));
432        }
433
434        // Step 2. If offset is greater than node’s length, then throw an "IndexSizeError"
435        // DOMException.
436        if offset > node.len() {
437            return Err(Error::IndexSize(Some(
438                "Offset is greater than the node's length".into(),
439            )));
440        }
441
442        // Step 3. Let bp be the boundary point (node, offset).
443        // NOTE: We don't need this part.
444        let mut notification = SelectionLiveRangeNotification::empty();
445        match start_or_end {
446            // If these steps were invoked as "set the start"
447            StartOrEnd::Start => {
448                // Step 4.1. If range’s root is not equal to node’s root, or if bp is after
449                // the range’s end, set range’s end to bp.
450                if self.root() != node.GetRootNode(&Default::default()) ||
451                    bp_position(
452                        no_gc,
453                        node,
454                        offset,
455                        &self.end_container(),
456                        self.end_offset(),
457                    ) == Ordering::Greater
458                {
459                    self.set_end_without_reporting(node, offset);
460                }
461
462                // Step 4.2. Set range’s start to bp.
463                notification.set(
464                    SelectionLiveRangeNotification::Start,
465                    self.set_start_without_reporting(node, offset),
466                );
467            },
468            // If these steps were invoked as "set the end"
469            StartOrEnd::End => {
470                // Step 4.1. If range’s root is not equal to node’s root, or if bp is
471                // before the range’s start, set range’s start to bp.
472                if self.root() != node.GetRootNode(&Default::default()) ||
473                    bp_position(
474                        no_gc,
475                        node,
476                        offset,
477                        &self.start_container(),
478                        self.start_offset(),
479                    ) == Ordering::Less
480                {
481                    self.set_start_without_reporting(node, offset);
482                }
483
484                // Step 4.2. Set range’s end to bp.
485                notification.set(
486                    SelectionLiveRangeNotification::End,
487                    self.set_end_without_reporting(node, offset),
488                );
489            },
490        }
491
492        self.maybe_update_document();
493        self.report_change(no_gc, notification);
494        Ok(())
495    }
496
497    /// When:
498    ///
499    /// - The start and end node have changed in a way in which they no longer have the same
500    ///   [`Document`]
501    /// - A node is adopted into a different [`Document`]
502    ///
503    /// this method ensures that the [`Document`] of this [`Range`] remains the same. If it doesn't
504    /// the [`Range`] is moved from the old [`Document`] to the new one.
505    pub(crate) fn maybe_update_document(&self) {
506        // Note: `debug_assert_eq!` requires the arguments to implement `Debug`.
507        debug_assert!(
508            self.start_container().owner_document() == self.end_container().owner_document(),
509        );
510
511        let current_document = self.document.get();
512        let new_document = self.start_container().owner_document();
513        if new_document != current_document {
514            current_document.live_ranges().remove(self);
515            new_document.live_ranges().push(WeakRef::new(self));
516            self.document.set(&new_document);
517        }
518    }
519
520    pub(crate) fn start_and_end_are_in_document_tree(&self) -> bool {
521        self.start_container().is_in_a_document_tree() &&
522            self.end_container().is_in_a_document_tree()
523    }
524}
525
526impl std::fmt::Debug for Range {
527    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
528        write!(
529            f,
530            "[({:?}, {}) -> ({:?}, {})]",
531            self.start_container(),
532            self.start_offset(),
533            self.end_container(),
534            self.end_offset()
535        )
536    }
537}
538
539#[derive(Copy, Clone)]
540pub(crate) enum StartOrEnd {
541    Start,
542    End,
543}
544
545impl RangeMethods<crate::DomTypeHolder> for Range {
546    /// <https://dom.spec.whatwg.org/#dom-range>
547    fn Constructor(
548        cx: &mut JSContext,
549        window: &Window,
550        proto: Option<HandleObject>,
551    ) -> Fallible<DomRoot<Range>> {
552        let document = window.Document();
553        Ok(Range::new_with_doc(cx, &document, proto))
554    }
555
556    /// <https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer>
557    fn CommonAncestorContainer(&self) -> DomRoot<Node> {
558        self.end_container()
559            .common_ancestor(&self.start_container(), ShadowIncluding::No)
560            .expect("Couldn't find common ancestor container")
561    }
562
563    /// <https://dom.spec.whatwg.org/#dom-range-setstart>
564    fn SetStart(&self, no_gc: &NoGC, node: &Node, offset: u32) -> ErrorResult {
565        self.set_the_start_or_end(no_gc, node, offset, StartOrEnd::Start)
566    }
567
568    /// <https://dom.spec.whatwg.org/#dom-range-setend>
569    fn SetEnd(&self, no_gc: &NoGC, node: &Node, offset: u32) -> ErrorResult {
570        self.set_the_start_or_end(no_gc, node, offset, StartOrEnd::End)
571    }
572
573    /// <https://dom.spec.whatwg.org/#dom-range-setstartbefore>
574    fn SetStartBefore(&self, no_gc: &NoGC, node: &Node) -> ErrorResult {
575        let parent = node
576            .GetParentNode()
577            .ok_or(Error::InvalidNodeType(Some("Node has no parent".into())))?;
578        self.SetStart(no_gc, &parent, node.index())
579    }
580
581    /// <https://dom.spec.whatwg.org/#dom-range-setstartafter>
582    fn SetStartAfter(&self, no_gc: &NoGC, node: &Node) -> ErrorResult {
583        let parent = node
584            .GetParentNode()
585            .ok_or(Error::InvalidNodeType(Some("Node has no parent".into())))?;
586        self.SetStart(no_gc, &parent, node.index() + 1)
587    }
588
589    /// <https://dom.spec.whatwg.org/#dom-range-setendbefore>
590    fn SetEndBefore(&self, no_gc: &NoGC, node: &Node) -> ErrorResult {
591        let parent = node
592            .GetParentNode()
593            .ok_or(Error::InvalidNodeType(Some("Node has no parent".into())))?;
594        self.SetEnd(no_gc, &parent, node.index())
595    }
596
597    /// <https://dom.spec.whatwg.org/#dom-range-setendafter>
598    fn SetEndAfter(&self, no_gc: &NoGC, node: &Node) -> ErrorResult {
599        let parent = node
600            .GetParentNode()
601            .ok_or(Error::InvalidNodeType(Some("Node has no parent".into())))?;
602        self.SetEnd(no_gc, &parent, node.index() + 1)
603    }
604
605    /// <https://dom.spec.whatwg.org/#dom-range-collapse>
606    fn Collapse(&self, no_gc: &NoGC, to_start: bool) {
607        if to_start {
608            self.set_end(no_gc, &self.start_container(), self.start_offset());
609        } else {
610            self.set_start(no_gc, &self.end_container(), self.end_offset());
611        }
612    }
613
614    /// <https://dom.spec.whatwg.org/#dom-range-selectnode>
615    fn SelectNode(&self, no_gc: &NoGC, node: &Node) -> ErrorResult {
616        // Steps 1, 2.
617        let parent = node
618            .GetParentNode()
619            .ok_or(Error::InvalidNodeType(Some("Node has no parent".into())))?;
620        // Step 3.
621        let index = node.index();
622        // Step 4.
623        self.set_start(no_gc, &parent, index);
624        // Step 5.
625        self.set_end(no_gc, &parent, index + 1);
626        self.maybe_update_document(); // owning document could have changed
627        Ok(())
628    }
629
630    /// <https://dom.spec.whatwg.org/#dom-range-selectnodecontents>
631    fn SelectNodeContents(&self, no_gc: &NoGC, node: &Node) -> ErrorResult {
632        if node.is_doctype() {
633            // Step 1.
634            return Err(Error::InvalidNodeType(Some("Node is a doctype".into())));
635        }
636        // Step 2.
637        let length = node.len();
638        // Step 3.
639        self.set_start(no_gc, node, 0);
640        // Step 4.
641        self.set_end(no_gc, node, length);
642        self.maybe_update_document(); // owning document could have changed
643        Ok(())
644    }
645
646    /// <https://dom.spec.whatwg.org/#dom-range-compareboundarypoints>
647    fn CompareBoundaryPoints(&self, no_gc: &NoGC, how: u16, source_range: &Range) -> Fallible<i16> {
648        // Step 1. If how is not one of
649        //    * START_TO_START,
650        //    * START_TO_END,
651        //    * END_TO_END, and
652        //    * END_TO_START,
653        // then throw a "NotSupportedError" DOMException.
654        if how > RangeConstants::END_TO_START {
655            return Err(Error::NotSupported(Some(
656                "Invalid comparison method".into(),
657            )));
658        }
659        // Step 2. If this’s root is not sourceRange’s root, then throw a
660        // "WrongDocumentError" DOMException.
661        if self.root() != source_range.root() {
662            return Err(Error::WrongDocument(Some(
663                "Ranges are not in the same tree".into(),
664            )));
665        }
666        // Step 3. Let thisPoint and sourcePoint be null.
667        // Step 4.  Switch on how:
668        //  ↪ START_TO_START:
669        //     Set thisPoint to this’s start and sourcePoint to sourceRange’s start.
670        //  ↪ START_TO_END:
671        //     Set thisPoint to this’s end and sourcePoint to sourceRange’s start.
672        //  ↪ END_TO_END:
673        //     Set thisPoint to this’s end and sourcePoint to sourceRange’s end.
674        //  ↪ END_TO_START:
675        //     Set thisPoint to this’s start and sourcePoint to sourceRange’s end.
676        let (this_point, source_point) = match how {
677            RangeConstants::START_TO_START => (self.start(), source_range.start()),
678            RangeConstants::START_TO_END => (self.end(), source_range.start()),
679            RangeConstants::END_TO_END => (self.end(), source_range.end()),
680            RangeConstants::END_TO_START => (self.start(), source_range.end()),
681            _ => unreachable!(),
682        };
683        // Step 5. Switch on the position of thisPoint relative to sourcePoint:
684        //  ↪ before
685        //      Return −1.
686        //  ↪ equal
687        //      Return 0.
688        //  ↪ after
689        //      Return 1.
690        match this_point.partial_cmp(no_gc, source_point).unwrap() {
691            Ordering::Less => Ok(-1),
692            Ordering::Equal => Ok(0),
693            Ordering::Greater => Ok(1),
694        }
695    }
696
697    /// <https://dom.spec.whatwg.org/#dom-range-clonerange>
698    fn CloneRange(&self, cx: &mut JSContext) -> DomRoot<Range> {
699        let start_node = self.start_container();
700        let owner_doc = start_node.owner_doc();
701        Range::new(
702            cx,
703            &owner_doc,
704            &start_node,
705            self.start_offset(),
706            &self.end_container(),
707            self.end_offset(),
708        )
709    }
710
711    /// <https://dom.spec.whatwg.org/#dom-range-ispointinrange>
712    fn IsPointInRange(&self, no_gc: &NoGC, node: &Node, offset: u32) -> Fallible<bool> {
713        match self.compare_point(no_gc, node, offset) {
714            Ok(Ordering::Less) => Ok(false),
715            Ok(Ordering::Equal) => Ok(true),
716            Ok(Ordering::Greater) => Ok(false),
717            Err(Error::WrongDocument(_)) => {
718                // Step 2.  If node’s root is not this’s root, then return false.
719                // Note: This is the only step that differs from `Self::compare_point`.
720                Ok(false)
721            },
722            Err(error) => Err(error),
723        }
724    }
725
726    /// <https://dom.spec.whatwg.org/#dom-range-comparepoint>
727    fn ComparePoint(&self, no_gc: &NoGC, node: &Node, offset: u32) -> Fallible<i16> {
728        self.compare_point(no_gc, node, offset)
729            .map(|order| match order {
730                Ordering::Less => -1,
731                Ordering::Equal => 0,
732                Ordering::Greater => 1,
733            })
734    }
735
736    /// <https://dom.spec.whatwg.org/#dom-range-intersectsnode>
737    fn IntersectsNode(&self, no_gc: &NoGC, node: &Node) -> bool {
738        // Step 1. If node’s root is not this’s root, then return false.
739        if self.root() != node.GetRootNode(&Default::default()) {
740            return false;
741        }
742        // Step 2. Let parent be node’s parent.
743        let Some(parent) = node.GetParentNode() else {
744            // Step 3. If parent is null, then return true.
745            return true;
746        };
747        // Step 4. Let offset be node’s index.
748        let offset = node.index();
749        // Step 5. If (parent, offset) is before end and (parent, offset + 1) is after
750        // start, then return true.
751        // Step 6. Return false.
752        let start_node = self.start_container();
753        Ordering::Greater ==
754            bp_position(no_gc, &parent, offset + 1, &start_node, self.start_offset()) &&
755            Ordering::Less ==
756                bp_position(
757                    no_gc,
758                    &parent,
759                    offset,
760                    &self.end_container(),
761                    self.end_offset(),
762                )
763    }
764
765    /// <https://dom.spec.whatwg.org/#dom-range-clonecontents>
766    /// <https://dom.spec.whatwg.org/#concept-range-clone>
767    fn CloneContents(&self, cx: &mut JSContext) -> Fallible<DomRoot<DocumentFragment>> {
768        // Step 3.
769        let start_node = self.start_container();
770        let start_offset = self.start_offset();
771        let end_node = self.end_container();
772        let end_offset = self.end_offset();
773
774        // Step 1.
775        let fragment = DocumentFragment::new(cx, &start_node.owner_doc());
776
777        // Step 2.
778        if self.start() == self.end() {
779            return Ok(fragment);
780        }
781
782        if end_node == start_node &&
783            let Some(cdata) = start_node.downcast::<CharacterData>()
784        {
785            // Steps 4.1-2.
786            let data = cdata
787                .SubstringData(start_offset, end_offset - start_offset)
788                .unwrap();
789            let clone = cdata.clone_with_data(cx, data, &start_node.owner_doc());
790            // Step 4.3.
791            fragment.upcast::<Node>().AppendChild(cx, &clone)?;
792            // Step 4.4
793            return Ok(fragment);
794        }
795
796        // Steps 5-12.
797        let ContainedChildren {
798            first_partially_contained_child,
799            last_partially_contained_child,
800            contained_children,
801        } = self.contained_children(cx.no_gc())?;
802
803        if let Some(child) = first_partially_contained_child {
804            // Step 13.
805            if let Some(cdata) = child.downcast::<CharacterData>() {
806                assert!(child == start_node);
807                // Steps 13.1-2.
808                let data = cdata
809                    .SubstringData(start_offset, start_node.len() - start_offset)
810                    .unwrap();
811                let clone = cdata.clone_with_data(cx, data, &start_node.owner_doc());
812                // Step 13.3.
813                fragment.upcast::<Node>().AppendChild(cx, &clone)?;
814            } else {
815                // Step 14.1.
816                let clone = child.CloneNode(cx, /* deep */ false)?;
817                // Step 14.2.
818                fragment.upcast::<Node>().AppendChild(cx, &clone)?;
819                // Step 14.3.
820                let subrange = Range::new(
821                    cx,
822                    &clone.owner_doc(),
823                    &start_node,
824                    start_offset,
825                    &child,
826                    child.len(),
827                );
828                // Step 14.4.
829                let subfragment = subrange.CloneContents(cx)?;
830                // Step 14.5.
831                clone.AppendChild(cx, subfragment.upcast())?;
832            }
833        }
834
835        // Step 15.
836        for child in contained_children {
837            // Step 15.1.
838            let clone = child.CloneNode(cx, /* deep */ true)?;
839            // Step 15.2.
840            fragment.upcast::<Node>().AppendChild(cx, &clone)?;
841        }
842
843        if let Some(child) = last_partially_contained_child {
844            // Step 16.
845            if let Some(cdata) = child.downcast::<CharacterData>() {
846                assert!(child == end_node);
847                // Steps 16.1-2.
848                let data = cdata.SubstringData(0, end_offset).unwrap();
849                let clone = cdata.clone_with_data(cx, data, &start_node.owner_doc());
850                // Step 16.3.
851                fragment.upcast::<Node>().AppendChild(cx, &clone)?;
852            } else {
853                // Step 17.1.
854                let clone = child.CloneNode(cx, /* deep */ false)?;
855                // Step 17.2.
856                fragment.upcast::<Node>().AppendChild(cx, &clone)?;
857                // Step 17.3.
858                let subrange = Range::new(cx, &clone.owner_doc(), &child, 0, &end_node, end_offset);
859                // Step 17.4.
860                let subfragment = subrange.CloneContents(cx)?;
861                // Step 17.5.
862                clone.AppendChild(cx, subfragment.upcast())?;
863            }
864        }
865
866        // Step 18.
867        Ok(fragment)
868    }
869
870    /// <https://dom.spec.whatwg.org/#dom-range-extractcontents>
871    /// <https://dom.spec.whatwg.org/#concept-range-extract>
872    fn ExtractContents(&self, cx: &mut JSContext) -> Fallible<DomRoot<DocumentFragment>> {
873        // Step 3.
874        let start_node = self.start_container();
875        let start_offset = self.start_offset();
876        let end_node = self.end_container();
877        let end_offset = self.end_offset();
878
879        // Step 1.
880        let fragment = DocumentFragment::new(cx, &start_node.owner_doc());
881
882        // Step 2.
883        if self.collapsed() {
884            return Ok(fragment);
885        }
886
887        if end_node == start_node &&
888            let Some(end_data) = end_node.downcast::<CharacterData>()
889        {
890            // Step 4.1.
891            let clone = end_node.CloneNode(cx, /* deep */ true)?;
892            // Step 4.2.
893            let text = end_data.SubstringData(start_offset, end_offset - start_offset);
894            clone
895                .downcast::<CharacterData>()
896                .unwrap()
897                .SetData(cx, text.unwrap());
898            // Step 4.3.
899            fragment.upcast::<Node>().AppendChild(cx, &clone)?;
900            // Step 4.4.
901            end_data.ReplaceData(
902                cx,
903                start_offset,
904                end_offset - start_offset,
905                DOMString::new(),
906            )?;
907            // Step 4.5.
908            return Ok(fragment);
909        }
910
911        // Steps 5-12.
912        let ContainedChildren {
913            first_partially_contained_child,
914            last_partially_contained_child,
915            contained_children,
916        } = self.contained_children(cx.no_gc())?;
917
918        let (new_node, new_offset) = if start_node.is_inclusive_ancestor_of(&end_node) {
919            // Step 13.
920            (DomRoot::from_ref(&*start_node), start_offset)
921        } else {
922            // Step 14.1-2.
923            let reference_node = start_node
924                .ancestors()
925                .take_while(|n| !n.is_inclusive_ancestor_of(&end_node))
926                .last()
927                .unwrap_or(DomRoot::from_ref(&start_node));
928            // Step 14.3.
929            (
930                reference_node.GetParentNode().unwrap(),
931                reference_node.index() + 1,
932            )
933        };
934
935        if let Some(child) = first_partially_contained_child {
936            if let Some(start_data) = child.downcast::<CharacterData>() {
937                assert!(child == start_node);
938                // Step 15.1.
939                let clone = start_node.CloneNode(cx, /* deep */ true)?;
940                // Step 15.2.
941                let text = start_data.SubstringData(start_offset, start_node.len() - start_offset);
942                clone
943                    .downcast::<CharacterData>()
944                    .unwrap()
945                    .SetData(cx, text.unwrap());
946                // Step 15.3.
947                fragment.upcast::<Node>().AppendChild(cx, &clone)?;
948                // Step 15.4.
949                start_data.ReplaceData(
950                    cx,
951                    start_offset,
952                    start_node.len() - start_offset,
953                    DOMString::new(),
954                )?;
955            } else {
956                // Step 16.1.
957                let clone = child.CloneNode(cx, /* deep */ false)?;
958                // Step 16.2.
959                fragment.upcast::<Node>().AppendChild(cx, &clone)?;
960                // Step 16.3.
961                let subrange = Range::new(
962                    cx,
963                    &clone.owner_doc(),
964                    &start_node,
965                    start_offset,
966                    &child,
967                    child.len(),
968                );
969                // Step 16.4.
970                let subfragment = subrange.ExtractContents(cx)?;
971                // Step 16.5.
972                clone.AppendChild(cx, subfragment.upcast())?;
973            }
974        }
975
976        // Step 17.
977        for child in contained_children {
978            fragment.upcast::<Node>().AppendChild(cx, &child)?;
979        }
980
981        if let Some(child) = last_partially_contained_child {
982            if let Some(end_data) = child.downcast::<CharacterData>() {
983                assert!(child == end_node);
984                // Step 18.1.
985                let clone = end_node.CloneNode(cx, /* deep */ true)?;
986                // Step 18.2.
987                let text = end_data.SubstringData(0, end_offset);
988                clone
989                    .downcast::<CharacterData>()
990                    .unwrap()
991                    .SetData(cx, text.unwrap());
992                // Step 18.3.
993                fragment.upcast::<Node>().AppendChild(cx, &clone)?;
994                // Step 18.4.
995                end_data.ReplaceData(cx, 0, end_offset, DOMString::new())?;
996            } else {
997                // Step 19.1.
998                let clone = child.CloneNode(cx, /* deep */ false)?;
999                // Step 19.2.
1000                fragment.upcast::<Node>().AppendChild(cx, &clone)?;
1001                // Step 19.3.
1002                let subrange = Range::new(cx, &clone.owner_doc(), &child, 0, &end_node, end_offset);
1003                // Step 19.4.
1004                let subfragment = subrange.ExtractContents(cx)?;
1005                // Step 19.5.
1006                clone.AppendChild(cx, subfragment.upcast())?;
1007            }
1008        }
1009
1010        // Step 20.
1011        self.SetStart(cx.no_gc(), &new_node, new_offset)?;
1012        self.SetEnd(cx.no_gc(), &new_node, new_offset)?;
1013
1014        // Step 21.
1015        Ok(fragment)
1016    }
1017
1018    /// <https://dom.spec.whatwg.org/#dom-range-detach>
1019    /// > The detach() method steps are to do nothing. Its functionality (disabling a Range object)
1020    /// > was removed, but the method itself is preserved for compatibility.
1021    fn Detach(&self) {
1022        // This method intentionally left blank.
1023    }
1024
1025    /// <https://dom.spec.whatwg.org/#dom-range-insertnode>
1026    /// <https://dom.spec.whatwg.org/#concept-range-insert>
1027    fn InsertNode(&self, cx: &mut JSContext, node: &Node) -> ErrorResult {
1028        let start_node = self.start_container();
1029        let start_offset = self.start_offset();
1030
1031        // Step 1.
1032        if &*start_node == node {
1033            return Err(Error::HierarchyRequest(Some(
1034                "Node is the range's start container".into(),
1035            )));
1036        }
1037        match start_node.type_id() {
1038            // Handled under step 2.
1039            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => (),
1040            NodeTypeId::CharacterData(_) => {
1041                return Err(Error::HierarchyRequest(Some(
1042                    "Cannot insert into a Comment or ProcessingInstruction node".into(),
1043                )));
1044            },
1045            _ => (),
1046        }
1047
1048        // Step 2.
1049        let (reference_node, parent) = match start_node.type_id() {
1050            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => {
1051                // Step 3.
1052                let parent = match start_node.GetParentNode() {
1053                    Some(parent) => parent,
1054                    // Step 1.
1055                    None => {
1056                        return Err(Error::HierarchyRequest(Some(
1057                            "Range's start container has no parent".into(),
1058                        )));
1059                    },
1060                };
1061                // Step 5.
1062                (Some(DomRoot::from_ref(&*start_node)), parent)
1063            },
1064            _ => {
1065                // Steps 4-5.
1066                let child = start_node.ChildNodes(cx).Item(cx, start_offset);
1067                (child, DomRoot::from_ref(&*start_node))
1068            },
1069        };
1070
1071        // Step 6.
1072        Node::ensure_pre_insertion_validity(
1073            cx.no_gc(),
1074            node,
1075            &parent,
1076            reference_node.as_deref(),
1077            &[],
1078        )?;
1079
1080        // Step 7.
1081        let split_text;
1082        let reference_node = match start_node.downcast::<Text>() {
1083            Some(text) => {
1084                split_text = text.SplitText(cx, start_offset)?;
1085                let new_reference = DomRoot::upcast::<Node>(split_text);
1086                assert!(new_reference.GetParentNode().as_deref() == Some(&parent));
1087                Some(new_reference)
1088            },
1089            _ => reference_node,
1090        };
1091
1092        // Step 8.
1093        let reference_node = if Some(node) == reference_node.as_deref() {
1094            node.GetNextSibling()
1095        } else {
1096            reference_node
1097        };
1098
1099        // Step 9.
1100        node.remove_self(cx);
1101
1102        // Step 10.
1103        let new_offset = reference_node
1104            .as_ref()
1105            .map_or(parent.len(), |node| node.index());
1106
1107        // Step 11
1108        let new_offset = new_offset +
1109            if let NodeTypeId::DocumentFragment(_) = node.type_id() {
1110                node.len()
1111            } else {
1112                1
1113            };
1114
1115        // Step 12.
1116        Node::pre_insert(cx, node, &parent, reference_node.as_deref())?;
1117
1118        // Step 13.
1119        if self.collapsed() {
1120            self.set_end(cx.no_gc(), &parent, new_offset);
1121        }
1122
1123        Ok(())
1124    }
1125
1126    /// <https://dom.spec.whatwg.org/#dom-range-deletecontents>
1127    fn DeleteContents(&self, cx: &mut JSContext) -> ErrorResult {
1128        // Step 1. If this is collapsed, then return.
1129        if self.collapsed() {
1130            return Ok(());
1131        }
1132
1133        // Step 2. Let originalStartNode, originalStartOffset, originalEndNode,
1134        // and originalEndOffset be this’s start node, start offset, end node, and end offset, respectively.
1135        let start_node = self.start_container();
1136        let end_node = self.end_container();
1137        let start_offset = self.start_offset();
1138        let end_offset = self.end_offset();
1139
1140        // Step 3. If originalStartNode is originalEndNode and it is a CharacterData node:
1141        if start_node == end_node &&
1142            let Some(text) = start_node.downcast::<CharacterData>()
1143        {
1144            // Step 3.1. Replace data of originalStartNode with originalStartOffset,
1145            // originalEndOffset − originalStartOffset, and the empty string.
1146            // Step 3.2. Return.
1147            return text.ReplaceData(
1148                cx,
1149                start_offset,
1150                end_offset - start_offset,
1151                DOMString::new(),
1152            );
1153        }
1154
1155        // Step 4. Let nodesToRemove be a list of all the nodes that are contained in this,
1156        // in tree order, omitting any node whose parent is also contained in this.
1157        rooted_vec!(let mut contained_children);
1158        let ancestor = self.CommonAncestorContainer();
1159
1160        let mut iter = start_node.following_nodes(&ancestor, ShadowIncluding::No);
1161
1162        let mut next = iter.next();
1163        while let Some(child) = next {
1164            if self.contains(cx.no_gc(), &child) {
1165                contained_children.push(Dom::from_ref(&*child));
1166                next = iter.next_skipping_children();
1167            } else {
1168                next = iter.next();
1169            }
1170        }
1171
1172        // Step 5. Let newNode and newOffset be null.
1173        // Step 6. If originalStartNode is an inclusive ancestor of originalEndNode,
1174        // then set newNode to originalStartNode and newOffset to originalStartOffset.
1175        let (new_node, new_offset) = if start_node.is_inclusive_ancestor_of(&end_node) {
1176            (DomRoot::from_ref(&*start_node), start_offset)
1177        } else {
1178            // Step 7. Otherwise:
1179            fn compute_reference(start_node: &Node, end_node: &Node) -> (DomRoot<Node>, u32) {
1180                // Step 7.1. Let referenceNode be originalStartNode.
1181                let mut reference_node = DomRoot::from_ref(start_node);
1182                // Step 7.2. While referenceNode’s parent is non-null and
1183                // is not an inclusive ancestor of originalEndNode: set referenceNode to its parent.
1184                while let Some(parent) = reference_node.GetParentNode() {
1185                    if parent.is_inclusive_ancestor_of(end_node) {
1186                        // Step 7.3. Set newNode to referenceNode’s parent and newOffset to referenceNode’s index + 1.
1187                        return (parent, reference_node.index() + 1);
1188                    }
1189                    reference_node = parent;
1190                }
1191                unreachable!()
1192            }
1193
1194            compute_reference(&start_node, &end_node)
1195        };
1196
1197        // Step 8. Set this’s start and end to (newNode, newOffset).
1198        self.SetStart(cx.no_gc(), &new_node, new_offset).unwrap();
1199        self.SetEnd(cx.no_gc(), &new_node, new_offset).unwrap();
1200
1201        // Step 9. If originalStartNode is a CharacterData node,
1202        // then replace data of originalStartNode with originalStartOffset,
1203        // originalStartNode’s length − originalStartOffset, and the empty string.
1204        if let Some(text) = start_node.downcast::<CharacterData>() {
1205            text.ReplaceData(
1206                cx,
1207                start_offset,
1208                start_node.len() - start_offset,
1209                DOMString::new(),
1210            )
1211            .unwrap();
1212        }
1213
1214        // Step 10. For each node of nodesToRemove, in tree order: remove node.
1215        for child in &*contained_children {
1216            child.remove_self(cx);
1217        }
1218
1219        // Step 11. If originalEndNode is a CharacterData node,
1220        // then replace data of originalEndNode with 0, originalEndOffset, and the empty string.
1221        if let Some(text) = end_node.downcast::<CharacterData>() {
1222            text.ReplaceData(cx, 0, end_offset, DOMString::new())
1223                .unwrap();
1224        }
1225
1226        Ok(())
1227    }
1228
1229    /// <https://dom.spec.whatwg.org/#dom-range-surroundcontents>
1230    fn SurroundContents(&self, cx: &mut JSContext, new_parent: &Node) -> ErrorResult {
1231        // Step 1.
1232        let start = self.start_container();
1233        let end = self.end_container();
1234
1235        if start
1236            .inclusive_ancestors(ShadowIncluding::No)
1237            .any(|n| !n.is_inclusive_ancestor_of(&end) && !n.is::<Text>()) ||
1238            end.inclusive_ancestors(ShadowIncluding::No)
1239                .any(|n| !n.is_inclusive_ancestor_of(&start) && !n.is::<Text>())
1240        {
1241            return Err(Error::InvalidState(Some(
1242                "Range partially contains a non-Text node".into(),
1243            )));
1244        }
1245
1246        // Step 2.
1247        match new_parent.type_id() {
1248            NodeTypeId::Document(_) |
1249            NodeTypeId::DocumentType |
1250            NodeTypeId::DocumentFragment(_) => {
1251                return Err(Error::InvalidNodeType(Some(
1252                    "Node cannot be a Document, DocumentType or DocumentFragment".into(),
1253                )));
1254            },
1255            _ => (),
1256        }
1257
1258        // Step 3.
1259        let fragment = self.ExtractContents(cx)?;
1260
1261        // Step 4.
1262        Node::replace_all(cx, None, new_parent);
1263
1264        // Step 5.
1265        self.InsertNode(cx, new_parent)?;
1266
1267        // Step 6.
1268        new_parent.AppendChild(cx, fragment.upcast())?;
1269
1270        // Step 7.
1271        self.SelectNode(cx.no_gc(), new_parent)
1272    }
1273
1274    /// <https://dom.spec.whatwg.org/#dom-range-stringifier>
1275    fn Stringifier(&self, no_gc: &NoGC) -> DOMString {
1276        let start_node = self.start_container();
1277        let end_node = self.end_container();
1278
1279        // Step 1. Let string be the empty string.
1280        let mut s = DOMString::new();
1281
1282        if let Some(text_node) = start_node.downcast::<Text>() {
1283            let char_data = text_node.upcast::<CharacterData>();
1284
1285            // Step 2. If this’s start node is this’s end node and it is a Text node,
1286            // then return the substring of that Text node’s data beginning at
1287            // this’s start offset and ending at this’s end offset.
1288            if start_node == end_node {
1289                return char_data
1290                    .SubstringData(self.start_offset(), self.end_offset() - self.start_offset())
1291                    .unwrap();
1292            }
1293
1294            // Step 3. If this’s start node is a Text node, then append the substring of
1295            // that node’s data from this’s start offset until the end to string.
1296            s.push_str(
1297                &char_data
1298                    .SubstringData(
1299                        self.start_offset(),
1300                        char_data.Length() - self.start_offset(),
1301                    )
1302                    .unwrap()
1303                    .str(),
1304            );
1305        }
1306
1307        // Step 4. Append the concatenation of the data of all Text nodes that are contained in this,
1308        // in tree order, to string.
1309        let ancestor = self.CommonAncestorContainer();
1310        let iter = start_node
1311            .following_nodes_unrooted(no_gc, &ancestor, ShadowIncluding::No)
1312            .filter_map(UnrootedDom::downcast::<Text>);
1313
1314        for child in iter {
1315            if self.contains(no_gc, child.upcast()) {
1316                s.push_str(&child.upcast::<CharacterData>().Data().str());
1317            }
1318        }
1319
1320        // Step 5. If this’s end node is a Text node, then append the substring of
1321        // that node’s data from its start until this’s end offset to string.
1322        if let Some(text_node) = end_node.downcast::<Text>() {
1323            let char_data = text_node.upcast::<CharacterData>();
1324            s.push_str(&char_data.SubstringData(0, self.end_offset()).unwrap().str());
1325        }
1326
1327        // Step 6. Return string.
1328        s
1329    }
1330
1331    /// <https://html.spec.whatwg.org/multipage/#dom-range-createcontextualfragment>
1332    fn CreateContextualFragment(
1333        &self,
1334        cx: &mut JSContext,
1335        fragment: TrustedHTMLOrString,
1336    ) -> Fallible<DomRoot<DocumentFragment>> {
1337        // Step 2. Let node be this's start node.
1338        //
1339        // Required to obtain the global, so we do this first. Shouldn't be an
1340        // observable difference.
1341        let node = self.start_container();
1342
1343        // Step 1. Let compliantString be the result of invoking the
1344        // Get Trusted Type compliant string algorithm with TrustedHTML,
1345        // this's relevant global object, string, "Range createContextualFragment", and "script".
1346        let fragment = TrustedHTML::get_trusted_type_compliant_string(
1347            cx,
1348            node.owner_window().upcast(),
1349            fragment,
1350            "Range createContextualFragment",
1351        )?;
1352
1353        let owner_doc = node.owner_doc();
1354
1355        // Step 3. Let element be null.
1356        // Step 4. If node implements Element, set element to node.
1357        // Step 5. Otherwise, if node implements Text or Comment, set element to node's parent element.
1358        let element = match node.type_id() {
1359            NodeTypeId::Element(_) => Some(DomRoot::downcast::<Element>(node).unwrap()),
1360            NodeTypeId::CharacterData(CharacterDataTypeId::Comment) |
1361            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => node.GetParentElement(),
1362            _ => None,
1363        };
1364
1365        // Step 6. If element is null or all of the following are true:
1366        let element = Element::fragment_parsing_context(cx, &owner_doc, element.as_deref());
1367
1368        // Step 7. Let fragment node be the result of invoking the fragment parsing algorithm steps with element and compliantString.
1369        let fragment_node = element.parse_fragment(fragment, cx)?;
1370
1371        // Step 8. For each script of fragment node's script element descendants:
1372        for node in fragment_node
1373            .upcast::<Node>()
1374            .traverse_preorder(ShadowIncluding::No)
1375        {
1376            if let Some(script) = node.downcast::<HTMLScriptElement>() {
1377                // Step 8.1. Set script's already started to false.
1378                script.set_already_started(false);
1379                // Step 8.2. Set script's parser document to null.
1380                script.set_parser_inserted(false);
1381            }
1382        }
1383
1384        // Step 9. Return fragment node.
1385        Ok(fragment_node)
1386    }
1387
1388    /// <https://drafts.csswg.org/cssom-view/#dom-range-getclientrects>
1389    fn GetClientRects(&self, cx: &mut JSContext) -> DomRoot<DOMRectList> {
1390        let start = self.start_container();
1391        let window = start.owner_window();
1392
1393        let client_rects = self.client_rects(cx);
1394        let client_rects = client_rects
1395            .iter()
1396            .map(|rect| {
1397                DOMRect::new(
1398                    cx,
1399                    window.upcast(),
1400                    rect.origin.x.to_f64_px(),
1401                    rect.origin.y.to_f64_px(),
1402                    rect.size.width.to_f64_px(),
1403                    rect.size.height.to_f64_px(),
1404                )
1405            })
1406            .collect();
1407
1408        DOMRectList::new(cx, &window, client_rects)
1409    }
1410
1411    /// <https://drafts.csswg.org/cssom-view/#dom-range-getboundingclientrect>
1412    fn GetBoundingClientRect(&self, cx: &mut JSContext) -> DomRoot<DOMRect> {
1413        let window = self.start_container().owner_window();
1414
1415        // Step 1. Let list be the result of invoking getClientRects() on the same range this method was invoked on.
1416        let list = self.client_rects(cx);
1417
1418        // Step 2. If list is empty return a DOMRect object whose x, y, width and height members are zero.
1419        // Step 3. If all rectangles in list have zero width or height, return the first rectangle in list.
1420        // Step 4. Otherwise, return a DOMRect object describing the smallest rectangle that includes all
1421        // of the rectangles in list of which the height or width is not zero.
1422        let bounding_rect = list
1423            .into_iter()
1424            .fold(euclid::Rect::zero(), |acc, rect| acc.union(&rect));
1425
1426        DOMRect::new(
1427            cx,
1428            window.upcast(),
1429            bounding_rect.origin.x.to_f64_px(),
1430            bounding_rect.origin.y.to_f64_px(),
1431            bounding_rect.size.width.to_f64_px(),
1432            bounding_rect.size.height.to_f64_px(),
1433        )
1434    }
1435}
1436
1437#[derive(MallocSizeOf)]
1438pub(crate) struct WeakRangeVec {
1439    cell: DomRefCell<WeakRefVec<Range>>,
1440}
1441
1442impl Default for WeakRangeVec {
1443    fn default() -> Self {
1444        WeakRangeVec {
1445            cell: DomRefCell::new(WeakRefVec::new()),
1446        }
1447    }
1448}
1449
1450impl WeakRangeVec {
1451    /// Get a rooted version of the contents of this [`WeakRangeVec`]
1452    pub(crate) fn as_vec(&self) -> SmallVec<[DomRoot<Range>; 4]> {
1453        self.cell
1454            .borrow()
1455            .iter()
1456            .filter_map(|range| range.root())
1457            .collect()
1458    }
1459
1460    pub(crate) fn for_each(&self, no_gc: &NoGC, mut callback: impl FnMut(&Range)) {
1461        for weak_range in self.cell.safe_borrow_mut(no_gc).iter() {
1462            if let Some(range) = weak_range.unrooted(no_gc) {
1463                callback(&range);
1464            }
1465        }
1466    }
1467
1468    pub(crate) fn is_empty(&self) -> bool {
1469        self.cell.borrow().is_empty()
1470    }
1471
1472    fn push(&self, weak_range: WeakRef<Range>) {
1473        self.cell.borrow_mut().push(weak_range);
1474    }
1475
1476    fn remove(&self, range_to_remove: &Range) {
1477        self.cell
1478            .borrow_mut()
1479            .retain(|range| range != range_to_remove);
1480    }
1481}
1482
1483#[expect(unsafe_code)]
1484unsafe impl JSTraceable for WeakRangeVec {
1485    unsafe fn trace(&self, _: *mut JSTracer) {
1486        self.cell.borrow_mut().retain_alive()
1487    }
1488}
1489
1490impl Document {
1491    /// <https://dom.spec.whatwg.org/#concept-node-insert> steps 5.1-5.2
1492    /// and
1493    /// <https://dom.spec.whatwg.org/#move> steps 17.1-17.2.
1494    pub(crate) fn live_range_insert_steps(
1495        &self,
1496        no_gc: &NoGC,
1497        parent: &Node,
1498        child: &Node,
1499        count: u32,
1500    ) {
1501        if self.live_ranges().is_empty() {
1502            return;
1503        }
1504
1505        let child_index = LazyCell::new(|| child.index());
1506        self.live_ranges().for_each(no_gc, |range| {
1507            // Step 5.1: For each live range whose start node is parent and start offset is
1508            // greater than child’s index: increase its start offset by count.
1509            if &*range.start_container() == parent && range.start_offset() > *child_index {
1510                range.set_start_without_reporting(parent, range.start_offset() + count);
1511            }
1512            // Step 5.2: For each live range whose end node is parent and end offset is
1513            // greater than child’s index: increase its end offset by count.
1514            if &*range.end_container() == parent && range.end_offset() > *child_index {
1515                range.set_end_without_reporting(parent, range.end_offset() + count);
1516            }
1517        });
1518    }
1519
1520    /// <https://dom.spec.whatwg.org/#live-range-pre-remove-steps> steps 4-7.
1521    pub(crate) fn live_range_pre_remove_steps(
1522        &self,
1523        no_gc: &NoGC,
1524        removed_node: &Node,           // "node" in the specification
1525        parent_of_removed_node: &Node, // "parent" in the specification
1526        index_of_removed_node: &mut dyn FnMut() -> u32, // "index" in the specification
1527    ) {
1528        if self.live_ranges().is_empty() {
1529            return;
1530        }
1531
1532        // Step 1. Let parent be node’s parent.
1533        // Note: This is `parent_of_removed_node`.
1534        // Step 2. Assert: parent is non-null.
1535        // Note: Cannot be null.
1536
1537        // Step 3. Let index be node’s index.
1538        // Note: This is `index_of_removed_node`.
1539
1540        self.live_ranges().for_each(no_gc, |range| {
1541            // Step 4: For each live range whose start node is an inclusive descendant of
1542            // node, set its start to (parent, index).
1543            let start_container = range.start_container();
1544            if removed_node.is_inclusive_ancestor_of(&start_container) {
1545                range.set_start_without_reporting(parent_of_removed_node, index_of_removed_node());
1546            }
1547            // Step 5: For each live range whose end node is an inclusive descendant of node,
1548            // set its end to (parent, index).
1549            if removed_node.is_inclusive_ancestor_of(&range.end_container()) {
1550                range.set_end_without_reporting(parent_of_removed_node, index_of_removed_node());
1551            }
1552
1553            // Step 6: For each live range whose start node is parent and start offset is
1554            // greater than index, decrease its start offset by 1.
1555            if &*range.start_container() == parent_of_removed_node &&
1556                range.start_offset() > index_of_removed_node()
1557            {
1558                range.set_start_without_reporting(parent_of_removed_node, range.start_offset() - 1);
1559            }
1560            // Step 7: For each live range whose end node is parent and end offset is greater than
1561            // index, decrease its end offset by 1.
1562            if &*range.end_container() == parent_of_removed_node &&
1563                range.end_offset() > index_of_removed_node()
1564            {
1565                range.set_end_without_reporting(parent_of_removed_node, range.end_offset() - 1);
1566            }
1567        });
1568    }
1569
1570    /// <https://dom.spec.whatwg.org/#dom-node-normalize> Steps 6.1-6.4.
1571    ///
1572    /// - `parent`: The parent of both other node arguments.
1573    /// - `node`: The node that text is being merged into.
1574    /// - `current_node`: The node which has text being merged into `node` and will be
1575    ///   removed from the DOM.
1576    /// - `current_node_index`: The index of `current_node` in `parent`.
1577    /// - `length`: The length of the text content in `node`, its original length plus
1578    ///   the length of all content that has already been merged from siblings before
1579    ///   `current_node`.
1580    pub(crate) fn live_range_normalization_steps(
1581        &self,
1582        no_gc: &NoGC,
1583        parent: &Node,
1584        node: &Node,
1585        current_node: &Node,
1586        current_node_index: &dyn Fn() -> u32,
1587        length: u32,
1588    ) {
1589        if self.live_ranges().is_empty() {
1590            return;
1591        }
1592
1593        self.live_ranges().for_each(no_gc, |range| {
1594            // Step 6.1: For each live range whose start node is currentNode: add length to
1595            // its start offset and set its start node to node.
1596            if &*range.start_container() == current_node {
1597                range.set_start_without_reporting(node, range.start_offset() + length);
1598            }
1599            // Step 6.2: For each live range whose end node is currentNode: add length to its
1600            // end offset and set its end node to node.
1601            if &*range.end_container() == current_node {
1602                range.set_end_without_reporting(node, range.end_offset() + length);
1603            }
1604
1605            // Step 6.3: For each live range whose start node is currentNode’s parent and
1606            // start offset is currentNode’s index: set its start node to node and its start
1607            // offset to length.
1608            if &*range.start_container() == parent && range.start_offset() == current_node_index() {
1609                range.set_start_without_reporting(node, length);
1610            }
1611            // Step 6.4: For each live range whose end node is currentNode’s parent and end
1612            // offset is currentNode’s index: set its end node to node and its end offset to
1613            // length.
1614            if &*range.end_container() == parent && range.end_offset() == current_node_index() {
1615                range.set_end_without_reporting(node, length);
1616            }
1617        });
1618    }
1619
1620    /// <https://dom.spec.whatwg.org/#concept-cd-replace> steps 8-11.
1621    pub(crate) fn live_range_replace_data_steps(
1622        &self,
1623        no_gc: &NoGC,
1624        node: &Node,
1625        offset: u32,
1626        removed_code_units: u32,
1627        added_code_units: &mut dyn FnMut() -> u32,
1628    ) {
1629        if self.live_ranges().is_empty() {
1630            return;
1631        }
1632
1633        self.live_ranges().for_each(no_gc, |range| {
1634            // Step 8: For each live range whose start node is node and start offset is
1635            // greater than offset but less than or equal to offset + count: set its start
1636            // offset to offset.
1637            let start_container = range.start_container();
1638            let start_offset = range.start_offset();
1639            if &*start_container == node &&
1640                start_offset > offset &&
1641                start_offset <= offset.saturating_add(removed_code_units)
1642            {
1643                range.set_start_without_reporting(node, offset);
1644            }
1645            // Step 9: For each live range whose end node is node and end offset is
1646            // greater than offset but less than or equal to offset + count: set its end
1647            // offset to offset.
1648            let end_container = range.end_container();
1649            let end_offset = range.end_offset();
1650            if &*end_container == node &&
1651                end_offset > offset &&
1652                end_offset <= offset.saturating_add(removed_code_units)
1653            {
1654                range.set_end_without_reporting(node, offset);
1655            }
1656            // Step 10: For each live range whose start node is node and start offset is
1657            // greater than offset + count: increase its start offset by data’s length and
1658            // decrease it by count.
1659            if &*start_container == node && start_offset > offset.saturating_add(removed_code_units)
1660            {
1661                range.set_start_without_reporting(
1662                    node,
1663                    start_offset + added_code_units() - removed_code_units,
1664                );
1665            }
1666            // Step 11: For each live range whose end node is node and end offset is
1667            // greater than offset + count: increase its end offset by data’s length and
1668            // decrease it by count.
1669            if &*end_container == node && end_offset > offset.saturating_add(removed_code_units) {
1670                range.set_end_without_reporting(
1671                    node,
1672                    end_offset + added_code_units() - removed_code_units,
1673                );
1674            }
1675        });
1676    }
1677
1678    /// <https://dom.spec.whatwg.org/#concept-text-split> steps 7.2-7.5.
1679    pub(crate) fn live_range_text_split_steps(
1680        &self,
1681        no_gc: &NoGC,
1682        parent: &Node,
1683        node: &Node,
1684        offset: u32,
1685        new_node: &Node,
1686    ) {
1687        if self.live_ranges().is_empty() {
1688            return;
1689        }
1690
1691        let node_index = LazyCell::new(|| node.index());
1692        self.live_ranges().for_each(no_gc, |range| {
1693            // Step 7.2. For each live range whose start node is node and start offset is
1694            // greater than offset, set its start node to newNode and decrease its start
1695            // offset by offset.
1696            if &*range.start_container() == node && range.start_offset() > offset {
1697                range.set_start_without_reporting(new_node, range.start_offset() - offset);
1698            }
1699            // Step 7.3. For each live range whose end node is node and end offset is
1700            // greater than offset, set its end node to newNode and decrease its end
1701            // offset by offset.
1702            if &*range.end_container() == node && range.end_offset() > offset {
1703                range.set_end_without_reporting(new_node, range.end_offset() - offset);
1704            }
1705
1706            // Step 7.4. For each live range whose start node is parent and start offset
1707            // is equal to the index of node plus 1, increase its start offset by 1.
1708            if &*range.start_container() == parent && range.start_offset() == *node_index + 1 {
1709                range.set_start_without_reporting(parent, range.start_offset() + 1);
1710            }
1711
1712            // Step 7.5. For each live range whose end node is parent and end offset is
1713            // equal to the index of node plus 1, increase its end offset by 1.
1714            if &*range.end_container() == parent && range.end_offset() == *node_index + 1 {
1715                range.set_end_without_reporting(parent, range.end_offset() + 1);
1716            }
1717        });
1718    }
1719}