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