1use crate::caret::{
22 CaretDirection, PointCaret, compare_point_caret_next, extend_caret_to_range, get_caret_range,
23 get_child_caret, get_collapsed_caret_range, get_sibling_caret,
24};
25use crate::caret_utils::{
26 caret_from_point, get_caret_range_in_direction, normalize_caret, rewind_sibling_caret,
27 set_selection_from_caret_range,
28};
29use crate::clipboard::{
30 caret_from_event, copy_to_clipboard, get_clipboard_data_from_selection, handle_rich_text_drop,
31 insert_data_transfer_for_rich_text, set_lexical_clipboard_data_transfer,
32 write_drag_source_to_data_transfer,
33};
34use crate::commands::{
35 CLICK_COMMAND, CONTROLLED_TEXT_INSERTION_COMMAND, COPY_COMMAND, CUT_COMMAND,
36 DELETE_CHARACTER_COMMAND, DELETE_LINE_COMMAND, DELETE_WORD_COMMAND, DRAGOVER_COMMAND,
37 DRAGSTART_COMMAND, DROP_COMMAND, FORMAT_ELEMENT_COMMAND, FORMAT_TEXT_COMMAND,
38 INDENT_CONTENT_COMMAND, INSERT_LINE_BREAK_COMMAND, INSERT_PARAGRAPH_COMMAND,
39 INSERT_TAB_COMMAND, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_LEFT_COMMAND, KEY_ARROW_RIGHT_COMMAND,
40 KEY_ARROW_UP_COMMAND, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, KEY_ENTER_COMMAND,
41 KEY_ESCAPE_COMMAND, KEY_SPACE_COMMAND, KEY_TAB_COMMAND, MOVE_TO_END, MOVE_TO_START,
42 OUTDENT_CONTENT_COMMAND, PASTE_COMMAND, REMOVE_TEXT_COMMAND, SELECT_ALL_COMMAND,
43 SET_TEXT_FORMAT_COMMAND,
44};
45use crate::editor::{COMMAND_PRIORITY_EDITOR, LexicalCommand};
46use crate::events::{ClipboardOrKeyboardEvent, DataTransferFile, KeyboardEvent, PasteCommandType};
47use crate::generated_json::{
48 export_compact_element_node, export_element_node, update_element_node,
49};
50use crate::json::{Object, Value};
51use crate::lexical_selection::SelectionRef;
52use crate::lexical_selection::get_selection;
53use crate::lexical_selection::{
54 PointType, RangeSelection, Which, create_node_selection, has_ancestor, set_selection,
55};
56use crate::lexical_utils::{
57 get_node_by_key, get_root, is_root_or_shadow_root, is_shadow_root_node,
58};
59use crate::lexical_utils::{set_node_key, with_writable};
60use crate::node::{LexicalNode, NodeBase, NodeRef};
61use crate::node_state::{
62 RequiredNodeStateConfig, StateConfig, create_state, get_state_direct, set_state,
63};
64use crate::nodes::element::ElementData;
65use crate::nodes::paragraph::create_paragraph_node;
66use crate::nodes::tab::create_tab_node;
67use crate::schema::{NodeSchema, SchemaValue, enum_value, node_schema, with_field};
68use crate::selection::{
69 is_parent_rtl, move_character, should_override_default_character_selection,
70};
71use crate::selection_deletion::{SelectionGranularity, needs_block_cursor_beside};
72use crate::selection_insert_nodes::normalize_selection;
73use crate::selection_insert_nodes::{insert_nodes, select_all};
74use crate::utils::{FilesEvent, event_files, get_nearest_block_element_ancestor_or_throw};
75use crate::utils::{find_matching_parent, handle_indent_and_outdent};
76use crate::utils::{is_at_end_of_node, is_at_start_of_node};
77use crate::{CUT_TAG, Editor, LexicalError, NodeClass, PASTE_TAG, Unregister, UpdateOptions};
78use std::rc::Rc;
79
80#[cfg(feature = "extension")]
81mod lexical_rich_text_extension;
82#[cfg(all(feature = "html", feature = "extension"))]
83mod rich_text_import_extension;
84mod table_of_contents;
85
86pub use table_of_contents::{TableOfContentsEntry, register_table_of_contents};
87
88#[cfg(feature = "extension")]
89pub use lexical_rich_text_extension::{
90 RichTextConfigOverrides, RichTextExtensionType, RichTextOutput, rich_text_extension,
91};
92#[cfg(all(feature = "html", feature = "extension"))]
93pub use rich_text_import_extension::{rich_text_import_rules, shadow_root_quote_rule};
94#[cfg(feature = "a11y")]
95mod heading_announce_extension;
96#[cfg(feature = "a11y")]
97pub use heading_announce_extension::{
98 HeadingAnnounceExtensionConfig, HeadingAnnounceExtensionConfigOverrides,
99 HeadingAnnounceExtensionType, HeadingAnnounceOutput, heading_announce_extension,
100};
101
102pub fn rich_text_nodes() -> Vec<NodeClass> {
105 vec![NodeClass::of::<HeadingNode>(), NodeClass::of::<QuoteNode>()]
106}
107
108#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
110pub enum HeadingTagType {
111 #[default]
112 H1,
113 H2,
114 H3,
115 H4,
116 H5,
117 H6,
118}
119
120impl HeadingTagType {
121 pub fn as_str(self) -> &'static str {
122 match self {
123 HeadingTagType::H1 => "h1",
124 HeadingTagType::H2 => "h2",
125 HeadingTagType::H3 => "h3",
126 HeadingTagType::H4 => "h4",
127 HeadingTagType::H5 => "h5",
128 HeadingTagType::H6 => "h6",
129 }
130 }
131
132 pub fn parse(tag: &str) -> Option<Self> {
134 Some(match tag {
135 "h1" => HeadingTagType::H1,
136 "h2" => HeadingTagType::H2,
137 "h3" => HeadingTagType::H3,
138 "h4" => HeadingTagType::H4,
139 "h5" => HeadingTagType::H5,
140 "h6" => HeadingTagType::H6,
141 _ => return None,
142 })
143 }
144}
145
146#[derive(Clone, Debug, Default)]
148pub struct HeadingNode {
149 base: NodeBase,
150 element: ElementData,
151 tag: HeadingTagType,
152}
153
154pub fn create_heading_node(tag: HeadingTagType) -> NodeRef {
156 crate::lexical_utils::replaced(set_node_key(Box::new(HeadingNode {
157 tag,
158 ..HeadingNode::default()
159 })))
160}
161
162pub fn is_heading_node(node: &NodeRef) -> bool {
164 node.get_latest().is::<HeadingNode>()
165}
166
167impl NodeRef {
168 pub fn get_heading_tag(&self) -> Option<HeadingTagType> {
170 self.get_latest()
171 .downcast_ref::<HeadingNode>()
172 .map(|h| h.tag)
173 }
174
175 pub fn set_heading_tag(&self, tag: HeadingTagType) {
177 if is_heading_node(self) {
178 with_writable(self.get_key(), |n| {
179 n.downcast_mut::<HeadingNode>().expect("a heading").tag = tag;
180 });
181 }
182 }
183
184 pub fn set_quote_is_shadow_root(&self, is_shadow_root: bool) -> Result<(), LexicalError> {
187 if is_quote_node(self) {
188 set_state(self, "e_shadow_root_state(), is_shadow_root)?;
189 }
190 Ok(())
191 }
192}
193
194fn with_tag(json: Object, tag: Option<HeadingTagType>) -> Object {
197 let mut out = Object::new();
198 for (key, value) in json.iter() {
199 out.insert(key, value.clone());
200 if key == "children"
201 && let Some(tag) = tag
202 {
203 out.insert("tag", tag.as_str().into());
204 }
205 }
206 out
207}
208
209thread_local! {
210 static HEADING_NODE_SCHEMA: NodeSchema = node_schema(vec![(
211 "tag",
212 with_field(
213 enum_value(HEADING_TAGS.map(Value::from).to_vec(), None).expect("the heading tags"),
214 |n: &HeadingNode| &n.tag,
215 |n: &mut HeadingNode| &mut n.tag,
216 )
217 .expect("a field"),
218 )])
219 .expect("HeadingNode's schema");
220}
221
222const HEADING_TAGS: [&str; 6] = ["h1", "h2", "h3", "h4", "h5", "h6"];
224
225pub fn heading_node_schema() -> NodeSchema {
227 HEADING_NODE_SCHEMA.with(Clone::clone)
228}
229
230impl SchemaValue for HeadingTagType {
231 fn to_schema_value(&self) -> Value {
232 self.as_str().into()
233 }
234 fn from_schema_value(value: &Value) -> Option<Self> {
235 value.as_str().and_then(HeadingTagType::parse)
236 }
237}
238
239impl LexicalNode for HeadingNode {
240 fn json_schema_chain(&self) -> Vec<NodeSchema> {
241 vec![
242 heading_node_schema(),
243 crate::nodes::element::element_node_schema(),
244 ]
245 }
246 fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
248 crate::structure::inline_holder_chain(self.get_type())
249 }
250
251 fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
254 prev_node
255 .downcast_ref::<HeadingNode>()
256 .is_some_and(|prev| prev.tag != self.tag)
257 }
258 fn get_type(&self) -> &'static str {
259 "heading"
260 }
261 #[cfg(feature = "html")]
264 fn create_dom(
265 &self,
266 _this: &NodeRef,
267 config: &crate::EditorConfig,
268 _editor: &Editor,
269 ) -> Result<crate::dom::DomNode, LexicalError> {
270 let tag = self.tag.as_str();
271 let element = crate::lexical_dom::get_document().create_element(tag);
272 if let Some(Value::Object(class_names)) = config.theme.get("heading") {
273 crate::lexical_dom::add_theme_class_names(&element, class_names, tag);
274 }
275 Ok(element)
276 }
277 #[cfg(feature = "html")]
278 fn export_dom(
279 &self,
280 this: &NodeRef,
281 editor: &Editor,
282 ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
283 rich_text_dom::export_block_dom(self, this, editor)
284 }
285 #[cfg(feature = "html")]
288 fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
289 Some(rich_text_dom::heading_import_dom())
290 }
291 fn extract_with_child(
294 &self,
295 _: &NodeRef,
296 _: &NodeRef,
297 _: Option<&SelectionRef>,
298 _: &str,
299 ) -> Result<bool, LexicalError> {
300 Ok(true)
301 }
302 fn base(&self) -> &NodeBase {
303 &self.base
304 }
305 fn base_mut(&mut self) -> &mut NodeBase {
306 &mut self.base
307 }
308 fn element(&self) -> Option<&ElementData> {
309 Some(&self.element)
310 }
311 fn element_mut(&mut self) -> Option<&mut ElementData> {
312 Some(&mut self.element)
313 }
314
315 fn generated_export_json(&self, compact: bool) -> Option<Object> {
319 Some(if compact {
320 let tag = Some(self.tag).filter(|t| *t != HeadingTagType::H1);
321 with_tag(export_compact_element_node(self), tag)
322 } else {
323 with_tag(export_element_node(self), Some(self.tag))
324 })
325 }
326
327 fn generated_update_from_json(&mut self, json: &Object) -> bool {
329 update_element_node(&mut self.element, json);
330 self.tag = json
331 .get("tag")
332 .and_then(Value::as_str)
333 .and_then(HeadingTagType::parse)
334 .unwrap_or_default();
335 true
336 }
337
338 fn insert_new_after(
343 &self,
344 this: &NodeRef,
345 selection: &SelectionRef,
346 restore_selection: bool,
347 ) -> Result<Option<NodeRef>, LexicalError> {
348 let anchor = selection.with_range(|r| r.anchor.clone());
349 let last_desc = this.get_last_descendant();
350 let is_at_end = match &anchor {
351 _ if last_desc.is_none() => true,
352 Some(anchor) => is_at_end_of_node(anchor, this)?,
353 None => false,
354 };
355 let is_at_start = match &anchor {
356 Some(anchor) => is_at_start_of_node(anchor, this)?,
357 None => false,
358 };
359 let new_element = if is_at_end || anchor.is_none() {
360 create_paragraph_node()
361 } else {
362 let heading = create_heading_node(self.tag);
365 heading.set_element_format(self.element.get_format_type());
366 heading.set_element_style(self.element.get_style());
367 heading
368 };
369 new_element.set_direction(self.element.get_direction());
370 this.insert_after(&new_element, restore_selection)?;
371 if is_at_start && !this.is_empty() {
372 let paragraph = create_paragraph_node();
373 paragraph.select(None, None)?;
374 this.replace(¶graph, true)?;
375 }
376 Ok(Some(new_element))
377 }
378
379 fn collapse_at_start(&self, this: &NodeRef, _: &SelectionRef) -> Result<bool, LexicalError> {
382 if this.is_empty() {
383 let paragraph = create_paragraph_node();
384 paragraph.append(&this.get_children())?;
385 this.replace(¶graph, false)?;
386 }
387 Ok(true)
388 }
389}
390
391#[derive(Clone, Debug, Default)]
395pub struct QuoteNode {
396 base: NodeBase,
397 element: ElementData,
398}
399
400thread_local! {
401 static QUOTE_SHADOW_ROOT_STATE: StateConfig<bool> =
402 create_state("shadowRoot", |v| v.as_bool().unwrap_or(false));
404}
405
406pub fn quote_shadow_root_state() -> StateConfig<bool> {
410 QUOTE_SHADOW_ROOT_STATE.with(Clone::clone)
411}
412
413pub fn create_quote_node(shadow_root: bool) -> NodeRef {
415 let node = crate::lexical_utils::replaced(set_node_key(Box::new(QuoteNode::default())));
416 if shadow_root {
417 set_state(&node, "e_shadow_root_state(), true)
418 .expect("a new quote has no other shadowRoot state");
419 }
420 node
421}
422
423pub fn is_quote_node(node: &NodeRef) -> bool {
425 node.get_latest().is::<QuoteNode>()
426}
427
428impl LexicalNode for QuoteNode {
429 fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
431 crate::structure::inline_holder_chain(self.get_type())
432 }
433
434 fn get_type(&self) -> &'static str {
435 "quote"
436 }
437 #[cfg(feature = "html")]
440 fn create_dom(
441 &self,
442 _this: &NodeRef,
443 config: &crate::EditorConfig,
444 _editor: &Editor,
445 ) -> Result<crate::dom::DomNode, LexicalError> {
446 let element = crate::lexical_dom::get_document().create_element("blockquote");
447 crate::lexical_dom::add_theme_class_names(&element, &config.theme, "quote");
448 Ok(element)
449 }
450 #[cfg(feature = "html")]
451 fn export_dom(
452 &self,
453 this: &NodeRef,
454 editor: &Editor,
455 ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
456 rich_text_dom::export_block_dom(self, this, editor)
457 }
458 #[cfg(feature = "html")]
460 fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
461 Some(vec![(
462 "blockquote".to_owned(),
463 crate::lexical_dom::importer(0, rich_text_dom::convert_blockquote_element),
464 )])
465 }
466 fn base(&self) -> &NodeBase {
467 &self.base
468 }
469 fn base_mut(&mut self) -> &mut NodeBase {
470 &mut self.base
471 }
472 fn element(&self) -> Option<&ElementData> {
473 Some(&self.element)
474 }
475 fn element_mut(&mut self) -> Option<&mut ElementData> {
476 Some(&mut self.element)
477 }
478
479 fn is_shadow_root(&self) -> bool {
482 get_state_direct(self, "e_shadow_root_state())
483 .expect("QuoteNode declares its shadowRoot state")
484 }
485
486 fn state_configs(&self) -> Vec<RequiredNodeStateConfig> {
489 vec![RequiredNodeStateConfig::new(
490 "e_shadow_root_state(),
491 true,
492 )]
493 }
494
495 fn can_merge_when_empty(&self) -> bool {
497 true
498 }
499
500 fn generated_export_json(&self, compact: bool) -> Option<Object> {
503 Some(if compact {
504 export_compact_element_node(self)
505 } else {
506 export_element_node(self)
507 })
508 }
509
510 fn generated_update_from_json(&mut self, json: &Object) -> bool {
513 update_element_node(&mut self.element, json);
514 true
515 }
516
517 fn insert_new_after(
521 &self,
522 this: &NodeRef,
523 selection: &SelectionRef,
524 restore_selection: bool,
525 ) -> Result<Option<NodeRef>, LexicalError> {
526 let (format, style) = selection
527 .with_range(|r| (r.format, r.style.clone()))
528 .unwrap_or_default();
529 let new_block = create_paragraph_node();
530 new_block.set_text_format(format);
531 new_block.set_text_style(&style);
532 new_block.set_direction(self.element.get_direction());
533 new_block.set_element_format(self.element.get_format_type());
534 new_block.set_element_style(self.element.get_style());
535 this.insert_after(&new_block, restore_selection)?;
536 Ok(Some(new_block))
537 }
538
539 fn collapse_at_start(&self, this: &NodeRef, _: &SelectionRef) -> Result<bool, LexicalError> {
542 if self.is_shadow_root() {
543 for child in this.get_children() {
544 this.insert_before(&child, true)?;
545 }
546 this.remove(false)?;
547 return Ok(true);
548 }
549 let paragraph = create_paragraph_node();
550 for child in this.get_children() {
551 paragraph.append(&[child])?;
552 }
553 this.replace(¶graph, false)?;
554 Ok(true)
555 }
556}
557
558fn on_paste_for_rich_text(event: &PasteCommandType, editor: &Editor) -> Result<(), LexicalError> {
561 event.event().prevent_default();
562 let target = editor.clone();
563 let clipboard_data = match event {
564 PasteCommandType::Clipboard(event) => event.clipboard_data.clone(),
565 PasteCommandType::Input(_) | PasteCommandType::Keyboard(_) => None,
566 };
567 editor.update(
568 move || {
569 let selection = get_selection();
570 if let (Some(clipboard_data), Some(selection)) = (clipboard_data, selection) {
571 insert_data_transfer_for_rich_text(&clipboard_data, &selection, &target)?;
572 }
573 Ok(())
574 },
575 UpdateOptions {
576 tags: vec![PASTE_TAG.to_owned()],
578 ..UpdateOptions::default()
579 },
580 )
581}
582
583fn on_cut_for_rich_text(
588 event: Option<&ClipboardOrKeyboardEvent>,
589 editor: &Editor,
590) -> Result<(), LexicalError> {
591 let cut = || vec![CUT_TAG.to_owned()];
592 editor.update(
593 || {
594 if let Some(selection) = range_selection()
595 && !selection.range().is_some_and(|r| r.is_collapsed())
596 {
597 crate::selection_deletion::internal_expand_selection_to_whole_document(&selection)?;
598 }
599 Ok(())
600 },
601 UpdateOptions {
602 discrete: true,
603 tags: cut(),
604 ..UpdateOptions::default()
605 },
606 )?;
607 copy_to_clipboard(
608 editor,
609 ClipboardOrKeyboardEvent::clipboard_event(event).cloned(),
610 )?;
611 editor.update(
612 || {
613 match get_selection() {
614 Some(selection) if selection.is_range() => selection.remove_text()?,
615 Some(selection) => {
616 for node in selection.get_nodes()? {
617 node.remove(false)?;
618 }
619 }
620 None => {}
621 }
622 Ok(())
623 },
624 UpdateOptions {
625 tags: cut(),
627 ..UpdateOptions::default()
628 },
629 )
630}
631
632pub const DRAG_DROP_PASTE: LexicalCommand<Vec<DataTransferFile>> =
636 LexicalCommand::constant(u64::MAX - 58, "DRAG_DROP_PASTE_FILE");
637
638#[derive(Clone, Copy, Debug, PartialEq, Eq)]
640pub enum EscapeFormatTrigger {
641 Enter,
642 Click,
643 Arrow,
644 Space,
645 Tab,
646}
647
648#[derive(Clone, Debug, Default, PartialEq, Eq)]
653pub struct TriggerConfig {
654 pub enter: Option<bool>,
655 pub click: Option<bool>,
656 pub arrow: Option<bool>,
657 pub space: Option<bool>,
658 pub tab: Option<bool>,
659 pub only_at_boundary: Option<bool>,
660}
661
662impl TriggerConfig {
663 pub fn get(&self, trigger: EscapeFormatTrigger) -> Option<bool> {
665 match trigger {
666 EscapeFormatTrigger::Enter => self.enter,
667 EscapeFormatTrigger::Click => self.click,
668 EscapeFormatTrigger::Arrow => self.arrow,
669 EscapeFormatTrigger::Space => self.space,
670 EscapeFormatTrigger::Tab => self.tab,
671 }
672 }
673
674 pub fn merged(&self, override_: &TriggerConfig) -> TriggerConfig {
677 TriggerConfig {
678 enter: override_.enter.or(self.enter),
679 click: override_.click.or(self.click),
680 arrow: override_.arrow.or(self.arrow),
681 space: override_.space.or(self.space),
682 tab: override_.tab.or(self.tab),
683 only_at_boundary: override_.only_at_boundary.or(self.only_at_boundary),
684 }
685 }
686}
687
688pub type EscapeFormatTriggerConfig = Vec<(String, Option<TriggerConfig>)>;
692
693pub fn default_escape_format_triggers() -> EscapeFormatTriggerConfig {
696 ["capitalize", "lowercase", "uppercase"]
697 .into_iter()
698 .map(|format| {
699 (
700 format.to_owned(),
701 Some(TriggerConfig {
702 enter: Some(true),
703 space: Some(true),
704 tab: Some(true),
705 ..TriggerConfig::default()
706 }),
707 )
708 })
709 .collect()
710}
711
712#[derive(Clone)]
717pub struct ShouldHandlePasteAsFiles(pub Rc<ShouldHandlePasteAsFilesFn>);
718
719pub type ShouldHandlePasteAsFilesFn = dyn Fn(&[DataTransferFile], bool) -> bool;
721
722impl PartialEq for ShouldHandlePasteAsFiles {
723 fn eq(&self, other: &Self) -> bool {
724 Rc::ptr_eq(&self.0, &other.0)
725 }
726}
727
728impl Default for ShouldHandlePasteAsFiles {
729 fn default() -> Self {
731 ShouldHandlePasteAsFiles(Rc::new(default_should_handle_paste_as_files))
732 }
733}
734
735pub fn default_should_handle_paste_as_files(
738 files: &[DataTransferFile],
739 has_text_content: bool,
740) -> bool {
741 !files.is_empty() && !has_text_content
742}
743
744#[derive(Clone, PartialEq)]
747pub struct RichTextConfig {
748 pub escape_format_triggers: EscapeFormatTriggerConfig,
751 pub should_handle_paste_as_files: ShouldHandlePasteAsFiles,
754}
755
756impl Default for RichTextConfig {
757 fn default() -> Self {
759 RichTextConfig {
760 escape_format_triggers: default_escape_format_triggers(),
761 should_handle_paste_as_files: ShouldHandlePasteAsFiles::default(),
762 }
763 }
764}
765
766#[derive(Clone, Copy, PartialEq, Eq)]
768enum EscapeDirection {
769 Start,
770 End,
771 Both,
772}
773
774fn escape_formats_for_trigger(
780 selection: &SelectionRef,
781 trigger: EscapeFormatTrigger,
782 direction: EscapeDirection,
783 config: &EscapeFormatTriggerConfig,
784) -> Result<(), LexicalError> {
785 let Some(range) = selection.range() else {
786 return Ok(());
787 };
788 let mut is_boundary = false;
789 let mut anchor_node = None;
790 if range.is_collapsed() && range.anchor.point_type == PointType::Text {
791 let node = range.anchor.get_node()?;
792 if node.is_text() {
793 let offset = range.anchor.offset;
794 let at_end =
795 offset == node.get_text_content_size() && node.get_next_sibling().is_none();
796 let at_start = offset == 0 && node.get_previous_sibling().is_none();
797 is_boundary = match direction {
798 EscapeDirection::End => at_end,
799 EscapeDirection::Start => at_start,
800 EscapeDirection::Both => at_end || at_start,
801 };
802 anchor_node = Some(node);
803 }
804 }
805 let mut did_escape_boundary = false;
806 for (format, triggers) in config {
807 let Some(triggers) = triggers else {
808 continue;
809 };
810 if triggers.get(trigger) != Some(true) {
811 continue;
812 }
813 if triggers.only_at_boundary == Some(true) {
814 if !is_boundary || !anchor_node.as_ref().is_some_and(|n| n.has_format(format)) {
815 continue;
816 }
817 did_escape_boundary = true;
818 }
819 if selection.has_format(format) {
820 selection.toggle_format(format);
821 }
822 }
823 if did_escape_boundary {
824 selection.set_style("");
825 }
826 Ok(())
827}
828
829fn is_selection_at_end_of_root(selection: &RangeSelection) -> bool {
831 selection.focus.key == "root" && selection.focus.offset == get_root().get_children_size()
832}
833
834fn is_selection_at_start_of_root(selection: &RangeSelection) -> bool {
836 selection.focus.key == "root" && selection.focus.offset == 0
837}
838
839fn is_block_cursor_at_root_edge(selection: &RangeSelection, direction: CaretDirection) -> bool {
843 if !selection.is_collapsed() {
844 return false;
845 }
846 let is_next = direction == CaretDirection::Next;
847 if !(if is_next {
848 is_selection_at_end_of_root(selection)
849 } else {
850 is_selection_at_start_of_root(selection)
851 }) {
852 return false;
853 }
854 let offset = selection.focus.offset;
855 let child = if is_next {
856 offset
857 .checked_sub(1)
858 .and_then(|index| get_root().get_child_at_index(index))
859 } else {
860 get_root().get_child_at_index(offset)
861 };
862 child.is_some_and(|child| needs_block_cursor_beside(&child))
863}
864
865fn is_selection_collapsed_at_front_of_indented_block(
868 selection: &RangeSelection,
869) -> Result<bool, LexicalError> {
870 if !selection.is_collapsed() || selection.anchor.offset != 0 {
871 return Ok(false);
872 }
873 let anchor_node = selection.anchor.get_node()?;
874 if anchor_node.is_root() {
875 return Ok(false);
876 }
877 let element = get_nearest_block_element_ancestor_or_throw(&anchor_node)?;
878 Ok(element.get_indent()? > 0.0
879 && (element == anchor_node
880 || element.get_first_descendant().as_ref() == Some(&anchor_node)))
881}
882
883fn try_enter_from_block_cursor(
886 selection: &RangeSelection,
887 direction: CaretDirection,
888) -> Result<bool, LexicalError> {
889 if !selection.is_collapsed() || selection.anchor.point_type != PointType::Element {
890 return Ok(false);
891 }
892 let caret = caret_from_point(&selection.anchor, direction)?;
893 if let Some(child) = caret.get_node_at_caret()
894 && is_shadow_root_node(&child)
895 && !child.is_inline()
896 && let Some(child_caret) = get_child_caret(&child, direction)
897 {
898 set_selection_from_caret_range(&get_collapsed_caret_range(normalize_caret(&child_caret)))?;
899 return Ok(true);
900 }
901 Ok(false)
902}
903
904fn try_block_cursor_shadow_root_navigation(
906 selection: &RangeSelection,
907 direction: CaretDirection,
908) -> Result<bool, LexicalError> {
909 Ok(try_exit_shadow_root_to_block_cursor(selection, direction)?
910 || try_enter_from_block_cursor(selection, direction)?)
911}
912
913fn try_exit_shadow_root_to_block_cursor(
917 selection: &RangeSelection,
918 direction: CaretDirection,
919) -> Result<bool, LexicalError> {
920 if !selection.is_collapsed() {
921 return Ok(false);
922 }
923 let focus_caret = caret_from_point(&selection.focus, direction)?;
924 let Some(shadow_root) = find_matching_parent(focus_caret.origin(), is_shadow_root_node) else {
927 return Ok(false);
928 };
929 let focus_node = selection.focus.get_node()?;
932 if shadow_root != focus_node && !has_ancestor(&focus_node, &shadow_root) {
933 return Ok(false);
934 }
935 let text_range = get_caret_range(focus_caret, get_sibling_caret(&shadow_root, direction))?;
937 if text_range.get_text_slices().iter().any(|slice| {
938 slice
939 .as_ref()
940 .is_some_and(|s| s.get_text_content_size() > 0)
941 }) {
942 return Ok(false);
943 }
944 let range = get_caret_range(
946 text_range.anchor.get_sibling_caret(),
947 text_range.focus.clone(),
948 )?;
949 let mut prev_origin = range.anchor.origin().clone();
952 for caret in range.iter() {
953 if !(caret.is_sibling_caret() && Some(caret.origin()) == prev_origin.get_parent().as_ref())
954 {
955 return Ok(false);
956 }
957 prev_origin = caret.origin().clone();
958 }
959 let mut prev_shadow = shadow_root.clone();
962 for caret in extend_caret_to_range(&get_sibling_caret(&shadow_root, direction))?.iter() {
963 if Some(caret.origin()) == prev_shadow.get_parent().as_ref() {
967 if !is_shadow_root_node(caret.origin()) {
968 break;
969 }
970 prev_shadow = caret.origin().clone();
971 continue;
972 }
973 if needs_block_cursor_beside(caret.origin()) {
974 let sr = get_sibling_caret(&prev_shadow, direction);
975 set_selection_from_caret_range(&get_caret_range(sr.clone(), sr)?)?;
976 return Ok(true);
977 }
978 break;
979 }
980 Ok(false)
981}
982
983fn is_selectable_block_decorator(node: &NodeRef) -> bool {
985 node.is_decorator() && !node.is_inline() && !node.is_isolated() && node.is_keyboard_selectable()
986}
987
988fn select_node(key: &str) {
990 let node_selection = create_node_selection();
991 node_selection.add(key);
992 set_selection(Some(node_selection));
993}
994
995fn try_decorator_line_navigation(
1002 selection: &RangeSelection,
1003 is_backward: bool,
1004 editor: &Editor,
1005) -> Result<bool, LexicalError> {
1006 if !selection.is_collapsed() {
1007 return Ok(false);
1008 }
1009 let focus = &selection.focus;
1010 let focus_node = focus.get_node()?;
1011 let direction = if is_backward {
1012 CaretDirection::Previous
1013 } else {
1014 CaretDirection::Next
1015 };
1016 let focus_caret = caret_from_point(focus, direction)?;
1017 if focus.point_type == PointType::Element
1018 && focus_node.is_element()
1019 && is_root_or_shadow_root(&focus_node)
1020 {
1021 if let Some(adjacent_child) = focus_caret.get_node_at_caret()
1022 && is_selectable_block_decorator(&adjacent_child)
1023 {
1024 select_node(adjacent_child.get_key());
1025 return Ok(true);
1026 }
1027 return Ok(false);
1028 }
1029 let start = if focus_node.is_element() {
1030 focus_node.clone()
1031 } else {
1032 focus_node.get_parent_or_throw()?
1033 };
1034 let Some(top_block) = find_matching_parent(&start, |n| {
1035 n.is_element()
1036 && !n.is_inline()
1037 && n.get_parent().is_some_and(|p| is_root_or_shadow_root(&p))
1038 }) else {
1039 return Ok(false);
1040 };
1041 let Some(adjacent_sibling) = get_sibling_caret(&top_block, direction)
1042 .get_node_at_caret()
1043 .filter(is_selectable_block_decorator)
1044 else {
1045 return Ok(false);
1046 };
1047 if top_block.get_text_content_size() == 0 {
1049 select_node(adjacent_sibling.get_key());
1050 return Ok(true);
1051 }
1052 let Some(movement) = editor
1053 .selection_movement()
1054 .filter(|movement| movement.has_dom_selection())
1055 else {
1056 return Ok(false);
1057 };
1058 let Some(landed) = movement.landed_point(focus, is_backward, SelectionGranularity::Line)?
1059 else {
1060 return Ok(false);
1061 };
1062 let Some(moved_node) = get_node_by_key(&landed.key) else {
1063 return Ok(false);
1064 };
1065 if landed.key == focus.key && landed.offset == focus.offset {
1067 select_node(adjacent_sibling.get_key());
1068 return Ok(true);
1069 }
1070 if moved_node == top_block || has_ancestor(&moved_node, &top_block) {
1071 return Ok(false);
1072 }
1073 select_node(adjacent_sibling.get_key());
1074 Ok(true)
1075}
1076
1077fn exit_node_selection_toward(
1081 node: &NodeRef,
1082 direction: CaretDirection,
1083) -> Result<(), LexicalError> {
1084 let caret = get_sibling_caret(node, direction);
1085 if let Some(sibling) = caret.get_adjacent_caret()
1086 && sibling.origin().is_element()
1087 && !sibling.origin().is_inline()
1088 && sibling.origin().get_latest().is_shadow_root()
1089 {
1090 set_selection_from_caret_range(&get_collapsed_caret_range(caret))?;
1091 } else if direction == CaretDirection::Next {
1092 node.select_next(Some(0), Some(0))?;
1093 } else {
1094 node.select_previous(None, None)?;
1095 }
1096 Ok(())
1097}
1098
1099fn sorted_sibling_carets(nodes: Vec<NodeRef>) -> Result<Vec<PointCaret>, LexicalError> {
1102 let mut carets: Vec<PointCaret> = nodes
1103 .iter()
1104 .map(|node| get_sibling_caret(node, CaretDirection::Next))
1105 .collect();
1106 let mut error = None;
1107 carets.sort_by(|a, b| match compare_point_caret_next(a, b) {
1108 Ok(ordering) => ordering,
1109 Err(e) => {
1110 error.get_or_insert(e);
1111 std::cmp::Ordering::Equal
1112 }
1113 });
1114 match error {
1115 Some(error) => Err(error),
1116 None => Ok(carets),
1117 }
1118}
1119
1120fn convert_contiguous_node_selection(
1124 selection: &SelectionRef,
1125 direction: CaretDirection,
1126) -> Result<bool, LexicalError> {
1127 let carets = sorted_sibling_carets(selection.get_nodes()?)?;
1128 let (Some(first_caret), Some(last_caret)) = (carets.first(), carets.last()) else {
1129 return Ok(false);
1130 };
1131 for pair in carets.windows(2) {
1132 if pair[0].get_node_at_caret().as_ref() != Some(pair[1].origin()) {
1133 return Ok(false);
1134 }
1135 }
1136 set_selection_from_caret_range(&get_caret_range_in_direction(
1137 &get_caret_range(rewind_sibling_caret(first_caret)?, last_caret.clone())?,
1138 direction,
1139 )?)?;
1140 crate::updates::flush_sync_after_update();
1143 Ok(true)
1144}
1145
1146fn promote_node_selection_to_block_edge(
1151 selection: &SelectionRef,
1152 is_backward: bool,
1153 event: &KeyboardEvent,
1154) -> Result<bool, LexicalError> {
1155 event.prevent_default();
1156 event.stop_propagation();
1157 let nodes = selection.get_nodes()?;
1158 if nodes.is_empty() {
1159 return Ok(true);
1160 }
1161 let sorted = sorted_sibling_carets(nodes)?;
1162 let target = if is_backward {
1163 sorted.first()
1164 } else {
1165 sorted.last()
1166 }
1167 .expect("not empty")
1168 .origin()
1169 .clone();
1170 let block = find_matching_parent(&target, |n| {
1171 n != &target && n.is_element() && !n.is_inline()
1172 })
1173 .unwrap_or_else(get_root);
1174 let offset = if is_backward {
1175 0
1176 } else {
1177 block.get_children_size()
1178 };
1179 block.select(Some(offset), Some(offset))?;
1180 Ok(true)
1181}
1182
1183fn nearest_block(node: &NodeRef) -> Option<NodeRef> {
1185 find_matching_parent(node, |n| n.is_element() && !n.is_inline())
1186}
1187
1188fn arrow_node_selection(
1193 event: &KeyboardEvent,
1194 direction: impl Fn(&NodeRef) -> CaretDirection,
1195) -> Result<(bool, Option<SelectionRef>), LexicalError> {
1196 let mut selection = get_selection();
1197 if let Some(node_selection) = selection.clone().filter(SelectionRef::is_node) {
1198 let nodes = node_selection.get_nodes()?;
1200 if let Some(first) = nodes.first() {
1201 let direction = direction(first);
1202 if event.shift_key && convert_contiguous_node_selection(&node_selection, direction)? {
1203 selection = get_selection();
1205 } else {
1206 event.prevent_default();
1207 exit_node_selection_toward(first, direction)?;
1208 return Ok((true, selection));
1209 }
1210 }
1211 }
1212 Ok((false, selection))
1213}
1214
1215fn range_selection() -> Option<SelectionRef> {
1217 get_selection().filter(SelectionRef::is_range)
1218}
1219
1220#[cfg(feature = "html")]
1222mod rich_text_dom {
1223 use super::{HeadingTagType, create_heading_node, create_quote_node};
1224 use crate::dom::DomNode;
1225 use crate::lexical_dom::{
1226 DomConversion, DomConversionMap, DomConversionOutput, DomExportOutput, get_document,
1227 importer, set_direction_from_dom, set_format_from_dom, set_node_indent_from_dom,
1228 };
1229 use crate::node::{LexicalNode, NodeRef};
1230 use crate::{Editor, LexicalError};
1231 use std::rc::Rc;
1232
1233 pub(super) fn export_block_dom(
1237 node: &dyn LexicalNode,
1238 this: &NodeRef,
1239 editor: &Editor,
1240 ) -> Result<DomExportOutput, LexicalError> {
1241 let output = crate::nodes::element::export_dom(node, this, editor)?;
1242 if let Some(element) = output.element.as_ref().filter(|e| e.is_element()) {
1243 if this.is_empty() {
1244 element.append_child(&get_document().create_element("br"));
1245 }
1246 let data = node.element().expect("an element");
1247 let format_type = data.get_format_type();
1248 if !format_type.is_empty() {
1249 element.style().set_property("text-align", format_type, "");
1250 }
1251 if let Some(direction) = data.get_direction() {
1252 element.set_dir(direction.as_str());
1253 }
1254 }
1255 Ok(DomExportOutput {
1256 element: output.element,
1257 ..DomExportOutput::default()
1258 })
1259 }
1260
1261 fn is_google_docs_title(dom_node: &DomNode) -> bool {
1263 dom_node.node_name().eq_ignore_ascii_case("span")
1264 && dom_node.style().get_property_value("font-size") == "26pt"
1265 }
1266
1267 pub(super) fn heading_import_dom() -> DomConversionMap {
1268 let mut map: DomConversionMap = ["h1", "h2", "h3", "h4", "h5", "h6"]
1269 .into_iter()
1270 .map(|tag| (tag.to_owned(), importer(0, convert_heading_element)))
1271 .collect();
1272 map.push((
1273 "p".to_owned(),
1274 Rc::new(|node: &DomNode| {
1275 let first_child = node.first_child()?;
1276 is_google_docs_title(&first_child).then(|| DomConversion {
1277 conversion: Rc::new(|_| Ok(Some(DomConversionOutput::node(None)))),
1278 priority: 3,
1279 })
1280 }),
1281 ));
1282 map.push((
1283 "span".to_owned(),
1284 Rc::new(|node: &DomNode| {
1285 is_google_docs_title(node).then(|| DomConversion {
1286 conversion: Rc::new(|_| {
1287 Ok(Some(DomConversionOutput::node(Some(create_heading_node(
1288 HeadingTagType::H1,
1289 )))))
1290 }),
1291 priority: 3,
1292 })
1293 }),
1294 ));
1295 map
1296 }
1297
1298 fn convert_heading_element(
1300 element: &DomNode,
1301 ) -> Result<Option<DomConversionOutput>, LexicalError> {
1302 let node = match HeadingTagType::parse(&element.node_name().to_lowercase()) {
1303 Some(tag) => {
1304 let node = create_heading_node(tag);
1305 set_node_indent_from_dom(element, &node)?;
1306 set_format_from_dom(&node, element);
1307 set_direction_from_dom(&node, element);
1308 Some(node)
1309 }
1310 None => None,
1311 };
1312 Ok(Some(DomConversionOutput::node(node)))
1313 }
1314
1315 pub(super) fn convert_blockquote_element(
1317 element: &DomNode,
1318 ) -> Result<Option<DomConversionOutput>, LexicalError> {
1319 let node = create_quote_node(false);
1320 set_format_from_dom(&node, element);
1321 set_node_indent_from_dom(element, &node)?;
1322 set_direction_from_dom(&node, element);
1323 Ok(Some(DomConversionOutput::node(Some(node))))
1324 }
1325}
1326
1327fn horizontal_arrow(
1329 event: &KeyboardEvent,
1330 is_left: bool,
1331 triggers: &EscapeFormatTriggerConfig,
1332) -> Result<bool, LexicalError> {
1333 let backward_unless_rtl = |node: &NodeRef| {
1335 if is_parent_rtl(node) == is_left {
1336 CaretDirection::Next
1337 } else {
1338 CaretDirection::Previous
1339 }
1340 };
1341 let (handled, selection) = arrow_node_selection(event, backward_unless_rtl)?;
1342 if handled {
1343 return Ok(true);
1344 }
1345 let Some(selection) = selection.filter(SelectionRef::is_range) else {
1346 return Ok(false);
1347 };
1348 let range = selection.range().expect("a range selection");
1349 let direction = backward_unless_rtl(&range.anchor.get_node()?);
1350 if is_block_cursor_at_root_edge(&range, direction) {
1351 event.prevent_default();
1352 return Ok(true);
1353 }
1354 if !event.shift_key && try_block_cursor_shadow_root_navigation(&range, direction)? {
1355 event.prevent_default();
1356 return Ok(true);
1357 }
1358 if !event.shift_key {
1359 escape_formats_for_trigger(
1360 &selection,
1361 EscapeFormatTrigger::Arrow,
1362 if is_left {
1363 EscapeDirection::Start
1364 } else {
1365 EscapeDirection::End
1366 },
1367 triggers,
1368 )?;
1369 }
1370 let range = selection.range().expect("a range selection");
1371 if should_override_default_character_selection(&range, is_left)? {
1372 event.prevent_default();
1373 move_character(&selection, event.shift_key, is_left)?;
1374 return Ok(true);
1375 }
1376 Ok(false)
1377}
1378
1379pub fn register_rich_text(editor: &Editor) -> Unregister {
1423 register_rich_text_with_config(editor, RichTextConfig::default())
1424}
1425
1426pub fn register_rich_text_with_config(editor: &Editor, config: RichTextConfig) -> Unregister {
1430 let config = Rc::new(config);
1431 let triggers = config.clone();
1432 register_rich_text_with(
1433 editor,
1434 Rc::new(move || triggers.escape_format_triggers.clone()),
1435 Rc::new(move || config.should_handle_paste_as_files.clone()),
1436 )
1437}
1438
1439pub(crate) fn register_rich_text_with(
1443 editor: &Editor,
1444 escape_format_triggers: Rc<dyn Fn() -> EscapeFormatTriggerConfig>,
1445 should_handle_paste_as_files: Rc<dyn Fn() -> ShouldHandlePasteAsFiles>,
1446) -> Unregister {
1447 let triggers = escape_format_triggers;
1448 let unregisters: Vec<Unregister> = vec![
1449 {
1450 let triggers = triggers.clone();
1451 editor.register_command(
1452 &CLICK_COMMAND,
1453 move |event, _| match get_selection() {
1454 Some(selection) if selection.is_node() => {
1455 if let Some(target) = event.target_key.as_deref().and_then(get_node_by_key)
1459 {
1460 for node in selection.get_nodes()? {
1461 if node == target || has_ancestor(&target, &node) {
1462 return Ok(false);
1463 }
1464 }
1465 }
1466 selection.clear();
1467 Ok(true)
1468 }
1469 Some(selection) => {
1470 escape_formats_for_trigger(
1471 &selection,
1472 EscapeFormatTrigger::Click,
1473 EscapeDirection::Both,
1474 &triggers(),
1475 )?;
1476 Ok(false)
1477 }
1478 None => Ok(false),
1479 },
1480 COMMAND_PRIORITY_EDITOR,
1481 )
1482 },
1483 editor.register_command(
1484 &DELETE_CHARACTER_COMMAND,
1485 |&is_backward, _| match get_selection() {
1486 Some(selection) if selection.is_range() => {
1487 selection.delete_character(is_backward)?;
1488 Ok(true)
1489 }
1490 Some(selection) if selection.is_node() => {
1491 selection.delete_nodes()?;
1492 Ok(true)
1493 }
1494 _ => Ok(false),
1495 },
1496 COMMAND_PRIORITY_EDITOR,
1497 ),
1498 editor.register_command(
1499 &DELETE_WORD_COMMAND,
1500 |&is_backward, _| {
1501 let Some(selection) = range_selection() else {
1502 return Ok(false);
1503 };
1504 selection.delete_word(is_backward)?;
1505 Ok(true)
1506 },
1507 COMMAND_PRIORITY_EDITOR,
1508 ),
1509 editor.register_command(
1510 &DELETE_LINE_COMMAND,
1511 |&is_backward, _| {
1512 let Some(selection) = range_selection() else {
1513 return Ok(false);
1514 };
1515 selection.delete_line(is_backward)?;
1516 Ok(true)
1517 },
1518 COMMAND_PRIORITY_EDITOR,
1519 ),
1520 editor.register_command(
1521 &CONTROLLED_TEXT_INSERTION_COMMAND,
1522 |text, _| {
1523 if let Some(selection) = get_selection() {
1524 selection.insert_text(text)?;
1525 }
1526 Ok(true)
1527 },
1528 COMMAND_PRIORITY_EDITOR,
1529 ),
1530 editor.register_command(
1531 &REMOVE_TEXT_COMMAND,
1532 |_, _| {
1533 let Some(selection) = range_selection() else {
1534 return Ok(false);
1535 };
1536 selection.remove_text()?;
1537 Ok(true)
1538 },
1539 COMMAND_PRIORITY_EDITOR,
1540 ),
1541 editor.register_command(
1542 &FORMAT_TEXT_COMMAND,
1543 |format, _| {
1544 let Some(selection) = get_selection() else {
1545 return Ok(false);
1546 };
1547 selection.format_text(format, None)?;
1548 Ok(true)
1549 },
1550 COMMAND_PRIORITY_EDITOR,
1551 ),
1552 editor.register_command(
1553 &SET_TEXT_FORMAT_COMMAND,
1554 |formats, _| {
1555 let Some(selection) = get_selection() else {
1556 return Ok(false);
1557 };
1558 let formats: Vec<(&str, bool)> = formats
1559 .iter()
1560 .map(|(name, value)| (name.as_str(), *value))
1561 .collect();
1562 selection.set_text_format(&formats)?;
1563 Ok(true)
1564 },
1565 COMMAND_PRIORITY_EDITOR,
1566 ),
1567 editor.register_command(
1568 &FORMAT_ELEMENT_COMMAND,
1569 |format, _| {
1570 let Some(selection) = get_selection() else {
1571 return Ok(false);
1572 };
1573 for node in selection.get_nodes()? {
1574 let element = find_matching_parent(&node, |parent| {
1575 parent.is_element() && !parent.is_inline()
1576 });
1577 if let Some(element) = element {
1578 element.set_element_format(format);
1579 }
1580 }
1581 Ok(true)
1582 },
1583 COMMAND_PRIORITY_EDITOR,
1584 ),
1585 editor.register_command(
1586 &INSERT_LINE_BREAK_COMMAND,
1587 |&select_start, _| {
1588 let Some(selection) = range_selection() else {
1589 return Ok(false);
1590 };
1591 selection.insert_line_break(select_start)?;
1592 Ok(true)
1593 },
1594 COMMAND_PRIORITY_EDITOR,
1595 ),
1596 editor.register_command(
1597 &INSERT_PARAGRAPH_COMMAND,
1598 |_, _| {
1599 let Some(selection) = range_selection() else {
1600 return Ok(false);
1601 };
1602 selection.insert_paragraph()?;
1603 Ok(true)
1604 },
1605 COMMAND_PRIORITY_EDITOR,
1606 ),
1607 {
1608 let triggers = triggers.clone();
1609 editor.register_command(
1610 &KEY_ENTER_COMMAND,
1611 move |event, editor| {
1612 let mut selection = get_selection();
1613 if let Some(s) = selection.as_ref().filter(|s| s.is_node()) {
1616 let nodes = s.get_nodes()?;
1617 if let [node] = nodes.as_slice()
1618 && node.is_decorator()
1619 && !node.is_inline()
1620 {
1621 selection = Some(node.select_next(None, None)?);
1622 }
1623 }
1624 let Some(selection) = selection.filter(SelectionRef::is_range) else {
1625 return Ok(false);
1626 };
1627 escape_formats_for_trigger(
1628 &selection,
1629 EscapeFormatTrigger::Enter,
1630 EscapeDirection::Both,
1631 &triggers(),
1632 )?;
1633 if let Some(event) = event {
1634 event.prevent_default();
1636 if event.shift_key {
1637 return editor.dispatch_command(&INSERT_LINE_BREAK_COMMAND, false);
1638 }
1639 }
1640 editor.dispatch_command(&INSERT_PARAGRAPH_COMMAND, ())
1641 },
1642 COMMAND_PRIORITY_EDITOR,
1643 )
1644 },
1645 editor.register_command(
1646 &KEY_ESCAPE_COMMAND,
1647 |_, editor| {
1648 if range_selection().is_none() {
1649 return Ok(false);
1650 }
1651 editor.blur();
1652 Ok(true)
1653 },
1654 COMMAND_PRIORITY_EDITOR,
1655 ),
1656 editor.register_command(
1657 &INSERT_TAB_COMMAND,
1658 |_, _| {
1659 let tab_node = create_tab_node();
1660 if let Some(range) = get_selection().and_then(|s| s.range()) {
1661 tab_node.set_format(range.format);
1662 tab_node.set_style(&range.style);
1663 }
1664 insert_nodes(vec![tab_node])?;
1665 Ok(true)
1666 },
1667 COMMAND_PRIORITY_EDITOR,
1668 ),
1669 editor.register_command(
1670 &INDENT_CONTENT_COMMAND,
1671 |_, _| {
1672 handle_indent_and_outdent(|block| {
1673 let indent = block.get_indent()?;
1674 block.set_indent(indent + 1.0)
1675 })
1676 },
1677 COMMAND_PRIORITY_EDITOR,
1678 ),
1679 editor.register_command(
1680 &OUTDENT_CONTENT_COMMAND,
1681 |_, _| {
1682 handle_indent_and_outdent(|block| {
1683 let indent = block.get_indent()?;
1684 if indent > 0.0 {
1685 block.set_indent((indent - 1.0).max(0.0))?;
1686 }
1687 Ok(())
1688 })
1689 },
1690 COMMAND_PRIORITY_EDITOR,
1691 ),
1692 editor.register_command(
1693 &KEY_ARROW_UP_COMMAND,
1694 |event, editor| {
1695 let (handled, selection) =
1696 arrow_node_selection(event, |_| CaretDirection::Previous)?;
1697 if handled {
1698 return Ok(true);
1699 }
1700 if let Some(selection) = selection.as_ref().and_then(SelectionRef::range) {
1701 if is_selection_at_start_of_root(&selection) {
1702 event.prevent_default();
1703 return Ok(true);
1704 }
1705 if !event.shift_key
1706 && try_block_cursor_shadow_root_navigation(
1707 &selection,
1708 CaretDirection::Previous,
1709 )?
1710 {
1711 event.prevent_default();
1712 return Ok(true);
1713 }
1714 if !event.shift_key && try_decorator_line_navigation(&selection, true, editor)?
1715 {
1716 event.prevent_default();
1717 return Ok(true);
1718 }
1719 }
1720 Ok(false)
1721 },
1722 COMMAND_PRIORITY_EDITOR,
1723 ),
1724 editor.register_command(
1725 &KEY_ARROW_DOWN_COMMAND,
1726 |event, editor| {
1727 let (handled, selection) = arrow_node_selection(event, |_| CaretDirection::Next)?;
1728 if handled {
1729 return Ok(true);
1730 }
1731 if let Some(selection) = selection.as_ref().and_then(SelectionRef::range) {
1732 if is_selection_at_end_of_root(&selection) {
1733 event.prevent_default();
1734 return Ok(true);
1735 }
1736 if !event.shift_key
1737 && try_block_cursor_shadow_root_navigation(
1738 &selection,
1739 CaretDirection::Next,
1740 )?
1741 {
1742 event.prevent_default();
1743 return Ok(true);
1744 }
1745 if !event.shift_key && try_decorator_line_navigation(&selection, false, editor)?
1746 {
1747 event.prevent_default();
1748 return Ok(true);
1749 }
1750 }
1751 Ok(false)
1752 },
1753 COMMAND_PRIORITY_EDITOR,
1754 ),
1755 {
1756 let triggers = triggers.clone();
1757 editor.register_command(
1758 &KEY_ARROW_LEFT_COMMAND,
1759 move |event, _| horizontal_arrow(event, true, &triggers()),
1760 COMMAND_PRIORITY_EDITOR,
1761 )
1762 },
1763 {
1764 let triggers = triggers.clone();
1765 editor.register_command(
1766 &KEY_ARROW_RIGHT_COMMAND,
1767 move |event, _| horizontal_arrow(event, false, &triggers()),
1768 COMMAND_PRIORITY_EDITOR,
1769 )
1770 },
1771 editor.register_command(
1772 &KEY_BACKSPACE_COMMAND,
1773 |event, editor| {
1774 match get_selection() {
1779 Some(selection) if selection.is_range() => {
1780 let range = selection.range().expect("a range selection");
1781 if is_selection_collapsed_at_front_of_indented_block(&range)? {
1782 event.prevent_default();
1783 return editor.dispatch_command(&OUTDENT_CONTENT_COMMAND, ());
1784 }
1785 }
1786 Some(_) => {}
1787 None => return Ok(false),
1788 }
1789 event.prevent_default();
1790 editor.dispatch_command(&DELETE_CHARACTER_COMMAND, true)
1791 },
1792 COMMAND_PRIORITY_EDITOR,
1793 ),
1794 editor.register_command(
1795 &KEY_DELETE_COMMAND,
1796 |event, editor| {
1797 if get_selection().is_none() {
1798 return Ok(false);
1799 }
1800 event.prevent_default();
1801 editor.dispatch_command(&DELETE_CHARACTER_COMMAND, false)
1802 },
1803 COMMAND_PRIORITY_EDITOR,
1804 ),
1805 editor.register_command(
1806 &SELECT_ALL_COMMAND,
1807 |_, _| {
1808 match get_selection().filter(SelectionRef::is_range) {
1811 Some(selection)
1812 if crate::slot::get_slot_frame(
1813 &selection
1814 .point(crate::Which::Anchor)
1815 .expect("a range")
1816 .get_node()?,
1817 )
1818 .is_some() =>
1819 {
1820 crate::selection_insert_nodes::select_all_in(&selection)?;
1821 }
1822 _ => {
1823 select_all()?;
1824 }
1825 }
1826 Ok(true)
1827 },
1828 COMMAND_PRIORITY_EDITOR,
1829 ),
1830 editor.register_command(
1831 &DROP_COMMAND,
1832 |event, editor| {
1833 let (_, files, _) = event_files(FilesEvent::Drag(event));
1834 if !files.is_empty() {
1835 if let Some(caret) = caret_from_event(event, editor) {
1836 let selection =
1837 set_selection_from_caret_range(&get_collapsed_caret_range(caret))?;
1838 normalize_selection(&selection)?;
1839 set_selection(Some(selection));
1840 }
1841 editor.dispatch_command(&DRAG_DROP_PASTE, files)?;
1845 event.prevent_default();
1846 return Ok(true);
1847 }
1848 handle_rich_text_drop(event, editor)
1849 },
1850 COMMAND_PRIORITY_EDITOR,
1851 ),
1852 editor.register_command(
1853 &DRAGSTART_COMMAND,
1854 |event, editor| {
1855 let (is_file_transfer, _, _) = event_files(FilesEvent::Drag(event));
1856 let selection = range_selection();
1857 if is_file_transfer && selection.is_none() {
1858 return Ok(false);
1859 }
1860 if let Some(selection) = selection
1861 && !selection.range().is_some_and(|r| r.is_collapsed())
1862 && let Some(data_transfer) = &event.data_transfer
1863 {
1864 set_lexical_clipboard_data_transfer(
1868 data_transfer,
1869 &get_clipboard_data_from_selection(Some(&selection))?,
1870 );
1871 write_drag_source_to_data_transfer(data_transfer, editor);
1872 }
1873 Ok(true)
1874 },
1875 COMMAND_PRIORITY_EDITOR,
1876 ),
1877 editor.register_command(
1878 &DRAGOVER_COMMAND,
1879 |event, editor| {
1880 let (is_file_transfer, _, _) = event_files(FilesEvent::Drag(event));
1881 if is_file_transfer && range_selection().is_none() {
1882 return Ok(false);
1883 }
1884 if caret_from_event(event, editor)
1887 .is_some_and(|caret| caret.origin().is_decorator())
1888 {
1889 event.prevent_default();
1890 }
1891 Ok(true)
1892 },
1893 COMMAND_PRIORITY_EDITOR,
1894 ),
1895 editor.register_command(
1896 ©_COMMAND,
1897 |event, editor| {
1898 copy_to_clipboard(
1899 editor,
1900 ClipboardOrKeyboardEvent::clipboard_event(event.as_ref()).cloned(),
1901 )?;
1902 Ok(true)
1903 },
1904 COMMAND_PRIORITY_EDITOR,
1905 ),
1906 editor.register_command(
1907 &CUT_COMMAND,
1908 |event, editor| {
1909 on_cut_for_rich_text(event.as_ref(), editor)?;
1910 Ok(true)
1911 },
1912 COMMAND_PRIORITY_EDITOR,
1913 ),
1914 editor.register_command(
1915 &PASTE_COMMAND,
1916 move |event, editor| {
1917 let (_, files, has_text_content) = event_files(FilesEvent::Paste(event));
1918 if (should_handle_paste_as_files().0)(&files, has_text_content)
1919 && editor.dispatch_command(&DRAG_DROP_PASTE, files)?
1920 {
1921 return Ok(true);
1922 }
1923 if get_selection().is_some() {
1924 on_paste_for_rich_text(event, editor)?;
1925 return Ok(true);
1926 }
1927 Ok(false)
1928 },
1929 COMMAND_PRIORITY_EDITOR,
1930 ),
1931 {
1932 let triggers = triggers.clone();
1933 editor.register_command(
1934 &KEY_SPACE_COMMAND,
1935 move |_, _| {
1936 if let Some(selection) = range_selection() {
1937 escape_formats_for_trigger(
1938 &selection,
1939 EscapeFormatTrigger::Space,
1940 EscapeDirection::Both,
1941 &triggers(),
1942 )?;
1943 }
1944 Ok(false)
1945 },
1946 COMMAND_PRIORITY_EDITOR,
1947 )
1948 },
1949 editor.register_command(
1950 &KEY_TAB_COMMAND,
1951 move |_, _| {
1952 if let Some(selection) = range_selection() {
1953 escape_formats_for_trigger(
1954 &selection,
1955 EscapeFormatTrigger::Tab,
1956 EscapeDirection::Both,
1957 &triggers(),
1958 )?;
1959 }
1960 Ok(false)
1961 },
1962 COMMAND_PRIORITY_EDITOR,
1963 ),
1964 editor.register_command(
1965 &MOVE_TO_END,
1966 |event, _| {
1967 let selection = get_selection();
1968 if let Some(selection) = selection.as_ref().filter(|s| s.is_node()) {
1969 return promote_node_selection_to_block_edge(selection, false, event);
1970 }
1971 let Some(selection) = selection.filter(SelectionRef::is_range) else {
1972 return Ok(false);
1973 };
1974 let anchor = selection.point(Which::Anchor).expect("a range selection");
1975 if anchor.point_type != PointType::Element || anchor.offset != 0 {
1976 return Ok(false);
1977 }
1978 let element = anchor.get_node()?;
1979 if !element.is_element() {
1980 return Ok(false);
1981 }
1982 if !element
1983 .get_first_child()
1984 .is_some_and(|child| child.is_decorator() && child.is_inline())
1985 {
1986 return Ok(false);
1987 }
1988 let ending = element.select_end()?;
1992 if event.shift_key {
1993 ending.point_set(Which::Anchor, element.get_key(), 0, PointType::Element)?;
1994 }
1995 event.prevent_default();
1996 event.stop_propagation();
1997 Ok(true)
1998 },
1999 COMMAND_PRIORITY_EDITOR,
2000 ),
2001 editor.register_command(
2002 &MOVE_TO_START,
2003 |event, _| {
2004 let selection = get_selection();
2005 if let Some(selection) = selection.as_ref().filter(|s| s.is_node()) {
2006 return promote_node_selection_to_block_edge(selection, true, event);
2007 }
2008 let Some(selection) = selection.filter(SelectionRef::is_range) else {
2009 return Ok(false);
2010 };
2011 let range = selection.range().expect("a range selection");
2012 let (anchor, focus) = (&range.anchor, &range.focus);
2013 let Some(focus_block) = nearest_block(&focus.get_node()?) else {
2014 return Ok(false);
2015 };
2016 if !focus_block
2017 .get_first_child()
2018 .is_some_and(|child| child.is_decorator() && child.is_inline())
2019 {
2020 return Ok(false);
2021 }
2022 if nearest_block(&anchor.get_node()?).as_ref() != Some(&focus_block) {
2024 return Ok(false);
2025 }
2026 let block_key = focus_block.get_key();
2027 if focus.point_type == PointType::Element
2028 && focus.key == block_key
2029 && focus.offset == 0
2030 {
2031 return Ok(false);
2032 }
2033 selection.point_set(Which::Focus, block_key, 0, PointType::Element)?;
2034 if !event.shift_key {
2035 selection.point_set(Which::Anchor, block_key, 0, PointType::Element)?;
2036 }
2037 event.prevent_default();
2038 event.stop_propagation();
2039 Ok(true)
2040 },
2041 COMMAND_PRIORITY_EDITOR,
2042 ),
2043 ];
2044 Box::new(move || {
2045 for unregister in unregisters {
2046 unregister();
2047 }
2048 })
2049}