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.
Payload's Lexical rich text editor is currently in beta. It's stable enough to use as you build on Payload, so if you're up for helping us fine-tune it, you should use it. But if you're looking for stability, use Slate instead.
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:
npm install @payloadcms/richtext-lexical
Once you have it installed, you can pass it to your top-level Payload config as follows:
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.
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.
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 (ol)
OrderedListFeature
Yes
Adds ordered lists (ul)
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
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 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!
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 the Frontend: Convert JSON to HTML on-demand, either in your frontend or elsewhere.
The editor comes with built-in HTML serializers, simplifying the process of converting JSON to HTML.
To add HTML generation directly within the collection, follow the example below:
import type {CollectionConfig}from'payload/types'
import{
HTMLConverterFeature,
lexicalEditor,
lexicalHTML
}from'@payloadcms/richtext-lexical'
constPages:CollectionConfig={
slug:'pages',
fields:[
{
name:'nameOfYourRichTextField',
type:'richText',
editor:lexicalEditor({
features:({ defaultFeatures })=>[
...defaultFeatures,
// The HTMLConverter Feature is the feature which manages the HTML serializers. If you do not pass any arguments to it, it will use the default serializers.
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.
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:
import type {HTMLConverter}from'@payloadcms/richtext-lexical'
nodeTypes:[UploadNode.getType()],// This is the type of the lexical node that this converter can handle. Instead of hardcoding 'upload' we can get the node type directly from the UploadNode, since it's static.
}
As you can see, we have access to all the information saved in the node (for the Upload node, this is valueand 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.
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:
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:
import{ defaultEditorConfig, defaultEditorFeatures }from'@payloadcms/richtext-lexical'// <= make sure this package is installed
const yourEditorConfig = defaultEditorConfig
// If you made changes to the features of the field's editor config, you should also make those changes here:
Using the discrete: true flag ensures instant updates to the editor state. If immediate reading of the updated state isn't necessary, you can omit the flag.
The .setEditorState() function immediately updates your editor state. Thus, there's no need for the discrete: true flag when reading the state afterward.
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:
import type {CollectionConfig}from'payload/types'
import{
SlateToLexicalFeature,
lexicalEditor,
}from'@payloadcms/richtext-lexical'
constPages:CollectionConfig={
slug:'pages',
fields:[
{
name:'nameOfYourRichTextField',
type:'richText',
editor:lexicalEditor({
features:({ defaultFeatures })=>[
...defaultFeatures,
SlateToLexicalFeature({})
],
}),
},
],
}
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.
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:
import type {Payload}from'payload'
import type {YourDocumentType}from'payload/generated-types'
if(richText &&Array.isArray(richText)&&!('root'in richText)){// It's Slate data - skip already-converted data
const converted =convertSlateToLexical({
converters: converters,
slateData: richText,
})
await payload.update({
id: doc.id,
collection: collectionName as any,
data:{
[fieldName]: converted,
},
})
}
})
// Wait for all promises in the batch to complete. Resolving batches of 20 asynchronously is faster than waiting for each doc to update individually
awaitPromise.all(promises)
// Update the count of processed docs
processed += batch.length
console.log(`Converted ${processed} of ${docs.length}`)
}
}
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.
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:
Instead of a SlateToLexicalFeature there is a LexicalPluginToLexicalFeature you can use. And instead of convertSlateToLexical you can use convertLexicalPluginToLexical.
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.