• Stars
    star
    16,985
  • Rank 1,511 (Top 0.04 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 3 years ago
  • Updated 10 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Lexical

GitHub Workflow Status Visit the NPM page Add yourself to our Discord Follow us on Twitter

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.

For documentation and more information about Lexical, be sure to visit the Lexical website.

Here are some examples of what you can do with Lexical:


Overview:


Getting started with React

Note: Lexical is not only limited to React. Lexical can support any underlying DOM based library once bindings for that library have been created.

Install lexical and @lexical/react:

npm install --save lexical @lexical/react

Below is an example of a basic plain text editor using lexical and @lexical/react (try it yourself).

import {$getRoot, $getSelection} from 'lexical';
import {useEffect} from 'react';

import {LexicalComposer} from '@lexical/react/LexicalComposer';
import {PlainTextPlugin} from '@lexical/react/LexicalPlainTextPlugin';
import {ContentEditable} from '@lexical/react/LexicalContentEditable';
import {HistoryPlugin} from '@lexical/react/LexicalHistoryPlugin';
import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary';

const theme = {
  // Theme styling goes here
  // ...
}

// When the editor changes, you can get notified via the
// LexicalOnChangePlugin!
function onChange(editorState) {
  editorState.read(() => {
    // Read the contents of the EditorState here.
    const root = $getRoot();
    const selection = $getSelection();

    console.log(root, selection);
  });
}

// Lexical React plugins are React components, which makes them
// highly composable. Furthermore, you can lazy load plugins if
// desired, so you don't pay the cost for plugins until you
// actually use them.
function MyCustomAutoFocusPlugin() {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    // Focus the editor when the effect fires!
    editor.focus();
  }, [editor]);

  return null;
}

// Catch any errors that occur during Lexical updates and log them
// or throw them as needed. If you don't throw them, Lexical will
// try to recover gracefully without losing user data.
function onError(error) {
  console.error(error);
}

function Editor() {
  const initialConfig = {
    namespace: 'MyEditor',
    theme,
    onError,
  };

  return (
    <LexicalComposer initialConfig={initialConfig}>
      <PlainTextPlugin
        contentEditable={<ContentEditable />}
        placeholder={<div>Enter some text...</div>}
        ErrorBoundary={LexicalErrorBoundary}
      />
      <OnChangePlugin onChange={onChange} />
      <HistoryPlugin />
      <MyCustomAutoFocusPlugin />
    </LexicalComposer>
  );
}

Lexical is a framework

The core of Lexical is a dependency-free text editor framework that allows developers to build powerful, simple and complex, editor surfaces. Lexical has a few concepts that are worth exploring:

Editor instances

Editor instances are the core thing that wires everything together. You can attach a contenteditable DOM element to editor instances, and also register listeners and commands. Most importantly, the editor allows for updates to its EditorState. You can create an editor instance using the createEditor() API, however you normally don't have to worry when using framework bindings such as @lexical/react as this is handled for you.

Editor States

An Editor State is the underlying data model that represents what you want to show on the DOM. Editor States contain two parts:

  • a Lexical node tree
  • a Lexical selection object

Editor States are immutable once created, and in order to create one, you must do so via editor.update(() => {...}). However, you can also "hook" into an existing update using node transforms or command handlers โ€“ which are invoked as part of an existing update workflow to prevent cascading/waterfalling of updates. You can retrieve the current editor state using editor.getEditorState().

Editor States are also fully serializable to JSON and can easily be serialized back into the editor using editor.parseEditorState().

Editor Updates

When you want to change something in an Editor State, you must do it via an update, editor.update(() => {...}). The closure passed to the update call is important. It's a place where you have full "lexical" context of the active editor state, and it exposes access to the underlying Editor State's node tree. We promote using $ prefixed functions in this context, as it signifies a place where they can be used exclusively. Attempting to use them outside of an update will trigger a runtime error with an appropriate error. For those familiar with React Hooks, you can think of these as having a similar functionality (except $ functions can be used in any order).

DOM Reconciler

Lexical has its own DOM reconciler that takes a set of Editor States (always the "current" and the "pending") and applies a "diff" on them. It then uses this diff to update only the parts of the DOM that need changing. You can think of this as a kind-of virtual DOM, except Lexical is able to skip doing much of the diffing work, as it knows what was mutated in a given update. The DOM reconciler adopts performance optimizations that benefit the typical heuristics of a content editable โ€“ and is able to ensure consistency for LTR and RTL languages automatically.

Listeners, Node Transforms and Commands

