Skip to main content

lexical_ui/
lexical_utils.rs

1//! `LexicalUtils.ts`: keys, node lookup, `getWritable` and the dirty marks
2//! it leaves for the update cycle.
3
4use crate::caret_tree::detach_node;
5use crate::constants::{LTR, RTL};
6use crate::editor::DirtyType;
7use crate::error::invariant;
8use crate::node::{LexicalNode, NodeKey, NodeRef};
9use crate::nodes::element::{Direction, is_root_or_shadow_root as is_root_or_shadow_root_node};
10use crate::nodes::paragraph::create_paragraph_node;
11use crate::updates::{
12    error_on_infinite_transforms, error_on_read_only, get_active_editor, get_active_editor_state,
13};
14use crate::{Editor, EditorState, LexicalError};
15use std::cell::Cell;
16use std::collections::{HashMap, HashSet};
17use std::rc::Rc;
18
19thread_local! {
20    static KEY_COUNTER: Cell<u64> = const { Cell::new(1) };
21}
22
23/// `getEditorsToPropagate(editor)`: the editor, then its parent editor,
24/// then that one's, up to an editor without one.
25pub(crate) fn get_editors_to_propagate(editor: &Editor) -> Vec<Editor> {
26    let mut editors_to_propagate = Vec::new();
27    let mut current_editor = Some(editor.clone());
28    while let Some(editor) = current_editor {
29        current_editor = editor.parent_editor().cloned();
30        editors_to_propagate.push(editor);
31    }
32    editors_to_propagate
33}
34
35/// `resetRandomKey()`: restarts the key counter, for deterministic keys in
36/// tests.
37pub fn reset_random_key() {
38    KEY_COUNTER.with(|c| c.set(1));
39}
40
41/// `createUID()`: five random lowercase letters, as JS takes them from
42/// `Math.random().toString(36)` (which can give fewer).
43pub(crate) fn create_uid() -> String {
44    use std::hash::{BuildHasher, Hasher};
45    let mut bits = std::collections::hash_map::RandomState::new()
46        .build_hasher()
47        .finish();
48    (0..5)
49        .map(|_| {
50            let letter = b'a' + (bits % 26) as u8;
51            bits /= 26;
52            char::from(letter)
53        })
54        .collect()
55}
56
57/// `generateRandomKey()`.
58pub(crate) fn generate_random_key() -> String {
59    KEY_COUNTER.with(|c| {
60        let key = c.get();
61        c.set(key + 1);
62        key.to_string()
63    })
64}
65
66pub(crate) fn get_node_by_key_impl(
67    editor_state: &EditorState,
68    key: &str,
69) -> Option<Rc<dyn LexicalNode>> {
70    editor_state.0.node_map.borrow().get(key).cloned()
71}
72
73/// `$getNodeByKey(key)`.
74pub fn get_node_by_key(key: &str) -> Option<NodeRef> {
75    get_node_by_key_impl(&get_active_editor_state(), key).map(|_| NodeRef::new(key))
76}
77
78/// `$getNodeByKeyOrThrow(key)`.
79pub(crate) fn get_node_by_key_or_throw(key: &str) -> Result<NodeRef, LexicalError> {
80    get_node_by_key(key).ok_or_else(|| {
81        LexicalError::new(format!(
82            "Expected node with key {key} to exist but it's not in the nodeMap."
83        ))
84    })
85}
86
87/// `$getRoot()`.
88pub fn get_root() -> NodeRef {
89    NodeRef::new("root")
90}
91
92/// `$isShadowRootNode(node)`.
93pub(crate) fn is_shadow_root_node(node: &NodeRef) -> bool {
94    let node = node.get_latest();
95    node.element().is_some() && node.is_shadow_root()
96}
97
98/// `INTERNAL_$isBlock(node)`: a `DecoratorNode` that is not inline, or an
99/// element that is not a root or shadow root, not inline, can be empty, and
100/// has no children or an inline first child.
101pub(crate) fn is_block(node: &NodeRef) -> bool {
102    if node.is_decorator() && !node.is_inline() {
103        return true;
104    }
105    if !node.is_element() || is_root_or_shadow_root_node(&*node.get_latest()) {
106        return false;
107    }
108    let is_leaf_element = node.get_first_child().is_none_or(|first| first.is_inline());
109    !node.is_inline() && node.can_be_empty() && is_leaf_element
110}
111
112/// `$removeFromParent(node)`: detaches the node without repairing the
113/// selection.
114pub(crate) fn remove_from_parent(node: &NodeRef) -> Result<(), LexicalError> {
115    if node.get_parent().is_some() {
116        get_writable(node.get_key());
117    }
118    detach_node(node)
119}
120
121/// `$restoreEmptyContainerParagraph(container, removedChild)`: appends an
122/// empty paragraph to a root or shadow root a removal left empty, and
123/// returns it.
124pub(crate) fn restore_empty_container_paragraph(
125    container: Option<&NodeRef>,
126    removed_child: Option<&NodeRef>,
127) -> Result<Option<NodeRef>, LexicalError> {
128    let Some(container) = container.filter(|c| is_root_or_shadow_root_node(&*c.get_latest()))
129    else {
130        return Ok(None);
131    };
132    // Root slots (such as footnotes) do not replace the editable body.
133    let has_content = if container.is_root() {
134        container.get_children_size() != 0
135    } else {
136        !container.is_empty()
137    };
138    if !container.is_attached()
139        || has_content
140        || !(container.is_root() || removed_child.is_some_and(is_block))
141    {
142        return Ok(None);
143    }
144    let paragraph = create_paragraph_node();
145    container.append(std::slice::from_ref(&paragraph))?;
146    Ok(Some(paragraph))
147}
148
149/// `$create(klass)`: a new node of the class `T`, with a key, in the active
150/// editor state; or, where the editor replaces the class
151/// ([`LexicalNodeReplacement`](crate::LexicalNodeReplacement)), a node of
152/// the class its `with_klass` chain ends at, or (for a replacement without
153/// `with_klass`) what its `with` makes of the new node. Where no editor
154/// registers `T` (outside an editor, or while parsing for one without it)
155/// the node is `T`'s, where JS throws.
156pub fn create<T: LexicalNode + Default>() -> NodeRef {
157    let node_type = T::default().get_type();
158    if let Some(editor) = crate::updates::get_registry_editor()
159        && let Ok(resolved) = editor.resolve_registered_node_after_replacements(node_type)
160        && let Some(class) = editor.get_registered_node(resolved)
161        && let Some(node) = class.construct()
162    {
163        // The resolve follows `withKlass` as far as it goes, so a `replace`
164        // still set on the class it stopped at is a deprecated one, whose
165        // `with` can only be given a constructed node.
166        return if class.replacement.is_some() {
167            replaced(node)
168        } else {
169            node
170        };
171    }
172    set_node_key(Box::new(T::default()))
173}
174
175/// `$applyNodeReplacement(node)`: what the active editor's replacement of
176/// the node's class (`{replace, with, withKlass}`) makes of the new node,
177/// or the node itself when the class has none. Fails as JS's invariants
178/// do: for a type the editor doesn't register, or a replacement that isn't
179/// of `withKlass` (or, without it, of a class extending the node's), or
180/// that kept the node's key.
181pub fn apply_node_replacement(node: &NodeRef) -> Result<NodeRef, LexicalError> {
182    let editor = crate::editor::get_editor();
183    let node_type = node.get_type();
184    let node_class_name = node.get_latest().class_name();
185    // `errorOnTypeKlassMismatch`, which JS's constructor runs on every node
186    // (in development, as the vectors were recorded): its type must be
187    // registered, and by its own class. Every node JS hands here was
188    // constructed, so it fails this before the invariant below.
189    let error_on_type_klass_mismatch = |node_type: &str, class_name: &str| {
190        match editor.get_registered_node(node_type) {
191            None => invariant!(
192                false,
193                "Create node: Attempted to create node {class_name} that was not configured to be used on the editor."
194            ),
195            Some(registered) => invariant!(
196                registered.class_name == class_name,
197                "Create node: Type {node_type} in node {class_name} does not match registered node {} with the same type",
198                registered.class_name
199            ),
200        }
201        Ok(())
202    };
203    if node_type != "root" {
204        error_on_type_klass_mismatch(node_type, node_class_name)?;
205    }
206    let Some(registered_node) = editor.get_registered_node(node_type) else {
207        return Err(LexicalError::new(format!(
208            "$applyNodeReplacement node {node_class_name} with type {node_type} must be registered to the editor. You can do this by passing the node class via the \"nodes\" array in the editor config."
209        )));
210    };
211    let Some(replacement) = registered_node.replacement else {
212        return Ok(node.clone());
213    };
214    let replacement_node = (replacement.with)(node)?;
215    let replacement_type = replacement_node.get_type();
216    let latest = replacement_node.get_latest();
217    let class_name = latest.class_name();
218    error_on_type_klass_mismatch(replacement_type, class_name)?;
219    let is_instance_of =
220        |base: &str| replacement_type == base || latest.super_types().contains(&base);
221    match &replacement.with_klass {
222        Some(with_klass) => invariant!(
223            is_instance_of(with_klass.node_type()),
224            "$applyNodeReplacement failed. Expected replacement node to be an instance of {} with type {} but returned {} with type {} from original node {} with type {}",
225            with_klass.class_name,
226            with_klass.node_type(),
227            class_name,
228            replacement_type,
229            node_class_name,
230            node_type
231        ),
232        None => invariant!(
233            replacement_type != node_type && is_instance_of(node_type),
234            "$applyNodeReplacement failed. Ensure replacement node {} with type {} is a subclass of the original node {} with type {}.",
235            class_name,
236            replacement_type,
237            node_class_name,
238            node_type
239        ),
240    }
241    invariant!(
242        replacement_node.get_key() != node.get_key(),
243        "$applyNodeReplacement failed. Ensure that the key argument is *not* used in your replace function (from node {} with type {} to node {} with type {}), Node keys must never be re-used except by the static clone method.",
244        node_class_name,
245        node_type,
246        class_name,
247        replacement_type
248    );
249    Ok(replacement_node)
250}
251
252/// `$applyNodeReplacement(node)` as the `$create*` functions call it: the
253/// node itself where no editor is active or the editor doesn't register its
254/// class (where JS throws), and a panic where a replacement breaks an
255/// invariant (a bug in the app's `with`, as a node implementation's would
256/// be).
257pub(crate) fn replaced(node: NodeRef) -> NodeRef {
258    let Some(editor) = crate::updates::get_registry_editor() else {
259        return node;
260    };
261    if editor
262        .get_registered_node(node.get_type())
263        .is_none_or(|class| class.replacement.is_none())
264    {
265        return node;
266    }
267    apply_node_replacement(&node).unwrap_or_else(|e| panic!("{e}"))
268}
269
270/// `$nodesOfType(klass)`, by the node type: the nodes of exactly that type
271/// in the active editor state, in its node map's order; in a state still
272/// being updated, only those attached to the root.
273pub fn nodes_of_type(node_type: &str) -> Vec<NodeRef> {
274    let editor_state = get_active_editor_state();
275    let read_only = editor_state.0.read_only.get();
276    let keys: Vec<String> = {
277        let node_map = editor_state.0.node_map.borrow();
278        editor_state
279            .keys_in_creation_order()
280            .into_iter()
281            .filter(|key| node_map[key].get_type() == node_type)
282            .collect()
283    };
284    keys.into_iter()
285        .map(NodeRef::new)
286        .filter(|node| read_only || node.is_attached())
287        .collect()
288}
289
290/// `$isTokenOrSegmented(node)`: whether a text node is in token or
291/// segmented mode.
292pub fn is_token_or_segmented(node: &NodeRef) -> bool {
293    node.is_token() || node.is_segmented()
294}
295
296/// `TypeToNodeMap`: an editor state's nodes by type, then by key.
297pub type TypeToNodeMap = HashMap<&'static str, HashMap<NodeKey, Rc<dyn LexicalNode>>>;
298
299/// `getCachedTypeToNodeMap(editorState)`: the nodes of a read-only editor
300/// state by type, computed once per state; an empty map for a writable
301/// state that is still empty. Panics for any other writable state, as JS's
302/// invariant throws.
303pub fn get_cached_type_to_node_map(editor_state: &EditorState) -> Rc<TypeToNodeMap> {
304    thread_local! {
305        static EMPTY_TYPE_TO_NODE_MAP: Rc<TypeToNodeMap> = Rc::default();
306    }
307    let read_only = editor_state.0.read_only.get();
308    if !read_only && editor_state.is_empty() {
309        return EMPTY_TYPE_TO_NODE_MAP.with(Rc::clone);
310    }
311    assert!(
312        read_only,
313        "getCachedTypeToNodeMap called with a writable EditorState"
314    );
315    editor_state
316        .0
317        .type_to_node_map
318        .borrow_mut()
319        .get_or_insert_with(|| {
320            let mut type_to_node_map = TypeToNodeMap::new();
321            for (key, node) in editor_state.0.node_map.borrow().iter() {
322                type_to_node_map
323                    .entry(node.get_type())
324                    .or_default()
325                    .insert(key.clone(), node.clone());
326            }
327            Rc::new(type_to_node_map)
328        })
329        .clone()
330}
331
332/// `getRegisteredSubtypeMap(nodes)`: each type of `nodes` to itself and the
333/// types of the classes of `nodes` that extend it.
334pub fn get_registered_subtype_map(
335    nodes: &[crate::NodeClass],
336) -> HashMap<&'static str, HashSet<&'static str>> {
337    let mut subtypes: HashMap<&'static str, HashSet<&'static str>> = nodes
338        .iter()
339        .map(|class| (class.node_type, HashSet::new()))
340        .collect();
341    for class in nodes {
342        for own_node_type in std::iter::once(class.node_type).chain((class.super_types)()) {
343            if let Some(bucket) = subtypes.get_mut(own_node_type) {
344                bucket.insert(class.node_type);
345            }
346        }
347    }
348    subtypes
349}
350
351/// `$getAdjacentNode(focus, isBackward)`: the node next to the point in the
352/// direction, or `None` at a boundary.
353pub fn get_adjacent_node(
354    focus: &crate::Point,
355    is_backward: bool,
356) -> Result<Option<NodeRef>, LexicalError> {
357    /// `resolveElement(element, isBackward, focusOffset)`.
358    fn resolve_element(
359        element: &NodeRef,
360        is_backward: bool,
361        focus_offset: usize,
362    ) -> Option<NodeRef> {
363        let parent = element.get_parent();
364        let mut offset = focus_offset;
365        let mut block = element.clone();
366        if let Some(parent) = parent {
367            if is_backward && focus_offset == 0 {
368                offset = block.get_index_within_parent().unwrap_or(0);
369                block = parent;
370            } else if !is_backward && focus_offset == block.get_children_size() {
371                offset = block.get_index_within_parent().unwrap_or(0) + 1;
372                block = parent;
373            }
374        }
375        if is_backward {
376            offset
377                .checked_sub(1)
378                .and_then(|i| block.get_child_at_index(i))
379        } else {
380            block.get_child_at_index(offset)
381        }
382    }
383    let focus_offset = focus.offset;
384    let focus_node = focus.get_node()?;
385    if focus.point_type == crate::PointType::Element {
386        return Ok(resolve_element(&focus_node, is_backward, focus_offset));
387    }
388    if (is_backward && focus_offset == 0)
389        || (!is_backward && focus_offset == focus_node.get_text_content_size())
390    {
391        let possible_node = if is_backward {
392            focus_node.get_previous_sibling()
393        } else {
394            focus_node.get_next_sibling()
395        };
396        if possible_node.is_none() {
397            let index = focus_node.get_index_within_parent().unwrap_or(0);
398            return Ok(resolve_element(
399                &focus_node.get_parent_or_throw()?,
400                is_backward,
401                index + usize::from(!is_backward),
402            ));
403        }
404        return Ok(possible_node);
405    }
406    Ok(None)
407}
408
409/// `$copyNode(node)`: a copy of the node with a new key and all its
410/// properties, but no parent, siblings or children, after
411/// `resetOnCopyNodeFrom`.
412pub fn copy_node(node: &NodeRef) -> NodeRef {
413    copy_node_with(node, false)
414}
415
416/// `$copyNode(node, skipReset)`: [`copy_node`], without
417/// `resetOnCopyNodeFrom` when `skip_reset` is true, so the copy keeps every
418/// property and state of the node.
419pub fn copy_node_with(node: &NodeRef, skip_reset: bool) -> NodeRef {
420    let mut copy = node.get_latest().clone_node();
421    let state = copy.base_mut().state.take();
422    *copy.base_mut() = crate::node::NodeBase::default();
423    if let Some(element) = copy.element_mut() {
424        element.first = None;
425        element.last = None;
426        element.size = 0;
427    }
428    let copy = set_node_key(copy);
429    // `afterCloneFrom` with another key, then `LexicalNode`'s
430    // `resetOnCopyNodeFrom`.
431    if let Some(state) = state {
432        let state = crate::node_state::copy_node_state(&state, copy.get_key(), skip_reset);
433        mutate(copy.get_key(), |n| n.base_mut().state = Some(state));
434    }
435    if !skip_reset {
436        copy.get_latest().reset_on_copy_node_from(&copy, node);
437    }
438    copy
439}
440
441/// `$isRootOrShadowRoot(node)`: whether the node is the root or a shadow
442/// root.
443pub fn is_root_or_shadow_root(node: &NodeRef) -> bool {
444    is_root_or_shadow_root_node(&*node.get_latest())
445}
446
447/// `$cloneWithProperties(latestNode)`: a clone of the node's latest version
448/// with the same key, links and properties, in no editor state. An editor
449/// state never sees it unless it is put there, so changing it changes no
450/// state.
451pub fn clone_with_properties(latest_node: &NodeRef) -> Rc<dyn LexicalNode> {
452    Rc::from(latest_node.get_latest().clone_node())
453}
454
455/// `$cloneWithPropertiesEphemeral(latestNode)`: a clone that can't join an
456/// editor state, for changing in place while serializing a slice. A clone
457/// from [`clone_with_properties`] is already outside every editor state, so
458/// it is the same clone.
459pub fn clone_with_properties_ephemeral(latest_node: &NodeRef) -> Rc<dyn LexicalNode> {
460    clone_with_properties(latest_node)
461}
462
463/// `$splitNode(node, offset)`: splits the element at its child `offset`
464/// and each ancestor up to the nearest root or shadow root, and returns the
465/// top of the left tree (`node`'s ancestor below the root, which keeps the
466/// children before the offset) and of the right tree (a copy, which gets
467/// the rest). The child at `offset` moves into the right tree; its ancestors
468/// are copied. An `offset` past the end splits after the last child. JS's
469/// return type lets the left be `null`; it never is.
470pub fn split_node(
471    node: &NodeRef,
472    offset: usize,
473) -> Result<(Option<NodeRef>, NodeRef), LexicalError> {
474    let start_node = node
475        .get_child_at_index(offset)
476        .unwrap_or_else(|| node.clone());
477    invariant!(
478        !is_root_or_shadow_root(node),
479        "Can not call $splitNode() on root element"
480    );
481    fn recurse(
482        current_node: &NodeRef,
483        start_node: &NodeRef,
484    ) -> Result<(NodeRef, NodeRef, NodeRef), LexicalError> {
485        let parent = current_node.get_parent_or_throw()?;
486        let is_parent_root = is_root_or_shadow_root(&parent);
487        // The node we start split from (leaf) is moved, but its recursive
488        // parents are copied to create separate tree
489        let node_to_move = if current_node == start_node && !is_parent_root {
490            current_node.clone()
491        } else {
492            copy_node(current_node)
493        };
494        if is_parent_root {
495            invariant!(
496                current_node.is_element() && node_to_move.is_element(),
497                "Children of a root must be ElementNode"
498            );
499            current_node.insert_after(&node_to_move, true)?;
500            Ok((current_node.clone(), node_to_move.clone(), node_to_move))
501        } else {
502            let (left_tree, right_tree, new_parent) = recurse(&parent, start_node)?;
503            let mut nodes = vec![node_to_move.clone()];
504            nodes.extend(current_node.get_next_siblings());
505            new_parent.append(&nodes)?;
506            Ok((left_tree, right_tree, node_to_move))
507        }
508    }
509    let (left_tree, right_tree, _) = recurse(&start_node, &start_node)?;
510    Ok((Some(left_tree), right_tree))
511}
512
513/// `$setNodeKey(node, null)`: gives a new node a key, puts it in the active
514/// editor state and marks it dirty.
515pub(crate) fn set_node_key(mut node: Box<dyn LexicalNode>) -> NodeRef {
516    error_on_read_only();
517    error_on_infinite_transforms();
518    let key = generate_random_key();
519    let editor_state = get_active_editor_state();
520    error_on_frozen_node_map(&editor_state, "set");
521    node.base_mut().key = key.clone();
522    node.base_mut().written_in = editor_state.0.id;
523    let is_element = node.element().is_some();
524    editor_state
525        .0
526        .node_map
527        .borrow_mut()
528        .insert(key.clone(), Rc::from(node));
529    if let Some(editor) = get_active_editor() {
530        editor.mark_dirty(&key, is_element);
531    }
532    NodeRef::new(key)
533}
534
535/// `internalMarkNodeAsDirty(node)`: marks the node's ancestors as dirty
536/// (unintentionally, `false`) up to the first one already marked, then the
537/// node itself.
538pub(crate) fn internal_mark_node_as_dirty(key: &str) {
539    error_on_infinite_transforms();
540    let Some(editor) = get_active_editor() else {
541        return;
542    };
543    let editor_state = get_active_editor_state();
544    let (parent, is_element) = {
545        let node_map = editor_state.0.node_map.borrow();
546        let node = node_map
547            .get(key)
548            .unwrap_or_else(|| panic!("internalMarkNodeAsDirty: node {key} does not exist"));
549        // A slotted node's up-link is its slot host: an edit in a slot
550        // dirties the host too.
551        let parent = node
552            .base()
553            .parent
554            .clone()
555            .or_else(|| crate::slot::slot_host_key_field(&**node).cloned());
556        (parent, node.element().is_some())
557    };
558    {
559        let node_map = editor_state.0.node_map.borrow();
560        let mut dirty = editor.0.dirty.borrow_mut();
561        // `internalMarkParentElementsAsDirty`.
562        let mut next_parent = parent;
563        while let Some(parent_key) = next_parent {
564            if dirty.elements.contains(&parent_key) {
565                break;
566            }
567            let Some(node) = node_map.get(&parent_key) else {
568                break;
569            };
570            dirty.elements.set(&parent_key, false);
571            next_parent = node
572                .base()
573                .parent
574                .clone()
575                .or_else(|| crate::slot::slot_host_key_field(&**node).cloned());
576        }
577        if dirty.dirty_type == DirtyType::None {
578            dirty.dirty_type = DirtyType::HasDirtyNodes;
579        }
580    }
581    editor.mark_dirty(key, is_element);
582}
583
584/// `internalMarkSiblingsAsDirty(node)`.
585pub(crate) fn internal_mark_siblings_as_dirty(node: &NodeRef) {
586    if let Some(previous) = node.get_previous_sibling() {
587        internal_mark_node_as_dirty(previous.get_key());
588    }
589    if let Some(next) = node.get_next_sibling() {
590        internal_mark_node_as_dirty(next.get_key());
591    }
592}
593
594/// `node.getWritable()`: marks the node dirty, and copies it into the
595/// active editor state if anything else (the previous editor state) shares
596/// it. Changes then go through [`mutate`].
597pub(crate) fn get_writable(key: &str) {
598    error_on_read_only();
599    if let Some(selection) = get_active_editor_state().0.selection.borrow().as_ref() {
600        selection.set_cached_nodes(None);
601    }
602    unshare(key);
603    internal_mark_node_as_dirty(key);
604}
605
606/// `handleDEVOnlyPendingUpdateGuarantees(editorState)`: a committed state's
607/// node map is frozen, so an update that goes on after a nested `read`
608/// committed it can't change it.
609fn error_on_frozen_node_map(editor_state: &EditorState, method: &str) {
610    if editor_state.0.read_only.get() {
611        panic!("Cannot call {method}() on a frozen Lexical node map");
612    }
613}
614
615fn unshare(key: &str) {
616    let editor_state = get_active_editor_state();
617    let mut node_map = editor_state.0.node_map.borrow_mut();
618    let node = node_map.get_mut(key).unwrap_or_else(|| {
619        panic!(
620            "Lexical node does not exist in active editor state (key {key}). The reference was probably kept from another read or update."
621        )
622    });
623    if Rc::get_mut(node).is_none() {
624        error_on_frozen_node_map(&editor_state, "set");
625        *node = Rc::from(node.clone_node());
626    }
627    // This version is the one of this update (JS's writable clone).
628    Rc::get_mut(node).expect("unshared").base_mut().written_in = editor_state.0.id;
629}
630
631/// Changes the fields of a node that [`get_writable`] already made writable
632/// in this update, as JS assigns to the fields of the writable node, without
633/// marking it dirty again.
634///
635/// `f` runs while the node map is borrowed, so it must only change the
636/// node's own fields, not read other nodes.
637pub(crate) fn mutate<R>(key: &str, f: impl FnOnce(&mut dyn LexicalNode) -> R) -> R {
638    error_on_read_only();
639    unshare(key);
640    let editor_state = get_active_editor_state();
641    let mut node_map = editor_state.0.node_map.borrow_mut();
642    let node = node_map.get_mut(key).expect("unshared above");
643    f(Rc::get_mut(node).expect("unshared above"))
644}
645
646/// `const self = node.getWritable(); f(self)`.
647pub(crate) fn with_writable<R>(key: &str, f: impl FnOnce(&mut dyn LexicalNode) -> R) -> R {
648    get_writable(key);
649    mutate(key, f)
650}
651
652/// `getTextDirection(text)`: the direction of the first strongly
653/// directional UTF-16 code unit in `text` (`RTL_REGEX`, then `LTR_REGEX`:
654/// `^[^LTR]*[RTL]` and `^[^RTL]*[LTR]`), or `None` when there is none.
655pub fn get_text_direction(text: &str) -> Option<Direction> {
656    let is_in =
657        |ranges: &[(u16, u16)], unit: u16| ranges.iter().any(|&(a, b)| a <= unit && unit <= b);
658    text.encode_utf16().find_map(|unit| {
659        if is_in(RTL, unit) {
660            Some(Direction::Rtl)
661        } else if is_in(LTR, unit) {
662            Some(Direction::Ltr)
663        } else {
664            None
665        }
666    })
667}
668
669/// `$setCompositionKey(compositionKey)`: the node an input method is
670/// composing in, or none. The previous and the new composition nodes are
671/// made writable, so they reconcile.
672pub fn set_composition_key(composition_key: Option<&str>) {
673    error_on_read_only();
674    let editor = get_active_editor().expect("an active editor");
675    let previous_composition_key = editor.composition_key();
676    if composition_key != previous_composition_key.as_deref() {
677        *editor.0.composition_key.borrow_mut() = composition_key.map(str::to_owned);
678        *editor.0.composition_merge_held.borrow_mut() = None;
679        if let Some(previous) = previous_composition_key
680            && let Some(node) = get_node_by_key(&previous)
681        {
682            get_writable(node.get_key());
683        }
684        if let Some(key) = composition_key
685            && let Some(node) = get_node_by_key(key)
686        {
687            get_writable(node.get_key());
688        }
689    }
690}
691
692/// `$getCompositionKey()`: the node an input method is composing in;
693/// always none in a read.
694pub fn get_composition_key() -> Option<NodeKey> {
695    if crate::updates::is_currently_read_only_mode() {
696        return None;
697    }
698    get_active_editor()?.composition_key()
699}
700
701/// `KeyboardEventModifiers`: a `KeyboardEvent`, or anything with its `key`,
702/// `code` and modifier fields.
703pub trait KeyboardEventModifiers {
704    fn key(&self) -> &str;
705    fn code(&self) -> &str;
706    fn alt_key(&self) -> bool;
707    fn ctrl_key(&self) -> bool;
708    fn meta_key(&self) -> bool;
709    fn shift_key(&self) -> bool;
710}
711
712/// The expected state of one modifier in a [`KeyboardEventModifierMask`]:
713/// JS's `true`, `false` (or omitted) and `'any'`.
714#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
715pub enum ModifierExpectation {
716    Pressed,
717    #[default]
718    Released,
719    Any,
720}
721
722impl ModifierExpectation {
723    fn matches(self, pressed: bool) -> bool {
724        match self {
725            ModifierExpectation::Any => true,
726            ModifierExpectation::Pressed => pressed,
727            ModifierExpectation::Released => !pressed,
728        }
729    }
730}
731
732impl From<bool> for ModifierExpectation {
733    fn from(pressed: bool) -> Self {
734        if pressed {
735            ModifierExpectation::Pressed
736        } else {
737            ModifierExpectation::Released
738        }
739    }
740}
741
742/// `KeyboardEventControlOrOther`'s `CONTROL_OR_OTHER_KEY`: the modifier
743/// that stands in for Control on the other platform.
744#[derive(Clone, Copy, Debug, PartialEq, Eq)]
745pub enum ControlOrOther {
746    MetaKey,
747    AltKey,
748}
749
750/// `KeyboardEventModifierMask` (with `KeyboardEventControlOrOther`): the
751/// expected state of each modifier; none pressed by default.
752#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
753pub struct KeyboardEventModifierMask {
754    pub alt_key: ModifierExpectation,
755    pub ctrl_key: ModifierExpectation,
756    pub meta_key: ModifierExpectation,
757    pub shift_key: ModifierExpectation,
758    /// `[CONTROL_OR_OTHER_KEY]`: set on `CONTROL_OR_META` (`MetaKey`) and
759    /// `CONTROL_OR_ALT` (`AltKey`).
760    pub control_or_other: Option<ControlOrOther>,
761}
762
763impl KeyboardEventModifierMask {
764    fn other(&mut self, other: ControlOrOther) -> &mut ModifierExpectation {
765        match other {
766            ControlOrOther::MetaKey => &mut self.meta_key,
767            ControlOrOther::AltKey => &mut self.alt_key,
768        }
769    }
770}
771
772/// `keyboardEventMaskForPlatform(mask, isApple)` (`@internal`): the mask as
773/// it is on the platform `is_apple` names, when it is a control-or-other
774/// mask made for the other one.
775pub fn keyboard_event_mask_for_platform(
776    mask: KeyboardEventModifierMask,
777    is_apple: bool,
778) -> KeyboardEventModifierMask {
779    match mask.control_or_other {
780        Some(other) if is_apple != crate::environment::is_apple() => {
781            let mut result = mask;
782            let mut source = mask;
783            result.ctrl_key = *source.other(other);
784            *result.other(other) = mask.ctrl_key;
785            result
786        }
787        _ => mask,
788    }
789}
790
791/// `isModifierMatch(event, mask)`: whether the event's modifiers are as the
792/// mask expects.
793pub fn is_modifier_match(
794    event: &impl KeyboardEventModifiers,
795    mask: &KeyboardEventModifierMask,
796) -> bool {
797    mask.alt_key.matches(event.alt_key())
798        && mask.ctrl_key.matches(event.ctrl_key())
799        && mask.shift_key.matches(event.shift_key())
800        && mask.meta_key.matches(event.meta_key())
801}
802
803/// `isExactShortcutMatch(event, expectedKey, mask)`: whether the event is
804/// `expected_key` (case-insensitive) with exactly the modifiers of `mask`,
805/// falling back to `event.code` for a single-character key on a non-Latin
806/// layout.
807pub fn is_exact_shortcut_match(
808    event: &impl KeyboardEventModifiers,
809    expected_key: &str,
810    mask: &KeyboardEventModifierMask,
811) -> bool {
812    if !is_modifier_match(event, mask) {
813        return false;
814    }
815    let key = event.key();
816    if key.to_lowercase() == expected_key.to_lowercase() {
817        // Special keys (Enter, Tab, ArrowUp...), and keys of an
818        // English-based layout.
819        return true;
820    }
821    if crate::utf16::len(expected_key) > 1 {
822        // A special key on another layout must not match by `event.code`.
823        return false;
824    }
825    if crate::utf16::len(key) == 1 && key.encode_utf16().next().is_some_and(|c| c <= 127) {
826        // An ASCII key must not match by `event.code`, which would break
827        // remapped layouts (Dvorak...).
828        return false;
829    }
830    let code = event.code();
831    // Fallback for number keys
832    if code.starts_with("Digit")
833        && expected_key.len() == 1
834        && expected_key.as_bytes()[0].is_ascii_digit()
835    {
836        return code == format!("Digit{expected_key}");
837    }
838    // Keys of a layout whose `event.key` isn't ASCII match by `event.code`.
839    code == format!("Key{}", expected_key.to_uppercase())
840}
841
842/// `isModifier(event)`: whether any modifier is down.
843pub fn is_modifier(event: &impl KeyboardEventModifiers) -> bool {
844    event.ctrl_key() || event.shift_key() || event.alt_key() || event.meta_key()
845}
846
847/// `isBackspace(event)`.
848pub fn is_backspace(event: &impl KeyboardEventModifiers) -> bool {
849    event.key() == "Backspace"
850}
851
852/// `isEscape(event)`.
853pub fn is_escape(event: &impl KeyboardEventModifiers) -> bool {
854    event.key() == "Escape"
855}
856
857/// `isDelete(event)`.
858pub fn is_delete(event: &impl KeyboardEventModifiers) -> bool {
859    event.key() == "Delete"
860}
861
862/// `isSelectAll(event)`: ⌘A on Apple platforms, Ctrl+A elsewhere.
863pub fn is_select_all(event: &impl KeyboardEventModifiers) -> bool {
864    is_exact_shortcut_match(event, "a", &crate::keyboard_shortcuts::control_or_meta())
865}