Server-side rendering
This library supports rendering an editor as an HTML string on a server and mounting the editor on the client. This has multiple advantages. Layout shifts can be completely avoided, and the editors will be visible before the JavaScript has been executed. This is the method used to render editors on this documentation website.
Rendering on the server
Section titled “Rendering on the server”renderEditor()
renders an editor with the specified RenderOptions
as an HTML string.
Rainbow brackets
Section titled “Rainbow brackets”The tokenizeCallback
option can be used to modify the tokens before they’re stringified. If you’re using an extension that modifies tokens such as matchBrackets()
, the same modifications should be done on the server to prevent the editor from flashing with incorrect tokens.
Overlays
Section titled “Overlays”The overlays
option accepts an array of functions that will be called with the current RenderOptions
. Any HTML returned by them will be inserted inside the overlays element. This can be used to server render indentation guides for example.
Mounting on the client
Section titled “Mounting on the client”The editors created from plain HTML are obviously not interactive. They must be mounted on the client using mountEditorsUnder()
. This function mounts all editors under the specified root in document order. Editors that have already been mounted are skipped.
Adding extensions
Section titled “Adding extensions”The second argument receives the options for an editor and returns the extensions that editor should be initialized with. This means you can add different extensions to editors with different options.
Adding extra options
Section titled “Adding extra options”You can define extra properties for renderEditor()
that will get stringified as JSON and later parsed by mountEditorsUnder()
. This can be very useful for configuring which extensions to add. In the example below, we are adding a _pairs
option to customize which characters are matched together by matchBrackets()
.
The editor below now matches <
and >
inside tags together. Try clicking on one of the tags.
Usage in practice
Section titled “Usage in practice”Many of the examples shown on this page might seem abstract. This is because the SSR utilities are meant to be usable with many technologies. It’s your job to integrate this API with the server-side framework or static-site generator you’re using. Here’s a working example for astro.
With markdown
Section titled “With markdown”There are markdown plugins for both rehype and marked that can create editors from fenced code blocks. These use renderEditor()
under the hood. Read their documentation to learn more.