Outside of invoking updates, the bulk of work done with Lexical is via listeners, node transforms and commands. These all stem from the editor and are prefixed with register. Another important feature is that all the register methods return a function to easily unsubscribe them. For example here is how you listen to an update to a Lexical editor:

const unregisterListener = editor.registerUpdateListener(({editorState}) => {
  // An update has occurred!
  console.log(editorState);
});

// Ensure we remove the listener later!
unregisterListener();

Commands are the communication system used to wire everything together in Lexical. Custom commands can be created using createCommand() and dispatched to an editor using editor.dispatchCommand(command, payload). Lexical dispatches commands internally when key presses are triggered and when other important signals occur. Commands can also be handled using editor.registerCommand(handler, priority), and incoming commands are propagated through all handlers by priority until a handler stops the propagation (in a similar way to event propagation in the browser).

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().

Working with Editor States

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 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, $createParagraphNode} from 'lexical';

// 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.
  });
});

Creating custom Lexical nodes

Contributing to Lexical

  1. Clone this repository

  2. Install dependencies

    • npm install
  3. Start local server and run tests

    • npm run start
    • npm run test-e2e-chromium to run only chromium e2e tests
      • The server needs to be running for the e2e tests

npm run start will start both the dev server and collab server. If you don't need collab, use npm run dev to start just the dev server.

Optional but recommended, use VSCode for development

  1. Download and install VSCode

    • Download from here (itโ€™s recommended to use the unmodified version)
  2. Install extensions

    • Flow Language Support
      • Make sure to follow the setup steps in the README
    • Prettier
      • Set prettier as the default formatter in editor.defaultFormatter
      • Optional: set format on save editor.formatOnSave
    • ESlint

Documentation

Browser Support

  • Firefox 52+
  • Chrome 49+
  • Edge 79+ (when Edge switched to Chromium)
  • Safari 11+
  • iOS 11+ (Safari)
  • iPad OS 13+ (Safari)
  • Android Chrome 72+

Note: Lexical does not support Internet Explorer or legacy versions of Edge.

Contributing

  1. Create a new branch
    • git checkout -b my-new-branch
  2. Commit your changes
    • git commit -a -m 'Description of the changes'
      • There are many ways of doing this and this is just a suggestion
  3. Push your branch to GitHub
    • git push origin my-new-branch
  4. Go to the repository page in GitHub and click on "Compare & pull request"
    • The GitHub CLI allows you to skip the web interface for this step (and much more)

Support

If you have any questions about Lexical, would like to discuss a bug report, or have questions about new integrations, feel free to join us at our Discord server.

Lexical engineers are checking this regularly.

Running tests

  • npm run test-unit runs only unit tests.
  • npm run test-e2e-chromium runs only chromium e2e tests.
  • npm run debug-test-e2e-chromium runs only chromium e2e tests in head mode for debugging.
  • npm run test-e2e-firefox runs only firefox e2e tests.
  • npm run debug-test-e2e-firefox runs only firefox e2e tests in head mode for debugging.
  • npm run test-e2e-webkit runs only webkit e2e tests.
  • npm run debug-test-e2e-webkit runs only webkit e2e tests in head mode for debugging.

License

Lexical is MIT licensed.

More Repositories

1

react

The library for web and native user interfaces.
JavaScript
218,990
star
2

react-native

A framework for building native applications using React
C++
114,975
star
3

create-react-app

Set up a modern web app by running one command.
JavaScript
101,534
star
4

docusaurus

Easy to maintain open source documentation websites.
TypeScript
51,169
star
5

jest

Delightful JavaScript Testing.
TypeScript
41,554
star
6

rocksdb

A library that provides an embeddable, persistent key-value store for fast storage.
C++
26,895
star
7

folly

An open-source C++ library developed and used at Facebook.
C++
26,731
star
8

flow

Adds static typing to JavaScript to improve developer productivity and code quality.
OCaml
22,040
star
9

zstd

Zstandard - Fast real-time compression algorithm
C
21,685
star
10

relay

Relay is a JavaScript framework for building data-driven React applications.
Rust
18,099
star
11

hhvm

A virtual machine for executing programs written in Hack.
C++
17,960
star
12

prophet

Tool for producing high quality forecasts for time series data that has multiple seasonality with linear or non-linear growth.
Python
17,624
star
13

fresco

An Android library for managing images and the memory they use.
Java
17,026
star
14

yoga

Yoga is a cross-platform layout engine which implements Flexbox. Follow https://twitter.com/yogalayout for updates.
C++
16,729
star
15

infer

A static analyzer for Java, C, C++, and Objective-C
OCaml
14,599
star
16

flipper

