Skip to main content

lexical_ui/selection/
utils.rs

1//! `packages/lexical-selection/src/utils.ts`: the model part, with the
2//! computed styles read from the root element
3//! ([`crate::RootElement::computed_style`]). The DOM ranges and rects
4//! (`createDOMRange`, `createRectsFromDOMRange`) need a DOM.
5
6use crate::node::NodeRef;
7use crate::set_dom_style::{StyleObject, get_style_object_from_css};
8
9/// The properties of a computed style (`CSSStyleDeclaration`) that
10/// `@lexical/selection` reads: `direction` and `writingMode`.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct ComputedStyle {
13    /// `direction`: `ltr` or `rtl`.
14    pub direction: String,
15    /// `writingMode`: `horizontal-tb`, `vertical-rl`...
16    pub writing_mode: String,
17}
18
19impl Default for ComputedStyle {
20    /// `ltr` and `horizontal-tb`, CSS's initial values.
21    fn default() -> Self {
22        Self {
23            direction: "ltr".to_owned(),
24            writing_mode: "horizontal-tb".to_owned(),
25        }
26    }
27}
28
29/// `$getComputedStyleForElement(element)`: the computed style of the
30/// element's rendered DOM, which the editor's root element reports
31/// ([`crate::RootElement::computed_style`], as JS reads
32/// `getComputedStyle(editor.getElementByKey(key))`). `None` without a root
33/// element, an active editor, or a style for the node.
34pub fn get_computed_style_for_element(element: &NodeRef) -> Option<ComputedStyle> {
35    let editor = crate::updates::get_active_editor()?;
36    editor
37        .get_root_element()?
38        .0
39        .computed_style(element.get_key())
40}
41
42/// `$getComputedStyleForParent(node)`: the computed style of the node's
43/// parent, or of the root itself. A named slot's value and a detached
44/// node have no parent, so `None`.
45pub fn get_computed_style_for_parent(node: &NodeRef) -> Option<ComputedStyle> {
46    let parent = if node.is_root() {
47        Some(node.clone())
48    } else {
49        node.get_parent()
50    };
51    parent.and_then(|parent| get_computed_style_for_element(&parent))
52}
53
54/// `$isParentRTL(node)`: whether the computed style of the node's parent
55/// has `direction: rtl`.
56pub fn is_parent_rtl(node: &NodeRef) -> bool {
57    get_computed_style_for_parent(node).is_some_and(|styles| styles.direction == "rtl")
58}
59
60/// `getStyleObjectFromRawCSS(css)`: deprecated upstream, an alias of
61/// `getStyleObjectFromCSS`.
62pub fn get_style_object_from_raw_css(css: &str) -> StyleObject {
63    get_style_object_from_css(css)
64}
65
66/// `getCSSFromStyleObject(styles)`: `prop: value;` for each property in
67/// order, the inverse of `getStyleObjectFromCSS`. An empty property name is
68/// left out.
69pub fn get_css_from_style_object(styles: &StyleObject) -> String {
70    let mut css = String::new();
71    for (style, value) in styles.iter() {
72        if !style.is_empty() {
73            css.push_str(style);
74            css.push_str(": ");
75            css.push_str(value);
76            css.push(';');
77        }
78    }
79    css
80}
81
82/// A rectangle as a `DOMRect` describes it (`left`, `top`, `right`,
83/// `bottom`, `width`, `height`): what [`filter_selection_rects`] and
84/// `@lexical/utils`' `dedupeSelectionRects` read of a selection's rects.
85#[derive(Clone, Copy, Debug, PartialEq)]
86pub struct SelectionRect {
87    pub left: f64,
88    pub top: f64,
89    pub right: f64,
90    pub bottom: f64,
91    pub width: f64,
92    pub height: f64,
93}
94
95impl SelectionRect {
96    /// A rect at `left`, `top` of the size `width` by `height`. A measured
97    /// rect whose edges and size disagree by rounding sets the fields
98    /// directly.
99    pub fn new(left: f64, top: f64, width: f64, height: f64) -> Self {
100        Self {
101            left,
102            top,
103            right: left + width,
104            bottom: top + height,
105            width,
106            height,
107        }
108    }
109}
110
111/// The filtering half of `createRectsFromDOMRange(editor, range)`: sorts a
112/// range's client rects (`range.getClientRects()`) from top left to bottom
113/// right, as rows when their tops are within 3 of each other, then drops
114/// each rect contained in the one kept before it and each that spans the
115/// root (its width plus `root_padding`, the root's horizontal padding,
116/// equals `root_width`, the width of the root's bounding rect). The DOM
117/// half, measuring the range and the root, is the platform's.
118pub fn filter_selection_rects(
119    rects: &[SelectionRect],
120    root_width: f64,
121    root_padding: f64,
122) -> Vec<SelectionRect> {
123    // `Array.prototype.sort` is stable; an insertion sort is too, and takes
124    // the 3-point tolerance, which is not a total order, without panicking.
125    let mut selection_rects: Vec<SelectionRect> = Vec::with_capacity(rects.len());
126    for rect in rects {
127        let mut i = selection_rects.len();
128        while i > 0 && sorts_before(rect, &selection_rects[i - 1]) {
129            i -= 1;
130        }
131        selection_rects.insert(i, *rect);
132    }
133    let mut prev_rect: Option<SelectionRect> = None;
134    let mut i = 0;
135    while i < selection_rects.len() {
136        let selection_rect = selection_rects[i];
137        // Only discard a rect whose entire area is already covered.
138        let is_contained_rect = prev_rect.is_some_and(|prev| {
139            prev.top <= selection_rect.top
140                && prev.bottom >= selection_rect.bottom
141                && prev.left <= selection_rect.left
142                && prev.right >= selection_rect.right
143        });
144        // Exclude selections that span the entire element
145        let selection_spans_element = selection_rect.width + root_padding == root_width;
146        if is_contained_rect || selection_spans_element {
147            selection_rects.remove(i);
148            continue;
149        }
150        prev_rect = Some(selection_rect);
151        i += 1;
152    }
153    selection_rects
154}
155
156/// Whether `createRectsFromDOMRange`'s comparator puts `a` before `b`:
157/// by `left` when the tops are within 3, by `top` otherwise.
158fn sorts_before(a: &SelectionRect, b: &SelectionRect) -> bool {
159    let top = a.top - b.top;
160    // Some rects match position closely, but not perfectly,
161    // so we give a 3px tolerance.
162    if top.abs() <= 3.0 {
163        return a.left - b.left < 0.0;
164    }
165    top < 0.0
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    fn sides(rects: &[SelectionRect]) -> Vec<[f64; 4]> {
173        rects
174            .iter()
175            .map(|r| [r.left, r.top, r.width, r.height])
176            .collect()
177    }
178
179    /// The rects JS's `createRectsFromDOMRange` returns for these client
180    /// rects (a root 500 wide with a padding of 8 and 12), recorded by
181    /// running it with a stubbed range and root.
182    #[test]
183    fn filter_selection_rects_matches_create_rects_from_dom_range() {
184        let r = SelectionRect::new;
185        let rects = [
186            r(50.0, 22.0, 30.0, 18.0),
187            r(10.0, 0.0, 40.0, 18.0),
188            r(5.0, 2.0, 20.0, 18.0),
189            r(0.0, 20.0, 480.0, 18.0),
190            r(12.0, 4.0, 10.0, 10.0),
191            r(60.0, 40.0, 10.0, 18.0),
192            r(12.0, 1.0, 10.0, 10.0),
193        ];
194        assert_eq!(
195            sides(&filter_selection_rects(&rects, 500.0, 20.0)),
196            [
197                [5.0, 2.0, 20.0, 18.0],
198                [10.0, 0.0, 40.0, 18.0],
199                [50.0, 22.0, 30.0, 18.0],
200                [60.0, 40.0, 10.0, 18.0],
201            ]
202        );
203        let rects = [
204            r(10.0, 0.0, 100.0, 20.0),
205            r(20.0, 5.0, 50.0, 10.0),
206            r(200.0, 1.0, 10.0, 10.0),
207            r(100.0, 0.0, 30.0, 20.0),
208        ];
209        assert_eq!(
210            sides(&filter_selection_rects(&rects, 500.0, 20.0)),
211            [
212                [10.0, 0.0, 100.0, 20.0],
213                [100.0, 0.0, 30.0, 20.0],
214                [200.0, 1.0, 10.0, 10.0],
215                [20.0, 5.0, 50.0, 10.0],
216            ]
217        );
218    }
219}