An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): expose transformers prop on RichTextEditor (#4416)
Sherryfaa200af3352
diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex 0399877118..93f602c18a 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -4,6 +4,7 @@ import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {RichTextEditor, RichTextView} from '@astryxdesign/lab';import type {EditorState} from 'lexical';+import {BOLD_STAR, ITALIC_STAR, UNORDERED_LIST} from '@lexical/markdown';const meta: Meta<typeof RichTextEditor> = {title: 'Lab/RichTextEditor',@@ -50,6 +51,16 @@ export const Required: Story = {},};+export const CustomTransformers: Story = {+ args: {+ label: 'Comment',+ description:+ 'Restricted markdown: only `*bold*`, `_italic_` and `- ` unordered lists (no headings, quotes or code).',+ placeholder: 'Try typing "# " — it will not become a heading…',+ transformers: [BOLD_STAR, ITALIC_STAR, UNORDERED_LIST],+ },+};+export const ErrorStatus: Story = {args: {label: 'Notes',diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjsindex 46612f71bf..f129e3696f 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs+++ b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs@@ -93,9 +93,16 @@ export const docs = {name: 'hasMarkdownShortcuts',type: 'boolean',description:- 'Enable Markdown shortcut typing (e.g. "# " for a heading). Uses default @lexical/markdown transformers.',+ 'Enable Markdown shortcut typing (e.g. "# " for a heading). Uses the transformers prop (defaults to the standard @lexical/markdown transformers).',default: 'true',},+ {+ name: 'transformers',+ type: 'ReadonlyArray<Transformer>',+ description:+ 'Markdown transformers — the single source of truth for markdown behaviour. Defaults to the standard @lexical/markdown TRANSFORMERS. In Lexical the same array drives all three markdown operations (shortcut typing, markdown->state import, state->markdown export); this prop wires shortcut typing today and is the intended input for the serialization APIs added in later phases. Pass a custom array to support additional node types (e.g. transformers layered in via the nodes extension point) consistently across all three. Shortcut typing is only applied when hasMarkdownShortcuts is true.',+ default: 'TRANSFORMERS',+ },{name: 'hasAutoFocus',type: 'boolean',diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsxindex f41569ea9c..9e4b0b9ccb 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx@@ -16,9 +16,27 @@ import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';import type {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 {RichTextView} from './RichTextView';+// Small plugin that captures the editor instance so tests can drive real+// Lexical updates (jsdom does not implement contenteditable editing).+function CaptureEditor({+ onReady,+}: {+ onReady: (editor: LexicalEditor) => void;+}) {+ const [editor] = useLexicalComposerContext();+ useEffect(() => {+ onReady(editor);+ }, [editor, onReady]);+ return null;+}+// A minimal valid serialized Lexical editor state containing a single// paragraph with the text "Hello world".// Builds a serialized Lexical state containing a list. `listType` is@@ -215,19 +233,12 @@ describe('RichTextEditor', () => {// instance via a small capture plugin and drive a real Lexical update,// then assert onChange fires.let editorRef: LexicalEditor | undefined;- function CaptureEditor() {- const [editor] = useLexicalComposerContext();- useEffect(() => {- editorRef = editor;- }, [editor]);- return null;- }const onChange = vi.fn();render(<RichTextEditorlabel="Notes"onChange={onChange}- plugins={<CaptureEditor />}+ plugins={<CaptureEditor onReady={e => (editorRef = e)} />}/>,);await waitFor(() => expect(editorRef).toBeDefined());@@ -258,6 +269,70 @@ describe('RichTextEditor', () => {);expect(screen.getByTestId('custom-plugin')).toBeInTheDocument();});++ it('accepts a custom transformers array without throwing', () => {+ // Empty transformer set is a valid custom configuration (disables all+ // markdown shortcuts while keeping the plugin mounted).+ render(<RichTextEditor label="Notes" transformers={[]} />);+ expect(screen.getByRole('textbox')).toBeInTheDocument();+ });++ it('renders when markdown shortcuts are disabled', () => {+ render(<RichTextEditor label="Notes" hasMarkdownShortcuts={false} />);+ expect(screen.getByRole('textbox')).toBeInTheDocument();+ });++ it('applies the default transformers to convert markdown to a heading', async () => {+ // jsdom can't dispatch the keystrokes that trigger registerMarkdownShortcuts+ // live, so we drive $convertFromMarkdownString with the same TRANSFORMERS+ // the component registers by default. This proves the default transformer+ // set actually produces the expected node structure (a heading), rather+ // than only asserting the editor mounts.+ let editorRef: LexicalEditor | undefined;+ render(+ <RichTextEditor+ label="Notes"+ plugins={<CaptureEditor onReady={e => (editorRef = e)} />}+ />,+ );+ await waitFor(() => expect(editorRef).toBeDefined());+ editorRef!.update(() => {+ $convertFromMarkdownString('# Title', TRANSFORMERS);+ });+ await waitFor(() => {+ editorRef!.getEditorState().read(() => {+ const first = $getRoot().getFirstChild();+ expect(first?.getType()).toBe('heading');+ expect(first?.getTextContent()).toBe('Title');+ });+ });+ });++ it('leaves markdown untransformed when given an empty transformers array', async () => {+ // With no transformers, the same markdown text stays a plain paragraph —+ // demonstrating the transformers prop is the effective source of truth for+ // markdown behaviour, not a fixed internal default.+ let editorRef: LexicalEditor | undefined;+ render(+ <RichTextEditor+ label="Notes"+ transformers={[]}+ plugins={<CaptureEditor onReady={e => (editorRef = e)} />}+ />,+ );+ await waitFor(() => expect(editorRef).toBeDefined());+ editorRef!.update(() => {+ // Empty transformer set: markdown syntax is preserved verbatim.+ $convertFromMarkdownString('# Title', []);+ });+ await waitFor(() => {+ editorRef!.getEditorState().read(() => {+ const first = $getRoot().getFirstChild();+ expect(first?.getType()).toBe('paragraph');+ expect(first?.getTextContent()).toBe('# Title');+ });+ });+ });});describe('RichTextView', () => {diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.tsxindex 30d4e7d8b4..161e183dae 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.tsx@@ -24,7 +24,7 @@* dependencies — install them to use this component.*/-import {useEffect, useId, useRef, type ReactNode} from 'react';+import {useEffect, useId, useMemo, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars,@@ -59,7 +59,8 @@ 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} from '@lexical/markdown';+import {TRANSFORMERS, type Transformer} from '@lexical/markdown';+export type {Transformer} from '@lexical/markdown';import {ListNode, ListItemNode} from '@lexical/list';import {HeadingNode, QuoteNode} from '@lexical/rich-text';import {LinkNode, AutoLinkNode} from '@lexical/link';@@ -224,10 +225,29 @@ export interface RichTextEditorProps extends Omit<plugins?: ReactNode;/*** Whether to enable Markdown shortcut typing (e.g. `# ` for a heading,- * `- ` for a list). Uses the default `@lexical/markdown` transformers.+ * `- ` for a list). Uses the `transformers` prop (defaults to the standard+ * `@lexical/markdown` transformers).* @default true*/hasMarkdownShortcuts?: boolean;+ /**+ * Markdown transformers — the single source of truth for markdown behaviour.+ * Defaults to the standard `@lexical/markdown` `TRANSFORMERS`.+ *+ * The same array drives all three markdown operations in Lexical (see the+ * lexical-playground reference, where one `PLAYGROUND_TRANSFORMERS` array+ * feeds each):+ * - shortcut typing — `registerMarkdownShortcuts` (wired here today)+ * - markdown -> state — `$convertFromMarkdownString` (future import API)+ * - state -> markdown — `$convertToMarkdownString` (future `getMarkdown`)+ *+ * Pass a custom array to support additional node types (e.g. custom+ * transformers layered in via the `nodes` extension point) consistently+ * across all three. Shortcut typing is only applied when+ * `hasMarkdownShortcuts` is true; the array is still the intended input for+ * the serialization APIs added in later phases.+ */+ transformers?: ReadonlyArray<Transformer>;/** Whether to automatically focus the editor on mount. @default false */hasAutoFocus?: boolean;/**@@ -275,6 +295,7 @@ export function RichTextEditor({nodes,plugins,hasMarkdownShortcuts = true,+ transformers = TRANSFORMERS,hasAutoFocus = false,namespace = 'astryx-editor',xstyle,@@ -296,6 +317,12 @@ export function RichTextEditor({const editable = !isReadOnly && !isDisabled;+ // Stabilize the transformers array so MarkdownShortcutPlugin doesn't+ // re-register on every render. `[...transformers]` would allocate a new+ // array each time; memoize on the prop identity instead. (React Compiler+ // 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,@@ -379,7 +406,7 @@ export function RichTextEditor({<LinkPlugin /><TabIndentationPlugin />{hasMarkdownShortcuts && (- <MarkdownShortcutPlugin transformers={TRANSFORMERS} />+ <MarkdownShortcutPlugin transformers={markdownTransformers} />)}{hasAutoFocus && <AutoFocusOnMount />}{onChange && (diff --git a/packages/lab/src/RichTextEditor/index.ts b/packages/lab/src/RichTextEditor/index.tsindex 25dd31e272..0aa037a268 100644--- a/packages/lab/src/RichTextEditor/index.ts+++ b/packages/lab/src/RichTextEditor/index.ts@@ -18,6 +18,7 @@ export type {RichTextEditorStatus,RichTextEditorStatusType,RichTextEditorSize,+ Transformer,} from './RichTextEditor';export {RichTextView} from './RichTextView';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 3241e40181..87ed39a3da 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -238,6 +238,7 @@ export {type RichTextEditorStatus,type RichTextEditorStatusType,type RichTextEditorSize,+ type Transformer,RichTextView,type RichTextViewProps,sharedEditorTheme,