A desktop debugging platform for mobile developers.
TypeScript
13,124
star
17

watchman

Watches files and records, or triggers actions, when they change.
C++
12,124
star
18

react-devtools

An extension that allows inspection of React component hierarchy in the Chrome and Firefox Developer Tools.
11,024
star
19

hermes

A JavaScript engine optimized for running React Native.
C++
9,167
star
20

chisel

Chisel is a collection of LLDB commands to assist debugging iOS apps.
Python
9,072
star
21

jscodeshift

A JavaScript codemod toolkit.
JavaScript
8,850
star
22

buck

A fast build system that encourages the creation of small, reusable modules over a variety of platforms and languages.
Java
8,568
star
23

proxygen

A collection of C++ HTTP libraries including an easy to use HTTP server.
C++
7,978
star
24

stylex

StyleX is the styling system for ambitious user interfaces.
JavaScript
7,921
star
25

facebook-ios-sdk

Used to integrate the Facebook Platform with your iOS & tvOS apps.
Swift
7,644
star
26

litho

A declarative framework for building efficient UIs on Android.
Java
7,633
star
27

pyre-check

Performant type-checking for python.
OCaml
6,620
star
28

facebook-android-sdk

Used to integrate Android apps with Facebook Platform.
Kotlin
6,020
star
29

redex

A bytecode optimizer for Android apps
C++
5,951
star
30

componentkit

A React-inspired view framework for iOS.
Objective-C++
5,740
star
31

sapling

A Scalable, User-Friendly Source Control System.
Rust
5,635
star
32

fishhook

A library that enables dynamically rebinding symbols in Mach-O binaries running on iOS.
C
5,061
star
33

PathPicker

PathPicker accepts a wide range of input -- output from git commands, grep results, searches -- pretty much anything. After parsing the input, PathPicker presents you with a nice UI to select which files you're interested in. After that you can open them in your favorite editor or execute arbitrary commands.
Python
5,033
star
34

metro

๐Ÿš‡ The JavaScript bundler for React Native
JavaScript
4,996
star
35

prop-types

Runtime type checking for React props and similar objects
JavaScript
4,427
star
36

idb

idb is a flexible command line interface for automating iOS simulators and devices
Objective-C
4,356
star
37

Haxl

A Haskell library that simplifies access to remote data, such as databases or web-based services.
Haskell
4,220
star
38

FBRetainCycleDetector

iOS library to help detecting retain cycles in runtime.
Objective-C++
4,178
star
39

memlab

A framework for finding JavaScript memory leaks and analyzing heap snapshots
TypeScript
4,088
star
40

duckling

Language, engine, and tooling for expressing, testing, and evaluating composable language rules on input strings.
Haskell
3,995
star
41

fbt

A JavaScript Internationalization Framework
JavaScript
3,836
star
42

regenerator

Source transformer enabling ECMAScript 6 generator functions in JavaScript-of-today.
JavaScript
3,795
star
43

mcrouter

Mcrouter is a memcached protocol router for scaling memcached deployments.
C++
3,186
star
44

buck2

Build system, successor to Buck
Rust
3,177
star
45

wangle

Wangle is a framework providing a set of common client/server abstractions for building services in a consistent, modular, and composable way.
C++
3,016
star
46

wdt

Warp speed Data Transfer (WDT) is an embeddedable library (and command line tool) aiming to transfer data between 2 systems as fast as possible over multiple TCP paths.
C++
2,827
star
47

igl

Intermediate Graphics Library (IGL) is a cross-platform library that commands the GPU. It provides a single low-level cross-platform interface on top of various graphics APIs (e.g. OpenGL, Metal and Vulkan).
C++
2,674
star
48

fbthrift

Facebook's branch of Apache Thrift, including a new C++ server.
C++
2,513
star
49

mysql-5.6

Facebook's branch of the Oracle MySQL database. This includes MyRocks.
C++
2,423
star
50

Ax

Adaptive Experimentation Platform
Python
2,226
star
51

jsx

The JSX specification is a XML-like syntax extension to ECMAScript.
HTML
1,941
star
52

fbjs

A collection of utility libraries used by other Meta JS projects.
JavaScript
1,939
star
53

react-native-website

The React Native website and docs
JavaScript
1,875
star
54

screenshot-tests-for-android

Generate fast deterministic screenshots during Android instrumentation tests
Java
1,727
star
55

idx

Library for accessing arbitrarily nested, possibly nullable properties on a JavaScript object.
JavaScript
1,687
star
56

TextLayoutBuilder

An Android library that allows you to build text layouts more easily.
Java
1,464
star
57

mvfst

