An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): add getMarkdown() to RichTextEditor imperative ref (#4509)
Sherrye1c2beaa4829
diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex cb6008296e..27bbacb378 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -183,6 +183,14 @@ export const ImperativeRef = {}}>getEditorState()</button>+ <button+ type="button"+ onClick={() => {+ const md = ref.current?.getMarkdown();+ setReadout(`getMarkdown():\n${md}`);+ }}>+ getMarkdown()+ </button><buttontype="button"onClick={() => {diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjsindex 798a2aa1c2..8abaa445b4 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs+++ b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs@@ -153,7 +153,7 @@ export const docs = {{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.',+ 'Use a ref (RichTextEditorRef) to imperatively focus(), clear(), read the state via getEditorState(), serialize to Markdown via getMarkdown(), or reach the LexicalEditor via getEditor(). The handle is available after mount. getMarkdown() uses the same transformers prop the editor is configured with. focus() and clear() are no-ops when the editor is read-only or disabled, and clear() resets to a single empty paragraph.',},{guidance: false,diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsxindex b62095b22c..b326ed5959 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx@@ -341,6 +341,7 @@ describe('RichTextEditor', () => {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?.getMarkdown).toBe('function');expect(typeof ref.current?.getEditor).toBe('function');});@@ -375,6 +376,56 @@ describe('RichTextEditor', () => {expect(typeof editor?.update).toBe('function');});+ it('ref.getMarkdown() serializes plain text content', () => {+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor ref={ref} label="Notes" defaultValue={HELLO_STATE} />,+ );+ expect(ref.current?.getMarkdown()).toBe('Hello world');+ });++ it('ref.getMarkdown() serializes a heading with the default transformers', async () => {+ const ref = createRef<RichTextEditorRef>();+ let editorRef: LexicalEditor | undefined;+ render(+ <RichTextEditor+ ref={ref}+ label="Notes"+ plugins={<CaptureEditor onReady={e => (editorRef = e)} />}+ />,+ );+ await waitFor(() => expect(editorRef).toBeDefined());+ editorRef!.update(() => {+ $convertFromMarkdownString('# Title', TRANSFORMERS);+ });+ await waitFor(() =>+ expect(ref.current?.getMarkdown()).toBe('# Title'),+ );+ });++ it('ref.getMarkdown() honors a custom transformers prop', async () => {+ // With an empty transformers set, a heading node cannot be represented in+ // markdown, so its text is emitted as a plain paragraph (no "# "). This+ // proves getMarkdown() uses the same transformers the editor is+ // configured with, not a hardcoded default.+ const ref = createRef<RichTextEditorRef>();+ let editorRef: LexicalEditor | undefined;+ render(+ <RichTextEditor+ ref={ref}+ label="Notes"+ transformers={[]}+ plugins={<CaptureEditor onReady={e => (editorRef = e)} />}+ />,+ );+ await waitFor(() => expect(editorRef).toBeDefined());+ // Seed a heading node directly (bypassing shortcuts) using the full set.+ editorRef!.update(() => {+ $convertFromMarkdownString('# Title', TRANSFORMERS);+ });+ await waitFor(() => expect(ref.current?.getMarkdown()).toBe('Title'));+ });+it('ref.clear() resets the editor to a single empty paragraph', async () => {const ref = createRef<RichTextEditorRef>();render(diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.tsxindex 8644830441..4745442947 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.tsx@@ -70,7 +70,11 @@ import {LinkPlugin} from '@lexical/react/LexicalLinkPlugin';import {TabIndentationPlugin} from '@lexical/react/LexicalTabIndentationPlugin';import {MarkdownShortcutPlugin} from '@lexical/react/LexicalMarkdownShortcutPlugin';import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';-import {TRANSFORMERS, type Transformer} from '@lexical/markdown';+import {+ TRANSFORMERS,+ $convertToMarkdownString,+ type Transformer,+} from '@lexical/markdown';export type {Transformer} from '@lexical/markdown';import {ListNode, ListItemNode} from '@lexical/list';import {HeadingNode, QuoteNode} from '@lexical/rich-text';@@ -226,6 +230,13 @@ export interface RichTextEditorRef {clear: () => void;/** Read the current `EditorState`. Serialize with `.toJSON()` to persist. */getEditorState: () => EditorState;+ /**+ * Serialize the current content to a Markdown string, using the same+ * `transformers` the editor is configured with (so custom transformers+ * layered in via the `transformers` prop are honored). Equivalent to+ * `$convertToMarkdownString` run in a read context.+ */+ getMarkdown: () => string;/*** Access the underlying `LexicalEditor` instance for advanced use cases* (custom commands, listeners, node transforms).@@ -528,7 +539,11 @@ export const RichTextEditor = forwardRef</>)}{plugins}- <EditorRefBridge editorRef={ref} editable={editable} />+ <EditorRefBridge+ editorRef={ref}+ editable={editable}+ transformers={markdownTransformers}+ />{maxLength != null && (<CharCountPlugin onCountChange={setCharCount} />)}@@ -582,9 +597,11 @@ function AutoFocusOnMount(): null {function EditorRefBridge({editorRef,editable,+ transformers,}: {editorRef: Ref<RichTextEditorRef>;editable: boolean;+ transformers: Array<Transformer>;}): null {const [editor] = useLexicalComposerContext();useImperativeHandle(@@ -607,9 +624,17 @@ function EditorRefBridge({editor.setEditorState(editor.parseEditorState(EMPTY_EDITOR_STATE_JSON));},getEditorState: () => editor.getEditorState(),+ getMarkdown: () =>+ // $convertToMarkdownString must run inside a read context. Honors the+ // same transformers the editor uses for shortcuts, so custom+ // transformers round-trip to Markdown. `@lexical/markdown` is a+ // subpackage (built dist) — safe, unlike a top-level `lexical` import.+ editor+ .getEditorState()+ .read(() => $convertToMarkdownString(transformers)),getEditor: () => editor,}),- [editor, editable],+ [editor, editable, transformers],);return null;}