Lexical Rich Text
One of Payload's goals is to build the best rich text editor experience that we possibly can. We want to combine the beauty and polish of the Medium editing experience with the strength and features of the Notion editor - all in one place.
Classically, we've used SlateJS to work toward this goal, but building custom elements into Slate has proven to be more difficult than we'd like, and we've been keeping our options open.
Lexical is extremely impressive and trivializes a lot of the hard parts of building new elements into a rich text editor. It has a few distinct advantages over Slate, including the following:
- A "/" menu, which allows editors to easily add new elements while never leaving their keyboard
- A "hover" toolbar that pops up if you select text
- It supports Payload blocks natively, directly within your rich text editor
- Custom elements, called "features", are much easier to build in Lexical vs. Slate
To use the Lexical editor, first you need to install it:
Once you have it installed, you can pass it to your top-level Payload config as follows:
You can also override Lexical settings on a field-by-field basis as follows:
Extending the lexical editor with Features
Lexical has been designed with extensibility in mind. Whether you're aiming to introduce new functionalities or tweak the existing ones, Lexical makes it seamless for you to bring those changes to life.
Features: The Building Blocks
At the heart of Lexical's customization potential are "features". While Lexical ships with a set of default features we believe are essential for most use cases, the true power lies in your ability to redefine, expand, or prune these as needed.
If you remove all the default features, you're left with a blank editor. You can then add in only the features you need, or you can build your own custom features from scratch.
Integrating New Features
To weave in your custom features, utilize the features
prop when initializing the Lexical Editor. Here's a basic example of how this is done:
Features overview
Here's an overview of all the included features:
Feature Name | Included by default | Description |
---|---|---|
BoldTextFeature | Yes | Handles the bold text format |
ItalicTextFeature | Yes | Handles the italic text format |
UnderlineTextFeature | Yes | Handles the underline text format |
StrikethroughTextFeature | Yes | Handles the strikethrough text format |
SubscriptTextFeature | Yes | Handles the subscript text format |
SuperscriptTextFeature | Yes | Handles the superscript text format |
InlineCodeTextFeature | Yes | Handles the inline-code text format |
ParagraphFeature | Yes | Handles paragraphs. Since they are already a key feature of lexical itself, this Feature mainly handles the Slash and Add-Block menu entries for paragraphs |
HeadingFeature | Yes | Adds Heading Nodes (by default, H1 - H6, but that can be customized) |
AlignFeature | Yes | Allows you to align text left, centered and right |
IndentFeature | Yes | Allows you to indent text with the tab key |
UnorderedListFeature | Yes | Adds unordered lists (ul) |
OrderedListFeature | Yes | Adds ordered lists (ol) |
CheckListFeature | Yes | Adds checklists |
LinkFeature | Yes | Allows you to create internal and external links |
RelationshipFeature | Yes | Allows you to create block-level (not inline) relationships to other documents |
BlockQuoteFeature | Yes | Allows you to create block-level quotes |
UploadFeature | Yes | Allows you to create block-level upload nodes - this supports all kinds of uploads, not just images |
HorizontalRuleFeature | Yes | Horizontal rules / separators. Basically displays an <hr> element |
BlocksFeature | No | Allows you to use Payload's Blocks Field directly inside your editor. In the feature props, you can specify the allowed blocks - just like in the Blocks field. |
TreeViewFeature | No | Adds a debug box under the editor, which allows you to see the current editor state live, the dom, as well as time travel. Very useful for debugging |
Creating your own, custom Feature
Creating your own custom feature requires deep knowledge of the Lexical editor. We recommend you take a look at the Lexical documentation first - especially the "concepts" section.
Next, take a look at the features we've already built - understanding how they work will help you understand how to create your own. There is no difference between the features included by default and the ones you create yourself - since those features are all isolated from the "core", you have access to the same APIs, whether the feature is part of payload or not!
Converters
Lexical => HTML
Lexical saves data in JSON, but can also generate its HTML representation via two main methods:
- Outputting HTML from the Collection: Create a new field in your collection to convert saved JSON content to HTML. Payload generates and outputs the HTML for use in your frontend.
- Generating HTML on any server Convert JSON to HTML on-demand on the server.
The editor comes with built-in HTML serializers, simplifying the process of converting JSON to HTML.
Outputting HTML from the Collection
To add HTML generation directly within the collection, follow the example below:
The lexicalHTML()
function creates a new field that automatically converts the referenced lexical richText field into HTML through an afterRead hook.
Generating HTML anywhere on the server:
If you wish to convert JSON to HTML ad-hoc, use this code snippet:
This method employs convertLexicalToHTML
from @payloadcms/richtext-lexical
, which converts the serialized editor state into HTML.
Because every Feature
is able to provide html converters, and because the htmlFeature
can modify those or provide their own, we need to consolidate them with the default html Converters using the consolidateHTMLConverters
function.
Creating your own HTML Converter
HTML Converters are typed as HTMLConverter
, which contains the node type it should handle, and a function that accepts the serialized node from the lexical editor, and outputs the HTML string. Here's the HTML Converter of the Upload node as an example:
As you can see, we have access to all the information saved in the node (for the Upload node, this is value
and relationTo
) and we can use that to generate the HTML.
The convertLexicalToHTML
is part of @payloadcms/richtext-lexical
automatically handles traversing the editor state and calling the correct converter for each node.
Embedding the HTML Converter in your Feature
You can embed your HTML Converter directly within your custom Feature
, allowing it to be handled automatically by the consolidateHTMLConverters
function. Here is an example:
Headless Editor
Lexical provides a seamless way to perform conversions between various other formats:
- HTML to Lexical (or, importing HTML into the lexical editor)
- Markdown to Lexical (or, importing Markdown into the lexical editor)
- Lexical to Markdown
A headless editor can perform such conversions outside of the main editor instance. Follow this method to initiate a headless editor:
Getting the editor config
As you can see, you need to provide an editor config in order to create a headless editor. This is because the editor config is used to determine which nodes & features are enabled, and which converters are used.
To get the editor config, simply import the default editor config and adjust it - just like you did inside of the editor: lexicalEditor({})
property:
HTML => Lexical
Once you have your headless editor instance, you can use it to convert HTML to Lexical:
Functions prefixed with a $
can only be run inside of an editor.update()
or editorState.read()
callback.
This has been taken from the lexical serialization & deserialization docs.
Markdown => Lexical
Convert markdown content to the Lexical editor format with the following:
Lexical => Markdown
Export content from the Lexical editor into Markdown format using these steps:
- Import your current editor state into the headless editor.
- Convert and fetch the resulting markdown string.
Here's the code for it:
The .setEditorState()
function immediately updates your editor state. Thus, there's no need for the discrete: true
flag when reading the state afterward.
Lexical => Plain Text
Export content from the Lexical editor into plain text using these steps:
- Import your current editor state into the headless editor.
- Convert and fetch the resulting plain text string.
Here's the code for it:
Migrating from Slate
While both Slate and Lexical save the editor state in JSON, the structure of the JSON is different.
Migration via SlateToLexicalFeature
One way to handle this is to just give your lexical editor the ability to read the slate JSON.
Simply add the SlateToLexicalFeature
to your editor:
and done! Now, everytime this lexical editor is initialized, it converts the slate date to lexical on-the-fly. If the data is already in lexical format, it will just pass it through.
This is by far the easiest way to migrate from Slate to Lexical, although it does come with a few caveats:
- There is a performance hit when initializing the lexical editor
- The editor will still output the Slate data in the output JSON, as the on-the-fly converter only runs for the admin panel
The easy way to solve this: Just save the document! This overrides the slate data with the lexical data, and the next time the document is loaded, the lexical data will be used. This solves both the performance and the output issue for that specific document.
Migration via migration script
The method described above does not solve the issue for all documents, though. If you want to convert all your documents to lexical, you can use a migration script. Here's a simple example:
The convertSlateToLexical
is the same method used in the SlateToLexicalFeature
- it handles traversing the Slate JSON for you.
Do note that this script might require adjustment depending on your document structure, especially if you have nested richText fields or localization enabled.
Converting custom Slate nodes
If you have custom Slate nodes, create a custom converter for them. Here's the Upload converter as an example:
It's pretty simple: You get a Slate node as input, and you return the lexical node. The nodeTypes
array is used to determine which Slate nodes this converter can handle.
When using a migration script, you can add your custom converters to the converters
property of the convertSlateToLexical
props, as seen in the example above
When using the SlateToLexicalFeature
, you can add your custom converters to the converters
property of the SlateToLexicalFeature
props:
Migrating from payload-plugin-lexical
Migrating from payload-plugin-lexical works similar to migrating from Slate.
Instead of a SlateToLexicalFeature
there is a LexicalPluginToLexicalFeature
you can use. And instead of convertSlateToLexical
you can use convertLexicalPluginToLexical
.
Coming Soon
Lots more documentation will be coming soon, which will show in detail how to create your own custom features within Lexical.
For now, take a look at the TypeScript interfaces and let us know if you need a hand. Much more will be coming from the Payload team on this topic soon.