Skip to main content

script/dom/execcommand/commands/
indent.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::{HashSet, VecDeque};
6
7use js::context::JSContext;
8use script_bindings::codegen::GenericBindings::NodeBinding::NodeMethods;
9use script_bindings::dom::UnrootedDom;
10use script_bindings::inheritance::Castable;
11
12use crate::dom::bindings::root::DomRoot;
13use crate::dom::document::Document;
14use crate::dom::element::Element;
15use crate::dom::execcommand::contenteditable::node::{
16    NodeOrString, is_allowed_child, wrap_node_list,
17};
18use crate::dom::html::htmllielement::HTMLLIElement;
19use crate::dom::html::htmlolistelement::HTMLOListElement;
20use crate::dom::html::htmlulistelement::HTMLUListElement;
21use crate::dom::node::Node;
22use crate::dom::selection::Selection;
23
24/// <https://w3c.github.io/editing/docs/execCommand/#indent>
25pub(crate) fn indent(
26    cx: &mut JSContext,
27    context_object: &Document,
28    node_list: VecDeque<DomRoot<Node>>,
29) {
30    // Step 1. If node list is empty, do nothing and abort these steps.
31    if node_list.is_empty() {
32        return;
33    }
34
35    // Step 2. Let first node be the first member of node list.
36    let first_node = node_list
37        .front()
38        .expect("Must have a first node by now.")
39        .clone();
40
41    // Step 3. If first node's parent is an ol or ul:
42    if let Some(parent) = first_node.GetParentElement() &&
43        (parent.is::<HTMLOListElement>() || parent.is::<HTMLUListElement>())
44    {
45        // Step 3.1. Let tag be the local name of the parent of first node.
46        let tag = parent.local_name();
47
48        // Step 3.2. Wrap node list,
49        //           with sibling criteria returning true for an HTML element with local name tag and false otherwise,
50        //           and new parent instructions returning the result of calling createElement(tag) on the ownerDocument of first node.
51        wrap_node_list(
52            cx,
53            node_list,
54            |_cx, sibling| {
55                sibling
56                    .downcast::<Element>()
57                    .is_some_and(|sibling| sibling.local_name() == tag)
58            },
59            |cx| {
60                Some(DomRoot::upcast(
61                    first_node.owner_doc().create_element(cx, tag),
62                ))
63            },
64        );
65
66        // Step 3.3. Abort these steps.
67        return;
68    }
69
70    // Step 4. Wrap node list,
71    //         with sibling criteria returning true for a simple indentation element and false otherwise,
72    //         and new parent instructions returning the result of calling createElement("blockquote") on the ownerDocument of first node.
73    //         Let new parent be the result.
74    let new_parent = wrap_node_list(
75        cx,
76        node_list,
77        |_cx, sibling| {
78            sibling
79                .downcast::<Element>()
80                .is_some_and(|sibling| sibling.is_simple_indentation_element())
81        },
82        |cx| {
83            Some(DomRoot::upcast(
84                first_node.owner_doc().create_element(cx, "blockquote"),
85            ))
86        },
87    );
88
89    // Step 5. Fix disallowed ancestors of new parent.
90    if let Some(new_parent) = new_parent {
91        new_parent.fix_disallowed_ancestors(cx, context_object);
92    }
93}
94
95/// <https://w3c.github.io/editing/docs/execCommand/#the-indent-command>
96pub(crate) fn execute_indent_command(
97    cx: &mut JSContext,
98    document: &Document,
99    selection: &Selection,
100) -> bool {
101    let mut active_range = selection
102        .active_range(cx)
103        .expect("Must always have an active range.");
104    // Step 1. Let items be a list of all lis that are inclusive ancestors of the active range's start and/or end node.
105    let items: HashSet<DomRoot<Node>> = active_range
106        .start_container()
107        .ancestors()
108        .chain(active_range.end_container().ancestors())
109        .filter(|ancestor| ancestor.is::<HTMLLIElement>())
110        .collect();
111
112    // Step 2. For each item in items, normalize sublists of item.
113    for item in items {
114        item.normalize_sublists(cx);
115    }
116
117    // Normalizing sublists probably messes up the range
118    active_range = selection
119        .active_range(cx)
120        .expect("Must always have an active range.");
121
122    // Step 3. Block-extend the active range, and let new range be the result.
123    let new_range = active_range.block_extend(cx, document);
124
125    // Step 4. Let node list be a list of nodes, initially empty.
126    let mut node_list: Vec<DomRoot<Node>> = vec![];
127
128    // Step 5. For each node node contained in new range,
129    //         if node is editable and is an allowed child of "div" or "ol"
130    //         and if the last member of node list (if any) is not an ancestor of node,
131    //         append node to node list.
132    let mut contained_nodes = new_range.contained_nodes_rooted();
133    while let Some(node) = contained_nodes.next(cx.no_gc()) {
134        if node.is_editable(cx) &&
135            (is_allowed_child(
136                NodeOrString::Node(UnrootedDom::from_ref(&*node, cx.no_gc())),
137                NodeOrString::String("div".to_owned()),
138            ) || is_allowed_child(
139                NodeOrString::Node(UnrootedDom::from_ref(&*node, cx.no_gc())),
140                NodeOrString::String("ol".to_owned()),
141            )) &&
142            node_list
143                .last()
144                .is_none_or(|last| !last.is_ancestor_of(&node))
145        {
146            node_list.push(node);
147        }
148    }
149
150    // Step 6. If the first visible member of node list is an li whose parent is an ol or ul:
151    if let Some(first_visible_member) = node_list.iter().find(|node| node.is_visible(cx)) &&
152        first_visible_member.is::<HTMLLIElement>() &&
153        let Some(parent) = first_visible_member.GetParentNode() &&
154        (parent.is::<HTMLOListElement>() || parent.is::<HTMLUListElement>())
155    {
156        // Step 6.1. Let sibling be node list's first visible member's previousSibling.
157        let mut sibling = first_visible_member.GetPreviousSibling();
158
159        // Step 6.2. While sibling is invisible, set sibling to its previousSibling.
160        while let Some(ref some_sibling) = sibling &&
161            some_sibling.is_invisible(cx)
162        {
163            sibling = some_sibling.GetPreviousSibling();
164        }
165
166        // Step 6.3. If sibling is an li, normalize sublists of sibling.
167        if let Some(sibling) = sibling &&
168            sibling.is::<HTMLLIElement>()
169        {
170            sibling.normalize_sublists(cx);
171        }
172    }
173
174    // Step 7. While node list is not empty:
175    let mut node_list_iter = node_list.iter().peekable();
176    while node_list_iter.peek().is_some() {
177        // Step 7.1. Let sublist be a list of nodes, initially empty.
178        let mut sublist: VecDeque<DomRoot<Node>> = VecDeque::new();
179
180        // Step 7.2. Remove the first member of node list and append it to sublist.
181        sublist.push_back(
182            node_list_iter
183                .next()
184                .expect("Must always have a next item")
185                .clone(),
186        );
187
188        // Step 7.3. While the first member of node list is the nextSibling of the last member of
189        //           sublist, remove the first member of node list and append it to sublist.
190        while node_list_iter.peek().is_some_and(|node| {
191            sublist
192                .back()
193                .expect("Must always have last element here.")
194                .GetNextSibling()
195                .is_some_and(|next_sibling| &&next_sibling == node)
196        }) {
197            sublist.push_back(
198                node_list_iter
199                    .next()
200                    .expect("Must always have a next item")
201                    .clone(),
202            );
203        }
204
205        // Step 7.4. Indent sublist.
206        indent(cx, document, sublist);
207    }
208
209    // Step 8. Return true.
210    // Note: This isn't in the spec (yet), see https://github.com/w3c/editing/pull/547
211    true
212}