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