script/dom/execcommand/contenteditable/node.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;
6use std::collections::VecDeque;
7use std::ops::Deref;
8
9use cssparser::color::OPAQUE;
10use html5ever::local_name;
11use js::context::{JSContext, NoGC};
12use script_bindings::codegen::GenericBindings::RangeBinding::RangeMethods;
13use script_bindings::inheritance::Castable;
14use style::attr::parse_legacy_color;
15use style::values::specified::box_::DisplayOutside;
16
17use crate::dom::Document;
18use crate::dom::abstractrange::bp_position;
19use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
20use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
21use crate::dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods;
22use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
23use crate::dom::bindings::error::Fallible;
24use crate::dom::bindings::inheritance::NodeTypeId;
25use crate::dom::bindings::root::{DomRoot, DomSlice, UnrootedDom};
26use crate::dom::bindings::str::DOMString;
27use crate::dom::characterdata::CharacterData;
28use crate::dom::element::{AdjacentPosition, Element};
29use crate::dom::execcommand::basecommand::{CommandName, CssPropertyName};
30use crate::dom::execcommand::commands::forecolor::serialize_to_simple_color;
31use crate::dom::html::htmlanchorelement::HTMLAnchorElement;
32use crate::dom::html::htmlbrelement::HTMLBRElement;
33use crate::dom::html::htmlelement::HTMLElement;
34use crate::dom::html::htmlimageelement::HTMLImageElement;
35use crate::dom::html::htmllielement::HTMLLIElement;
36use crate::dom::html::htmlolistelement::HTMLOListElement;
37use crate::dom::html::htmlulistelement::HTMLUListElement;
38use crate::dom::iterators::ShadowIncluding;
39use crate::dom::node::{Node, NodeTraits};
40use crate::dom::text::Text;
41
42pub(crate) enum NodeOrString<'a> {
43 String(String),
44 Node(UnrootedDom<'a, Node>),
45}
46
47impl<'a> NodeOrString<'a> {
48 pub(crate) fn from_node(node: &Node, no_gc: &'a NoGC) -> NodeOrString<'a> {
49 NodeOrString::Node(UnrootedDom::from_ref(node, no_gc))
50 }
51
52 fn as_node(&self) -> Option<UnrootedDom<'a, Node>> {
53 match self {
54 NodeOrString::String(_) => None,
55 NodeOrString::Node(node) => Some(node.clone()),
56 }
57 }
58}
59
60// This is a macro instead of a method on `NodeOrString` since `UnrootedDom::downcast`
61// would result in `element` being a temporary referenced value. Therefore, it wouldn't
62// be possible to return its localname as `&str`. Instead, we need to compare immediately
63// when we have the element referenced, which is why we have to duplicate the `matches!`.
64macro_rules! node_or_string_matches_name(
65 ( $node_or_string:ident, $pattern:pat $(if $guard:expr)? $(,)? ) => (
66 match $node_or_string {
67 NodeOrString::String(ref str_) => matches!(str_.as_ref(), $pattern),
68 NodeOrString::Node(ref node) => UnrootedDom::downcast::<Element>(node.clone())
69 .map(|element| matches!(element.local_name().as_ref(), $pattern))
70 .unwrap_or_default(),
71 }
72 );
73);
74
75macro_rules! node_matches_local_name(
76 ( $node:ident, $pattern:pat $(if $guard:expr)? $(,)? ) => (
77 $node.downcast::<Element>().is_some_and(|element|
78 matches!(
79 *element.local_name(),
80 $pattern
81 )
82 )
83 );
84);
85
86pub(crate) use node_matches_local_name;
87
88/// <https://w3c.github.io/editing/docs/execCommand/#prohibited-paragraph-child-name>
89const PROHIBITED_PARAGRAPH_CHILD_NAMES: [&str; 47] = [
90 "address",
91 "article",
92 "aside",
93 "blockquote",
94 "caption",
95 "center",
96 "col",
97 "colgroup",
98 "dd",
99 "details",
100 "dir",
101 "div",
102 "dl",
103 "dt",
104 "fieldset",
105 "figcaption",
106 "figure",
107 "footer",
108 "form",
109 "h1",
110 "h2",
111 "h3",
112 "h4",
113 "h5",
114 "h6",
115 "header",
116 "hgroup",
117 "hr",
118 "li",
119 "listing",
120 "menu",
121 "nav",
122 "ol",
123 "p",
124 "plaintext",
125 "pre",
126 "section",
127 "summary",
128 "table",
129 "tbody",
130 "td",
131 "tfoot",
132 "th",
133 "thead",
134 "tr",
135 "ul",
136 "xmp",
137];
138/// <https://w3c.github.io/editing/docs/execCommand/#name-of-an-element-with-inline-contents>
139const NAME_OF_AN_ELEMENT_WITH_INLINE_CONTENTS: [&str; 43] = [
140 "a", "abbr", "b", "bdi", "bdo", "cite", "code", "dfn", "em", "h1", "h2", "h3", "h4", "h5",
141 "h6", "i", "kbd", "mark", "p", "pre", "q", "rp", "rt", "ruby", "s", "samp", "small", "span",
142 "strong", "sub", "sup", "u", "var", "acronym", "listing", "strike", "xmp", "big", "blink",
143 "font", "marquee", "nobr", "tt",
144];
145
146/// <https://w3c.github.io/editing/docs/execCommand/#element-with-inline-contents>
147fn is_element_with_inline_contents(element: &Node) -> bool {
148 // > An element with inline contents is an HTML element whose local name is a name of an element with inline contents.
149 let Some(html_element) = element.downcast::<HTMLElement>() else {
150 return false;
151 };
152 NAME_OF_AN_ELEMENT_WITH_INLINE_CONTENTS.contains(&html_element.local_name())
153}
154
155/// <https://w3c.github.io/editing/docs/execCommand/#preserving-ranges>
156pub(crate) fn move_preserving_ranges<Move, Return>(cx: &mut JSContext, node: &Node, mut move_: Move)
157where
158 Move: FnMut(&mut JSContext) -> Fallible<Return>,
159{
160 // Step 1. Let node be the moved node, old parent and old index be the old parent
161 // (which may be null) and index, and new parent and new index be the new parent and index.
162 let old_parent = node.GetParentNode();
163 let old_index = node.index();
164
165 let selection = node
166 .owner_document()
167 .GetSelection(cx)
168 .expect("Must always have a selection");
169 let active_range = selection
170 .active_range(cx)
171 .expect("Must always have an active range");
172
173 // Selection is currently implemented as a live range (not great!), which means that
174 // we need to record the old boundary point (container and offset) before actually
175 // performing the move operation and then apply the editing spec's range update
176 // algorithm to this original boundary point.
177 let start_container = active_range.start_container();
178 let start_offset = active_range.start_offset();
179 let end_container = active_range.end_container();
180 let end_offset = active_range.end_offset();
181
182 let should_adjust_start = !node.is_inclusive_ancestor_of(&start_container);
183 let should_adjust_end = !node.is_inclusive_ancestor_of(&end_container);
184
185 if move_(cx).is_err() {
186 unreachable!("Must always be able to move");
187 }
188
189 let new_parent = node.GetParentNode().expect("Must always have a new parent");
190 let new_index = node.index();
191
192 let adjust_boundary_point = |mut container, mut offset, should_adjust: bool| {
193 // Step 2. If a boundary point's node is the same as or a descendant of node, leave it
194 // unchanged, so it moves to the new location.
195 //
196 // From the spec:
197 // > This is actually implicit, but I state it anyway for completeness.
198 //
199 // However, this does not seem to be implicit for text nodes that are partially/fully
200 // selected. In these cases, we shouldn't update the offsets to the new parent, but
201 // instead retain them on the original text node. Therefore, if that's the case,
202 // update them here and immediately return.
203 if !should_adjust {
204 return (container, offset);
205 }
206
207 // Step 3. If a boundary point's node is new parent and its offset is greater than new
208 // index, add one to its offset.
209 if container == new_parent && offset > new_index {
210 offset += 1;
211 }
212
213 if let Some(old_parent) = old_parent.as_ref() {
214 // Step 4. If a boundary point's node is old parent and its offset is old
215 // index or old index + 1, set its node to new parent and add new index −
216 // old index to its offset.
217 if container == *old_parent && (offset == old_index || offset == old_index + 1) {
218 container = new_parent.clone();
219 offset += new_index;
220 offset -= old_index;
221 }
222
223 // Step 5. If a boundary point's node is old parent and its offset is
224 // greater than old index + 1, subtract one from its offset.
225 if container == *old_parent && (offset > old_index + 1) {
226 offset -= 1;
227 }
228 }
229
230 (container, offset)
231 };
232
233 let (new_start_container, new_start_offset) =
234 adjust_boundary_point(start_container, start_offset, should_adjust_start);
235 let (new_end_container, new_end_offset) =
236 adjust_boundary_point(end_container, end_offset, should_adjust_end);
237
238 let _ = active_range.SetStart(cx.no_gc(), &new_start_container, new_start_offset);
239 let _ = active_range.SetEnd(cx.no_gc(), &new_end_container, new_end_offset);
240}
241
242/// <https://w3c.github.io/editing/docs/execCommand/#allowed-child>
243pub(crate) fn is_allowed_child(child: NodeOrString, parent: NodeOrString) -> bool {
244 // Step 1. If parent is "colgroup", "table", "tbody", "tfoot", "thead", "tr",
245 // or an HTML element with local name equal to one of those,
246 // and child is a Text node whose data does not consist solely of space characters, return false.
247 if node_or_string_matches_name!(
248 parent,
249 "colgroup" | "table" | "tbody" | "tfoot" | "thead" | "tr"
250 ) && child.as_node().is_some_and(|node| {
251 // Note: cannot use `.and_then` here, since `downcast` would outlive its reference
252 node.downcast::<Text>()
253 .is_some_and(|text| !text.data().bytes().all(|byte| byte == b' '))
254 }) {
255 return false;
256 }
257 // Step 2. If parent is "script", "style", "plaintext", or "xmp",
258 // or an HTML element with local name equal to one of those, and child is not a Text node, return false.
259 if node_or_string_matches_name!(parent, "script" | "style" | "plaintext" | "xmp") &&
260 child.as_node().is_none_or(|node| !node.is::<Text>())
261 {
262 return false;
263 }
264 // Step 3. If child is a document, DocumentFragment, or DocumentType, return false.
265 if let NodeOrString::Node(ref node) = child &&
266 matches!(
267 node.type_id(),
268 NodeTypeId::Document(_) | NodeTypeId::DocumentFragment(_) | NodeTypeId::DocumentType
269 )
270 {
271 return false;
272 }
273 // Step 4. If child is an HTML element, set child to the local name of child.
274 let child_name = match child {
275 NodeOrString::String(str_) => str_,
276 NodeOrString::Node(node) => match node.downcast::<HTMLElement>() {
277 // Step 5. If child is not a string, return true.
278 None => return true,
279 Some(html_element) => html_element.local_name().to_owned(),
280 },
281 };
282 let child = child_name.as_str();
283 let parent_name = match parent {
284 NodeOrString::String(str_) => str_,
285 NodeOrString::Node(parent) => {
286 // Step 6. If parent is an HTML element:
287 if let Some(parent_element) = parent.downcast::<HTMLElement>() {
288 // Step 6.1. If child is "a", and parent or some ancestor of parent is an a, return false.
289 if child == "a" &&
290 parent
291 .inclusive_ancestors(ShadowIncluding::No)
292 .any(|node| node.is::<HTMLAnchorElement>())
293 {
294 return false;
295 }
296 // Step 6.2. If child is a prohibited paragraph child name and parent or some ancestor of parent
297 // is an element with inline contents, return false.
298 if PROHIBITED_PARAGRAPH_CHILD_NAMES.contains(&child) &&
299 parent
300 .inclusive_ancestors(ShadowIncluding::No)
301 .any(|node| is_element_with_inline_contents(&node))
302 {
303 return false;
304 }
305 // Step 6.3. If child is "h1", "h2", "h3", "h4", "h5", or "h6",
306 // and parent or some ancestor of parent is an HTML element with local name
307 // "h1", "h2", "h3", "h4", "h5", or "h6", return false.
308 if matches!(child, "h1" | "h2" | "h3" | "h4" | "h5" | "h6") &&
309 parent.inclusive_ancestors(ShadowIncluding::No).any(|node| {
310 node.downcast::<HTMLElement>().is_some_and(|html_element| {
311 matches!(
312 html_element.local_name(),
313 "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
314 )
315 })
316 })
317 {
318 return false;
319 }
320 // Step 6.4. Let parent be the local name of parent.
321 parent_element.local_name().to_owned()
322 } else {
323 // Step 7. If parent is an Element or DocumentFragment, return true.
324 // Step 8. If parent is not a string, return false.
325 return matches!(
326 parent.type_id(),
327 NodeTypeId::DocumentFragment(_) | NodeTypeId::Element(_)
328 );
329 }
330 },
331 };
332 let parent = parent_name.as_str();
333 // Step 9. If parent is on the left-hand side of an entry on the following list,
334 // then return true if child is listed on the right-hand side of that entry, and false otherwise.
335 match parent {
336 "colgroup" => return child == "col",
337 "table" => {
338 return matches!(
339 child,
340 "caption" | "col" | "colgroup" | "tbody" | "td" | "tfoot" | "th" | "thead" | "tr"
341 );
342 },
343 "tbody" | "tfoot" | "thead" => return matches!(child, "td" | "th" | "tr"),
344 "tr" => return matches!(child, "td" | "th"),
345 "dl" => return matches!(child, "dt" | "dd"),
346 "dir" | "ol" | "ul" => return matches!(child, "dir" | "li" | "ol" | "ul"),
347 "hgroup" => return matches!(child, "h1" | "h2" | "h3" | "h4" | "h5" | "h6"),
348 _ => {},
349 };
350 // Step 10. If child is "body", "caption", "col", "colgroup", "frame", "frameset", "head",
351 // "html", "tbody", "td", "tfoot", "th", "thead", or "tr", return false.
352 if matches!(
353 child,
354 "body" |
355 "caption" |
356 "col" |
357 "colgroup" |
358 "frame" |
359 "frameset" |
360 "head" |
361 "html" |
362 "tbody" |
363 "td" |
364 "tfoot" |
365 "th" |
366 "thead" |
367 "tr"
368 ) {
369 return false;
370 }
371 // Step 11. If child is "dd" or "dt" and parent is not "dl", return false.
372 if matches!(child, "dd" | "dt") && parent != "dl" {
373 return false;
374 }
375 // Step 12. If child is "li" and parent is not "ol" or "ul", return false.
376 if child == "li" && !matches!(parent, "ol" | "ul") {
377 return false;
378 }
379 // Step 13. If parent is on the left-hand side of an entry on the following list
380 // and child is listed on the right-hand side of that entry, return false.
381 if match parent {
382 "a" => child == "a",
383 "dd" | "dt" => matches!(child, "dd" | "dt"),
384 "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
385 matches!(child, "h1" | "h2" | "h3" | "h4" | "h5" | "h6")
386 },
387 "li" => child == "li",
388 "nobr" => child == "nobr",
389 "td" | "th" => {
390 matches!(
391 child,
392 "caption" | "col" | "colgroup" | "tbody" | "td" | "tfoot" | "th" | "thead" | "tr"
393 )
394 },
395 _ if NAME_OF_AN_ELEMENT_WITH_INLINE_CONTENTS.contains(&parent) => {
396 PROHIBITED_PARAGRAPH_CHILD_NAMES.contains(&child)
397 },
398 _ => false,
399 } {
400 return false;
401 }
402 // Step 14. Return true.
403 true
404}
405
406/// <https://w3c.github.io/editing/docs/execCommand/#split-the-parent>
407pub(crate) fn split_the_parent<'a>(cx: &mut JSContext, node_list: &'a [&'a Node]) {
408 assert!(!node_list.is_empty());
409 // Step 1. Let original parent be the parent of the first member of node list.
410 let Some(original_parent) = node_list.first().and_then(|first| first.GetParentNode()) else {
411 return;
412 };
413 let context_object = original_parent.owner_document();
414 // Step 2. If original parent is not editable or its parent is null, do nothing and abort these steps.
415 if !original_parent.is_editable(cx) {
416 return;
417 }
418 let Some(parent_of_original_parent) = original_parent.GetParentNode() else {
419 return;
420 };
421 // Step 3. If the first child of original parent is in node list, remove extraneous line breaks before original parent.
422 if original_parent
423 .children()
424 .next()
425 .is_some_and(|first_child| node_list.contains(&first_child.deref()))
426 {
427 original_parent.remove_extraneous_line_breaks_before(cx);
428 }
429 // Step 4. If the first child of original parent is in node list, and original parent follows a line break,
430 // set follows line break to true. Otherwise, set follows line break to false.
431 let first_child_is_in_node_list = original_parent
432 .children()
433 .next()
434 .is_some_and(|first_child| node_list.contains(&first_child.deref()));
435 let follows_line_break =
436 first_child_is_in_node_list && original_parent.follows_a_line_break(cx);
437 // Step 5. If the last child of original parent is in node list, and original parent precedes a line break,
438 // set precedes line break to true. Otherwise, set precedes line break to false.
439 let last_child_is_in_node_list = original_parent
440 .children()
441 .last()
442 .is_some_and(|last_child| node_list.contains(&last_child.deref()));
443 let precedes_line_break =
444 last_child_is_in_node_list && original_parent.precedes_a_line_break(cx);
445 // Step 6. If the first child of original parent is not in node list, but its last child is:
446 if !first_child_is_in_node_list && last_child_is_in_node_list {
447 // Step 6.1. For each node in node list, in reverse order,
448 // insert node into the parent of original parent immediately after original parent, preserving ranges.
449 let next_of_original_parent = original_parent.GetNextSibling();
450 for node in node_list.iter().rev() {
451 move_preserving_ranges(cx, node, |cx| {
452 parent_of_original_parent.InsertBefore(cx, node, next_of_original_parent.as_deref())
453 });
454 }
455 // Step 6.2. If precedes line break is true, and the last member of node list does not precede a line break,
456 // call createElement("br") on the context object and insert the result immediately after the last member of node list.
457 if precedes_line_break &&
458 let Some(last) = node_list.last() &&
459 !last.precedes_a_line_break(cx)
460 {
461 let br = context_object.create_element(cx, "br");
462 if last
463 .GetParentNode()
464 .expect("Must always have a parent")
465 .InsertBefore(cx, br.upcast(), last.GetNextSibling().as_deref())
466 .is_err()
467 {
468 unreachable!("Must always be able to append");
469 }
470 }
471 // Step 6.3. Remove extraneous line breaks at the end of original parent.
472 original_parent.remove_extraneous_line_breaks_at_the_end_of(cx);
473 // Step 6.4. Abort these steps.
474 return;
475 }
476 // Step 7. If the first child of original parent is not in node list:
477 if !first_child_is_in_node_list {
478 // Step 7.1. Let cloned parent be the result of calling cloneNode(false) on original parent.
479 let Ok(cloned_parent) = original_parent.CloneNode(cx, false) else {
480 unreachable!("Must always be able to clone node");
481 };
482 // Step 7.2. If original parent has an id attribute, unset it.
483 if let Some(element) = original_parent.downcast::<Element>() {
484 element.remove_attribute_by_name(cx, &local_name!("id"));
485 }
486 // Step 7.3. Insert cloned parent into the parent of original parent immediately before original parent.
487 if parent_of_original_parent
488 .InsertBefore(cx, &cloned_parent, Some(&original_parent))
489 .is_err()
490 {
491 unreachable!("Must always have a parent");
492 }
493 // Step 7.4. While the previousSibling of the first member of node list is not null,
494 // append the first child of original parent as the last child of cloned parent, preserving ranges.
495 loop {
496 if node_list
497 .first()
498 .and_then(|first| first.GetPreviousSibling())
499 .is_some() &&
500 let Some(first_of_original) = original_parent.children().next()
501 {
502 move_preserving_ranges(cx, &first_of_original, |cx| {
503 cloned_parent.AppendChild(cx, &first_of_original)
504 });
505 continue;
506 }
507 break;
508 }
509 }
510 // Step 8. For each node in node list, insert node into the parent of original parent immediately before original parent, preserving ranges.
511 for node in node_list.iter() {
512 move_preserving_ranges(cx, node, |cx| {
513 parent_of_original_parent.InsertBefore(cx, node, Some(&original_parent))
514 });
515 }
516 // Step 9. If follows line break is true, and the first member of node list does not follow a line break,
517 // call createElement("br") on the context object and insert the result immediately before the first member of node list.
518 if follows_line_break &&
519 let Some(first) = node_list.first() &&
520 !first.follows_a_line_break(cx)
521 {
522 let br = context_object.create_element(cx, "br");
523 if first
524 .GetParentNode()
525 .expect("Must always have a parent")
526 .InsertBefore(cx, br.upcast(), Some(first))
527 .is_err()
528 {
529 unreachable!("Must always be able to insert");
530 }
531 }
532 // Step 10. If the last member of node list is an inline node other than a br,
533 // and the first child of original parent is a br, and original parent is not an inline node,
534 // remove the first child of original parent from original parent.
535 if node_list
536 .last()
537 .is_some_and(|last| last.is_inline_node(cx) && !last.is::<HTMLBRElement>()) &&
538 !original_parent.is_inline_node(cx) &&
539 let Some(first_of_original) = original_parent.children().next() &&
540 first_of_original.is::<HTMLBRElement>()
541 {
542 assert!(first_of_original.has_parent());
543 first_of_original.remove_self(cx);
544 }
545 // Step 11. If original parent has no children:
546 if original_parent.children_count() == 0 {
547 // Step 11.1. Remove original parent from its parent.
548 assert!(original_parent.has_parent());
549 original_parent.remove_self(cx);
550 // Step 11.2. If precedes line break is true, and the last member of node list does not precede a line break,
551 // call createElement("br") on the context object and insert the result immediately after the last member of node list.
552 if precedes_line_break &&
553 let Some(last) = node_list.last() &&
554 !last.precedes_a_line_break(cx)
555 {
556 let br = context_object.create_element(cx, "br");
557 if last
558 .GetParentNode()
559 .expect("Must always have a parent")
560 .InsertBefore(cx, br.upcast(), last.GetNextSibling().as_deref())
561 .is_err()
562 {
563 unreachable!("Must always be able to insert");
564 }
565 }
566 } else {
567 // Step 12. Otherwise, remove extraneous line breaks before original parent.
568 original_parent.remove_extraneous_line_breaks_before(cx);
569 }
570 // Step 13. If node list's last member's nextSibling is null, but its parent is not null,
571 // remove extraneous line breaks at the end of node list's last member's parent.
572 if let Some(last) = node_list.last() &&
573 last.GetNextSibling().is_none() &&
574 let Some(parent_of_last) = last.GetParentNode()
575 {
576 parent_of_last.remove_extraneous_line_breaks_at_the_end_of(cx);
577 }
578}
579
580/// <https://w3c.github.io/editing/docs/execCommand/#wrap>
581pub(crate) fn wrap_node_list<SiblingCriteria, NewParentInstructions>(
582 cx: &mut JSContext,
583 mut node_list: VecDeque<DomRoot<Node>>,
584 mut sibling_criteria: SiblingCriteria,
585 new_parent_instructions: NewParentInstructions,
586) -> Option<DomRoot<Node>>
587where
588 SiblingCriteria: FnMut(&mut JSContext, &Node) -> bool,
589 NewParentInstructions: Fn(&mut JSContext) -> Option<DomRoot<Node>>,
590{
591 // Step 1. If every member of node list is invisible,
592 // and none is a br, return null and abort these steps.
593 if node_list
594 .iter()
595 .all(|node| node.is_invisible(cx) && !node.is::<HTMLBRElement>())
596 {
597 return None;
598 }
599
600 // Step 2. If node list's first member's parent is null, return null and abort these steps.
601 node_list.front().and_then(|first| first.GetParentNode())?;
602 // Step 3. If node list's last member is an inline node that's not a br,
603 // and node list's last member's nextSibling is a br, append that br to node list.
604 if let Some(last) = node_list.back() &&
605 last.is_inline_node(cx) &&
606 !last.is::<HTMLBRElement>() &&
607 let Some(next_of_last) = last.GetNextSibling() &&
608 next_of_last.is::<HTMLBRElement>()
609 {
610 node_list.push_back(next_of_last);
611 }
612 // Step 4. While node list's first member's previousSibling is invisible, prepend it to node list.
613 while let Some(previous_of_first) = node_list.front().and_then(|last| last.GetPreviousSibling())
614 {
615 if previous_of_first.is_invisible(cx) {
616 node_list.push_front(previous_of_first);
617 continue;
618 }
619 break;
620 }
621 // Step 5. While node list's last member's nextSibling is invisible, append it to node list.
622 while let Some(next_of_last) = node_list.back().and_then(|last| last.GetNextSibling()) {
623 if next_of_last.is_invisible(cx) {
624 node_list.push_back(next_of_last);
625 continue;
626 }
627 break;
628 }
629 // Step 6. If the previousSibling of the first member of node list is editable
630 // and running sibling criteria on it returns true,
631 // let new parent be the previousSibling of the first member of node list.
632 let new_parent = node_list
633 .front()
634 .and_then(|first| first.GetPreviousSibling())
635 .filter(|previous_of_first| {
636 previous_of_first.is_editable(cx) && sibling_criteria(cx, previous_of_first)
637 });
638 // Step 7. Otherwise, if the nextSibling of the last member of node list is editable
639 // and running sibling criteria on it returns true,
640 // let new parent be the nextSibling of the last member of node list.
641 let new_parent = new_parent.or_else(|| {
642 node_list
643 .back()
644 .and_then(|last| last.GetNextSibling())
645 .filter(|next_of_last| {
646 next_of_last.is_editable(cx) && sibling_criteria(cx, next_of_last)
647 })
648 });
649 // Step 8. Otherwise, run new parent instructions, and let new parent be the result.
650 // Step 9. If new parent is null, abort these steps and return null.
651 let new_parent = new_parent.or_else(|| new_parent_instructions(cx))?;
652 // Step 11. Let original parent be the parent of the first member of node list.
653 let first_in_node_list = node_list
654 .front()
655 .expect("Must always have at least one node");
656 let original_parent = first_in_node_list
657 .GetParentNode()
658 .expect("First node must have a parent");
659 // Step 10. If new parent's parent is null:
660 if new_parent.GetParentNode().is_none() {
661 // Step 10.1. Insert new parent into the parent of the first member
662 // of node list immediately before the first member of node list.
663 if original_parent
664 .InsertBefore(cx, &new_parent, Some(first_in_node_list))
665 .is_err()
666 {
667 unreachable!("Must always be able to insert");
668 }
669 // Step 10.2. If any range has a boundary point with node equal
670 // to the parent of new parent and offset equal to the index of new parent,
671 // add one to that boundary point's offset.
672 if let Some(range) = first_in_node_list
673 .owner_document()
674 .GetSelection(cx)
675 .and_then(|selection| selection.active_range(cx))
676 {
677 let parent_of_new_parent = new_parent.GetParentNode().expect("Must have a parent");
678 let start_container = range.start_container();
679 let start_offset = range.start_offset();
680
681 if start_container == parent_of_new_parent && start_offset == new_parent.index() {
682 let _ = range.SetStart(cx.no_gc(), &start_container, start_offset + 1);
683 }
684
685 let end_container = range.end_container();
686 let end_offset = range.end_offset();
687
688 if end_container == parent_of_new_parent && end_offset == new_parent.index() {
689 let _ = range.SetEnd(cx.no_gc(), &end_container, end_offset + 1);
690 }
691 }
692 }
693 // Step 12. If new parent is before the first member of node list in tree order:
694 if new_parent.is_before(cx.no_gc(), first_in_node_list) {
695 // Step 12.1. If new parent is not an inline node, but the last visible child of new parent
696 // and the first visible member of node list are both inline nodes,
697 // and the last child of new parent is not a br,
698 // call createElement("br") on the ownerDocument of new parent
699 // and append the result as the last child of new parent.
700 if !new_parent.is_inline_node(cx) &&
701 new_parent
702 .rev_children()
703 .find(|child| child.is_visible(cx))
704 .is_some_and(|child| child.is_inline_node(cx)) &&
705 node_list
706 .iter()
707 .find(|node| node.is_visible(cx))
708 .is_some_and(|node| node.is_inline_node(cx)) &&
709 new_parent
710 .children_unrooted(cx.no_gc())
711 .last()
712 .is_none_or(|last_child| !last_child.is::<HTMLBRElement>())
713 {
714 let new_br_element = new_parent.owner_document().create_element(cx, "br");
715 if new_parent.AppendChild(cx, new_br_element.upcast()).is_err() {
716 unreachable!("Must always be able to append");
717 }
718 }
719 // Step 12.2. For each node in node list, append node as the last child of new parent, preserving ranges.
720 for node in node_list {
721 move_preserving_ranges(cx, &node, |cx| new_parent.AppendChild(cx, &node));
722 }
723 } else {
724 // Step 13. Otherwise:
725 // Step 13.1. If new parent is not an inline node, but the first visible child of new parent
726 // and the last visible member of node list are both inline nodes,
727 // and the last member of node list is not a br,
728 // call createElement("br") on the ownerDocument of new parent
729 // and insert the result as the first child of new parent.
730 if !new_parent.is_inline_node(cx) &&
731 new_parent
732 .children()
733 .find(|child| child.is_visible(cx))
734 .is_some_and(|child| child.is_inline_node(cx)) &&
735 node_list
736 .iter()
737 .rev()
738 .find(|node| node.is_visible(cx))
739 .is_some_and(|node| node.is_inline_node(cx)) &&
740 node_list
741 .back()
742 .is_none_or(|last_child| !last_child.is::<HTMLBRElement>())
743 {
744 let new_br_element = new_parent.owner_document().create_element(cx, "br");
745 if new_parent
746 .InsertBefore(
747 cx,
748 new_br_element.upcast(),
749 new_parent.GetFirstChild().as_deref(),
750 )
751 .is_err()
752 {
753 unreachable!("Must always be able to append");
754 }
755 }
756 // Step 13.2. For each node in node list, in reverse order,
757 // insert node as the first child of new parent, preserving ranges.
758 let mut before = new_parent.GetFirstChild();
759 for node in node_list.iter().rev() {
760 move_preserving_ranges(cx, node, |cx| {
761 new_parent.InsertBefore(cx, node, before.as_deref())
762 });
763 before = Some(DomRoot::from_ref(node));
764 }
765 }
766 // Step 14. If original parent is editable and has no children, remove it from its parent.
767 if original_parent.is_editable(cx) && original_parent.children_count() == 0 {
768 original_parent.remove_self(cx);
769 }
770 // Step 15. If new parent's nextSibling is editable and running sibling criteria on it returns true:
771 if let Some(next_of_new_parent) = new_parent.GetNextSibling() &&
772 next_of_new_parent.is_editable(cx) &&
773 sibling_criteria(cx, &next_of_new_parent)
774 {
775 // Step 15.1. If new parent is not an inline node,
776 // but new parent's last child and new parent's nextSibling's first child are both inline nodes,
777 // and new parent's last child is not a br, call createElement("br") on the ownerDocument
778 // of new parent and append the result as the last child of new parent.
779 if !new_parent.is_inline_node(cx) {
780 let child = new_parent
781 .children_unrooted(cx.no_gc())
782 .last()
783 .map(|node| node.as_rooted());
784 if let Some(last_child_of_new_parent) = child &&
785 last_child_of_new_parent.is_inline_node(cx) &&
786 !last_child_of_new_parent.is::<HTMLBRElement>() &&
787 next_of_new_parent
788 .children()
789 .next()
790 .is_some_and(|first| first.is_inline_node(cx))
791 {
792 let new_br_element = new_parent.owner_document().create_element(cx, "br");
793 if new_parent.AppendChild(cx, new_br_element.upcast()).is_err() {
794 unreachable!("Must always be able to append");
795 }
796 }
797 }
798 // Step 15.2. While new parent's nextSibling has children,
799 // append its first child as the last child of new parent, preserving ranges.
800 for child in next_of_new_parent.children() {
801 move_preserving_ranges(cx, &child, |cx| new_parent.AppendChild(cx, &child));
802 }
803 // Step 15.3. Remove new parent's nextSibling from its parent.
804 next_of_new_parent.remove_self(cx);
805 }
806 // Step 16. Remove extraneous line breaks from new parent.
807 new_parent.remove_extraneous_line_breaks_from(cx);
808 // Step 17. Return new parent.
809 Some(new_parent)
810}
811
812pub(crate) struct RecordedValueAndCommandOfNode {
813 node: DomRoot<Node>,
814 command: CommandName,
815 specified_command_value: Option<DOMString>,
816}
817
818/// <https://w3c.github.io/editing/docs/execCommand/#record-the-values>
819pub(crate) fn record_the_values(
820 cx: &mut JSContext,
821 node_list: Vec<DomRoot<Node>>,
822) -> Vec<RecordedValueAndCommandOfNode> {
823 // Step 1. Let values be a list of (node, command, specified command value) triples, initially empty.
824 let mut values = vec![];
825 // Step 2. For each node in node list,
826 // for each command in the list "subscript", "bold", "fontName", "fontSize", "foreColor",
827 // "hiliteColor", "italic", "strikethrough", and "underline" in that order:
828 for node in node_list {
829 for command in vec![
830 CommandName::Subscript,
831 CommandName::Bold,
832 CommandName::FontName,
833 CommandName::FontSize,
834 CommandName::ForeColor,
835 CommandName::HiliteColor,
836 CommandName::Italic,
837 CommandName::Strikethrough,
838 CommandName::Underline,
839 ] {
840 // Step 2.1. Let ancestor equal node.
841 let mut ancestor =
842 if let Some(node_element) = DomRoot::downcast::<Element>(node.clone()) {
843 Some(node_element)
844 } else {
845 // Step 2.2. If ancestor is not an Element, set it to its parent.
846 node.GetParentElement()
847 };
848 // Step 2.3. While ancestor is an Element and its specified command value for command is null, set it to its parent.
849 while let Some(ref ancestor_element) = ancestor {
850 if ancestor_element
851 .specified_command_value(cx, &command)
852 .is_none()
853 {
854 ancestor = ancestor_element.upcast::<Node>().GetParentElement();
855 continue;
856 }
857 break;
858 }
859 // Step 2.4. If ancestor is an Element,
860 // add (node, command, ancestor's specified command value for command) to values.
861 // Otherwise add (node, command, null) to values.
862 let specified_command_value =
863 ancestor.and_then(|ancestor| ancestor.specified_command_value(cx, &command));
864 values.push(RecordedValueAndCommandOfNode {
865 node: node.clone(),
866 command,
867 specified_command_value,
868 });
869 }
870 }
871 // Step 3. Return values.
872 values
873}
874
875/// <https://w3c.github.io/editing/docs/execCommand/#restore-the-values>
876pub(crate) fn restore_the_values(cx: &mut JSContext, values: Vec<RecordedValueAndCommandOfNode>) {
877 // Step 1. For each (node, command, value) triple in values:
878 for triple in values {
879 let RecordedValueAndCommandOfNode {
880 node,
881 command,
882 specified_command_value,
883 } = triple;
884 // Step 1.1. Let ancestor equal node.
885 let mut ancestor = if let Some(node_element) = DomRoot::downcast::<Element>(node.clone()) {
886 Some(node_element)
887 } else {
888 // Step 1.2. If ancestor is not an Element, set it to its parent.
889 node.GetParentElement()
890 };
891 // Step 1.3. While ancestor is an Element and its specified command value for command is null, set it to its parent.
892 while let Some(ref ancestor_element) = ancestor {
893 if ancestor_element
894 .specified_command_value(cx, &command)
895 .is_none()
896 {
897 ancestor = ancestor_element.upcast::<Node>().GetParentElement();
898 continue;
899 }
900 break;
901 }
902 // Step 1.4. If value is null and ancestor is an Element,
903 // push down values on node for command, with new value null.
904 if specified_command_value.is_none() && ancestor.is_some() {
905 node.push_down_values(cx, &command, None);
906 } else {
907 // Step 1.5. Otherwise, if ancestor is an Element and its specified command value for command is not equivalent to value,
908 // or if ancestor is not an Element and value is not null, force the value of command to value on node.
909 if match (ancestor, specified_command_value.as_ref()) {
910 (Some(ancestor), value) => !command.are_equivalent_values(
911 ancestor.specified_command_value(cx, &command).as_ref(),
912 value,
913 ),
914 (None, Some(_)) => true,
915 _ => false,
916 } {
917 node.force_the_value(cx, &command, specified_command_value.as_ref());
918 }
919 }
920 }
921}
922
923impl HTMLBRElement {
924 /// <https://w3c.github.io/editing/docs/execCommand/#extraneous-line-break>
925 fn is_extraneous_line_break(&self, cx: &mut JSContext) -> bool {
926 let node = self.upcast::<Node>();
927 // > An extraneous line break is a br that has no visual effect, in that removing it from the DOM would not change layout,
928 // except that a br that is the sole child of an li is not extraneous.
929 if node
930 .GetParentNode()
931 .filter(|parent| parent.is::<HTMLLIElement>())
932 .is_some_and(|li| li.children_count() == 1)
933 {
934 return false;
935 }
936 // TODO: Figure out what this actually makes it have no visual effect
937 !node.is_block_node(cx)
938 }
939}
940
941impl Node {
942 /// <https://w3c.github.io/editing/docs/execCommand/#push-down-values>
943 pub(crate) fn push_down_values(
944 &self,
945 cx: &mut JSContext,
946 command: &CommandName,
947 new_value: Option<DOMString>,
948 ) {
949 // Step 1. Let command be the current command.
950 //
951 // Passed in as argument
952
953 // Step 4. Let current ancestor be node's parent.
954 let mut current_ancestor = self.GetParentElement();
955 // Step 2. If node's parent is not an Element, abort this algorithm.
956 if current_ancestor.is_none() {
957 return;
958 };
959 // Step 3. If the effective command value of command is loosely equivalent to new value on node,
960 // abort this algorithm.
961 if command.are_loosely_equivalent_values(
962 self.effective_command_value(cx, command).as_ref(),
963 new_value.as_ref(),
964 ) {
965 return;
966 }
967 // Step 5. Let ancestor list be a list of nodes, initially empty.
968 rooted_vec!(let mut ancestor_list);
969 // Step 6. While current ancestor is an editable Element and
970 // the effective command value of command is not loosely equivalent to new value on it,
971 // append current ancestor to ancestor list, then set current ancestor to its parent.
972 while let Some(ancestor) = current_ancestor {
973 let ancestor_node = ancestor.upcast::<Node>();
974 if ancestor_node.is_editable(cx) &&
975 !command.are_loosely_equivalent_values(
976 ancestor_node.effective_command_value(cx, command).as_ref(),
977 new_value.as_ref(),
978 )
979 {
980 ancestor_list.push(ancestor.clone());
981 current_ancestor = ancestor_node.GetParentElement();
982 continue;
983 }
984 break;
985 }
986 let Some(last_ancestor) = ancestor_list.last() else {
987 // Step 7. If ancestor list is empty, abort this algorithm.
988 return;
989 };
990 // Step 8. Let propagated value be the specified command value of command on the last member of ancestor list.
991 let mut propagated_value = last_ancestor.specified_command_value(cx, command);
992 // Step 9. If propagated value is null and is not equal to new value, abort this algorithm.
993 if propagated_value.is_none() && new_value.is_some() {
994 return;
995 }
996 // Step 10. If the effective command value of command is not loosely equivalent to new value on the parent
997 // of the last member of ancestor list, and new value is not null, abort this algorithm.
998 if new_value.is_some() &&
999 !last_ancestor
1000 .upcast::<Node>()
1001 .GetParentNode()
1002 .is_some_and(|last_ancestor_parent| {
1003 command.are_loosely_equivalent_values(
1004 last_ancestor_parent
1005 .effective_command_value(cx, command)
1006 .as_ref(),
1007 new_value.as_ref(),
1008 )
1009 })
1010 {
1011 return;
1012 }
1013 // Step 11. While ancestor list is not empty:
1014 let mut ancestor_list_iter = ancestor_list.iter().rev().peekable();
1015 while let Some(current_ancestor) = ancestor_list_iter.next() {
1016 let current_ancestor_node = current_ancestor.upcast::<Node>();
1017 // Step 11.1. Let current ancestor be the last member of ancestor list.
1018 // Step 11.2. Remove the last member from ancestor list.
1019 //
1020 // Both of these steps done by iterating and reversing the iterator
1021
1022 // Step 11.3. If the specified command value of current ancestor for command is not null, set propagated value to that value.
1023 let command_value = current_ancestor.specified_command_value(cx, command);
1024 let has_command_value = command_value.is_some();
1025 propagated_value = command_value.or(propagated_value);
1026 // Step 11.4. Let children be the children of current ancestor.
1027 let children = current_ancestor_node
1028 .children()
1029 .collect::<Vec<DomRoot<Node>>>();
1030 // Step 11.5. If the specified command value of current ancestor for command is not null, clear the value of current ancestor.
1031 if has_command_value &&
1032 let Some(html_element) = current_ancestor.downcast::<HTMLElement>()
1033 {
1034 html_element.clear_the_value(cx, command);
1035 }
1036 // Step 11.6. For every child in children:
1037 for child in children {
1038 // Step 11.6.1. If child is node, continue with the next child.
1039 if *child == *self {
1040 continue;
1041 }
1042 // Step 11.6.2. If child is an Element whose specified command value for command is neither null
1043 // nor equivalent to propagated value, continue with the next child.
1044 if let Some(child_element) = child.downcast::<Element>() {
1045 let specified_value = child_element.specified_command_value(cx, command);
1046 if specified_value.is_some() &&
1047 !command.are_equivalent_values(
1048 specified_value.as_ref(),
1049 propagated_value.as_ref(),
1050 )
1051 {
1052 continue;
1053 }
1054 }
1055
1056 // Step 11.6.3. If child is the last member of ancestor list, continue with the next child.
1057 //
1058 // Since we had to remove the last member in step 11.2, if we now peek at the next possible
1059 // value, we essentially have the "last member after removal"
1060 if ancestor_list_iter
1061 .peek()
1062 .is_some_and(|ancestor| *ancestor.upcast::<Node>() == *child)
1063 {
1064 continue;
1065 }
1066 // step 11.6.4. Force the value of child, with command as in this algorithm and new value equal to propagated value.
1067 child.force_the_value(cx, command, propagated_value.as_ref());
1068 }
1069 }
1070 }
1071
1072 /// <https://w3c.github.io/editing/docs/execCommand/#reorder-modifiable-descendants>
1073 fn reorder_modifiable_descendants(
1074 &self,
1075 cx: &mut JSContext,
1076 command: &CommandName,
1077 new_value: &DOMString,
1078 ) {
1079 // Step 1. Let candidate equal node.
1080 let mut candidate = DomRoot::from_ref(self);
1081 // Step 2. While candidate is a modifiable element, and candidate has exactly one child,
1082 // and that child is also a modifiable element,
1083 // and candidate is not a simple modifiable element or candidate's specified command value
1084 // for command is not equivalent to new value, set candidate to its child.
1085 loop {
1086 if let Some(candidate_element) = candidate.downcast::<Element>() &&
1087 candidate_element.is_modifiable_element() &&
1088 candidate.children_count() == 1 &&
1089 (!candidate_element.is_simple_modifiable_element() ||
1090 !command.are_equivalent_values(
1091 candidate_element
1092 .specified_command_value(cx, command)
1093 .as_ref(),
1094 Some(new_value),
1095 ))
1096 {
1097 let child = candidate.children().next().expect("Has one child");
1098
1099 if let Some(child_element) = child.downcast::<Element>() &&
1100 child_element.is_modifiable_element()
1101 {
1102 candidate = child;
1103 continue;
1104 }
1105 }
1106 break;
1107 }
1108 // Step 3. If candidate is node, or is not a simple modifiable element,
1109 // or its specified command value is not equivalent to new value,
1110 // or its effective command value is not loosely equivalent to new value, abort these steps.
1111 if *candidate == *self ||
1112 !command.are_loosely_equivalent_values(
1113 candidate.effective_command_value(cx, command).as_ref(),
1114 Some(new_value),
1115 )
1116 {
1117 return;
1118 }
1119 if let Some(candidate) = candidate.downcast::<Element>() &&
1120 (!candidate.is_simple_modifiable_element() ||
1121 !command.are_equivalent_values(
1122 candidate.specified_command_value(cx, command).as_ref(),
1123 Some(new_value),
1124 ))
1125 {
1126 return;
1127 }
1128 // Step 4. While candidate has children,
1129 // insert the first child of candidate into candidate's parent immediately before candidate, preserving ranges.
1130 let parent_of_candidate = candidate
1131 .GetParentNode()
1132 .expect("Must always have a parent");
1133 for child in candidate.children() {
1134 move_preserving_ranges(cx, &child, |cx| {
1135 parent_of_candidate.InsertBefore(cx, &child, Some(&candidate))
1136 });
1137 }
1138 // Step 5. Insert candidate into node's parent immediately after node.
1139 let parent_of_node = self.GetParentNode().expect("Must always have a parent");
1140 if parent_of_node
1141 .InsertBefore(cx, &candidate, self.GetNextSibling().as_deref())
1142 .is_err()
1143 {
1144 unreachable!("Must always be able to insert");
1145 }
1146 // Step 6. Append the node as the last child of candidate, preserving ranges.
1147 move_preserving_ranges(cx, self, |cx| candidate.AppendChild(cx, self));
1148 }
1149
1150 /// <https://w3c.github.io/editing/docs/execCommand/#force-the-value>
1151 pub(crate) fn force_the_value(
1152 &self,
1153 cx: &mut JSContext,
1154 command: &CommandName,
1155 new_value: Option<&DOMString>,
1156 ) {
1157 // Step 1. Let command be the current command.
1158 //
1159 // That's command
1160
1161 // Step 2. If node's parent is null, abort this algorithm.
1162 if self.GetParentNode().is_none() {
1163 return;
1164 }
1165 // Step 3. If new value is null, abort this algorithm.
1166 let Some(new_value) = new_value else {
1167 return;
1168 };
1169 // Step 4. If node is an allowed child of "span":
1170 if is_allowed_child(
1171 NodeOrString::from_node(self, cx.no_gc()),
1172 NodeOrString::String("span".to_owned()),
1173 ) {
1174 // Step 4.1. Reorder modifiable descendants of node's previousSibling.
1175 if let Some(previous) = self.GetPreviousSibling() {
1176 previous.reorder_modifiable_descendants(cx, command, new_value);
1177 }
1178 // Step 4.2. Reorder modifiable descendants of node's nextSibling.
1179 if let Some(next) = self.GetNextSibling() {
1180 next.reorder_modifiable_descendants(cx, command, new_value);
1181 }
1182 // Step 4.3. Wrap the one-node list consisting of node,
1183 // with sibling criteria returning true for a simple modifiable element whose
1184 // specified command value is equivalent to new value and whose effective command value
1185 // is loosely equivalent to new value and false otherwise,
1186 // and with new parent instructions returning null.
1187 wrap_node_list(
1188 cx,
1189 VecDeque::from([DomRoot::from_ref(self)]),
1190 |cx, sibling| {
1191 sibling
1192 .downcast::<Element>()
1193 .is_some_and(|sibling_element| {
1194 sibling_element.is_simple_modifiable_element() &&
1195 command.are_equivalent_values(
1196 sibling_element
1197 .specified_command_value(cx, command)
1198 .as_ref(),
1199 Some(new_value),
1200 ) &&
1201 command.are_loosely_equivalent_values(
1202 sibling.effective_command_value(cx, command).as_ref(),
1203 Some(new_value),
1204 )
1205 })
1206 },
1207 |_| None,
1208 );
1209 }
1210 // Step 5. If node is invisible, abort this algorithm.
1211 if self.is_invisible(cx) {
1212 return;
1213 }
1214 // Step 6. If the effective command value of command is loosely equivalent to new value on node, abort this algorithm.
1215 if command.are_loosely_equivalent_values(
1216 self.effective_command_value(cx, command).as_ref(),
1217 Some(new_value),
1218 ) {
1219 return;
1220 }
1221 // Step 7. If node is not an allowed child of "span":
1222 if !is_allowed_child(
1223 NodeOrString::from_node(self, cx.no_gc()),
1224 NodeOrString::String("span".to_owned()),
1225 ) {
1226 // Step 7.1. Let children be all children of node, omitting any that are Elements whose
1227 // specified command value for command is neither null nor equivalent to new value.
1228 let children = self
1229 .children()
1230 .filter(|child| {
1231 !child.downcast::<Element>().is_some_and(|child_element| {
1232 let specified_value = child_element.specified_command_value(cx, command);
1233 specified_value.is_some() &&
1234 !command
1235 .are_equivalent_values(specified_value.as_ref(), Some(new_value))
1236 })
1237 })
1238 .collect::<Vec<DomRoot<Node>>>();
1239 // Step 7.2. Force the value of each node in children,
1240 // with command and new value as in this invocation of the algorithm.
1241 for child in children {
1242 child.force_the_value(cx, command, Some(new_value));
1243 }
1244 // Step 7.3. Abort this algorithm.
1245 return;
1246 }
1247 // Step 8. If the effective command value of command is loosely equivalent to new value on node, abort this algorithm.
1248 if command.are_loosely_equivalent_values(
1249 self.effective_command_value(cx, command).as_ref(),
1250 Some(new_value),
1251 ) {
1252 return;
1253 }
1254 // Step 9. Let new parent be null.
1255 let mut new_parent = None;
1256 let document = self.owner_document();
1257 let css_styling_flag = document.css_styling_flag();
1258 // Step 10. If the CSS styling flag is false:
1259 if !css_styling_flag {
1260 match command {
1261 // Step 10.1. If command is "bold" and new value is "bold",
1262 // let new parent be the result of calling createElement("b") on the ownerDocument of node.
1263 CommandName::Bold => {
1264 new_parent = Some(document.create_element(cx, "b"));
1265 },
1266 // Step 10.2. If command is "italic" and new value is "italic",
1267 // let new parent be the result of calling createElement("i") on the ownerDocument of node.
1268 CommandName::Italic => {
1269 new_parent = Some(document.create_element(cx, "i"));
1270 },
1271 // Step 10.3. If command is "strikethrough" and new value is "line-through",
1272 // let new parent be the result of calling createElement("s") on the ownerDocument of node.
1273 //
1274 // Despite what the spec says, all browsers generate a strike element instead
1275 CommandName::Strikethrough => {
1276 new_parent = Some(document.create_element(cx, "strike"));
1277 },
1278 // Step 10.4. If command is "underline" and new value is "underline",
1279 // let new parent be the result of calling createElement("u") on the ownerDocument of node.
1280 CommandName::Underline => {
1281 new_parent = Some(document.create_element(cx, "u"));
1282 },
1283 // Step 10.5. If command is "foreColor", and new value is fully opaque with
1284 // red, green, and blue components in the range 0 to 255:
1285 CommandName::ForeColor => {
1286 if let Ok(legacy_color) = parse_legacy_color(&new_value.str()) &&
1287 legacy_color.alpha() == Some(OPAQUE)
1288 {
1289 // Step 10.5.1. Let new parent be the result of calling createElement("font") on the ownerDocument of node.
1290 let new_font_element = document.create_element(cx, "font");
1291 // Step 10.5.2. Set the color attribute of new parent to the result of applying the rules for
1292 // serializing simple color values to new value (interpreted as a simple color).
1293 new_font_element.set_string_attribute(
1294 cx,
1295 &local_name!("color"),
1296 serialize_to_simple_color(legacy_color),
1297 );
1298 new_parent = Some(new_font_element);
1299 }
1300 },
1301 // Step 10.6. If command is "fontName",
1302 // let new parent be the result of calling createElement("font") on the ownerDocument of node,
1303 // then set the face attribute of new parent to new value.
1304 CommandName::FontName => {
1305 let new_font_element = document.create_element(cx, "font");
1306 new_font_element.set_string_attribute(
1307 cx,
1308 &local_name!("face"),
1309 new_value.clone(),
1310 );
1311 new_parent = Some(new_font_element);
1312 },
1313 _ => {},
1314 }
1315 }
1316
1317 match command {
1318 // Step 11. If command is "createLink" or "unlink":
1319 CommandName::CreateLink | CommandName::Unlink => {
1320 // Step 11.1. Let new parent be the result of calling createElement("a") on the ownerDocument of node.
1321 let new_element = document.create_element(cx, "a");
1322 // Step 11.2. Set the href attribute of new parent to new value.
1323 new_element
1324 .downcast::<HTMLAnchorElement>()
1325 .expect("Must always create an anchor")
1326 .SetHref(cx, new_value.to_string().into());
1327 // Step 11.3. Let ancestor be node's parent.
1328 let mut ancestor = self.GetParentNode();
1329 // Step 11.4. While ancestor is not null:
1330 while let Some(current_ancestor) = ancestor {
1331 // Step 11.4.1. If ancestor is an a, set the tag name of ancestor to "span", and let ancestor be the result.
1332 let current_ancestor = if current_ancestor.is::<HTMLAnchorElement>() {
1333 current_ancestor
1334 .downcast::<Element>()
1335 .expect("Must always be an element")
1336 .set_the_tag_name(cx, "span")
1337 } else {
1338 current_ancestor
1339 };
1340 // Step 11.4.2. Set ancestor to its parent.
1341 ancestor = current_ancestor.GetParentNode();
1342 }
1343 new_parent = Some(new_element);
1344 },
1345 // Step 12. If command is "fontSize"; and new value is one of
1346 // "x-small", "small", "medium", "large", "x-large", "xx-large", or "xxx-large";
1347 // and either the CSS styling flag is false, or new value is "xxx-large":
1348 // let new parent be the result of calling createElement("font") on the ownerDocument of node,
1349 // then set the size attribute of new parent to the number from the following table based on new value:
1350 CommandName::FontSize if !css_styling_flag || new_value == "xxx-large" => {
1351 let size = match &*new_value.str() {
1352 "x-small" => 1,
1353 "small" => 2,
1354 "medium" => 3,
1355 "large" => 4,
1356 "x-large" => 5,
1357 "xx-large" => 6,
1358 "xxx-large" => 7,
1359 _ => 0,
1360 };
1361
1362 if size > 0 {
1363 let new_font_element = document.create_element(cx, "font");
1364 new_font_element.set_attribute(cx, &local_name!("size"), size.into());
1365 new_parent = Some(new_font_element);
1366 }
1367 },
1368 CommandName::Subscript | CommandName::Superscript => {
1369 // Step 13. If command is "subscript" or "superscript" and new value is "subscript",
1370 // let new parent be the result of calling createElement("sub") on the ownerDocument of node.
1371 if new_value == "subscript" {
1372 new_parent = Some(document.create_element(cx, "sub"));
1373 }
1374 // Step 14. If command is "subscript" or "superscript" and new value is "superscript",
1375 // let new parent be the result of calling createElement("sup") on the ownerDocument of node.
1376 if new_value == "superscript" {
1377 new_parent = Some(document.create_element(cx, "sup"));
1378 }
1379 },
1380 _ => {},
1381 }
1382 // Step 15. If new parent is null, let new parent be the result of calling createElement("span") on the ownerDocument of node.
1383 let new_parent = new_parent.unwrap_or_else(|| document.create_element(cx, "span"));
1384 let new_parent_html_element = new_parent
1385 .downcast::<HTMLElement>()
1386 .expect("Must always create a HTML element");
1387 // Step 16. Insert new parent in node's parent before node.
1388 if self
1389 .GetParentNode()
1390 .expect("Must always have a parent")
1391 .InsertBefore(cx, new_parent.upcast(), Some(self))
1392 .is_err()
1393 {
1394 unreachable!("Must always be able to insert");
1395 }
1396 // Step 17. If the effective command value of command for new parent is not loosely equivalent to new value,
1397 // and the relevant CSS property for command is not null,
1398 // set that CSS property of new parent to new value (if the new value would be valid).
1399 if !command.are_loosely_equivalent_values(
1400 new_parent
1401 .upcast::<Node>()
1402 .effective_command_value(cx, command)
1403 .as_ref(),
1404 Some(new_value),
1405 ) && let Some(css_property) = command.relevant_css_property()
1406 {
1407 css_property.set_for_element(cx, new_parent_html_element, new_value.clone());
1408 }
1409 #[expect(clippy::collapsible_match, reason = "That would be unreadable.")]
1410 match command {
1411 // Step 18. If command is "strikethrough", and new value is "line-through",
1412 // and the effective command value of "strikethrough" for new parent is not "line-through",
1413 // set the "text-decoration" property of new parent to "line-through".
1414 CommandName::Strikethrough => {
1415 if new_value == "line-through" &&
1416 new_parent
1417 .upcast::<Node>()
1418 .effective_command_value(cx, &CommandName::Strikethrough)
1419 .is_none_or(|value| value != "line-through")
1420 {
1421 CssPropertyName::TextDecoration.set_for_element(
1422 cx,
1423 new_parent_html_element,
1424 new_value.clone(),
1425 );
1426 }
1427 },
1428 // Step 19. If command is "underline", and new value is "underline",
1429 // and the effective command value of "underline" for new parent is not "underline",
1430 // set the "text-decoration" property of new parent to "underline".
1431 CommandName::Underline => {
1432 if new_value == "underline" &&
1433 new_parent
1434 .upcast::<Node>()
1435 .effective_command_value(cx, &CommandName::Underline)
1436 .is_none_or(|value| value != "underline")
1437 {
1438 CssPropertyName::TextDecoration.set_for_element(
1439 cx,
1440 new_parent_html_element,
1441 new_value.clone(),
1442 );
1443 }
1444 },
1445 _ => {},
1446 }
1447 // Step 20. Append node to new parent as its last child, preserving ranges.
1448 let new_parent = new_parent.upcast::<Node>();
1449 move_preserving_ranges(cx, self, |cx| new_parent.AppendChild(cx, self));
1450 // Step 21. If node is an Element and the effective command value of command for node is not loosely equivalent to new value:
1451 if self.is::<Element>() &&
1452 !command.are_loosely_equivalent_values(
1453 self.effective_command_value(cx, command).as_ref(),
1454 Some(new_value),
1455 )
1456 {
1457 // Step 21.1. Insert node into the parent of new parent before new parent, preserving ranges.
1458 let parent_of_new_parent = new_parent.GetParentNode().expect("Must have a parent");
1459 move_preserving_ranges(cx, self, |cx| {
1460 parent_of_new_parent.InsertBefore(cx, self, Some(new_parent))
1461 });
1462 // Step 21.2. Remove new parent from its parent.
1463 new_parent.remove_self(cx);
1464 // Step 21.3. Let children be all children of node,
1465 // omitting any that are Elements whose specified command value for command is neither null nor equivalent to new value.
1466 let children = self
1467 .children()
1468 .filter(|child| {
1469 !child.downcast::<Element>().is_some_and(|child_element| {
1470 let specified_command_value =
1471 child_element.specified_command_value(cx, command);
1472 specified_command_value.is_some() &&
1473 !command.are_equivalent_values(
1474 specified_command_value.as_ref(),
1475 Some(new_value),
1476 )
1477 })
1478 })
1479 .collect::<Vec<DomRoot<Node>>>();
1480 // Step 21.4. Force the value of each node in children,
1481 // with command and new value as in this invocation of the algorithm.
1482 for child in children {
1483 child.force_the_value(cx, command, Some(new_value));
1484 }
1485 }
1486 }
1487
1488 /// <https://w3c.github.io/editing/docs/execCommand/#in-the-same-editing-host>
1489 pub(crate) fn same_editing_host(&self, other: &Node) -> bool {
1490 // > Two nodes are in the same editing host if the editing host of the first is non-null and the same as the editing host of the second.
1491 self.editing_host_of()
1492 .is_some_and(|editing_host| other.editing_host_of() == Some(editing_host))
1493 }
1494
1495 /// <https://w3c.github.io/editing/docs/execCommand/#block-node>
1496 pub(crate) fn is_block_node(&self, cx: &mut JSContext) -> bool {
1497 // > A block node is either an Element whose "display" property does not have resolved value "inline" or "inline-block" or "inline-table" or "none",
1498 if self
1499 .downcast::<Element>()
1500 .and_then(|element| element.resolved_display_value(cx))
1501 .is_some_and(|display| {
1502 display != DisplayOutside::Inline && display != DisplayOutside::None
1503 })
1504 {
1505 return true;
1506 }
1507 // > or a document, or a DocumentFragment.
1508 matches!(
1509 self.type_id(),
1510 NodeTypeId::Document(_) | NodeTypeId::DocumentFragment(_)
1511 )
1512 }
1513
1514 /// <https://w3c.github.io/editing/docs/execCommand/#inline-node>
1515 pub(crate) fn is_inline_node(&self, cx: &mut JSContext) -> bool {
1516 // > An inline node is a node that is not a block node.
1517 !self.is_block_node(cx)
1518 }
1519
1520 /// <https://w3c.github.io/editing/docs/execCommand/#block-node-of>
1521 pub(crate) fn block_node_of(&self, cx: &mut JSContext) -> Option<DomRoot<Node>> {
1522 let mut node = DomRoot::from_ref(self);
1523
1524 loop {
1525 // Step 1. While node is an inline node, set node to its parent.
1526 if node.is_inline_node(cx) {
1527 node = node.GetParentNode()?;
1528 continue;
1529 }
1530 // Step 2. Return node.
1531 return Some(node);
1532 }
1533 }
1534
1535 /// <https://w3c.github.io/editing/docs/execCommand/#visible>
1536 pub(crate) fn is_visible(&self, cx: &mut JSContext) -> bool {
1537 for parent in self.inclusive_ancestors(ShadowIncluding::No) {
1538 // > excluding any node with an inclusive ancestor Element whose "display" property has resolved value "none".
1539 if parent
1540 .downcast::<Element>()
1541 .and_then(|element| element.resolved_display_value(cx))
1542 .is_some_and(|display| display == DisplayOutside::None)
1543 {
1544 return false;
1545 }
1546 }
1547 // > Something is visible if it is a node that either is a block node,
1548 if self.is_block_node(cx) {
1549 return true;
1550 }
1551 // > or a Text node that is not a collapsed whitespace node,
1552 if self
1553 .downcast::<Text>()
1554 .is_some_and(|text| !text.is_collapsed_whitespace_node(cx))
1555 {
1556 return true;
1557 }
1558 // > or an img, or a br that is not an extraneous line break, or any node with a visible descendant;
1559 if self.is::<HTMLImageElement>() {
1560 return true;
1561 }
1562 if self
1563 .downcast::<HTMLBRElement>()
1564 .is_some_and(|br| !br.is_extraneous_line_break(cx))
1565 {
1566 return true;
1567 }
1568 for child in self.children() {
1569 if child.is_visible(cx) {
1570 return true;
1571 }
1572 }
1573 false
1574 }
1575
1576 /// <https://w3c.github.io/editing/docs/execCommand/#invisible>
1577 pub(crate) fn is_invisible(&self, cx: &mut JSContext) -> bool {
1578 // > Something is invisible if it is a node that is not visible.
1579 !self.is_visible(cx)
1580 }
1581
1582 /// <https://w3c.github.io/editing/docs/execCommand/#formattable-node>
1583 pub(crate) fn is_formattable(&self, cx: &mut JSContext) -> bool {
1584 // > A formattable node is an editable visible node that is either a Text node, an img, or a br.
1585 self.is_editable(cx) &&
1586 self.is_visible(cx) &&
1587 (self.is::<Text>() || self.is::<HTMLImageElement>() || self.is::<HTMLBRElement>())
1588 }
1589
1590 /// <https://w3c.github.io/editing/docs/execCommand/#single-line-container>
1591 pub(crate) fn is_single_line_container(&self) -> bool {
1592 // > A single-line container is either a non-list single-line container,
1593 // > or an HTML element with local name "li", "dt", or "dd".
1594 let Some(element) = self.downcast::<Element>() else {
1595 return false;
1596 };
1597 element.is_non_list_single_line_container() ||
1598 matches!(
1599 *element.local_name(),
1600 local_name!("li") | local_name!("dt") | local_name!("dd")
1601 )
1602 }
1603
1604 /// <https://w3c.github.io/editing/docs/execCommand/#block-start-point>
1605 pub(crate) fn is_block_start_point(&self, cx: &mut JSContext, offset: usize) -> bool {
1606 // > A boundary point (node, offset) is a block start point if either node's parent is null and offset is zero;
1607 if offset == 0 {
1608 return self.GetParentNode().is_none();
1609 }
1610 // > or node has a child with index offset − 1, and that child is either a visible block node or a visible br.
1611 let child = {
1612 let no_gc = cx.no_gc();
1613 self.children_unrooted(no_gc)
1614 .nth(offset - 1)
1615 .map(|node| node.as_rooted())
1616 };
1617 child.is_some_and(|child| {
1618 child.is_visible(cx) && (child.is_block_node(cx) || child.is::<HTMLBRElement>())
1619 })
1620 }
1621
1622 /// <https://w3c.github.io/editing/docs/execCommand/#block-end-point>
1623 pub(crate) fn is_block_end_point(&self, cx: &mut JSContext, offset: u32) -> bool {
1624 // > A boundary point (node, offset) is a block end point if either node's parent is null and offset is node's length;
1625 if self.GetParentNode().is_none() && offset == self.len() {
1626 return true;
1627 }
1628 // > or node has a child with index offset, and that child is a visible block node.
1629 self.children()
1630 .nth(offset as usize)
1631 .is_some_and(|child| child.is_visible(cx) && child.is_block_node(cx))
1632 }
1633
1634 /// <https://w3c.github.io/editing/docs/execCommand/#block-boundary-point>
1635 pub(crate) fn is_block_boundary_point(&self, cx: &mut JSContext, offset: u32) -> bool {
1636 // > A boundary point is a block boundary point if it is either a block start point or a block end point.
1637 self.is_block_start_point(cx, offset as usize) || self.is_block_end_point(cx, offset)
1638 }
1639
1640 pub(crate) fn is_no_allowed_child_in_same_editing_host(&self, no_gc: &NoGC) -> bool {
1641 // > If node is not an allowed child of any of its ancestors in the same editing host
1642 let Some(editing_host) = self.editing_host_of() else {
1643 return false;
1644 };
1645 let self_unrooted = UnrootedDom::from_ref(self, no_gc);
1646 self.ancestors_unrooted(no_gc)
1647 .take_while(|ancestor| ancestor.editing_host_of().as_ref() == Some(&editing_host))
1648 .all(|ancestor| {
1649 !is_allowed_child(
1650 NodeOrString::Node(self_unrooted.clone()),
1651 NodeOrString::Node(ancestor),
1652 )
1653 })
1654 }
1655
1656 /// <https://w3c.github.io/editing/docs/execCommand/#prohibited-paragraph-child>
1657 pub(crate) fn is_prohibited_paragraph_child(&self) -> bool {
1658 // > A prohibited paragraph child is an HTML element whose local name is a prohibited paragraph child name.
1659 let Some(node_as_element) = self.downcast::<HTMLElement>() else {
1660 return false;
1661 };
1662 PROHIBITED_PARAGRAPH_CHILD_NAMES.contains(&node_as_element.local_name())
1663 }
1664
1665 /// <https://w3c.github.io/editing/docs/execCommand/#fix-disallowed-ancestors>
1666 pub(crate) fn fix_disallowed_ancestors(&self, cx: &mut JSContext, context_object: &Document) {
1667 // Step 1. If node is not editable, abort these steps.
1668 if !self.is_editable(cx) {
1669 return;
1670 }
1671 // Step 2. If node is not an allowed child of any of its ancestors in the same editing host:
1672 if self.is_no_allowed_child_in_same_editing_host(cx.no_gc()) {
1673 // Step 2.1. If node is a dd or dt, wrap the one-node list consisting of node,
1674 // with sibling criteria returning true for any dl with no attributes and false otherwise,
1675 // and new parent instructions returning
1676 // the result of calling createElement("dl") on the context object.
1677 // Then abort these steps.
1678 if node_matches_local_name!(self, local_name!("dd") | local_name!("dt")) {
1679 wrap_node_list(
1680 cx,
1681 VecDeque::from([DomRoot::from_ref(self)]),
1682 |_cx, sibling| {
1683 sibling
1684 .downcast::<Element>()
1685 .is_some_and(|sibling_element| {
1686 let attrs = sibling_element.attrs().borrow();
1687 sibling_element.local_name() == &local_name!("dl") &&
1688 attrs.is_empty()
1689 })
1690 },
1691 |cx| Some(DomRoot::upcast(context_object.create_element(cx, "dl"))),
1692 );
1693 return;
1694 }
1695 // Step 2.2. If "p" is not an allowed child of the editing host of node,
1696 // abort these steps.
1697 if let Some(editing_host) = self.editing_host_of() &&
1698 !is_allowed_child(
1699 NodeOrString::String("p".to_owned()),
1700 NodeOrString::from_node(&editing_host, cx.no_gc()),
1701 )
1702 {
1703 return;
1704 }
1705 // Step 2.3. If node is not a prohibited paragraph child, abort these steps.
1706 if !self.is_prohibited_paragraph_child() {
1707 return;
1708 }
1709 // Step 2.4. Set the tag name of node to the default single-line container name,
1710 // and let node be the result.
1711 let node = self
1712 .downcast::<Element>()
1713 .expect("Must always be an element")
1714 .set_the_tag_name(
1715 cx,
1716 context_object.default_single_line_container_name().str(),
1717 );
1718 // Step 2.5. Fix disallowed ancestors of node.
1719 //
1720 // NOTE: We should only do this if we actually changed node. If node didn't change
1721 // (for example it was already the correct tag), then we would infinitely recurse
1722 // here. Therefore, we should check if we changed the node and only then do it
1723 // again.
1724 if *node != *self {
1725 node.fix_disallowed_ancestors(cx, context_object);
1726 }
1727 // Step 2.6. Let children be node's children.
1728 let children = node.children().collect::<Vec<DomRoot<Node>>>();
1729 // Step 2.7. For each child in children, if child is a prohibited paragraph child:
1730 for child in children {
1731 if child.is_prohibited_paragraph_child() {
1732 // Step 2.7.1. Record the values of the one-node list consisting of child,
1733 // and let values be the result.
1734 let values = record_the_values(cx, vec![child.clone()]);
1735 // Step 2.7.2. Split the parent of the one-node list consisting of child.
1736 split_the_parent(cx, &[&child]);
1737 // Step 2.7.3. Restore the values from values.
1738 restore_the_values(cx, values);
1739 }
1740 }
1741 // Step 2.8. Abort these steps.
1742 return;
1743 }
1744 // Step 3. Record the values of the one-node list consisting of node, and let values be the result.
1745 let values = record_the_values(cx, vec![DomRoot::from_ref(self)]);
1746 // Step 4. While node is not an allowed child of its parent,
1747 // split the parent of the one-node list consisting of node.
1748 loop {
1749 let Some(parent) = self.GetParentNode() else {
1750 break;
1751 };
1752 if is_allowed_child(
1753 NodeOrString::from_node(self, cx.no_gc()),
1754 NodeOrString::from_node(&parent, cx.no_gc()),
1755 ) {
1756 break;
1757 }
1758 split_the_parent(cx, &[self]);
1759 }
1760 // Step 5. Restore the values from values.
1761 restore_the_values(cx, values);
1762 }
1763
1764 /// <https://w3c.github.io/editing/docs/execCommand/#normalize-sublists>
1765 pub(crate) fn normalize_sublists(&self, cx: &mut JSContext) {
1766 let item_element = self
1767 .downcast::<Element>()
1768 .expect("item should be an element.");
1769
1770 // Step 1. If item is not an li or it is not editable or its parent is not editable, abort these steps.
1771 if !self.is::<HTMLLIElement>() ||
1772 !self.is_editable(cx) ||
1773 !self
1774 .GetParentElement()
1775 .is_some_and(|parent| parent.upcast::<Node>().is_editable(cx))
1776 {
1777 return;
1778 }
1779
1780 // Step 2. Let new item be null.
1781 let mut new_item: Option<DomRoot<Element>> = None;
1782
1783 // Step 3. While item has an ol or ul child:
1784 while self
1785 .child_elements()
1786 .any(|child| child.is::<HTMLOListElement>() || child.is::<HTMLUListElement>())
1787 {
1788 // Step 3.1. Let child be the last child of item.
1789 let child = self.GetLastChild().expect("Must have a last child here.");
1790
1791 // Step 3.2. If child is an ol or ul, or new item is null and child is a Text node whose data consists of zero of more space characters:
1792 if child.is::<HTMLOListElement>() ||
1793 child.is::<HTMLUListElement>() ||
1794 (new_item.is_none() &&
1795 child
1796 .downcast::<Text>()
1797 .is_some_and(|text| text.data().bytes().all(|byte| byte == b' ')))
1798 {
1799 // Step 3.2.1. Set new item to null.
1800 new_item = None;
1801
1802 // Step 3.2.2. Insert child into the parent of item immediately following item, preserving ranges.
1803 move_preserving_ranges(cx, &child, |cx| {
1804 item_element
1805 .insert_adjacent(cx, AdjacentPosition::AfterEnd, &child)
1806 .map(|elem| elem.expect("Should have inserted"))
1807 });
1808
1809 continue;
1810 }
1811 // Step 3.3. Otherwise:
1812 // Step 3.3.1. If new item is null,
1813 // let new item be the result of calling createElement("li") on the ownerDocument of item,
1814 // then insert new item into the parent of item immediately after item.
1815 if new_item.is_none() {
1816 new_item = Some(self.owner_document().create_element(cx, "li"));
1817 item_element
1818 .insert_adjacent(cx, AdjacentPosition::AfterEnd, &child)
1819 .expect("Insertion should always work here.");
1820 }
1821
1822 // Step 3.3.2. Insert child into new item as its first child, preserving ranges.
1823 move_preserving_ranges(cx, &child, |cx| {
1824 new_item
1825 .as_ref()
1826 .expect("Must have new item here")
1827 .downcast::<Element>()
1828 .expect("New item must be able to support children")
1829 .insert_adjacent(cx, AdjacentPosition::AfterBegin, &child)
1830 .map(|elem| elem.expect("Should have inserted"))
1831 });
1832 }
1833 }
1834
1835 /// <https://w3c.github.io/editing/docs/execCommand/#collapsed-block-prop>
1836 pub(crate) fn is_collapsed_block_prop(&self, cx: &mut JSContext) -> bool {
1837 // > A collapsed block prop is either a collapsed line break that is not an extraneous line break,
1838 if self.is_collapsed_line_break(cx) &&
1839 self.downcast::<HTMLBRElement>()
1840 .is_some_and(|br| !br.is_extraneous_line_break(cx))
1841 {
1842 return true;
1843 }
1844 // > or an Element that is an inline node and whose children are all either invisible or collapsed block props
1845 if !self.is::<Element>() {
1846 return false;
1847 };
1848 if !self.is_inline_node(cx) {
1849 return false;
1850 }
1851 let mut at_least_one_collapsed_block_prop = false;
1852 for child in self.children() {
1853 if child.is_collapsed_block_prop(cx) {
1854 at_least_one_collapsed_block_prop = true;
1855 continue;
1856 }
1857 if child.is_invisible(cx) {
1858 continue;
1859 }
1860
1861 return false;
1862 }
1863 // > and that has at least one child that is a collapsed block prop.
1864 at_least_one_collapsed_block_prop
1865 }
1866
1867 /// <https://w3c.github.io/editing/docs/execCommand/#follows-a-line-break>
1868 fn follows_a_line_break(&self, cx: &mut JSContext) -> bool {
1869 // Step 1. Let offset be zero.
1870 let mut offset = 0;
1871 // Step 2. While (node, offset) is not a block boundary point:
1872 let mut node = DomRoot::from_ref(self);
1873 while !node.is_block_boundary_point(cx, offset) {
1874 // Step 2.2. If offset is zero or node has no children, set offset to node's index, then set node to its parent.
1875 if offset == 0 || node.children_count() == 0 {
1876 offset = node.index();
1877 node = node.GetParentNode().expect("Must always have a parent");
1878 continue;
1879 }
1880 // Step 2.1. If node has a visible child with index offset minus one, return false.
1881 let child = node.children().nth(offset as usize - 1);
1882 let Some(child) = child else {
1883 return false;
1884 };
1885 if child.is_visible(cx) {
1886 return false;
1887 }
1888 // Step 2.3. Otherwise, set node to its child with index offset minus one, then set offset to node's length.
1889 node = child;
1890 offset = node.len();
1891 }
1892 // Step 3. Return true.
1893 true
1894 }
1895
1896 /// <https://w3c.github.io/editing/docs/execCommand/#precedes-a-line-break>
1897 fn precedes_a_line_break(&self, cx: &mut JSContext) -> bool {
1898 let mut node = DomRoot::from_ref(self);
1899 // Step 1. Let offset be node's length.
1900 let mut offset = node.len();
1901 // Step 2. While (node, offset) is not a block boundary point:
1902 while !node.is_block_boundary_point(cx, offset) {
1903 // Step 2.1. If node has a visible child with index offset, return false.
1904 if node
1905 .children()
1906 .nth(offset as usize)
1907 .is_some_and(|child| child.is_visible(cx))
1908 {
1909 return false;
1910 }
1911 // Step 2.2. If offset is node's length or node has no children, set offset to one plus node's index, then set node to its parent.
1912 if offset == node.len() || node.children_count() == 0 {
1913 offset = 1 + node.index();
1914 node = node.GetParentNode().expect("Must always have a parent");
1915 continue;
1916 }
1917 // Step 2.3. Otherwise, set node to its child with index offset and set offset to zero.
1918 let child = node.children().nth(offset as usize);
1919 node = match child {
1920 None => return false,
1921 Some(child) => child,
1922 };
1923 offset = 0;
1924 }
1925 // Step 3. Return true.
1926 true
1927 }
1928
1929 /// <https://w3c.github.io/editing/docs/execCommand/#canonical-space-sequence>
1930 fn canonical_space_sequence(
1931 n: usize,
1932 non_breaking_start: bool,
1933 non_breaking_end: bool,
1934 ) -> String {
1935 let mut n = n;
1936 // Step 1. If n is zero, return the empty string.
1937 if n == 0 {
1938 return String::new();
1939 }
1940 // Step 2. If n is one and both non-breaking start and non-breaking end are false, return a single space (U+0020).
1941 if n == 1 {
1942 if !non_breaking_start && !non_breaking_end {
1943 return "\u{0020}".to_owned();
1944 }
1945 // Step 3. If n is one, return a single non-breaking space (U+00A0).
1946 return "\u{00A0}".to_owned();
1947 }
1948 // Step 4. Let buffer be the empty string.
1949 let mut buffer = String::new();
1950 // Step 5. If non-breaking start is true, let repeated pair be U+00A0 U+0020. Otherwise, let it be U+0020 U+00A0.
1951 let repeated_pair = if non_breaking_start {
1952 "\u{00A0}\u{0020}"
1953 } else {
1954 "\u{0020}\u{00A0}"
1955 };
1956 // Step 6. While n is greater than three, append repeated pair to buffer and subtract two from n.
1957 while n > 3 {
1958 buffer.push_str(repeated_pair);
1959 n -= 2;
1960 }
1961 // Step 7. If n is three, append a three-code unit string to buffer depending on non-breaking start and non-breaking end:
1962 if n == 3 {
1963 buffer.push_str(match (non_breaking_start, non_breaking_end) {
1964 (false, false) => "\u{0020}\u{00A0}\u{0020}",
1965 (true, false) => "\u{00A0}\u{00A0}\u{0020}",
1966 (false, true) => "\u{0020}\u{00A0}\u{00A0}",
1967 (true, true) => "\u{00A0}\u{0020}\u{00A0}",
1968 });
1969 } else {
1970 // Step 8. Otherwise, append a two-code unit string to buffer depending on non-breaking start and non-breaking end:
1971 buffer.push_str(match (non_breaking_start, non_breaking_end) {
1972 (false, false) | (true, false) => "\u{00A0}\u{0020}",
1973 (false, true) => "\u{0020}\u{00A0}",
1974 (true, true) => "\u{00A0}\u{00A0}",
1975 });
1976 }
1977 // Step 9. Return buffer.
1978 buffer
1979 }
1980
1981 /// <https://w3c.github.io/editing/docs/execCommand/#canonicalize-whitespace>
1982 pub(crate) fn canonicalize_whitespace(
1983 &self,
1984 cx: &mut JSContext,
1985 offset: u32,
1986 fix_collapsed_space: bool,
1987 ) {
1988 // Step 1. If node is neither editable nor an editing host, abort these steps.
1989 if !self.is_editable_or_editing_host() {
1990 return;
1991 }
1992 // Step 2. Let start node equal node and let start offset equal offset.
1993 let mut start_node = DomRoot::from_ref(self);
1994 let mut start_offset = offset;
1995 // Step 3. Repeat the following steps:
1996 loop {
1997 // Step 3.1. If start node has a child in the same editing host with index start offset minus one,
1998 // set start node to that child, then set start offset to start node's length.
1999 if start_offset > 0 {
2000 let child = start_node.children().nth(start_offset as usize - 1);
2001 if let Some(child) = child &&
2002 start_node.same_editing_host(&child)
2003 {
2004 start_node = child;
2005 start_offset = start_node.len();
2006 continue;
2007 };
2008 }
2009 // Step 3.2. Otherwise, if start offset is zero and start node does not follow a line break
2010 // and start node's parent is in the same editing host, set start offset to start node's index,
2011 // then set start node to its parent.
2012 if start_offset == 0 &&
2013 !start_node.follows_a_line_break(cx) &&
2014 let Some(parent) = start_node.GetParentNode() &&
2015 parent.same_editing_host(&start_node)
2016 {
2017 start_offset = start_node.index();
2018 start_node = parent;
2019 }
2020 // Step 3.3. Otherwise, if start node is a Text node and its parent's resolved
2021 // value for "white-space" is neither "pre" nor "pre-wrap" and start offset is not zero
2022 // and the (start offset − 1)st code unit of start node's data is a space (0x0020) or
2023 // non-breaking space (0x00A0), subtract one from start offset.
2024 if start_offset != 0 &&
2025 start_node.downcast::<Text>().is_some_and(|text| {
2026 text.has_whitespace_and_has_parent_with_whitespace_preserve(
2027 cx,
2028 start_offset - 1,
2029 &[&'\u{0020}', &'\u{00A0}'],
2030 )
2031 })
2032 {
2033 start_offset -= 1;
2034 }
2035 // Step 3.4. Otherwise, break from this loop.
2036 break;
2037 }
2038 // Step 4. Let end node equal start node and end offset equal start offset.
2039 let mut end_node = start_node.clone();
2040 let mut end_offset = start_offset;
2041 // Step 5. Let length equal zero.
2042 let mut length = 0;
2043 // Step 6. Let collapse spaces be true if start offset is zero and start node follows a line break, otherwise false.
2044 let mut collapse_spaces = start_offset == 0 && start_node.follows_a_line_break(cx);
2045 // Step 7. Repeat the following steps:
2046 loop {
2047 // Step 7.1. If end node has a child in the same editing host with index end offset,
2048 // set end node to that child, then set end offset to zero.
2049 if let Some(child) = end_node.children().nth(end_offset as usize) &&
2050 child.same_editing_host(&end_node)
2051 {
2052 end_node = child;
2053 end_offset = 0;
2054 continue;
2055 }
2056 // Step 7.2. Otherwise, if end offset is end node's length
2057 // and end node does not precede a line break
2058 // and end node's parent is in the same editing host,
2059 // set end offset to one plus end node's index, then set end node to its parent.
2060 if end_offset == end_node.len() &&
2061 !end_node.precedes_a_line_break(cx) &&
2062 let Some(parent) = end_node.GetParentNode() &&
2063 parent.same_editing_host(&end_node)
2064 {
2065 end_offset = 1 + end_node.index();
2066 end_node = parent;
2067 continue;
2068 }
2069 // Step 7.3. Otherwise, if end node is a Text node and its parent's resolved value for "white-space"
2070 // is neither "pre" nor "pre-wrap"
2071 // and end offset is not end node's length and the end offsetth code unit of end node's data
2072 // is a space (0x0020) or non-breaking space (0x00A0):
2073 if let Some(text) = end_node.downcast::<Text>() &&
2074 text.has_whitespace_and_has_parent_with_whitespace_preserve(
2075 cx,
2076 end_offset,
2077 &[&'\u{0020}', &'\u{00A0}'],
2078 )
2079 {
2080 // Step 7.3.1. If fix collapsed space is true, and collapse spaces is true,
2081 // and the end offsetth code unit of end node's data is a space (0x0020):
2082 // call deleteData(end offset, 1) on end node, then continue this loop from the beginning.
2083 let has_space_at_offset = text
2084 .data()
2085 .chars()
2086 .nth(end_offset as usize)
2087 .is_some_and(|c| c == '\u{0020}');
2088 if fix_collapsed_space && collapse_spaces && has_space_at_offset {
2089 if text
2090 .upcast::<CharacterData>()
2091 .DeleteData(cx, end_offset, 1)
2092 .is_err()
2093 {
2094 unreachable!("Invalid deletion for character at end offset");
2095 }
2096 continue;
2097 }
2098 // Step 7.3.2. Set collapse spaces to true if the end offsetth code unit of
2099 // end node's data is a space (0x0020), false otherwise.
2100 collapse_spaces = text
2101 .data()
2102 .chars()
2103 .nth(end_offset as usize)
2104 .is_some_and(|c| c == '\u{0020}');
2105 // Step 7.3.3. Add one to end offset.
2106 end_offset += 1;
2107 // Step 7.3.4. Add one to length.
2108 length += 1;
2109 continue;
2110 }
2111 // Step 7.4. Otherwise, break from this loop.
2112 break;
2113 }
2114 // Step 8. If fix collapsed space is true, then while (start node, start offset)
2115 // is before (end node, end offset):
2116 if fix_collapsed_space {
2117 while bp_position(cx.no_gc(), &start_node, start_offset, &end_node, end_offset) ==
2118 Ordering::Less
2119 {
2120 // Step 8.1. If end node has a child in the same editing host with index end offset − 1,
2121 // set end node to that child, then set end offset to end node's length.
2122 if end_offset > 0 &&
2123 let Some(child) = end_node.children().nth(end_offset as usize - 1) &&
2124 child.same_editing_host(&end_node)
2125 {
2126 end_node = child;
2127 end_offset = end_node.len();
2128 continue;
2129 }
2130 // Step 8.2. Otherwise, if end offset is zero and end node's parent is in the same editing host,
2131 // set end offset to end node's index, then set end node to its parent.
2132 if let Some(parent) = end_node.GetParentNode() &&
2133 end_offset == 0 &&
2134 parent.same_editing_host(&end_node)
2135 {
2136 end_offset = end_node.index();
2137 end_node = parent;
2138 continue;
2139 }
2140 // Step 8.3. Otherwise, if end node is a Text node and its parent's resolved value for "white-space"
2141 // is neither "pre" nor "pre-wrap"
2142 // and end offset is end node's length and the last code unit of end node's data
2143 // is a space (0x0020) and end node precedes a line break:
2144 if let Some(text) = end_node.downcast::<Text>() &&
2145 text.has_whitespace_and_has_parent_with_whitespace_preserve(
2146 cx,
2147 text.data().len() as u32,
2148 &[&'\u{0020}'],
2149 ) &&
2150 end_node.precedes_a_line_break(cx)
2151 {
2152 // Step 8.3.1. Subtract one from end offset.
2153 end_offset -= 1;
2154 // Step 8.3.2. Subtract one from length.
2155 length -= 1;
2156 // Step 8.3.3. Call deleteData(end offset, 1) on end node.
2157 if text
2158 .upcast::<CharacterData>()
2159 .DeleteData(cx, end_offset, 1)
2160 .is_err()
2161 {
2162 unreachable!("Invalid deletion for character at end offset");
2163 }
2164 continue;
2165 }
2166 // Step 8.4. Otherwise, break from this loop.
2167 break;
2168 }
2169 }
2170 // Step 9. Let replacement whitespace be the canonical space sequence of length length.
2171 // non-breaking start is true if start offset is zero and start node follows a line break, and false otherwise.
2172 // non-breaking end is true if end offset is end node's length and end node precedes a line break, and false otherwise.
2173 let replacement_whitespace = Node::canonical_space_sequence(
2174 length,
2175 start_offset == 0 && start_node.follows_a_line_break(cx),
2176 end_offset == end_node.len() && end_node.precedes_a_line_break(cx),
2177 );
2178 let mut replacement_whitespace_chars = replacement_whitespace.chars();
2179 // Step 10. While (start node, start offset) is before (end node, end offset):
2180 while bp_position(cx.no_gc(), &start_node, start_offset, &end_node, end_offset) ==
2181 Ordering::Less
2182 {
2183 // Step 10.1. If start node has a child with index start offset, set start node to that child, then set start offset to zero.
2184 if let Some(child) = start_node.children().nth(start_offset as usize) {
2185 start_node = child;
2186 start_offset = 0;
2187 continue;
2188 }
2189 // Step 10.2. Otherwise, if start node is not a Text node or if start offset is start node's length,
2190 // set start offset to one plus start node's index, then set start node to its parent.
2191 let start_node_as_text = start_node.downcast::<Text>();
2192 if start_node_as_text.is_none() || start_offset == start_node.len() {
2193 start_offset = 1 + start_node.index();
2194 start_node = start_node
2195 .GetParentNode()
2196 .expect("Must always have a parent");
2197 continue;
2198 }
2199 let start_node_as_text =
2200 start_node_as_text.expect("Already verified none in previous statement");
2201 // Step 10.3. Otherwise:
2202 // Step 10.3.1. Remove the first code unit from replacement whitespace, and let element be that code unit.
2203 if let Some(element) = replacement_whitespace_chars.next() {
2204 // Step 10.3.2. If element is not the same as the start offsetth code unit of start node's data:
2205 if start_node_as_text.data().chars().nth(start_offset as usize) != Some(element) {
2206 let character_data = start_node_as_text.upcast::<CharacterData>();
2207 // Step 10.3.2.1. Call insertData(start offset, element) on start node.
2208 if character_data
2209 .InsertData(cx, start_offset, element.to_string().into())
2210 .is_err()
2211 {
2212 unreachable!("Invalid insertion for character at start offset");
2213 }
2214 // Step 10.3.2.2. Call deleteData(start offset + 1, 1) on start node.
2215 if character_data.DeleteData(cx, start_offset + 1, 1).is_err() {
2216 unreachable!("Invalid deletion for character at start offset + 1");
2217 }
2218 }
2219 }
2220 // Step 10.3.3. Add one to start offset.
2221 start_offset += 1;
2222 }
2223 }
2224
2225 /// <https://w3c.github.io/editing/docs/execCommand/#remove-extraneous-line-breaks-before>
2226 fn remove_extraneous_line_breaks_before(&self, cx: &mut JSContext) {
2227 let parent = self.GetParentNode();
2228 // Step 1. Let ref be the previousSibling of node.
2229 let Some(mut ref_) = self.GetPreviousSibling() else {
2230 // Step 2. If ref is null, abort these steps.
2231 return;
2232 };
2233 // Step 3. While ref has children, set ref to its lastChild.
2234 while let Some(last_child) = ref_.children().last() {
2235 ref_ = last_child;
2236 }
2237 // Step 4. While ref is invisible but not an extraneous line break,
2238 // and ref does not equal node's parent, set ref to the node before it in tree order.
2239 loop {
2240 if ref_.is_invisible(cx) &&
2241 ref_.downcast::<HTMLBRElement>()
2242 .is_none_or(|br| !br.is_extraneous_line_break(cx)) &&
2243 let Some(parent) = parent.as_ref() &&
2244 ref_ != *parent
2245 {
2246 ref_ = match ref_.preceding_nodes(parent).nth(0) {
2247 None => break,
2248 Some(node) => node,
2249 };
2250 continue;
2251 }
2252 break;
2253 }
2254 // Step 5. If ref is an editable extraneous line break, remove it from its parent.
2255 if ref_.is_editable(cx) &&
2256 ref_.downcast::<HTMLBRElement>()
2257 .is_some_and(|br| br.is_extraneous_line_break(cx))
2258 {
2259 assert!(ref_.has_parent());
2260 ref_.remove_self(cx);
2261 }
2262 }
2263
2264 /// <https://w3c.github.io/editing/docs/execCommand/#remove-extraneous-line-breaks-at-the-end-of>
2265 pub(crate) fn remove_extraneous_line_breaks_at_the_end_of(&self, cx: &mut JSContext) {
2266 // Step 1. Let ref be node.
2267 let mut ref_ = DomRoot::from_ref(self);
2268 // Step 2. While ref has children, set ref to its lastChild.
2269 while let Some(last_child) = ref_.children().last() {
2270 ref_ = last_child;
2271 }
2272 // Step 3. While ref is invisible but not an extraneous line break, and ref does not equal node,
2273 // set ref to the node before it in tree order.
2274 loop {
2275 if ref_.is_invisible(cx) &&
2276 *ref_ != *self &&
2277 ref_.downcast::<HTMLBRElement>()
2278 .is_none_or(|br| !br.is_extraneous_line_break(cx)) &&
2279 let Some(parent_of_ref) = ref_.GetParentNode()
2280 {
2281 ref_ = match ref_.preceding_nodes(&parent_of_ref).nth(0) {
2282 None => break,
2283 Some(node) => node,
2284 };
2285 continue;
2286 }
2287 break;
2288 }
2289 // Step 4. If ref is an editable extraneous line break:
2290 if ref_.is_editable(cx) &&
2291 ref_.downcast::<HTMLBRElement>()
2292 .is_some_and(|br| br.is_extraneous_line_break(cx))
2293 {
2294 // Step 4.1. While ref's parent is editable and invisible, set ref to its parent.
2295 loop {
2296 if let Some(parent) = ref_.GetParentNode() &&
2297 parent.is_editable(cx) &&
2298 parent.is_invisible(cx)
2299 {
2300 ref_ = parent;
2301 continue;
2302 }
2303 break;
2304 }
2305 // Step 4.2. Remove ref from its parent.
2306 assert!(ref_.has_parent());
2307 ref_.remove_self(cx);
2308 }
2309 }
2310
2311 /// <https://w3c.github.io/editing/docs/execCommand/#remove-extraneous-line-breaks-from>
2312 fn remove_extraneous_line_breaks_from(&self, cx: &mut JSContext) {
2313 // > To remove extraneous line breaks from a node, first remove extraneous line breaks before it,
2314 // > then remove extraneous line breaks at the end of it.
2315 self.remove_extraneous_line_breaks_before(cx);
2316 self.remove_extraneous_line_breaks_at_the_end_of(cx);
2317 }
2318
2319 /// <https://w3c.github.io/editing/docs/execCommand/#preserving-its-descendants>
2320 pub(crate) fn remove_preserving_its_descendants(&self, cx: &mut JSContext) {
2321 // > To remove a node node while preserving its descendants,
2322 // > split the parent of node's children if it has any.
2323 // > If it has no children, instead remove it from its parent.
2324 if self.children_count() == 0 {
2325 assert!(self.has_parent());
2326 self.remove_self(cx);
2327 } else {
2328 rooted_vec!(let children <- self.children().map(|child| DomRoot::as_traced(&child)));
2329 split_the_parent(cx, children.as_ref_slice());
2330 }
2331 }
2332
2333 /// <https://w3c.github.io/editing/docs/execCommand/#effective-command-value>
2334 pub(crate) fn effective_command_value(
2335 &self,
2336 cx: &mut JSContext,
2337 command: &CommandName,
2338 ) -> Option<DOMString> {
2339 // Step 1. If neither node nor its parent is an Element, return null.
2340 // Step 2. If node is not an Element, return the effective command value of its parent for command.
2341 let Some(element) = self.downcast::<Element>() else {
2342 return self
2343 .GetParentElement()
2344 .and_then(|parent| parent.upcast::<Node>().effective_command_value(cx, command));
2345 };
2346 match command {
2347 // Step 3. If command is "createLink" or "unlink":
2348 CommandName::CreateLink | CommandName::Unlink => {
2349 // Step 3.1. While node is not null, and is not an a element that has an href attribute, set node to its parent.
2350 let mut current_node = Some(DomRoot::from_ref(self));
2351 while let Some(node) = current_node {
2352 if let Some(anchor_value) =
2353 node.downcast::<HTMLAnchorElement>().and_then(|anchor| {
2354 anchor
2355 .upcast::<Element>()
2356 .get_attribute_string_value(&local_name!("href"))
2357 })
2358 {
2359 // Step 3.3. Return the value of node's href attribute.
2360 return Some(anchor_value.into());
2361 }
2362 current_node = node.GetParentNode();
2363 }
2364 // Step 3.2. If node is null, return null.
2365 None
2366 },
2367 // Step 4. If command is "backColor" or "hiliteColor":
2368 CommandName::BackColor | CommandName::HiliteColor => {
2369 // Step 4.1. While the resolved value of "background-color" on node is any fully transparent value,
2370 // and node's parent is an Element, set node to its parent.
2371 let mut current_element = Some(DomRoot::from_ref(element));
2372 while let Some(element) = current_element {
2373 if let Some(background_color) =
2374 CssPropertyName::BackgroundColor.resolved_value_for_node(cx, &element)
2375 {
2376 // Step 4.2. Return the resolved value of "background-color" for node.
2377 return Some(background_color);
2378 }
2379 current_element = element.upcast::<Node>().GetParentElement();
2380 }
2381 Some(DOMString::from_static("rgba(0, 0, 0, 0)"))
2382 },
2383 // Step 5. If command is "subscript" or "superscript":
2384 CommandName::Subscript | CommandName::Superscript => {
2385 // Step 5.1. Let affected by subscript and affected by superscript be two boolean variables,
2386 // both initially false.
2387 let mut affected_by_subscript = false;
2388 let mut affected_by_superscript = false;
2389 // Step 5.2. While node is an inline node:
2390 let mut current_node = Some(DomRoot::from_ref(self));
2391 while let Some(node) = current_node {
2392 if !node.is_inline_node(cx) {
2393 break;
2394 }
2395 if let Some(element) = node.downcast::<Element>() {
2396 // Step 5.2.1. If node is a sub, set affected by subscript to true.
2397 if *element.local_name() == local_name!("sub") {
2398 affected_by_subscript = true;
2399 } else if *element.local_name() == local_name!("sup") {
2400 // Step 5.2.2. Otherwise, if node is a sup, set affected by superscript to true.
2401 affected_by_superscript = true;
2402 }
2403 }
2404 // Step 5.2.3. Set node to its parent.
2405 current_node = node.GetParentNode();
2406 }
2407 Some(match (affected_by_subscript, affected_by_superscript) {
2408 // Step 5.3. If affected by subscript and affected by superscript are both true,
2409 // return the string "mixed".
2410 (true, true) => DOMString::from_static("mixed"),
2411 // Step 5.4. If affected by subscript is true, return "subscript".
2412 (true, false) => DOMString::from_static("subscript"),
2413 // Step 5.5. If affected by superscript is true, return "superscript".
2414 (false, true) => DOMString::from_static("superscript"),
2415 // Step 5.6. Return null.
2416 (false, false) => return None,
2417 })
2418 },
2419 // Step 6. If command is "strikethrough",
2420 // and the "text-decoration" property of node or any of its ancestors has resolved value containing "line-through",
2421 // return "line-through". Otherwise, return null.
2422 CommandName::Strikethrough => self
2423 .inclusive_ancestors(ShadowIncluding::No)
2424 .any(|node| {
2425 node.downcast::<Element>()
2426 .and_then(|element| {
2427 CssPropertyName::TextDecorationLine.resolved_value_for_node(cx, element)
2428 })
2429 .is_some_and(|property| property.contains("line-through"))
2430 })
2431 .then_some(DOMString::from_static("line-through")),
2432 // Step 7. If command is "underline",
2433 // and the "text-decoration" property of node or any of its ancestors has resolved value containing "underline",
2434 // return "underline". Otherwise, return null.
2435 CommandName::Underline => self
2436 .inclusive_ancestors(ShadowIncluding::No)
2437 .any(|node| {
2438 node.downcast::<Element>()
2439 .and_then(|element| {
2440 CssPropertyName::TextDecorationLine.resolved_value_for_node(cx, element)
2441 })
2442 .is_some_and(|property| property.contains("underline"))
2443 })
2444 .then_some(DOMString::from_static("underline")),
2445 // Step 8. Return the resolved value for node of the relevant CSS property for command.
2446 _ => command.resolved_value_for_node(cx, element),
2447 }
2448 }
2449
2450 /// <https://w3c.github.io/editing/docs/execCommand/#collapsed-line-break>
2451 pub(crate) fn is_collapsed_line_break(&self, cx: &mut JSContext) -> bool {
2452 // > A collapsed line break is a br that begins a line box which has nothing else in it,
2453 // > and therefore has zero height.
2454 //
2455 // This also takes into account a newly created text node with the only value "\n", since
2456 // that's what browsers insert when the white-space CSS property indicates it has pre-formatted
2457 // content.
2458 if !self.is::<HTMLBRElement>() &&
2459 !self
2460 .downcast::<Text>()
2461 .is_some_and(|text| text.data().as_str() == "\n")
2462 {
2463 return false;
2464 }
2465
2466 // Inspired by the reverse-engineered implementation from Ladybird, we look at DOM nodes to
2467 // figure out what "nothing else in it" means. However, we don't follow the logic from Ladybird
2468 // completely, as the end-condition for block nodes is different.
2469 //
2470 // If the next node contains some text, then it is not collapsed. This would be the case where
2471 // there is a `<br>some text`.
2472 //
2473 // In any other case, we either have inline or block nodes. For inline nodes, it means that these
2474 // nodes would be rendered on the same line. In that case, we also aren't collapsed. For example
2475 // when there is a `<br><span></span>`
2476 //
2477 // Only in the case that a `<br>` is followed by nothing (whitespace or no nodes) leading immediately
2478 // to a block node, it is considered collapsed.
2479 let editing_host = self.editing_host_of().expect("Must always be editable");
2480 let root = self
2481 .block_node_of(cx)
2482 // It could be that all ancestors up to and including the editing host are all inline. In that case
2483 // we should only consider up to the editing host, as it acts as the bounding box for considering
2484 // whether something is collapsed.
2485 .filter(|block_node| editing_host.is_ancestor_of(block_node))
2486 .unwrap_or(editing_host);
2487
2488 for following in self.following_nodes(&root, ShadowIncluding::No) {
2489 if let Some(text) = following.downcast::<Text>() {
2490 if text.is_whitespace_node(cx) {
2491 continue;
2492 }
2493 return false;
2494 }
2495
2496 // This is checking if we have nodes like comments, which we should not consider for this algorithm
2497 let Some(element) = following.downcast::<Element>() else {
2498 continue;
2499 };
2500
2501 if following.is_block_node(cx) {
2502 return true;
2503 }
2504
2505 if element.is_void() {
2506 return false;
2507 }
2508 }
2509
2510 true
2511 }
2512}