An implementation of the QUIC transport protocol.
C++
1,384
star
58

SoLoader

Native code loader for Android
Java
1,269
star
59

facebook-python-business-sdk

Python SDK for Meta Marketing APIs
Python
1,211
star
60

ThreatExchange

Trust & Safety tools for working together to fight digital harms.
C++
1,092
star
61

mariana-trench

A security focused static analysis tool for Android and Java applications.
C++
1,022
star
62

CacheLib

Pluggable in-process caching engine to build and scale high performance services
C++
1,018
star
63

fatal

Fatal is a library for fast prototyping software in modern C++. It provides facilities to enhance the expressive power of C++. The library is heavily based on template meta-programming, while keeping the complexity under-the-hood.
C++
993
star
64

transform360

Transform360 is an equirectangular to cubemap transform for 360 video.
C
991
star
65

openr

Distributed platform for building autonomic network functions.
C++
879
star
66

fboss

Facebook Open Switching System Software for controlling network switches.
C++
842
star
67

facebook-php-business-sdk

PHP SDK for Meta Marketing API
PHP
787
star
68

ktfmt

A program that reformats Kotlin source code to comply with the common community standard for Kotlin code conventions.
Kotlin
776
star
69

winterfell

A STARK prover and verifier for arbitrary computations
Rust
691
star
70

pyre2

Python wrapper for RE2
C++
629
star
71

openbmc

OpenBMC is an open software framework to build a complete Linux image for a Board Management Controller (BMC).
C
607
star
72

SPARTA

SPARTA is a library of software components specially designed for building high-performance static analyzers based on the theory of Abstract Interpretation.
C++
604
star
73

chef-cookbooks

Open source chef cookbooks.
Ruby
561
star
74

IT-CPE

Meta's Client Platform Engineering tools. Some of the tools we have written to help manage our fleet of client systems.
Ruby
553
star
75

time

Meta's Time libraries
Go
471
star
76

facebook-nodejs-business-sdk

Node.js SDK for Meta Marketing APIs
JavaScript
464
star
77

facebook-sdk-for-unity

The facebook sdk for unity.
C#
461
star
78

lexical-ios

Lexical iOS is an extensible text editor framework that integrates the APIs and philosophies from Lexical Web with a Swift API built on top of TextKit.
Swift
446
star
79

Rapid

The OpenStreetMap editor driven by open data, AI, and supercharged features
JavaScript
425
star
80

FAI-PEP

Facebook AI Performance Evaluation Platform
Python
379
star
81

facebook-java-business-sdk

Java SDK for Meta Marketing APIs
Java
374
star
82

chef-utils

Utilities related to Chef
Ruby
287
star
83

opaque-ke

An implementation of the OPAQUE password-authenticated key exchange protocol
Rust
262
star
84

dns

Collection of Meta's DNS Libraries
Go
251
star
85

facebook360_dep

Facebook360 Depth Estimation Pipeline - https://facebook.github.io/facebook360_dep
HTML
238
star
86

akd

An implementation of an auditable key directory
Rust
207
star
87

tac_plus

A Tacacs+ Daemon tested on Linux (CentOS) to run AAA via TACACS+ Protocol via IPv4 and IPv6.
C
205
star
88

facebook-ruby-business-sdk

Ruby SDK for Meta Marketing API
Ruby
200
star
89

dotslash

Simplified executable deployment
Rust
165
star
90

usort

Safe, minimal import sorting for Python projects.
Python
161
star
91

grocery-delivery

The Grocery Delivery utility for managing cookbook uploads to distributed Chef backends.
Ruby
151
star
92

taste-tester

Software to manage a chef-zero instance and use it to test changes on production servers.
Ruby
144
star
93

TestSlide

A Python test framework
Python
139
star
94

homebrew-fb

OS X Homebrew formulas to install Meta open source software
Ruby
122
star
95

sapp

Post Processor for Facebook Static Analysis Tools.
Python
122
star
96

squangle

SQuangLe is a C++ API for accessing MySQL servers
C++
119
star
97

threat-research

Welcome to the Meta Threat Research Indicator Repository, a dedicated resource for the sharing of Indicators of Compromise (IOCs) and other threat indicators with the external research community
Python
115
star
98

ocamlrep

Sets of libraries and tools to write applications and libraries mixing OCaml and Rust. These libraries will help keeping your types and data structures synchronized, and enable seamless exchange between OCaml and Rust
Rust
97
star
99

bpfilter

BPF-based packet filtering framework
C
79
star
100

facebook-business-sdk-codegen

Codegen project for our business SDKs
PHP
74
star