Skip to main content

script/drag/
document_selection_drag.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::cmp::Ordering;
6
7use js::context::{JSContext, NoGC};
8use layout_api::SegmentGranularity;
9use rustc_hash::FxHashMap;
10use script_bindings::dom::UnrootedDom;
11use script_bindings::inheritance::Castable;
12use script_bindings::root::{Dom, DomRoot};
13use style::values::computed::UserSelect;
14
15use crate::dom::inputevent::HitTestResult;
16use crate::dom::selection::UsedUserSelect;
17use crate::dom::selection_range::{RootedSelectionBoundary, SelectionRange};
18use crate::dom::{Document, Element, Node};
19
20/// Information stored when the start of the drag was triggered via double or triple
21/// click which highlighted a segment of text.
22#[derive(JSTraceable, MallocSizeOf)]
23#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
24pub(crate) struct DocumentDragSegment {
25    /// The granularity of the selection drag.
26    #[no_trace]
27    pub granularity: SegmentGranularity,
28    /// The original segment that was highlighted at the start of the drag.
29    pub range: SelectionRange,
30}
31
32#[derive(JSTraceable, MallocSizeOf)]
33#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
34pub(crate) struct DocumentSelectionDragHandler {
35    /// The [`Document`] of this [`DocumentSelectionDragHandler`].
36    document: Dom<Document>,
37    /// The node with `user-select: contain` that this selection must not leave, if any.
38    user_select_contain_node_for_selection_anchor: Option<Dom<Node>>,
39    /// Information when the start of the drag highlighted a segment of text.
40    segment: Option<DocumentDragSegment>,
41}
42
43impl DocumentSelectionDragHandler {
44    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
45    pub(crate) fn new(
46        document: &Document,
47        user_select_contain_node: Option<&Node>,
48        segment: Option<DocumentDragSegment>,
49    ) -> Self {
50        Self {
51            document: Dom::from_ref(document),
52            user_select_contain_node_for_selection_anchor: user_select_contain_node
53                .map(Dom::from_ref),
54            segment,
55        }
56    }
57
58    pub(crate) fn still_connected(&self) -> bool {
59        self.user_select_contain_node_for_selection_anchor
60            .as_ref()
61            .is_none_or(|node| node.is_connected())
62    }
63
64    /// Process a mouse move event on this [`DocumentSelectionDragHandler`].
65    ///
66    /// Returns `true` if the drag should continue and `false` otherwise.
67    pub(crate) fn moved(&self, cx: &mut JSContext, hit_test_result: &HitTestResult) -> bool {
68        let Some(selection) = self.document.selection() else {
69            return true;
70        };
71
72        let Some(boundary) = hit_test_result.dom_position_for_selection.as_ref() else {
73            return true;
74        };
75
76        let adjust_for_user_select =
77            |no_gc: &NoGC,
78             anchor: Option<&RootedSelectionBoundary>,
79             focus: RootedSelectionBoundary| {
80                adjust_focus_for_user_select(
81                    no_gc,
82                    anchor,
83                    focus,
84                    self.user_select_contain_node_for_selection_anchor
85                        .as_deref(),
86                )
87            };
88
89        let Some(segment) = &self.segment else {
90            selection.collapse_or_extend_to_dom_position(
91                cx,
92                &adjust_for_user_select(
93                    cx.no_gc(),
94                    selection.composed_anchor_position().as_ref(),
95                    boundary.clone(),
96                ),
97            );
98            return true;
99        };
100
101        let (start, end) = self
102            .document
103            .window()
104            .query_text_segment(
105                cx,
106                &boundary.container,
107                boundary.utf32_offset(),
108                segment.granularity,
109            )
110            .unwrap_or_else(|| (boundary.clone(), boundary.clone()));
111
112        let original_start = segment.range.start.rooted();
113        let original_end = segment.range.end.rooted();
114        let (anchor, focus) = if boundary.cmp(cx.no_gc(), &original_start) == Ordering::Less {
115            // If the drag position is before the original starting point, then the newly
116            // selected text extends from the old end to the start of the drag segment.
117            (original_end, start)
118        } else if boundary.cmp(cx.no_gc(), &original_end) == Ordering::Greater {
119            // If the drag position is after the original end, then the newly selected
120            // text extends from the original start to the end of the drag segment.
121            (original_start, end)
122        } else {
123            // This is when we are dragging within the original segment and want to keep
124            // it selected.
125            (original_start, original_end)
126        };
127
128        let focus = adjust_for_user_select(cx.no_gc(), Some(&anchor), focus);
129        selection.set_anchor_and_focus(cx, &anchor, &focus);
130        true
131    }
132}
133
134/// Adjust the range boundary for the selection anchor (start of a drag gesture)
135/// based on [`user-select`] of the container node and of its ancestors.
136///
137/// Returns `None` if no new drag gesture should be started (`user-select: none`), or:
138///
139/// * The new anchor container
140/// * The new anchor offset
141/// * The node with `user-select: contain` that the selection must not leave, if any
142///
143/// [`user-select`]: https://drafts.csswg.org/css-ui-4/#content-selection
144pub(crate) fn adjust_anchor_for_user_select(
145    no_gc: &NoGC,
146    mut anchor_candidate: RootedSelectionBoundary,
147) -> Option<(RootedSelectionBoundary, Option<DomRoot<Node>>)> {
148    let mut cache = Default::default();
149    if anchor_candidate
150        .container
151        .used_user_select(no_gc, &mut cache) ==
152        UsedUserSelect::None
153    {
154        return None;
155    }
156
157    // The nearest inclusive ancestor with `user-select: contain`
158    let mut nearest_with_user_select_contain = None;
159
160    // The furthest inclusive ancestor with `user-select: all`, as long as all intermediate
161    // inclusive ancestors also have `user-select: all`.
162    let mut furthest_with_user_select_all = None;
163    let mut each_so_far_has_user_select_all = true;
164
165    for ancestor in anchor_candidate
166        .container
167        .inclusive_ancestors_in_flat_tree_unrooted(no_gc)
168    {
169        match ancestor.used_user_select(no_gc, &mut cache) {
170            UsedUserSelect::Text | UsedUserSelect::None => {
171                each_so_far_has_user_select_all = false;
172            },
173            UsedUserSelect::Contain => {
174                nearest_with_user_select_contain = Some(ancestor.as_rooted());
175                // `each_so_far_has_user_select_all` should be set to false but will no
176                // longer be used after this break.
177                break;
178            },
179            UsedUserSelect::All => {
180                if each_so_far_has_user_select_all {
181                    furthest_with_user_select_all = Some(ancestor);
182                }
183            },
184        }
185    }
186
187    if let Some(atomic) = furthest_with_user_select_all {
188        // TODO: to properly implement `user-select: all` we should keep track of two potential
189        // start boundaries: one with offset zero as is done here, and another with offset
190        // `Node::len(atomic)` representing the end of that node. The latter would be used
191        // when the range is backwards (if the end boundary is outside of and before `atomic`)
192        // so that `atomic` would be entirely selected regardless of the range direction.
193        anchor_candidate = RootedSelectionBoundary::start_of(&atomic);
194    }
195    Some((anchor_candidate, nearest_with_user_select_contain))
196}
197
198/// Adjust the range boundary for the selection focus (end of a drag gesture)
199/// based on [`user-select`] of the container node and of its ancestors.
200///
201/// [`user-select`]: https://drafts.csswg.org/css-ui-4/#content-selection
202pub(crate) fn adjust_focus_for_user_select(
203    no_gc: &NoGC,
204    anchor: Option<&RootedSelectionBoundary>,
205    mut focus_candidate: RootedSelectionBoundary,
206    user_select_contain_node_for_anchor: Option<&Node>,
207) -> RootedSelectionBoundary {
208    let mut cache = Default::default();
209    let mut user_select_contain_node_for_anchor_is_inclusive_ancestor = false;
210    let mut each_so_far_has_user_select_all = true;
211    let mut furthest_node_with_user_select_all = None;
212    let mut each_so_far_has_user_select_none = true;
213    // Either `user-select: contain` the selection starts outside of, or `user-select: none`
214    let mut furthest_node_to_avoid = None;
215
216    for inclusive_ancestor in focus_candidate
217        .container
218        .inclusive_ancestors_in_flat_tree_unrooted(no_gc)
219    {
220        if user_select_contain_node_for_anchor == Some(&**inclusive_ancestor) {
221            user_select_contain_node_for_anchor_is_inclusive_ancestor = true
222        }
223        match inclusive_ancestor.used_user_select(no_gc, &mut cache) {
224            UsedUserSelect::Text => {
225                each_so_far_has_user_select_all = false;
226                each_so_far_has_user_select_none = false;
227            },
228            UsedUserSelect::None => {
229                each_so_far_has_user_select_all = false;
230                if each_so_far_has_user_select_none {
231                    furthest_node_to_avoid = Some(inclusive_ancestor)
232                }
233            },
234            UsedUserSelect::Contain => {
235                each_so_far_has_user_select_all = false;
236                each_so_far_has_user_select_none = false;
237                if !user_select_contain_node_for_anchor_is_inclusive_ancestor {
238                    furthest_node_to_avoid = Some(inclusive_ancestor)
239                }
240            },
241            UsedUserSelect::All => {
242                each_so_far_has_user_select_none = false;
243                if each_so_far_has_user_select_all {
244                    furthest_node_with_user_select_all = Some(inclusive_ancestor)
245                }
246            },
247        }
248        if !each_so_far_has_user_select_all &&
249            !each_so_far_has_user_select_none &&
250            user_select_contain_node_for_anchor_is_inclusive_ancestor
251        {
252            // Nothing else to find in ancestors
253            break;
254        }
255    }
256    let selection_is_backward = || {
257        anchor.is_some_and(|anchor| {
258            anchor.compare_dom_positions(no_gc, &focus_candidate) == Some(Ordering::Greater)
259        })
260    };
261    if let Some(contain_for_anchor) = user_select_contain_node_for_anchor &&
262        !user_select_contain_node_for_anchor_is_inclusive_ancestor
263    {
264        // `focus_container` is outside of `contain_for_anchor`:
265        // find the closest position within `contain_for_anchor`: either its start or end
266        focus_candidate = if selection_is_backward() {
267            RootedSelectionBoundary::start_of(contain_for_anchor)
268        } else {
269            RootedSelectionBoundary::end_of(contain_for_anchor)
270        };
271    } else if let Some(focus_ancestor_to_avoid) = furthest_node_to_avoid {
272        focus_candidate = if selection_is_backward() {
273            RootedSelectionBoundary::end_of(&focus_ancestor_to_avoid)
274        } else {
275            RootedSelectionBoundary::start_of(&focus_ancestor_to_avoid)
276        };
277    } else if let Some(with_user_select_all) = furthest_node_with_user_select_all {
278        // anchor was snapped to the start of the `user-select: all` element,
279        // so snap the focus to the end unconditionally
280        focus_candidate = RootedSelectionBoundary::end_of(&with_user_select_all);
281    }
282
283    focus_candidate
284}
285
286impl Node {
287    /// Returns the used value of <https://drafts.csswg.org/css-ui-4/#propdef-user-select>.
288    ///
289    /// It is the caller’s responsibility to ensure that style is up to date for this node and
290    /// its (flat tree) ancestors.
291    ///
292    /// `cache` can be initialized with `Default::default()`, and should be shared across calls
293    /// for nodes that may share some (flat tree) ancestors.
294    pub(crate) fn used_user_select<'no_gc>(
295        &self,
296        no_gc: &'no_gc NoGC,
297        cache: &mut FxHashMap<UnrootedDom<'no_gc, Node>, UsedUserSelect>,
298    ) -> UsedUserSelect {
299        let cache_key = UnrootedDom::from_ref(self, no_gc);
300        if let Some(&used_value) = cache.get(&cache_key) {
301            return used_value;
302        }
303        // https://html.spec.whatwg.org/multipage/#inert
304        // > When a node is inert: Text selection functionality must act as if
305        // > the 'user-select' CSS property were set to 'none'.
306        if self.is_inert_without_reflow() {
307            cache.insert(cache_key, UsedUserSelect::None);
308            return UsedUserSelect::None;
309        }
310        // > The used value is the same as the computed value, except:
311        // >
312        // > 1. on editable elements where the used value is always `contain`
313        // >    regardless of the computed value
314        // > 2. when the computed value is `auto`, in which case the used value
315        // >    is one of the other values as defined below
316        // >
317        // > For the purpose of this specification, an editable element is
318        // > either an editing host or a mutable form control with textual
319        // > content, such as textarea.
320        //
321        // For form controls, we handle selection separately without looking at
322        // `user-select`.
323        if self.is_editing_host() {
324            let used_value = UsedUserSelect::Contain;
325            cache.insert(cache_key, used_value);
326            return used_value;
327        }
328        let computed_value = self
329            .downcast()
330            .and_then(Element::computed_user_select)
331            // Non-element nodes and unstyled elements: use the initial value
332            .unwrap_or(UserSelect::Auto);
333        let used_value = match computed_value {
334            UserSelect::Text => UsedUserSelect::Text,
335            UserSelect::None => UsedUserSelect::None,
336            UserSelect::Contain => UsedUserSelect::Contain,
337            UserSelect::All => UsedUserSelect::All,
338            UserSelect::Auto => {
339                let parent_used_value = self
340                    .parent_in_flat_tree(no_gc)
341                    .into_parent()
342                    .map(|parent| parent.used_user_select(no_gc, cache));
343                // > The used value of `auto` is determined as follows:
344                // > * On the `::before` and `::after` pseudo-elements, the used value is `none`
345                // > * If the element is an editable element, the used value is `contain`
346                // > * Otherwise, if the used value of `user-select` on the parent of this element
347                // >   is `all`, the used value is `all`
348                // > * Otherwise, if the used value of `user-select` on the parent of this element
349                // >   is `none`, the used value is `none`
350                // > * Otherwise, the used value is `text`
351                match parent_used_value {
352                    Some(UsedUserSelect::All) => UsedUserSelect::All,
353                    Some(UsedUserSelect::None) => UsedUserSelect::None,
354                    _ => UsedUserSelect::Text,
355                }
356            },
357        };
358        cache.insert(cache_key, used_value);
359        used_value
360    }
361}