Skip to main content

script/dom/execcommand/contenteditable/
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 js::context::{JSContext, NoGC};
6use script_bindings::inheritance::Castable;
7use script_bindings::str::DOMString;
8
9use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
10use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
11use crate::dom::bindings::codegen::Bindings::RangeBinding::RangeMethods;
12use crate::dom::bindings::root::{DomRoot, UnrootedDom};
13use crate::dom::document::Document;
14use crate::dom::execcommand::basecommand::{
15    BoolOrOptionalString, CommandName, RecordedStateOfCommand,
16};
17use crate::dom::execcommand::commands::fontsize::legacy_font_size_for;
18use crate::dom::html::htmllielement::HTMLLIElement;
19use crate::dom::iterators::{ShadowIncluding, TreeIterator};
20use crate::dom::node::Node;
21use crate::dom::range::Range;
22use crate::dom::selection::Selection;
23use crate::dom::text::Text;
24
25pub(crate) struct ContainedNodes<'a> {
26    range: &'a Range,
27    traversal: TreeIterator,
28}
29
30impl ContainedNodes<'_> {
31    pub(crate) fn next(&mut self, no_gc: &NoGC) -> Option<DomRoot<Node>> {
32        self.traversal
33            .by_ref()
34            .find(|node| self.range.contains(no_gc, node))
35    }
36}
37
38impl Range {
39    /// <https://w3c.github.io/editing/docs/execCommand/#effectively-contained>
40    fn is_effectively_contained_node(&self, no_gc: &NoGC, node: &Node) -> bool {
41        // > A node node is effectively contained in a range range if range is not collapsed,
42        if self.collapsed() {
43            return false;
44        }
45        // > and at least one of the following holds:
46        // > node is range's start node, it is a Text node, and its length is different from range's start offset.
47        let start_container = self.start_container();
48        if *start_container == *node && node.is::<Text>() && node.len() != self.start_offset() {
49            return true;
50        }
51        // > node is range's end node, it is a Text node, and range's end offset is not 0.
52        let end_container = self.end_container();
53        if *end_container == *node && node.is::<Text>() && self.end_offset() != 0 {
54            return true;
55        }
56        // > node is contained in range.
57        if self.contains(no_gc, node) {
58            return true;
59        }
60        // > node has at least one child; and all its children are effectively contained in range;
61        node.children_count() > 0 && node.children().all(|child| self.is_effectively_contained_node(no_gc, &child))
62        // > and either range's start node is not a descendant of node or is not a Text node or range's start offset is zero;
63        && (!node.is_ancestor_of(&start_container) || !start_container.is::<Text>() || self.start_offset() == 0)
64        // > and either range's end node is not a descendant of node or is not a Text node or range's end offset is its end node's length.
65        && (!node.is_ancestor_of(&end_container) || !end_container.is::<Text>() || self.end_offset() == end_container.len())
66    }
67
68    /// The definition of "effectively contained" contains the recursion of
69    /// ancestors of a single fully selected text node. That is to say, that
70    /// if the selection is a fully selected text node <div>[foobar]</div>,
71    /// then the div would also be considered effectively contained. As such,
72    /// we can't use the common ancestor container, since that would be the
73    /// text node only.
74    ///
75    /// Instead, we traverse all the way up to the editing host, which we know
76    /// is sufficient to know to include all contained nodes. That way, we also
77    /// would traverse ancestors such as the parent div.
78    fn ancestor_for_effectively_contained(&self) -> DomRoot<Node> {
79        let ancestor_container = self.CommonAncestorContainer();
80        ancestor_container
81            .editing_host_of()
82            .unwrap_or(ancestor_container)
83    }
84
85    pub(crate) fn first_formattable_contained_node(
86        &self,
87        cx: &mut JSContext,
88    ) -> Option<DomRoot<Node>> {
89        if self.collapsed() {
90            return None;
91        }
92
93        self.ancestor_for_effectively_contained()
94            .traverse_preorder(ShadowIncluding::No)
95            .find(|child| {
96                child.is_formattable(cx) && self.is_effectively_contained_node(cx.no_gc(), child)
97            })
98    }
99
100    pub(crate) fn for_each_effectively_contained_child<Callback: FnMut(&mut JSContext, &Node)>(
101        &self,
102        cx: &mut JSContext,
103        mut callback: Callback,
104    ) {
105        if self.collapsed() {
106            return;
107        }
108
109        // Make sure to keep track of the tree nodes before, since `callback` might modify
110        // the underyling tree and then the iterator would prematurely stop.
111        let children = self
112            .ancestor_for_effectively_contained()
113            .traverse_preorder(ShadowIncluding::No)
114            .collect::<Vec<DomRoot<Node>>>();
115
116        for child in children {
117            if self.is_effectively_contained_node(cx.no_gc(), &child) {
118                callback(cx, &child);
119            }
120        }
121    }
122
123    pub(crate) fn contained_nodes<'a>(
124        &self,
125        no_gc: &'a NoGC,
126    ) -> impl Iterator<Item = UnrootedDom<'a, Node>> {
127        self.CommonAncestorContainer()
128            .traverse_preorder_unrooted(no_gc, ShadowIncluding::No)
129            .filter(|node| self.contains(no_gc, node))
130    }
131
132    pub(crate) fn contained_nodes_rooted(&self) -> ContainedNodes<'_> {
133        ContainedNodes {
134            range: self,
135            traversal: self
136                .CommonAncestorContainer()
137                .traverse_preorder(ShadowIncluding::No),
138        }
139    }
140
141    /// <https://w3c.github.io/editing/docs/execCommand/#block-extend>
142    pub(crate) fn block_extend(&self, cx: &mut JSContext, document: &Document) -> DomRoot<Range> {
143        // Step 1. Let start node, start offset, end node,
144        // and end offset be the start and end nodes and offsets of range.
145        let mut start_node = self.start_container();
146        let mut start_offset = self.start_offset();
147        let mut end_node = self.end_container();
148        let mut end_offset = self.end_offset();
149        // Step 2. If some inclusive ancestor of start node is an li,
150        // set start offset to the index of the last such li in tree order, and set start node to that li's parent.
151        if let Some(li_ancestor) = start_node
152            .inclusive_ancestors_unrooted(cx.no_gc(), ShadowIncluding::No)
153            .find(|ancestor| ancestor.is::<HTMLLIElement>())
154        {
155            start_offset = li_ancestor.index();
156            start_node = li_ancestor
157                .GetParentNode()
158                .expect("Must always have a parent");
159        }
160        // Step 3. If (start node, start offset) is not a block start point, repeat the following steps:
161        if !start_node.is_block_start_point(cx, start_offset as usize) {
162            loop {
163                // Step 3.1. If start offset is zero, set it to start node's index, then set start node to its parent.
164                if start_offset == 0 {
165                    start_offset = start_node.index();
166                    start_node = start_node
167                        .GetParentNode()
168                        .expect("Must always have a parent");
169                } else {
170                    // Step 3.2. Otherwise, subtract one from start offset.
171                    start_offset -= 1;
172                }
173                // Step 3.3. If (start node, start offset) is a block boundary point, break from this loop.
174                if start_node.is_block_boundary_point(cx, start_offset) {
175                    break;
176                }
177            }
178        }
179        // Step 4. While start offset is zero and start node's parent is not null,
180        // set start offset to start node's index, then set start node to its parent.
181        while start_offset == 0 &&
182            let Some(parent) = start_node.GetParentNode()
183        {
184            start_offset = start_node.index();
185            start_node = parent;
186        }
187        // Step 5. If some inclusive ancestor of end node is an li,
188        // set end offset to one plus the index of the last such li in tree order,
189        // and set end node to that li's parent.
190        if let Some(li_ancestor) = end_node
191            .inclusive_ancestors_unrooted(cx.no_gc(), ShadowIncluding::No)
192            .find(|ancestor| ancestor.is::<HTMLLIElement>())
193        {
194            end_offset = 1 + li_ancestor.index();
195            end_node = li_ancestor
196                .GetParentNode()
197                .expect("Must always have a parent");
198        }
199        // Step 6. If (end node, end offset) is not a block end point, repeat the following steps:
200        if !end_node.is_block_end_point(cx, end_offset) {
201            loop {
202                // Step 6.1. If end offset is end node's length, set it to one plus end node's index, then set end node to its parent.
203                if end_offset == end_node.len() {
204                    end_offset = 1 + end_node.index();
205                    end_node = end_node.GetParentNode().expect("Must always have a parent");
206                } else {
207                    // Step 6.2. Otherwise, add one to end offset.
208                    end_offset += 1;
209                }
210                // Step 6.3. If (end node, end offset) is a block boundary point, break from this loop.
211                if end_node.is_block_boundary_point(cx, end_offset) {
212                    break;
213                }
214            }
215        }
216        // Step 7. While end offset is end node's length and end node's parent is not null,
217        // set end offset to one plus end node's index, then set end node to its parent.
218        while end_offset == end_node.len() &&
219            let Some(parent) = end_node.GetParentNode()
220        {
221            end_offset = 1 + end_node.index();
222            end_node = parent;
223        }
224        // Step 8. Let new range be a new range whose start and end nodes and offsets are start node,
225        // start offset, end node, and end offset.
226        let new_range = document.CreateRange(cx);
227        let _ = new_range.SetStart(cx.no_gc(), &start_node, start_offset);
228        let _ = new_range.SetEnd(cx.no_gc(), &end_node, end_offset);
229        // Step 9. Return new range.
230        new_range
231    }
232
233    /// <https://w3c.github.io/editing/docs/execCommand/#record-current-states-and-values>
234    pub(crate) fn record_current_states_and_values(
235        &self,
236        cx: &mut JSContext,
237    ) -> Vec<RecordedStateOfCommand> {
238        // Step 1. Let overrides be a list of (string, string or boolean) ordered pairs, initially empty.
239        //
240        // We return the vec in one go for the relevant values
241
242        // Step 2. Let node be the first formattable node effectively contained in the active range,
243        // or null if there is none.
244        let Some(node) = self.first_formattable_contained_node(cx) else {
245            // Step 3. If node is null, return overrides.
246            return vec![];
247        };
248        // Step 8. Return overrides.
249        let document = node.owner_doc();
250        vec![
251            // Step 4. Add ("createLink", node's effective command value for "createLink") to overrides.
252            RecordedStateOfCommand::for_command_node(cx, CommandName::CreateLink, &node),
253            // Step 5. For each command in the list
254            // "bold", "italic", "strikethrough", "subscript", "superscript", "underline", in order:
255            // if node's effective command value for command is one of its inline command activated values,
256            // add (command, true) to overrides, and otherwise add (command, false) to overrides.
257            RecordedStateOfCommand::for_command_node_with_inline_activated_values(
258                cx,
259                CommandName::Bold,
260                &node,
261            ),
262            RecordedStateOfCommand::for_command_node_with_inline_activated_values(
263                cx,
264                CommandName::Italic,
265                &node,
266            ),
267            RecordedStateOfCommand::for_command_node_with_inline_activated_values(
268                cx,
269                CommandName::Strikethrough,
270                &node,
271            ),
272            RecordedStateOfCommand::for_command_node_with_inline_activated_values(
273                cx,
274                CommandName::Subscript,
275                &node,
276            ),
277            RecordedStateOfCommand::for_command_node_with_inline_activated_values(
278                cx,
279                CommandName::Superscript,
280                &node,
281            ),
282            RecordedStateOfCommand::for_command_node_with_inline_activated_values(
283                cx,
284                CommandName::Underline,
285                &node,
286            ),
287            // Step 6. For each command in the list "fontName", "foreColor", "hiliteColor", in order:
288            // add (command, command's value) to overrides.
289            RecordedStateOfCommand::for_command_node_with_value(
290                cx,
291                CommandName::FontName,
292                &document,
293            ),
294            RecordedStateOfCommand::for_command_node_with_value(
295                cx,
296                CommandName::ForeColor,
297                &document,
298            ),
299            RecordedStateOfCommand::for_command_node_with_value(
300                cx,
301                CommandName::HiliteColor,
302                &document,
303            ),
304            // Step 7. Add ("fontSize", node's effective command value for "fontSize") to overrides.
305            RecordedStateOfCommand::for_command_node(cx, CommandName::FontSize, &node),
306        ]
307    }
308
309    /// <https://w3c.github.io/editing/docs/execCommand/#restore-states-and-values>
310    pub(crate) fn restore_states_and_values(
311        &self,
312        cx: &mut JSContext,
313        selection: &Selection,
314        context_object: &Document,
315        overrides: Vec<RecordedStateOfCommand>,
316    ) {
317        // Step 1. Let node be the first formattable node effectively contained in the active range,
318        // or null if there is none.
319        let mut first_formattable_contained_node = self.first_formattable_contained_node(cx);
320        for override_state in overrides {
321            // Step 2. If node is not null, then for each (command, override) pair in overrides, in order:
322            if let Some(ref node) = first_formattable_contained_node {
323                match override_state.value {
324                    // Step 2.1. If override is a boolean, and queryCommandState(command)
325                    // returns something different from override, take the action for command,
326                    // with value equal to the empty string.
327                    BoolOrOptionalString::Bool(bool_)
328                        if override_state
329                            .command
330                            .current_state(cx, context_object)
331                            .is_some_and(|value| value != bool_) =>
332                    {
333                        override_state.command.execute(
334                            cx,
335                            context_object,
336                            selection,
337                            DOMString::new(),
338                        );
339                    },
340                    BoolOrOptionalString::OptionalString(optional_string) => {
341                        match override_state.command {
342                            // Step 2.3. Otherwise, if override is a string; and command is "createLink";
343                            // and either there is a value override for "createLink" that is not equal to override,
344                            // or there is no value override for "createLink" and node's effective command value
345                            // for "createLink" is not equal to override: take the action for "createLink", with value equal to override.
346                            CommandName::CreateLink => {
347                                let value_override =
348                                    context_object.value_override(&CommandName::CreateLink);
349                                if value_override != optional_string {
350                                    CommandName::CreateLink.execute(
351                                        cx,
352                                        context_object,
353                                        selection,
354                                        optional_string.unwrap_or_default(),
355                                    );
356                                }
357                            },
358                            // Step 2.4. Otherwise, if override is a string; and command is "fontSize";
359                            // and either there is a value override for "fontSize" that is not equal to override,
360                            // or there is no value override for "fontSize" and node's effective command value for "fontSize"
361                            // is not loosely equivalent to override:
362                            CommandName::FontSize => {
363                                let value_override =
364                                    context_object.value_override(&CommandName::FontSize);
365                                if value_override != optional_string ||
366                                    (value_override.is_none() &&
367                                        !CommandName::FontSize.are_loosely_equivalent_values(
368                                            node.effective_command_value(
369                                                cx,
370                                                &CommandName::FontSize,
371                                            )
372                                            .as_ref(),
373                                            optional_string.as_ref(),
374                                        ))
375                                {
376                                    // Step 2.5. Convert override to an integer number of pixels,
377                                    // and set override to the legacy font size for the result.
378                                    let pixels = optional_string
379                                        .and_then(|value| value.parse::<i32>().ok())
380                                        .map(|value| {
381                                            legacy_font_size_for(value as f32, context_object)
382                                        })
383                                        .unwrap_or(DOMString::from_static("7"));
384                                    // Step 2.6. Take the action for "fontSize", with value equal to override.
385                                    CommandName::FontSize.execute(
386                                        cx,
387                                        context_object,
388                                        selection,
389                                        pixels,
390                                    );
391                                }
392                            },
393                            // Step 2.2. Otherwise, if override is a string, and command is neither "createLink" nor "fontSize",
394                            // and queryCommandValue(command) returns something not equivalent to override,
395                            // take the action for command, with value equal to override.
396                            command
397                                if command.current_value(cx, context_object) != optional_string =>
398                            {
399                                command.execute(
400                                    cx,
401                                    context_object,
402                                    selection,
403                                    optional_string.unwrap_or_default(),
404                                );
405                            },
406                            // Step 2.5. Otherwise, continue this loop from the beginning.
407                            _ => {
408                                continue;
409                            },
410                        }
411                    },
412                    // Step 2.5. Otherwise, continue this loop from the beginning.
413                    _ => {
414                        continue;
415                    },
416                }
417                // Step 2.6. Set node to the first formattable node effectively contained in the active range, if there is one.
418                first_formattable_contained_node = self.first_formattable_contained_node(cx);
419            } else {
420                // Step 3. Otherwise, for each (command, override) pair in overrides, in order:
421                // Step 3.1. If override is a boolean, set the state override for command to override.
422                match override_state.value {
423                    BoolOrOptionalString::Bool(bool_) => {
424                        context_object.set_state_override(override_state.command, Some(bool_))
425                    },
426                    // Step 3.2. If override is a string, set the value override for command to override.
427                    BoolOrOptionalString::OptionalString(optional_string) => {
428                        context_object.set_value_override(override_state.command, optional_string)
429                    },
430                }
431            }
432        }
433    }
434}