Skip to main content

lexical_ui/menu/
mod.rs

1//! The typeahead and node menus of `@lexical/react` without their views
2//! (the `menu` feature): `LexicalTypeaheadMenuPluginUtils.ts`
3//! ([`PUNCTUATION`], [`basic_typeahead_trigger_match`]),
4//! `LexicalMenuOption.ts` ([`MenuOption`]), and the platform-neutral parts
5//! of `shared/LexicalMenu.tsx` ([`MenuTextMatch`], [`MenuResolution`],
6//! [`get_full_match_offset`], [`split_node_containing_query`], the menu's
7//! state and option selection, [`MenuState`]),
8//! `LexicalTypeaheadMenuPlugin.tsx` ([`get_text_up_to_anchor`],
9//! [`is_selection_on_entity_boundary`], [`register_typeahead_menu`]) and
10//! `LexicalNodeMenuPlugin.tsx` ([`NodeMenu`]).
11//!
12//! The app's view draws the menu: it reads [`MenuState`] (its
13//! [`resolution`](MenuState::resolution), options and highlighted index)
14//! and places it at the resolution's model range, where JS positions an
15//! anchor `div` at a DOM `Range`'s rect (`tryToPositionRange`).
16//!
17//! While a menu is open it handles the keys the core's keydown handler
18//! dispatches, at its `commandPriority`: the up and down arrows move the
19//! highlight, wrapping around, and dispatch
20//! [`SCROLL_TYPEAHEAD_OPTION_INTO_VIEW_COMMAND`] for the view to scroll to
21//! it; Escape closes the menu; Tab and Enter (not Shift+Enter) choose the
22//! highlighted option.
23//!
24//! Not ported: an `onClose` that returns a promise; and the React
25//! rendering, the anchor element and its scroll handling (rust/PARITY.md).
26
27mod lexical_typeahead_menu_plugin_utils;
28
29pub use lexical_typeahead_menu_plugin_utils::{
30    PUNCTUATION, SCROLL_TYPEAHEAD_OPTION_INTO_VIEW_COMMAND, ScrollTypeaheadOptionIntoViewPayload,
31    TypeaheadTriggerOptions, basic_typeahead_trigger_match,
32};
33
34use crate::commands::{
35    KEY_ARROW_DOWN_COMMAND, KEY_ARROW_UP_COMMAND, KEY_ENTER_COMMAND, KEY_ESCAPE_COMMAND,
36    KEY_TAB_COMMAND,
37};
38use crate::editor::COMMAND_PRIORITY_LOW;
39use crate::events::KeyboardEvent;
40use crate::lexical_selection::{PointType, RangeSelection, get_selection};
41use crate::merge_register::merge_register;
42use crate::{Editor, LexicalError, NodeKey, NodeRef, Unregister, UpdateOptions, utf16};
43use std::cell::RefCell;
44use std::rc::Rc;
45
46/// `MenuTextMatch`: where a trigger matched the text before the caret: the
47/// `leadOffset` (UTF-16) where the match starts, the query after the
48/// trigger (`matchingString`), and the text, trigger included, that an
49/// option replaces (`replaceableString`).
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct MenuTextMatch {
52    pub lead_offset: usize,
53    pub matching_string: String,
54    pub replaceable_string: String,
55}
56
57/// `TriggerFn`: the match of the text before the caret that opens a menu.
58pub type TriggerFn = Rc<dyn Fn(&str, &Editor) -> Option<MenuTextMatch>>;
59
60/// `MenuOption`: an item of a typeahead or node menu, with a unique key.
61/// JS's `ref` and `icon` belong to the view that draws the option.
62pub trait MenuOption {
63    /// `key`.
64    fn key(&self) -> &str;
65    /// `title`: the text the menu shows for the option.
66    fn title(&self) -> Option<&str> {
67        None
68    }
69}
70
71/// `MenuResolution`: what an open menu is anchored at. JS carries a
72/// `getRect` over a DOM `Range`; here the anchor is the model range from
73/// the trigger to the caret (`anchor_key`, UTF-16 offsets), which the view
74/// measures. A node menu has no match and anchors at its node.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct MenuResolution {
77    /// `match`.
78    pub text_match: Option<MenuTextMatch>,
79    /// The text node the range is in, or the node a node menu is for.
80    pub anchor_key: NodeKey,
81    pub start_offset: usize,
82    pub end_offset: usize,
83}
84
85/// `getFullMatchOffset(documentText, entryText, offset)`: walks back along
86/// the typed text and forward through the entry's text, to replace as much
87/// of what was typed as matches the entry. In UTF-16 code units.
88pub fn get_full_match_offset(document_text: &str, entry_text: &str, offset: usize) -> usize {
89    let document: Vec<u16> = document_text.encode_utf16().collect();
90    let entry: Vec<u16> = entry_text.encode_utf16().collect();
91    let mut trigger_offset = offset;
92    for i in offset..=entry.len() {
93        // `documentText.slice(-i)`: the whole text for 0.
94        let suffix = if i == 0 {
95            &document[..]
96        } else {
97            &document[document.len().saturating_sub(i)..]
98        };
99        if suffix == &entry[..i] {
100            trigger_offset = i;
101        }
102    }
103    trigger_offset
104}
105
106/// The anchor of a collapsed range selection in simple text, with the
107/// text before it: what `$splitNodeContainingQuery` and
108/// `getTextUpToAnchor` both read.
109fn anchor_text(selection: &RangeSelection) -> Option<(NodeRef, String)> {
110    let anchor = &selection.anchor;
111    if anchor.point_type != PointType::Text {
112        return None;
113    }
114    let anchor_node = anchor.get_node().ok()?;
115    if !anchor_node.is_simple_text() {
116        return None;
117    }
118    let text = utf16::slice(&anchor_node.get_text_content(), 0, anchor.offset);
119    Some((anchor_node, text))
120}
121
122/// `$splitNodeContainingQuery(match)`: splits the text node at the caret so
123/// the query, with its trigger, is a node of its own, and returns it;
124/// `None` without a collapsed range selection in simple text, or when the
125/// query starts before the node.
126pub fn split_node_containing_query(
127    text_match: &MenuTextMatch,
128) -> Result<Option<NodeRef>, LexicalError> {
129    let Some(selection) = get_selection().and_then(|s| s.range()) else {
130        return Ok(None);
131    };
132    if !selection.is_collapsed() {
133        return Ok(None);
134    }
135    let Some((anchor_node, text_content)) = anchor_text(&selection) else {
136        return Ok(None);
137    };
138    let selection_offset = selection.anchor.offset;
139    let character_offset = utf16::len(&text_match.replaceable_string);
140    let query_offset =
141        get_full_match_offset(&text_content, &text_match.matching_string, character_offset);
142    let Some(start_offset) = selection_offset.checked_sub(query_offset) else {
143        return Ok(None);
144    };
145    let parts = if start_offset == 0 {
146        anchor_node.split_text(&[selection_offset as i64])?
147    } else {
148        let mut parts = anchor_node.split_text(&[start_offset as i64, selection_offset as i64])?;
149        if parts.is_empty() {
150            parts
151        } else {
152            parts.split_off(1)
153        }
154    };
155    Ok(parts.into_iter().next())
156}
157
158/// `getTextUpToAnchor(selection)`: the text of the anchor's node before
159/// it, when the anchor is in simple text.
160pub fn get_text_up_to_anchor(selection: &RangeSelection) -> Option<String> {
161    anchor_text(selection).map(|(_, text)| text)
162}
163
164/// `isSelectionOnEntityBoundary(editor, offset)`: whether a match at
165/// `offset` 0 follows a text entity (a hashtag), in the editor's latest
166/// state.
167pub fn is_selection_on_entity_boundary(editor: &Editor, offset: usize) -> bool {
168    if offset != 0 {
169        return false;
170    }
171    editor.get_editor_state().read(|| {
172        get_selection()
173            .and_then(|s| s.range())
174            .and_then(|range| range.anchor.get_node().ok())
175            .and_then(|node| node.get_previous_sibling())
176            .is_some_and(|prev| prev.is_text() && prev.is_text_entity())
177    })
178}
179
180/// What a menu runs when an option is chosen (`onSelectOption`): the
181/// option, the text node holding the query (split off when the menu splits
182/// it), what closes the menu, and the query.
183pub type MenuSelectOption<O> =
184    Rc<dyn Fn(&Rc<O>, Option<NodeRef>, &dyn Fn(), &str) -> Result<(), LexicalError>>;
185
186struct MenuInner<O> {
187    resolution: Option<MenuResolution>,
188    options: Vec<Rc<O>>,
189    /// The highlighted index as set: -1 after an arrow key found no option
190    /// to highlight (JS's `updateSelectedIndex(-1)`).
191    selected_index: Option<isize>,
192    /// Whether the menu is open as far as `onOpen` and `onClose` are
193    /// concerned (`isOpenRef`).
194    is_open: bool,
195    /// Whether the view draws the menu with no options (JS's
196    /// `menuRenderFn`).
197    draws_empty_menu: bool,
198    /// What unregisters the keyboard commands while the menu is open.
199    unregister_commands: Option<Unregister>,
200    /// Counts the opens (`openGenerationRef`), so a close that waits for
201    /// `on_close_async` clears only the query it closed.
202    open_generation: u64,
203}
204
205/// An open or closed menu and its options: the state `LexicalMenu`,
206/// `LexicalTypeaheadMenuPlugin` and `LexicalNodeMenuPlugin` keep in React.
207/// The view that draws the menu is told of each change (`on_change`), and
208/// calls [`select_option_and_clean_up`](Self::select_option_and_clean_up)
209/// and [`set_highlighted_index`](Self::set_highlighted_index) for its input.
210/// Cloning it shares the menu.
211pub struct MenuState<O> {
212    editor: Editor,
213    inner: Rc<RefCell<MenuInner<O>>>,
214    command_priority: i8,
215    preselect_first_item: bool,
216    should_split_node_with_query: bool,
217    on_select_option: MenuSelectOption<O>,
218    callbacks: Rc<MenuCallbacks>,
219}
220
221impl<O> Clone for MenuState<O> {
222    fn clone(&self) -> Self {
223        self.with_editor(&self.editor)
224    }
225}
226
227impl<O> MenuState<O> {
228    /// The same menu, holding `editor`.
229    fn with_editor(&self, editor: &Editor) -> Self {
230        MenuState {
231            editor: editor.clone(),
232            inner: self.inner.clone(),
233            command_priority: self.command_priority,
234            preselect_first_item: self.preselect_first_item,
235            should_split_node_with_query: self.should_split_node_with_query,
236            on_select_option: self.on_select_option.clone(),
237            callbacks: self.callbacks.clone(),
238        }
239    }
240
241    /// The menu without its editor, which a keyboard command's listener
242    /// holds and makes the menu again from the editor it is dispatched in.
243    fn detach(&self) -> DetachedMenu<O> {
244        DetachedMenu {
245            inner: self.inner.clone(),
246            command_priority: self.command_priority,
247            preselect_first_item: self.preselect_first_item,
248            should_split_node_with_query: self.should_split_node_with_query,
249            on_select_option: self.on_select_option.clone(),
250            callbacks: self.callbacks.clone(),
251        }
252    }
253}
254
255/// A [`MenuState`] without its editor.
256struct DetachedMenu<O> {
257    inner: Rc<RefCell<MenuInner<O>>>,
258    command_priority: i8,
259    preselect_first_item: bool,
260    should_split_node_with_query: bool,
261    on_select_option: MenuSelectOption<O>,
262    callbacks: Rc<MenuCallbacks>,
263}
264
265impl<O> DetachedMenu<O> {
266    fn menu(&self, editor: &Editor) -> MenuState<O> {
267        MenuState {
268            editor: editor.clone(),
269            inner: self.inner.clone(),
270            command_priority: self.command_priority,
271            preselect_first_item: self.preselect_first_item,
272            should_split_node_with_query: self.should_split_node_with_query,
273            on_select_option: self.on_select_option.clone(),
274            callbacks: self.callbacks.clone(),
275        }
276    }
277}
278
279/// `onOpen(resolution)`.
280pub type OnOpen = Rc<dyn Fn(&MenuResolution)>;
281
282/// An `onClose` that returns a promise, given what settles it.
283pub type OnCloseAsync = Rc<dyn Fn(MenuCloseDone)>;
284
285/// `onQueryChange(matchingString)`.
286pub type OnQueryChange = Rc<dyn Fn(Option<&str>)>;
287
288/// What settles a close that [`MenuCallbacks::on_close_async`] waits for,
289/// as the promise JS's `onClose` returns does (`result.then(finish,
290/// finish)`): [`finish`](Self::finish) it, or drop it, and the menu clears
291/// unless it was opened again since.
292pub struct MenuCloseDone(Option<Box<dyn FnOnce()>>);
293
294impl MenuCloseDone {
295    /// The promise resolved.
296    pub fn finish(mut self) {
297        if let Some(finish) = self.0.take() {
298            finish();
299        }
300    }
301}
302
303impl Drop for MenuCloseDone {
304    fn drop(&mut self) {
305        if let Some(finish) = self.0.take() {
306            finish();
307        }
308    }
309}
310
311/// A menu's `onOpen`, `onClose`, and what the view hears of its changes.
312#[derive(Default)]
313pub struct MenuCallbacks {
314    /// `onOpen(resolution)`.
315    pub on_open: RefCell<Option<OnOpen>>,
316    /// `onClose()`.
317    pub on_close: RefCell<Option<Rc<dyn Fn()>>>,
318    /// An `onClose` that returns a promise (`LexicalTypeaheadMenuPlugin`'s
319    /// `onClose?: () => void | PromiseLike<void>`), called after
320    /// [`on_close`](Self::on_close) with what settles it: the menu stays
321    /// drawn, with its keys, until the app finishes the [`MenuCloseDone`]
322    /// (or drops it, as a promise that rejects), then clears unless a newer
323    /// query opened the menu meanwhile.
324    pub on_close_async: RefCell<Option<OnCloseAsync>>,
325    /// Called when the resolution, the options or the highlighted index
326    /// change, for the view to draw the menu again.
327    pub on_change: RefCell<Option<Rc<dyn Fn()>>>,
328}
329
330impl<O: MenuOption + 'static> MenuState<O> {
331    fn new(
332        editor: &Editor,
333        command_priority: i8,
334        preselect_first_item: bool,
335        should_split_node_with_query: bool,
336        on_select_option: MenuSelectOption<O>,
337    ) -> Self {
338        MenuState {
339            editor: editor.clone(),
340            inner: Rc::new(RefCell::new(MenuInner {
341                resolution: None,
342                options: Vec::new(),
343                selected_index: None,
344                is_open: false,
345                draws_empty_menu: false,
346                unregister_commands: None,
347                open_generation: 0,
348            })),
349            command_priority,
350            preselect_first_item,
351            should_split_node_with_query,
352            on_select_option,
353            callbacks: Rc::new(MenuCallbacks::default()),
354        }
355    }
356
357    /// The menu's `onOpen`, `onClose` and change callback.
358    pub fn callbacks(&self) -> &MenuCallbacks {
359        &self.callbacks
360    }
361
362    fn changed(&self) {
363        let on_change = self.callbacks.on_change.borrow().clone();
364        if let Some(on_change) = on_change {
365            on_change();
366        }
367    }
368
369    /// The resolution while the menu is open, which the view anchors it at.
370    pub fn resolution(&self) -> Option<MenuResolution> {
371        self.inner.borrow().resolution.clone()
372    }
373
374    /// The options (JS's `options` prop).
375    pub fn options(&self) -> Vec<Rc<O>> {
376        self.inner.borrow().options.clone()
377    }
378
379    /// The highlighted option's index, clamped to the options
380    /// (`Math.min(options.length - 1, selectedIndex)`); `None` when no
381    /// option is highlighted.
382    pub fn selected_index(&self) -> Option<usize> {
383        self.clamped_index()
384            .and_then(|index| usize::try_from(index).ok())
385    }
386
387    /// `selectedIndex` as `LexicalMenu` reads it: clamped, and -1 (or
388    /// below) when there is no option to highlight.
389    fn clamped_index(&self) -> Option<isize> {
390        let inner = self.inner.borrow();
391        let last = inner.options.len() as isize - 1;
392        inner.selected_index.map(|index| index.min(last))
393    }
394
395    /// The highlighted option, if any.
396    fn selected_option(&self) -> Option<Rc<O>> {
397        let index = self.selected_index()?;
398        self.inner.borrow().options.get(index).cloned()
399    }
400
401    /// The command priority its keyboard commands are registered at (JS's
402    /// `commandPriority`, `COMMAND_PRIORITY_LOW` by default).
403    pub fn command_priority(&self) -> i8 {
404        self.command_priority
405    }
406
407    /// Whether the view draws the menu even with no options, as a JS
408    /// `menuRenderFn` is called whatever the options are and may show a
409    /// "no results" panel. While it is false (the default renderer), an
410    /// empty menu draws nothing and its keys pass through to the editor
411    /// (`rendersNothing`).
412    pub fn set_draws_empty_menu(&self, draws_empty_menu: bool) {
413        self.inner.borrow_mut().draws_empty_menu = draws_empty_menu;
414    }
415
416    /// `rendersNothing`: the default renderer with no options.
417    fn renders_nothing(&self) -> bool {
418        let inner = self.inner.borrow();
419        !inner.draws_empty_menu && inner.options.is_empty()
420    }
421
422    /// Replaces the options (JS renders the menu with new `options`); an
423    /// open menu that preselects its first item highlights it.
424    pub fn set_options(&self, options: Vec<Rc<O>>) {
425        {
426            let mut inner = self.inner.borrow_mut();
427            inner.options = options;
428            if inner.selected_index.is_none()
429                && self.preselect_first_item
430                && inner.resolution.is_some()
431            {
432                inner.selected_index = Some(0);
433            }
434        }
435        self.changed();
436    }
437
438    /// `setHighlightedIndex(index)`.
439    pub fn set_highlighted_index(&self, index: Option<usize>) {
440        self.inner.borrow_mut().selected_index = index.map(|i| i as isize);
441        self.changed();
442    }
443
444    /// `openTypeahead(resolution)` / `openNodeMenu(resolution)`: a new query
445    /// highlights the first option again (`preselectFirstItem`).
446    fn open(&self, resolution: MenuResolution) {
447        let was_open = {
448            let mut inner = self.inner.borrow_mut();
449            let query = |r: &Option<MenuResolution>| {
450                r.as_ref()
451                    .and_then(|r| r.text_match.as_ref())
452                    .map(|m| m.matching_string.clone())
453            };
454            if self.preselect_first_item
455                && query(&inner.resolution)
456                    != resolution
457                        .text_match
458                        .as_ref()
459                        .map(|m| m.matching_string.clone())
460            {
461                inner.selected_index = Some(0);
462            }
463            inner.resolution = Some(resolution.clone());
464            // Track pending opens.
465            inner.open_generation += 1;
466            std::mem::replace(&mut inner.is_open, true)
467        };
468        if !was_open {
469            // A close still waiting for `on_close_async` kept the keys.
470            if self.inner.borrow().unregister_commands.is_none() {
471                self.register_commands();
472            }
473            let on_open = self.callbacks.on_open.borrow().clone();
474            if let Some(on_open) = on_open {
475                on_open(&resolution);
476            }
477        }
478        self.changed();
479    }
480
481    /// `closeTypeahead()` / `closeNodeMenu()`: `onClose`, then the menu is
482    /// cleared, or with [`on_close_async`](MenuCallbacks::on_close_async)
483    /// once what it is given is finished, unless the menu opened again.
484    pub fn close(&self) {
485        if !std::mem::replace(&mut self.inner.borrow_mut().is_open, false) {
486            return;
487        }
488        let open_generation = self.inner.borrow().open_generation;
489        let on_close = self.callbacks.on_close.borrow().clone();
490        if let Some(on_close) = on_close {
491            on_close();
492        }
493        let on_close_async = self.callbacks.on_close_async.borrow().clone();
494        match on_close_async {
495            Some(on_close_async) => {
496                let menu = self.clone();
497                on_close_async(MenuCloseDone(Some(Box::new(move || {
498                    menu.finish_close(open_generation)
499                }))));
500            }
501            None => self.finish_close(open_generation),
502        }
503    }
504
505    /// `finish()` in `closeTypeahead`: the menu is cleared unless it was
506    /// opened since the close.
507    fn finish_close(&self, open_generation: u64) {
508        let unregister_commands = {
509            let mut inner = self.inner.borrow_mut();
510            if inner.open_generation != open_generation {
511                return;
512            }
513            inner.resolution = None;
514            inner.selected_index = None;
515            inner.unregister_commands.take()
516        };
517        if let Some(unregister) = unregister_commands {
518            unregister();
519        }
520        self.changed();
521    }
522
523    /// The up and down arrows (`forward`): the next or previous option is
524    /// highlighted, wrapping around, and scrolled into view
525    /// ([`SCROLL_TYPEAHEAD_OPTION_INTO_VIEW_COMMAND`]); with no option to
526    /// highlight, none is. A menu that draws nothing lets the key go on.
527    fn move_highlight(&self, forward: bool, event: &KeyboardEvent) -> Result<bool, LexicalError> {
528        if self.renders_nothing() {
529            // There is nothing to move through, and no menu on screen, so
530            // the key has to reach whatever would otherwise move the caret.
531            return Ok(false);
532        }
533        let last = self.inner.borrow().options.len() as isize - 1;
534        let new_index = match self.clamped_index() {
535            None if forward => 0,
536            None => last,
537            Some(index) if forward => {
538                if index != last {
539                    index + 1
540                } else {
541                    0
542                }
543            }
544            Some(index) => {
545                if index != 0 {
546                    index - 1
547                } else {
548                    last
549                }
550            }
551        };
552        self.inner.borrow_mut().selected_index = Some(new_index);
553        let option = usize::try_from(new_index)
554            .ok()
555            .and_then(|index| self.inner.borrow().options.get(index).cloned());
556        let Some(option) = option else {
557            self.inner.borrow_mut().selected_index = Some(-1);
558            self.changed();
559            event.prevent_default();
560            return Ok(true);
561        };
562        self.editor.dispatch_command(
563            &SCROLL_TYPEAHEAD_OPTION_INTO_VIEW_COMMAND,
564            ScrollTypeaheadOptionIntoViewPayload {
565                index: new_index as usize,
566                option,
567            },
568        )?;
569        self.changed();
570        event.prevent_default();
571        Ok(true)
572    }
573
574    /// `LexicalMenu`'s keyboard commands, at the menu's command priority,
575    /// while it is open.
576    fn register_commands(&self) {
577        let priority = self.command_priority;
578        // Each listener holds the menu without its editor, so the editor's
579        // listeners don't keep the editor alive.
580        let (down, up, escape, tab, enter) = (
581            self.detach(),
582            self.detach(),
583            self.detach(),
584            self.detach(),
585            self.detach(),
586        );
587        let unregister = merge_register(vec![
588            self.editor.register_command(
589                &KEY_ARROW_DOWN_COMMAND,
590                move |event, editor| down.menu(editor).move_highlight(true, event),
591                priority,
592            ),
593            self.editor.register_command(
594                &KEY_ARROW_UP_COMMAND,
595                move |event, editor| up.menu(editor).move_highlight(false, event),
596                priority,
597            ),
598            self.editor.register_command(
599                &KEY_ESCAPE_COMMAND,
600                move |event, editor| {
601                    let menu = escape.menu(editor);
602                    if menu.renders_nothing() {
603                        // With nothing on screen there is no menu to dismiss.
604                        return Ok(false);
605                    }
606                    event.prevent_default();
607                    menu.close();
608                    Ok(true)
609                },
610                priority,
611            ),
612            self.editor.register_command(
613                &KEY_TAB_COMMAND,
614                move |event, editor| {
615                    let menu = tab.menu(editor);
616                    let Some(option) = menu.selected_option() else {
617                        return Ok(false);
618                    };
619                    event.prevent_default();
620                    menu.select_option_and_clean_up(&option)?;
621                    Ok(true)
622                },
623                priority,
624            ),
625            self.editor.register_command(
626                &KEY_ENTER_COMMAND,
627                move |event, editor| {
628                    let menu = enter.menu(editor);
629                    let Some(option) = menu.selected_option() else {
630                        return Ok(false);
631                    };
632                    // Shift+Enter must reach rich text's line break.
633                    if event.as_ref().is_some_and(|event| event.shift_key) {
634                        return Ok(false);
635                    }
636                    if let Some(event) = event {
637                        event.prevent_default();
638                    }
639                    menu.select_option_and_clean_up(&option)?;
640                    Ok(true)
641                },
642                priority,
643            ),
644        ]);
645        self.inner.borrow_mut().unregister_commands = Some(unregister);
646    }
647
648    /// `selectOptionAndCleanUp(option)`: in an update, splits off the query
649    /// (`$splitNodeContainingQuery`) for a typeahead menu, then runs
650    /// `onSelectOption`.
651    pub fn select_option_and_clean_up(&self, option: &Rc<O>) -> Result<(), LexicalError> {
652        let text_match = self.resolution().and_then(|r| r.text_match);
653        let (menu, option) = (self.clone(), option.clone());
654        self.editor.update(
655            move || {
656                let text_node_containing_query = match &text_match {
657                    Some(text_match) if menu.should_split_node_with_query => {
658                        split_node_containing_query(text_match)?
659                    }
660                    _ => None,
661                };
662                let close_menu = || menu.close();
663                (menu.on_select_option)(
664                    &option,
665                    text_node_containing_query,
666                    &close_menu,
667                    text_match
668                        .as_ref()
669                        .map_or("", |m| m.matching_string.as_str()),
670                )
671            },
672            UpdateOptions::default(),
673        )
674    }
675}
676
677/// `LexicalTypeaheadMenuPlugin`'s options besides its callbacks.
678#[derive(Clone, Copy, Debug)]
679pub struct TypeaheadMenuOptions {
680    /// `commandPriority` (`COMMAND_PRIORITY_LOW`): the priority of the
681    /// menu's keyboard commands.
682    pub command_priority: i8,
683    /// `preselectFirstItem` (true).
684    pub preselect_first_item: bool,
685    /// `ignoreEntityBoundary` (false): a match right after a text entity
686    /// opens the menu too.
687    pub ignore_entity_boundary: bool,
688}
689
690impl Default for TypeaheadMenuOptions {
691    fn default() -> Self {
692        TypeaheadMenuOptions {
693            command_priority: COMMAND_PRIORITY_LOW,
694            preselect_first_item: true,
695            ignore_entity_boundary: false,
696        }
697    }
698}
699
700/// `LexicalTypeaheadMenuPlugin`: after each update, opens the menu while
701/// `trigger_fn` matches the text before a collapsed caret in an editable
702/// editor (and not right after a text entity, unless
703/// `ignore_entity_boundary`), reports the query to `on_query_change`, and
704/// closes it otherwise; choosing an option replaces the query. Returns the
705/// menu and what unregisters it.
706pub fn register_typeahead_menu<O: MenuOption + 'static>(
707    editor: &Editor,
708    trigger_fn: TriggerFn,
709    on_query_change: OnQueryChange,
710    on_select_option: MenuSelectOption<O>,
711    options: TypeaheadMenuOptions,
712) -> (MenuState<O>, Unregister) {
713    let menu = MenuState::new(
714        editor,
715        options.command_priority,
716        options.preselect_first_item,
717        true,
718        on_select_option,
719    );
720    let listening = menu.clone();
721    let weak = editor.weak();
722    let unregister_update = editor.register_update_listener(move |_| {
723        let Some(editor) = weak.upgrade().map(Editor) else {
724            return;
725        };
726        let menu = &listening;
727        // `editor.read('latest', ...)`.
728        enum Next {
729            Close,
730            CloseUnlessComposing,
731            Open(MenuResolution),
732        }
733        let next = editor.get_editor_state().read(|| {
734            // Check if editor is in read-only mode
735            if !editor.is_editable() {
736                return Next::Close;
737            }
738            let Some(selection) = get_selection().and_then(|s| s.range()) else {
739                return Next::CloseUnlessComposing;
740            };
741            let Some(text) = get_text_up_to_anchor(&selection) else {
742                return Next::CloseUnlessComposing;
743            };
744            if !selection.is_collapsed() {
745                return Next::CloseUnlessComposing;
746            }
747            let text_match = trigger_fn(&text, &editor);
748            on_query_change(text_match.as_ref().map(|m| m.matching_string.as_str()));
749            match text_match {
750                Some(text_match)
751                    if options.ignore_entity_boundary
752                        || !is_selection_on_entity_boundary(&editor, text_match.lead_offset) =>
753                {
754                    // `tryToPositionRange`'s model half: the range from the
755                    // trigger to the caret.
756                    Next::Open(MenuResolution {
757                        start_offset: text_match.lead_offset,
758                        end_offset: selection.anchor.offset,
759                        anchor_key: selection.anchor.key.clone(),
760                        text_match: Some(text_match),
761                    })
762                }
763                _ => Next::CloseUnlessComposing,
764            }
765        });
766        match next {
767            Next::Close => menu.close(),
768            // `closeUnlessComposing()`.
769            Next::CloseUnlessComposing => {
770                if !editor.is_composing() {
771                    menu.close();
772                }
773            }
774            Next::Open(resolution) => menu.open(resolution),
775        }
776    });
777    let closing = menu.clone();
778    let unregister_editable = editor.register_editable_listener(move |is_editable| {
779        if !is_editable {
780            closing.close();
781        }
782    });
783    let unregister = merge_register(vec![unregister_update, unregister_editable]);
784    (menu, unregister)
785}
786
787/// `LexicalNodeMenuPlugin`: a menu anchored at the node `node_key`, open
788/// while it is set and the node exists; [`set_node_key`](Self::set_node_key)
789/// is the `nodeKey` prop.
790pub struct NodeMenu<O> {
791    menu: MenuState<O>,
792    node_key: Rc<RefCell<Option<NodeKey>>>,
793}
794
795impl<O> Clone for NodeMenu<O> {
796    fn clone(&self) -> Self {
797        NodeMenu {
798            menu: self.menu.clone(),
799            node_key: self.node_key.clone(),
800        }
801    }
802}
803
804impl<O: MenuOption + 'static> NodeMenu<O> {
805    /// A closed node menu that runs `on_select_option` for the chosen
806    /// option, with no query, whose keyboard commands are at
807    /// `command_priority` (JS's `commandPriority`, `COMMAND_PRIORITY_LOW`
808    /// by default).
809    pub fn new(
810        editor: &Editor,
811        on_select_option: MenuSelectOption<O>,
812        command_priority: i8,
813    ) -> Self {
814        NodeMenu {
815            menu: MenuState::new(editor, command_priority, true, false, on_select_option),
816            node_key: Rc::new(RefCell::new(None)),
817        }
818    }
819
820    /// The menu.
821    pub fn menu(&self) -> &MenuState<O> {
822        &self.menu
823    }
824
825    /// The `nodeKey` prop.
826    pub fn node_key(&self) -> Option<NodeKey> {
827        self.node_key.borrow().clone()
828    }
829
830    /// `positionOrCloseMenu()` for a new `nodeKey`: opens the menu at the
831    /// node when it exists, and closes it without a key.
832    pub fn set_node_key(&self, key: Option<NodeKey>) {
833        *self.node_key.borrow_mut() = key.clone();
834        let Some(key) = key else {
835            if self.menu.resolution().is_some() {
836                self.menu.close();
837            }
838            return;
839        };
840        let exists = self
841            .menu
842            .editor
843            .get_editor_state()
844            .read(|| crate::get_node_by_key(&key).is_some());
845        if exists && self.menu.resolution().is_none() {
846            self.menu.open(MenuResolution {
847                text_match: None,
848                anchor_key: key,
849                start_offset: 0,
850                end_offset: 0,
851            });
852        }
853    }
854}
855
856#[cfg(all(test, feature = "rich-text"))]
857mod tests {
858    //! The menu's keyboard commands, as `swift/Tests/LexicalMenuTests` checks
859    //! them (JS's are React hooks, which no vector records): the arrows move
860    //! the highlight, wrapping around, at the menu's priority; Enter and Tab
861    //! choose, Shift+Enter is left to rich text; Escape closes; an empty
862    //! menu that draws nothing lets the keys go on. And the typeahead's
863    //! closes: `closeUnlessComposing`, and an `onClose` that returns a
864    //! promise (`on_close_async`).
865    use super::*;
866    use crate::commands::KEY_TAB_COMMAND;
867    use crate::editor::COMMAND_PRIORITY_EDITOR;
868    use crate::{
869        CreateEditorArgs, create_editor, create_paragraph_node, create_text_node, get_root,
870        rich_text,
871    };
872    use std::cell::Cell;
873
874    struct Item(String);
875
876    impl MenuOption for Item {
877        fn key(&self) -> &str {
878            &self.0
879        }
880    }
881
882    struct Fixture {
883        editor: Editor,
884        menu: MenuState<Item>,
885        chosen: Rc<RefCell<Vec<String>>>,
886        _unregister: Vec<Unregister>,
887    }
888
889    impl Fixture {
890        /// A rich text editor with a `/` typeahead menu of the options
891        /// `a`, `b` and `c`, which removes the query of the option chosen.
892        fn new() -> Self {
893            let editor = create_editor(CreateEditorArgs {
894                nodes: rich_text::rich_text_nodes(),
895                ..CreateEditorArgs::default()
896            });
897            let rich_text = rich_text::register_rich_text(&editor);
898            let chosen = Rc::new(RefCell::new(Vec::new()));
899            let log = chosen.clone();
900            let (menu, unregister) = register_typeahead_menu::<Item>(
901                &editor,
902                basic_typeahead_trigger_match(
903                    "/",
904                    TypeaheadTriggerOptions {
905                        min_length: 0,
906                        allow_whitespace: true,
907                        ..TypeaheadTriggerOptions::default()
908                    },
909                ),
910                Rc::new(|_| {}),
911                Rc::new(move |option, query, close, _| {
912                    log.borrow_mut().push(option.key().to_owned());
913                    if let Some(query) = query {
914                        query.remove(false)?;
915                    }
916                    close();
917                    Ok(())
918                }),
919                TypeaheadMenuOptions::default(),
920            );
921            menu.set_options(
922                ["a", "b", "c"]
923                    .into_iter()
924                    .map(|key| Rc::new(Item(key.to_owned())))
925                    .collect(),
926            );
927            Fixture {
928                editor,
929                menu,
930                chosen,
931                _unregister: vec![rich_text, unregister],
932            }
933        }
934
935        /// Replaces the document with `text`, the caret at its end.
936        fn type_(&self, text: &str) {
937            let text = text.to_owned();
938            self.editor
939                .update(
940                    move || {
941                        let root = get_root();
942                        root.clear()?;
943                        let paragraph = create_paragraph_node();
944                        let node = create_text_node(&text);
945                        paragraph.append(std::slice::from_ref(&node))?;
946                        root.append(&[paragraph])?;
947                        node.select_end().map(|_| ())
948                    },
949                    UpdateOptions {
950                        discrete: true,
951                        ..UpdateOptions::default()
952                    },
953                )
954                .unwrap();
955        }
956
957        fn text(&self) -> String {
958            self.editor.read(|| get_root().get_text_content()).unwrap()
959        }
960
961        fn key(key: &str, shift_key: bool) -> Rc<KeyboardEvent> {
962            Rc::new(KeyboardEvent {
963                key: key.to_owned(),
964                code: key.to_owned(),
965                shift_key,
966                ..KeyboardEvent::default()
967            })
968        }
969    }
970
971    /// `closeUnlessComposing()`: while an input method composes, a caret
972    /// the trigger doesn't match (here, no selection) leaves the menu open;
973    /// a read-only editor closes it anyway.
974    #[test]
975    fn the_menu_stays_open_while_composing() {
976        let f = Fixture::new();
977        f.type_("/q");
978        assert!(f.menu.resolution().is_some());
979        let update = |compose: bool| {
980            f.editor
981                .update(
982                    move || {
983                        let text = get_root().get_first_descendant().unwrap();
984                        crate::set_composition_key(compose.then_some(text.get_key()));
985                        crate::set_selection(None);
986                        Ok(())
987                    },
988                    UpdateOptions {
989                        discrete: true,
990                        ..UpdateOptions::default()
991                    },
992                )
993                .unwrap()
994        };
995        update(true);
996        assert!(f.editor.is_composing());
997        assert!(f.menu.resolution().is_some());
998        update(false);
999        assert_eq!(f.menu.resolution(), None);
1000        f.type_("/q");
1001        update(true);
1002        f.editor.set_editable(false);
1003        assert_eq!(f.menu.resolution(), None);
1004    }
1005
1006    /// An `onClose` that returns a promise: the menu stays drawn, with its
1007    /// keys, until it settles, then clears unless it opened again.
1008    #[test]
1009    fn a_close_waits_for_on_close_async() {
1010        let f = Fixture::new();
1011        let log = Rc::new(RefCell::new(Vec::new()));
1012        let pending: Rc<RefCell<Vec<MenuCloseDone>>> = Rc::default();
1013        let (closed, waiting) = (log.clone(), pending.clone());
1014        *f.menu.callbacks().on_close.borrow_mut() =
1015            Some(Rc::new(move || closed.borrow_mut().push("onClose")));
1016        let closed = log.clone();
1017        *f.menu.callbacks().on_close_async.borrow_mut() = Some(Rc::new(move |done| {
1018            closed.borrow_mut().push("onCloseAsync");
1019            waiting.borrow_mut().push(done);
1020        }));
1021        f.type_("/q");
1022        f.editor
1023            .dispatch_command(&KEY_ESCAPE_COMMAND, Fixture::key("Escape", false))
1024            .unwrap();
1025        assert_eq!(*log.borrow(), ["onClose", "onCloseAsync"]);
1026        // Still drawn, and its keys still the menu's.
1027        assert!(f.menu.resolution().is_some());
1028        assert!(
1029            f.editor
1030                .dispatch_command(&KEY_ARROW_DOWN_COMMAND, Fixture::key("ArrowDown", false))
1031                .unwrap()
1032        );
1033        // Closing again does nothing until it opens again.
1034        f.menu.close();
1035        assert_eq!(log.borrow().len(), 2);
1036        pending.borrow_mut().pop().unwrap().finish();
1037        assert_eq!(f.menu.resolution(), None);
1038        assert!(
1039            !f.editor
1040                .dispatch_command(&KEY_ARROW_DOWN_COMMAND, Fixture::key("ArrowDown", false))
1041                .unwrap()
1042        );
1043        // A query opened before the close settles is kept, and a dropped
1044        // completion settles as a rejected promise does.
1045        f.type_("/q");
1046        f.menu.close();
1047        f.type_("/r");
1048        drop(pending.borrow_mut().pop().unwrap());
1049        assert!(f.menu.resolution().is_some());
1050        assert!(
1051            f.editor
1052                .dispatch_command(&KEY_ARROW_DOWN_COMMAND, Fixture::key("ArrowDown", false))
1053                .unwrap()
1054        );
1055        f.menu.close();
1056        drop(pending.borrow_mut().pop().unwrap());
1057        assert_eq!(f.menu.resolution(), None);
1058    }
1059
1060    // upstream: lexical-react/src/__tests__/unit/LexicalMenu.test.tsx::LexicalMenu > default rendering (without menuRenderFn) > should select an option when Enter is pressed without Shift
1061    // upstream: lexical-react/src/__tests__/unit/LexicalMenuEmptyOptions.test.tsx::LexicalMenu arrow keys with no options > still consumes ArrowUp when there are options
1062    #[test]
1063    fn arrows_wrap_and_enter_chooses() {
1064        let f = Fixture::new();
1065        f.type_("x /q");
1066        assert_eq!(f.menu.selected_index(), Some(0));
1067        let up = Fixture::key("ArrowUp", false);
1068        assert!(
1069            f.editor
1070                .dispatch_command(&KEY_ARROW_UP_COMMAND, up.clone())
1071                .unwrap()
1072        );
1073        assert!(up.default_prevented());
1074        assert_eq!(f.menu.selected_index(), Some(2));
1075        let scrolled = Rc::new(RefCell::new(Vec::new()));
1076        let log = scrolled.clone();
1077        let _scroll = f.editor.register_command(
1078            &SCROLL_TYPEAHEAD_OPTION_INTO_VIEW_COMMAND,
1079            move |payload, _| {
1080                log.borrow_mut()
1081                    .push((payload.index, payload.option.key().to_owned()));
1082                Ok(true)
1083            },
1084            crate::editor::COMMAND_PRIORITY_CRITICAL,
1085        );
1086        let down = || Fixture::key("ArrowDown", false);
1087        assert!(
1088            f.editor
1089                .dispatch_command(&KEY_ARROW_DOWN_COMMAND, down())
1090                .unwrap()
1091        );
1092        assert_eq!(f.menu.selected_index(), Some(0));
1093        f.editor
1094            .dispatch_command(&KEY_ARROW_DOWN_COMMAND, down())
1095            .unwrap();
1096        assert_eq!(
1097            *scrolled.borrow(),
1098            [(0, "a".to_owned()), (1, "b".to_owned())]
1099        );
1100        let enter = Fixture::key("Enter", false);
1101        assert!(
1102            f.editor
1103                .dispatch_command(&KEY_ENTER_COMMAND, Some(enter.clone()))
1104                .unwrap()
1105        );
1106        assert!(enter.default_prevented());
1107        assert_eq!(*f.chosen.borrow(), ["b"]);
1108        // The query, trigger included, was split off and removed.
1109        assert_eq!(f.text(), "x ");
1110        assert_eq!(f.menu.resolution(), None);
1111    }
1112
1113    // upstream: lexical-react/src/__tests__/unit/LexicalMenu.test.tsx::LexicalMenu > default rendering (without menuRenderFn) > should not select an option when Enter is pressed with Shift (line break / fall-through)
1114    #[test]
1115    fn tab_chooses_and_shift_enter_is_left_to_rich_text() {
1116        let f = Fixture::new();
1117        f.type_("/q");
1118        f.editor
1119            .dispatch_command(&KEY_ENTER_COMMAND, Some(Fixture::key("Enter", true)))
1120            .unwrap();
1121        assert!(f.chosen.borrow().is_empty());
1122        f.type_("/q");
1123        let tab = Fixture::key("Tab", false);
1124        assert!(
1125            f.editor
1126                .dispatch_command(&KEY_TAB_COMMAND, tab.clone())
1127                .unwrap()
1128        );
1129        assert!(tab.default_prevented());
1130        assert_eq!(*f.chosen.borrow(), ["a"]);
1131    }
1132
1133    // upstream: lexical-react/src/__tests__/unit/LexicalMenuEmptyOptions.test.tsx::LexicalMenu arrow keys with no options > lets ArrowDown through when there are no options
1134    // upstream: lexical-react/src/__tests__/unit/LexicalMenuEmptyOptions.test.tsx::LexicalMenu arrow keys with no options > still consumes ArrowDown when a custom renderer draws an empty menu
1135    #[test]
1136    fn escape_closes_and_keys_pass_through_when_closed_or_empty() {
1137        let f = Fixture::new();
1138        f.type_("/");
1139        assert!(
1140            f.editor
1141                .dispatch_command(&KEY_ESCAPE_COMMAND, Fixture::key("Escape", false))
1142                .unwrap()
1143        );
1144        assert_eq!(f.menu.resolution(), None);
1145        // Closed: the menu's commands are unregistered.
1146        assert!(
1147            !f.editor
1148                .dispatch_command(&KEY_TAB_COMMAND, Fixture::key("Tab", false))
1149                .unwrap()
1150        );
1151        f.type_("/z");
1152        // With no options nothing is drawn, so the keys are not the menu's.
1153        f.menu.set_options(Vec::new());
1154        let reached_editor = Rc::new(Cell::new(false));
1155        let reached = reached_editor.clone();
1156        let _fallback = f.editor.register_command(
1157            &KEY_ARROW_DOWN_COMMAND,
1158            move |_, _| {
1159                reached.set(true);
1160                Ok(false)
1161            },
1162            COMMAND_PRIORITY_EDITOR,
1163        );
1164        let down = Fixture::key("ArrowDown", false);
1165        assert!(
1166            !f.editor
1167                .dispatch_command(&KEY_ARROW_DOWN_COMMAND, down.clone())
1168                .unwrap()
1169        );
1170        assert!(reached_editor.get());
1171        assert!(!down.default_prevented());
1172        f.editor
1173            .dispatch_command(&KEY_ESCAPE_COMMAND, Fixture::key("Escape", false))
1174            .unwrap();
1175        assert!(f.menu.resolution().is_some());
1176        // A menu that draws an empty panel takes the arrows, with no option
1177        // to highlight.
1178        f.menu.set_draws_empty_menu(true);
1179        let down = Fixture::key("ArrowDown", false);
1180        assert!(
1181            f.editor
1182                .dispatch_command(&KEY_ARROW_DOWN_COMMAND, down.clone())
1183                .unwrap()
1184        );
1185        assert!(down.default_prevented());
1186        assert_eq!(f.menu.selected_index(), None);
1187    }
1188
1189    #[test]
1190    fn commands_are_at_the_menu_priority() {
1191        let f = Fixture::new();
1192        assert_eq!(f.menu.command_priority(), COMMAND_PRIORITY_LOW);
1193        f.type_("/q");
1194        // A handler above the menu's priority takes the key first.
1195        let _above = f.editor.register_command(
1196            &KEY_ARROW_DOWN_COMMAND,
1197            |_, _| Ok(true),
1198            crate::editor::COMMAND_PRIORITY_NORMAL,
1199        );
1200        f.editor
1201            .dispatch_command(&KEY_ARROW_DOWN_COMMAND, Fixture::key("ArrowDown", false))
1202            .unwrap();
1203        assert_eq!(f.menu.selected_index(), Some(0));
1204    }
1205}