You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 7-8.RSVP
Socket
Socket
Sign inDemoInstall

lexical

Package Overview
Dependencies
Maintainers
0
Versions
134
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lexical

Lexical is an extensible text editor framework that provides excellent reliability, accessible and performance.


Version published
Weekly downloads
386K
decreased by-15.8%
Maintainers
0
Install size
0.993 MB
Created
Weekly downloads
 

Package description

What is lexical?

Lexical is a modern, extensible text editor framework that provides a set of tools and APIs to build rich text editors with ease. It is designed to be highly performant, flexible, and easy to integrate into various applications.

What are lexical's main functionalities?

Basic Text Editing

This feature allows you to create a basic text editor instance and perform simple text editing operations such as appending text.

const { createEditor } = require('lexical');
const editor = createEditor();
editor.update(() => {
  const root = editor.getRoot();
  root.appendText('Hello, Lexical!');
});

Custom Plugins

Lexical supports custom plugins to extend the editor's functionality. This example demonstrates how to create a custom plugin that logs the editor state changes.

const { createEditor, LexicalComposer } = require('lexical');
const MyCustomPlugin = () => {
  return {
    onChange(editorState) {
      console.log('Editor state changed:', editorState);
    }
  };
};
const editor = createEditor({ plugins: [MyCustomPlugin] });

Rich Text Formatting

This feature allows you to apply rich text formatting such as bold, italic, and underline to the text within the editor.

const { createEditor, $createParagraphNode, $createTextNode } = require('lexical');
const editor = createEditor();
editor.update(() => {
  const root = editor.getRoot();
  const paragraph = $createParagraphNode();
  const text = $createTextNode('Bold Text');
  text.toggleFormat('bold');
  paragraph.append(text);
  root.append(paragraph);
});

Other packages similar to lexical

Changelog

Source

