Skip to main content

script/dom/execcommand/commands/
insertparagraph.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::collections::VecDeque;
6
7use html5ever::local_name;
8use js::context::JSContext;
9use script_bindings::codegen::GenericBindings::SelectionBinding::SelectionMethods;
10use script_bindings::inheritance::Castable;
11
12use crate::dom::Node;
13use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
14use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
15use crate::dom::bindings::codegen::Bindings::RangeBinding::RangeMethods;
16use crate::dom::bindings::codegen::Bindings::TextBinding::TextMethods;
17use crate::dom::bindings::root::DomRoot;
18use crate::dom::comment::Comment;
19use crate::dom::document::Document;
20use crate::dom::element::Element;
21use crate::dom::execcommand::commands::insertlinebreak::execute_insert_line_break_command;
22use crate::dom::execcommand::contenteditable::node::{
23    NodeOrString, is_allowed_child, node_matches_local_name, split_the_parent, wrap_node_list,
24};
25use crate::dom::html::htmlbrelement::HTMLBRElement;
26use crate::dom::iterators::ShadowIncluding;
27use crate::dom::selection::Selection;
28use crate::dom::text::Text;
29
30/// <https://w3c.github.io/editing/docs/execCommand/#the-insertparagraph-command>
31pub(crate) fn execute_insert_paragraph_command(
32    cx: &mut JSContext,
33    document: &Document,
34    selection: &Selection,
35) -> bool {
36    // Step 1. Delete the selection.
37    selection.delete_the_selection(
38        cx,
39        document,
40        Default::default(),
41        Default::default(),
42        Default::default(),
43    );
44    // Step 3. Let node and offset be the active range's start node and offset.
45    let (mut node, mut offset) = selection.start_boundary(cx);
46    // Step 2. If the active range's start node is neither editable
47    // nor an editing host, return true.
48    if !node.is_editable_or_editing_host() {
49        return true;
50    }
51    // Step 4. If node is a Text node, and offset is neither 0 nor the length of node,
52    // call splitText(offset) on node.
53    if offset != 0 &&
54        offset != node.len() &&
55        let Some(text_node) = node.downcast::<Text>() &&
56        text_node.SplitText(cx, offset).is_err()
57    {
58        unreachable!("Must always be able to split");
59    }
60    // Step 5. If node is a Text node and offset is its length,
61    // set offset to one plus the index of node, then set node to its parent.
62    if node.is::<Text>() && offset == node.len() {
63        offset = 1 + node.index();
64        node = node.GetParentNode().expect("Must always have a parent");
65    }
66    // Step 6. If node is a Text or Comment node, set offset to the index of node,
67    // then set node to its parent.
68    if node.is::<Text>() || node.is::<Comment>() {
69        offset = node.index();
70        node = node.GetParentNode().expect("Must always have a parent");
71    }
72    // Step 7. Call collapse(node, offset) on the context object's selection.
73    let _ = selection.Collapse(cx, Some(&node), offset);
74    // Step 8. Let container equal node.
75    let mut container = node.clone();
76    // Step 9. While container is not a single-line container,
77    // and container's parent is editable and in the same editing host as node,
78    // set container to its parent.
79    while !container.is_single_line_container() &&
80        let Some(parent) = container.GetParentNode() &&
81        parent.is_editable(cx) &&
82        parent.same_editing_host(&node)
83    {
84        container = parent;
85    }
86    // Step 10. If container is an editable single-line container in the same editing host as node,
87    // and its local name is "p" or "div":
88    if container.is_editable(cx) &&
89        container.is_single_line_container() &&
90        container.same_editing_host(&node) &&
91        node_matches_local_name!(container, local_name!("p") | local_name!("div"))
92    {
93        // Step 10.1. Let outer container equal container.
94        let mut outer_container = container.clone();
95        // Step 10.2. While outer container is not a dd or dt or li,
96        // and outer container's parent is editable, set outer container to its parent.
97        while !node_matches_local_name!(
98            outer_container,
99            local_name!("dd") | local_name!("dt") | local_name!("li")
100        ) && let Some(parent) = outer_container.GetParentNode() &&
101            parent.is_editable(cx)
102        {
103            outer_container = parent;
104        }
105        // Step 10.3. If outer container is a dd or dt or li, set container to outer container.
106        if node_matches_local_name!(
107            outer_container,
108            local_name!("dd") | local_name!("dt") | local_name!("li")
109        ) {
110            container = outer_container;
111        }
112    }
113    // Step 11. If container is not editable or not in the same editing host as node or is not a single-line container:
114    if !container.is_editable(cx) ||
115        !container.same_editing_host(&node) ||
116        !container.is_single_line_container()
117    {
118        // Step 11.1. Let tag be the default single-line container name.
119        let tag = document.default_single_line_container_name();
120        // Step 11.2. Block-extend the active range, and let new range be the result.
121        let new_range = selection.expect_active_range(cx).block_extend(cx, document);
122        // Step 11.4. Append to node list the first node in tree order that is contained in new range and is an allowed child of "p", if any.
123        let mut node_list = if let Some(eligible_node) = new_range
124            .contained_children(cx.no_gc())
125            .ok()
126            .and_then(|contained_children| {
127                contained_children
128                    .contained_children
129                    .into_iter()
130                    .find(|node| {
131                        is_allowed_child(
132                            NodeOrString::from_node(node, cx.no_gc()),
133                            NodeOrString::String("p".to_owned()),
134                        )
135                    })
136            }) {
137            VecDeque::from([eligible_node])
138        } else {
139            // Step 11.3. Let node list be a list of nodes, initially empty.
140            // Step 11.5. If node list is empty:
141            // Step 11.5.1. If tag is not an allowed child of the active range's start node, return true.
142            if !is_allowed_child(
143                NodeOrString::String(tag.str().to_owned()),
144                NodeOrString::from_node(
145                    &selection.expect_active_range(cx).start_container(),
146                    cx.no_gc(),
147                ),
148            ) {
149                // Instead of true, browsers actually insert a line break instead:
150                // https://github.com/w3c/editing/issues/552
151                return execute_insert_line_break_command(cx, document, selection);
152            }
153            // Step 11.5.2. Set container to the result of calling createElement(tag) on the context object.
154            let container = document.create_element(cx, tag.str());
155            let container = container.upcast::<Node>();
156            // Step 11.5.3. Call insertNode(container) on the active range.
157            if selection
158                .expect_active_range(cx)
159                .InsertNode(cx, container)
160                .is_err()
161            {
162                unreachable!("Must always be able to insert");
163            }
164            // Step 11.5.4. Call createElement("br") on the context object,
165            // and append the result as the last child of container.
166            let br = document.create_element(cx, "br");
167            if container.AppendChild(cx, br.upcast()).is_err() {
168                unreachable!("Must always be able to append");
169            }
170            // Step 11.5.5. Call collapse(container, 0) on the context object's selection.
171            let _ = selection.Collapse(cx, Some(container), 0);
172            // Step 11.5.6. Return true.
173            return true;
174        };
175        // Step 11.6. While the nextSibling of the last member of node list is not null
176        // and is an allowed child of "p", append it to node list.
177        while let Some(next_of_last) = node_list
178            .iter()
179            .last()
180            .and_then(|node| node.GetNextSibling())
181            .filter(|next_of_last| {
182                is_allowed_child(
183                    NodeOrString::from_node(next_of_last, cx.no_gc()),
184                    NodeOrString::String("p".to_owned()),
185                )
186            })
187        {
188            node_list.push_back(next_of_last);
189        }
190        // Step 11.7. Wrap node list, with sibling criteria returning false
191        // and new parent instructions returning the result of calling createElement(tag) on the context object.
192        // Set container to the result.
193        container = wrap_node_list(
194            cx,
195            node_list,
196            |_cx, _| false,
197            |cx| Some(DomRoot::upcast(document.create_element(cx, tag.str()))),
198        )
199        .expect("Must always be able to wrap");
200    }
201    // Step 12. If container's local name is "address", "listing", or "pre":
202    if node_matches_local_name!(
203        container,
204        local_name!("address") | local_name!("listing") | local_name!("pre")
205    ) {
206        // Step 12.1. Let br be the result of calling createElement("br") on the context object.
207        let br = document.create_element(cx, "br");
208        // Step 12.2. Call insertNode(br) on the active range.
209        if selection
210            .expect_active_range(cx)
211            .InsertNode(cx, br.upcast())
212            .is_err()
213        {
214            unreachable!("Must always be able to insert");
215        }
216        // Step 12.3. Call collapse(node, offset + 1) on the context object's selection.
217        let _ = selection.Collapse(cx, Some(&node), offset + 1);
218        // Step 12.4. If br is the last descendant of container,
219        // let br be the result of calling createElement("br") on the context object,
220        // then call insertNode(br) on the active range.
221        if container
222            .children()
223            .last()
224            .is_some_and(|child| *child == *br.upcast())
225        {
226            let br = document.create_element(cx, "br");
227            if selection
228                .expect_active_range(cx)
229                .InsertNode(cx, br.upcast())
230                .is_err()
231            {
232                unreachable!("Must always be able to insert");
233            }
234        }
235        // Step 12.5. Return true.
236        return true;
237    }
238    // Step 13. If container's local name is "li", "dt", or "dd";
239    // and either it has no children or it has a single child and that child is a br:
240    if node_matches_local_name!(
241        container,
242        local_name!("li") | local_name!("dt") | local_name!("dd")
243    ) && (container.children_count() == 0 ||
244        (container.children_count() == 1 &&
245            container
246                .children()
247                .next()
248                .expect("has one child")
249                .is::<HTMLBRElement>()))
250    {
251        // Step 13.1. Split the parent of the one-node list consisting of container.
252        split_the_parent(cx, &[&container]);
253        // Step 13.2. If container has no children,
254        // call createElement("br") on the context object and append the result as the last child of container.
255        if container.children_count() == 0 {
256            let br = document.create_element(cx, "br");
257            if container.AppendChild(cx, br.upcast()).is_err() {
258                unreachable!("Must always be able to append");
259            }
260        }
261        // Step 13.3. If container is a dd or dt,
262        // and it is not an allowed child of any of its ancestors in the same editing host,
263        // set the tag name of container to the default single-line container name and let container be the result.
264        if node_matches_local_name!(container, local_name!("dd") | local_name!("dt")) &&
265            container.is_no_allowed_child_in_same_editing_host(cx.no_gc())
266        {
267            container = container
268                .downcast::<Element>()
269                .expect("Must always be an element")
270                .set_the_tag_name(cx, document.default_single_line_container_name().str());
271        }
272        // Step 13.4. Fix disallowed ancestors of container.
273        container.fix_disallowed_ancestors(cx, document);
274        // Step 13.5. Return true.
275        return true;
276    }
277    // Step 14. Let new line range be a new range whose start is the same as the active range's,
278    // and whose end is (container, length of container).
279    let new_line_range = document.CreateRange(cx);
280    let (start_container, start_offset) = selection.start_boundary(cx);
281    let _ = new_line_range.SetStart(cx.no_gc(), &start_container, start_offset);
282    let _ = new_line_range.SetEnd(cx.no_gc(), &container, container.len());
283    // Step 15. While new line range's start offset is zero and its start node
284    // is not a prohibited paragraph child,
285    // set its start to (parent of start node, index of start node).
286    while new_line_range.start_offset() == 0 &&
287        !new_line_range
288            .start_container()
289            .is_prohibited_paragraph_child()
290    {
291        let start = new_line_range.start_container();
292        let _ = new_line_range.SetStart(
293            cx.no_gc(),
294            &start.GetParentNode().expect("Must always have a parent"),
295            start.index(),
296        );
297    }
298    // Step 16. While new line range's start offset is the length of its start node
299    // and its start node is not a prohibited paragraph child,
300    // set its start to (parent of start node, 1 + index of start node).
301    while new_line_range.start_offset() == new_line_range.start_container().len() &&
302        !new_line_range
303            .start_container()
304            .is_prohibited_paragraph_child()
305    {
306        let start = new_line_range.start_container();
307        let _ = new_line_range.SetStart(
308            cx.no_gc(),
309            &start.GetParentNode().expect("Must always have a parent"),
310            1 + start.index(),
311        );
312    }
313    // Step 17. Let end of line be true if new line range contains either nothing or a single br, and false otherwise.
314    let end_of_line =
315        new_line_range
316            .contained_children(cx.no_gc())
317            .is_ok_and(|contained_children| {
318                let contained_children = contained_children.contained_children;
319                contained_children.is_empty() ||
320                    (contained_children.len() == 1 &&
321                        contained_children[0].is::<HTMLBRElement>())
322            });
323    // Step 18. If the local name of container is "h1", "h2", "h3", "h4", "h5", or "h6",
324    // and end of line is true, let new container name be the default single-line container name.
325    let container_as_element = container
326        .downcast::<Element>()
327        .expect("Must always be an element");
328    let container_name = container_as_element.local_name();
329    let new_container_name = if end_of_line &&
330        matches!(
331            *container_name,
332            local_name!("h1") |
333                local_name!("h2") |
334                local_name!("h3") |
335                local_name!("h4") |
336                local_name!("h5") |
337                local_name!("h6")
338        ) {
339        document
340            .default_single_line_container_name()
341            .str()
342            .to_owned()
343    } else
344    // Step 19. Otherwise, if the local name of container is "dt" and end of line is true, let new container name be "dd".
345    if end_of_line && container_name == &local_name!("dt") {
346        "dd".to_owned()
347    } else
348    // Step 20. Otherwise, if the local name of container is "dd" and end of line is true, let new container name be "dt".
349    if end_of_line && container_name == &local_name!("dd") {
350        "dt".to_owned()
351    } else {
352        // Step 21. Otherwise, let new container name be the local name of container.
353        container_name.to_string()
354    };
355    // Step 22. Let new container be the result of calling createElement(new container name) on the context object.
356    let new_container = document.create_element(cx, &new_container_name);
357    // Step 23. Copy all attributes of container to new container.
358    container_as_element.copy_all_attributes_to_other_element(cx, &new_container);
359    // Step 24. If new container has an id attribute, unset it.
360    new_container.remove_attribute_by_name(cx, &local_name!("id"));
361    // Step 25. Insert new container into the parent of container immediately after container.
362    let new_container_node = DomRoot::upcast(new_container);
363    if container
364        .GetParentNode()
365        .expect("Must always have a parent")
366        .InsertBefore(
367            cx,
368            &new_container_node,
369            container.GetNextSibling().as_deref(),
370        )
371        .is_err()
372    {
373        unreachable!("Must always be able to insert");
374    }
375    // Step 26. Let contained nodes be all nodes contained in new line range.
376    let contained_nodes: Vec<DomRoot<Node>> = new_line_range
377        .contained_nodes(cx.no_gc())
378        .map(|node| node.as_rooted())
379        .collect();
380    // Step 27. Let frag be the result of calling extractContents() on new line range.
381    let Ok(frag) = new_line_range.ExtractContents(cx) else {
382        unreachable!("Must always be able to extract");
383    };
384    let frag_as_node = frag.upcast::<Node>();
385    // Step 28. Unset the id attribute (if any) of each Element descendant of frag
386    // that is not in contained nodes.
387    for descendant in frag_as_node.traverse_preorder(ShadowIncluding::No) {
388        if !contained_nodes.contains(&descendant) &&
389            let Some(descendant) = descendant.downcast::<Element>()
390        {
391            descendant.remove_attribute_by_name(cx, &local_name!("id"));
392        }
393    }
394    // Step 29. Call appendChild(frag) on new container.
395    if new_container_node.AppendChild(cx, frag_as_node).is_err() {
396        unreachable!("Must always be able to append");
397    }
398    // Step 30. While container's lastChild is a prohibited paragraph child,
399    // set container to its lastChild.
400    loop {
401        let Some(last_child) = container.children().last() else {
402            break;
403        };
404        if !last_child.is_prohibited_paragraph_child() {
405            break;
406        }
407        container = last_child;
408    }
409    // Step 31. While new container's lastChild is a prohibited paragraph child,
410    // set new container to its lastChild.
411    let mut new_container_node = new_container_node;
412    loop {
413        let Some(last_child) = new_container_node.children().last() else {
414            break;
415        };
416        if !last_child.is_prohibited_paragraph_child() {
417            break;
418        }
419        new_container_node = last_child;
420    }
421    // Step 32. If container has no visible children,
422    // call createElement("br") on the context object,
423    // and append the result as the last child of container.
424    if container.children().all(|child| child.is_invisible(cx)) {
425        let br = document.create_element(cx, "br");
426        if container.AppendChild(cx, br.upcast()).is_err() {
427            unreachable!("Must always be able to append");
428        }
429    }
430    // Step 33. If new container has no visible children,
431    // call createElement("br") on the context object,
432    // and append the result as the last child of new container.
433    if new_container_node
434        .children()
435        .all(|child| child.is_invisible(cx))
436    {
437        let br = document.create_element(cx, "br");
438        if new_container_node.AppendChild(cx, br.upcast()).is_err() {
439            unreachable!("Must always be able to append");
440        }
441    }
442    // Step 34. Call collapse(new container, 0) on the context object's selection.
443    let _ = selection.Collapse(cx, Some(&new_container_node), 0);
444    // Step 35. Return true.
445    true
446}