1use crate::LexicalError;
10use crate::caret::{
11 CaretDirection, CaretRange, CommonAncestorResult, NodeCaret, PointCaret, RootMode,
12 SiblingCaret, TextOffset, TextPointCaretSlice, compare_point_caret_next, flip_direction,
13 get_adjacent_child_caret, get_caret_in_direction, get_caret_range, get_child_caret,
14 get_collapsed_caret_range, get_common_ancestor, get_sibling_caret, get_text_node_offset,
15 get_text_point_caret, get_text_point_caret_at_end,
16};
17use crate::error::invariant;
18use crate::lexical_selection::{
19 Point, PointType, RangeSelection, SelectionRef, Which, create_range_selection, get_selection,
20 set_selection,
21};
22use crate::lexical_utils::{
23 copy_node, get_node_by_key_or_throw, get_root, is_block, is_shadow_root_node,
24 remove_from_parent, restore_empty_container_paragraph,
25};
26use crate::node::{NodeKey, NodeRef};
27use crate::node_state::carry_node_state;
28use crate::nodes::element::is_root_or_shadow_root;
29use crate::nodes::paragraph::create_paragraph_node;
30use crate::nodes::text::create_text_node;
31use crate::selection_insert_nodes::is_block_container;
32use std::collections::HashSet;
33
34pub fn caret_from_point(
36 point: &Point,
37 direction: CaretDirection,
38) -> Result<PointCaret, LexicalError> {
39 let node = get_node_by_key_or_throw(&point.key)?;
40 if point.point_type == PointType::Text {
41 invariant!(
42 node.is_text(),
43 "$caretFromPoint: Node with type {} and key {} that does not inherit from TextNode encountered for text point",
44 node.get_type(),
45 point.key
46 );
47 return get_text_point_caret(&node, direction, point.offset);
48 }
49 invariant!(
50 node.is_element(),
51 "$caretFromPoint: Node with type {} and key {} that does not inherit from ElementNode encountered for element point",
52 node.get_type(),
53 point.key
54 );
55 Ok(get_child_caret_at_index(&node, point.offset, direction))
56}
57
58pub fn set_point_from_caret(
61 selection: &SelectionRef,
62 which: Which,
63 caret: &PointCaret,
64) -> Result<(), LexicalError> {
65 let origin = caret.origin();
66 let direction = caret.direction();
67 let is_next = direction == CaretDirection::Next;
68 if let Some(offset) = caret.offset() {
69 selection.point_set(which, origin.get_key(), offset, PointType::Text)
70 } else if caret.is_sibling_caret() {
71 if origin.is_text() {
72 let offset = get_text_node_offset(origin, direction.into(), false)?;
73 selection.point_set(which, origin.get_key(), offset, PointType::Text)
74 } else {
75 let parent = origin.get_parent_or_throw()?;
76 let index = origin
77 .get_index_within_parent()
78 .expect("a child of its parent");
79 selection.point_set(
80 which,
81 parent.get_key(),
82 index + usize::from(is_next),
83 PointType::Element,
84 )
85 }
86 } else {
87 assert!(
88 caret.is_child_caret() && origin.is_element(),
89 "$setPointFromCaret: exhaustiveness check"
90 );
91 let offset = if is_next {
92 0
93 } else {
94 origin.get_children_size()
95 };
96 selection.point_set(which, origin.get_key(), offset, PointType::Element)
97 }
98}
99
100pub fn set_selection_from_caret_range(
103 caret_range: &CaretRange,
104) -> Result<SelectionRef, LexicalError> {
105 let selection = get_selection()
106 .filter(SelectionRef::is_range)
107 .unwrap_or_else(create_range_selection);
108 update_range_selection_from_caret_range(&selection, caret_range)?;
109 set_selection(Some(selection.clone()));
110 Ok(selection)
111}
112
113pub fn update_range_selection_from_caret_range(
115 selection: &SelectionRef,
116 caret_range: &CaretRange,
117) -> Result<(), LexicalError> {
118 set_point_from_caret(selection, Which::Anchor, &caret_range.anchor)?;
119 set_point_from_caret(selection, Which::Focus, &caret_range.focus)
120}
121
122pub fn caret_range_from_selection(selection: &RangeSelection) -> Result<CaretRange, LexicalError> {
125 let anchor_caret = caret_from_point(&selection.anchor, CaretDirection::Next)?;
126 let focus_caret = caret_from_point(&selection.focus, CaretDirection::Next)?;
127 let direction = if compare_point_caret_next(&anchor_caret, &focus_caret)?.is_le() {
128 CaretDirection::Next
129 } else {
130 CaretDirection::Previous
131 };
132 get_caret_range(
133 get_caret_in_direction(&anchor_caret, direction)?,
134 get_caret_in_direction(&focus_caret, direction)?,
135 )
136}
137
138pub fn rewind_sibling_caret(caret: &SiblingCaret) -> Result<NodeCaret, LexicalError> {
141 let direction = caret.direction();
142 let origin = caret.origin();
143 let rewind_origin = get_sibling_caret(origin, flip_direction(direction)).get_node_at_caret();
145 Ok(match rewind_origin {
146 Some(rewind_origin) => get_sibling_caret(&rewind_origin, direction),
147 None => get_child_caret(&origin.get_parent_or_throw()?, direction)
148 .expect("a parent is an element"),
149 })
150}
151
152fn get_anchor_candidates(
155 anchor: &PointCaret,
156 root_mode: RootMode,
157) -> Result<Vec<PointCaret>, LexicalError> {
158 let mut carets = vec![anchor.clone()];
161 let mut parent = if anchor.is_child_caret() {
162 anchor.get_parent_caret(root_mode)
163 } else {
164 Some(anchor.get_sibling_caret())
165 };
166 while let Some(p) = parent {
167 carets.push(rewind_sibling_caret(&p)?);
168 parent = p.get_parent_caret(root_mode);
169 }
170 Ok(carets)
171}
172
173fn is_caret_attached(caret: &PointCaret) -> bool {
175 caret.origin().is_attached()
176}
177
178#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
180pub enum SliceMode {
181 #[default]
184 RemoveEmptySlices,
185 PreserveEmptyTextSliceCaret,
188}
189
190pub fn remove_text_from_caret_range(
195 initial_range: &CaretRange,
196 slice_mode: SliceMode,
197) -> Result<CaretRange, LexicalError> {
198 if initial_range.is_collapsed() {
199 return Ok(initial_range.clone());
200 }
201 let root_mode = RootMode::Root;
203 let next_direction = CaretDirection::Next;
204 let mut slice_state = slice_mode;
205 let range = get_caret_range_in_direction(initial_range, next_direction)?;
206
207 let mut range_container = Some(range.anchor.origin().clone());
210 while let Some(container) = range_container
211 .as_ref()
212 .filter(|c| !is_root_or_shadow_root(&*c.get_latest()))
213 {
214 range_container = container.get_parent();
215 }
216 let range_container_child = range_container
220 .as_ref()
221 .filter(|c| c.is_element())
222 .and_then(NodeRef::get_first_child);
223
224 let mut anchor_candidates = get_anchor_candidates(&range.anchor, root_mode)?;
225 let mut focus_candidates = get_anchor_candidates(&range.focus.get_flipped()?, root_mode)?;
226
227 let mut seen_start: HashSet<NodeKey> = HashSet::new();
229 let mut removed_nodes: Vec<NodeRef> = Vec::new();
231 for caret in range.iter_node_carets(root_mode) {
232 if caret.is_child_caret() {
233 seen_start.insert(caret.origin().get_key().to_owned());
234 } else if caret.is_sibling_caret() {
235 let origin = caret.origin();
236 if !origin.is_element() || seen_start.contains(origin.get_key()) {
237 removed_nodes.push(origin.clone());
238 }
239 }
240 }
241 let mut removed_parents: Vec<NodeRef> = Vec::new();
244 for node in &removed_nodes {
245 if let Some(parent) = node.get_parent()
248 && !seen_start.contains(parent.get_key())
249 && !removed_parents.contains(&parent)
250 {
251 removed_parents.push(parent);
252 }
253 remove_from_parent(node)?;
255 }
256 for parent in &removed_parents {
258 if !parent.can_be_empty()
259 && !is_root_or_shadow_root(&*parent.get_latest())
260 && parent.is_empty()
261 && parent.is_attached()
262 {
263 parent.remove(false)?;
264 }
265 }
266
267 for slice in range.get_text_slices().into_iter().flatten() {
274 let origin = slice.caret.origin().clone();
275 let content_size = origin.get_text_content_size();
276 let caret_before = rewind_sibling_caret(&get_sibling_caret(&origin, next_direction))?;
277 let mode = origin.text_data().get_mode();
278 if (slice.distance.unsigned_abs() == content_size
279 && slice_state == SliceMode::RemoveEmptySlices)
280 || (mode == "token" && slice.distance != 0)
281 {
282 caret_before.remove()?;
284 } else if slice.distance != 0 {
285 slice_state = SliceMode::RemoveEmptySlices;
286 let mut next_caret = slice.remove_text_slice()?;
287 let slice_origin = slice.caret.origin();
288 if mode == "segmented" {
289 let src = next_caret.origin().clone();
290 let data = src.text_data();
291 let plain_text_node = create_text_node(data.get_text());
292 plain_text_node.set_style(data.get_style());
293 plain_text_node.set_format(data.get_format());
294 plain_text_node.set_detail(data.get_detail())?;
295 carry_node_state(&src, &plain_text_node)?;
298 caret_before.replace_or_insert(&plain_text_node, false)?;
299 next_caret = get_text_point_caret(
300 &plain_text_node,
301 next_direction,
302 next_caret.offset().expect("a text point caret"),
303 )?;
304 }
305 if slice_origin == anchor_candidates[0].origin() {
306 anchor_candidates[0] = next_caret.clone();
307 }
308 if slice_origin == focus_candidates[0].origin() {
309 focus_candidates[0] = next_caret.get_flipped()?;
310 }
311 }
312 }
313
314 let anchor_candidate = get_attached_caret(anchor_candidates.iter());
316 let focus_candidate = get_attached_caret(focus_candidates.iter());
317
318 let merge_targets = get_block_merge_targets(
320 anchor_candidate.as_ref(),
321 focus_candidate.as_ref(),
322 &seen_start,
323 );
324 if let Some((anchor_block, focus_block)) = merge_targets {
325 get_child_caret(&anchor_block, CaretDirection::Previous)
328 .expect("a block is an element")
329 .splice(0, &focus_block.get_children(), CaretDirection::Next)?;
330 let mut parent = focus_block.get_parent();
332 focus_block.remove(true)?;
333 while let Some(p) = parent.filter(NodeRef::is_empty) {
334 parent = p.get_parent();
335 p.remove(true)?;
336 }
337 } else if let Some(focus_candidate) = &focus_candidate {
338 let focus_block = get_block_from_caret(focus_candidate);
339 let focus_block_parent = focus_block.as_ref().and_then(NodeRef::get_parent);
340 let topmost_shadow_root = focus_block
341 .as_ref()
342 .and_then(|b| b.get_parents().into_iter().rev().find(is_shadow_root_node));
343 if let (Some(focus_block), Some(focus_block_parent)) = (&focus_block, &focus_block_parent)
344 && !focus_block_parent.is_root()
345 && focus_block.is_empty()
346 && seen_start.contains(focus_block.get_key())
347 && crate::slot::get_slot_names(focus_block).is_empty()
348 && topmost_shadow_root.is_none_or(|r| seen_start.contains(r.get_key()))
349 {
350 focus_block.remove(true)?;
351 let mut parent = Some(focus_block_parent.clone());
352 while let Some(p) = parent.filter(|p| !p.is_root() && p.is_empty()) {
353 let grandparent = p.get_parent();
354 if let Some(g) = &grandparent
355 && g.is_root()
356 && g.get_children_size() <= 1
357 && p.can_be_empty()
362 {
363 break;
364 }
365 parent = grandparent;
366 p.remove(true)?;
367 }
368 }
369 }
370
371 if restore_empty_container_paragraph(range_container.as_ref(), range_container_child.as_ref())?
382 .is_none()
383 && range_container.as_ref().is_some_and(|c| !c.is_attached())
384 {
385 restore_empty_container_paragraph(Some(&get_root()), None)?;
386 }
387
388 let best_candidate = get_attached_caret(
390 anchor_candidate
391 .iter()
392 .chain(&focus_candidate)
393 .chain(&anchor_candidates)
394 .chain(&focus_candidates),
395 );
396 if let Some(best_candidate) = best_candidate {
397 let anchor = get_caret_in_direction(&best_candidate, initial_range.direction())?;
398 return Ok(get_collapsed_caret_range(anchor));
399 }
400 let keys: Vec<String> = anchor_candidates
401 .iter()
402 .map(|c| format!("\"{}\"", c.origin().get_key()))
403 .collect();
404 Err(LexicalError::new(format!(
405 "$removeTextFromCaretRange: selection was lost, could not find a new anchor given candidates with keys: [{}]",
406 keys.join(",")
407 )))
408}
409
410fn get_attached_caret<'a>(
413 mut candidates: impl Iterator<Item = &'a PointCaret>,
414) -> Option<PointCaret> {
415 candidates
416 .find(|c| is_caret_attached(c))
417 .map(normalize_caret)
418}
419
420fn get_block_from_caret(caret: &PointCaret) -> Option<NodeRef> {
422 if caret.is_child_caret() {
423 let origin = caret.origin();
424 is_block(origin).then(|| origin.clone())
425 } else {
426 caret.get_parent_at_caret().filter(is_block)
427 }
428}
429
430fn get_block_merge_targets(
434 anchor: Option<&PointCaret>,
435 focus: Option<&PointCaret>,
436 seen_start: &HashSet<NodeKey>,
437) -> Option<(NodeRef, NodeRef)> {
438 let anchor_parent = anchor?.get_parent_at_caret()?;
439 let focus_parent = focus?.get_parent_at_caret()?;
440 let common = get_common_ancestor(&anchor_parent, &focus_parent)?;
441 if !matches!(common, CommonAncestorResult::Branch { .. }) {
442 return None;
443 }
444 let get_block = |parent: &NodeRef, selected_only: bool| -> Option<NodeRef> {
445 let mut block = None;
446 let mut node = Some(parent.clone());
449 while let Some(n) = node.filter(|n| n != common.common_ancestor()) {
450 if is_root_or_shadow_root(&*n.get_latest()) {
451 return None;
452 }
453 if (!selected_only || seen_start.contains(n.get_key())) && is_block(&n) {
454 block = Some(n.clone());
455 }
456 node = n.get_parent();
457 }
458 block
459 };
460 let anchor_block = get_block(&anchor_parent, false)?;
461 let focus_block = get_block(&focus_parent, true)?;
462 crate::slot::get_slot_names(&focus_block)
465 .is_empty()
466 .then_some((anchor_block, focus_block))
467}
468
469fn get_deepest_child_or_self(initial_caret: PointCaret) -> PointCaret {
472 let mut caret = initial_caret;
473 while caret.is_child_caret() {
474 match get_adjacent_child_caret(Some(&caret)) {
475 Some(adjacent) if adjacent.is_child_caret() => caret = adjacent,
476 _ => break,
477 }
478 }
479 caret
480}
481
482pub fn normalize_caret(initial_caret: &PointCaret) -> PointCaret {
485 let caret = get_deepest_child_or_self(initial_caret.get_latest());
486 let direction = caret.direction();
487 if caret.origin().is_text() {
488 return if caret.is_text_point_caret() {
489 caret
490 } else {
491 get_text_point_caret_at_end(caret.origin(), direction, direction)
492 };
493 }
494 match caret.get_adjacent_caret() {
495 Some(adj) if adj.is_sibling_caret() && adj.origin().is_text() => {
496 get_text_point_caret_at_end(adj.origin(), direction, flip_direction(direction))
497 }
498 _ => caret,
499 }
500}
501
502pub fn is_extendable_text_point_caret(caret: &PointCaret) -> bool {
505 caret.offset().is_some_and(|offset| {
506 get_text_node_offset(caret.origin(), TextOffset::End(caret.direction()), false)
507 .is_ok_and(|end| offset != end)
508 })
509}
510
511pub fn get_caret_range_in_direction(
514 range: &CaretRange,
515 direction: CaretDirection,
516) -> Result<CaretRange, LexicalError> {
517 if range.direction() == direction {
518 return Ok(range.clone());
519 }
520 get_caret_range(
521 get_caret_in_direction(&range.focus, direction)?,
523 get_caret_in_direction(&range.anchor, direction)?,
524 )
525}
526
527pub fn get_child_caret_at_index(
530 parent: &NodeRef,
531 index: usize,
532 direction: CaretDirection,
533) -> NodeCaret {
534 let size = parent.get_children_size();
535 let offset = index.min(size);
536 let origin = match direction {
537 CaretDirection::Next => offset.checked_sub(1),
538 CaretDirection::Previous => Some(offset),
539 }
540 .filter(|&i| i < size)
541 .and_then(|i| parent.get_child_at_index(i));
542 match origin {
543 Some(origin) => get_sibling_caret(&origin, direction),
544 None => get_child_caret(parent, direction).expect("a parent is an element"),
545 }
546}
547
548pub fn get_adjacent_sibling_or_parent_sibling_caret(
552 start_caret: &NodeCaret,
553 root_mode: RootMode,
554) -> Option<(NodeCaret, isize)> {
555 let mut depth_diff = 0;
556 let mut caret = start_caret.clone();
557 let mut next_caret = get_adjacent_child_caret(Some(&caret));
558 while next_caret.is_none() {
559 depth_diff -= 1;
560 caret = caret.get_parent_caret(root_mode)?;
561 next_caret = get_adjacent_child_caret(Some(&caret));
562 }
563 next_caret.map(|c| (c, depth_diff))
564}
565
566pub fn get_text_point_caret_slice_for_node<'a>(
569 slices: &'a [Option<TextPointCaretSlice>],
570 node: &NodeRef,
571) -> Option<&'a TextPointCaretSlice> {
572 slices
573 .iter()
574 .flatten()
575 .find(|slice| slice.caret.origin() == node)
576}
577
578pub fn split_text_point_caret(text_point_caret: &PointCaret) -> Result<NodeCaret, LexicalError> {
582 let origin = text_point_caret.origin();
583 let direction = text_point_caret.direction();
584 let offset = text_point_caret.offset().expect("a text point caret");
585 if offset == get_text_node_offset(origin, TextOffset::End(direction), false)? {
586 return Ok(text_point_caret.get_sibling_caret());
587 } else if offset
588 == get_text_node_offset(origin, TextOffset::End(flip_direction(direction)), false)?
589 {
590 return rewind_sibling_caret(&text_point_caret.get_sibling_caret());
591 }
592 let parts = origin.split_text(&[offset as i64])?;
593 let text_node = parts.first().filter(|n| n.is_text()).ok_or_else(|| {
594 LexicalError::new("$splitTextPointCaret: splitText must return at least one TextNode")
595 })?;
596 get_caret_in_direction(
597 &get_sibling_caret(text_node, CaretDirection::Next),
598 direction,
599 )
600}
601
602#[derive(Clone, Copy)]
606pub struct SplitAtPointCaretNextOptions {
607 pub root_mode: RootMode,
610 pub should_split: fn(&NodeRef, &'static str) -> bool,
614 pub remove_empty_destination: bool,
617}
618
619impl Default for SplitAtPointCaretNextOptions {
620 fn default() -> Self {
621 Self {
622 root_mode: RootMode::ShadowRoot,
623 should_split: |_, _| true,
624 remove_empty_destination: false,
625 }
626 }
627}
628
629pub(crate) fn get_adjacent_nodes(initial_caret: &NodeCaret) -> Vec<NodeRef> {
632 let next = initial_caret.direction() == CaretDirection::Next;
633 let mut siblings = Vec::new();
634 let mut node = initial_caret.get_node_at_caret();
635 while let Some(n) = node {
636 node = if next {
637 n.get_next_sibling()
638 } else {
639 n.get_previous_sibling()
640 };
641 siblings.push(n);
642 }
643 siblings
644}
645
646pub fn split_at_point_caret_next(
650 point_caret: &PointCaret,
651 options: &SplitAtPointCaretNextOptions,
652) -> Result<Option<NodeCaret>, LexicalError> {
653 if point_caret.is_text_point_caret() {
654 return split_text_point_caret(point_caret).map(Some);
655 }
656 let parent_caret = point_caret.get_parent_caret(options.root_mode);
657 if let Some(parent_caret) = &parent_caret {
658 let origin = parent_caret.origin();
659 if point_caret.is_child_caret() {
660 let before_parent_caret = rewind_sibling_caret(parent_caret)?;
661 if options.remove_empty_destination && origin.is_empty() {
662 origin.remove(false)?;
663 return Ok(Some(before_parent_caret));
664 }
665 if !(origin.can_be_empty() && (options.should_split)(origin, "first")) {
666 return Ok(Some(before_parent_caret));
667 }
668 }
669 let siblings = get_adjacent_nodes(point_caret);
670 if !siblings.is_empty()
671 || (!options.remove_empty_destination
672 && origin.can_be_empty()
673 && (options.should_split)(origin, "last"))
674 {
675 let copy = copy_node(origin);
677 copy.splice(0, 0, &siblings)?;
678 parent_caret.insert(©)?;
679 }
680 }
681 Ok(parent_caret)
682}
683
684pub fn insert_node_to_nearest_root_at_caret(
689 node: &NodeRef,
690 caret: &PointCaret,
691 options: &SplitAtPointCaretNextOptions,
692) -> Result<NodeCaret, LexicalError> {
693 let mut insert_caret = get_caret_in_direction(caret, CaretDirection::Next)?;
694 if let Some(offset) = insert_caret.offset() {
696 let origin = insert_caret.origin().clone();
697 if offset == 0 {
698 insert_caret = get_sibling_caret(&origin, CaretDirection::Previous).get_flipped()?;
699 } else if offset == origin.get_text_content_size() {
700 insert_caret = get_sibling_caret(&origin, CaretDirection::Next);
701 }
702 }
703 if insert_caret.origin() == node {
705 invariant!(
706 insert_caret.is_sibling_caret(),
707 "$insertNodeToNearestRootAtCaret node {} of type {} can not be inserted into itself",
708 node.get_key(),
709 node.get_type()
710 );
711 insert_caret = rewind_sibling_caret(&insert_caret)?;
712 }
713 if insert_caret.get_node_at_caret().as_ref() == Some(node)
716 || insert_caret.get_flipped()?.get_node_at_caret().as_ref() == Some(node)
717 {
718 node.remove(true)?;
719 }
720 let stops_at_containers = options.root_mode == RootMode::ShadowRoot;
721 let mut next_caret = Some(insert_caret.clone());
722 while let Some(caret) = next_caret {
723 insert_caret = caret;
724 let container = if insert_caret.is_child_caret() {
727 Some(insert_caret.origin().clone())
728 } else {
729 insert_caret.origin().get_parent()
730 };
731 if stops_at_containers
732 && !insert_caret.is_text_point_caret()
733 && container.as_ref().is_some_and(is_block_container)
734 {
735 break;
736 }
737 next_caret = split_at_point_caret_next(&insert_caret, options)?;
738 }
739 invariant!(
740 !insert_caret.is_text_point_caret(),
741 "$insertNodeToNearestRootAtCaret: An unattached TextNode can not be split"
742 );
743 if node.is_inline() {
744 let paragraph = create_paragraph_node();
745 paragraph.append(std::slice::from_ref(node))?;
746 insert_caret.insert(¶graph)?;
747 } else {
748 insert_caret.insert(node)?;
749 }
750 get_caret_in_direction(
751 &get_sibling_caret(node, CaretDirection::Next),
752 caret.direction(),
753 )
754}