Skip to main content

script/dom/execcommand/commands/
insertlinebreak.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;
6use script_bindings::codegen::GenericBindings::NodeBinding::NodeMethods;
7use script_bindings::codegen::GenericBindings::RangeBinding::RangeMethods;
8use script_bindings::codegen::GenericBindings::SelectionBinding::SelectionMethods;
9use script_bindings::inheritance::Castable;
10use script_bindings::str::DOMString;
11use style::values::specified::WhiteSpaceCollapse;
12
13use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
14use crate::dom::bindings::root::DomRoot;
15use crate::dom::document::Document;
16use crate::dom::element::Element;
17use crate::dom::execcommand::contenteditable::node::{
18    NodeOrString, is_allowed_child, move_preserving_ranges,
19};
20use crate::dom::execcommand::contenteditable::selection::SelectionDeletionStripWrappers;
21use crate::dom::html::htmlpreelement::HTMLPreElement;
22use crate::dom::selection::Selection;
23use crate::dom::text::Text;
24
25/// <https://w3c.github.io/editing/docs/execCommand/#the-insertlinebreak-command>
26pub(crate) fn execute_insert_line_break_command(
27    cx: &mut JSContext,
28    document: &Document,
29    selection: &Selection,
30) -> bool {
31    // Step 1. Delete the selection, with strip wrappers false.
32    selection.delete_the_selection(
33        cx,
34        document,
35        Default::default(),
36        SelectionDeletionStripWrappers::NoStrip,
37        Default::default(),
38    );
39
40    // Step 2. If the active range's start node is neither editable nor an editing host, return
41    //         true.
42    let mut active_range = selection
43        .active_range(cx)
44        .expect("Must always have an active range.");
45    if !active_range.start_container().is_editable_or_editing_host() {
46        return true;
47    }
48
49    // Step 3. If the active range's start node is an Element, and "br" is not an allowed child of
50    //         it, return true.
51    if active_range.start_container().is::<Element>() &&
52        !is_allowed_child(
53            NodeOrString::String("br".to_owned()),
54            NodeOrString::from_node(&active_range.start_container(), cx.no_gc()),
55        )
56    {
57        return true;
58    }
59
60    // Step 4. If the active range's start node is not an Element, and "br" is not an allowed child
61    //         of the active range's start node's parent, return true.
62    if !active_range.start_container().is::<Element>() &&
63        !is_allowed_child(
64            NodeOrString::String("br".to_owned()),
65            NodeOrString::from_node(
66                &active_range
67                    .start_container()
68                    .GetParentNode()
69                    .expect("Must always have a parent."),
70                cx.no_gc(),
71            ),
72        )
73    {
74        return true;
75    }
76
77    // Step 5. If the active range's start node is a Text node and its start offset is zero, call
78    //         collapse() on the context object's selection, with first argument equal to the
79    //         active range's start node's parent and second argument equal to the active range's
80    //         start node's index.
81    if active_range.start_container().is::<Text>() && active_range.start_offset() == 0 {
82        if selection
83            .Collapse(
84                cx,
85                active_range.start_container().GetParentNode().as_deref(),
86                active_range.start_container().index(),
87            )
88            .is_err()
89        {
90            unreachable!("Should always be able to collapse the selection.");
91        }
92        active_range = selection
93            .active_range(cx)
94            .expect("Must always have an active range");
95    }
96
97    // Step 6. If the active range's start node is a Text node and its start offset is the length
98    //         of its start node, call collapse() on the context object's selection, with first
99    //         argument equal to the active range's start node's parent and second argument equal
100    //         to one plus the active range's start node's index.
101    if active_range.start_container().is::<Text>() &&
102        active_range.start_offset() == active_range.start_container().len()
103    {
104        if selection
105            .Collapse(
106                cx,
107                active_range.start_container().GetParentNode().as_deref(),
108                1 + active_range.start_container().index(),
109            )
110            .is_err()
111        {
112            unreachable!("Should always be able to collapse the selection.");
113        }
114        active_range = selection
115            .active_range(cx)
116            .expect("Must always have an active range");
117    }
118
119    // Step 7. Let br be the result of calling createElement("br") on the context object.
120    //
121    // Browsers use a newline character for insertion when the CSS style for "white-space"
122    // preserves whitespace (that's the case for "pre", "pre-line" and "pre-wrap"). However,
123    // confusingly they don't do that when the node is exactly a `<pre>`.
124    let start_container = active_range.start_container();
125    let has_preformatted_styling = start_container
126        .downcast::<Element>()
127        // In case the start_container is a text node where we need to insert a "\n"
128        .or(start_container.GetParentElement().as_deref())
129        .filter(|element| !element.is::<HTMLPreElement>())
130        .and_then(|element| element.style(cx))
131        .is_some_and(|style| {
132            let white_space_collapse = style.get_inherited_text().white_space_collapse;
133            white_space_collapse == WhiteSpaceCollapse::Preserve ||
134                white_space_collapse == WhiteSpaceCollapse::PreserveBreaks
135        });
136
137    let newline_node = if has_preformatted_styling {
138        DomRoot::upcast(document.CreateTextNode(cx, DOMString::from_static("\n")))
139    } else {
140        DomRoot::upcast(document.create_element(cx, "br"))
141    };
142
143    // Step 8. Call insertNode(br) on the active range.
144    if active_range.InsertNode(cx, &newline_node).is_err() {
145        unreachable!("The node should always be insertable.");
146    }
147
148    // Step 9. Call collapse() on the context object's selection, with br's parent as the first
149    //         argument and one plus br's index as the second argument.
150    if selection
151        .Collapse(
152            cx,
153            newline_node.GetParentNode().as_deref(),
154            1 + newline_node.index(),
155        )
156        .is_err()
157    {
158        unreachable!("Should always be able to collapse the selection.");
159    }
160
161    active_range = selection
162        .active_range(cx)
163        .expect("Must always have an active range");
164
165    // Step 10. If br is a collapsed line break, call createElement("br") on the context object and
166    //          let extra br be the result, then call insertNode(extra br) on the active range.
167    if newline_node.is_collapsed_line_break(cx) {
168        // Same as above at step 7, we insert a newline character when appropriate
169        let extra_newline_node = if has_preformatted_styling {
170            DomRoot::upcast(document.CreateTextNode(cx, DOMString::from_static("\n")))
171        } else {
172            DomRoot::upcast(document.create_element(cx, "br"))
173        };
174
175        move_preserving_ranges(cx, &extra_newline_node, |cx| {
176            active_range.InsertNode(cx, &extra_newline_node)
177        });
178    }
179
180    // Step 11. Return true.
181    true
182}