1use crate::caret::{
5 CommonAncestorResult, get_common_ancestor, get_common_ancestor_result_branch_order,
6};
7use crate::caret_tree::{
8 detach_node_with_selection, error_on_insert_text_node_on_root, insert_node_between,
9 insert_sibling, select_adjacent_node,
10};
11use crate::editor_state::NodeMap;
12use crate::error::invariant;
13use crate::lexical_selection::{
14 PointType, SelectionRef, Which, get_selection, maybe_move_children_selection_to_parent,
15 move_selection_point_to_end, move_selection_point_to_sibling, set_selection,
16};
17use crate::lexical_utils::{get_node_by_key_impl, get_writable, mutate, with_writable};
18use crate::node_state::{NodeStateRef, RequiredNodeStateConfig};
19use crate::nodes::element::{self, ElementData, is_root_or_shadow_root};
20use crate::nodes::root::RootNode;
21use crate::nodes::text::TextData;
22use crate::updates::{error_on_read_only, get_active_editor_state};
23use crate::{LexicalError, json::Object, utf16};
24use std::any::Any;
25use std::cmp::Ordering;
26use std::fmt;
27use std::rc::Rc;
28
29pub type NodeKey = String;
32
33#[derive(Clone, Debug, Default)]
40pub struct NodeBase {
41 pub(crate) key: NodeKey,
42 pub(crate) parent: Option<NodeKey>,
43 pub(crate) prev: Option<NodeKey>,
44 pub(crate) next: Option<NodeKey>,
45 pub(crate) state: Option<NodeStateRef>,
46 pub(crate) slot_host: Option<NodeKey>,
49 pub(crate) slots: Option<Rc<crate::slot::SlotMap>>,
52 pub(crate) written_in: u64,
55 pub(crate) structure_rule_inputs: StructureRuleInputs,
59}
60
61#[derive(Debug, Default)]
64pub(crate) struct StructureRuleInputs(std::cell::Cell<Option<u8>>);
65
66impl Clone for StructureRuleInputs {
67 fn clone(&self) -> Self {
68 Self::default()
69 }
70}
71
72impl StructureRuleInputs {
73 pub(crate) fn get(&self) -> Option<u8> {
74 self.0.get()
75 }
76 pub(crate) fn set(&self, value: Option<u8>) {
77 self.0.set(value);
78 }
79}
80
81pub trait LexicalNode: NodeClone + fmt::Debug + 'static {
101 fn get_type(&self) -> &'static str;
103
104 fn base(&self) -> &NodeBase;
105 fn base_mut(&mut self) -> &mut NodeBase;
106
107 fn element(&self) -> Option<&ElementData> {
109 None
110 }
111 fn element_mut(&mut self) -> Option<&mut ElementData> {
112 None
113 }
114
115 fn text(&self) -> Option<&TextData> {
117 None
118 }
119 fn text_mut(&mut self) -> Option<&mut TextData> {
120 None
121 }
122
123 #[cfg(feature = "decorator-block")]
127 fn decorator_block(&self) -> Option<&crate::decorator_block::DecoratorBlockData> {
128 None
129 }
130 #[cfg(feature = "decorator-block")]
131 fn decorator_block_mut(&mut self) -> Option<&mut crate::decorator_block::DecoratorBlockData> {
132 None
133 }
134
135 fn is_inline(&self) -> bool {
141 if self.text().is_some() {
142 return true;
143 }
144 if let Some(inline) = crate::structure::declared_inline(self.as_node()) {
145 return inline;
146 }
147 self.is_decorator() && !is_decorator_block(self)
148 }
149
150 fn is_decorator(&self) -> bool {
155 is_decorator_block(self)
156 }
157
158 fn decorate(&self, editor: &crate::Editor) -> Option<Rc<dyn Any>> {
167 let _ = editor;
168 None
169 }
170
171 fn is_isolated(&self) -> bool {
175 false
176 }
177
178 fn is_keyboard_selectable(&self) -> bool {
181 true
182 }
183
184 fn is_inline_formattable(&self) -> bool {
188 self.text().is_some()
189 }
190
191 fn get_inline_format(&self) -> f64 {
193 self.text().map_or(0.0, |t| t.format)
194 }
195
196 fn set_inline_format(&self, this: &NodeRef, format: f64) -> Result<(), LexicalError> {
199 self.set_format(this, format);
200 Ok(())
201 }
202
203 fn is_shadow_root(&self) -> bool {
205 false
206 }
207
208 fn can_be_empty(&self) -> bool {
211 true
212 }
213
214 fn can_indent(&self) -> bool {
217 !is_decorator_block(self)
218 }
219
220 fn can_merge_when_empty(&self) -> bool {
223 false
224 }
225
226 fn is_parent_required(&self) -> bool {
229 false
230 }
231
232 fn create_parent_element_node(&self) -> NodeRef {
235 crate::nodes::paragraph::create_paragraph_node()
236 }
237
238 fn insert_new_after(
243 &self,
244 this: &NodeRef,
245 selection: &SelectionRef,
246 restore_selection: bool,
247 ) -> Result<Option<NodeRef>, LexicalError> {
248 let _ = (this, selection, restore_selection);
249 Ok(None)
250 }
251
252 fn collapse_at_start(
256 &self,
257 this: &NodeRef,
258 selection: &SelectionRef,
259 ) -> Result<bool, LexicalError> {
260 let _ = (this, selection);
261 Ok(false)
262 }
263
264 fn append(&self, this: &NodeRef, nodes: &[NodeRef]) -> Result<(), LexicalError> {
267 this.splice(this.get_children_size(), 0, nodes)
268 }
269
270 fn splice(
274 &self,
275 this: &NodeRef,
276 start: usize,
277 delete_count: usize,
278 nodes_to_insert: &[NodeRef],
279 ) -> Result<(), LexicalError> {
280 element::splice(this, start, delete_count, nodes_to_insert)
281 }
282
283 fn replace(
286 &self,
287 this: &NodeRef,
288 replace_with: &NodeRef,
289 include_children: bool,
290 ) -> Result<NodeRef, LexicalError> {
291 replace(this, replace_with, include_children)
292 }
293
294 fn insert_after(
297 &self,
298 this: &NodeRef,
299 node_to_insert: &NodeRef,
300 restore_selection: bool,
301 ) -> Result<NodeRef, LexicalError> {
302 insert_after(this, node_to_insert, restore_selection)
303 }
304
305 fn remove(&self, this: &NodeRef, preserve_empty_parent: bool) -> Result<(), LexicalError> {
308 remove(this, preserve_empty_parent)
309 }
310
311 fn get_indent(&self, this: &NodeRef) -> Result<f64, LexicalError> {
313 let _ = this;
314 Ok(self.element().map_or(0.0, |e| e.indent))
315 }
316
317 fn set_indent(&self, this: &NodeRef, indent: f64) -> Result<(), LexicalError> {
320 with_writable(this.get_key(), |n| {
321 n.element_mut().expect("an element").indent = indent
322 });
323 Ok(())
324 }
325
326 fn transform(&self, this: &NodeRef) -> Result<(), LexicalError> {
331 let _ = this;
332 Ok(())
333 }
334
335 fn state_configs(&self) -> Vec<RequiredNodeStateConfig> {
339 Vec::new()
340 }
341
342 fn reset_on_copy_node_from(&self, this: &NodeRef, original: &NodeRef) {
347 let _ = (this, original);
348 }
349
350 fn extract_with_child(
356 &self,
357 this: &NodeRef,
358 child: &NodeRef,
359 selection: Option<&SelectionRef>,
360 destination: &str,
361 ) -> Result<bool, LexicalError> {
362 let _ = (this, child, selection, destination);
363 Ok(false)
364 }
365
366 fn declared_slots(&self) -> &'static [&'static str] {
370 &[]
371 }
372
373 fn declares_inline_children(&self) -> bool {
379 use crate::structure::{NodeChildEntry, NodeChildrenConfig};
380 match crate::structure::get_declared_node_structure(self.as_node()).children {
381 Some(NodeChildrenConfig::Inline) => true,
382 Some(NodeChildrenConfig::List(entries)) => entries.contains(&NodeChildEntry::Inline),
383 _ => false,
384 }
385 }
386
387 fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
394 Vec::new()
395 }
396
397 fn internal_after_structure_merge(
404 &self,
405 this: &NodeRef,
406 last: &NodeRef,
407 first: &NodeRef,
408 ) -> Result<bool, LexicalError> {
409 let _ = (this, last, first);
410 Ok(false)
411 }
412
413 fn internal_after_structure_split(
418 &self,
419 this: &NodeRef,
420 original: &NodeRef,
421 preceding: &[NodeRef],
422 ) -> Result<(), LexicalError> {
423 let _ = (this, original, preceding);
424 Ok(())
425 }
426
427 fn internal_lifts_from_structure(&self) -> Option<crate::structure::LiftsFromStructure> {
432 None
433 }
434
435 fn is_text_entity(&self) -> bool {
438 false
439 }
440
441 fn can_have_format(&self) -> bool {
444 true
445 }
446
447 fn exclude_from_copy(&self, destination: &str) -> bool {
452 let _ = destination;
453 false
454 }
455
456 fn can_replace_with(&self, replacement: &NodeRef) -> bool {
459 let _ = replacement;
460 true
461 }
462
463 fn can_insert_after(&self, node: &NodeRef) -> bool {
466 let _ = node;
467 true
468 }
469
470 fn selection_transform(
476 &self,
477 this: &NodeRef,
478 prev_selection: Option<&SelectionRef>,
479 next_selection: &SelectionRef,
480 ) -> Result<(), LexicalError> {
481 let _ = (this, prev_selection, next_selection);
482 Ok(())
483 }
484
485 fn set_format(&self, this: &NodeRef, format: f64) {
488 with_writable(this.get_key(), |n| {
489 n.text_mut().expect("a text node").format = format
490 });
491 }
492
493 fn can_insert_text_before(&self) -> bool {
496 true
497 }
498
499 fn can_insert_text_after(&self) -> bool {
502 true
503 }
504
505 fn get_text_content(&self) -> String {
507 if let Some(text) = self.text() {
508 return text.text.clone();
509 }
510 if self.element().is_some() {
511 return element::get_text_content(self.as_node());
512 }
513 crate::slot::get_slots_text_content(self.as_node())
515 }
516
517 fn get_text_content_size(&self) -> usize {
525 if self.element().is_some() {
526 return element::get_text_content_size(self.as_node());
527 }
528 utf16::len(&self.get_text_content())
529 }
530
531 fn should_serialize_text_styles(&self) -> bool {
533 element::should_serialize_text_styles(self.as_node())
534 }
535
536 #[cfg(feature = "html")]
540 fn create_dom(
541 &self,
542 this: &NodeRef,
543 config: &crate::EditorConfig,
544 editor: &crate::Editor,
545 ) -> Result<crate::dom::DomNode, LexicalError> {
546 let _ = (this, editor);
547 if self.text().is_some() {
548 return crate::nodes::text::create_dom(self.as_node(), config);
549 }
550 Err(LexicalError::new("createDOM: base method not extended"))
551 }
552
553 #[cfg(feature = "html")]
558 fn export_dom(
559 &self,
560 this: &NodeRef,
561 editor: &crate::Editor,
562 ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
563 if self.element().is_some() {
564 element::export_dom(self.as_node(), this, editor)
565 } else if self.text().is_some() {
566 crate::nodes::text::export_dom(self.as_node(), this, editor)
567 } else {
568 crate::lexical_dom::export_dom_base(self.as_node(), this, editor)
569 }
570 }
571
572 fn super_types(&self) -> Vec<&'static str> {
582 if self.text().is_some() && self.get_type() != "text" {
583 vec!["text"]
584 } else {
585 Vec::new()
586 }
587 }
588
589 #[cfg(feature = "html")]
592 fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
593 None
594 }
595
596 fn json_schema_chain(&self) -> Vec<crate::schema::NodeSchema> {
605 if self.element().is_some() {
606 return vec![element::element_node_schema()];
607 }
608 if self.text().is_some() {
609 return vec![crate::nodes::text::text_node_schema()];
610 }
611 #[cfg(feature = "decorator-block")]
612 if self.decorator_block().is_some() {
613 return vec![crate::decorator_block::decorator_block_node_schema()];
614 }
615 Vec::new()
616 }
617
618 fn generated_export_json(&self, compact: bool) -> Option<Object> {
624 let _ = compact;
625 None
626 }
627
628 fn generated_update_from_json(&mut self, json: &Object) -> bool {
632 let _ = json;
633 false
634 }
635
636 fn export_json(&self, compact: bool) -> Object {
644 crate::schema::export_node_json_once(self.as_node(), compact)
645 }
646
647 fn update_from_json(&mut self, json: &Object) {
653 crate::schema::apply_json_setters(self.as_node_mut(), json);
654 }
655
656 fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
662 match (self.text(), prev_node.text()) {
663 (Some(next), Some(prev)) => crate::nodes::text::update_dom(prev, next),
664 _ => false,
665 }
666 }
667}
668
669#[allow(unused_variables)]
671fn is_decorator_block<N: LexicalNode + ?Sized>(node: &N) -> bool {
672 #[cfg(feature = "decorator-block")]
673 return node.decorator_block().is_some();
674 #[cfg(not(feature = "decorator-block"))]
675 false
676}
677
678pub trait NodeClone {
681 fn clone_node(&self) -> Box<dyn LexicalNode>;
682 fn as_any(&self) -> &dyn Any;
683 fn as_any_mut(&mut self) -> &mut dyn Any;
684 fn as_node(&self) -> &dyn LexicalNode;
685 fn as_node_mut(&mut self) -> &mut dyn LexicalNode;
686 fn class_name(&self) -> &'static str;
689}
690
691impl<T: LexicalNode + Clone> NodeClone for T {
692 fn clone_node(&self) -> Box<dyn LexicalNode> {
693 Box::new(self.clone())
694 }
695 fn as_any(&self) -> &dyn Any {
696 self
697 }
698 fn as_any_mut(&mut self) -> &mut dyn Any {
699 self
700 }
701 fn as_node(&self) -> &dyn LexicalNode {
702 self
703 }
704 fn as_node_mut(&mut self) -> &mut dyn LexicalNode {
705 self
706 }
707 fn class_name(&self) -> &'static str {
708 let name = std::any::type_name::<T>();
709 let name = name.split('<').next().unwrap_or(name);
710 name.rsplit("::").next().unwrap_or(name)
711 }
712}
713
714impl dyn LexicalNode {
715 pub fn get_key(&self) -> &str {
716 &self.base().key
717 }
718
719 pub fn is<T: LexicalNode>(&self) -> bool {
721 self.as_any().is::<T>()
722 }
723
724 pub fn downcast_ref<T: LexicalNode>(&self) -> Option<&T> {
725 self.as_any().downcast_ref()
726 }
727
728 pub fn downcast_mut<T: LexicalNode>(&mut self) -> Option<&mut T> {
729 self.as_any_mut().downcast_mut()
730 }
731}
732
733#[derive(Clone, Debug, PartialEq, Eq, Hash)]
739pub struct NodeRef {
740 key: NodeKey,
741}
742
743fn sibling<'a>(node_map: &'a NodeMap, key: &str, forward: bool) -> Option<&'a str> {
747 let node = node_map.get(key).unwrap_or_else(|| {
748 panic!(
749 "Lexical node does not exist in active editor state. Avoid using the same node references between nested closures from editorState.read/editor.update."
750 )
751 });
752 let base = node.base();
753 if forward { &base.next } else { &base.prev }.as_deref()
754}
755
756pub(crate) fn sibling_key_at(key: &str, steps: usize, forward: bool) -> Option<NodeKey> {
759 let editor_state = get_active_editor_state();
760 let node_map = editor_state.0.node_map.borrow();
761 let mut key = key;
762 for _ in 0..steps {
763 key = sibling(&node_map, key, forward)?;
764 }
765 Some(key.to_owned())
766}
767
768impl NodeRef {
769 pub(crate) fn new(key: impl Into<NodeKey>) -> Self {
770 Self { key: key.into() }
771 }
772
773 pub fn get_key(&self) -> &str {
774 &self.key
775 }
776
777 pub fn get_latest(&self) -> Rc<dyn LexicalNode> {
779 get_node_by_key_impl(&get_active_editor_state(), &self.key).unwrap_or_else(|| {
780 panic!(
781 "Lexical node does not exist in active editor state. Avoid using the same node references between nested closures from editorState.read/editor.update."
782 )
783 })
784 }
785
786 pub fn get_type(&self) -> &'static str {
787 self.get_latest().get_type()
788 }
789
790 pub fn is_element(&self) -> bool {
792 self.get_latest().element().is_some()
793 }
794
795 pub fn is_text(&self) -> bool {
797 self.get_latest().text().is_some()
798 }
799
800 pub fn is_decorator(&self) -> bool {
802 self.get_latest().is_decorator()
803 }
804
805 pub fn is_isolated(&self) -> bool {
807 self.get_latest().is_isolated()
808 }
809
810 pub fn is_keyboard_selectable(&self) -> bool {
812 self.get_latest().is_keyboard_selectable()
813 }
814
815 pub fn is_root(&self) -> bool {
817 self.get_latest().is::<RootNode>()
818 }
819
820 pub fn is_inline(&self) -> bool {
821 self.get_latest().is_inline()
822 }
823
824 pub fn get_parent(&self) -> Option<NodeRef> {
825 self.get_latest().base().parent.clone().map(NodeRef::new)
826 }
827
828 pub fn get_parents(&self) -> Vec<NodeRef> {
830 let mut parents = Vec::new();
831 let mut node = self.get_parent();
832 while let Some(n) = node {
833 node = n.get_parent();
834 parents.push(n);
835 }
836 parents
837 }
838
839 pub fn get_previous_sibling(&self) -> Option<NodeRef> {
840 self.get_latest().base().prev.clone().map(NodeRef::new)
841 }
842
843 pub fn get_next_sibling(&self) -> Option<NodeRef> {
844 self.get_latest().base().next.clone().map(NodeRef::new)
845 }
846
847 pub fn get_first_child(&self) -> Option<NodeRef> {
848 let node = self.get_latest();
849 node.element()?.first.clone().map(NodeRef::new)
850 }
851
852 pub fn get_last_child(&self) -> Option<NodeRef> {
853 let node = self.get_latest();
854 node.element()?.last.clone().map(NodeRef::new)
855 }
856
857 pub fn get_children_size(&self) -> usize {
858 self.get_latest().element().map_or(0, |e| e.size)
859 }
860
861 pub fn get_children(&self) -> Vec<NodeRef> {
863 let mut children = Vec::with_capacity(self.get_children_size());
864 let mut child = self.get_first_child();
865 while let Some(c) = child {
866 child = c.get_next_sibling();
867 children.push(c);
868 }
869 children
870 }
871
872 pub fn get_text_content(&self) -> String {
873 self.get_latest().get_text_content()
874 }
875
876 pub fn export_json(&self, compact: bool) -> Object {
878 crate::node_state::export_json_with_state(&*self.get_latest(), compact)
879 }
880
881 pub fn update_from_json(&self, json: &Object) -> Result<(), LexicalError> {
885 crate::node_state::update_state_from_json(self, json)?;
886 crate::node_state::apply_flat_states(self, json)?;
887 with_writable(&self.key, |node| node.update_from_json(json));
888 Ok(())
889 }
890
891 pub fn get_parent_or_throw(&self) -> Result<NodeRef, LexicalError> {
893 self.get_parent().ok_or_else(|| {
894 LexicalError::new(format!("Expected node {} to have a parent.", self.key))
895 })
896 }
897
898 pub fn is_attached(&self) -> bool {
901 let editor_state = get_active_editor_state();
902 let node_map = editor_state.0.node_map.borrow();
903 let mut key = self.key.as_str();
904 loop {
905 if key == "root" {
906 return true;
907 }
908 match node_map.get(key).and_then(|n| {
910 n.base()
911 .parent
912 .as_deref()
913 .or_else(|| crate::slot::slot_host_key_field(&**n).map(String::as_str))
914 }) {
915 Some(parent) => key = parent,
916 None => return false,
917 }
918 }
919 }
920
921 pub fn get_index_within_parent(&self) -> Option<usize> {
923 let parent = self.get_parent()?;
924 let size = parent.get_children_size();
925 let editor_state = get_active_editor_state();
926 let node_map = editor_state.0.node_map.borrow();
927 let (mut before, mut after) = (self.key.as_str(), self.key.as_str());
930 let mut steps = 0;
931 loop {
932 match sibling(&node_map, before, false) {
933 Some(key) => before = key,
934 None => return Some(steps),
935 }
936 match sibling(&node_map, after, true) {
937 Some(key) => after = key,
938 None => return size.checked_sub(steps + 1),
939 }
940 steps += 1;
941 }
942 }
943
944 pub fn get_text_content_size(&self) -> usize {
947 self.get_latest().get_text_content_size()
948 }
949
950 pub fn can_be_empty(&self) -> bool {
952 self.get_latest().can_be_empty()
953 }
954
955 pub fn can_indent(&self) -> bool {
957 self.get_latest().can_indent()
958 }
959
960 pub fn can_merge_when_empty(&self) -> bool {
962 self.get_latest().can_merge_when_empty()
963 }
964
965 pub fn is_parent_required(&self) -> bool {
967 self.get_latest().is_parent_required()
968 }
969
970 pub fn create_parent_element_node(&self) -> NodeRef {
972 self.get_latest().create_parent_element_node()
973 }
974
975 pub fn insert_new_after(
977 &self,
978 selection: &SelectionRef,
979 restore_selection: bool,
980 ) -> Result<Option<NodeRef>, LexicalError> {
981 self.get_latest()
982 .insert_new_after(self, selection, restore_selection)
983 }
984
985 pub fn collapse_at_start(&self, selection: &SelectionRef) -> Result<bool, LexicalError> {
987 self.get_latest().collapse_at_start(self, selection)
988 }
989
990 pub fn extract_with_child(
992 &self,
993 child: &NodeRef,
994 selection: Option<&SelectionRef>,
995 destination: &str,
996 ) -> Result<bool, LexicalError> {
997 self.get_latest()
998 .extract_with_child(self, child, selection, destination)
999 }
1000
1001 pub fn is_text_entity(&self) -> bool {
1003 self.get_latest().is_text_entity()
1004 }
1005
1006 pub fn can_have_format(&self) -> bool {
1008 self.get_latest().can_have_format()
1009 }
1010
1011 pub fn exclude_from_copy(&self, destination: &str) -> bool {
1013 self.get_latest().exclude_from_copy(destination)
1014 }
1015
1016 pub fn can_replace_with(&self, replacement: &NodeRef) -> bool {
1018 self.get_latest().can_replace_with(replacement)
1019 }
1020
1021 pub fn can_insert_after(&self, node: &NodeRef) -> bool {
1023 self.get_latest().can_insert_after(node)
1024 }
1025
1026 pub fn get_top_level_element(&self) -> Result<Option<NodeRef>, LexicalError> {
1032 let mut node = Some(self.clone());
1033 while let Some(n) = node {
1034 let parent = n.get_parent();
1035 if parent
1036 .as_ref()
1037 .is_some_and(|p| crate::nodes::element::is_root_or_shadow_root(&*p.get_latest()))
1038 || crate::slot::get_slot_host_key(&n).is_some()
1039 {
1040 if !(n.is_element() || (n == *self && n.is_decorator())) {
1041 return Err(LexicalError::new(
1042 "Children of root nodes must be elements or decorators",
1043 ));
1044 }
1045 return Ok(Some(n));
1046 }
1047 node = parent;
1048 }
1049 Ok(None)
1050 }
1051
1052 pub fn get_top_level_element_or_throw(&self) -> Result<NodeRef, LexicalError> {
1056 if self.is_root() {
1057 return Err(LexicalError::new(
1058 "getTopLevelElementOrThrow: root nodes are not top level elements",
1059 ));
1060 }
1061 self.get_top_level_element()?.ok_or_else(|| {
1062 LexicalError::new(format!(
1063 "Expected node {} to have a top parent element.",
1064 self.key
1065 ))
1066 })
1067 }
1068
1069 pub fn get_parent_keys(&self) -> Vec<NodeKey> {
1071 self.get_parents()
1072 .into_iter()
1073 .map(|p| p.get_key().to_owned())
1074 .collect()
1075 }
1076
1077 pub fn get_children_keys(&self) -> Vec<NodeKey> {
1079 self.get_children()
1080 .into_iter()
1081 .map(|c| c.get_key().to_owned())
1082 .collect()
1083 }
1084
1085 pub fn is_last_child(&self) -> Result<bool, LexicalError> {
1088 Ok(self.get_parent_or_throw()?.get_last_child().as_ref() == Some(self))
1089 }
1090
1091 pub fn get_first_child_or_throw(&self) -> Result<NodeRef, LexicalError> {
1093 self.get_first_child().ok_or_else(|| {
1094 LexicalError::new(format!("Expected node {} to have a first child.", self.key))
1095 })
1096 }
1097
1098 pub fn get_last_child_or_throw(&self) -> Result<NodeRef, LexicalError> {
1100 self.get_last_child().ok_or_else(|| {
1101 LexicalError::new(format!("Expected node {} to have a last child.", self.key))
1102 })
1103 }
1104
1105 pub fn has_text_format(&self, format_type: &str) -> bool {
1108 use crate::constants::{TEXT_TYPE_TO_FORMAT, lookup};
1109 let flag = lookup(TEXT_TYPE_TO_FORMAT, format_type).unwrap_or(0);
1110 let format = self.get_latest().element().map_or(0.0, |e| e.text_format);
1111 crate::nodes::text::to_int32(format) & flag != 0
1112 }
1113
1114 pub fn get_format_flags(&self, format_type: &str, align_with_format: Option<i32>) -> i32 {
1118 let latest = self.get_latest();
1119 let format = match (latest.text(), latest.element()) {
1120 (Some(text), _) => text.format,
1121 (None, Some(element)) => element.text_format,
1122 (None, None) => 0.0,
1123 };
1124 crate::nodes::text::toggle_text_format_type(
1125 crate::nodes::text::to_int32(format),
1126 format_type,
1127 align_with_format,
1128 )
1129 }
1130
1131 pub fn is_directionless(&self) -> bool {
1134 let detail = self.get_latest().text().map_or(0.0, |t| t.detail);
1135 crate::nodes::text::to_int32(detail) & crate::constants::IS_DIRECTIONLESS != 0
1136 }
1137
1138 pub fn is_parent_of(&self, target: &NodeRef) -> bool {
1141 if self == target {
1142 return false;
1143 }
1144 let mut node = target.get_parent();
1145 while let Some(n) = node {
1146 if &n == self {
1147 return true;
1148 }
1149 node = n.get_parent();
1150 }
1151 false
1152 }
1153
1154 pub fn is_selected(&self, selection: Option<&SelectionRef>) -> Result<bool, LexicalError> {
1160 let current;
1161 let target_selection = match selection {
1162 Some(selection) => selection,
1163 None => match get_selection() {
1164 Some(selection) => {
1165 current = selection;
1166 ¤t
1167 }
1168 None => return Ok(false),
1169 },
1170 };
1171 let is_selected = target_selection
1173 .get_nodes()?
1174 .iter()
1175 .any(|node| node.get_key() == self.key);
1176 if !is_selected || self.is_text() {
1177 return Ok(is_selected);
1178 }
1179 if let Some(range) = target_selection.range()
1183 && range.anchor.point_type == PointType::Element
1184 && range.focus.point_type == PointType::Element
1185 {
1186 if range.is_collapsed() {
1187 return Ok(false);
1188 }
1189 let parent_node = self.get_parent();
1190 if let Some(parent_node) =
1191 parent_node.filter(|_| self.is_decorator() && self.is_inline())
1192 {
1193 let first_point = if target_selection.is_backward()? {
1194 &range.focus
1195 } else {
1196 &range.anchor
1197 };
1198 if first_point.key == parent_node.get_key()
1199 && first_point.offset == parent_node.get_children_size()
1200 && parent_node.get_last_child().as_ref() == Some(self)
1201 {
1202 return Ok(false);
1203 }
1204 }
1205 }
1206 Ok(is_selected)
1207 }
1208
1209 pub fn is_before(&self, target: &NodeRef) -> bool {
1212 match get_common_ancestor(self, target) {
1213 None => false,
1214 Some(CommonAncestorResult::Descendant { .. }) => true,
1215 Some(CommonAncestorResult::Branch { a, b, .. }) => {
1216 get_common_ancestor_result_branch_order(&a, &b) == Ordering::Less
1217 }
1218 Some(CommonAncestorResult::Same { .. } | CommonAncestorResult::Ancestor { .. }) => {
1219 false
1220 }
1221 }
1222 }
1223
1224 pub fn get_nodes_between(&self, target: &NodeRef) -> Vec<NodeRef> {
1228 let forward = self.is_before(target);
1229 let mut nodes = Vec::new();
1230 let mut node = Some(self.clone());
1231 let mut entering = true;
1232 let mut open_elements = 0usize;
1233 while let Some(current) = node {
1234 if entering || open_elements == 0 {
1238 nodes.push(current.clone());
1239 }
1240 if ¤t == target {
1241 break;
1242 }
1243 if !entering && open_elements > 0 {
1244 open_elements -= 1;
1245 }
1246 let child = if entering && current.is_element() {
1247 if forward {
1248 current.get_first_child()
1249 } else {
1250 current.get_last_child()
1251 }
1252 } else {
1253 None
1254 };
1255 if child.is_some() {
1256 open_elements += 1;
1257 }
1258 let adjacent = child.or_else(|| {
1259 if forward {
1260 current.get_next_sibling()
1261 } else {
1262 current.get_previous_sibling()
1263 }
1264 });
1265 entering = adjacent.is_some();
1266 node = adjacent.or_else(|| current.get_parent());
1267 }
1268 if !forward {
1269 nodes.reverse();
1270 }
1271 nodes
1272 }
1273
1274 fn is_selected_by_node_selection(&self, selection: &SelectionRef) -> bool {
1277 selection.with_node(|n| n.has(&self.key)).unwrap_or(false)
1278 }
1279
1280 pub fn mark_dirty(&self) {
1282 get_writable(&self.key);
1283 }
1284
1285 pub fn remove(&self, preserve_empty_parent: bool) -> Result<(), LexicalError> {
1287 self.get_latest().remove(self, preserve_empty_parent)
1288 }
1289
1290 pub fn replace(
1293 &self,
1294 replace_with: &NodeRef,
1295 include_children: bool,
1296 ) -> Result<NodeRef, LexicalError> {
1297 self.get_latest()
1298 .replace(self, replace_with, include_children)
1299 }
1300
1301 pub fn insert_after(
1303 &self,
1304 node_to_insert: &NodeRef,
1305 restore_selection: bool,
1306 ) -> Result<NodeRef, LexicalError> {
1307 self.get_latest()
1308 .insert_after(self, node_to_insert, restore_selection)
1309 }
1310
1311 pub fn get_indent(&self) -> Result<f64, LexicalError> {
1313 self.get_latest().get_indent(self)
1314 }
1315
1316 pub fn set_indent(&self, indent: f64) -> Result<(), LexicalError> {
1318 self.get_latest().set_indent(self, indent)
1319 }
1320
1321 pub fn get_previous_siblings(&self) -> Vec<NodeRef> {
1324 let mut siblings = Vec::new();
1325 let mut node = self.get_previous_sibling();
1326 while let Some(n) = node {
1327 node = n.get_previous_sibling();
1328 siblings.push(n);
1329 }
1330 siblings.reverse();
1331 siblings
1332 }
1333
1334 pub fn get_next_siblings(&self) -> Vec<NodeRef> {
1336 let mut siblings = Vec::new();
1337 let mut node = self.get_next_sibling();
1338 while let Some(n) = node {
1339 node = n.get_next_sibling();
1340 siblings.push(n);
1341 }
1342 siblings
1343 }
1344
1345 pub fn insert_before(
1347 &self,
1348 node_to_insert: &NodeRef,
1349 restore_selection: bool,
1350 ) -> Result<NodeRef, LexicalError> {
1351 invariant!(
1352 !self.is_root(),
1353 "insertBefore: cannot be called on root nodes"
1354 );
1355 insert_sibling(self, false, node_to_insert, restore_selection)
1356 }
1357
1358 pub fn select(
1361 &self,
1362 anchor_offset: Option<usize>,
1363 focus_offset: Option<usize>,
1364 ) -> Result<SelectionRef, LexicalError> {
1365 if self.is_text() {
1366 self.select_text(anchor_offset, focus_offset)
1367 } else if self.is_element() {
1368 self.select_element(anchor_offset, focus_offset)
1369 } else {
1370 Err(LexicalError::new(format!(
1371 "select: node {} is not a text node or an element",
1372 self.key
1373 )))
1374 }
1375 }
1376
1377 pub fn select_start(&self) -> Result<SelectionRef, LexicalError> {
1379 if self.is_text() {
1380 self.select(Some(0), Some(0))
1381 } else if self.is_element() {
1382 match self.get_first_descendant() {
1383 Some(first) => first.select_start(),
1384 None => self.select(None, None),
1385 }
1386 } else {
1387 self.select_previous(None, None)
1388 }
1389 }
1390
1391 pub fn select_end(&self) -> Result<SelectionRef, LexicalError> {
1393 if self.is_text() {
1394 let size = self.get_text_content_size();
1395 self.select(Some(size), Some(size))
1396 } else if self.is_element() {
1397 match self.get_last_descendant() {
1398 Some(last) => last.select_end(),
1399 None => self.select(None, None),
1400 }
1401 } else {
1402 self.select_next(Some(0), Some(0))
1403 }
1404 }
1405
1406 pub fn select_previous(
1408 &self,
1409 anchor_offset: Option<usize>,
1410 focus_offset: Option<usize>,
1411 ) -> Result<SelectionRef, LexicalError> {
1412 select_adjacent_node(self, false, anchor_offset, focus_offset)
1413 }
1414
1415 pub fn select_next(
1417 &self,
1418 anchor_offset: Option<usize>,
1419 focus_offset: Option<usize>,
1420 ) -> Result<SelectionRef, LexicalError> {
1421 select_adjacent_node(self, true, anchor_offset, focus_offset)
1422 }
1423}
1424
1425pub(crate) fn remove(this: &NodeRef, preserve_empty_parent: bool) -> Result<(), LexicalError> {
1428 invariant!(!this.is_root(), "remove: cannot be called on root nodes");
1429 remove_node(this, true, preserve_empty_parent)
1430}
1431
1432pub(crate) fn replace(
1435 this: &NodeRef,
1436 replace_with: &NodeRef,
1437 include_children: bool,
1438) -> Result<NodeRef, LexicalError> {
1439 invariant!(!this.is_root(), "replace: cannot be called on root nodes");
1440 error_on_read_only();
1441 let selection = get_selection().map(|s| s.clone_selection());
1442 error_on_insert_text_node_on_root(this, replace_with)?;
1443 let to_replace_key = this.get_key().to_owned();
1444 if let Some(slot_host) = crate::slot::get_slot_host(this) {
1445 return Err(LexicalError::new(format!(
1446 "replace: node {to_replace_key} (type {}) is slotted into host {} (type {}); a slot value cannot be replaced through the tree API. Use $setSlot on its host to assign a replacement.",
1447 this.get_type(),
1448 slot_host.get_key(),
1449 slot_host.get_type()
1450 )));
1451 }
1452 get_writable(replace_with.get_key());
1453 let parent = this.get_parent_or_throw()?;
1454 get_writable(parent.get_key());
1455 crate::slot::error_on_slot_cycle_child(&parent, replace_with)?;
1456 let size = parent.get_children_size();
1457 let replace_with_old_parent = replace_with.get_parent();
1458 let range = selection.as_ref().filter(|s| s.is_range());
1459 detach_node_with_selection(replace_with, range)?;
1460 let prev_sibling = this.get_previous_sibling();
1461 let next_sibling = this.get_next_sibling();
1462 remove_node(this, false, true)?;
1463 if let Some(p) = &prev_sibling {
1464 get_writable(p.get_key());
1465 }
1466 if let Some(n) = &next_sibling {
1467 get_writable(n.get_key());
1468 }
1469 insert_node_between(
1470 parent.get_key(),
1471 replace_with.get_key(),
1472 prev_sibling.as_ref().map(NodeRef::get_key),
1473 next_sibling.as_ref().map(NodeRef::get_key),
1474 );
1475 let size = if replace_with_old_parent.as_ref() == Some(&parent) {
1478 size - 1
1479 } else {
1480 size
1481 };
1482 mutate(parent.get_key(), |p| {
1483 p.element_mut().expect("a parent is an element").size = size
1484 });
1485 let mut prev_size_before_children_transfer = 0;
1486 if include_children {
1487 invariant!(
1488 this.is_element() && replace_with.is_element(),
1489 "includeChildren should only be true for ElementNodes"
1490 );
1491 prev_size_before_children_transfer = replace_with.get_children_size();
1492 replace_with.splice(prev_size_before_children_transfer, 0, &this.get_children())?;
1493 }
1494 if let Some(selection) = range {
1495 set_selection(Some(selection.clone()));
1496 for which in [Which::Anchor, Which::Focus] {
1497 let point = selection.point(which).expect("a range selection");
1498 if point.key == to_replace_key {
1499 if include_children && point.point_type == PointType::Element {
1500 selection.point_set(
1501 which,
1502 replace_with.get_key(),
1503 prev_size_before_children_transfer + point.offset,
1504 PointType::Element,
1505 )?;
1506 } else {
1507 move_selection_point_to_end(selection, which, replace_with)?;
1508 }
1509 }
1510 }
1511 }
1512 if crate::lexical_utils::get_composition_key().as_deref() == Some(to_replace_key.as_str()) {
1513 crate::lexical_utils::set_composition_key(Some(replace_with.get_key()));
1514 }
1515 Ok(replace_with.clone())
1516}
1517
1518pub(crate) fn insert_after(
1521 this: &NodeRef,
1522 node_to_insert: &NodeRef,
1523 restore_selection: bool,
1524) -> Result<NodeRef, LexicalError> {
1525 invariant!(
1526 !this.is_root(),
1527 "insertAfter: cannot be called on root nodes"
1528 );
1529 insert_sibling(this, true, node_to_insert, restore_selection)
1530}
1531
1532pub(crate) fn remove_node(
1534 node_to_remove: &NodeRef,
1535 restore_selection: bool,
1536 preserve_empty_parent: bool,
1537) -> Result<(), LexicalError> {
1538 error_on_read_only();
1539 let key = node_to_remove.get_key().to_owned();
1540 let Some(parent) = node_to_remove.get_parent() else {
1541 let slot_host_key = crate::slot::get_slot_host_key(node_to_remove);
1542 invariant!(
1543 slot_host_key.is_none(),
1544 "$removeNode: node {key} is slotted into host {}; use removeSlot on the host instead of remove().",
1545 slot_host_key.unwrap_or_default()
1546 );
1547 return Ok(());
1548 };
1549 let selection = maybe_move_children_selection_to_parent(node_to_remove)?;
1550 let mut selection_moved = false;
1551 match &selection {
1552 Some(range) if range.is_range() && restore_selection => {
1553 for which in [Which::Anchor, Which::Focus] {
1554 if range.point(which).expect("a range selection").key == key {
1555 move_selection_point_to_sibling(
1556 range,
1557 which,
1558 node_to_remove,
1559 &parent,
1560 node_to_remove.get_previous_sibling().as_ref(),
1561 node_to_remove.get_next_sibling().as_ref(),
1562 )?;
1563 selection_moved = true;
1564 }
1565 }
1566 }
1567 Some(nodes)
1568 if nodes.is_node()
1569 && restore_selection
1570 && node_to_remove.is_selected_by_node_selection(nodes) =>
1571 {
1572 node_to_remove.select_previous(None, None)?;
1573 }
1574 _ => {}
1575 }
1576
1577 get_writable(&key);
1578 let range = selection
1579 .as_ref()
1580 .filter(|s| restore_selection && !selection_moved && s.is_range());
1581 detach_node_with_selection(node_to_remove, range)?;
1582
1583 if !preserve_empty_parent
1584 && !is_root_or_shadow_root(&*parent.get_latest())
1585 && !parent.can_be_empty()
1586 && parent.is_empty()
1587 {
1588 remove_node(&parent, restore_selection, false)?;
1589 }
1590 if restore_selection && selection.is_some() && parent.is_root() && parent.is_empty() {
1591 parent.select_end()?;
1592 }
1593 Ok(())
1594}