v0.16.1 (2024-07-01)

  • lexical-playgroundlexical-poll Bug Fix Fixes undefined context inside Poll add option (#6361) Roman Lyubimov
  • (docs) Add existing history page to navigation (#6359) Oliver Lassen
  • Lexical Fix broken sync due to deprecation of ReactDOMComet to ReactDOM (#6358) Sahejkm
  • lexical-html Bug Fix Preserve text alignment of nested block elements, when converting HTML to Lexical Nodes (#6340) Zigopis Nikolaos
  • Replace await with async in lexical-headlessREADME.md (#6343) Kibaek Kim
  • Bug Fix Fix selection when hitting shiftarrowdown into a table. (#6274) Serey Roth
  • Update feature request template (#6316) Sherry
  • Add impact description to bug report issue template (#6317) Sherry
  • lexical-reactlexical-dev-tools-core Bug Fix TreeView selection indicator (#6336) Ira Hopkinson
  • lexical Bug Fix Export type EditorUpdateOptions (#6332) Bob Ippolito
  • lexical-link Fix bug when cant remove link formatting from autolink (#6306) Maksym Plavinskyi
  • lexical Bug Fix Make reconcileParagraphFormat respect editor readonly state (#6295) Aleksandr Lapukin
  • LexicalGallery add option to add gallery content in Meta Intern only (#6321) Sahejkm
  • Few missing exports that are useful (#6318) Piechota
  • LexicalCI Fix issues in afterapproval workflow (#6307) Sahejkm
  • LexicalMeta Add meta intern static docs config (#6302) Sahejkm
  • lexical-playground Fix bug Insert an image inside another images caption (#6109) (#6230) Maksym Plavinskyi
  • CI Only send flaky test notice once (#6298) Sherry
  • LexicalUI Gallery Fix meta lexical website intern build errors (#6300) Sahejkm
  • CI Comment to look up Flaky test tracker on e2e test failure (#6292) Sherry
  • fix yjs collaboration plugin in react strict mode (#6271) Meron Ogbai
  • lexicaldevtools Bug Fix Fixed issue when extension devtools panel gets out of sync with background script in Chrome Edge (#6297) Vlad Fedosov
  • lexicalauto-link Fix auto link node escapes on second . (#6146) Maksym Plavinskyi
  • lexical-markdown Add test to keep code language (#6259) Vladimir Ivakin
  • lexical-playgroundlexical-devtools Fix Add missing explicit devDependencies for vite config (#6291) Bob Ippolito
  • LexicalMeta Add dependencies needed to setup lexical-website in m (#6293) Sahejkm
  • Upgrade vite version to address vulnerabilities detected by the Open (#6284) Sahejkm
  • LexicalTables Follow up on #6267 handle multi column delete crash on forward selection at end of the table (#6279) Sahejkm
  • Feature Automated nightly releases (#6204) Bob Ippolito
  • lexical-selection Fix lost autolink styling (#6275) Maksym Plavinskyi
  • Lexical Fix #6221 delete multiple column table crash (#6267) Sahejkm
  • lexical-markdown Bug Fix standardise selection to move to start after markdown toggle (#6220) Sherry
  • lexical-playground CI fix flaky MaxLength emoji e2e test (#6257) Sherry
  • LexicalCI Skip extended tests workflow run on multiple approvals (#6265) Sahejkm
  • Revert lexical-react Bug Fix checklist cannot be toggled in sub-e (#6264) Gerard Rovira
  • lexical-utils Fix mergeRegister should call cleanup functions in reverse order (#6260) Bob Ippolito
  • Lexical Fix missing meta copyright headers in files (#6258) Sahejkm
  • docsexamples Update plain text and rich text examples (#6187) Maksym Plavinskyi
  • lexical-eslint-plugin Fix Use cjs compatible export from built version (#6252) Bob Ippolito
  • Lexical Skip newly added flaky Resize merged cells heightwidth tests for linuxcollabfirefox mode (#6250) Sahejkm
  • lexical-playground CI standardise key press delay (#6246) Sherry
  • v0.16.0 (#6248) Ivaylo Pavlov
  • v0.16.0 Lexical GitHub Actions Bot

Readme

Source

lexical

See API Documentation

Lexical is an extensible JavaScript web text-editor framework with an emphasis on reliability, accessibility, and performance. Lexical aims to provide a best-in-class developer experience, so you can easily prototype and build features with confidence. Combined with a highly extensible architecture, Lexical allows developers to create unique text editing experiences that scale in size and functionality.

The core of Lexical is a dependency-free text editor engine that allows for powerful, simple and complex, editor implementations to be built on top. Lexical's engine provides three main parts:

  • editor instances that each attach to a single content editable element.
  • a set of editor states that represent the current and pending states of the editor at any given time.
  • a DOM reconciler that takes a set of editor states, diffs the changes, and updates the DOM according to their state.

By design, the core of Lexical tries to be as minimal as possible. Lexical doesn't directly concern itself with things that monolithic editors tend to do – such as UI components, toolbars or rich-text features and markdown. Instead the logic for those features can be included via a plugin interface and used as and when they're needed. This ensures great extensibility and keeps code-sizes to a minimal – ensuring apps only pay the cost for what they actually import.

For React apps, Lexical has tight integration with React 18+ via the optional @lexical/react package. This package provides production-ready utility functions, helpers and React hooks that make it seemless to create text editors within React.

Usage

The lexical package contains only the core Lexical engine and nodes. This package is intended to be used in conjunction with packages that wire Lexical up to applications, such as @lexical/react.

Working with Lexical

This section covers how to use Lexical, independently of any framework or library. For those intending to use Lexical in their React applications, it's advisable to check out the source-code for the hooks that are shipped in @lexical/react.

Creating an editor and using it

When you work with Lexical, you normally work with a single editor instance. An editor instance can be thought of as the one responsible for wiring up an EditorState with the DOM. The editor is also the place where you can register custom nodes, add listeners, and transforms.

An editor instance can be created from the lexical package and accepts an optional configuration object that allows for theming and other options:

import {createEditor} from 'lexical';

const config = {
  namespace: 'MyEditor',
  theme: {
    ...
  },
};

const editor = createEditor(config);

Once you have an editor instance, when ready, you can associate the editor instance with a content editable <div> element in your document:

const contentEditableElement = document.getElementById('editor');

editor.setRootElement(contentEditableElement);

If you want to clear the editor instance from the element, you can pass null. Alternatively, you can switch to another element if need be, just pass an alternative element reference to setRootElement().

Understanding the Editor State

With Lexical, the source of truth is not the DOM, but rather an underlying state model that Lexical maintains and associates with an editor instance. You can get the latest editor state from an editor by calling editor.getEditorState().

Editor states have two phases:

  • During an update they can be thought of as "mutable". See "Updating an editor" below to mutate an editor state.
  • After an update, the editor state is then locked and deemed immutable from there one. This editor state can therefore be thought of as a "snapshot".

Editor states contain two core things:

  • The editor node tree (starting from the root node).
  • The editor selection (which can be null).

Editor states are serializable to JSON, and the editor instance provides a useful method to deserialize stringified editor states.

const stringifiedEditorState = JSON.stringify(editor.getEditorState().toJSON());

const newEditorState = editor.parseEditorState(stringifiedEditorState);

Updating an editor

There are a few ways to update an editor instance:

  • Trigger an update with editor.update()
  • Setting the editor state via editor.setEditorState()
  • Applying a change as part of an existing update via editor.registerNodeTransform()
  • Using a command listener with editor.registerCommand(EXAMPLE_COMMAND, () => {...}, priority)

The most common way to update the editor is to use editor.update(). Calling this function requires a function to be passed in that will provide access to mutate the underlying editor state. When starting a fresh update, the current editor state is cloned and used as the starting point. From a technical perspective, this means that Lexical leverages a technique called double-buffering during updates. There's an editor state to represent what is current on the screen, and another work-in-progress editor state that represents future changes.

Creating an update is typically an async process that allows Lexical to batch multiple updates together in a single update – improving performance. When Lexical is ready to commit the update to the DOM, the underlying mutations and changes in the update will form a new immutable editor state. Calling editor.getEditorState() will then return the latest editor state based on the changes from the update.

Here's an example of how you can update an editor instance:

import {$getRoot, $getSelection} from 'lexical';
import {$createParagraphNode} from 'lexical/PargraphNode';

// Inside the `editor.update` you can use special $ prefixed helper functions.
// These functions cannot be used outside the closure, and will error if you try.
// (If you're familiar with React, you can imagine these to be a bit like using a hook
// outside of a React function component).
editor.update(() => {
  // Get the RootNode from the EditorState
  const root = $getRoot();

  // Get the selection from the EditorState
  const selection = $getSelection();

  // Create a new ParagraphNode
  const paragraphNode = $createParagraphNode();

  // Create a new TextNode
  const textNode = $createTextNode('Hello world');

  // Append the text node to the paragraph
  paragraphNode.append(textNode);

  // Finally, append the paragraph to the root
  root.append(paragraphNode);
});

If you want to know when the editor updates so you can react to the changes, you can add an update listener to the editor, as shown below:

editor.registerUpdateListener(({editorState}) => {
  // The latest EditorState can be found as `editorState`.
  // To read the contents of the EditorState, use the following API:

  editorState.read(() => {
    // Just like editor.update(), .read() expects a closure where you can use
    // the $ prefixed helper functions.
  });
});

Keywords

FAQs

Package last updated on 01 Jul 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc