slate.js is a fully customizable framework for building rich text editors. Here we use slate.js to build a rich text editor focused on document editing.
A rich text editor is a text editor that can be embedded in a browser and provides a what-you-see-is-what-you-get editing experience. There are many out-of-the-box rich text editors available, such as UEditor and WangEditor. They may have limited customization, but they offer quick implementation and visible results. On the other hand, frameworks like Draft.js and Slate.js serve as the core or controller of a rich text editor, providing high customizability but requiring more development time. When considering practical application or technology selection, it is important to conduct thorough research, as there is no absolute advantage or disadvantage of a framework in business scenarios – it's all about suitability.
The slate framework's design principles are described in its documentation:
Plugins are first-class citizens, meaning you can fully customize the editing experience to build complex editors like those of Medium or Dropbox without struggling against the library's defaults.
Lean schema core, providing minimal presets for the data structure you're editing, allowing complex use cases without being hindered by predefined content.
Nested document model, similar to the DOM, enabling the construction of complex components such as tables or nested references for advanced use cases, while also supporting a simple single-level structure.
Like the DOM, slate's data model is based on a nested tree, using text selections and ranges, and exposing all standard event handling functions. This means that advanced features like tables and nested references, almost anything possible in the DOM, can be achieved in slate.
Intuitive commands, executing commands for editing that are designed to be highly intuitive, providing expressive customizability and greatly enhancing code understanding.
Collaborative data model, designed to allow collaboration edits at the top level, meaning that implementing collaborative editing won't require a complete overhaul.
Clear core boundaries, using a plugin-focused structure and lean core, ensuring clear boundaries between core and customization, preventing core editing experience from being troubled by various edge cases.
As mentioned earlier, slate is just a core. In other words, it doesn't provide various rich text editing features; all rich text functionality needs to be implemented using its provided API, even its plugin mechanism needs to be extended manually. Although slate's documentation is not very detailed, its examples are quite rich. It also provides a tutorial as a starting point, making it relatively friendly for beginners. Here, we have built a rich text editor focused on document editing, with a lot of references to the interaction and UI of the Feishu Documents. Overall, there are quite a few challenges, especially in terms of interaction strategies, but with proper fallbacks, implementing basic document editor functionality is not a problem. The slate version used here is 0.80.0, and it's worth noting that framework strategies may adjust in the future, so pay attention to version information as well.
As mentioned earlier, slate itself does not provide a plugin registration mechanism, as can be seen directly in the documentation's tutorial. It also exposes some props to extend slate's functionality, such as renderElement, renderLeaf, and onKeyDown. It can be observed that slate maintains data and rendering separately, and what we need to do is maintain the data structure and decide how to render a certain type of data. Therefore, we need to implement our plugin extension scheme based on these registration mechanisms.
This is the final implementation code of the tutorial in the documentation. It provides a simple understanding of slate's control handling. We can see that the rendering of block-level elements, such as <CodeElement />, is achieved through renderElement, and the rendering of inline elements, such as the bold style, is achieved through renderLeaf. In onKeyDown, we can see that by listening to keyboard input, we perform some data processing on slate's maintained data through Transforms, write attributes into the data structure by matching Node, and then render them using the two render props. This is how slate's extension mechanism and data rendering separation work.
const initialValue =[{ type:'paragraph', children:[{ text:'A line of text in a paragraph.'}],},]constApp=()=>{const[editor]=useState(()=>withReact(createEditor()))
const renderElement =useCallback(props=>{switch(props.element.type){case'code':return<CodeElement {...props}/>default:return<DefaultElement {...props}/>}},[])// Define a leaf rendering function that is memoized with `useCallback`.const renderLeaf =useCallback(props=>{return<Leaf {...props}/>},[])return(<Slate editor={editor} value={initialValue}><Editable
renderElement={renderElement}// Pass in the `renderLeaf` function. renderLeaf={renderLeaf} onKeyDown={event=>{if(!event.ctrlKey){return}switch(event.key){case'`':{ event.preventDefault()const[match]= Editor.nodes(editor,{match:n=> n.type ==='code',}) Transforms.setNodes( editor,{type: match ?null:'code'},{match:n=> Editor.isBlock(editor, n)})break}case'b':{ event.preventDefault() Transforms.setNodes( editor,{bold:true},{match:n=> Text.isText(n),split:true})break}}}}/></Slate>)constLeaf=props=>{return(<span
{...props.attributes} style={{fontWeight: props.leaf.bold ?'bold':'normal'}}>{props.children}</span>)}
In the previous section, we learned about the extension and data processing methods of slate plugins, and we can see that this basic plugin registration method is still quite cumbersome. Therefore, we can implement our own plugin registration method to uniformly encapsulate the plugin registration form to extend slate. Here, the plugin registration is implemented through slate-plugins.tsx. Specifically, each plugin is a function that must return a Plugin type. Of course, it is also possible to directly define an object, but the advantage of using a function is that it can pass parameters when registered, so generally a function is directly used for definition.
key: Represents the name of the plugin, which generally cannot be repeated.
priority: Indicates the execution priority of the plugin, and is usually used to wrap the component of renderLine.
command: Registers the command of the plugin, which is the function that needs to be executed when the toolbar is clicked or a shortcut key is pressed.
onKeyDown: The keyboard event handling function, which can be used to specify the specific behavior of operations such as Enter or delete.
type: Marks whether it is block or inline.
match: Only the plugin that returns true will be executed.
renderLine: Used for the component of block, usually used to wrap a layer of component around its child elements.
render: For the specific rendering of the block component, it is determined by this function, and for the inline component, it behaves the same as renderLine for block.
typeBasePlugin={ key:string; priority?:number;// The higher the priority, the further out it is command?: CommandFn; onKeyDown?:(event: React.KeyboardEvent<HTMLDivElement>)=>boolean|void;};typeElementPlugin= BasePlugin &{ type:typeofEDITOR_ELEMENT_TYPE.BLOCK;match:(props: RenderElementProps)=>boolean; renderLine?:(context: ElementContext)=>JSX.Element; render?:(context: ElementContext)=>JSX.Element;};typeLeafPlugin= BasePlugin &{ type:typeofEDITOR_ELEMENT_TYPE.INLINE;match:(props: RenderLeafProps)=>boolean; render?:(context: LeafContext)=>JSX.Element;};
In the specific implementation, we use the instantiation of classes. After instantiation, we can continuously add plugins. Because the toolbar and other plugins are responsible for executing commands, we need to first obtain the commands of the previously registered plugins, pass them in, and then register them to the plugins. Through this registration mechanism, we achieve unified plugin management. After apply, we can pass the returned value into <Editable />, and the plugins can be seamlessly integrated into slate.
In slate, a good type extension mechanism is provided, which can be used to extend the types of BlockElement and TextElement through declare module in TypeScript, combined with interface, to provide strict type checking for plugin attributes.
Here is the specific plugin implementation approach and examples. Each section represents the implementation of a specific type of plugin. The specific code can be found on Github. In terms of plugin implementation, we mainly leverage HTML5 tags to achieve various styles, which helps maintain the semantic integrity of the document, but may result in deep DOM nesting. It's also feasible to use pure CSS to implement various plugins, which is simpler in implementation. The context provides classList to manipulate className, but the semantic integrity of the tags is somewhat compromised when using pure CSS for styling. This is mainly a matter of trade-off. The plugins implemented here are all based on HTML5 tags and some custom interaction strategies. Interactions are executed by triggering the implementation after registering commands for the plugin.
The leaf type of plugin is an inline element, such as bold, italics, underline, and strikethrough. In its implementation, you only need to pay attention to the registration of the plugin's command and how to render the element under that command. Below is the implementation of the bold plugin, mainly registering the command for manipulating attributes and using <strong /> as the rendering format tag.
The element type of plugin belongs to block-level elements, such as headers, paragraphs, and alignment. Simply put, it acts on elements within a line. In its implementation, you not only need to pay attention to the registration of commands and rendering elements but also to various cases, especially when nested in a wrapper. In the example of heading below, during the command phase, it handles whether it is already in a heading state, if so, it cancels the heading. The generated id is intended for later use as an anchor point. When handling keyboard events, you need to handle some cases, such as ensuring that when pressing Enter, the next line does not inherit the heading format. Also, when the cursor is placed at the beginning of the line and you click delete, it will remove the header format for that line.
The wrapper type plugin also belongs to block-level elements, such as block quotes, ordered lists, unordered lists, etc. In simple terms, it nests an additional line on the line. Therefore, in the implementation, we not only need to pay attention to the registration of commands and rendering elements, but also need to pay attention to various cases. There are particularly many cases to consider under wrapper, so we need to implement some strategies to avoid these problems ourselves. In the quote-block example below, support for first-level block quotes is implemented. Pressing Enter inherits the format. As a wrapped plugin, it cannot be used in parallel with other wrapped plugins. If the line is empty and the line is the first or last line of a wrapped block quote, pressing Enter or Delete will cancel the block quote format of the line. Clicking to delete at the beginning of the line and the line is the first or last line of a wrapped block quote will also cancel the block quote format of the line.
The plugin of type void also belongs to block-level elements, such as dividing lines, images, videos, etc. The void element should be an empty element with an empty text child node for rendering, and it is not editable, so it is a separate type of node. In the example of dividing-line below, special attention should be paid to the selection of the dividing line and the definition of the void node.
The toolbar type of plugin belongs to a custom category of plugins, mainly used for executing commands. Since we registered commands when defining the plugin, it means that we can completely drive the node changes through commands. The toolbar is used to execute commands. In the doc-toolbar example below, we can see how to implement the floating menu on the left and execute commands.
The shortcut type plugin belongs to a custom category of plugins, also used for executing commands with keyboard shortcuts, which is another implementation driven by commands. In the shortcut example below, we can see how to handle keyboard shortcut inputs and execute commands.