Skip to main content

lexical_ui/
events.rs

1//! `LexicalEvents.ts`, the part that needs no DOM: the default handlers of
2//! `KEY_DOWN_COMMAND` (`$handleKeyDown` and `buildKeyDownShortcuts`),
3//! `BEFORE_INPUT_COMMAND` (`$handleBeforeInput`) and the composition
4//! commands, which `registerDefaultCommandHandlers` registers on every
5//! editor, and the DOM-shaped events those commands carry, as Swift has
6//! them (`swift/Sources/Lexical/LexicalEvents.swift`).
7//!
8//! A headless editor has no DOM to listen to, so an app makes the events
9//! from its own (a key press, an input method, the platform's clipboard)
10//! with the DOM's `key` and `code` values, and passes them to
11//! [`on_key_down`], [`on_before_input`], [`on_composition_start`] and
12//! [`on_composition_end`], as JS's root element listeners do. Handlers
13//! ported from JS read the same fields.
14//!
15//! Input is model-first, as in Swift: an app never edits its own text, so
16//! every `beforeinput` is handled the way JS handles one it prevents, in
17//! controlled mode. The app sets the model selection to the input's target
18//! range before it dispatches, where JS applies `getTargetRanges()`, and
19//! writes an input method's marked text through the model, where JS reads
20//! the composed text back from the DOM.
21
22use crate::commands::{BEFORE_INPUT_COMMAND, COMPOSITION_END_COMMAND, COMPOSITION_START_COMMAND};
23use crate::commands::{
24    CONTROLLED_TEXT_INSERTION_COMMAND, COPY_COMMAND, CUT_COMMAND, DELETE_CHARACTER_COMMAND,
25    DELETE_LINE_COMMAND, DELETE_WORD_COMMAND, FORMAT_TEXT_COMMAND, INSERT_LINE_BREAK_COMMAND,
26    INSERT_PARAGRAPH_COMMAND, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_LEFT_COMMAND,
27    KEY_ARROW_RIGHT_COMMAND, KEY_ARROW_UP_COMMAND, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND,
28    KEY_DOWN_COMMAND, KEY_ENTER_COMMAND, KEY_ESCAPE_COMMAND, KEY_MODIFIER_COMMAND,
29    KEY_SPACE_COMMAND, KEY_TAB_COMMAND, MOVE_TO_END, MOVE_TO_START, PASTE_COMMAND, REDO_COMMAND,
30    REMOVE_TEXT_COMMAND, SELECT_ALL_COMMAND, UNDO_COMMAND,
31};
32use crate::constants::DOUBLE_LINE_BREAK;
33use crate::editor::{
34    COMMAND_PRIORITY_EDITOR, COMPOSITION_END_TAG, COMPOSITION_START_TAG, SKIP_SELECTION_FOCUS_TAG,
35};
36use crate::environment::is_apple;
37use crate::keyboard_shortcuts::{
38    CompiledKeyboardShortcuts, KeyboardShortcutMatch, compile_keyboard_shortcuts, control_or_alt,
39    control_or_meta,
40};
41use crate::lexical_selection::{SelectionRef, Which, get_selection, set_selection};
42use crate::lexical_utils::{
43    KeyboardEventModifierMask, KeyboardEventModifiers, ModifierExpectation, get_node_by_key,
44    is_modifier, is_token_or_segmented, set_composition_key,
45};
46use crate::node::{NodeKey, NodeRef};
47use crate::nodes::text::create_text_node;
48use crate::selection_insert_nodes::{find_matching_parent, get_previous_selection};
49use crate::{Editor, LexicalCommand, LexicalError, Unregister, utf16};
50use std::cell::{Cell, RefCell};
51use std::ops::Deref;
52use std::rc::Rc;
53
54// The events.
55
56/// The `Event` fields handlers use. Every event below holds one and
57/// dereferences to it, as the DOM's event interfaces inherit from `Event`.
58/// Events are shared (`Rc`), so a handler's `prevent_default()` is seen by
59/// the code that dispatched the event.
60#[derive(Debug)]
61pub struct Event {
62    /// `type` (`"keydown"`, `"beforeinput"`...).
63    pub type_: String,
64    pub cancelable: bool,
65    /// `timeStamp`, in milliseconds.
66    pub time_stamp: f64,
67    default_prevented: Cell<bool>,
68    propagation_stopped: Cell<bool>,
69}
70
71impl Event {
72    /// An event of `type_` that can be cancelled, at time 0.
73    pub fn new(type_: &str) -> Self {
74        Self::with_cancelable(type_, true)
75    }
76
77    fn with_cancelable(type_: &str, cancelable: bool) -> Self {
78        Self {
79            type_: type_.to_owned(),
80            cancelable,
81            time_stamp: 0.0,
82            default_prevented: Cell::new(false),
83            propagation_stopped: Cell::new(false),
84        }
85    }
86
87    /// `preventDefault()`: a cancelable event's default action is not to
88    /// happen.
89    pub fn prevent_default(&self) {
90        if self.cancelable {
91            self.default_prevented.set(true);
92        }
93    }
94
95    /// `defaultPrevented`.
96    pub fn default_prevented(&self) -> bool {
97        self.default_prevented.get()
98    }
99
100    /// `stopPropagation()`.
101    pub fn stop_propagation(&self) {
102        self.propagation_stopped.set(true);
103    }
104
105    /// Whether `stopPropagation()` was called.
106    pub fn propagation_stopped(&self) -> bool {
107        self.propagation_stopped.get()
108    }
109}
110
111macro_rules! extends {
112    ($name:ty, $field:ident: $base:ty) => {
113        impl Deref for $name {
114            type Target = $base;
115            fn deref(&self) -> &$base {
116                &self.$field
117            }
118        }
119    };
120}
121
122/// A DOM `KeyboardEvent`, with the DOM's `key` and `code` values
123/// (`"Enter"`, `"b"`, `"KeyB"`, `"ArrowLeft"`...).
124#[derive(Debug)]
125pub struct KeyboardEvent {
126    pub event: Event,
127    pub key: String,
128    pub code: String,
129    pub alt_key: bool,
130    pub ctrl_key: bool,
131    pub meta_key: bool,
132    pub shift_key: bool,
133    pub repeat: bool,
134    pub is_composing: bool,
135}
136
137extends!(KeyboardEvent, event: Event);
138
139impl Default for KeyboardEvent {
140    /// A `keydown` with no key and no modifiers.
141    fn default() -> Self {
142        Self {
143            event: Event::new("keydown"),
144            key: String::new(),
145            code: String::new(),
146            alt_key: false,
147            ctrl_key: false,
148            meta_key: false,
149            shift_key: false,
150            repeat: false,
151            is_composing: false,
152        }
153    }
154}
155
156impl KeyboardEventModifiers for KeyboardEvent {
157    fn key(&self) -> &str {
158        &self.key
159    }
160    fn code(&self) -> &str {
161        &self.code
162    }
163    fn alt_key(&self) -> bool {
164        self.alt_key
165    }
166    fn ctrl_key(&self) -> bool {
167        self.ctrl_key
168    }
169    fn meta_key(&self) -> bool {
170        self.meta_key
171    }
172    fn shift_key(&self) -> bool {
173        self.shift_key
174    }
175}
176
177/// A DOM `MouseEvent` (and the `PointerEvent` fields Lexical reads), with
178/// the node the app hit in place of the DOM target.
179#[derive(Debug)]
180pub struct MouseEvent {
181    pub event: Event,
182    pub client_x: f64,
183    pub client_y: f64,
184    pub button: i32,
185    pub detail: i32,
186    pub alt_key: bool,
187    pub ctrl_key: bool,
188    pub meta_key: bool,
189    pub shift_key: bool,
190    /// The key of the node under the pointer, as the app resolves it
191    /// (Swift's `targetKey`).
192    pub target_key: Option<NodeKey>,
193}
194
195extends!(MouseEvent, event: Event);
196
197impl MouseEvent {
198    /// A mouse event of `type_` at (0, 0), with the main button, one click
199    /// and no modifiers.
200    pub fn new(type_: &str) -> Self {
201        Self {
202            event: Event::new(type_),
203            client_x: 0.0,
204            client_y: 0.0,
205            button: 0,
206            detail: 1,
207            alt_key: false,
208            ctrl_key: false,
209            meta_key: false,
210            shift_key: false,
211            target_key: None,
212        }
213    }
214}
215
216impl Default for MouseEvent {
217    /// A `click`.
218    fn default() -> Self {
219        Self::new("click")
220    }
221}
222
223impl KeyboardEventModifiers for MouseEvent {
224    fn key(&self) -> &str {
225        ""
226    }
227    fn code(&self) -> &str {
228        ""
229    }
230    fn alt_key(&self) -> bool {
231        self.alt_key
232    }
233    fn ctrl_key(&self) -> bool {
234        self.ctrl_key
235    }
236    fn meta_key(&self) -> bool {
237        self.meta_key
238    }
239    fn shift_key(&self) -> bool {
240        self.shift_key
241    }
242}
243
244/// A DOM `DragEvent`: a drag or a drop, with its data.
245#[derive(Debug)]
246pub struct DragEvent {
247    pub mouse: MouseEvent,
248    pub data_transfer: Option<Rc<DataTransfer>>,
249}
250
251extends!(DragEvent, mouse: MouseEvent);
252
253impl DragEvent {
254    pub fn new(type_: &str, data_transfer: Option<Rc<DataTransfer>>) -> Self {
255        Self {
256            mouse: MouseEvent::new(type_),
257            data_transfer,
258        }
259    }
260}
261
262/// A DOM `FocusEvent` (`focus`, `blur`).
263#[derive(Debug)]
264pub struct FocusEvent {
265    pub event: Event,
266}
267
268extends!(FocusEvent, event: Event);
269
270impl FocusEvent {
271    pub fn new(type_: &str) -> Self {
272        Self {
273            event: Event::with_cancelable(type_, false),
274        }
275    }
276}
277
278/// A DOM `InputEvent`: a `beforeinput` or `input`.
279#[derive(Debug)]
280pub struct InputEvent {
281    pub event: Event,
282    /// `inputType` (`"insertText"`, `"deleteContentBackward"`...).
283    pub input_type: String,
284    pub data: Option<String>,
285    pub data_transfer: Option<Rc<DataTransfer>>,
286    pub is_composing: bool,
287}
288
289extends!(InputEvent, event: Event);
290
291impl InputEvent {
292    /// A `beforeinput` of `input_type`, with no data.
293    pub fn new(input_type: &str) -> Self {
294        Self {
295            event: Event::new("beforeinput"),
296            input_type: input_type.to_owned(),
297            data: None,
298            data_transfer: None,
299            is_composing: false,
300        }
301    }
302}
303
304/// A DOM `CompositionEvent`: an input method composition starts or ends.
305#[derive(Debug)]
306pub struct CompositionEvent {
307    pub event: Event,
308    pub data: String,
309}
310
311extends!(CompositionEvent, event: Event);
312
313impl CompositionEvent {
314    pub fn new(type_: &str, data: &str) -> Self {
315        Self {
316            event: Event::with_cancelable(type_, false),
317            data: data.to_owned(),
318        }
319    }
320}
321
322/// A DOM `ClipboardEvent`: a copy, cut or paste, with its data.
323#[derive(Debug)]
324pub struct ClipboardEvent {
325    pub event: Event,
326    pub clipboard_data: Option<Rc<DataTransfer>>,
327}
328
329extends!(ClipboardEvent, event: Event);
330
331impl ClipboardEvent {
332    pub fn new(type_: &str, clipboard_data: Option<Rc<DataTransfer>>) -> Self {
333        Self {
334            event: Event::new(type_),
335            clipboard_data,
336        }
337    }
338}
339
340/// `PasteCommandType`: `ClipboardEvent | InputEvent | KeyboardEvent`, the
341/// payload of `PASTE_COMMAND`.
342#[derive(Clone, Debug)]
343pub enum PasteCommandType {
344    Clipboard(Rc<ClipboardEvent>),
345    Input(Rc<InputEvent>),
346    Keyboard(Rc<KeyboardEvent>),
347}
348
349impl PasteCommandType {
350    /// The event, whichever it is.
351    pub fn event(&self) -> &Event {
352        match self {
353            PasteCommandType::Clipboard(e) => e,
354            PasteCommandType::Input(e) => e,
355            PasteCommandType::Keyboard(e) => e,
356        }
357    }
358}
359
360/// `ClipboardEvent | KeyboardEvent`, the payload of `COPY_COMMAND` and
361/// `CUT_COMMAND` (or `None`, JS's `null`).
362#[derive(Clone, Debug)]
363pub enum ClipboardOrKeyboardEvent {
364    Clipboard(Rc<ClipboardEvent>),
365    Keyboard(Rc<KeyboardEvent>),
366}
367
368impl ClipboardOrKeyboardEvent {
369    /// The event, whichever it is.
370    pub fn event(&self) -> &Event {
371        match self {
372            ClipboardOrKeyboardEvent::Clipboard(e) => e,
373            ClipboardOrKeyboardEvent::Keyboard(e) => e,
374        }
375    }
376
377    /// The clipboard event, when it is one (JS's
378    /// `objectKlassEquals(event, ClipboardEvent) ? event : null`).
379    pub fn clipboard_event(event: Option<&Self>) -> Option<&Rc<ClipboardEvent>> {
380        match event {
381            Some(ClipboardOrKeyboardEvent::Clipboard(e)) => Some(e),
382            _ => None,
383        }
384    }
385}
386
387/// One file of a [`DataTransfer`], as a web `File`: its name, type and
388/// size are known up front, and its contents are read only when
389/// [`bytes`](Self::bytes) asks for them, as `File.bytes()` reads a lazy
390/// `Blob`.
391#[derive(Clone)]
392pub struct DataTransferFile {
393    /// `File.name`.
394    pub name: String,
395    /// `File.type`, a MIME type.
396    pub type_: String,
397    /// `File.size` in bytes, or `None` when it isn't known without reading
398    /// the file.
399    pub size: Option<usize>,
400    load: Rc<dyn Fn() -> std::io::Result<Vec<u8>>>,
401}
402
403impl DataTransferFile {
404    /// A file whose contents are `data`, in memory.
405    pub fn new(name: &str, type_: &str, data: Vec<u8>) -> Self {
406        let size = data.len();
407        Self::lazy(name, type_, Some(size), move || Ok(data.clone()))
408    }
409
410    /// A file that `load` reads each time [`bytes`](Self::bytes) is called.
411    pub fn lazy(
412        name: &str,
413        type_: &str,
414        size: Option<usize>,
415        load: impl Fn() -> std::io::Result<Vec<u8>> + 'static,
416    ) -> Self {
417        Self {
418            name: name.to_owned(),
419            type_: type_.to_owned(),
420            size,
421            load: Rc::new(load),
422        }
423    }
424
425    /// `File.bytes()`: the file's contents, or the error that it can no
426    /// longer be read (a web `File` rejects with `NotReadableError`).
427    pub fn bytes(&self) -> std::io::Result<Vec<u8>> {
428        (self.load)()
429    }
430}
431
432impl std::fmt::Debug for DataTransferFile {
433    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
434        f.debug_struct("DataTransferFile")
435            .field("name", &self.name)
436            .field("type_", &self.type_)
437            .field("size", &self.size)
438            .finish_non_exhaustive()
439    }
440}
441
442/// `DataTransfer`: the data of a clipboard or drag operation, by format (a
443/// MIME type), in the order each format was first set, and its files.
444///
445/// It is shared as a DOM `DataTransfer` is, so its setters take `&self`: a
446/// copy fills the one the platform's clipboard event carries, and the
447/// caller reads it afterwards.
448#[derive(Debug)]
449pub struct DataTransfer {
450    entries: RefCell<Vec<(String, String)>>,
451    files: RefCell<Vec<DataTransferFile>>,
452    drop_effect: RefCell<String>,
453    effect_allowed: RefCell<String>,
454}
455
456impl Default for DataTransfer {
457    fn default() -> Self {
458        Self {
459            entries: RefCell::new(Vec::new()),
460            files: RefCell::new(Vec::new()),
461            drop_effect: RefCell::new("none".to_owned()),
462            effect_allowed: RefCell::new("uninitialized".to_owned()),
463        }
464    }
465}
466
467impl DataTransfer {
468    /// `new DataTransfer()`: one with no data.
469    pub fn new() -> Self {
470        Self::default()
471    }
472
473    /// The format a type names: lowercased, with `text` read as
474    /// `text/plain` and `url` as `text/uri-list`, as browsers do.
475    fn format(format: &str) -> String {
476        let format = format.to_lowercase();
477        match format.as_str() {
478            "text" => "text/plain".to_owned(),
479            "url" => "text/uri-list".to_owned(),
480            _ => format,
481        }
482    }
483
484    /// `types`: the formats set so far, in order, then `"Files"` when there
485    /// are files, as browsers report it.
486    pub fn types(&self) -> Vec<String> {
487        let mut types: Vec<String> = self
488            .entries
489            .borrow()
490            .iter()
491            .map(|(t, _)| t.clone())
492            .collect();
493        if !self.files.borrow().is_empty() {
494            types.push("Files".to_owned());
495        }
496        types
497    }
498
499    /// `getData(format)`: the data for `format`, or `""`.
500    pub fn get_data(&self, format: &str) -> String {
501        let format = Self::format(format);
502        self.entries
503            .borrow()
504            .iter()
505            .find(|(t, _)| *t == format)
506            .map(|(_, data)| data.clone())
507            .unwrap_or_default()
508    }
509
510    /// `setData(format, data)`: sets the data for `format`, keeping its
511    /// place if it was set before.
512    pub fn set_data(&self, format: &str, data: &str) {
513        let format = Self::format(format);
514        let mut entries = self.entries.borrow_mut();
515        match entries.iter_mut().find(|(t, _)| *t == format) {
516            Some(entry) => entry.1 = data.to_owned(),
517            None => entries.push((format, data.to_owned())),
518        }
519    }
520
521    /// `clearData(format)`: removes the data for `format`, or with `None`
522    /// all of it (not the files).
523    pub fn clear_data(&self, format: Option<&str>) {
524        let mut entries = self.entries.borrow_mut();
525        match format {
526            Some(format) => {
527                let format = Self::format(format);
528                entries.retain(|(t, _)| *t != format);
529            }
530            None => entries.clear(),
531        }
532    }
533
534    /// `files`.
535    pub fn files(&self) -> Vec<DataTransferFile> {
536        self.files.borrow().clone()
537    }
538
539    /// Sets `files` (what `items.add(file)` builds up in a browser).
540    pub fn set_files(&self, files: Vec<DataTransferFile>) {
541        *self.files.borrow_mut() = files;
542    }
543
544    /// `dropEffect` (`"none"` at first).
545    pub fn drop_effect(&self) -> String {
546        self.drop_effect.borrow().clone()
547    }
548
549    pub fn set_drop_effect(&self, drop_effect: &str) {
550        *self.drop_effect.borrow_mut() = drop_effect.to_owned();
551    }
552
553    /// `effectAllowed` (`"uninitialized"` at first).
554    pub fn effect_allowed(&self) -> String {
555        self.effect_allowed.borrow().clone()
556    }
557
558    pub fn set_effect_allowed(&self, effect_allowed: &str) {
559        *self.effect_allowed.borrow_mut() = effect_allowed.to_owned();
560    }
561}
562
563// The editor's input state.
564
565/// The part of `editor._inputState` the model reads: whether the Enter
566/// that comes before an `insertParagraph` asked for a line break, the
567/// `key` of the last key pressed, and the segmented node a composition was
568/// redirected into.
569#[derive(Debug, Default)]
570pub(crate) struct InputState {
571    pub(crate) is_insert_line_break: bool,
572    pub(crate) last_key_code: Option<String>,
573    pub(crate) composed_segmented_key: Option<NodeKey>,
574}
575
576// The entry points.
577
578/// `onKeyDown(event, editor)`: an app's key press. It records the key and,
579/// unless an input method is composing, dispatches `KEY_DOWN_COMMAND`,
580/// whose default handler dispatches the command the key stands for. Read
581/// `event.default_prevented()` afterwards to know whether the key was
582/// taken (the app then skips its own handling of it).
583pub fn on_key_down(event: &Rc<KeyboardEvent>, editor: &Editor) -> Result<(), LexicalError> {
584    editor.0.input_state.borrow_mut().last_key_code = Some(event.key.clone());
585    if editor.is_composing() {
586        return Ok(());
587    }
588    editor.dispatch_command(&KEY_DOWN_COMMAND, event.clone())?;
589    Ok(())
590}
591
592/// `onBeforeInput(event, editor)`: an app's `beforeinput`. A composition's
593/// own input (`insertCompositionText`, `deleteCompositionText`) is left to
594/// the composition commands; anything else dispatches
595/// `BEFORE_INPUT_COMMAND`.
596pub fn on_before_input(event: &Rc<InputEvent>, editor: &Editor) -> Result<(), LexicalError> {
597    if matches!(
598        event.input_type.as_str(),
599        "deleteCompositionText" | "insertCompositionText"
600    ) {
601        return Ok(());
602    }
603    editor.dispatch_command(&BEFORE_INPUT_COMMAND, event.clone())?;
604    Ok(())
605}
606
607/// `onCompositionStart(event, editor)`: dispatches
608/// `COMPOSITION_START_COMMAND`.
609pub fn on_composition_start(
610    event: &Rc<CompositionEvent>,
611    editor: &Editor,
612) -> Result<(), LexicalError> {
613    editor.dispatch_command(&COMPOSITION_START_COMMAND, event.clone())?;
614    Ok(())
615}
616
617/// `onCompositionEnd(event, editor)`: dispatches
618/// `COMPOSITION_END_COMMAND` (where JS waits for Firefox's and Safari's
619/// input event, the model has none to wait for).
620pub fn on_composition_end(
621    event: &Rc<CompositionEvent>,
622    editor: &Editor,
623) -> Result<(), LexicalError> {
624    editor.dispatch_command(&COMPOSITION_END_COMMAND, event.clone())?;
625    Ok(())
626}
627
628/// `onSelectionChange(domSelection, editor, isActive)`, its model half: an
629/// app's view selected `anchor` to `focus` (`None` when the selection left
630/// the editor). An editor that isn't active (`is_active` false, another
631/// editor of the view has the selection) gets no selection, as in JS.
632/// Otherwise the points become the selection, with the format and style of
633/// the editor state's (the last committed) selection, as
634/// `$internalCreateRangeSelection` gives a selection read from the DOM; a caret takes
635/// the format and style of where it is (`$updateCollapsedSelectionFormatStyle`)
636/// and a range the format all its text has; then the change is announced
637/// with `SELECTION_CHANGE_COMMAND` (`$dispatchSelectionChangeCommand`).
638///
639/// What JS reads from the DOM is the view's: whether the selection is
640/// within the editor, the drag adjustment, and the selection the reconciler
641/// applied (`isSelectionChangeFromDOMUpdate`). Nothing marks a collapsed
642/// selection's format (`markCollapsedSelectionFormat` runs when JS writes
643/// the DOM selection), so a caret always takes the format where it is.
644pub fn on_selection_change(
645    editor: &Editor,
646    points: Option<(crate::Point, crate::Point)>,
647    is_active: bool,
648) -> Result<(), LexicalError> {
649    crate::updates::update_editor_sync(
650        editor,
651        || {
652            let Some((anchor, focus)) = points.filter(|_| is_active) else {
653                set_selection(None);
654                return Ok(());
655            };
656            let (format, style) = match editor
657                .get_editor_state()
658                .selection()
659                .and_then(|s| s.range())
660            {
661                Some(last) => (last.format, last.style),
662                None => (0.0, String::new()),
663            };
664            let selection = SelectionRef::new(crate::lexical_selection::Selection::Range(
665                crate::RangeSelection::new(anchor, focus, format, style),
666            ));
667            set_selection(Some(selection.clone()));
668            // A selection read from the DOM isn't dirty until its format
669            // changes below.
670            selection.set_dirty(false);
671            let range = selection.range().expect("a range selection");
672            if range.is_collapsed() {
673                update_collapsed_selection_format_style(editor, &selection, &range)?;
674            } else {
675                update_range_selection_format(&selection, &range)?;
676            }
677            let force = selection.is_dirty();
678            crate::updates::dispatch_selection_change_command(editor, Some(&selection), force)
679        },
680        None,
681    )
682}
683
684/// `$updateSelectionFormatStyle(selection, format, style)`.
685fn update_selection_format_style(selection: &SelectionRef, format: f64, style: &str) {
686    selection.with_range(|r| {
687        if r.format != format || r.style != style {
688            r.format = format;
689            r.style = style.to_owned();
690            r.dirty = true;
691        }
692    });
693}
694
695/// `$updateCollapsedSelectionFormatStyle(editor, selection)`: a caret takes
696/// the format and style of where it is.
697fn update_collapsed_selection_format_style(
698    editor: &Editor,
699    selection: &SelectionRef,
700    range: &crate::RangeSelection,
701) -> Result<(), LexicalError> {
702    let anchor_node = range.anchor.get_node()?;
703    if range.anchor.point_type == crate::PointType::Text {
704        if !anchor_node.is_text() {
705            return Err(LexicalError::new(
706                "Point.getNode() must return TextNode when type is text",
707            ));
708        }
709        let data = anchor_node.text_data();
710        update_selection_format_style(selection, data.get_format(), data.get_style());
711    } else if editor.is_composing() || !crate::get_root().get_text_content().is_empty() {
712        if !anchor_node.is_element() {
713            return Err(LexicalError::new(
714                "Point.getNode() must return ElementNode when type is element",
715            ));
716        }
717        if anchor_node.is_empty() {
718            crate::selection_editing::internal_refresh_selection_format_and_style(selection, "")?;
719        } else {
720            update_selection_format_style(selection, range.format, "");
721        }
722    }
723    Ok(())
724}
725
726/// The format a range takes in `onSelectionChange`: the format every text
727/// node it covers has, leaving out an empty boundary at either end, or none
728/// when it covers no text. Its style is kept.
729fn update_range_selection_format(
730    selection: &SelectionRef,
731    range: &crate::RangeSelection,
732) -> Result<(), LexicalError> {
733    let nodes = selection.get_nodes()?;
734    let (start, end) = if selection.is_backward()? {
735        (&range.focus, &range.anchor)
736    } else {
737        (&range.anchor, &range.focus)
738    };
739    let mut combined = crate::constants::IS_ALL_FORMATTING;
740    let mut has_text_nodes = false;
741    let last = nodes.len().wrapping_sub(1);
742    for (i, node) in nodes.iter().enumerate() {
743        let size = node.get_text_content_size();
744        let key = node.get_key();
745        if node.is_text()
746            && size != 0
747            && !((i == 0 && key == start.key && start.offset == size)
748                || (i == last && key == end.key && end.offset == 0))
749        {
750            has_text_nodes = true;
751            combined &= crate::nodes::text::to_int32(node.text_data().get_format());
752            if combined == 0 {
753                break;
754            }
755        }
756    }
757    let format = if has_text_nodes { combined as f64 } else { 0.0 };
758    selection.with_range(|r| r.format = format);
759    Ok(())
760}
761
762// The default KEY_DOWN_COMMAND handler.
763
764type OnMatch = Rc<dyn Fn(&Rc<KeyboardEvent>, &Editor) -> Result<(), LexicalError>>;
765
766/// `KeyDownShortcut`: a key-down binding of `$handleKeyDown`.
767#[derive(Clone)]
768pub(crate) struct KeyDownShortcut {
769    key: &'static str,
770    modifiers: KeyboardEventModifierMask,
771    on_match: OnMatch,
772}
773
774impl KeyboardShortcutMatch for KeyDownShortcut {
775    fn key(&self) -> &str {
776        self.key
777    }
778    fn modifiers(&self) -> KeyboardEventModifierMask {
779        self.modifiers
780    }
781}
782
783const ANY: ModifierExpectation = ModifierExpectation::Any;
784const PRESSED: ModifierExpectation = ModifierExpectation::Pressed;
785const RELEASED: ModifierExpectation = ModifierExpectation::Released;
786
787const ANY_MODIFIERS: KeyboardEventModifierMask = KeyboardEventModifierMask {
788    alt_key: ANY,
789    ctrl_key: ANY,
790    meta_key: ANY,
791    shift_key: ANY,
792    control_or_other: None,
793};
794const NO_MODIFIERS: KeyboardEventModifierMask = KeyboardEventModifierMask {
795    alt_key: RELEASED,
796    ctrl_key: RELEASED,
797    meta_key: RELEASED,
798    shift_key: RELEASED,
799    control_or_other: None,
800};
801const CTRL_KEY: KeyboardEventModifierMask = KeyboardEventModifierMask {
802    ctrl_key: PRESSED,
803    ..NO_MODIFIERS
804};
805const META_KEY: KeyboardEventModifierMask = KeyboardEventModifierMask {
806    meta_key: PRESSED,
807    ..NO_MODIFIERS
808};
809const SHIFT_KEY_ANY: KeyboardEventModifierMask = KeyboardEventModifierMask {
810    shift_key: ANY,
811    ..NO_MODIFIERS
812};
813const ALT_SHIFT_KEY_ANY: KeyboardEventModifierMask = KeyboardEventModifierMask {
814    alt_key: ANY,
815    shift_key: ANY,
816    ..NO_MODIFIERS
817};
818
819/// `buildKeyDownShortcuts()`: the key-down bindings, for the platform
820/// [`is_apple`] names. Each mask is exclusive of every other mask on the
821/// same key, so at most one matches an event. JS's bindings for Chrome's
822/// text replacement (`markHandledSelectionCommandInsertText`), iOS's
823/// virtual Shift key and inputs embedded in a node's DOM
824/// (`$isEventFromEmbeddedInput`) have no counterpart without a browser.
825pub(crate) fn build_key_down_shortcuts() -> Vec<KeyDownShortcut> {
826    fn shortcut(
827        key: &'static str,
828        modifiers: KeyboardEventModifierMask,
829        on_match: impl Fn(&Rc<KeyboardEvent>, &Editor) -> Result<(), LexicalError> + 'static,
830    ) -> KeyDownShortcut {
831        KeyDownShortcut {
832            key,
833            modifiers,
834            on_match: Rc::new(on_match),
835        }
836    }
837    // Dispatches the command with the KeyboardEvent as its payload.
838    fn dispatch(
839        key: &'static str,
840        modifiers: KeyboardEventModifierMask,
841        command: LexicalCommand<Rc<KeyboardEvent>>,
842    ) -> KeyDownShortcut {
843        shortcut(key, modifiers, move |event, editor| {
844            editor.dispatch_command(&command, event.clone())?;
845            Ok(())
846        })
847    }
848    // `preventDefault()`, then dispatches the command with a fixed payload.
849    fn prevent<T: Clone + 'static>(
850        key: &'static str,
851        modifiers: KeyboardEventModifierMask,
852        command: LexicalCommand<T>,
853        payload: T,
854    ) -> KeyDownShortcut {
855        shortcut(key, modifiers, move |event, editor| {
856            event.prevent_default();
857            editor.dispatch_command(&command, payload.clone())?;
858            Ok(())
859        })
860    }
861    fn enter(modifiers: KeyboardEventModifierMask, is_insert_line_break: bool) -> KeyDownShortcut {
862        shortcut("Enter", modifiers, move |event, editor| {
863            editor.0.input_state.borrow_mut().is_insert_line_break = is_insert_line_break;
864            editor.dispatch_command(&KEY_ENTER_COMMAND, Some(event.clone()))?;
865            if event.default_prevented() {
866                editor.0.input_state.borrow_mut().is_insert_line_break = false;
867            }
868            Ok(())
869        })
870    }
871    // Only a RangeSelection can use the native cut and copy.
872    fn copy_or_cut(
873        key: &'static str,
874        command: LexicalCommand<Option<ClipboardOrKeyboardEvent>>,
875    ) -> KeyDownShortcut {
876        shortcut(key, control_or_meta(), move |event, editor| {
877            let prev_selection = editor.get_editor_state().selection();
878            if prev_selection.is_some_and(|s| !s.is_range()) {
879                event.prevent_default();
880                editor.dispatch_command(
881                    &command,
882                    Some(ClipboardOrKeyboardEvent::Keyboard(event.clone())),
883                )?;
884            }
885            Ok(())
886        })
887    }
888    let mut shortcuts = vec![
889        // moveForward / moveToEnd / moveBackward / moveToStart / moveUp / moveDown
890        dispatch("ArrowRight", SHIFT_KEY_ANY, KEY_ARROW_RIGHT_COMMAND),
891        dispatch("ArrowLeft", SHIFT_KEY_ANY, KEY_ARROW_LEFT_COMMAND),
892        dispatch("ArrowUp", ALT_SHIFT_KEY_ANY, KEY_ARROW_UP_COMMAND),
893        dispatch("ArrowDown", ALT_SHIFT_KEY_ANY, KEY_ARROW_DOWN_COMMAND),
894        // lineBreak / paragraph
895        enter(
896            KeyboardEventModifierMask {
897                shift_key: PRESSED,
898                ..ANY_MODIFIERS
899            },
900            true,
901        ),
902        enter(
903            KeyboardEventModifierMask {
904                shift_key: RELEASED,
905                ..ANY_MODIFIERS
906            },
907            false,
908        ),
909        dispatch(" ", ANY_MODIFIERS, KEY_SPACE_COMMAND),
910        // deleteBackward
911        dispatch("Backspace", SHIFT_KEY_ANY, KEY_BACKSPACE_COMMAND),
912        dispatch("Escape", ANY_MODIFIERS, KEY_ESCAPE_COMMAND),
913        // deleteForward
914        dispatch("Delete", NO_MODIFIERS, KEY_DELETE_COMMAND),
915        // deleteWordBackward / deleteWordForward
916        prevent("Backspace", control_or_alt(), DELETE_WORD_COMMAND, true),
917        prevent("Delete", control_or_alt(), DELETE_WORD_COMMAND, false),
918        prevent(
919            "b",
920            control_or_meta(),
921            FORMAT_TEXT_COMMAND,
922            "bold".to_owned(),
923        ),
924        prevent(
925            "u",
926            control_or_meta(),
927            FORMAT_TEXT_COMMAND,
928            "underline".to_owned(),
929        ),
930        prevent(
931            "i",
932            control_or_meta(),
933            FORMAT_TEXT_COMMAND,
934            "italic".to_owned(),
935        ),
936        dispatch("Tab", SHIFT_KEY_ANY, KEY_TAB_COMMAND),
937        // undo / redo
938        prevent("z", control_or_meta(), UNDO_COMMAND, ()),
939        prevent(
940            "z",
941            KeyboardEventModifierMask {
942                shift_key: PRESSED,
943                ..control_or_meta()
944            },
945            REDO_COMMAND,
946            (),
947        ),
948    ];
949    if is_apple() {
950        shortcuts.extend([
951            // openLineBreak
952            prevent("o", CTRL_KEY, INSERT_LINE_BREAK_COMMAND, true),
953            // moveToStart / moveToEnd mac
954            dispatch(
955                "ArrowLeft",
956                KeyboardEventModifierMask {
957                    meta_key: PRESSED,
958                    ..SHIFT_KEY_ANY
959                },
960                MOVE_TO_START,
961            ),
962            dispatch(
963                "ArrowRight",
964                KeyboardEventModifierMask {
965                    meta_key: PRESSED,
966                    ..SHIFT_KEY_ANY
967                },
968                MOVE_TO_END,
969            ),
970            // deleteBackward / deleteForward
971            prevent("h", CTRL_KEY, DELETE_CHARACTER_COMMAND, true),
972            prevent("d", CTRL_KEY, DELETE_CHARACTER_COMMAND, false),
973            // deleteLineBackward / deleteLineForward
974            prevent("Backspace", META_KEY, DELETE_LINE_COMMAND, true),
975            prevent("Delete", META_KEY, DELETE_LINE_COMMAND, false),
976            prevent("k", CTRL_KEY, DELETE_LINE_COMMAND, false),
977        ]);
978    } else {
979        shortcuts.extend([
980            dispatch("Home", SHIFT_KEY_ANY, MOVE_TO_START),
981            dispatch("End", SHIFT_KEY_ANY, MOVE_TO_END),
982            prevent("y", CTRL_KEY, REDO_COMMAND, ()),
983        ]);
984    }
985    shortcuts.extend([
986        // selectAll
987        shortcut("a", control_or_meta(), |event, editor| {
988            event.prevent_default();
989            editor.dispatch_command(&SELECT_ALL_COMMAND, event.clone())?;
990            Ok(())
991        }),
992        copy_or_cut("c", COPY_COMMAND),
993        copy_or_cut("x", CUT_COMMAND),
994    ]);
995    shortcuts
996}
997
998/// The editor's compiled key-down bindings (JS `editor._keyDownShortcuts`),
999/// for the platform they were compiled for.
1000pub(crate) type KeyDownShortcuts = (bool, Rc<CompiledKeyboardShortcuts<KeyDownShortcut>>);
1001
1002/// `$handleKeyDown(event)`: dispatches the command the key stands for,
1003/// then `KEY_MODIFIER_COMMAND` when a modifier is down. Always reports the
1004/// event as handled, as in JS.
1005pub(crate) fn handle_key_down(
1006    event: &Rc<KeyboardEvent>,
1007    editor: &Editor,
1008) -> Result<bool, LexicalError> {
1009    let is_apple = is_apple();
1010    let cached = editor
1011        .0
1012        .key_down_shortcuts
1013        .borrow()
1014        .as_ref()
1015        .filter(|(apple, _)| *apple == is_apple)
1016        .map(|(_, shortcuts)| shortcuts.clone());
1017    let compiled = match cached {
1018        Some(compiled) => compiled,
1019        None => {
1020            let compiled = Rc::new(compile_keyboard_shortcuts(build_key_down_shortcuts())?);
1021            *editor.0.key_down_shortcuts.borrow_mut() = Some((is_apple, compiled.clone()));
1022            compiled
1023        }
1024    };
1025    if let Some(shortcut) = compiled.r#match(&**event) {
1026        (shortcut.on_match)(event, editor)?;
1027    }
1028    if is_modifier(&**event) {
1029        editor.dispatch_command(&KEY_MODIFIER_COMMAND, event.clone())?;
1030    }
1031    Ok(true)
1032}
1033
1034// The default BEFORE_INPUT_COMMAND handler.
1035
1036/// `$isTokenOrTab(node)`.
1037fn is_token_or_tab(node: &NodeRef) -> bool {
1038    node.get_type() == "tab" || node.is_token()
1039}
1040
1041/// `$maybeMoveSelectionPastTrailingAcceptanceBoundary(insertedText)`: after
1042/// a text replacement accepted by the key that ends it (a space, Enter,
1043/// Tab), puts the caret after that key's character, which the replacement
1044/// arrived in front of.
1045fn maybe_move_selection_past_trailing_acceptance_boundary(
1046    editor: &Editor,
1047    inserted_text: Option<&str>,
1048) -> Result<(), LexicalError> {
1049    let last_key_code = editor.0.input_state.borrow().last_key_code.clone();
1050    let (Some(inserted_text), Some(last_key_code)) = (inserted_text, last_key_code) else {
1051        return Ok(());
1052    };
1053    if utf16::len(inserted_text) <= 1 {
1054        return Ok(());
1055    }
1056    let character_to_search_for: u16 = if utf16::len(&last_key_code) == 1 {
1057        last_key_code.encode_utf16().next().unwrap_or(0)
1058    } else if last_key_code == "Enter" {
1059        u16::from(b'\n')
1060    } else if last_key_code == "Tab" {
1061        u16::from(b'\t')
1062    } else {
1063        return Ok(());
1064    };
1065    let Some(selection) = get_selection().filter(SelectionRef::is_range) else {
1066        return Ok(());
1067    };
1068    let Some(range) = selection.range() else {
1069        return Ok(());
1070    };
1071    if !range.is_collapsed() {
1072        return Ok(());
1073    }
1074    let anchor_node = range.anchor.get_node()?;
1075    if !anchor_node.is_text() {
1076        return Ok(());
1077    }
1078    let offset = range.anchor.offset;
1079    let text: Vec<u16> = anchor_node.get_text_content().encode_utf16().collect();
1080    if text.len() == offset {
1081        let next_sibling = anchor_node.get_next_sibling();
1082        if character_to_search_for == u16::from(b'\n') {
1083            match next_sibling {
1084                Some(line_break) if line_break.get_type() == "linebreak" => {
1085                    line_break.select_end()?;
1086                }
1087                None => {
1088                    let block =
1089                        find_matching_parent(&anchor_node, |n| n.is_element() && !n.is_inline());
1090                    if let Some(next_block) = block.and_then(|b| b.get_next_sibling())
1091                        && next_block.is_element()
1092                    {
1093                        next_block.select_start()?;
1094                    }
1095                }
1096                Some(_) => {}
1097            }
1098        } else if character_to_search_for == u16::from(b'\t') {
1099            if let Some(tab) = next_sibling.filter(|n| n.get_type() == "tab") {
1100                tab.select_end()?;
1101            }
1102        } else if let Some(next) = next_sibling.filter(NodeRef::is_text)
1103            && next.get_text_content().encode_utf16().next() == Some(character_to_search_for)
1104        {
1105            next.select(Some(1), Some(1))?;
1106        }
1107    } else if text.get(offset) == Some(&character_to_search_for) {
1108        anchor_node.select(Some(offset + 1), Some(offset + 1))?;
1109    }
1110    Ok(())
1111}
1112
1113/// `$canRemoveText(anchorNode, focusNode)`.
1114fn can_remove_text(anchor_node: &NodeRef, focus_node: &NodeRef) -> bool {
1115    anchor_node.get_key() != focus_node.get_key()
1116        || anchor_node.is_element()
1117        || focus_node.is_element()
1118        || !is_token_or_tab(anchor_node)
1119        || !is_token_or_tab(focus_node)
1120}
1121
1122/// `$handleBeforeInput(event)`: dispatches the command an input stands
1123/// for. Text is always inserted in controlled mode, as a string
1124/// (`CONTROLLED_TEXT_INSERTION_COMMAND`), since there is no DOM edit to let
1125/// through and no DOM to read it back from; JS's workarounds for Android,
1126/// iOS, Chrome and Firefox, and its target ranges, have no counterpart.
1127pub(crate) fn handle_before_input(
1128    event: &Rc<InputEvent>,
1129    editor: &Editor,
1130) -> Result<bool, LexicalError> {
1131    let input_type = event.input_type.as_str();
1132    let selection = get_selection();
1133
1134    if input_type == "deleteContentBackward" {
1135        match &selection {
1136            None => {
1137                // Use previous selection
1138                let Some(prev_selection) = get_previous_selection().filter(SelectionRef::is_range)
1139                else {
1140                    return Ok(true);
1141                };
1142                set_selection(Some(prev_selection.clone_selection()));
1143            }
1144            Some(selection) if selection.is_range() => {
1145                set_composition_key(None);
1146                event.prevent_default();
1147                editor.dispatch_command(&DELETE_CHARACTER_COMMAND, true)?;
1148                return Ok(true);
1149            }
1150            Some(_) => {}
1151        }
1152    }
1153
1154    let Some(selection) = selection.filter(SelectionRef::is_range) else {
1155        if input_type == "historyUndo" || input_type == "historyRedo" {
1156            event.prevent_default();
1157            let command = if input_type == "historyUndo" {
1158                UNDO_COMMAND
1159            } else {
1160                REDO_COMMAND
1161            };
1162            editor.dispatch_command(&command, ())?;
1163        }
1164        return Ok(true);
1165    };
1166
1167    let data = event.data.as_deref();
1168    if input_type == "insertText" || input_type == "insertTranspose" {
1169        if data == Some("\n") {
1170            event.prevent_default();
1171            editor.dispatch_command(&INSERT_LINE_BREAK_COMMAND, false)?;
1172        } else if data == Some(DOUBLE_LINE_BREAK) {
1173            event.prevent_default();
1174            editor.dispatch_command(&INSERT_PARAGRAPH_COMMAND, ())?;
1175        } else if data.is_none()
1176            && let Some(data_transfer) = &event.data_transfer
1177        {
1178            // Gets around a Safari text replacement bug.
1179            let text = data_transfer.get_data("text/plain");
1180            event.prevent_default();
1181            selection.insert_raw_text(&text)?;
1182        } else if let Some(data) = data {
1183            event.prevent_default();
1184            editor.dispatch_command(&CONTROLLED_TEXT_INSERTION_COMMAND, data.to_owned())?;
1185            maybe_move_selection_past_trailing_acceptance_boundary(editor, Some(data))?;
1186        }
1187        return Ok(true);
1188    }
1189
1190    // Prevent the default, so we control the output.
1191    event.prevent_default();
1192    let range = selection.range().expect("a range selection");
1193    let anchor_node = range.anchor.get_node()?;
1194    let focus_node = range.focus.get_node()?;
1195
1196    match input_type {
1197        "insertFromYank" | "insertFromDrop" | "insertReplacementText" => {
1198            let text = event
1199                .data_transfer
1200                .as_ref()
1201                .map(|d| d.get_data("text/plain"));
1202            let inserted = text.as_deref().or(data);
1203            editor.dispatch_command(
1204                &CONTROLLED_TEXT_INSERTION_COMMAND,
1205                inserted.unwrap_or("").to_owned(),
1206            )?;
1207            maybe_move_selection_past_trailing_acceptance_boundary(editor, inserted)?;
1208        }
1209        "insertFromComposition" => {
1210            let prev_composition_key = editor.composition_key();
1211            set_composition_key(None);
1212            editor.dispatch_command(
1213                &CONTROLLED_TEXT_INSERTION_COMMAND,
1214                data.unwrap_or("").to_owned(),
1215            )?;
1216            cleanup_composed_subclass(editor, prev_composition_key.as_deref())?;
1217        }
1218        "insertLineBreak" => {
1219            // Used for Android
1220            set_composition_key(None);
1221            editor.0.input_state.borrow_mut().is_insert_line_break = false;
1222            editor.dispatch_command(&INSERT_LINE_BREAK_COMMAND, false)?;
1223        }
1224        "insertParagraph" => {
1225            // Used for Android
1226            set_composition_key(None);
1227            // Safari does not provide the type "insertLineBreak", so the
1228            // keydown handler saves the intent for this input.
1229            let is_insert_line_break =
1230                std::mem::take(&mut editor.0.input_state.borrow_mut().is_insert_line_break);
1231            if is_insert_line_break {
1232                editor.dispatch_command(&INSERT_LINE_BREAK_COMMAND, false)?;
1233            } else {
1234                editor.dispatch_command(&INSERT_PARAGRAPH_COMMAND, ())?;
1235            }
1236        }
1237        "insertFromPaste" | "insertFromPasteAsQuotation" => {
1238            editor.dispatch_command(&PASTE_COMMAND, PasteCommandType::Input(event.clone()))?;
1239        }
1240        "deleteByComposition" => {
1241            if can_remove_text(&anchor_node, &focus_node) {
1242                editor.dispatch_command(&REMOVE_TEXT_COMMAND, ())?;
1243            }
1244        }
1245        "deleteByDrag" => {
1246            // The drop target is taking over focus and the selection.
1247            editor.add_tags(&[SKIP_SELECTION_FOCUS_TAG.to_owned()]);
1248            editor.dispatch_command(&REMOVE_TEXT_COMMAND, ())?;
1249        }
1250        "deleteByCut" => {
1251            editor.dispatch_command(&REMOVE_TEXT_COMMAND, ())?;
1252        }
1253        "deleteContent" => {
1254            editor.dispatch_command(&DELETE_CHARACTER_COMMAND, false)?;
1255        }
1256        "deleteWordBackward" => {
1257            editor.dispatch_command(&DELETE_WORD_COMMAND, true)?;
1258        }
1259        "deleteWordForward" => {
1260            editor.dispatch_command(&DELETE_WORD_COMMAND, false)?;
1261        }
1262        "deleteHardLineBackward" | "deleteSoftLineBackward" => {
1263            editor.dispatch_command(&DELETE_LINE_COMMAND, true)?;
1264        }
1265        "deleteContentForward" | "deleteHardLineForward" | "deleteSoftLineForward" => {
1266            // JS deletes one character instead when the target range lay
1267            // before a caret in a slot (#9363); there are no target ranges
1268            // here, and an app sets the selection to the range it deletes.
1269            editor.dispatch_command(&DELETE_LINE_COMMAND, false)?;
1270        }
1271        "formatStrikeThrough" => {
1272            editor.dispatch_command(&FORMAT_TEXT_COMMAND, "strikethrough".to_owned())?;
1273        }
1274        "formatBold" => {
1275            editor.dispatch_command(&FORMAT_TEXT_COMMAND, "bold".to_owned())?;
1276        }
1277        "formatItalic" => {
1278            editor.dispatch_command(&FORMAT_TEXT_COMMAND, "italic".to_owned())?;
1279        }
1280        "formatUnderline" => {
1281            editor.dispatch_command(&FORMAT_TEXT_COMMAND, "underline".to_owned())?;
1282        }
1283        "historyUndo" => {
1284            editor.dispatch_command(&UNDO_COMMAND, ())?;
1285        }
1286        "historyRedo" => {
1287            editor.dispatch_command(&REDO_COMMAND, ())?;
1288        }
1289        _ => {}
1290    }
1291    Ok(true)
1292}
1293
1294// The default composition handlers.
1295
1296/// `$handleCompositionStart(event)`: marks the anchor's node as the one
1297/// being composed, in an update tagged `composition-start`. JS also
1298/// prepares a text node for the browser to compose into (the empty space
1299/// heuristic, which inserts a placeholder character); an app writes the
1300/// marked text through the model, which makes one as typing does.
1301fn handle_composition_start(
1302    _event: &Rc<CompositionEvent>,
1303    editor: &Editor,
1304) -> Result<bool, LexicalError> {
1305    if let Some(range) = get_selection().and_then(|s| s.range())
1306        && !editor.is_composing()
1307    {
1308        set_composition_key(Some(&range.anchor.key));
1309        editor.add_tags(&[COMPOSITION_START_TAG.to_owned()]);
1310    }
1311    Ok(true)
1312}
1313
1314/// `$cleanupComposedSubclass(compositionKey)`: a composition that ended in
1315/// a plain-text subclass node it was redirected into (a segmented node made
1316/// normal) turns that node back into a `TextNode`.
1317fn cleanup_composed_subclass(
1318    editor: &Editor,
1319    composition_key: Option<&str>,
1320) -> Result<(), LexicalError> {
1321    let composed_segmented_key = editor
1322        .0
1323        .input_state
1324        .borrow_mut()
1325        .composed_segmented_key
1326        .take();
1327    let Some(composition_key) = composition_key else {
1328        return Ok(());
1329    };
1330    if composed_segmented_key.as_deref() != Some(composition_key) {
1331        return Ok(());
1332    }
1333    let Some(composed_node) = get_node_by_key(composition_key) else {
1334        return Ok(());
1335    };
1336    if !composed_node.is_text()
1337        || composed_node.get_type() == "text"
1338        || is_token_or_segmented(&composed_node)
1339        || !composed_node.is_attached()
1340    {
1341        return Ok(());
1342    }
1343    let offset = get_selection()
1344        .and_then(|s| s.range())
1345        .filter(|r| r.anchor.key == composition_key)
1346        .map(|r| r.anchor.offset);
1347    let replacement = create_text_node(&composed_node.get_text_content());
1348    replacement.set_format(composed_node.text_data().get_format());
1349    replacement.set_style(composed_node.text_data().get_style());
1350    composed_node.replace(&replacement, false)?;
1351    if let Some(offset) = offset {
1352        let safe_offset = offset.min(replacement.get_text_content_size());
1353        replacement.select(Some(safe_offset), Some(safe_offset))?;
1354    }
1355    Ok(())
1356}
1357
1358/// `$onCompositionEndImpl(editor, data)`. The composed text is already in
1359/// the model (the app writes the marked text through it), so where JS
1360/// reads it back from the DOM (`$updateTextNodeFromDOMContent`,
1361/// `$updateSelectedTextFromDOM`) there is nothing left to do.
1362fn on_composition_end_impl(editor: &Editor, data: Option<&str>) -> Result<bool, LexicalError> {
1363    let composition_key = editor.composition_key();
1364    set_composition_key(None);
1365
1366    // Handle termination of composition.
1367    if let (Some(key), Some(data)) = (composition_key.as_deref(), data) {
1368        if data.is_empty() {
1369            cleanup_composed_subclass(editor, Some(key))?;
1370            return Ok(false);
1371        }
1372        if data.ends_with('\n')
1373            && let Some(selection) = get_selection()
1374        {
1375            // If the last character is a line break, we also need to insert
1376            // a line break.
1377            if let Some(range) = selection.range() {
1378                let focus = range.focus;
1379                selection.point_set(Which::Anchor, &focus.key, focus.offset, focus.point_type)?;
1380            }
1381            editor.dispatch_command(&KEY_ENTER_COMMAND, None)?;
1382            cleanup_composed_subclass(editor, Some(key))?;
1383            return Ok(false);
1384        }
1385        // When composition ends on a token node, the composed text goes
1386        // beside it, through insertText's token redirect.
1387        if let Some(node) = get_node_by_key(key).filter(NodeRef::is_text)
1388            && is_token_or_segmented(&node)
1389        {
1390            node.mark_dirty();
1391            let text_len = node.get_text_content_size();
1392            let offset = get_selection()
1393                .and_then(|s| s.range())
1394                .filter(|r| r.anchor.key == key)
1395                .map_or(text_len, |r| r.anchor.offset);
1396            node.select(Some(offset), Some(offset))?.insert_text(data)?;
1397            return Ok(true);
1398        }
1399    }
1400    cleanup_composed_subclass(editor, composition_key.as_deref())?;
1401    Ok(false)
1402}
1403
1404/// `$handleCompositionEnd(event)`: ends the composition, in an update
1405/// tagged `composition-end`.
1406fn handle_composition_end(
1407    event: &Rc<CompositionEvent>,
1408    editor: &Editor,
1409) -> Result<bool, LexicalError> {
1410    on_composition_end_impl(editor, Some(&event.data))?;
1411    editor.add_tags(&[COMPOSITION_END_TAG.to_owned()]);
1412    Ok(true)
1413}
1414
1415/// `registerDefaultCommandHandlers(editor)`: the handlers every editor has,
1416/// which `createEditor` registers. JS's `INPUT_COMMAND` handler
1417/// (`$handleInput`) reads what the browser wrote to the DOM, which an app
1418/// never does, so it isn't registered.
1419pub(crate) fn register_default_command_handlers(editor: &Editor) -> Unregister {
1420    let unregisters = [
1421        editor.register_command(
1422            &BEFORE_INPUT_COMMAND,
1423            handle_before_input,
1424            COMMAND_PRIORITY_EDITOR,
1425        ),
1426        editor.register_command(
1427            &COMPOSITION_START_COMMAND,
1428            handle_composition_start,
1429            COMMAND_PRIORITY_EDITOR,
1430        ),
1431        editor.register_command(
1432            &COMPOSITION_END_COMMAND,
1433            handle_composition_end,
1434            COMMAND_PRIORITY_EDITOR,
1435        ),
1436        editor.register_command(&KEY_DOWN_COMMAND, handle_key_down, COMMAND_PRIORITY_EDITOR),
1437    ];
1438    Box::new(move || {
1439        for unregister in unregisters {
1440            unregister();
1441        }
1442    })
1443}
1444
1445#[cfg(test)]
1446mod tests {
1447    use super::*;
1448
1449    #[test]
1450    fn data_by_format_in_order() {
1451        let data_transfer = DataTransfer::new();
1452        data_transfer.set_data("text/html", "");
1453        data_transfer.set_data("Text", "plain");
1454        data_transfer.set_data("text/html", "<b>x</b>");
1455        assert_eq!(data_transfer.types(), ["text/html", "text/plain"]);
1456        assert_eq!(data_transfer.get_data("text/plain"), "plain");
1457        assert_eq!(data_transfer.get_data("TEXT/HTML"), "<b>x</b>");
1458        assert_eq!(data_transfer.get_data("URL"), "");
1459        data_transfer.set_files(vec![DataTransferFile::new(
1460            "a.txt",
1461            "text/plain",
1462            b"a".to_vec(),
1463        )]);
1464        assert_eq!(data_transfer.types(), ["text/html", "text/plain", "Files"]);
1465        assert_eq!(data_transfer.files()[0].bytes().unwrap(), b"a");
1466        data_transfer.clear_data(Some("text"));
1467        assert_eq!(data_transfer.types(), ["text/html", "Files"]);
1468        data_transfer.clear_data(None);
1469        assert_eq!(data_transfer.types(), ["Files"]);
1470        assert_eq!(data_transfer.drop_effect(), "none");
1471        assert_eq!(data_transfer.effect_allowed(), "uninitialized");
1472    }
1473
1474    struct Root;
1475    impl crate::RootElement for Root {}
1476
1477    /// `onSelectionChange` against what JS does with a DOM selection at the
1478    /// same points: a caret in bold text takes bold and the text's style, a
1479    /// range over bold and plain text takes no format (and keeps the
1480    /// style), an empty boundary node is left out, and each change is
1481    /// announced once; a selection made where it already was isn't.
1482    #[test]
1483    fn selection_change_sets_points_format_and_notifies() {
1484        use crate::lexical_selection::Selection;
1485        // "bold" (bold, red) then "plain", in one paragraph.
1486        const STATE: &str = r#"{"root":{"children":[{"children":[{"detail":0,"format":1,"mode":"normal","style":"color: red","text":"bold","type":"text","version":1},{"detail":0,"format":0,"mode":"normal","style":"","text":"plain","type":"text","version":1}],"direction":null,"format":"","indent":0,"textFormat":0,"textStyle":"","type":"paragraph","version":1}],"direction":null,"format":"","indent":0,"type":"root","version":1}}"#;
1487        let editor = crate::create_editor(crate::CreateEditorArgs::default());
1488        editor
1489            .set_root_element(Some(crate::RootElementRef(Rc::new(Root))))
1490            .unwrap();
1491        let state = editor.parse_editor_state(STATE).unwrap();
1492        editor.set_editor_state(&state, None).unwrap();
1493        let notified = Rc::new(Cell::new(0));
1494        let n = notified.clone();
1495        let _unregister = editor.register_command(
1496            &crate::commands::SELECTION_CHANGE_COMMAND,
1497            move |_, _| {
1498                n.set(n.get() + 1);
1499                Ok(false)
1500            },
1501            COMMAND_PRIORITY_EDITOR,
1502        );
1503        let (bold, plain) = editor
1504            .read(|| {
1505                let p = crate::get_root().get_first_child().unwrap();
1506                let bold = p.get_first_child().unwrap();
1507                let plain = bold.get_next_sibling().unwrap();
1508                (bold.get_key().to_owned(), plain.get_key().to_owned())
1509            })
1510            .unwrap();
1511        let text = |key: &str, offset| crate::Point::new(key, offset, crate::PointType::Text);
1512        let range = |editor: &Editor| {
1513            editor
1514                .read(|| match get_selection().map(|s| s.get()) {
1515                    Some(Selection::Range(r)) => r,
1516                    _ => panic!("no range selection"),
1517                })
1518                .unwrap()
1519        };
1520
1521        on_selection_change(&editor, Some((text(&bold, 2), text(&bold, 2))), true).unwrap();
1522        let caret = range(&editor);
1523        assert_eq!((caret.format, caret.style.as_str()), (1.0, "color: red"));
1524        assert_eq!(caret.anchor, text(&bold, 2));
1525        assert_eq!(notified.get(), 1);
1526
1527        // The same caret again: nothing changed, nothing is announced.
1528        on_selection_change(&editor, Some((text(&bold, 2), text(&bold, 2))), true).unwrap();
1529        assert_eq!(notified.get(), 1);
1530
1531        // Bold and plain text: no format they share; the style is kept.
1532        on_selection_change(&editor, Some((text(&bold, 1), text(&plain, 2))), true).unwrap();
1533        let mixed = range(&editor);
1534        assert_eq!((mixed.format, mixed.style.as_str()), (0.0, "color: red"));
1535        assert_eq!(notified.get(), 2);
1536
1537        // Backward, from the start of "plain" (an empty boundary) into
1538        // "bold": only bold text is covered.
1539        on_selection_change(&editor, Some((text(&plain, 0), text(&bold, 1))), true).unwrap();
1540        assert_eq!(range(&editor).format, 1.0);
1541        assert_eq!(notified.get(), 3);
1542
1543        // Another editor took the selection.
1544        on_selection_change(&editor, Some((text(&bold, 1), text(&bold, 1))), false).unwrap();
1545        assert!(editor.read(get_selection).unwrap().is_none());
1546    }
1547}