## Why this exists
Lexical in Payload is a React Server Component (RSC). Historically that
created three headaches:
1. You couldn’t render the editor directly from the client.
2. Features like blocks, tables, upload and link drawers require the
server to know the shape of nested sub‑fields at render time. If you
tried to render on demand, the server didn’t know those schemas.
3. The rich text field is designed to live inside a Form. For simple use
cases, setting up a full form just to manage editor state was
cumbersome.
## What’s new
We now ship a client component, `<RenderLexical />`, that renders a
Lexical editor **on demand** while still covering the full feature set.
On mount, it calls a server action to render the editor on the server
using the new `render-field` server action. That server render gives
Lexical everything it needs (including nested field schemas) and returns
a ready‑to‑hydrate editor.
## Example - Rendering in custom component within existing Form
```tsx
'use client'
import type { JSONFieldClientComponent } from 'payload'
import { buildEditorState, RenderLexical } from '@payloadcms/richtext-lexical/client'
import { lexicalFullyFeaturedSlug } from '../../slugs.js'
export const Component: JSONFieldClientComponent = (args) => {
return (
<div>
Fully-Featured Component:
<RenderLexical
field={{ name: 'json' }}
initialValue={buildEditorState({ text: 'defaultValue' })}
schemaPath={`collection.${lexicalFullyFeaturedSlug}.richText`}
/>
</div>
)
}
```
## Example - Rendering outside of Form, manually managing richText
values
```ts
'use client'
import type { DefaultTypedEditorState } from '@payloadcms/richtext-lexical'
import type { JSONFieldClientComponent } from 'payload'
import { buildEditorState, RenderLexical } from '@payloadcms/richtext-lexical/client'
import React, { useState } from 'react'
import { lexicalFullyFeaturedSlug } from '../../slugs.js'
export const Component: JSONFieldClientComponent = (args) => {
const [value, setValue] = useState<DefaultTypedEditorState | undefined>(() =>
buildEditorState({ text: 'state default' }),
)
const handleReset = React.useCallback(() => {
setValue(buildEditorState({ text: 'state default' }))
}, [])
return (
<div>
Default Component:
<RenderLexical
field={{ name: 'json' }}
initialValue={buildEditorState({ text: 'defaultValue' })}
schemaPath={`collection.${lexicalFullyFeaturedSlug}.richText`}
setValue={setValue as any}
value={value}
/>
<button onClick={handleReset} style={{ marginTop: 8 }} type="button">
Reset Editor State
</button>
</div>
)
}
```
## How it works (under the hood)
- On first render, `<RenderLexical />` calls the server function
`render-field` (wired into @payloadcms/next), passing a schemaPath.
- The server loads the exact field config and its client schema map for
that path, renders the Lexical editor server‑side (so nested features
like blocks/tables/relationships are fully known), and returns the
component tree.
- While waiting, the client shows a small shimmer skeleton.
- Inside Forms, RenderLexical plugs into the parent form via useField;
outside Forms, you can fully control the value by passing
value/setValue.
## Type Improvements
While implementing the `buildEditorState` helper function for our test
suite, I noticed some issues with our `TypedEditorState` type:
- nodes were no longer narrowed by their node.type types
- upon fixing this issue, the type was no longer compatible with the
generated types. To address this, I had to weaken the generated type a
bit.
In order to ensure the type will keep functioning as intended from now
on, this PR also adds some type tests
---
- To see the specific tasks where the Asana app for GitHub is being
used, see below:
- https://app.asana.com/0/0/1211110462564644
107 lines
3.8 KiB
TypeScript
107 lines
3.8 KiB
TypeScript
import { expect, test } from '@playwright/test'
|
|
import { AdminUrlUtil } from 'helpers/adminUrlUtil.js'
|
|
import { reInitializeDB } from 'helpers/reInitializeDB.js'
|
|
import path from 'path'
|
|
import { fileURLToPath } from 'url'
|
|
|
|
import { ensureCompilationIsDone, saveDocAndAssert } from '../../../helpers.js'
|
|
import { initPayloadE2ENoConfig } from '../../../helpers/initPayloadE2ENoConfig.js'
|
|
import { TEST_TIMEOUT_LONG } from '../../../playwright.config.js'
|
|
import { LexicalHelpers } from '../utils.js'
|
|
const filename = fileURLToPath(import.meta.url)
|
|
const currentFolder = path.dirname(filename)
|
|
const dirname = path.resolve(currentFolder, '../../')
|
|
|
|
const { beforeAll, beforeEach, describe } = test
|
|
|
|
const { serverURL } = await initPayloadE2ENoConfig({
|
|
dirname,
|
|
})
|
|
|
|
describe('Lexical On Demand', () => {
|
|
let lexical: LexicalHelpers
|
|
beforeAll(async ({ browser }, testInfo) => {
|
|
testInfo.setTimeout(TEST_TIMEOUT_LONG)
|
|
process.env.SEED_IN_CONFIG_ONINIT = 'false' // Makes it so the payload config onInit seed is not run. Otherwise, the seed would be run unnecessarily twice for the initial test run - once for beforeEach and once for onInit
|
|
const page = await browser.newPage()
|
|
await ensureCompilationIsDone({ page, serverURL })
|
|
await page.close()
|
|
})
|
|
|
|
describe('within form', () => {
|
|
beforeEach(async ({ page }) => {
|
|
await reInitializeDB({
|
|
serverURL,
|
|
snapshotKey: 'lexicalTest',
|
|
uploadsDir: [path.resolve(dirname, './collections/Upload/uploads')],
|
|
})
|
|
const url = new AdminUrlUtil(serverURL, 'OnDemandForm')
|
|
lexical = new LexicalHelpers(page)
|
|
await page.goto(url.create)
|
|
await lexical.editor.first().focus()
|
|
})
|
|
test('lexical is rendered on demand within form', async ({ page }) => {
|
|
await page.keyboard.type('Hello')
|
|
|
|
await saveDocAndAssert(page)
|
|
await page.reload()
|
|
|
|
const paragraph = lexical.editor.locator('> p')
|
|
await expect(paragraph).toHaveText('Hello')
|
|
})
|
|
|
|
test('on-demand editor within form can render nested fields', async () => {
|
|
await lexical.slashCommand('table', false)
|
|
|
|
await expect(lexical.drawer.locator('#field-rows')).toHaveValue('5')
|
|
await expect(lexical.drawer.locator('#field-columns')).toHaveValue('5')
|
|
})
|
|
})
|
|
|
|
describe('outside form', () => {
|
|
beforeEach(async ({ page }) => {
|
|
await reInitializeDB({
|
|
serverURL,
|
|
snapshotKey: 'lexicalTest',
|
|
uploadsDir: [path.resolve(dirname, './collections/Upload/uploads')],
|
|
})
|
|
const url = new AdminUrlUtil(serverURL, 'OnDemandOutsideForm')
|
|
lexical = new LexicalHelpers(page)
|
|
await page.goto(url.create)
|
|
await lexical.editor.first().focus()
|
|
})
|
|
test('lexical is rendered on demand outside form', async ({ page }) => {
|
|
await page.keyboard.type('Hello')
|
|
|
|
const paragraph = lexical.editor.locator('> p')
|
|
await expect(paragraph).toHaveText('Hellostate default')
|
|
|
|
await saveDocAndAssert(page)
|
|
await page.reload()
|
|
|
|
const paragraphAfterSave = lexical.editor.locator('> p')
|
|
await expect(paragraphAfterSave).not.toHaveText('Hellostate default') // Outside Form => Not Saved
|
|
})
|
|
|
|
test('lexical value can be controlled outside form', async ({ page }) => {
|
|
await page.keyboard.type('Hello')
|
|
|
|
const paragraph = lexical.editor.locator('> p')
|
|
await expect(paragraph).toHaveText('Hellostate default')
|
|
|
|
// Click button with text
|
|
const button = page.getByRole('button', { name: 'Reset Editor State' })
|
|
await button.click()
|
|
|
|
await expect(paragraph).toHaveText('state default')
|
|
})
|
|
|
|
test('on-demand editor outside form can render nested fields', async () => {
|
|
await lexical.slashCommand('table', false)
|
|
|
|
await expect(lexical.drawer.locator('#field-rows')).toHaveValue('5')
|
|
await expect(lexical.drawer.locator('#field-columns')).toHaveValue('5')
|
|
})
|
|
})
|
|
})
|