Expand description
A Rust port of Lexical’s model and headless
packages, at parity with the JS implementation: the same documents give
the same editor state and the same JSON, byte for byte, in the legacy and
compact forms. Parity is checked against the conformance vectors that
packages/lexical-conformance records from the JS packages (see
rust/PARITY.md).
The internals mirror the upstream sources file by file. JS’s $
functions drop the $ and take snake case: $getRoot() is
get_root(), and like JS they only work inside Editor::update,
Editor::read or EditorState::read. A node is read and changed
through a NodeRef, which resolves the latest version on every call,
as JS node methods do. Text offsets are UTF-16 code units, as in JS.
use lexical_ui::{create_editor, get_root, CreateEditorArgs, UpdateOptions};
let editor = create_editor(CreateEditorArgs::default());
let state = editor
.parse_editor_state(r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","text":"Hi"}]}]}}"#)
.unwrap();
assert_eq!(state.read(|| get_root().get_text_content()), "Hi");
assert_eq!(
state.to_json(true).to_string(),
r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","text":"Hi"}]}]}}"#,
);
// An update: split the text and bold the second half.
editor.set_editor_state(&state, None).unwrap();
editor
.update(
|| {
let text = get_root().get_first_descendant().unwrap();
let parts = text.split_text(&[1])?;
parts[1].toggle_format("bold");
Ok(())
},
UpdateOptions { discrete: true, ..UpdateOptions::default() },
)
.unwrap();
assert_eq!(
editor.get_editor_state().to_json(true).to_string(),
r#"{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","text":"H"},{"type":"text","format":1,"text":"i"}]}]}}"#,
);Re-exports§
pub use headless::create_headless_editor;pub use nodes::element::Direction;pub use nodes::element::ElementData;pub use nodes::paragraph::create_paragraph_node;pub use nodes::text::TextData;pub use nodes::text::create_text_node;pub use nodes::text::toggle_text_format_type;
Modules§
- a11y
@lexical/a11y’s announcements (thea11yfeature), frompackages/lexical-a11y/src/index.ts: the live region an editor announces through (LiveRegion, shown by the app’sLiveRegionHost),AriaLiveRegionExtension, whose output’sannouncethe other announcers write to,HistoryAnnounceExtensionandEditorModeAnnounceExtension. Withrich-text,@lexical/rich-text’sHeadingAnnounceExtensionisheading_announce_extension, and withlink,@lexical/link’sAutoLinkAnnounceExtensionisauto_link_announce_extension.- auto_
embed @lexical/react’s auto-embed without React (theauto-embedfeature):LexicalAutoEmbedPluginUtils.ts(EmbedMatchResult,EmbedConfig,URL_MATCHER,INSERT_EMBED_COMMAND,AutoEmbedOption) and the logic ofLexicalAutoEmbedPlugin.tsx(register_auto_embed): a pasted link that an embed config recognizes (a video, a post) opens a node menu at it that offers to replace it with the embed. React keeps the match in component state and rendersLexicalNodeMenuPlugin; hereregister_auto_embedkeeps it and drives aNodeMenu, which the app’s view draws.- clipboard
@lexical/clipboard(theclipboardfeature): the model half ofpackages/lexical-clipboard/src/clipboard.ts, with the default import stack ofClipboardImportExtension.tsthat$insertDataTransferForRichTextruns.- code
@lexical/code-core(thecodefeature), frompackages/lexical-code-core/src:CodeNodeandCodeHighlightNodewith their generated JSON (LexicalCodeCoreGeneratedJSON.ts),$exitCodeNodeOnEnter(CodeNode.ts), the line functions ofFlatStructureUtils.ts,CodeExtension’s transform (register_code) andregisterCodeIndentation’s command handlers, Tab, the arrow keys (escapeWithArrows),MOVE_TO_STARTandMOVE_TO_ENDamong them (register_code_indentation); with theextensionfeature,CodeExtensionandCodeIndentExtension(code_extension,code_indent_extension).- constants
LexicalConstants.ts: the flags and the tables between their serialized names and stored values. The DOM and platform constants come with the packages that use them.- decorator_
block @lexical/react’sDecoratorBlockNode(thedecorator-blockfeature), frompackages/lexical-react/src/LexicalDecoratorBlockNode.ts: the base of block embeds (videos, tweets), a block decorator that keeps an element alignment (format) and is not indentable.- devtools
@lexical/devtools-core(thedevtoolsfeature), frompackages/lexical-devtools-core/src:generate_content, the text of the playground’s tree view of an editor’s state, its selection and the editor’s settings. Its React parts (TreeView.tsx,useLexicalCommandsLog.ts) aren’t ported; a log of commands is the caller’s to keep (LexicalCommandLogEntry).- dom
- A small DOM (the
htmlfeature): what a browser, or jsdom in upstream’s unit tests, gives Lexical’screateDOM,exportDOMand HTML import and export. Nothing renders it; it exists so that HTML export and import run the same node methods as JS and write the same bytes, as the Swift port’sDOMDocumentdoes (swift/DESIGN.md, “The DOM is a small model of jsdom’s”). - extension
@lexical/extension’s decorators (theextensionfeature), frompackages/lexical-extension/src:HorizontalRuleNode, a block decorator (HorizontalRuleExtension.ts), andDecoratorTextNode, an inline one that carries a text format (DecoratorTextExtension.ts), with their$create/$isfunctions. Neither has a schema of its own, so their JSON isLexicalNode’s, withDecoratorTextNode’sformatas a flat NodeState.- file
@lexical/file(thefilefeature), frompackages/lexical-file/src: the.lexicaldocument format (serialized_document_from_editor_state,editor_state_from_serialized_document) and importing and exporting files (import_file,export_file), where the app picks and saves the file, as upstream’s DOM file input and download link do.- hashtag
@lexical/hashtag(thehashtagfeature), frompackages/lexical-hashtag/src:HashtagNode, the text entity a#hashtagbecomes,$createHashtagNode,$isHashtagNode, the default matcher (get_hashtag_match) andregister_lexical_hashtag, which makes hashtags of the text it matches withregister_lexical_text_entity. Its JSON isTextNode’s.- headless
@lexical/headless(packages/lexical-headless/src): an editor for use without a view, such as on a server, which refuses a root element.- history
@lexical/history(packages/lexical-history/src/index.ts): undo and redo.register_historyrecords the editor’s states on an undo stack, merging an update into the entry before it when it continues the same kind of change (typing, deleting) within a delay, and handlesUNDO_COMMAND,REDO_COMMAND,CLEAR_HISTORY_COMMANDandCLEAR_EDITOR_COMMAND, dispatchingCAN_UNDO_COMMANDandCAN_REDO_COMMANDas the stacks fill and empty.- html
@lexical/html(thehtmlfeature): HTML from an editor state (generate_html_from_nodes) and Lexical nodes from a DOM (generate_nodes_from_dom), through the nodes’exportDOMandimportDOMand the editor’shtmlconfig. The DOM iscrate::dom; parse HTML into it withcrate::dom::parse_from_string.- json
- JSON as JS reads and writes it:
JSON.parse,JSON.stringifywith JS’s property order and number formatting, andundefined. Lexical’s serialized documents must be byte-identical to what JS writes, whichserde_jsondoesn’t promise (key order,1e+21,-0), and the crate has no third-party dependencies (rust/DESIGN.md). - lexical_
dom - The DOM side of the core (the
htmlfeature): whatcreateDOM,exportDOMandimportDOMexchange (DOMExportOutput,DOMConversionMapand the rest,LexicalNode.tsandLexicalEditor.ts), the editor’s default render config (DEFAULT_EDITOR_DOM_CONFIG), the import conversion cache (initializeConversionCache), and the DOM helpers ofLexicalUtils.ts,utils/classNames.tsandnodes/LexicalLineBreakNode.tsthat nodes and@lexical/htmluse. The DOM iscrate::dom. - link
@lexical/link(thelinkfeature), frompackages/lexical-link/src:LinkNodeandAutoLinkNodewith their generated JSON (LexicalLinkGeneratedJSON.ts),$linkNodeTransform,$toggleLink,TOGGLE_LINK_COMMANDandformatUrl(LexicalLinkNode.ts), andregisterLink’s transform and command handlers, with the paste of a URLvalidateUrlaccepts (LexicalLinkExtension.ts); with theautolinkfeature,registerAutoLinkand its matchers (LexicalAutoLinkExtension.ts), whose regular expressions need theregexcrate.- list
@lexical/list(thelistfeature), frompackages/lexical-list/src:ListNodeandListItemNodewith their generated JSON (LexicalListGeneratedJSON.ts), the model functions offormatList.tsandutils.ts,registerList’s command handlers (Backspace at an item’s start among them) and transforms (register_list), and the model part ofregisterCheckList(register_check_list).- mark
@lexical/mark(themarkfeature), frompackages/lexical-mark/src:MarkNodewith its generated JSON (MarkNode.ts,LexicalMarkGeneratedJSON.ts),$wrapSelectionInMarkNode,$unwrapMarkNode,$getMarkIDsandMarkExtension(index.ts), andMarkStateExtension.ts, which keeps mark ids as a NodeState of the leaves they cover instead of wrapping them ($addMarkID,$removeMarkID,$getNodeMarkIDs,$getMarkIDsAtSelection,$migrateMarkNodesToMarkState; with theextensionfeature the mark flavors, their extensions and the inserted-text rule).- markdown
@lexical/markdown(themarkdownfeature), frompackages/lexical-markdown/src: markdown import ($convertFromMarkdownString), export ($convertToMarkdownString,$convertSelectionToMarkdownString), the transformers (MarkdownTransformers.ts) and the markdown shortcuts (registerMarkdownShortcuts).- menu
- The typeahead and node menus of
@lexical/reactwithout their views (themenufeature):LexicalTypeaheadMenuPluginUtils.ts(PUNCTUATION,basic_typeahead_trigger_match),LexicalMenuOption.ts(MenuOption), and the platform-neutral parts ofshared/LexicalMenu.tsx(MenuTextMatch,MenuResolution,get_full_match_offset,split_node_containing_query, the menu’s state and option selection,MenuState),LexicalTypeaheadMenuPlugin.tsx(get_text_up_to_anchor,is_selection_on_entity_boundary,register_typeahead_menu) andLexicalNodeMenuPlugin.tsx(NodeMenu). - nodes
nodes/: the core nodes every editor registers.- overflow
@lexical/overflow(theoverflowfeature), frompackages/lexical-overflow/src/index.ts:OverflowNode, the element@lexical/react’s character limit wraps the text past the limit in,$createOverflowNodeand$isOverflowNode. It has no schema of its own, so its JSON isElementNode’s.- plain_
text @lexical/plain-text(theplain-textfeature):registerPlainText’s command handlers that act on the model, frompackages/lexical-plain-text/src/index.ts.- rich_
text @lexical/rich-text(therich-textfeature):HeadingNodeandQuoteNode, frompackages/lexical-rich-text/src/index.ts, with their generated JSON (LexicalRichTextGeneratedJSON.ts).- schema
LexicalSchema.ts: serialization schemas. ASerializationSchemaparses an untrusted JSON value into its domain (substituting its default for anything outside it), knows that default, and describes its domain (SerializationSchemaMeta). A node class declares the properties of its JSON as aNodeSchema(nodeSchema) ofSchemaFields (withField,withAccessors), which drives itsexportJSONin both forms and itsupdateFromJSON(LexicalUtils.ts’ compiled schema,walk_export_jsonandwalk_update_from_json); a NodeState can be parsed by one (createState(key, {parse: schema}),StateValueConfig::from_schema).- selection
@lexical/selection(theselectionfeature): whatindex.tsexports fromlexical-node.ts,range-selection.tsand the model part ofutils.ts, and what it re-exports fromlexical(deprecated upstream).- table
@lexical/table(thetablefeature), frompackages/lexical-table/src:TableNode,TableRowNodeandTableCellNodewith their generated JSON,TableSelection, the table map utilities ofLexicalTableUtils.ts,INSERT_TABLE_COMMAND, and the model parts of the table handlers.- text
@lexical/text(thetextfeature), frompackages/lexical-text/src:register_lexical_text_entity, the transforms that make text entities (such as hashtags) of the text a matcher finds, and turn them back into text when an edit leaves them no match; and the root helpers (root_text_content,is_root_text_content_empty,can_show_placeholder,find_text_intersection_from_characters).- utf16
- Text offsets in UTF-16 code units, as JS strings count them, over Rust’s UTF-8 strings. A slice that splits a surrogate pair gives U+FFFD for the half it keeps, the Tier 1 exception for unpaired surrogates (rust/PARITY.md); it is still one unit long, so lengths and offsets agree with JS.
- utils
@lexical/utils(theutilsfeature): the model part ofpackages/lexical-utils/src/index.ts, and what it re-exports fromlexical.
Structs§
- Abort
Controller AbortController: what aborts anAbortSignal.- Abort
Signal AbortSignal, as the builder hands it toregister: aborted once, when the editor is disposed. Cloning it shares the signal.- AnyLexical
Extension Argument AnyLexicalExtensionArgument: an extension, alone or with config overrides (NormalizedLexicalExtensionArgument, whichconfig_extensionmakes). Every extension converts into one.- AnyState
Config AnyStateConfig: aStateConfigof any value type.- Caret
Range CaretRange: a range selection as a pair of carets in one direction.- Clipboard
Event - A DOM
ClipboardEvent: a copy, cut or paste, with its data. - Compiled
Keyboard Shortcuts CompiledKeyboardShortcuts(@experimental @internal): a shortcut table indexed by the event’s modifier bits andkey(and, for non-Latin layouts, itscode), so a look-up costs the same however many shortcuts it holds.- Composition
Event - A DOM
CompositionEvent: an input method composition starts or ends. - Create
Editor Args CreateEditorArgs: the node classes (andLexicalNodeReplacements, asNodeClasses) to register besides the core ones, the editor’snamespace(when empty, its parent editor’s, or a random one,createUID()), the initial state, whether it is editable, the theme, the parent editor,onWarn, and (with thehtmlfeature) the HTML import and export overrides and the render config. JS’sonErrorhas no counterpart: an update’s error is returned fromEditor::update.- Data
Transfer DataTransfer: the data of a clipboard or drag operation, by format (a MIME type), in the order each format was first set, and its files.- Data
Transfer File - One file of a
DataTransfer, as a webFile: its name, type and size are known up front, and its contents are read only whenbytesasks for them, asFile.bytes()reads a lazyBlob. - Declared
By - The class each key of a
DeclaredNodeStructurecame from, by type. - Declared
Node Structure DeclaredNodeStructure(@experimental node-structure): the structural facts a class declares, each from the nearest class in its config chain that declares it, and the values it declares derived. Keys no class declares areNone; amergeAdjacent: falsedeclaration reads asNonetoo.- Decorators
editor._decorators(Record<NodeKey, unknown>): what each decorator the reconciler rendered returned fromdecorate, by key, in the order JS’s object lists its keys (Object.entries): array-index keys ascending, which every generated key is, then the others in insertion order. A value is the app’sRc<dyn Any>, compared by identity (Rc::ptr_eq) as JS compares the object adecoratereturns (===).- Drag
Event - A DOM
DragEvent: a drag or a drop, with its data. - Editor
- A Lexical editor. A handle; cloning it shares the same editor. Without a
DOM it is what JS calls a headless editor. It is neither
SendnorSync. - Editor
Config EditorConfig(editor._config): whatcreateDOMreads.- Editor
State - An editor state: the node map and the selection. A handle; cloning it
shares the same state. Once read-only (committed or parsed), nothing
changes it: an update works on a clone whose node map shares the nodes,
and a node is copied before its first change (
getWritable). - Event
- The
Eventfields handlers use. Every event below holds one and dereferences to it, as the DOM’s event interfaces inherit fromEvent. Events are shared (Rc), so a handler’sprevent_default()is seen by the code that dispatched the event. - Extension
Build State ExtensionBuildState: whatbuildcan ask of the builder; its dependencies are built before it.- Extension
Init State ExtensionInitState: whatinitcan ask of the builder about other extensions, whose configs are merged before it runs.- Extension
Register State ExtensionRegisterState: whatregisterandafterRegistrationcan ask of the builder.- Focus
Event - A DOM
FocusEvent(focus,blur). - Initial
Editor Config InitialEditorConfig: the editor configuration an extension contributes, and whatinitmay change. Of JS’s fields, the ones the port has:namespace, the node classes and replacements,$initialEditorState,theme,parentEditor,editable,onWarn, and (with thehtmlfeature)htmlanddom.disableEventshas no counterpart (the app dispatches the events it has), nor hasonError(an update’s error is returned fromEditor::update).- Input
Event - A DOM
InputEvent: abeforeinputorinput. - Insert
Clipboard Nodes Payload SELECTION_INSERT_CLIPBOARD_NODES_COMMAND’s payload: the nodes a paste made and the selection to insert them at.- Keyboard
Event - A DOM
KeyboardEvent, with the DOM’skeyandcodevalues ("Enter","b","KeyB","ArrowLeft"…). - Keyboard
Event Modifier Mask KeyboardEventModifierMask(withKeyboardEventControlOrOther): the expected state of each modifier; none pressed by default.- Keyboard
Shortcut KeyboardShortcut(@experimental): a shortcut as data, the key and modifiers to match and the command to dispatch with the matched event.@lexical/extension’sKeyboardShortcutsExtension(keyboard_shortcuts_extension, theextensionfeature) dispatches a table of them.- Lexical
Command - A command (
createCommand), compared by identity: two commands made with the same name are different commands. - Lexical
Error - A JS
invariantfailure (or another error JS throws), carrying the same message. Invariants that only a bug in a node implementation can break panic instead, asRefCelldoes; the ones a document can break return this. - Lexical
Extension LexicalExtension: a composable, named unit of editor configuration (nodes, the initial state) and of behavior registered once the editor exists. Write one with struct update syntax overLexicalExtension::new, and make it withdefine_extension.- Lexical
Extension Dependency LexicalExtensionDependency: a built extension’s merged config, its init result and its output (Nonewithoutinitorbuild, JS’sundefined).- Lexical
Node Replacement LexicalNodeReplacement: an entry ofCreateEditorArgs::nodes(as aNodeClass, throughFrom) that makes$createand the$create*functions of thereplaceclass give whatwithmakes of their node.with_klass, the classwithmakes (which must extendreplaceand be registered too), lets transforms and mutation listeners registered forreplacereach its nodes.- Lexical
Warning LexicalWarning: a warning with a stable code, passed to the editor’sonWarn(as theLexicalErrorLexicalError::from_warningmakes, whosewarningit is) by packages that report recoverable, warn-level conditions. The code is namespaced by the package that reports it ("@example/pkg/some-condition"); amatchover codes needs a default arm, since packages may add codes in any release.- Merge
Adjacent Config MergeAdjacentConfig(@experimental node-structure).- Mouse
Event - A DOM
MouseEvent(and thePointerEventfields Lexical reads), with the node the app hit in place of the DOM target. - Mutation
Listener Options MutationListenerOptions.- Mutation
Listener Payload - A mutation listener’s second argument (
MutationListener’s{dirtyLeaves, prevEditorState, updateTags}). - Node
Base - The fields every node has: its key, its links to its parent and
siblings (
__key,__parent,__prev,__next) and its NodeState (__state), which a clone shares until one of them writes it; and, used by elements and decorators only, the slot fields JS’sElementNodeandDecoratorNodeadd (__slotHost,__slots). A clone keeps them, as theirafterCloneFromdoes for the same key;$copyNodedrops them. - Node
Class - A node class an editor registers: its type and how it imports JSON (the
static
importJSON). As an editor’s registration (RegisteredNode) it also holds the class’s node replacement, if any: whatLexicalNodeReplacementmakes of the class. - Node
Class Ref - A node class that a
childrenlist names: its type, and how to make a node of it ($create(klass), for the wrapper a list of classes wraps a stray child in). - Node
Config Link - One class of a config chain (
iterStaticNodeConfigChain’s{klass, ownNodeType, ownNodeConfig}). - NodeRef
- A node by its key, resolved in the active editor state on every call, so
it always reads the latest version, as JS node methods do through
getLatest(). Like a JS node reference, it can only be used insideEditor::readorEditorState::read, and panics elsewhere. - Node
Selection NodeSelection’s fields: the selected keys, in the order added.- Normalized
Peer Dependency NormalizedPeerDependency:[name, config?], fromdeclare_peer_dependency.- Point
PointType: a node key, an offset and a type.- Point
Caret PointCaret: aNodeCaretor aTextPointCaret.- Range
Selection RangeSelection’s fields.- RefCounted
Registry RefCountedRegistry<Key, Options>: the first registration of a key runs the activation; what it returned runs once the last registration of that key is released. A handle; cloning it shares the registry.- Required
Node State Config RequiredNodeStateConfig: a state a node class declares in its$config’sstateConfigs(LexicalNode::state_configs), which its type knows before any node reads it; aflatone serializes at the top level of the node’s JSON instead of under"$".- Root
Element Ref - A root element, compared by identity.
- Selection
Ref - A selection object, shared as JS shares it:
$getSelection()returns the one the editor state holds, so a change through it is a change of the state’s selection;clone_selectionmakes a separate one. - Split
AtPoint Caret Next Options SplitAtPointCaretNextOptions.$copyElementNodeand$splitTextPointCaretNextare always their defaults ($copyNodeandsplit_text_point_caret).- State
Config StateConfig: whatcreate_statereturns, forget_stateandset_state. Clones are the same config: nodes tell configs apart by identity, as JS does.- State
Value Config StateValueConfig: how a state’s value parses from JSON (parse, which gives the default forundefined), writes back (unparse) and compares (isEqual), whether$copyNoderesets it (resetOnCopyNode), whether the node’s own code recomputes it (derived,@experimental), and the schemaparsewas given as (StateConfig.schema), when it was one.- Static
Node Config - The node-structure keys of one class’s own
$config()(StaticNodeConfigValue’sinline,childrenandmergeAdjacent). What it declaresderivedcomes from its schema (LexicalNode::json_schema_chain) and its NodeState (LexicalNode::state_configs). - Style
Object - A
Record<string, string>of CSS properties, asget_style_object_from_cssreturns it: keys in JS’s property order (array indices first, ascending, then the rest in the order they were first set), so iterating it writes CSS in the order JS does. - Text
Point Caret Slice TextPointCaretSlice: a text point caret and a signed distance from its offset. A negative distance selects the text before the offset, a positive one the text after it, whatever the caret’s direction.- Update
Listener Payload - What an update listener receives (
UpdateListenerPayload). The dirty nodes are in the order they were marked; each dirty element says whether it was marked itself (true) or only because a descendant was. - Update
Options EditorUpdateOptions.eventcomes with its users.
Enums§
- Caret
Direction CaretDirection:'next'points towards the end of the document,'previous'towards the beginning.- Caret
Kind - A caret’s JS
type, with the offset a text point caret carries. - Clipboard
OrKeyboard Event ClipboardEvent | KeyboardEvent, the payload ofCOPY_COMMANDandCUT_COMMAND(orNone, JS’snull).- Common
Ancestor Across Slots Result CommonAncestorAcrossSlotsResult(@experimental): likeCommonAncestorResult, except that the common ancestor may be a decorator slot host, and the node on either side below it may be one of its slot values rather than a child.- Common
Ancestor Result CommonAncestorResult: how two nodes relate through their common ancestor.- Control
OrOther KeyboardEventControlOrOther’sCONTROL_OR_OTHER_KEY: the modifier that stands in for Control on the other platform.- Editor
Focus Options EditorFocusOptions.- Editor
Read Mode EditorReadMode: which stateEditor::read_with_modereads.- Initial
Editor State Type InitialEditorStateType: howInitialStateExtensionfills a new editor.- Merge
Adjacent Declaration - A class’s own
mergeAdjacentdeclaration:Offis JS’sfalse, which turns off a declaration an ancestor made. - Merge
Adjacent Entry - One value
mergeAdjacent.bynames: a schema field of the class (a property of its JSON), or a NodeState. - Modifier
Expectation - The expected state of one modifier in a
KeyboardEventModifierMask: JS’strue,false(or omitted) and'any'. - Node
Child Entry - One entry of a
childrenlist:'inline', or a class (which allows its subclasses). - Node
Children Config NodeChildrenConfig(@experimental node-structure): what an element may hold.Inlineis a paragraph’s content,Blocka table cell’s, andListonly the listed entries.- Node
Mutation NodeMutation: what the reconciler did with a node in a commit.- Paste
Command Type PasteCommandType:ClipboardEvent | InputEvent | KeyboardEvent, the payload ofPASTE_COMMAND.- Point
Type - A point’s type: inside a text node (an offset in UTF-16 code units) or between an element’s children (a child index).
- Root
Mode RootMode: whether a traversal up the tree stops at the root only ('root'), or at the root and any shadow root ('shadowRoot').- Selection
- A selection’s value.
- Selection
Alter 'move'or'extend'.- Selection
Granularity 'character','word','line'or'lineboundary'.- Slice
Mode - The
sliceModeofremove_text_from_caret_range. - Text
Offset - An offset into a text node: a number of UTF-16 code units, or the end
in a direction (
'next'is the end,'previous'the start), as JS’snumber | CaretDirection. - Which
- Which point of a range selection.
Constants§
- BEFORE_
INPUT_ COMMAND BEFORE_INPUT_COMMAND: dispatched on abeforeinputevent; the core’s handler ($handleBeforeInput) turns it into the command it stands for.- BLUR_
COMMAND BLUR_COMMAND: dispatched when the editor loses the focus.- CAN_
REDO_ COMMAND CAN_REDO_COMMAND: dispatched when whether redo is possible changes; the payload is whether it is. JS deprecates it (v0.49.0) forHistoryExtension’scanRedosignal (HistoryExtensionOutput::can_redo).- CAN_
UNDO_ COMMAND CAN_UNDO_COMMAND: dispatched when whether undo is possible changes; the payload is whether it is. JS deprecates it (v0.49.0) forHistoryExtension’scanUndosignal (HistoryExtensionOutput::can_undo).- CLEAR_
EDITOR_ COMMAND CLEAR_EDITOR_COMMAND: dispatched to clear all editor content.- CLEAR_
HISTORY_ COMMAND CLEAR_HISTORY_COMMAND: dispatched to clear the undo and redo stacks.- CLICK_
COMMAND CLICK_COMMAND: dispatched on a click in the editor.- COLLABORATION_
TAG COLLABORATION_TAG(LexicalUpdateTags.ts): the update applies changes that came from another replica.- COMMAND_
PRIORITY_ BEFORE_ CRITICAL COMMAND_PRIORITY_BEFORE_CRITICAL: the beginning of the critical priority queue.- COMMAND_
PRIORITY_ BEFORE_ EDITOR COMMAND_PRIORITY_BEFORE_EDITOR: the beginning of the editor priority queue.- COMMAND_
PRIORITY_ BEFORE_ HIGH COMMAND_PRIORITY_BEFORE_HIGH: the beginning of the high priority queue.- COMMAND_
PRIORITY_ BEFORE_ LOW COMMAND_PRIORITY_BEFORE_LOW: the beginning of the low priority queue.- COMMAND_
PRIORITY_ BEFORE_ NORMAL COMMAND_PRIORITY_BEFORE_NORMAL: the beginning of the normal priority queue.- COMMAND_
PRIORITY_ CRITICAL COMMAND_PRIORITY_CRITICAL: the end of the critical priority queue.- COMMAND_
PRIORITY_ EDITOR COMMAND_PRIORITY_EDITOR: a listener added to the end of the editor priority queue (after critical, high, normal, low).- COMMAND_
PRIORITY_ HIGH COMMAND_PRIORITY_HIGH: the end of the high priority queue.- COMMAND_
PRIORITY_ LOW COMMAND_PRIORITY_LOW: the end of the low priority queue.- COMMAND_
PRIORITY_ NORMAL COMMAND_PRIORITY_NORMAL: the end of the normal priority queue.- COMPOSITION_
END_ COMMAND COMPOSITION_END_COMMAND: dispatched when an input method composition ends.- COMPOSITION_
END_ TAG COMPOSITION_END_TAG(LexicalUpdateTags.ts): the update ends an input method composition.- COMPOSITION_
START_ COMMAND COMPOSITION_START_COMMAND: dispatched when an input method composition starts.- COMPOSITION_
START_ TAG COMPOSITION_START_TAG(LexicalUpdateTags.ts): the update starts an input method composition.- CONTROLLED_
TEXT_ INSERTION_ COMMAND CONTROLLED_TEXT_INSERTION_COMMAND: dispatched to insert text. JS also takes thebeforeinputevent; without a DOM only the string form is here.- COPY_
COMMAND COPY_COMMAND: dispatched on a copy, with theClipboardEvent, theKeyboardEvent(⌘C on macOS, Ctrl+C elsewhere), orNone(JSnull).- CUT_
COMMAND CUT_COMMAND: dispatched on a cut; the payload is asCOPY_COMMAND’s.- CUT_TAG
CUT_TAG(LexicalUpdateTags.ts): the update is a cut.- DEFER_
COMPOSITION_ MERGE_ TAG DEFER_COMPOSITION_MERGE_TAG(LexicalUpdateTags.ts): the update must not merge text into or out of the node being composed.- DELETE_
CHARACTER_ COMMAND DELETE_CHARACTER_COMMAND: dispatched to delete a character; the payload istruefor a backward deletion (Backspace) andfalsefor a forward one (Delete).- DELETE_
LINE_ COMMAND DELETE_LINE_COMMAND: dispatched to delete a line; the payload istruefor a backward deletion (Cmd+Delete on macOS).- DELETE_
WORD_ COMMAND DELETE_WORD_COMMAND: dispatched to delete a word; the payload istruefor a backward deletion (Opt+Delete on macOS).- DRAGEND_
COMMAND DRAGEND_COMMAND: dispatched when a drag ends.- DRAGOVER_
COMMAND DRAGOVER_COMMAND: dispatched when a drag is over the editor.- DRAGSTART_
COMMAND DRAGSTART_COMMAND: dispatched when a drag starts.- DROP_
COMMAND DROP_COMMAND: dispatched on a drop.- FOCUS_
COMMAND FOCUS_COMMAND: dispatched when the editor gets the focus.- FOCUS_
TAG FOCUS_TAG(LexicalUpdateTags.ts): the update isEditor::focus’s.- FORMAT_
ELEMENT_ COMMAND FORMAT_ELEMENT_COMMAND: dispatched to set the alignment ("left","center", …) of the selected blocks.- FORMAT_
TEXT_ COMMAND FORMAT_TEXT_COMMAND: dispatched to toggle a text format ("bold","italic", …) on the selection.- HISTORIC_
TAG HISTORIC_TAG(LexicalUpdateTags.ts): the update applies a state from the undo or redo stack.- HISTORY_
MERGE_ TAG HISTORY_MERGE_TAG(LexicalUpdateTags.ts): the update joins the previous history entry.- HISTORY_
PUSH_ TAG HISTORY_PUSH_TAG(LexicalUpdateTags.ts): the update starts a new history entry.- INDENT_
CONTENT_ COMMAND INDENT_CONTENT_COMMAND: dispatched to indent the selected content.- INPUT_
COMMAND INPUT_COMMAND: dispatched on aninputevent.- INSERT_
LINE_ BREAK_ COMMAND INSERT_LINE_BREAK_COMMAND: dispatched to insert a line break. Withfalsethe caret moves to the new line (Shift+Enter); withtrueit stays (Ctrl+O on macOS).- INSERT_
PARAGRAPH_ COMMAND INSERT_PARAGRAPH_COMMAND: dispatched to insert a new paragraph (Enter).- INSERT_
TAB_ COMMAND INSERT_TAB_COMMAND: dispatched to insert a tab.- KEY_
ARROW_ DOWN_ COMMAND KEY_ARROW_DOWN_COMMAND: dispatched whenArrowDownis pressed; Shift and Alt may be down.- KEY_
ARROW_ LEFT_ COMMAND KEY_ARROW_LEFT_COMMAND: dispatched whenArrowLeftis pressed; Shift may be down.- KEY_
ARROW_ RIGHT_ COMMAND KEY_ARROW_RIGHT_COMMAND: dispatched whenArrowRightis pressed; Shift may be down.- KEY_
ARROW_ UP_ COMMAND KEY_ARROW_UP_COMMAND: dispatched whenArrowUpis pressed; Shift and Alt may be down.- KEY_
BACKSPACE_ COMMAND KEY_BACKSPACE_COMMAND: dispatched whenBackspaceis pressed; Shift may be down.- KEY_
DELETE_ COMMAND KEY_DELETE_COMMAND: dispatched whenDeleteis pressed (Fn+Delete on macOS), with no modifiers.- KEY_
DOWN_ COMMAND KEY_DOWN_COMMAND(namedKEYDOWN_COMMAND, as in JS): dispatched when any key is pressed; the core’s handler ($handleKeyDown) dispatches the command the key stands for.- KEY_
ENTER_ COMMAND KEY_ENTER_COMMAND: dispatched when Enter is pressed, with the key event, orNone(JSnull) when the intent is to insert a newline without one. Rich and plain text’s handlers turn it intoINSERT_PARAGRAPH_COMMANDorINSERT_LINE_BREAK_COMMAND.- KEY_
ESCAPE_ COMMAND KEY_ESCAPE_COMMAND: dispatched whenEscapeis pressed, with any modifiers.- KEY_
MODIFIER_ COMMAND KEY_MODIFIER_COMMAND: dispatched after any key pressed with a modifier. JS deprecates it (v0.31.0) forKEY_DOWN_COMMAND, checking the modifiers.- KEY_
SPACE_ COMMAND KEY_SPACE_COMMAND: dispatched when the space key is pressed, with any modifiers.- KEY_
TAB_ COMMAND KEY_TAB_COMMAND: dispatched whenTabis pressed; Shift may be down.- MOVE_
TO_ END MOVE_TO_END: dispatched on the move to end shortcut (⌘→ on macOS, End elsewhere).- MOVE_
TO_ START MOVE_TO_START: dispatched on the move to start shortcut (⌘← on macOS, Home elsewhere).- OUTDENT_
CONTENT_ COMMAND OUTDENT_CONTENT_COMMAND: dispatched to outdent the selected content.- PASTE_
COMMAND PASTE_COMMAND: dispatched on a paste, with theClipboardEvent(or theInputEventorKeyboardEventthat pasted).- PASTE_
TAG PASTE_TAG(LexicalUpdateTags.ts): the update is a paste.- REDO_
COMMAND REDO_COMMAND: dispatched on redo (⇧⌘Z on macOS, Ctrl+Shift+Z or Ctrl+Y elsewhere).- REMOVE_
TEXT_ COMMAND REMOVE_TEXT_COMMAND: dispatched to remove the selected text. JS’s payload is the input event ornull, which no handler reads.- SELECTION_
CHANGE_ COMMAND SELECTION_CHANGE_COMMAND: dispatched in an update when the selection changes. The core dispatches it from the DOM half of the update cycle, which isn’t ported (rust/PARITY.md), so only an app dispatches it.- SELECTION_
INSERT_ CLIPBOARD_ NODES_ COMMAND SELECTION_INSERT_CLIPBOARD_NODES_COMMAND: dispatched by$insertGeneratedNodes(theclipboardfeature) before it inserts the nodes of a paste; a handler that returnstrueinserts them itself.- SELECT_
ALL_ COMMAND SELECT_ALL_COMMAND: dispatched on the select all shortcut (⌘A on macOS, Ctrl+A elsewhere), with the key event.- SET_
TEXT_ FORMAT_ COMMAND SET_TEXT_FORMAT_COMMAND: dispatched to set (true) or clear (false) text formats on the selection. JS’s payload is an object; its keys’ order is the order here.- SKIP_
COLLAB_ TAG SKIP_COLLAB_TAG(LexicalUpdateTags.ts): the update must not be sent to other replicas.- SKIP_
DOM_ SELECTION_ TAG SKIP_DOM_SELECTION_TAG(LexicalUpdateTags.ts): the update must not change the platform’s selection.- SKIP_
SCROLL_ INTO_ VIEW_ TAG SKIP_SCROLL_INTO_VIEW_TAG(LexicalUpdateTags.ts): the update must not scroll the selection into view.- SKIP_
SELECTION_ FOCUS_ TAG SKIP_SELECTION_FOCUS_TAG(LexicalUpdateTags.ts): the update must not move the focus to the editor.- UNDO_
COMMAND UNDO_COMMAND: dispatched on undo (⌘Z on macOS, Ctrl+Z elsewhere).- UPSTREAM_
VERSION - The upstream Lexical release this port conforms to. The conformance
vectors (
meta.json) name the same one, so an upstream sync can’t move one without the other.
Traits§
- AnyLexical
Extension AnyLexicalExtension: anyLexicalExtension, as the builder sees it. OnlyLexicalExtensionimplements it.- Extension
Config Base ExtensionConfigBase: what an extension’s config is. JS configs are objects, their overrides arePartial<Config>, andshallowMergeConfigmerges one as{...config, ...overrides}. A Rust config names its overrides’ type and how they apply:Object, the JS form, merges as JS does;()is the config of an extension with none (JS{}).- Keyboard
Event Modifiers KeyboardEventModifiers: aKeyboardEvent, or anything with itskey,codeand modifier fields.- Keyboard
Shortcut Match KeyboardShortcutMatch(@experimental): which keyboard events a shortcut matches, anevent.keyvalue (case-insensitive) and aKeyboardEventModifierMask, with the semantics ofis_exact_shortcut_match, including theevent.codefallback for non-Latin layouts.- Lexical
Node - What every node implements. JS’s class hierarchy (
LexicalNode,ElementNode,TextNode, …) becomes this trait plus the data each base class adds (ElementData,TextData); a node that extendsElementNodereturns itsElementDatafromelement. - Listener
Cleanup - What an update, text content, decorator or editable listener returns:
nothing (
()), or a clean-up function (anUnregister, or anOptionof one), which runs before the listener’s next call, or when it is unregistered. JS takes a returned function as the clean-up and ignores any other value (triggerListeners). - Node
Clone - The parts of
LexicalNodeevery implementation writes the same way, implemented for anyClonenode. - Root
Element - The editor’s root element: what JS’s
HTMLElementroot is to an app without a DOM, the view that shows the document. Setting one (Editor::set_root_element) runs the reconciler’s model half, so mutation listeners hear from the editor. Root elements compare by identity, as JS’s elements do. - Selection
Movement - Where a caret lands when it moves one unit, which only text layout knows
(the DOM’s
Selection.modifyin JS). Called inside an update or read, so it can read nodes. - State
Value - A value a state can hold without saying how it serializes and compares:
one that JSON writes as it is (JS’s default
unparse), compared withObject.is(JS’s defaultisEqual).
Functions§
- add_
update_ tag $addUpdateTag(tag): adds a tag to the running update, which update and mutation listeners andhas_update_tagsee. Panics in a read, or outside an update, as JS’serrorOnReadOnlyandgetActiveEditor()throw.- apply_
node_ replacement $applyNodeReplacement(node): what the active editor’s replacement of the node’s class ({replace, with, withKlass}) makes of the new node, or the node itself when the class has none. Fails as JS’s invariants do: for a type the editor doesn’t register, or a replacement that isn’t ofwithKlass(or, without it, of a class extending the node’s), or that kept the node’s key.- caret_
from_ point $caretFromPoint(point, direction): the caret at a selection point.- caret_
range_ from_ selection $caretRangeFromSelection(selection): the carets of a range selection, in thepreviousdirection when the focus is before the anchor.- clamp_
range_ selection_ to_ slot_ frame $clampRangeSelectionToSlotFrame(selection)(@experimental): keeps the focus of a range selection in the anchor’s slot frame, at the boundary on the side the focus was, in the default slots-before-children order (compare_point_caret_next_across_slots). Returns whether it moved the focus, which marks the selection dirty.- clone_
with_ properties $cloneWithProperties(latestNode): a clone of the node’s latest version with the same key, links and properties, in no editor state. An editor state never sees it unless it is put there, so changing it changes no state.- clone_
with_ properties_ ephemeral $cloneWithPropertiesEphemeral(latestNode): a clone that can’t join an editor state, for changing in place while serializing a slice. A clone fromclone_with_propertiesis already outside every editor state, so it is the same clone.- compare_
point_ caret_ next $comparePointCaretNext(a, b): the total order ofnextcarets in which aCaretRangeiterates them. For one origin, a child caret and a text point caret come before the sibling caret. Carets whose origins have no common ancestor are an error.- compare_
point_ caret_ next_ across_ slots $comparePointCaretNextAcrossSlots(a, b)(@experimental): likecompare_point_caret_next, with a host’s slot values, in slot order, after the points before the host and before its children.Nonewhen the carets have no common ancestor.- compile_
keyboard_ shortcuts compileKeyboardShortcuts(shortcuts)(@experimental @internal).- config_
extension configExtension(extension, ...configs): the extension with config overrides, for another extension’sdependenciesor forbuild_editor_from_extensions. The builder merges them withmergeConfig, or withshallow_merge_config.- control_
or_ alt CONTROL_OR_ALT: the secondary shortcut modifier, ⌥ (altKey) on Apple platforms and Ctrl elsewhere, for word-level editing and block formats.- control_
or_ meta CONTROL_OR_META: the primary shortcut modifier, ⌘ (metaKey) on Apple platforms and Ctrl elsewhere, for the platformis_applenames.- copy_
node $copyNode(node): a copy of the node with a new key and all its properties, but no parent, siblings or children, afterresetOnCopyNodeFrom.- copy_
node_ with $copyNode(node, skipReset):copy_node, withoutresetOnCopyNodeFromwhenskip_resetis true, so the copy keeps every property and state of the node.- create
$create(klass): a new node of the classT, with a key, in the active editor state; or, where the editor replaces the class (LexicalNodeReplacement), a node of the class itswith_klasschain ends at, or (for a replacement withoutwith_klass) what itswithmakes of the new node. Where no editor registersT(outside an editor, or while parsing for one without it) the node isT’s, where JS throws.- create_
command createCommand(type).- create_
editor createEditor(config): registers the core nodes (root, text, line break, tab, paragraph, artificial) andargs.nodes, inargs.namespace, or the parent editor’s when that is empty. (JS’screateEditor()with no config at all takes the active editor as the parent; Rust always takes a config, as Swift does.)- create_
node_ selection $createNodeSelection().- create_
range_ selection $createRangeSelection(): a selection at the start of the root, not set on the editor state.- create_
ref_ counted_ registry createRefCountedRegistry(activate).- create_
state createState(key, {parse}): a state with JS’s defaultunparseandisEqual(StateValue).- create_
state_ with createState(key, valueConfig).- declare_
peer_ dependency declarePeerDependency(name, config?): a peer dependency on the extension namedname, whose config is aC(JS gives the extension’s type as a type argument), optionally with config overrides.- define_
extension defineExtension(extension): the extension, behind theRcwhose identity the builder tells extensions apart by (JS returns the object itself, compared with===). Define each extension once and share theRc: two definitions with one name can’t be built together.- export_
node_ json $exportNodeJSON(node): one node’s JSON in the active form, checked as every export walk checks it. A failed check is a bug in the node’s implementation, so it panics.- extend_
caret_ to_ range $extendCaretToRange(anchor): a range fromanchorto the end of the document in its direction.- flip_
direction flipDirection(direction).- get_
adjacent_ child_ caret $getAdjacentChildCaret(caret): the adjacent caret, or its child caret when its origin is an element. WithgetParentCaretthis walks the whole tree depth first.- get_
adjacent_ node $getAdjacentNode(focus, isBackward): the node next to the point in the direction, orNoneat a boundary.- get_
adjacent_ sibling_ or_ parent_ sibling_ caret $getAdjacentSiblingOrParentSiblingCaret(startCaret, rootMode): the next caret in a depth first walk that doesn’t descend into the start, with the change in depth.- get_
cached_ type_ to_ node_ map getCachedTypeToNodeMap(editorState): the nodes of a read-only editor state by type, computed once per state; an empty map for a writable state that is still empty. Panics for any other writable state, as JS’s invariant throws.- get_
caret_ in_ direction $getCaretInDirection(caret, direction): the caret if it is indirection, otherwisecaret.getFlipped().- get_
caret_ range $getCaretRange(anchor, focus): a range between carets in the same direction, where the anchor points towards the focus.- get_
caret_ range_ in_ direction $getCaretRangeInDirection(range, direction): the range, or the same part of the document iterated the other way.- get_
child_ caret $getChildCaret(origin, direction): a caret pointing to the first (next) or last (previous) child oforigin, orNoneif it isn’t an element.- get_
child_ caret_ at_ index $getChildCaretAtIndex(parent, index, direction): a caret pointing to the child atindex, or the last caret inparentpast the end.- get_
child_ caret_ or_ self $getChildCaretOrSelf(caret): the caret’s child caret if it has one, otherwise the caret.- get_
collapsed_ caret_ range $getCollapsedCaretRange(anchor).- get_
common_ ancestor $getCommonAncestor(a, b): howaandbrelate, orNoneif they have no common ancestor.- get_
common_ ancestor_ across_ slots $getCommonAncestorAcrossSlots(a, b)(@experimental): likeget_common_ancestor, but a slot value’s parent is its host.- get_
common_ ancestor_ result_ branch_ order $getCommonAncestorResultBranchOrder(compare):Lessifa(a sibling ofb) comes first,Greaterotherwise.- get_
composition_ key $getCompositionKey(): the node an input method is composing in; always none in a read.- get_
declared_ node_ structure getDeclaredNodeStructure(klass)(@experimental node-structure): the structural declarations of the class ofnode. Depends on the class only.- get_
declared_ slots getDeclaredSlots(klass)(@experimental): theslotsa class declares in its$config()(its own, or the nearest ancestor’s), the canonical order of its slots; empty when it declares none.- get_
editor $getEditor(): the editor of the running update or read (or the oneparseEditorStateparses for). Panics outside them, as JS’sgetActiveEditor()throws.- get_
node_ by_ key $getNodeByKey(key).- get_
point_ slot_ frame $getPointSlotFrame(point): the slot frame of the point’s node.- get_
registered_ subtype_ map getRegisteredSubtypeMap(nodes): each type ofnodesto itself and the types of the classes ofnodesthat extend it.- get_
root $getRoot().- get_
selection $getSelection().- get_
selection_ slot_ frame $getSelectionSlotFrame(selection)(@experimental): the slot frame the selection is in, from a range selection’s anchor or the first node of any other selection, orNoneoutside every slot (or without a selection).- get_
sibling_ caret $getSiblingCaret(origin, direction): a caret pointing fromoriginto its next or previous sibling. JS returnsnullfor anullorigin; here that isOption::map.- get_
slot $getSlot(node, name)(@experimental): the node in the named slot, orNonewhen it is empty.- get_
slot_ frame $getSlotFrame(node)(@experimental): the slot value (the “slot frame”) whose isolated subtree holds the node, the node itself when it is one, orNoneoutside every slot.- get_
slot_ host $getSlotHost(node)(@experimental): the host whose named slot holds the node, orNonewhen it is not slotted. Kept apart fromNodeRef::get_parent, so the slot boundary behaves like a shadow root.- get_
slot_ name_ within_ host $getSlotNameWithinHost(slotChild)(@experimental): the name of the slot the node occupies on its host, orNonewhen it is not slotted.- get_
slot_ names $getSlotNames(node)(@experimental): the names of the node’s occupied slots, in their canonical order.- get_
state $getState(node, stateConfig): the value of the state on the latest version of the node, or its default. Fails when another config with the same key was used on the node’s type.- get_
state_ change $getStateChange(node, prevNode, stateConfig):Nonewhen the two versions hold equal values, else(value, prevValue).- get_
state_ direct $getState(node, stateConfig, NODE_STATE_DIRECT): the value on this version of the node, which needs no editor state.- get_
style_ object_ from_ css getStyleObjectFromCSS(css): parses inline CSS text into an object that is compatible withCSSStyleDeclaration.setProperty(). Comments are dropped;:and;inside quotes or parentheses are not delimiters.- get_
text_ direction getTextDirection(text): the direction of the first strongly directional UTF-16 code unit intext(RTL_REGEX, thenLTR_REGEX:^[^LTR]*[RTL]and^[^RTL]*[LTR]), orNonewhen there is none.- get_
text_ node_ offset $getTextNodeOffset(origin, offset, mode): the numeric offset ofoffsetinorigin. Out of bounds it is an error (JS’s development build), or clamped whenclamp(mode'clamp').- get_
text_ point_ caret $getTextPointCaret(origin, direction, offset): a caret atoffsetin the text nodeorigin. An offset past the end is an error, as in JS’s development build.- get_
text_ point_ caret_ slice $getTextPointCaretSlice(caret, distance).- get_
text_ point_ caret_ slice_ for_ node $getTextPointCaretSliceForNode(slices, node): the slice ofnodeamong a caret range’s text slices.- has_
update_ tag $hasUpdateTag(tag): whether the running update has the tag (one of its options’ tags, or oneadd_update_tagadded). Panics outside an update or a read of an editor, as JS’sgetActiveEditor()throws.- insert_
node_ to_ nearest_ root_ at_ caret $insertNodeToNearestRootAtCaret(node, caret, options): insertsnodeat the caret, splitting its ancestors up to the nearest block container (the root or a shadow root, with the defaultroot_mode), and returns the caret after it.- insert_
nodes $insertNodes(nodes): insertsnodesat the selection, the previous one if there is none, or else the end of the root.- internal_
is_ inline_ content INTERNAL_isInlineContent(node): whether the node structure normalization treatsnodeas inline content: text, line breaks, inline elements and decorators, and the character limit’sOverflowNode.- internal_
is_ node_ structure_ enforced INTERNAL_isNodeStructureEnforced(editor)(internal): whethereditorenforces declared node structure (NodeStructureExtensionorregisterNodeStructureis registered on it).- internal_
normalize_ node_ structure INTERNAL_$normalizeNodeStructure(node)(internal): normalize the subtree rooted atnodenow, asNodeStructureExtensiondoes, bottom-up (which may splitnodein its parent), then mergenode(or what it was split into) with its equal siblings. For code that applies an update withskip_transforms, which the extension doesn’t normalize.- internal_
register_ node_ structure INTERNAL_registerNodeStructure(editor)(internal, forNodeStructureExtensionandregisterNodeStructure): enforce the structure node classes declare oneditor, and mark every element and decorator dirty so the current document is normalized too. Registrations are counted: the normalization stops when the last one is disposed.- is_
apple IS_APPLE: whether the keyboard conventions are Apple’s (⌘ for the primary shortcuts, ⌥ for words). JS reads the browser’s platform; here it istrueon Apple platforms.with_is_appleoverrides it on this thread, as Swift’swithIsAppledoes, since the vectors are recorded for both.- is_
backspace isBackspace(event).- is_
block_ container $isBlockContainer(node)(@experimental node-structure): whether structural commands treatnodeas a container of blocks: the root, a shadow root, or, in an editor that enforces declared node structure, a block element whose class declareschildren: 'block'. With no active editor, only the root and shadow roots are containers.- is_
block_ fully_ selected $isBlockFullySelected(blockNode, selection): whether the selection covers everything in the block. A range in another slot frame never does.is_block_fully_selected_by_caret_rangetakes aCaretRange, as JS’s also does.- is_
block_ fully_ selected_ by_ caret_ range $isBlockFullySelected(blockNode, range)with aCaretRange: whether the range, in either direction, covers everything in the block.- is_
compact_ export $isCompactExport(): whether the export walk in progress writes the compact form.- is_
delete isDelete(event).- is_
escape isEscape(event).- is_
exact_ shortcut_ match isExactShortcutMatch(event, expectedKey, mask): whether the event isexpected_key(case-insensitive) with exactly the modifiers ofmask, falling back toevent.codefor a single-character key on a non-Latin layout.- is_
extendable_ text_ point_ caret $isExtendableTextPointCaret(caret): a text point caret whose offset can move further in its direction without leaving the node.- is_
modifier isModifier(event): whether any modifier is down.- is_
modifier_ match isModifierMatch(event, mask): whether the event’s modifiers are as the mask expects.- is_
root_ or_ shadow_ root $isRootOrShadowRoot(node): whether the node is the root or a shadow root.- is_
same_ frame $isSameFrame(a, b).- is_
select_ all isSelectAll(event): ⌘A on Apple platforms, Ctrl+A elsewhere.- is_
slot_ child $isSlotChild(node)(@experimental): whether the node can be slotted, an element or a decorator (set_slotrefuses an inline one).- is_
slot_ host $isSlotHost(node)(@experimental): whether the node can host slots, an element or a decorator. What may be slotted is checked byset_slot.- is_
token_ or_ segmented $isTokenOrSegmented(node): whether a text node is in token or segmented mode.- iter_
static_ node_ config_ chain iterStaticNodeConfigChain(klass): the node’s class and the classes it extends, most derived first (LexicalNode::static_node_config_chain), or the node’s class alone, declaring nothing, for a class that gives no chain.- js_trim
String.prototype.trim: without JS’s whitespace (and line terminators) at either end.- keyboard_
event_ mask_ for_ platform keyboardEventMaskForPlatform(mask, isApple)(@internal): the mask as it is on the platformis_applenames, when it is a control-or-other mask made for the other one.- make_
stepwise_ iterator makeStepwiseIterator({initial, hasNext, step, map}): yieldsmap(state)whilehas_next(state), stepping the state after each.- merge_
register mergeRegister(...func): one clean-up function that calls each offuncsin reverse order, as clean-ups usually need to run in the reverse of the order they were registered.- nodes_
of_ type $nodesOfType(klass), by the node type: the nodes of exactly that type in the active editor state, in its node map’s order; in a state still being updated, only those attached to the root.- normalize_
caret $normalizeCaret(initialCaret): the deepest equivalent caret, a text point caret when there is text at the caret.- on_
before_ input onBeforeInput(event, editor): an app’sbeforeinput. A composition’s own input (insertCompositionText,deleteCompositionText) is left to the composition commands; anything else dispatchesBEFORE_INPUT_COMMAND.- on_
composition_ end onCompositionEnd(event, editor): dispatchesCOMPOSITION_END_COMMAND(where JS waits for Firefox’s and Safari’s input event, the model has none to wait for).- on_
composition_ start onCompositionStart(event, editor): dispatchesCOMPOSITION_START_COMMAND.- on_
key_ down onKeyDown(event, editor): an app’s key press. It records the key and, unless an input method is composing, dispatchesKEY_DOWN_COMMAND, whose default handler dispatches the command the key stands for. Readevent.default_prevented()afterwards to know whether the key was taken (the app then skips its own handling of it).- on_
selection_ change onSelectionChange(domSelection, editor, isActive), its model half: an app’s view selectedanchortofocus(Nonewhen the selection left the editor). An editor that isn’t active (is_activefalse, another editor of the view has the selection) gets no selection, as in JS. Otherwise the points become the selection, with the format and style of the editor state’s (the last committed) selection, as$internalCreateRangeSelectiongives a selection read from the DOM; a caret takes the format and style of where it is ($updateCollapsedSelectionFormatStyle) and a range the format all its text has; then the change is announced withSELECTION_CHANGE_COMMAND($dispatchSelectionChangeCommand).- on_
update $onUpdate(updateFn)(LexicalUtils.ts): runsupdate_fnonce the update that is running commits, after its listeners.- parse_
serialized_ node $parseSerializedNode(serializedNode): a node, and its children, from its JSON, created in the active update with the active editor’s node classes.- remove_
slot $removeSlot(host, name)(@experimental): empties the named slot ofhost, removing the node it held. Nothing happens when it is empty. Returns the host.- remove_
text_ from_ caret_ range $removeTextFromCaretRange(initialRange, sliceMode): removes the text and nodes in the range, merging the rest of the later block into the earlier one when the range spans blocks. Returns the collapsed range where the removal was, in the initial range’s direction.- reset_
random_ key resetRandomKey(): restarts the key counter, for deterministic keys in tests.- rewind_
sibling_ caret $rewindSiblingCaret(caret): the caret, in the same direction, whose adjacent caret iscaret.- safe_
cast safeCast(value):value. JS uses it to give a config its type where inference wouldn’t; Rust infers it from the annotation, so this only keeps ported code close to JS.- select_
all $selectAll(): selects the whole root, with the points moved down to text where they can be, and returns the selection.select_all_inis$selectAll(selection), which scopes an existing selection.- select_
all_ in $selectAll(selection): for a range selection, moves its points to the start and end of the root or shadow root that holds its anchor, down to text where they can be, and returns it (in a slot, the contents of the slot value); for a node selection,select_all, which is$selectAll().- set_
composition_ key $setCompositionKey(compositionKey): the node an input method is composing in, or none. The previous and the new composition nodes are made writable, so they reconcile.- set_
dom_ style_ from_ css setDOMStyleFromCSS(domStyle, cssText, prevCSSText): sets the properties ofcss_textand removes those onlyprev_css_texthas.- set_
dom_ style_ object setDOMStyleObject(domStyle, styleObject): sets each property with a value and removes each one without (null).- set_
point_ from_ caret $setPointFromCaret(point, caret): sets the pointwhichof a range selection to the caret’s position.- set_
selection $setSelection(selection).- set_
selection_ from_ caret_ range $setSelectionFromCaretRange(caretRange): sets the editor’s range selection (the current one, or a new one) to the range, and returns it.- set_
slot $setSlot(host, name, node)(@experimental): putsnodein the named slot ofhost, replacing (and removing) the node the slot held. The node moves, from a parent or another slot. It must be an element or a decorator that is not inline; the slot link is its shadow boundary. Returns the host.- set_
state $setState(node, stateConfig, value): sets the state on the node (the node is written even when the value is the one it has). Fails when another config with the same key was used on the node’s type.- set_
state_ with $setState(node, stateConfig, updater): sets the state to whatupdatermakes of the node’s value, unless that is equal to it, when the node is left as it is.- shallow_
merge_ config shallowMergeConfig(config, overrides): the default merge of config overrides,configwithout them, otherwiseExtensionConfigBase::shallow_merge({...config, ...overrides}).- split_
at_ point_ caret_ next $splitAtPointCaretNext(pointCaret, options): splits the node at the caret once, and returns the caret where it split, orNonewhere it can’t.- split_
node $splitNode(node, offset): splits the element at its childoffsetand each ancestor up to the nearest root or shadow root, and returns the top of the left tree (node’s ancestor below the root, which keeps the children before the offset) and of the right tree (a copy, which gets the rest). The child atoffsetmoves into the right tree; its ancestors are copied. Anoffsetpast the end splits after the last child. JS’s return type lets the left benull; it never is.- split_
text_ point_ caret $splitTextPointCaret(textPointCaret): splits the text at the caret, and returns the sibling caret between the two halves (or beside the text, at either end).- update_
range_ selection_ from_ caret_ range $updateRangeSelectionFromCaretRange(selection, caretRange).- with_
compact_ export $withCompactExport(compact, f): runsfwriting the compact form (or, withfalse, the legacy form) for any export it performs.- with_
is_ apple - Runs
fwithis_applereturningis_appleon this thread. - with_
warning_ handler - Runs
fwithhandlerreceiving, on this thread, the warnings JS writes withconsole.warn, and restores the previous handler after, even whenfpanics.
Type Aliases§
- Child
Caret ChildCaret: aPointCaretwhose kind isCaretKind::Child.- Extension
Build Fn build(LexicalExtension.build).- Extension
Init Fn init(LexicalExtension.init).- Extension
Merge Config Fn mergeConfig(LexicalExtension.mergeConfig).- Extension
Register Fn registerandafterRegistration(LexicalExtension.register): they return the clean-up function.- Initial
Editor State Fn (editor: LexicalEditor) => void, an initial state that updates the editor.- Lifts
From Structure - A holder’s own hook for a child its declared
childrenallow that must still be lifted out (INTERNAL_$liftsFromStructure): the holder, the child, and whether this isINTERNAL_$normalizeNodeStructure’s normalization. - Mutated
Nodes MutatedNodes: the nodes a commit mutated by node type, in the order the reconciler first reached one of the type (JS keys itsMapby class).- Node
Caret NodeCaret: a sibling or child caret.- NodeKey
- A node’s key in its editor state’s node map. Keys are strings, as in JS,
from a per-thread counter (
generateRandomKey). - Node
Mutations - The nodes of one class a commit mutated, in the order the reconciler
reached them (JS’s
Map<NodeKey, NodeMutation>). - Node
Replace - A node replacement’s
with: given a new node of the replaced class (with a key, in the active editor state), the node to use instead, which must have a key of its own. - Shortcut
Disabled Fn - A shortcut’s
$disabled(selection, editor). - Shortcut
Dispatch Fn - A shortcut’s
$dispatch(command, event, $next, editor). - Sibling
Caret SiblingCaret: aPointCaretwhose kind isCaretKind::Sibling.- State
IsEqual - A state’s
isEqual: whether two of its values are the same value. - Text
Point Caret TextPointCaret: aPointCaretwhose kind isCaretKind::Text.- Transform
- A node transform (
Transform<T>). - Type
ToNode Map TypeToNodeMap: an editor state’s nodes by type, then by key.- Unregister
- Calling it removes what was registered, as the function JS’s
register*methods return. Dropping it without calling it keeps the registration. - Warning
Handler ErrorHandlerasonWarntakes it: it gets a warning the editor has recovered from, and what it returns is what the call that warned returns (JS’s default throws in development, as the vectors record).