An open source design system that's fully customizable and agent ready
TypeScript
fix(lab): make RichTextView react to value prop changes (#4671)
Sherry0d69c3a2e571
diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsxindex bbaa948cd4..e1bce516b3 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx@@ -49,6 +49,40 @@ function CaptureEditor({onReady}: {onReady: (editor: LexicalEditor) => void}) {// A minimal valid serialized Lexical editor state containing a single// paragraph with the text "Hello world".+// Builds a serialized Lexical state containing a single paragraph with the+// given text. Used to verify that RichTextView reacts to `value` changes.+function makeParagraphState(text: string): string {+ return JSON.stringify({+ root: {+ children: [+ {+ children: [+ {+ detail: 0,+ format: 0,+ mode: 'normal',+ style: '',+ text,+ type: 'text',+ version: 1,+ },+ ],+ direction: 'ltr',+ format: '',+ indent: 0,+ type: 'paragraph',+ version: 1,+ },+ ],+ direction: 'ltr',+ format: '',+ indent: 0,+ type: 'root',+ version: 1,+ },+ });+}+// Builds a serialized Lexical state containing a list. `listType` is// 'bullet' (renders <ul>) or 'number' (renders <ol>). Used to verify that the// editor theme applies visible list markers rather than bare indentation.@@ -678,6 +712,44 @@ describe('RichTextView', () => {expect(() => render(<RichTextView value={'garbage'} />)).not.toThrow();expect(screen.queryByRole('textbox')).not.toBeInTheDocument();});++ it('updates the rendered content when the value prop changes', async () => {+ // LexicalComposer's initialConfig.editorState is only read on mount, so+ // without the internal sync plugin the view would freeze at the first+ // value. This guards that a changed `value` re-renders the content — the+ // exact bug in the "Markdown Serializers" story (RichTextView stayed stale+ // while the Markdown input changed).+ const {rerender} = render(+ <RichTextView value={makeParagraphState('first version')} />,+ );+ await waitFor(() =>+ expect(screen.getByText('first version')).toBeInTheDocument(),+ );++ rerender(<RichTextView value={makeParagraphState('second version')} />);+ await waitFor(() =>+ expect(screen.getByText('second version')).toBeInTheDocument(),+ );+ expect(screen.queryByText('first version')).not.toBeInTheDocument();+ });++ it('recovers from a malformed value once a valid value is supplied again', async () => {+ // A bad value renders the fallback; a subsequent valid value must re-mount+ // the composer and render the new content (hasError resets on change).+ const {rerender} = render(+ <RichTextView+ value={'{ not valid json'}+ errorFallback={<div data-testid="view-fallback">Unavailable</div>}+ />,+ );+ expect(screen.getByTestId('view-fallback')).toBeInTheDocument();++ rerender(<RichTextView value={makeParagraphState('recovered')} />);+ await waitFor(() =>+ expect(screen.getByText('recovered')).toBeInTheDocument(),+ );+ expect(screen.queryByTestId('view-fallback')).not.toBeInTheDocument();+ });});describe('markdown serializers', () => {diff --git a/packages/lab/src/RichTextEditor/RichTextView.tsx b/packages/lab/src/RichTextEditor/RichTextView.tsxindex 8444f2b656..937c891570 100644--- a/packages/lab/src/RichTextEditor/RichTextView.tsx+++ b/packages/lab/src/RichTextEditor/RichTextView.tsx@@ -16,7 +16,7 @@* - /apps/storybook/stories/RichTextEditor.stories.tsx*/-import {useRef, useState, type ReactNode} from 'react';+import {useEffect, useRef, useState, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {sharedEditorTheme} from './editorTheme';import type {BaseProps} from '@astryxdesign/core';@@ -25,6 +25,7 @@ import {LexicalComposer,type InitialConfigType,} from '@lexical/react/LexicalComposer';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';import {RichTextPlugin} from '@lexical/react/LexicalRichTextPlugin';import {ContentEditable} from '@lexical/react/LexicalContentEditable';import {LexicalErrorBoundary} from '@lexical/react/LexicalErrorBoundary';@@ -86,6 +87,47 @@ export interface RichTextViewProps extends BaseProps {errorFallback?: ReactNode;}+/**+ * 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+ * 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.+ *+ * 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.+ *+ * `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).+ */+function SyncValuePlugin({value}: {value: string}): null {+ const [editor] = useLexicalComposerContext();+ const isFirstRun = useRef(true);+ useEffect(() => {+ if (isFirstRun.current) {+ isFirstRun.current = false;+ return;+ }+ editor.setEditorState(editor.parseEditorState(value));+ }, [editor, value]);+ return null;+}+/*** A read-only renderer for serialized Lexical content. Renders the same styled* output as {@link RichTextEditor} without any editing affordances.@@ -170,6 +212,7 @@ export function RichTextView({style={style}{...rest}><LexicalComposer initialConfig={initialConfig}>+ <SyncValuePlugin value={value} /><RichTextPlugincontentEditable={<ContentEditable />}placeholder={null}