An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): add imperative ref API to RichTextEditor (#4417)
Sherry68f565466087
diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex 93f602c18a..adcf383036 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -1,10 +1,15 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {useState} from 'react';+import {useRef, useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';-import {RichTextEditor, RichTextView} from '@astryxdesign/lab';+import {+ RichTextEditor,+ RichTextView,+ type RichTextEditorRef,+} from '@astryxdesign/lab';import type {EditorState} from 'lexical';import {BOLD_STAR, ITALIC_STAR, UNORDERED_LIST} from '@lexical/markdown';+import {$getRoot} from 'lexical';const meta: Meta<typeof RichTextEditor> = {title: 'Lab/RichTextEditor',@@ -139,3 +144,57 @@ export const ControlledPersistence = {);},};++export const ImperativeRef = {+ render: () => {+ const ref = useRef<RichTextEditorRef>(null);+ const [readout, setReadout] = useState<string>('(nothing read yet)');+ return (+ <div style={{display: 'grid', gap: 16, maxWidth: 560}}>+ <RichTextEditor+ ref={ref}+ label="Editor with imperative ref"+ defaultValue={SEED}+ placeholder="Type here, then use the buttons below…"+ />+ <div style={{display: 'flex', gap: 8, flexWrap: 'wrap'}}>+ <button type="button" onClick={() => ref.current?.focus()}>+ focus()+ </button>+ <button type="button" onClick={() => ref.current?.clear()}>+ clear()+ </button>+ <button+ type="button"+ onClick={() => {+ const state = ref.current?.getEditorState();+ const text = state?.read(() => $getRoot().getTextContent());+ setReadout(`getEditorState() text content: ${JSON.stringify(text)}`);+ }}>+ getEditorState()+ </button>+ <button+ type="button"+ onClick={() => {+ const editor = ref.current?.getEditor();+ setReadout(+ `getEditor() -> ${editor ? 'LexicalEditor instance ✓' : 'null'}`,+ );+ }}>+ getEditor()+ </button>+ </div>+ <pre+ style={{+ background: '#f5f5f5',+ padding: 12,+ borderRadius: 6,+ fontSize: 13,+ whiteSpace: 'pre-wrap',+ }}>+ {readout}+ </pre>+ </div>+ );+ },+};diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjsindex 18685c2d22..471169626f 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs+++ b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs@@ -144,6 +144,11 @@ export const docs = {description:'Register custom node types via the nodes prop on BOTH the editor and the RichTextView so serialized content round-trips.',},+ {+ guidance: true,+ description:+ 'Use a ref (RichTextEditorRef) to imperatively focus(), clear(), read the state via getEditorState(), or reach the LexicalEditor via getEditor(). The handle is available after mount. focus() and clear() are no-ops when the editor is read-only or disabled, and clear() resets to a single empty paragraph.',+ },{guidance: false,description:diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsxindex 9e4b0b9ccb..dbc6c7ce18 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx@@ -11,16 +11,16 @@import {describe, it, expect, vi} from 'vitest';import {render, screen, waitFor} from '@testing-library/react';-import {useEffect} from 'react';+import {createRef, useEffect} from 'react';import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';-import type {LexicalEditor} from 'lexical';+import type {EditorState, LexicalEditor} from 'lexical';import {$getRoot, $createParagraphNode, $createTextNode} from 'lexical';import {HeadingNode} from '@lexical/rich-text';import {TRANSFORMERS,$convertFromMarkdownString,} from '@lexical/markdown';-import {RichTextEditor} from './RichTextEditor';+import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';import {RichTextView} from './RichTextView';// Small plugin that captures the editor instance so tests can drive real@@ -333,6 +333,128 @@ describe('RichTextEditor', () => {});});});++ it('exposes an imperative ref handle after mount', () => {+ const ref = createRef<RichTextEditorRef>();+ render(<RichTextEditor ref={ref} label="Notes" />);+ expect(ref.current).not.toBeNull();+ expect(typeof ref.current?.focus).toBe('function');+ expect(typeof ref.current?.clear).toBe('function');+ expect(typeof ref.current?.getEditorState).toBe('function');+ expect(typeof ref.current?.getEditor).toBe('function');+ });++ it('ref.focus() runs without throwing and targets the editable surface', () => {+ const ref = createRef<RichTextEditorRef>();+ render(<RichTextEditor ref={ref} label="Notes" />);+ // Lexical dispatches focus via its editor command; jsdom does not always+ // reflect programmatic contenteditable focus onto document.activeElement,+ // so assert the call is wired and the root element is reachable rather+ // than asserting jsdom focus state.+ expect(() => ref.current?.focus()).not.toThrow();+ const root = ref.current?.getEditor().getRootElement();+ expect(root).toBe(screen.getByRole('textbox'));+ });++ it('ref.getEditorState() returns the current EditorState', () => {+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor ref={ref} label="Notes" defaultValue={HELLO_STATE} />,+ );+ const state = ref.current?.getEditorState();+ expect(state).toBeDefined();+ const text = state?.read(() => $getRoot().getTextContent());+ expect(text).toBe('Hello world');+ });++ it('ref.getEditor() returns the underlying LexicalEditor', () => {+ const ref = createRef<RichTextEditorRef>();+ render(<RichTextEditor ref={ref} label="Notes" />);+ const editor = ref.current?.getEditor();+ expect(editor).toBeDefined();+ expect(typeof editor?.update).toBe('function');+ });++ it('ref.clear() resets the editor to a single empty paragraph', async () => {+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor ref={ref} label="Notes" defaultValue={HELLO_STATE} />,+ );+ ref.current?.clear();+ await waitFor(() => {+ const state: EditorState | undefined = ref.current?.getEditorState();+ const text = state?.read(() => $getRoot().getTextContent());+ expect(text).toBe('');+ });+ // The root should hold exactly one (empty) paragraph, not zero children —+ // a bare root breaks selection/typing.+ const state = ref.current?.getEditorState();+ const childCount = state?.read(() => $getRoot().getChildrenSize());+ expect(childCount).toBe(1);+ });++ it('ref.clear() fires onChange', async () => {+ const ref = createRef<RichTextEditorRef>();+ const onChange = vi.fn();+ render(+ <RichTextEditor+ ref={ref}+ label="Notes"+ defaultValue={HELLO_STATE}+ onChange={onChange}+ />,+ );+ // Wait for the editor to mount and the initial state to settle so any+ // seed-time onChange has already fired before we assert on clear().+ await waitFor(() => expect(ref.current).not.toBeNull());+ onChange.mockClear();+ ref.current?.clear();+ await waitFor(() => expect(onChange).toHaveBeenCalled());+ });++ it('ref.clear() and ref.focus() are no-ops when isReadOnly', async () => {+ const ref = createRef<RichTextEditorRef>();+ const onChange = vi.fn();+ render(+ <RichTextEditor+ ref={ref}+ label="Notes"+ defaultValue={HELLO_STATE}+ onChange={onChange}+ isReadOnly+ />,+ );+ onChange.mockClear();+ ref.current?.focus();+ ref.current?.clear();+ // Give any (unexpected) async update a chance to flush before asserting.+ await new Promise(resolve => setTimeout(resolve, 0));+ expect(onChange).not.toHaveBeenCalled();+ const state = ref.current?.getEditorState();+ const text = state?.read(() => $getRoot().getTextContent());+ expect(text).toBe('Hello world');+ });++ it('ref.clear() is a no-op when isDisabled', async () => {+ const ref = createRef<RichTextEditorRef>();+ const onChange = vi.fn();+ render(+ <RichTextEditor+ ref={ref}+ label="Notes"+ defaultValue={HELLO_STATE}+ onChange={onChange}+ isDisabled+ />,+ );+ onChange.mockClear();+ ref.current?.clear();+ await new Promise(resolve => setTimeout(resolve, 0));+ expect(onChange).not.toHaveBeenCalled();+ const state = ref.current?.getEditorState();+ const text = state?.read(() => $getRoot().getTextContent());+ expect(text).toBe('Hello world');+ });});describe('RichTextView', () => {diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.tsxindex 161e183dae..50d3e434a6 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.tsx@@ -24,7 +24,16 @@* dependencies — install them to use this component.*/-import {useEffect, useId, useMemo, useRef, type ReactNode} from 'react';+import {+ useEffect,+ useId,+ useImperativeHandle,+ useMemo,+ useRef,+ forwardRef,+ type ReactNode,+ type Ref,+} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars,@@ -73,6 +82,40 @@ import type {EditorThemeClasses,} from 'lexical';+/**+ * Serialized state for an empty editor: a root containing a single empty+ * paragraph. Used by the imperative `clear()` handle.+ *+ * We deliberately reset the editor via `editor.setEditorState(...)` rather than+ * an `editor.update(() => { $getRoot()... })` callback, because `$getRoot` /+ * `$createParagraphNode` are *runtime value* imports from the top-level+ * `lexical` package. In the sandbox's Next build a top-level `lexical` value+ * import forces Babel to transpile lexical's raw `src/*.ts` (which uses+ * `declare` class fields) and fails the build. `parseEditorState` /+ * `setEditorState` are methods on the editor instance, so no top-level+ * `lexical` value import is needed. Setting a fresh state still notifies update+ * listeners, so `onChange` fires.+ */+const EMPTY_EDITOR_STATE_JSON = JSON.stringify({+ root: {+ children: [+ {+ children: [],+ direction: null,+ format: '',+ indent: 0,+ type: 'paragraph',+ version: 1,+ },+ ],+ direction: null,+ format: '',+ indent: 0,+ type: 'root',+ version: 1,+ },+});+const styles = stylex.create({wrapper: {flexDirection: 'column',@@ -147,6 +190,30 @@ export interface RichTextEditorStatus {message?: string;}+/**+ * Imperative handle exposed via `ref`. Lets callers focus, clear, and read the+ * editor without wiring a custom plugin. Available after mount.+ */+export interface RichTextEditorRef {+ /**+ * Move focus into the editor's editable surface. No-op when the editor is+ * read-only or disabled.+ */+ focus: () => void;+ /**+ * Remove all content, resetting the editor to a single empty paragraph.+ * No-op when the editor is read-only or disabled.+ */+ clear: () => void;+ /** Read the current `EditorState`. Serialize with `.toJSON()` to persist. */+ getEditorState: () => EditorState;+ /**+ * Access the underlying `LexicalEditor` instance for advanced use cases+ * (custom commands, listeners, node transforms).+ */+ getEditor: () => LexicalEditor;+}+export interface RichTextEditorProps extends Omit<BaseProps,'onChange' | 'defaultValue'@@ -269,40 +336,50 @@ export interface RichTextEditorProps extends Omit<** @example* ```- * import {RichTextEditor} from '@astryxdesign/lab';+ * import {RichTextEditor, type RichTextEditorRef} from '@astryxdesign/lab';+ *+ * const ref = useRef<RichTextEditorRef>(null);* <RichTextEditor+ * ref={ref}* label="Notes"* placeholder="Write something..."* onChange={state => save(JSON.stringify(state.toJSON()))}* />+ * // Later: ref.current?.focus(); ref.current?.clear();* ```*/-export function RichTextEditor({- label,- isLabelHidden = false,- description,- isOptional = false,- isRequired = false,- defaultValue,- onChange,- placeholder,- isReadOnly = false,- isDisabled = false,- status,- width,- labelTooltip,- size: sizeProp,- nodes,- plugins,- hasMarkdownShortcuts = true,- transformers = TRANSFORMERS,- hasAutoFocus = false,- namespace = 'astryx-editor',- xstyle,- className,- style,- ...rest-}: RichTextEditorProps) {+export const RichTextEditor = forwardRef<+ RichTextEditorRef,+ RichTextEditorProps+>(function RichTextEditor(+ {+ label,+ isLabelHidden = false,+ description,+ isOptional = false,+ isRequired = false,+ defaultValue,+ onChange,+ placeholder,+ isReadOnly = false,+ isDisabled = false,+ status,+ width,+ labelTooltip,+ size: sizeProp,+ nodes,+ plugins,+ hasMarkdownShortcuts = true,+ transformers = TRANSFORMERS,+ hasAutoFocus = false,+ namespace = 'astryx-editor',+ xstyle,+ className,+ style,+ ...rest+ }: RichTextEditorProps,+ ref: Ref<RichTextEditorRef>,+) {const size = useSize(sizeProp, 'md');const id = useId();const descriptionID = useId();@@ -417,12 +494,13 @@ export function RichTextEditor({/>)}{plugins}+ <EditorRefBridge editorRef={ref} editable={editable} /></div></LexicalComposer></div></Field>);-}+});RichTextEditor.displayName = 'RichTextEditor';@@ -438,6 +516,50 @@ function AutoFocusOnMount(): null {return null;}+/**+ * Wires the imperative `RichTextEditorRef` handle. Split into its own plugin so+ * it runs inside the composer context and can reach the `LexicalEditor` via+ * `useLexicalComposerContext()`. Renders nothing.+ *+ * `focus()` and `clear()` are gated on `editable` so a read-only or disabled+ * editor cannot be mutated or focused through the imperative handle — matching+ * the behaviour of the editable surface itself.+ */+function EditorRefBridge({+ editorRef,+ editable,+}: {+ editorRef: Ref<RichTextEditorRef>;+ editable: boolean;+}): null {+ const [editor] = useLexicalComposerContext();+ useImperativeHandle(+ editorRef,+ () => ({+ focus: () => {+ if (!editable) {+ return;+ }+ editor.focus();+ },+ clear: () => {+ if (!editable) {+ return;+ }+ // Reset to a single empty paragraph via a fresh EditorState. Uses the+ // editor instance's own parse/set methods so we avoid a top-level+ // `lexical` value import (see EMPTY_EDITOR_STATE_JSON). This still+ // notifies update listeners, so `onChange` fires.+ editor.setEditorState(editor.parseEditorState(EMPTY_EDITOR_STATE_JSON));+ },+ getEditorState: () => editor.getEditorState(),+ getEditor: () => editor,+ }),+ [editor, editable],+ );+ return null;+}+/*** Renders the Lexical ContentEditable. Split out so the placeholder* discriminated union (`placeholder` + `aria-placeholder` present together, ordiff --git a/packages/lab/src/RichTextEditor/index.ts b/packages/lab/src/RichTextEditor/index.tsindex 0aa037a268..d4f5add723 100644--- a/packages/lab/src/RichTextEditor/index.ts+++ b/packages/lab/src/RichTextEditor/index.ts@@ -15,6 +15,7 @@export {RichTextEditor} from './RichTextEditor';export type {RichTextEditorProps,+ RichTextEditorRef,RichTextEditorStatus,RichTextEditorStatusType,RichTextEditorSize,diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 87ed39a3da..f358e1a5bf 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -235,6 +235,7 @@ export {export {RichTextEditor,type RichTextEditorProps,+ type RichTextEditorRef,type RichTextEditorStatus,type RichTextEditorStatusType,type RichTextEditorSize,