Skip to main content

script/dom/
selection_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 crate::dom::abstractrange::BoundaryPoint;
6use crate::dom::bindings::root::Dom;
7use crate::dom::node::Node;
8use crate::dom::range::Range;
9
10/// A selection boundary. This is similar to `BoundaryPoint`, but supports
11/// positions in the composed tree.
12#[derive(Clone, JSTraceable, PartialEq, MallocSizeOf)]
13#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
14pub(crate) struct SelectionBoundary {
15    pub container: Dom<Node>,
16    pub offset: u32,
17}
18
19impl SelectionBoundary {
20    pub(crate) fn new(container: &Node, offset: u32) -> Self {
21        Self {
22            container: Dom::from_ref(container),
23            offset,
24        }
25    }
26}
27
28impl PartialEq<BoundaryPoint> for SelectionBoundary {
29    fn eq(&self, boundary_point: &BoundaryPoint) -> bool {
30        *self.container == *boundary_point.node().get() && self.offset == boundary_point.offset().0
31    }
32}
33
34#[derive(JSTraceable, PartialEq, MallocSizeOf)]
35#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
36pub(crate) struct SelectionRange {
37    pub start: SelectionBoundary,
38    pub end: SelectionBoundary,
39}
40
41impl SelectionRange {
42    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
43    pub(crate) fn new(start: SelectionBoundary, end: SelectionBoundary) -> Self {
44        Self { start, end }
45    }
46
47    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
48    pub(crate) fn collapsed_at(at: SelectionBoundary) -> Self {
49        Self {
50            start: at.clone(),
51            end: at,
52        }
53    }
54
55    pub(crate) fn collapsed(&self) -> bool {
56        self.start == self.end
57    }
58}
59
60impl From<&Range> for SelectionRange {
61    fn from(range: &Range) -> Self {
62        Self::new(
63            SelectionBoundary::new(&range.start_container(), range.start_offset()),
64            SelectionBoundary::new(&range.end_container(), range.end_offset()),
65        )
66    }
67}