use crate::LexicalError;
use crate::caret::{
CaretDirection, CaretRange, CommonAncestorResult, NodeCaret, PointCaret, RootMode,
SiblingCaret, TextOffset, TextPointCaretSlice, compare_point_caret_next, flip_direction,
get_adjacent_child_caret, get_caret_in_direction, get_caret_range, get_child_caret,
get_collapsed_caret_range, get_common_ancestor, get_sibling_caret, get_text_node_offset,
get_text_point_caret, get_text_point_caret_at_end,
};
use crate::error::invariant;
use crate::lexical_selection::{
Point, PointType, RangeSelection, SelectionRef, Which, create_range_selection, get_selection,
set_selection,
};
use crate::lexical_utils::{
copy_node, get_node_by_key_or_throw, get_root, is_block, is_shadow_root_node,
remove_from_parent, restore_empty_container_paragraph,
};
use crate::node::{NodeKey, NodeRef};
use crate::node_state::carry_node_state;
use crate::nodes::element::is_root_or_shadow_root;
use crate::nodes::paragraph::create_paragraph_node;
use crate::nodes::text::create_text_node;
use crate::selection_insert_nodes::is_block_container;
use std::collections::HashSet;
pub fn caret_from_point(
point: &Point,
direction: CaretDirection,
) -> Result<PointCaret, LexicalError> {
let node = get_node_by_key_or_throw(&point.key)?;
if point.point_type == PointType::Text {
invariant!(
node.is_text(),
"$caretFromPoint: Node with type {} and key {} that does not inherit from TextNode encountered for text point",
node.get_type(),
point.key
);
return get_text_point_caret(&node, direction, point.offset);
}
invariant!(
node.is_element(),
"$caretFromPoint: Node with type {} and key {} that does not inherit from ElementNode encountered for element point",
node.get_type(),
point.key
);
Ok(get_child_caret_at_index(&node, point.offset, direction))
}
pub fn set_point_from_caret(
selection: &SelectionRef,
which: Which,
caret: &PointCaret,
) -> Result<(), LexicalError> {
let origin = caret.origin();
let direction = caret.direction();
let is_next = direction == CaretDirection::Next;
if let Some(offset) = caret.offset() {
selection.point_set(which, origin.get_key(), offset, PointType::Text)
} else if caret.is_sibling_caret() {
if origin.is_text() {
let offset = get_text_node_offset(origin, direction.into(), false)?;
selection.point_set(which, origin.get_key(), offset, PointType::Text)
} else {
let parent = origin.get_parent_or_throw()?;
let index = origin
.get_index_within_parent()
.expect("a child of its parent");
selection.point_set(
which,
parent.get_key(),
index + usize::from(is_next),
PointType::Element,
)
}
} else {
assert!(
caret.is_child_caret() && origin.is_element(),
"$setPointFromCaret: exhaustiveness check"
);
let offset = if is_next {
0
} else {
origin.get_children_size()
};
selection.point_set(which, origin.get_key(), offset, PointType::Element)
}
}
pub fn set_selection_from_caret_range(
caret_range: &CaretRange,
) -> Result<SelectionRef, LexicalError> {
let selection = get_selection()
.filter(SelectionRef::is_range)
.unwrap_or_else(create_range_selection);
update_range_selection_from_caret_range(&selection, caret_range)?;
set_selection(Some(selection.clone()));
Ok(selection)
}
pub fn update_range_selection_from_caret_range(
selection: &SelectionRef,
caret_range: &CaretRange,
) -> Result<(), LexicalError> {
set_point_from_caret(selection, Which::Anchor, &caret_range.anchor)?;
set_point_from_caret(selection, Which::Focus, &caret_range.focus)
}
pub fn caret_range_from_selection(selection: &RangeSelection) -> Result<CaretRange, LexicalError> {
let anchor_caret = caret_from_point(&selection.anchor, CaretDirection::Next)?;
let focus_caret = caret_from_point(&selection.focus, CaretDirection::Next)?;
let direction = if compare_point_caret_next(&anchor_caret, &focus_caret)?.is_le() {
CaretDirection::Next
} else {
CaretDirection::Previous
};
get_caret_range(
get_caret_in_direction(&anchor_caret, direction)?,
get_caret_in_direction(&focus_caret, direction)?,
)
}
pub fn rewind_sibling_caret(caret: &SiblingCaret) -> Result<NodeCaret, LexicalError> {
let direction = caret.direction();
let origin = caret.origin();
let rewind_origin = get_sibling_caret(origin, flip_direction(direction)).get_node_at_caret();
Ok(match rewind_origin {
Some(rewind_origin) => get_sibling_caret(&rewind_origin, direction),
None => get_child_caret(&origin.get_parent_or_throw()?, direction)
.expect("a parent is an element"),
})
}
fn get_anchor_candidates(
anchor: &PointCaret,
root_mode: RootMode,
) -> Result<Vec<PointCaret>, LexicalError> {
let mut carets = vec![anchor.clone()];
let mut parent = if anchor.is_child_caret() {
anchor.get_parent_caret(root_mode)
} else {
Some(anchor.get_sibling_caret())
};
while let Some(p) = parent {
carets.push(rewind_sibling_caret(&p)?);
parent = p.get_parent_caret(root_mode);
}
Ok(carets)
}
fn is_caret_attached(caret: &PointCaret) -> bool {
caret.origin().is_attached()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SliceMode {
#[default]
RemoveEmptySlices,
PreserveEmptyTextSliceCaret,
}
pub fn remove_text_from_caret_range(
initial_range: &CaretRange,
slice_mode: SliceMode,
) -> Result<CaretRange, LexicalError> {
if initial_range.is_collapsed() {
return Ok(initial_range.clone());
}
let root_mode = RootMode::Root;
let next_direction = CaretDirection::Next;
let mut slice_state = slice_mode;
let range = get_caret_range_in_direction(initial_range, next_direction)?;
let mut range_container = Some(range.anchor.origin().clone());
while let Some(container) = range_container
.as_ref()
.filter(|c| !is_root_or_shadow_root(&*c.get_latest()))
{
range_container = container.get_parent();
}
let range_container_child = range_container
.as_ref()
.filter(|c| c.is_element())
.and_then(NodeRef::get_first_child);
let mut anchor_candidates = get_anchor_candidates(&range.anchor, root_mode)?;
let mut focus_candidates = get_anchor_candidates(&range.focus.get_flipped()?, root_mode)?;
let mut seen_start: HashSet<NodeKey> = HashSet::new();
let mut removed_nodes: Vec<NodeRef> = Vec::new();
for caret in range.iter_node_carets(root_mode) {
if caret.is_child_caret() {
seen_start.insert(caret.origin().get_key().to_owned());
} else if caret.is_sibling_caret() {
let origin = caret.origin();
if !origin.is_element() || seen_start.contains(origin.get_key()) {
removed_nodes.push(origin.clone());
}
}
}
let mut removed_parents: Vec<NodeRef> = Vec::new();
for node in &removed_nodes {
if let Some(parent) = node.get_parent()
&& !seen_start.contains(parent.get_key())
&& !removed_parents.contains(&parent)
{
removed_parents.push(parent);
}
remove_from_parent(node)?;
}
for parent in &removed_parents {
if !parent.can_be_empty()
&& !is_root_or_shadow_root(&*parent.get_latest())
&& parent.is_empty()
&& parent.is_attached()
{
parent.remove(false)?;
}
}
for slice in range.get_text_slices().into_iter().flatten() {
let origin = slice.caret.origin().clone();
let content_size = origin.get_text_content_size();
let caret_before = rewind_sibling_caret(&get_sibling_caret(&origin, next_direction))?;
let mode = origin.text_data().get_mode();
if (slice.distance.unsigned_abs() == content_size
&& slice_state == SliceMode::RemoveEmptySlices)
|| (mode == "token" && slice.distance != 0)
{
caret_before.remove()?;
} else if slice.distance != 0 {
slice_state = SliceMode::RemoveEmptySlices;
let mut next_caret = slice.remove_text_slice()?;
let slice_origin = slice.caret.origin();
if mode == "segmented" {
let src = next_caret.origin().clone();
let data = src.text_data();
let plain_text_node = create_text_node(data.get_text());
plain_text_node.set_style(data.get_style());
plain_text_node.set_format(data.get_format());
plain_text_node.set_detail(data.get_detail())?;
carry_node_state(&src, &plain_text_node)?;
caret_before.replace_or_insert(&plain_text_node, false)?;
next_caret = get_text_point_caret(
&plain_text_node,
next_direction,
next_caret.offset().expect("a text point caret"),
)?;
}
if slice_origin == anchor_candidates[0].origin() {
anchor_candidates[0] = next_caret.clone();
}
if slice_origin == focus_candidates[0].origin() {
focus_candidates[0] = next_caret.get_flipped()?;
}
}
}
let anchor_candidate = get_attached_caret(anchor_candidates.iter());
let focus_candidate = get_attached_caret(focus_candidates.iter());
let merge_targets = get_block_merge_targets(
anchor_candidate.as_ref(),
focus_candidate.as_ref(),
&seen_start,
);
if let Some((anchor_block, focus_block)) = merge_targets {
get_child_caret(&anchor_block, CaretDirection::Previous)
.expect("a block is an element")
.splice(0, &focus_block.get_children(), CaretDirection::Next)?;
let mut parent = focus_block.get_parent();
focus_block.remove(true)?;
while let Some(p) = parent.filter(NodeRef::is_empty) {
parent = p.get_parent();
p.remove(true)?;
}
} else if let Some(focus_candidate) = &focus_candidate {
let focus_block = get_block_from_caret(focus_candidate);
let focus_block_parent = focus_block.as_ref().and_then(NodeRef::get_parent);
let topmost_shadow_root = focus_block
.as_ref()
.and_then(|b| b.get_parents().into_iter().rev().find(is_shadow_root_node));
if let (Some(focus_block), Some(focus_block_parent)) = (&focus_block, &focus_block_parent)
&& !focus_block_parent.is_root()
&& focus_block.is_empty()
&& seen_start.contains(focus_block.get_key())
&& crate::slot::get_slot_names(focus_block).is_empty()
&& topmost_shadow_root.is_none_or(|r| seen_start.contains(r.get_key()))
{
focus_block.remove(true)?;
let mut parent = Some(focus_block_parent.clone());
while let Some(p) = parent.filter(|p| !p.is_root() && p.is_empty()) {
let grandparent = p.get_parent();
if let Some(g) = &grandparent
&& g.is_root()
&& g.get_children_size() <= 1
&& p.can_be_empty()
{
break;
}
parent = grandparent;
p.remove(true)?;
}
}
}
if restore_empty_container_paragraph(range_container.as_ref(), range_container_child.as_ref())?
.is_none()
&& range_container.as_ref().is_some_and(|c| !c.is_attached())
{
restore_empty_container_paragraph(Some(&get_root()), None)?;
}
let best_candidate = get_attached_caret(
anchor_candidate
.iter()
.chain(&focus_candidate)
.chain(&anchor_candidates)
.chain(&focus_candidates),
);
if let Some(best_candidate) = best_candidate {
let anchor = get_caret_in_direction(&best_candidate, initial_range.direction())?;
return Ok(get_collapsed_caret_range(anchor));
}
let keys: Vec<String> = anchor_candidates
.iter()
.map(|c| format!("\"{}\"", c.origin().get_key()))
.collect();
Err(LexicalError::new(format!(
"$removeTextFromCaretRange: selection was lost, could not find a new anchor given candidates with keys: [{}]",
keys.join(",")
)))
}
fn get_attached_caret<'a>(
mut candidates: impl Iterator<Item = &'a PointCaret>,
) -> Option<PointCaret> {
candidates
.find(|c| is_caret_attached(c))
.map(normalize_caret)
}
fn get_block_from_caret(caret: &PointCaret) -> Option<NodeRef> {
if caret.is_child_caret() {
let origin = caret.origin();
is_block(origin).then(|| origin.clone())
} else {
caret.get_parent_at_caret().filter(is_block)
}
}
fn get_block_merge_targets(
anchor: Option<&PointCaret>,
focus: Option<&PointCaret>,
seen_start: &HashSet<NodeKey>,
) -> Option<(NodeRef, NodeRef)> {
let anchor_parent = anchor?.get_parent_at_caret()?;
let focus_parent = focus?.get_parent_at_caret()?;
let common = get_common_ancestor(&anchor_parent, &focus_parent)?;
if !matches!(common, CommonAncestorResult::Branch { .. }) {
return None;
}
let get_block = |parent: &NodeRef, selected_only: bool| -> Option<NodeRef> {
let mut block = None;
let mut node = Some(parent.clone());
while let Some(n) = node.filter(|n| n != common.common_ancestor()) {
if is_root_or_shadow_root(&*n.get_latest()) {
return None;
}
if (!selected_only || seen_start.contains(n.get_key())) && is_block(&n) {
block = Some(n.clone());
}
node = n.get_parent();
}
block
};
let anchor_block = get_block(&anchor_parent, false)?;
let focus_block = get_block(&focus_parent, true)?;
crate::slot::get_slot_names(&focus_block)
.is_empty()
.then_some((anchor_block, focus_block))
}
fn get_deepest_child_or_self(initial_caret: PointCaret) -> PointCaret {
let mut caret = initial_caret;
while caret.is_child_caret() {
match get_adjacent_child_caret(Some(&caret)) {
Some(adjacent) if adjacent.is_child_caret() => caret = adjacent,
_ => break,
}
}
caret
}
pub fn normalize_caret(initial_caret: &PointCaret) -> PointCaret {
let caret = get_deepest_child_or_self(initial_caret.get_latest());
let direction = caret.direction();
if caret.origin().is_text() {
return if caret.is_text_point_caret() {
caret
} else {
get_text_point_caret_at_end(caret.origin(), direction, direction)
};
}
match caret.get_adjacent_caret() {
Some(adj) if adj.is_sibling_caret() && adj.origin().is_text() => {
get_text_point_caret_at_end(adj.origin(), direction, flip_direction(direction))
}
_ => caret,
}
}
pub fn is_extendable_text_point_caret(caret: &PointCaret) -> bool {
caret.offset().is_some_and(|offset| {
get_text_node_offset(caret.origin(), TextOffset::End(caret.direction()), false)
.is_ok_and(|end| offset != end)
})
}
pub fn get_caret_range_in_direction(
range: &CaretRange,
direction: CaretDirection,
) -> Result<CaretRange, LexicalError> {
if range.direction() == direction {
return Ok(range.clone());
}
get_caret_range(
get_caret_in_direction(&range.focus, direction)?,
get_caret_in_direction(&range.anchor, direction)?,
)
}
pub fn get_child_caret_at_index(
parent: &NodeRef,
index: usize,
direction: CaretDirection,
) -> NodeCaret {
let size = parent.get_children_size();
let offset = index.min(size);
let origin = match direction {
CaretDirection::Next => offset.checked_sub(1),
CaretDirection::Previous => Some(offset),
}
.filter(|&i| i < size)
.and_then(|i| parent.get_child_at_index(i));
match origin {
Some(origin) => get_sibling_caret(&origin, direction),
None => get_child_caret(parent, direction).expect("a parent is an element"),
}
}
pub fn get_adjacent_sibling_or_parent_sibling_caret(
start_caret: &NodeCaret,
root_mode: RootMode,
) -> Option<(NodeCaret, isize)> {
let mut depth_diff = 0;
let mut caret = start_caret.clone();
let mut next_caret = get_adjacent_child_caret(Some(&caret));
while next_caret.is_none() {
depth_diff -= 1;
caret = caret.get_parent_caret(root_mode)?;
next_caret = get_adjacent_child_caret(Some(&caret));
}
next_caret.map(|c| (c, depth_diff))
}
pub fn get_text_point_caret_slice_for_node<'a>(
slices: &'a [Option<TextPointCaretSlice>],
node: &NodeRef,
) -> Option<&'a TextPointCaretSlice> {
slices
.iter()
.flatten()
.find(|slice| slice.caret.origin() == node)
}
pub fn split_text_point_caret(text_point_caret: &PointCaret) -> Result<NodeCaret, LexicalError> {
let origin = text_point_caret.origin();
let direction = text_point_caret.direction();
let offset = text_point_caret.offset().expect("a text point caret");
if offset == get_text_node_offset(origin, TextOffset::End(direction), false)? {
return Ok(text_point_caret.get_sibling_caret());
} else if offset
== get_text_node_offset(origin, TextOffset::End(flip_direction(direction)), false)?
{
return rewind_sibling_caret(&text_point_caret.get_sibling_caret());
}
let parts = origin.split_text(&[offset as i64])?;
let text_node = parts.first().filter(|n| n.is_text()).ok_or_else(|| {
LexicalError::new("$splitTextPointCaret: splitText must return at least one TextNode")
})?;
get_caret_in_direction(
&get_sibling_caret(text_node, CaretDirection::Next),
direction,
)
}
#[derive(Clone, Copy)]
pub struct SplitAtPointCaretNextOptions {
pub root_mode: RootMode,
pub should_split: fn(&NodeRef, &'static str) -> bool,
pub remove_empty_destination: bool,
}
impl Default for SplitAtPointCaretNextOptions {
fn default() -> Self {
Self {
root_mode: RootMode::ShadowRoot,
should_split: |_, _| true,
remove_empty_destination: false,
}
}
}
pub(crate) fn get_adjacent_nodes(initial_caret: &NodeCaret) -> Vec<NodeRef> {
let next = initial_caret.direction() == CaretDirection::Next;
let mut siblings = Vec::new();
let mut node = initial_caret.get_node_at_caret();
while let Some(n) = node {
node = if next {
n.get_next_sibling()
} else {
n.get_previous_sibling()
};
siblings.push(n);
}
siblings
}
pub fn split_at_point_caret_next(
point_caret: &PointCaret,
options: &SplitAtPointCaretNextOptions,
) -> Result<Option<NodeCaret>, LexicalError> {
if point_caret.is_text_point_caret() {
return split_text_point_caret(point_caret).map(Some);
}
let parent_caret = point_caret.get_parent_caret(options.root_mode);
if let Some(parent_caret) = &parent_caret {
let origin = parent_caret.origin();
if point_caret.is_child_caret() {
let before_parent_caret = rewind_sibling_caret(parent_caret)?;
if options.remove_empty_destination && origin.is_empty() {
origin.remove(false)?;
return Ok(Some(before_parent_caret));
}
if !(origin.can_be_empty() && (options.should_split)(origin, "first")) {
return Ok(Some(before_parent_caret));
}
}
let siblings = get_adjacent_nodes(point_caret);
if !siblings.is_empty()
|| (!options.remove_empty_destination
&& origin.can_be_empty()
&& (options.should_split)(origin, "last"))
{
let copy = copy_node(origin);
copy.splice(0, 0, &siblings)?;
parent_caret.insert(©)?;
}
}
Ok(parent_caret)
}
pub fn insert_node_to_nearest_root_at_caret(
node: &NodeRef,
caret: &PointCaret,
options: &SplitAtPointCaretNextOptions,
) -> Result<NodeCaret, LexicalError> {
let mut insert_caret = get_caret_in_direction(caret, CaretDirection::Next)?;
if let Some(offset) = insert_caret.offset() {
let origin = insert_caret.origin().clone();
if offset == 0 {
insert_caret = get_sibling_caret(&origin, CaretDirection::Previous).get_flipped()?;
} else if offset == origin.get_text_content_size() {
insert_caret = get_sibling_caret(&origin, CaretDirection::Next);
}
}
if insert_caret.origin() == node {
invariant!(
insert_caret.is_sibling_caret(),
"$insertNodeToNearestRootAtCaret node {} of type {} can not be inserted into itself",
node.get_key(),
node.get_type()
);
insert_caret = rewind_sibling_caret(&insert_caret)?;
}
if insert_caret.get_node_at_caret().as_ref() == Some(node)
|| insert_caret.get_flipped()?.get_node_at_caret().as_ref() == Some(node)
{
node.remove(true)?;
}
let stops_at_containers = options.root_mode == RootMode::ShadowRoot;
let mut next_caret = Some(insert_caret.clone());
while let Some(caret) = next_caret {
insert_caret = caret;
let container = if insert_caret.is_child_caret() {
Some(insert_caret.origin().clone())
} else {
insert_caret.origin().get_parent()
};
if stops_at_containers
&& !insert_caret.is_text_point_caret()
&& container.as_ref().is_some_and(is_block_container)
{
break;
}
next_caret = split_at_point_caret_next(&insert_caret, options)?;
}
invariant!(
!insert_caret.is_text_point_caret(),
"$insertNodeToNearestRootAtCaret: An unattached TextNode can not be split"
);
if node.is_inline() {
let paragraph = create_paragraph_node();
paragraph.append(std::slice::from_ref(node))?;
insert_caret.insert(¶graph)?;
} else {
insert_caret.insert(node)?;
}
get_caret_in_direction(
&get_sibling_caret(node, CaretDirection::Next),
caret.direction(),
)
}