script/dom/execcommand/contenteditable/selection.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;
6
7use js::context::JSContext;
8use script_bindings::codegen::GenericBindings::RangeBinding::RangeMethods;
9use script_bindings::codegen::GenericBindings::SelectionBinding::SelectionMethods;
10use script_bindings::inheritance::Castable;
11
12use crate::dom::abstractrange::bp_position;
13use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
14use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
15use crate::dom::bindings::codegen::Bindings::TextBinding::TextMethods;
16use crate::dom::bindings::root::{DomRoot, DomSlice};
17use crate::dom::bindings::str::DOMString;
18use crate::dom::characterdata::CharacterData;
19use crate::dom::document::Document;
20use crate::dom::execcommand::basecommand::CommandName;
21use crate::dom::execcommand::contenteditable::node::{
22 NodeOrString, is_allowed_child, move_preserving_ranges, record_the_values, restore_the_values,
23 split_the_parent,
24};
25use crate::dom::html::htmlbrelement::HTMLBRElement;
26use crate::dom::html::htmlelement::HTMLElement;
27use crate::dom::html::htmltablecellelement::HTMLTableCellElement;
28use crate::dom::html::htmltablerowelement::HTMLTableRowElement;
29use crate::dom::html::htmltablesectionelement::HTMLTableSectionElement;
30use crate::dom::node::Node;
31use crate::dom::selection::Selection;
32use crate::dom::text::Text;
33
34#[derive(Default, PartialEq)]
35pub(crate) enum SelectionDeletionBlockMerging {
36 #[default]
37 Merge,
38 Skip,
39}
40
41#[derive(Default, PartialEq)]
42pub(crate) enum SelectionDeletionStripWrappers {
43 #[default]
44 Strip,
45 NoStrip,
46}
47
48#[derive(Default, PartialEq)]
49pub(crate) enum SelectionDeleteDirection {
50 #[default]
51 Forward,
52 Backward,
53}
54
55trait EquivalentPoint {
56 fn previous_equivalent_point(&self) -> Option<(DomRoot<Node>, u32)>;
57 fn next_equivalent_point(&self) -> Option<(DomRoot<Node>, u32)>;
58 fn first_equivalent_point(self) -> (DomRoot<Node>, u32);
59 fn last_equivalent_point(self) -> (DomRoot<Node>, u32);
60}
61
62impl EquivalentPoint for (DomRoot<Node>, u32) {
63 /// <https://w3c.github.io/editing/docs/execCommand/#previous-equivalent-point>
64 fn previous_equivalent_point(&self) -> Option<(DomRoot<Node>, u32)> {
65 let (node, offset) = self;
66 // Step 1. If node's length is zero, return null.
67 let len = node.len();
68 if len == 0 {
69 return None;
70 }
71 // Step 2. If offset is 0, and node's parent is not null, and node is an inline node,
72 // return (node's parent, node's index).
73 if *offset == 0 &&
74 node.is_inline_node() &&
75 let Some(parent) = node.GetParentNode()
76 {
77 return Some((parent, node.index()));
78 }
79 // Step 3. If node has a child with index offset − 1, and that child's length is not zero,
80 // and that child is an inline node, return (that child, that child's length).
81 if *offset > 0 &&
82 let Some(child) = node.children().nth(*offset as usize - 1) &&
83 !child.is_empty() &&
84 child.is_inline_node()
85 {
86 let len = child.len();
87 return Some((child, len));
88 }
89
90 // Step 4. Return null.
91 None
92 }
93
94 /// <https://w3c.github.io/editing/docs/execCommand/#next-equivalent-point>
95 fn next_equivalent_point(&self) -> Option<(DomRoot<Node>, u32)> {
96 let (node, offset) = self;
97 // Step 1. If node's length is zero, return null.
98 let len = node.len();
99 if len == 0 {
100 return None;
101 }
102
103 // Step 2.
104 //
105 // This step does not exist in the spec
106
107 // Step 3. If offset is node's length, and node's parent is not null, and node is an inline node,
108 // return (node's parent, 1 + node's index).
109 if *offset == len &&
110 node.is_inline_node() &&
111 let Some(parent) = node.GetParentNode()
112 {
113 return Some((parent, node.index() + 1));
114 }
115
116 // Step 4.
117 //
118 // This step does not exist in the spec
119
120 // Step 5. If node has a child with index offset, and that child's length is not zero,
121 // and that child is an inline node, return (that child, 0).
122 if let Some(child) = node.children().nth(*offset as usize) &&
123 !child.is_empty() &&
124 child.is_inline_node()
125 {
126 return Some((child, 0));
127 }
128
129 // Step 6.
130 //
131 // This step does not exist in the spec
132
133 // Step 7. Return null.
134 None
135 }
136
137 /// <https://w3c.github.io/editing/docs/execCommand/#first-equivalent-point>
138 fn first_equivalent_point(self) -> (DomRoot<Node>, u32) {
139 let mut previous_equivalent_point = self;
140 // Step 1. While (node, offset)'s previous equivalent point is not null, set (node, offset) to its previous equivalent point.
141 loop {
142 if let Some(next) = previous_equivalent_point.previous_equivalent_point() {
143 previous_equivalent_point = next;
144 } else {
145 // Step 2. Return (node, offset).
146 return previous_equivalent_point;
147 }
148 }
149 }
150
151 /// <https://w3c.github.io/editing/docs/execCommand/#last-equivalent-point>
152 fn last_equivalent_point(self) -> (DomRoot<Node>, u32) {
153 let mut next_equivalent_point = self;
154 // Step 1. While (node, offset)'s next equivalent point is not null, set (node, offset) to its next equivalent point.
155 loop {
156 if let Some(next) = next_equivalent_point.next_equivalent_point() {
157 next_equivalent_point = next;
158 } else {
159 // Step 2. Return (node, offset).
160 return next_equivalent_point;
161 }
162 }
163 }
164}
165
166impl Selection {
167 /// <https://w3c.github.io/editing/docs/execCommand/#delete-the-selection>
168 pub(crate) fn delete_the_selection(
169 &self,
170 cx: &mut JSContext,
171 context_object: &Document,
172 block_merging: SelectionDeletionBlockMerging,
173 strip_wrappers: SelectionDeletionStripWrappers,
174 direction: SelectionDeleteDirection,
175 ) {
176 // Step 1. If the active range is null, abort these steps and do nothing.
177 if self.active_range(cx).is_none() {
178 return;
179 };
180
181 // Step 2. Canonicalize whitespace at the active range's start.
182 let (start_container, start_offset) = self.start_boundary(cx);
183 start_container.canonicalize_whitespace(cx, start_offset, true);
184
185 // Step 3. Canonicalize whitespace at the active range's end.
186 let (end_container, end_offset) = self.end_boundary(cx);
187 end_container.canonicalize_whitespace(cx, end_offset, true);
188
189 // Step 4. Let (start node, start offset) be the last equivalent point for the active range's start.
190 let (mut start_node, mut start_offset) = self.start_boundary(cx).last_equivalent_point();
191
192 // Step 5. Let (end node, end offset) be the first equivalent point for the active range's end.
193 let (mut end_node, mut end_offset) = self.end_boundary(cx).first_equivalent_point();
194
195 // Step 6. If (end node, end offset) is not after (start node, start offset):
196 if bp_position(&end_node, end_offset, &start_node, start_offset) != Ordering::Greater {
197 // Step 6.1. If direction is "forward", call collapseToStart() on the context object's selection.
198 if direction == SelectionDeleteDirection::Forward {
199 let _ = self.CollapseToStart(cx);
200 } else {
201 // Step 6.2. Otherwise, call collapseToEnd() on the context object's selection.
202 let _ = self.CollapseToEnd(cx);
203 }
204 // Step 6.3. Abort these steps.
205 return;
206 }
207
208 // Step 7. If start node is a Text node and start offset is 0, set start offset to the index of start node,
209 // then set start node to its parent.
210 if start_node.is::<Text>() && start_offset == 0 {
211 start_offset = start_node.index();
212 start_node = start_node
213 .GetParentNode()
214 .expect("Must always have a parent");
215 }
216
217 // Step 8. If end node is a Text node and end offset is its length, set end offset to one plus the index of end node,
218 // then set end node to its parent.
219 if end_node.is::<Text>() && end_offset == end_node.len() {
220 end_offset = end_node.index() + 1;
221 end_node = end_node.GetParentNode().expect("Must always have a parent");
222 }
223
224 // Step 9. Call collapse(start node, start offset) on the context object's selection.
225 let _ = self.Collapse(cx, Some(&start_node), start_offset);
226
227 // Step 10. Call extend(end node, end offset) on the context object's selection.
228 let _ = self.Extend(cx, &end_node, end_offset);
229
230 // Step 11.
231 //
232 // This step does not exist in the spec
233
234 // Step 12. Let start block be the active range's start node.
235 let mut start_block = self.start_boundary(cx).0;
236
237 // Step 13. While start block's parent is in the same editing host and start block is an inline node,
238 // set start block to its parent.
239 loop {
240 if start_block.is_inline_node() &&
241 let Some(parent) = start_block.GetParentNode() &&
242 parent.same_editing_host(&start_node)
243 {
244 start_block = parent;
245 continue;
246 }
247 break;
248 }
249
250 // Step 14. If start block is neither a block node nor an editing host,
251 // or "span" is not an allowed child of start block,
252 // or start block is a td or th, set start block to null.
253 let start_block = if (!start_block.is_block_node() && !start_block.is_editing_host()) ||
254 !is_allowed_child(
255 NodeOrString::String("span".to_owned()),
256 NodeOrString::from_node(&start_block, cx.no_gc()),
257 ) ||
258 start_block.is::<HTMLTableCellElement>()
259 {
260 None
261 } else {
262 Some(start_block)
263 };
264
265 // Step 15. Let end block be the active range's end node.
266 let mut end_block = self.end_boundary(cx).0;
267
268 // Step 16. While end block's parent is in the same editing host and end block is an inline node, set end block to its parent.
269 loop {
270 if end_block.is_inline_node() &&
271 let Some(parent) = end_block.GetParentNode() &&
272 parent.same_editing_host(&end_block)
273 {
274 end_block = parent;
275 continue;
276 }
277 break;
278 }
279
280 // Step 17. If end block is neither a block node nor an editing host, or "span" is not an allowed child of end block,
281 // or end block is a td or th, set end block to null.
282 let end_block = if (!end_block.is_block_node() && !end_block.is_editing_host()) ||
283 !is_allowed_child(
284 NodeOrString::String("span".to_owned()),
285 NodeOrString::from_node(&end_block, cx.no_gc()),
286 ) ||
287 end_block.is::<HTMLTableCellElement>()
288 {
289 None
290 } else {
291 Some(end_block)
292 };
293
294 // Step 18.
295 //
296 // This step does not exist in the spec
297
298 // Step 19. Record current states and values, and let overrides be the result.
299 let overrides = self
300 .expect_active_range(cx)
301 .record_current_states_and_values(cx);
302
303 // Step 20.
304 //
305 // This step does not exist in the spec
306
307 // Step 21. If start node and end node are the same, and start node is an editable Text node:
308 if start_node == end_node &&
309 start_node.is_editable() &&
310 let Some(start_text) = start_node.downcast::<Text>()
311 {
312 // Step 21.1. Call deleteData(start offset, end offset − start offset) on start node.
313 if start_text
314 .upcast::<CharacterData>()
315 .DeleteData(cx, start_offset, end_offset - start_offset)
316 .is_err()
317 {
318 unreachable!("Must always be able to delete");
319 }
320 // Step 21.2. Canonicalize whitespace at (start node, start offset), with fix collapsed space false.
321 start_node.canonicalize_whitespace(cx, start_offset, false);
322 // Step 21.3. If direction is "forward", call collapseToStart() on the context object's selection.
323 if direction == SelectionDeleteDirection::Forward {
324 let _ = self.CollapseToStart(cx);
325 } else {
326 // Step 21.4. Otherwise, call collapseToEnd() on the context object's selection.
327 let _ = self.CollapseToEnd(cx);
328 }
329 // Step 21.5. Restore states and values from overrides.
330 self.expect_active_range(cx).restore_states_and_values(
331 cx,
332 self,
333 context_object,
334 overrides,
335 );
336
337 // Step 21.6. Abort these steps.
338 return;
339 }
340
341 // Step 22. If start node is an editable Text node, call deleteData() on it, with start offset as
342 // the first argument and (length of start node − start offset) as the second argument.
343 if start_node.is_editable() &&
344 let Some(start_text) = start_node.downcast::<Text>() &&
345 start_text
346 .upcast::<CharacterData>()
347 .DeleteData(cx, start_offset, start_node.len() - start_offset)
348 .is_err()
349 {
350 unreachable!("Must always be able to delete");
351 }
352
353 // Step 23. Let node list be a list of nodes, initially empty.
354 rooted_vec!(let mut node_list);
355
356 // Step 24. For each node contained in the active range, append node to node list if the
357 // last member of node list (if any) is not an ancestor of node; node is editable;
358 // and node is not a thead, tbody, tfoot, tr, th, or td.
359 for node in self.expect_active_range(cx).contained_nodes(cx.no_gc()) {
360 // This type is only used to tell the compiler how to handle the type of `node_list.last()`.
361 // It is not allowed to add a `& DomRoot<Node>` annotation, as test-tidy disallows that.
362 // However, if we omit the type, the compiler doesn't know what it is, since we also
363 // aren't allowed to add a type annotation to `node_list` itself, as that is handled
364 // by the `rooted_vec` macro. Lastly, we also can't make it `&Node`, since then the compiler
365 // thinks that the contents of the `RootedVec` is `Node`, whereas it is should be
366 // `RootedVec<DomRoot<Node>>`. The type alias here doesn't upset test-tidy,
367 // while also providing the necessary information to the compiler to work.
368 type DomRootNode = DomRoot<Node>;
369 if node.is_editable() &&
370 !(node.is::<HTMLTableSectionElement>() ||
371 node.is::<HTMLTableRowElement>() ||
372 node.is::<HTMLTableCellElement>()) &&
373 node_list
374 .last()
375 .is_none_or(|last: &DomRootNode| !last.is_ancestor_of(&node))
376 {
377 node_list.push(node.as_rooted());
378 }
379 }
380
381 // Step 25. For each node in node list:
382 for node in node_list.iter() {
383 // Step 25.1. Let parent be the parent of node.
384 let parent = node.GetParentNode().expect("Must always have a parent");
385 // Step 25.2. Remove node from parent.
386 assert!(node.has_parent());
387 node.remove_self(cx);
388 // Step 25.3. If the block node of parent has no visible children, and parent is editable or an editing host,
389 // call createElement("br") on the context object and append the result as the last child of parent.
390 if parent.block_node_of().is_some_and(|block_node| {
391 block_node
392 .children_unrooted(cx.no_gc())
393 .all(|child| child.is_invisible(cx.no_gc()))
394 }) && parent.is_editable_or_editing_host()
395 {
396 let br = context_object.create_element(cx, "br");
397 if parent.AppendChild(cx, br.upcast()).is_err() {
398 unreachable!("Must always be able to append");
399 }
400 }
401 // Step 25.4. If strip wrappers is true or parent is not an inclusive ancestor of start node,
402 // while parent is an editable inline node with length 0, let grandparent be the parent of parent,
403 // then remove parent from grandparent, then set parent to grandparent.
404 if strip_wrappers == SelectionDeletionStripWrappers::Strip ||
405 !parent.is_inclusive_ancestor_of(&start_node)
406 {
407 let mut parent = parent;
408 loop {
409 if parent.is_editable() && parent.is_inline_node() && parent.is_empty() {
410 let grand_parent =
411 parent.GetParentNode().expect("Must always have a parent");
412 assert!(parent.has_parent());
413 parent.remove_self(cx);
414 parent = grand_parent;
415 continue;
416 }
417 break;
418 }
419 }
420 }
421
422 // Step 26. If end node is an editable Text node, call deleteData(0, end offset) on it.
423 if end_node.is_editable() &&
424 let Some(end_text) = end_node.downcast::<Text>() &&
425 end_text
426 .upcast::<CharacterData>()
427 .DeleteData(cx, 0, end_offset)
428 .is_err()
429 {
430 unreachable!("Must always be able to delete");
431 }
432
433 // Step 27. Canonicalize whitespace at the active range's start, with fix collapsed space false.
434 let (start_container, start_offset) = self.start_boundary(cx);
435 start_container.canonicalize_whitespace(cx, start_offset, false);
436
437 // Step 28. Canonicalize whitespace at the active range's end, with fix collapsed space false.
438 let (end_container, end_offset) = self.end_boundary(cx);
439 end_container.canonicalize_whitespace(cx, end_offset, false);
440
441 // Step 29
442 //
443 // This step does not exist in the spec
444
445 // Step 30. If block merging is false, or start block or end block is null, or start block is not
446 // in the same editing host as end block, or start block and end block are the same:
447 if block_merging == SelectionDeletionBlockMerging::Skip ||
448 start_block.as_ref().zip(end_block.as_ref()).is_none_or(
449 |(start_block, end_block)| {
450 start_block == end_block || !start_block.same_editing_host(end_block)
451 },
452 )
453 {
454 // Step 30.1. If direction is "forward", call collapseToStart() on the context object's selection.
455 if direction == SelectionDeleteDirection::Forward {
456 let _ = self.CollapseToStart(cx);
457 } else {
458 // Step 30.2. Otherwise, call collapseToEnd() on the context object's selection.
459 let _ = self.CollapseToEnd(cx);
460 }
461 // Step 30.3. Restore states and values from overrides.
462 self.expect_active_range(cx).restore_states_and_values(
463 cx,
464 self,
465 context_object,
466 overrides,
467 );
468
469 // Step 30.4. Abort these steps.
470 return;
471 }
472 let start_block = start_block.expect("Already checked for None in previous statement");
473 let end_block = end_block.expect("Already checked for None in previous statement");
474
475 // Step 31. If start block has one child, which is a collapsed block prop, remove its child from it.
476 if start_block.children_count() == 1 {
477 let Some(child) = start_block.children().nth(0) else {
478 unreachable!("Must always have a single child");
479 };
480 if child.is_collapsed_block_prop(cx.no_gc()) {
481 assert!(child.has_parent());
482 child.remove_self(cx);
483 }
484 }
485
486 // Step 32. If start block is an ancestor of end block:
487 let values = if start_block.is_ancestor_of(&end_block) {
488 // Step 32.1. Let reference node be end block.
489 let mut reference_node = end_block.clone();
490 // Step 32.2. While reference node is not a child of start block, set reference node to its parent.
491 loop {
492 if start_block
493 .children_unrooted(cx.no_gc())
494 .all(|child| **child != *reference_node)
495 {
496 reference_node = reference_node
497 .GetParentNode()
498 .expect("Must always have a parent, at least start_block");
499 continue;
500 }
501 break;
502 }
503 // Step 32.3. Call collapse() on the context object's selection,
504 // with first argument start block and second argument the index of reference node.
505 let _ = self.Collapse(cx, Some(&start_block), reference_node.index());
506 // Step 32.4. If end block has no children:
507 if end_block.children_count() == 0 {
508 let mut end_block = end_block;
509 // Step 32.4.1. While end block is editable and is the only child of its parent and is not a child of start block,
510 // let parent equal end block, then remove end block from parent, then set end block to parent.
511 loop {
512 if end_block.is_editable() &&
513 start_block.children().all(|child| child != end_block) &&
514 let Some(parent) = end_block.GetParentNode() &&
515 parent.children_count() == 1
516 {
517 assert!(end_block.has_parent());
518 end_block.remove_self(cx);
519 end_block = parent;
520 continue;
521 }
522 break;
523 }
524 // Step 32.4.2. If end block is editable and is not an inline node,
525 // and its previousSibling and nextSibling are both inline nodes,
526 // call createElement("br") on the context object and insert it into end block's parent immediately after end block.
527 if end_block.is_editable() &&
528 !end_block.is_inline_node() &&
529 end_block
530 .GetPreviousSibling()
531 .is_some_and(|previous| previous.is_inline_node()) &&
532 let Some(next_of_end_block) = end_block.GetNextSibling() &&
533 next_of_end_block.is_inline_node()
534 {
535 let br = context_object.create_element(cx, "br");
536 let parent = end_block
537 .GetParentNode()
538 .expect("Must always have a parent");
539 if parent
540 .InsertBefore(cx, br.upcast(), Some(&next_of_end_block))
541 .is_err()
542 {
543 unreachable!("Must always be able to insert into parent");
544 }
545 }
546 // Step 32.4.3. If end block is editable, remove it from its parent.
547 if end_block.is_editable() {
548 assert!(end_block.has_parent());
549 end_block.remove_self(cx);
550 }
551 // Step 32.4.4. Restore states and values from overrides.
552 self.expect_active_range(cx).restore_states_and_values(
553 cx,
554 self,
555 context_object,
556 overrides,
557 );
558
559 // Step 32.4.5. Abort these steps.
560 return;
561 }
562 let first_child = end_block
563 .children()
564 .nth(0)
565 .expect("Already checked at least 1 child in previous statement");
566 // Step 32.5. If end block's firstChild is not an inline node,
567 // restore states and values from record, then abort these steps.
568 if !first_child.is_inline_node() {
569 self.expect_active_range(cx).restore_states_and_values(
570 cx,
571 self,
572 context_object,
573 overrides,
574 );
575 return;
576 }
577 // Step 32.6. Let children be a list of nodes, initially empty.
578 rooted_vec!(let mut children);
579 // Step 32.7. Append the first child of end block to children.
580 children.push(first_child.as_traced());
581 // Step 32.8. While children's last member is not a br,
582 // and children's last member's nextSibling is an inline node,
583 // append children's last member's nextSibling to children.
584 while let Some(last) = children.last() {
585 if last.is::<HTMLBRElement>() {
586 break;
587 }
588 let Some(next) = last.GetNextSibling() else {
589 break;
590 };
591 if next.is_inline_node() {
592 children.push(next.as_traced());
593 continue;
594 }
595 break;
596 }
597 // Step 32.9. Record the values of children, and let values be the result.
598 let values = record_the_values(children.iter().map(|dom| dom.as_rooted()).collect());
599
600 // Step 32.10. While children's first member's parent is not start block,
601 // split the parent of children.
602 loop {
603 if children
604 .first()
605 .and_then(|child| child.GetParentNode())
606 .is_some_and(|parent_of_child| parent_of_child != start_block)
607 {
608 split_the_parent(cx, children.r());
609 continue;
610 }
611 break;
612 }
613 // Step 32.11. If children's first member's previousSibling is an editable br,
614 // remove that br from its parent.
615 if let Some(first) = children.first() &&
616 let Some(previous_of_first) = first.GetPreviousSibling() &&
617 previous_of_first.is_editable() &&
618 previous_of_first.is::<HTMLBRElement>()
619 {
620 assert!(previous_of_first.has_parent());
621 previous_of_first.remove_self(cx);
622 }
623
624 values
625 // Step 33. Otherwise, if start block is a descendant of end block:
626 } else if end_block.is_ancestor_of(&start_block) {
627 // Step 33.1. Call collapse() on the context object's selection,
628 // with first argument start block and second argument start block's length.
629 let _ = self.Collapse(cx, Some(&start_block), start_block.len());
630 // Step 33.2. Let reference node be start block.
631 let mut reference_node = start_block.clone();
632 // Step 33.3. While reference node is not a child of end block, set reference node to its parent.
633 loop {
634 if end_block.children().all(|child| child != reference_node) &&
635 let Some(parent) = reference_node.GetParentNode()
636 {
637 reference_node = parent;
638 continue;
639 }
640 break;
641 }
642 // Step 33.4. If reference node's nextSibling is an inline node and start block's lastChild is a br,
643 // remove start block's lastChild from it.
644 if reference_node
645 .GetNextSibling()
646 .is_some_and(|next| next.is_inline_node()) &&
647 let Some(last) = start_block.children().last() &&
648 last.is::<HTMLBRElement>()
649 {
650 assert!(last.has_parent());
651 last.remove_self(cx);
652 }
653 // Step 33.5. Let nodes to move be a list of nodes, initially empty.
654 rooted_vec!(let mut nodes_to_move);
655 // Step 33.6. If reference node's nextSibling is neither null nor a block node,
656 // append it to nodes to move.
657 if let Some(next) = reference_node.GetNextSibling() &&
658 !next.is_block_node()
659 {
660 nodes_to_move.push(next);
661 }
662 // Step 33.7. While nodes to move is nonempty and its last member isn't a br
663 // and its last member's nextSibling is neither null nor a block node,
664 // append its last member's nextSibling to nodes to move.
665 loop {
666 if let Some(last) = nodes_to_move.last() &&
667 !last.is::<HTMLBRElement>() &&
668 let Some(next_of_last) = last.GetNextSibling() &&
669 !next_of_last.is_block_node()
670 {
671 nodes_to_move.push(next_of_last);
672 continue;
673 }
674 break;
675 }
676 // Step 33.8. Record the values of nodes to move, and let values be the result.
677 let values = record_the_values(nodes_to_move.iter().cloned().collect());
678
679 // Step 33.9. For each node in nodes to move,
680 // append node as the last child of start block, preserving ranges.
681 for node in nodes_to_move.iter() {
682 move_preserving_ranges(cx, node, |cx| start_block.AppendChild(cx, node));
683 }
684
685 values
686 // Step 34. Otherwise:
687 } else {
688 // Step 34.1. Call collapse() on the context object's selection,
689 // with first argument start block and second argument start block's length.
690 let _ = self.Collapse(cx, Some(&start_block), start_block.len());
691 // Step 34.2. If end block's firstChild is an inline node and start block's lastChild is a br,
692 // remove start block's lastChild from it.
693 if end_block
694 .children()
695 .nth(0)
696 .is_some_and(|next| next.is_inline_node()) &&
697 let Some(last) = start_block.children().last() &&
698 last.is::<HTMLBRElement>()
699 {
700 assert!(last.has_parent());
701 last.remove_self(cx);
702 }
703 // Step 34.3. Record the values of end block's children, and let values be the result.
704 let values = record_the_values(end_block.children().collect());
705
706 // Step 34.4. While end block has children,
707 // append the first child of end block to start block, preserving ranges.
708 loop {
709 if let Some(first_child) = end_block.children().nth(0) {
710 move_preserving_ranges(cx, &first_child, |cx| {
711 start_block.AppendChild(cx, &first_child)
712 });
713 continue;
714 }
715 break;
716 }
717 // Step 34.5. While end block has no children,
718 // let parent be the parent of end block, then remove end block from parent,
719 // then set end block to parent.
720 let mut end_block = end_block;
721 loop {
722 if end_block.children_count() == 0 &&
723 let Some(parent) = end_block.GetParentNode()
724 {
725 assert!(end_block.has_parent());
726 end_block.remove_self(cx);
727 end_block = parent;
728 continue;
729 }
730 break;
731 }
732
733 values
734 };
735
736 // Step 35.
737 //
738 // This step does not exist in the spec
739
740 // Step 36. Let ancestor be start block.
741 // TODO
742
743 // Step 37. While ancestor has an inclusive ancestor ol in the same editing host whose nextSibling is
744 // also an ol in the same editing host, or an inclusive ancestor ul in the same editing host whose nextSibling
745 // is also a ul in the same editing host:
746 // TODO
747
748 // Step 38. Restore the values from values.
749 restore_the_values(cx, values);
750
751 // Step 39. If start block has no children, call createElement("br") on the context object and
752 // append the result as the last child of start block.
753 if start_block.children_count() == 0 {
754 let br = context_object.create_element(cx, "br");
755 if start_block.AppendChild(cx, br.upcast()).is_err() {
756 unreachable!("Must always be able to append");
757 }
758 }
759
760 // Step 40. Remove extraneous line breaks at the end of start block.
761 start_block.remove_extraneous_line_breaks_at_the_end_of(cx);
762
763 // Step 41. Restore states and values from overrides.
764 self.expect_active_range(cx)
765 .restore_states_and_values(cx, self, context_object, overrides);
766 }
767
768 /// <https://w3c.github.io/editing/docs/execCommand/#set-the-selection%27s-value>
769 pub(crate) fn set_the_selection_value(
770 &self,
771 cx: &mut JSContext,
772 new_value: Option<DOMString>,
773 command: CommandName,
774 context_object: &Document,
775 ) {
776 // Step 1. Let command be the current command.
777 //
778 // Passed as argument
779
780 // Step 2. If there is no formattable node effectively contained in the active range:
781 if self
782 .expect_active_range(cx)
783 .first_formattable_contained_node(cx.no_gc())
784 .is_none()
785 {
786 // Step 2.1. If command has inline command activated values, set the state override to true if new value is among them and false if it's not.
787 let inline_command_activated_values = command.inline_command_activated_values();
788 if !inline_command_activated_values.is_empty() {
789 context_object.set_state_override(
790 command,
791 Some(new_value.as_ref().is_some_and(|new_value| {
792 inline_command_activated_values.contains(&new_value.str().as_ref())
793 })),
794 );
795 }
796 // Step 2.2. If command is "subscript", unset the state override for "superscript".
797 if command == CommandName::Subscript {
798 context_object.set_state_override(CommandName::Superscript, None);
799 }
800 // Step 2.3. If command is "superscript", unset the state override for "subscript".
801 if command == CommandName::Superscript {
802 context_object.set_state_override(CommandName::Subscript, None);
803 }
804 // Step 2.4. If new value is null, unset the value override (if any).
805 // Step 2.5. Otherwise, if command is "createLink" or it has a value specified, set the value override to new value.
806 context_object.set_value_override(command, new_value);
807 // Step 2.6. Abort these steps.
808 return;
809 }
810 // Step 3. If the active range's start node is an editable Text node,
811 // and its start offset is neither zero nor its start node's length,
812 // call splitText() on the active range's start node,
813 // with argument equal to the active range's start offset.
814 // Then set the active range's start node to the result, and its start offset to zero.
815 let (start_node, start_offset) = self.start_boundary(cx);
816 if start_node.is_editable() &&
817 start_offset != 0 &&
818 start_offset != start_node.len() &&
819 let Some(start_text) = start_node.downcast::<Text>()
820 {
821 let Ok(start_text) = start_text.SplitText(cx, start_offset) else {
822 unreachable!("Must always be able to split");
823 };
824 let _ = self
825 .expect_active_range(cx)
826 .SetStart(start_text.upcast(), 0);
827 }
828 // Step 4. If the active range's end node is an editable Text node,
829 // and its end offset is neither zero nor its end node's length,
830 // call splitText() on the active range's end node,
831 // with argument equal to the active range's end offset.
832 let (end_node, end_offset) = self.end_boundary(cx);
833 if end_node.is_editable() &&
834 end_offset != 0 &&
835 end_offset != end_node.len() &&
836 let Some(end_text) = end_node.downcast::<Text>() &&
837 end_text.SplitText(cx, end_offset).is_err()
838 {
839 unreachable!("Must always be able to split");
840 };
841 // Step 5. Let element list be all editable Elements effectively contained in the active range.
842 // Step 6. For each element in element list, clear the value of element.
843 self.expect_active_range(cx)
844 .for_each_effectively_contained_child(|child| {
845 if child.is_editable() &&
846 let Some(element_child) = child.downcast::<HTMLElement>()
847 {
848 element_child.clear_the_value(cx, &command);
849 }
850 });
851 // Step 7. Let node list be all editable nodes effectively contained in the active range.
852 // Step 8. For each node in node list:
853 self.expect_active_range(cx)
854 .for_each_effectively_contained_child(|child| {
855 if child.is_editable() {
856 // Step 8.1. Push down values on node.
857 child.push_down_values(cx, &command, new_value.clone());
858 // Step 8.2. If node is an allowed child of "span", force the value of node.
859 if is_allowed_child(
860 NodeOrString::from_node(child, cx.no_gc()),
861 NodeOrString::String("span".to_owned()),
862 ) {
863 child.force_the_value(cx, &command, new_value.as_ref());
864 }
865 }
866 });
867 }
868}