Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(richtext): build the editor through LexicalExtensionComposer (#6241)

Sherryf138ed997b88
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsx
index 9781c01226..4d39dd3f83 100644
--- a/packages/richtext/src/RichTextEditor.tsx
+++ b/packages/richtext/src/RichTextEditor.tsx
@@ -4,8 +4,9 @@
/**
* @file RichTextEditor.tsx
- * @input Uses React, useId, Lexical (lexical + @lexical/react), Field,
- * VisuallyHidden, useInputStatusIcon, mergeProps, design tokens
+ * @input Uses React, useId, Lexical (lexical + @lexical/react, composed through
+ * LexicalExtensionComposer), Field, VisuallyHidden, useInputStatusIcon,
+ * mergeProps, design tokens
* @output Exports an accessibly labelled RichTextEditor component with a flush
* top toolbar slot and configurable editable-surface minimum height, RichTextEditorProps,
* RichTextEditorStatus, RichTextEditorStatusType, RichTextEditorSize
@@ -58,10 +59,7 @@ import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
import {mergeProps, themeProps, type SizeValue} from '@astryxdesign/core/utils';
import {useSize} from '@astryxdesign/core/SizeContext';
-import {
- LexicalComposer,
- type InitialConfigType,
-} from '@lexical/react/LexicalComposer';
+import {LexicalExtensionComposer} from '@lexical/react/LexicalExtensionComposer';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import {RichTextPlugin} from '@lexical/react/LexicalRichTextPlugin';
import {ContentEditable} from '@lexical/react/LexicalContentEditable';
@@ -83,10 +81,12 @@ import {DEFAULT_NODES} from './editorNodes';
import {
BLUR_COMMAND,
COMMAND_PRIORITY_LOW,
+ defineExtension,
KEY_DOWN_COMMAND,
KEY_ESCAPE_COMMAND,
KEY_TAB_COMMAND,
mergeRegister,
+ type AnyLexicalExtension,
type EditorState,
type Klass,
type LexicalEditor,
@@ -526,17 +526,35 @@ export const RichTextEditor = forwardRef<
// isn't running the transform in this repo, so this isn't auto-memoized.)
const markdownTransformers = useMemo(() => [...transformers], [transformers]);
- const initialConfig: InitialConfigType = {
- namespace,
- theme: themeRef.current,
- editable,
- editorState: defaultValue ?? undefined,
- nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],
- onError(error: Error) {
- // Surface errors to the host app rather than swallowing them.
- throw error;
- },
- };
+ // The extension replaces LexicalComposer's `initialConfig`: it carries the
+ // same editor configuration (namespace, theme, nodes, editability, initial
+ // state) in the shape LexicalBuilder consumes.
+ //
+ // LexicalExtensionComposer re-creates the editor whenever the extension's
+ // identity changes, whereas LexicalComposer read `initialConfig` exactly once
+ // on mount. Build it on first render and keep it, so the editor's lifetime —
+ // and the content it holds — is unaffected by later renders (a consumer
+ // passing an inline `nodes={[...]}` array would otherwise blow away the
+ // editor's content on every render).
+ const extensionRef = useRef<AnyLexicalExtension | null>(null);
+ if (extensionRef.current === null) {
+ extensionRef.current = defineExtension({
+ name: '@astryxdesign/richtext/RichTextEditor',
+ namespace,
+ theme: themeRef.current,
+ editable,
+ nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],
+ // `undefined` (not `null`) leaves Lexical's default initializer in place,
+ // which seeds the empty document with one paragraph — what
+ // LexicalComposer did when no `editorState` was given. `null` would mean
+ // "start from a genuinely empty root".
+ $initialEditorState: defaultValue ?? undefined,
+ onError(error: Error) {
+ // Surface errors to the host app rather than swallowing them.
+ throw error;
+ },
+ });
+ }
const hasTabEscapeHint = editable && tabEscapeHint !== '';
const hasToolbar = toolbar != null && typeof toolbar !== 'boolean';
@@ -606,7 +624,9 @@ export const RichTextEditor = forwardRef<
className,
style,
)}>
- <LexicalComposer initialConfig={initialConfig}>
+ <LexicalExtensionComposer
+ extension={extensionRef.current}
+ contentEditable={null}>
{hasToolbar ? toolbar : null}
<div
{...stylex.props(
@@ -664,7 +684,7 @@ export const RichTextEditor = forwardRef<
<div {...stylex.props(styles.statusIcon)}>{statusIcon}</div>
)}
</div>
- </LexicalComposer>
+ </LexicalExtensionComposer>
{hasTabEscapeHint && (
<VisuallyHidden id={tabEscapeHintID}>{tabEscapeHint}</VisuallyHidden>
)}
diff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsx
index b0a63cd3da..746ee1a4eb 100644
--- a/packages/richtext/src/RichTextView.tsx
+++ b/packages/richtext/src/RichTextView.tsx
@@ -4,7 +4,8 @@
/**
* @file RichTextView.tsx
- * @input Uses React, Lexical (lexical + @lexical/react), design tokens
+ * @input Uses React, Lexical (lexical + @lexical/react, composed through
+ * LexicalExtensionComposer), design tokens
* @output Exports RichTextView component and RichTextViewProps
* @position Read-only renderer for serialized Lexical editor state; experimental
* (richtext), exported from @astryxdesign/richtext
@@ -20,10 +21,7 @@ import * as stylex from '@stylexjs/stylex';
import {sharedEditorTheme} from './editorTheme';
import type {BaseProps} from '@astryxdesign/core';
-import {
- LexicalComposer,
- type InitialConfigType,
-} from '@lexical/react/LexicalComposer';
+import {LexicalExtensionComposer} from '@lexical/react/LexicalExtensionComposer';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import {RichTextPlugin} from '@lexical/react/LexicalRichTextPlugin';
import {ContentEditable} from '@lexical/react/LexicalContentEditable';
@@ -32,7 +30,13 @@ import {ListNode, ListItemNode} from '@lexical/list';
import {HeadingNode, QuoteNode} from '@lexical/rich-text';
import {LinkNode, AutoLinkNode} from '@lexical/link';
import {CodeNode, CodeHighlightNode} from '@lexical/code';
-import type {Klass, LexicalNode, EditorThemeClasses} from 'lexical';
+import type {
+ AnyLexicalExtension,
+ Klass,
+ LexicalNode,
+ EditorThemeClasses,
+} from 'lexical';
+import {defineExtension} from 'lexical';
const styles = stylex.create({
root: {
@@ -89,30 +93,28 @@ export interface RichTextViewProps extends BaseProps {
/**
* Keeps the rendered content in sync with the `value` prop after mount.
*
- * `LexicalComposer`'s `initialConfig.editorState` is only read once on mount, so
- * a plain `<RichTextView value={changingValue} />` would freeze at its first
+ * The editor's initial state is seeded once, when the composer mounts, so a
+ * plain `<RichTextView value={changingValue} />` would freeze at its first
* value — the content would never update when `value` changed. This plugin runs
* inside the composer context and re-applies `value` whenever it changes, so the
* read-only view stays reactive (e.g. previewing content edited elsewhere).
*
- * The initial `value` is already applied via `initialConfig.editorState`, so we
- * skip the first run to avoid a redundant re-parse on mount.
+ * The initial `value` is already applied via the extension's
+ * `$initialEditorState`, so we skip the first run to avoid a redundant re-parse
+ * on mount.
*
* This mirrors the canonical Lexical pattern for applying externally-sourced
* serialized state after mount: the Lexical Playground's ActionsPlugin does the
* same `editor.setEditorState(editor.parseEditorState(...))` from inside a
* plugin (see facebook/lexical
* packages/lexical-playground/src/plugins/ActionsPlugin/index.tsx). It is
- * necessary because `LexicalComposer` builds the editor in a `useMemo(..., [])`
- * and reads `initialConfig.editorState` exactly once on init
- * (packages/lexical-react/src/LexicalComposer.tsx), so a changed prop cannot
- * re-seed the editor on its own. A read-only view has no history, so we skip the
- * Playground's accompanying CLEAR_HISTORY_COMMAND.
+ * necessary because the composer builds the editor once and reads the initial
+ * state exactly once at that point, so a changed prop cannot re-seed the editor
+ * on its own. A read-only view has no history, so we skip the Playground's
+ * accompanying CLEAR_HISTORY_COMMAND.
*
* `parseEditorState` / `setEditorState` are methods on the editor instance, so
- * this avoids a top-level `lexical` *value* import (which would force the
- * sandbox's Next build to transpile lexical's raw `src/*.ts` and fail — see the
- * matching note in RichTextEditor.tsx).
+ * this plugin needs no module-level Lexical imports of its own.
*/
function SyncValuePlugin({value}: {value: string}): null {
const [editor] = useLexicalComposerContext();
@@ -154,6 +156,12 @@ export function RichTextView({
themeRef.current = sharedEditorTheme();
}
+ // Built on first render (and again after an error, below) rather than per
+ // render: LexicalExtensionComposer re-creates the editor whenever the
+ // extension's identity changes, and `value` updates are applied in place by
+ // SyncValuePlugin instead.
+ const extensionRef = useRef<AnyLexicalExtension | null>(null);
+
const [hasError, setHasError] = useState(false);
// Reset the error state when the value changes so a corrected value recovers.
@@ -171,8 +179,9 @@ export function RichTextView({
};
// Validate `value` parses as JSON before handing it to Lexical. Malformed
- // JSON would otherwise throw synchronously during LexicalComposer init and
- // escape any error boundary, taking down the host on the render path.
+ // JSON would otherwise throw synchronously while the composer builds the
+ // editor and escape any error boundary, taking down the host on the render
+ // path.
if (!hasError) {
try {
JSON.parse(value);
@@ -182,6 +191,10 @@ export function RichTextView({
}
if (hasError) {
+ // The composer subtree is unmounted while the fallback renders. Drop the
+ // extension so that recovering from the error builds a fresh one, seeded
+ // with the corrected `value`.
+ extensionRef.current = null;
return (
<div
{...stylex.props(styles.root, xstyle)}
@@ -193,16 +206,19 @@ export function RichTextView({
);
}
- const initialConfig: InitialConfigType = {
- namespace,
- theme: themeRef.current,
- editable: false,
- editorState: value,
- nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],
- // A read-only view renders persisted content; a bad node/schema should not
- // crash the host. Surface it via onParseError + fallback instead of re-throwing.
- onError: handleError,
- };
+ if (extensionRef.current === null) {
+ extensionRef.current = defineExtension({
+ name: '@astryxdesign/richtext/RichTextView',
+ namespace,
+ theme: themeRef.current,
+ editable: false,
+ nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],
+ $initialEditorState: value,
+ // A read-only view renders persisted content; a bad node/schema should not
+ // crash the host. Surface it via onParseError + fallback instead of re-throwing.
+ onError: handleError,
+ });
+ }
return (
<div
@@ -210,7 +226,9 @@ export function RichTextView({
className={className}
style={style}
{...rest}>
- <LexicalComposer initialConfig={initialConfig}>
+ <LexicalExtensionComposer
+ extension={extensionRef.current}
+ contentEditable={null}>
<SyncValuePlugin value={value} />
<RichTextPlugin
contentEditable={<ContentEditable />}
@@ -218,7 +236,7 @@ export function RichTextView({
ErrorBoundary={LexicalErrorBoundary}
/>
{plugins}
- </LexicalComposer>
+ </LexicalExtensionComposer>
</div>
);
}