Skip to content

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

TypeScript

feat(lab): refresh rich text editor (#4818)

Ernestba1f13162f46
diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsx
index 1a46309526..33741db88c 100644
--- a/apps/storybook/stories/RichTextEditor.stories.tsx
+++ b/apps/storybook/stories/RichTextEditor.stories.tsx
@@ -31,7 +31,16 @@ const meta: Meta<typeof RichTextEditor> = {
hasMarkdownShortcuts: {control: 'boolean'},
hasAutoFocus: {control: 'boolean'},
maxLength: {control: 'number'},
+ minHeight: {
+ control: 'text',
+ description:
+ 'Minimum height of the editable surface (number in pixels or CSS length).',
+ },
size: {control: 'select', options: ['sm', 'md', 'lg']},
+ statusVariant: {
+ control: 'select',
+ options: ['attached', 'detached', 'tooltip'],
+ },
},
};
@@ -49,7 +58,69 @@ export const WithToolbar: Story = {
args: {
label: 'Notes',
placeholder: 'Format with the toolbar above…',
- plugins: <RichTextEditorToolbar />,
+ toolbar: <RichTextEditorToolbar />,
+ },
+};
+
+export const ResponsiveToolbar: Story = {
+ name: 'Responsive toolbar',
+ render: args => (
+ <div
+ style={{
+ width: 420,
+ minWidth: 280,
+ maxWidth: '100%',
+ resize: 'horizontal',
+ overflow: 'hidden',
+ }}>
+ <RichTextEditor {...args} />
+ </div>
+ ),
+ args: {
+ label: 'Notes',
+ description: 'Resize the editor to test the horizontal toolbar scroll.',
+ placeholder: 'Every formatting action stays directly available…',
+ toolbar: <RichTextEditorToolbar />,
+ },
+};
+
+export const ResponsiveToolbarStressTest: Story = {
+ name: 'Responsive toolbar — stress test',
+ render: args => {
+ const [width, setWidth] = useState(420);
+
+ return (
+ <div style={{display: 'grid', gap: 16}}>
+ <label
+ style={{
+ display: 'grid',
+ gap: 8,
+ maxWidth: 560,
+ font: 'inherit',
+ }}>
+ <span>Editor width: {width}px</span>
+ <input
+ type="range"
+ min={240}
+ max={900}
+ step={10}
+ value={width}
+ aria-label="Editor width"
+ onChange={event => setWidth(event.currentTarget.valueAsNumber)}
+ />
+ </label>
+ <div style={{width, maxWidth: '100%'}}>
+ <RichTextEditor {...args} />
+ </div>
+ </div>
+ );
+ },
+ args: {
+ label: 'Responsive toolbar stress test',
+ description:
+ 'Sweep from 240px to 900px to stress the horizontal toolbar scroll.',
+ placeholder: 'Scroll the toolbar and toggle several formats…',
+ toolbar: <RichTextEditorToolbar />,
},
};
@@ -60,7 +131,7 @@ export const WithLinks: Story = {
'Select text and press the Link button (or Cmd/Ctrl+K) to add a link…',
// The toolbar's Link button creates new-tab links by default (target/rel
// baked into the node). No extra plugin needed.
- plugins: <RichTextEditorToolbar />,
+ toolbar: <RichTextEditorToolbar />,
},
};
@@ -68,13 +139,9 @@ export const WithAutoLink: Story = {
args: {
label: 'Notes',
placeholder: 'Type a URL like https://astryx.dev and it auto-links…',
- plugins: (
- <>
- <RichTextEditorToolbar />
- {/* Auto-linkify typed/pasted URLs + emails (open in a new tab). */}
- <RichTextEditorAutoLinkPlugin />
- </>
- ),
+ toolbar: <RichTextEditorToolbar />,
+ // Auto-linkify typed/pasted URLs + emails (open in a new tab).
+ plugins: <RichTextEditorAutoLinkPlugin />,
},
};
@@ -119,6 +186,25 @@ export const ErrorStatus: Story = {
label: 'Notes',
placeholder: 'Write something…',
status: {type: 'error', message: 'This field is required.'},
+ statusVariant: 'attached',
+ },
+};
+
+export const DetachedStatus: Story = {
+ args: {
+ label: 'Notes',
+ placeholder: 'Write something…',
+ status: {type: 'warning', message: 'Review this content before saving.'},
+ statusVariant: 'detached',
+ },
+};
+
+export const TooltipStatus: Story = {
+ args: {
+ label: 'Notes',
+ placeholder: 'Write something…',
+ status: {type: 'error', message: 'This field is required.'},
+ statusVariant: 'tooltip',
},
};
diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs
index f2710b9516..81fe1f529b 100644
--- a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs
+++ b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs
@@ -51,7 +51,8 @@ export const docs = {
{
name: 'placeholder',
type: 'string',
- description: 'Placeholder text shown when the editor is empty.',
+ description:
+ 'Placeholder text shown when the editor is empty. Uses the same responsive body typography and text inset as the editable content.',
},
{
name: 'isReadOnly',
@@ -69,7 +70,14 @@ export const docs = {
name: 'status',
type: '{ type: "warning" | "error" | "success"; message?: string }',
description:
- 'Status indicator. Shows a colored border and an optional message below the editor.',
+ 'Validation status. Shows a colored border and status icon; an optional message follows the statusVariant placement. Error also sets aria-invalid.',
+ },
+ {
+ name: 'statusVariant',
+ type: "'attached' | 'detached' | 'tooltip'",
+ description:
+ 'How the status is presented: attached keeps the icon in the editor and overlaps the message below; detached floats the message below with its own icon; tooltip hides the message box and reveals it from the focusable in-editor status icon.',
+ default: "'attached'",
},
{
name: 'size',
@@ -83,11 +91,17 @@ export const docs = {
description:
'Additional Lexical nodes to register beyond the default OSS set (Heading, Quote, List, Link, Code). Extension point for custom nodes (mentions, images) without forking.',
},
+ {
+ name: 'toolbar',
+ type: 'ReactNode',
+ description:
+ 'Toolbar content rendered edge-to-edge at the top of the field, before the padded editing surface. Pass RichTextEditorToolbar here for correct visual and keyboard order.',
+ },
{
name: 'plugins',
type: 'ReactNode',
description:
- 'Additional Lexical plugins rendered inside the composer. Compose toolbars, mentions, autolink, etc. on top of the base editor.',
+ 'Additional Lexical plugins rendered inside the composer. Compose mentions, autolink, and other editor behavior on top of the base editor.',
},
{
name: 'hasMarkdownShortcuts',
@@ -128,6 +142,13 @@ export const docs = {
description:
'Width of the field. Numbers are pixels, strings used as-is (e.g. "100%").',
},
+ {
+ name: 'minHeight',
+ type: 'SizeValue',
+ description:
+ 'Minimum height of the editable content surface. Numbers are pixels; strings are used as CSS lengths. Content continues growing beyond this height.',
+ default: "'4.5rem'",
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -140,7 +161,7 @@ export const docs = {
},
usage: {
description:
- 'A WYSIWYG rich-text editor built on Lexical, styled with Astryx design tokens. Experimental component in @astryxdesign/lab (canary). lexical and @lexical/* are optional peer dependencies. The editor is deliberately minimal and extensible: pass nodes and plugins to layer richer behaviour (toolbars, mentions, hover cards) on top without forking. Use RichTextView to render serialized content read-only.',
+ 'A WYSIWYG rich-text editor built on Lexical, styled with Astryx design tokens. Its field container shares TextArea input visuals for the resting border, hover ring, focus-within ring, disabled state, and status colors. Experimental component in @astryxdesign/lab (canary). lexical and @lexical/* are optional peer dependencies. The editor is deliberately minimal and extensible: pass toolbar, nodes, and plugins to layer richer behaviour (formatting, mentions, hover cards) on top without forking. Use RichTextView to render serialized content read-only.',
bestPractices: [
{
guidance: true,
@@ -170,12 +191,12 @@ export const docs = {
{
guidance: true,
description:
- 'Add a formatting toolbar by rendering RichTextEditorToolbar in the plugins slot: plugins={<RichTextEditorToolbar />}. It is built from Astryx Toolbar/ToggleButton primitives (so it matches the theme), syncs active states to the selection, and covers bold/italic/underline/strikethrough/code, links, headings, quote, lists, and undo/redo. Compose extra controls via its endContent prop.',
+ 'Add a formatting toolbar with toolbar={<RichTextEditorToolbar />}. The dedicated slot places it edge-to-edge at the top of the field, before the padded editing surface, with correct keyboard order. It uses small Astryx Toolbar controls: undo/redo, a divided block-format Selector for paragraphs/headings/lists/quotes, then divided inline ToggleButtons for bold/italic/underline/strikethrough/code and links. The complete action row scrolls horizontally when space is tight, keeping every control directly available without a More menu. The Selector keeps its default adaptive placement. Compose extra controls via endContent.',
},
{
guidance: true,
description:
- 'Links: the toolbar Link button (on by default; disable with hasLink={false}) and Cmd/Ctrl+K toggle a link on the selection via Lexical TOGGLE_LINK_COMMAND. It prompts for a URL with window.prompt by default; pass promptForUrl to plug in a custom prompt (e.g. an Astryx Dialog or floating popover). Entered URLs are sanitized (only http/https/mailto/tel are written; javascript:/data: are rejected). Links open in a new tab by default: target=_blank and rel=noopener noreferrer are written into the link node data (so they serialize and round-trip), not patched onto the DOM; set linkOpensInNewTab={false} for same-tab links. Pressing the button while a link is selected removes it.',
+ 'Links: the toolbar Link button (on by default; disable with hasLink={false}) and Cmd/Ctrl+K open an Astryx Dialog. The form preserves the Lexical selection while focus moves into the URL input and supports add, update, remove, Escape, and focus return. Pass promptForUrl only when integrating an existing synchronous URL flow. Entered URLs are sanitized (only http/https/mailto/tel are written; javascript:/data: are rejected). Links open in a new tab by default: target=_blank and rel=noopener noreferrer are written into the link node data; set linkOpensInNewTab={false} for same-tab links.',
},
{
guidance: true,
diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx
index c8778c8a5b..1a37978bc0 100644
--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx
+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx
@@ -3,13 +3,16 @@
/**
* @file RichTextEditor.test.tsx
* @input Uses vitest, @testing-library/react, RichTextEditor + RichTextView
- * @output Unit tests for the opt-in Lexical editor components
+ * @output Unit tests for the opt-in Lexical editor components, including
+ * accessible label wiring, shared input visuals/status variants,
+ * placeholder semantics, canonical link-dialog layout, and top-toolbar
+ * ordering and horizontal scrolling
* @position Testing; validates RichTextEditor.tsx and RichTextView.tsx
*
* SYNC: When the editor components change, update these tests to match.
*/
-import {describe, it, expect, vi, beforeAll} from 'vitest';
+import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
import {render, screen, waitFor, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {createRef, useEffect} from 'react';
@@ -43,6 +46,50 @@ import {
} from './RichTextEditorAutoLinkPlugin';
import {sanitizeUrl, validateUrl} from './linkUtils';
+// Closed popover-backed tooltips are intentionally hidden from the default
+// accessibility tree until their trigger opens them.
+const h = {hidden: true} as const;
+
+const originalShowModal = Object.getOwnPropertyDescriptor(
+ HTMLDialogElement.prototype,
+ 'showModal',
+);
+const originalDialogClose = Object.getOwnPropertyDescriptor(
+ HTMLDialogElement.prototype,
+ 'close',
+);
+
+beforeAll(() => {
+ // JSDOM does not implement the native dialog lifecycle used by Dialog.
+ HTMLDialogElement.prototype.showModal = function () {
+ this.setAttribute('open', '');
+ };
+ HTMLDialogElement.prototype.close = function () {
+ this.removeAttribute('open');
+ };
+});
+
+afterAll(() => {
+ if (originalShowModal) {
+ Object.defineProperty(
+ HTMLDialogElement.prototype,
+ 'showModal',
+ originalShowModal,
+ );
+ } else {
+ delete (HTMLDialogElement.prototype as {showModal?: unknown}).showModal;
+ }
+ if (originalDialogClose) {
+ Object.defineProperty(
+ HTMLDialogElement.prototype,
+ 'close',
+ originalDialogClose,
+ );
+ } else {
+ delete (HTMLDialogElement.prototype as {close?: unknown}).close;
+ }
+});
+
// 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}) {
@@ -223,17 +270,69 @@ const HELLO_STATE = JSON.stringify({
});
describe('RichTextEditor', () => {
+ it('keeps TextArea-style input visuals alongside consumer props', () => {
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ className="custom-editor"
+ style={{width: '42rem'}}
+ />,
+ );
+
+ const wrapper = container.querySelector('.astryx-rich-text-editor');
+ expect(wrapper).toBeInTheDocument();
+ expect(wrapper).toHaveClass('custom-editor');
+ expect(wrapper).toHaveAttribute('data-size', 'md');
+ expect(wrapper).toHaveStyle({width: '42rem'});
+ expect(
+ [...(wrapper?.classList ?? [])].some(className =>
+ className.startsWith('x'),
+ ),
+ ).toBe(true);
+ });
+
it('renders a labelled editable textbox', () => {
render(<RichTextEditor label="Notes" />);
- const textbox = screen.getByRole('textbox');
+ const textbox = screen.getByRole('textbox', {name: 'Notes'});
+ const label = screen.getByText('Notes');
+
expect(textbox).toBeInTheDocument();
expect(textbox).toHaveAttribute('contenteditable', 'true');
- expect(screen.getByText('Notes')).toBeInTheDocument();
+ expect(label).toHaveAttribute(
+ 'id',
+ textbox.getAttribute('aria-labelledby'),
+ );
+ expect(textbox).toHaveAttribute('id', label.getAttribute('for'));
+ });
+
+ it('applies minHeight only to the editable content surface', () => {
+ const {container, rerender} = render(<RichTextEditor label="Notes" />);
+ const wrapper = container.querySelector('.astryx-rich-text-editor');
+
+ expect(
+ screen.getByRole('textbox').style.getPropertyValue('--x-minHeight'),
+ ).toBe('4.5rem');
+ expect(wrapper).not.toHaveStyle({'--x-minHeight': '4.5rem'});
+
+ rerender(<RichTextEditor label="Notes" minHeight={180} />);
+ expect(
+ screen.getByRole('textbox').style.getPropertyValue('--x-minHeight'),
+ ).toBe('180px');
+
+ rerender(<RichTextEditor label="Notes" minHeight="12rem" />);
+ expect(
+ screen.getByRole('textbox').style.getPropertyValue('--x-minHeight'),
+ ).toBe('12rem');
});
it('shows the placeholder when empty', () => {
render(<RichTextEditor label="Notes" placeholder="Write something…" />);
- expect(screen.getByText('Write something…')).toBeInTheDocument();
+ const textbox = screen.getByRole('textbox');
+ const visualPlaceholder = screen.getByText('Write something…');
+
+ expect(textbox).toHaveAttribute('aria-placeholder', 'Write something…');
+ expect(visualPlaceholder).toHaveAttribute('aria-hidden', 'true');
+ expect(textbox.parentElement).toContainElement(visualPlaceholder);
});
it('renders the initial value from defaultValue', async () => {
@@ -270,6 +369,71 @@ describe('RichTextEditor', () => {
expect(screen.getByText('Required')).toBeInTheDocument();
});
+ it.each(['error', 'warning', 'success'] as const)(
+ 'renders an in-editor %s icon for the default attached status',
+ type => {
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ status={{type, message: `${type} message`}}
+ />,
+ );
+
+ const statusIcon = container.querySelector('.astryx-input-status-icon');
+ expect(statusIcon).toBeInTheDocument();
+ expect(statusIcon).toHaveAttribute('data-status', type);
+ expect(statusIcon).toHaveAttribute('data-size', 'md');
+ expect(container.querySelector('.astryx-field-status')).toHaveAttribute(
+ 'data-variant',
+ 'attached',
+ );
+ },
+ );
+
+ it('uses the detached message icon and suppresses the in-editor icon', () => {
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ status={{type: 'warning', message: 'Review this value'}}
+ statusVariant="detached"
+ />,
+ );
+
+ expect(
+ container.querySelector('.astryx-input-status-icon'),
+ ).not.toBeInTheDocument();
+ expect(container.querySelector('.astryx-field-status')).toHaveAttribute(
+ 'data-variant',
+ 'detached',
+ );
+ expect(
+ container.querySelector('.astryx-field-status-icon'),
+ ).toBeInTheDocument();
+ });
+
+ it('surfaces tooltip status through a focusable in-editor icon', () => {
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ status={{type: 'error', message: 'Required'}}
+ statusVariant="tooltip"
+ />,
+ );
+
+ expect(
+ container.querySelector('.astryx-field-status'),
+ ).not.toBeInTheDocument();
+ const statusButton = screen.getByRole('button', {
+ name: /error details/i,
+ });
+ const tooltip = screen.getByRole('tooltip', h);
+ const textbox = screen.getByRole('textbox');
+ expect(statusButton).toHaveAttribute('type', 'button');
+ expect(statusButton.getAttribute('aria-describedby')).toContain(tooltip.id);
+ expect(textbox.getAttribute('aria-describedby')).toContain(tooltip.id);
+ expect(tooltip).toHaveTextContent('Required');
+ });
+
it('sets aria-required when required', () => {
render(<RichTextEditor label="Notes" isRequired />);
expect(screen.getByRole('textbox')).toHaveAttribute(
@@ -930,24 +1094,85 @@ describe('markdown serializers', () => {
});
describe('RichTextEditorToolbar', () => {
- it('renders inside the editor plugins slot with formatting controls', () => {
- render(
- <RichTextEditor label="Notes" plugins={<RichTextEditorToolbar />} />,
+ it('treats a false conditional toolbar as absent', () => {
+ const {container, rerender} = render(
+ <RichTextEditor label="Notes" toolbar={false} tabEscapeHint="" />,
);
- // Toolbar landmark with its accessible label.
+ const conditionalBodyClass = container.querySelector(
+ '.astryx-rich-text-editor',
+ )?.firstElementChild?.className;
+
+ rerender(<RichTextEditor label="Notes" tabEscapeHint="" />);
+
expect(
- screen.getByRole('toolbar', {name: 'Text formatting'}),
- ).toBeInTheDocument();
- // A representative set of format buttons are present and labelled.
+ container.querySelector('.astryx-rich-text-editor')?.firstElementChild
+ ?.className,
+ ).toBe(conditionalBodyClass);
+ expect(screen.queryByRole('toolbar')).not.toBeInTheDocument();
+ });
+
+ it('renders flush at the top before the editing surface', () => {
+ const {container} = render(
+ <RichTextEditor label="Notes" toolbar={<RichTextEditorToolbar />} />,
+ );
+ const toolbar = screen.getByRole('toolbar', {name: 'Text formatting'});
+ const textbox = screen.getByRole('textbox');
+ const editor = container.querySelector('.astryx-rich-text-editor');
+ const toolbarRegion = toolbar.parentElement?.parentElement;
+ const editorBody = toolbarRegion?.nextElementSibling;
+
+ expect(toolbar).toHaveClass('astryx-toolbar');
+ expect(toolbar).toHaveAttribute('data-size', 'sm');
+ expect(screen.getByRole('button', {name: 'Bold'})).toHaveAttribute(
+ 'data-size',
+ 'sm',
+ );
+ expect(
+ toolbar.compareDocumentPosition(textbox) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(toolbarRegion?.parentElement).toBe(editor);
+ expect(editorBody).toBeInstanceOf(HTMLElement);
+ // Vitest's JSDOM setup does not load compiled StyleX CSS. The WithToolbar
+ // story provides visual coverage for flush edges and preserved body inset;
+ // here we verify that the dedicated body receives its StyleX layout.
+ expect(
+ [...(editorBody?.classList ?? [])].some(className =>
+ className.startsWith('x'),
+ ),
+ ).toBe(true);
+
+ // Block formatting is consolidated into a selector, while history and
+ // inline formatting remain direct buttons.
+ expect(
+ screen.getByRole('combobox', {name: 'Block format'}).parentElement,
+ ).toHaveAttribute('data-size', 'sm');
+ const historyDivider = screen.getByRole('separator', {
+ name: 'History and block formats',
+ });
+ const inlineDivider = screen.getByRole('separator', {
+ name: 'Block and inline formats',
+ });
+ expect(historyDivider).toHaveAttribute('aria-orientation', 'vertical');
+ expect(inlineDivider).toHaveAttribute('aria-orientation', 'vertical');
+
+ const blockSelector = screen.getByRole('combobox', {
+ name: 'Block format',
+ });
+ expect(
+ historyDivider.compareDocumentPosition(blockSelector) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(
+ blockSelector.compareDocumentPosition(inlineDivider) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
for (const name of [
'Bold',
'Italic',
'Underline',
'Strikethrough',
'Inline code',
- 'Quote',
- 'Bulleted list',
- 'Numbered list',
'Undo',
'Redo',
]) {
@@ -955,17 +1180,28 @@ describe('RichTextEditorToolbar', () => {
}
});
- it('renders one heading button per configured level', () => {
+ it('renders configured headings and block formats in the selector', async () => {
+ const user = userEvent.setup();
render(
<RichTextEditor
label="Notes"
- plugins={<RichTextEditorToolbar headingLevels={['h1', 'h2']} />}
+ toolbar={<RichTextEditorToolbar headingLevels={['h1', 'h2']} />}
/>,
);
- expect(screen.getByRole('button', {name: 'Heading 1'})).toBeInTheDocument();
- expect(screen.getByRole('button', {name: 'Heading 2'})).toBeInTheDocument();
+ await user.click(screen.getByRole('combobox', {name: 'Block format'}));
+
+ for (const name of [
+ 'Paragraph',
+ 'Heading 1',
+ 'Heading 2',
+ 'Bulleted list',
+ 'Numbered list',
+ 'Block quote',
+ ]) {
+ expect(screen.getByRole('option', {name, ...h})).toBeInTheDocument();
+ }
expect(
- screen.queryByRole('button', {name: 'Heading 3'}),
+ screen.queryByRole('option', {name: 'Heading 3', ...h}),
).not.toBeInTheDocument();
});
@@ -973,7 +1209,7 @@ describe('RichTextEditorToolbar', () => {
render(
<RichTextEditor
label="Notes"
- plugins={<RichTextEditorToolbar label="Editor controls" />}
+ toolbar={<RichTextEditorToolbar label="Editor controls" />}
/>,
);
expect(
@@ -985,7 +1221,7 @@ describe('RichTextEditorToolbar', () => {
render(
<RichTextEditor
label="Notes"
- plugins={
+ toolbar={
<RichTextEditorToolbar
endContent={<button type="button">Custom</button>}
/>
@@ -995,12 +1231,35 @@ describe('RichTextEditorToolbar', () => {
expect(screen.getByRole('button', {name: 'Custom'})).toBeInTheDocument();
});
+ it('keeps every formatting action directly available in the scroll row', () => {
+ render(
+ <RichTextEditor label="Notes" toolbar={<RichTextEditorToolbar />} />,
+ );
+
+ const actionRow = screen.getByRole('group', {
+ name: 'Formatting actions',
+ });
+ for (const name of [
+ 'Bold',
+ 'Italic',
+ 'Underline',
+ 'Strikethrough',
+ 'Inline code',
+ 'Link',
+ ]) {
+ expect(actionRow).toContainElement(screen.getByRole('button', {name}));
+ }
+ expect(
+ screen.queryByRole('button', {name: 'More text formatting options'}),
+ ).not.toBeInTheDocument();
+ });
+
it('disables formatting controls when the editor is read-only', () => {
render(
<RichTextEditor
label="Notes"
isReadOnly
- plugins={<RichTextEditorToolbar />}
+ toolbar={<RichTextEditorToolbar />}
/>,
);
expect(screen.getByRole('button', {name: 'Bold'})).toBeDisabled();
@@ -1012,12 +1271,14 @@ describe('RichTextEditorToolbar', () => {
});
try {
render(
- <RichTextEditor label="Notes" plugins={<RichTextEditorToolbar />} />,
+ <RichTextEditor label="Notes" toolbar={<RichTextEditorToolbar />} />,
);
// The Bold control uses the theme's registered glyph instead of the
// bundled inline default.
const bold = screen.getByRole('button', {name: 'Bold'});
- expect(bold).toContainElement(screen.getByTestId('themed-bold'));
+ expect(
+ bold.querySelector('[data-testid="themed-bold"]'),
+ ).toBeInTheDocument();
} finally {
resetIcons();
}
@@ -1069,16 +1330,51 @@ describe('linkUtils', () => {
describe('RichTextEditorToolbar — links', () => {
it('renders a Link button by default', () => {
render(
- <RichTextEditor label="Notes" plugins={<RichTextEditorToolbar />} />,
+ <RichTextEditor label="Notes" toolbar={<RichTextEditorToolbar />} />,
);
expect(screen.getByRole('button', {name: 'Link'})).toBeInTheDocument();
});
+ it('opens an Astryx Dialog instead of the browser prompt by default', async () => {
+ const browserPrompt = vi.spyOn(window, 'prompt').mockReturnValue(null);
+ try {
+ render(
+ <RichTextEditor label="Notes" toolbar={<RichTextEditorToolbar />} />,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Link'}));
+
+ expect(browserPrompt).not.toHaveBeenCalled();
+ await waitFor(() =>
+ expect(
+ screen.getByRole('dialog', {name: 'Insert link', ...h}),
+ ).toBeInTheDocument(),
+ );
+ const dialog = screen.getByRole('dialog', {
+ name: 'Insert link',
+ ...h,
+ });
+ expect(dialog.querySelector('.astryx-layout-header')).toBeInTheDocument();
+ expect(
+ dialog.querySelector('.astryx-layout-content'),
+ ).toBeInTheDocument();
+ expect(dialog.querySelector('.astryx-layout-footer')).toBeInTheDocument();
+ expect(
+ screen.getByRole('textbox', {name: 'URL', ...h}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Add link', ...h}),
+ ).toBeInTheDocument();
+ } finally {
+ browserPrompt.mockRestore();
+ }
+ });
+
it('omits the Link button when hasLink is false', () => {
render(
<RichTextEditor
label="Notes"
- plugins={<RichTextEditorToolbar hasLink={false} />}
+ toolbar={<RichTextEditorToolbar hasLink={false} />}
/>,
);
expect(
@@ -1091,7 +1387,7 @@ describe('RichTextEditorToolbar — links', () => {
render(
<RichTextEditor
label="Notes"
- plugins={<RichTextEditorToolbar promptForUrl={promptForUrl} />}
+ toolbar={<RichTextEditorToolbar promptForUrl={promptForUrl} />}
/>,
);
const textbox = screen.getByRole('textbox');
@@ -1117,12 +1413,8 @@ describe('RichTextEditorToolbar — links', () => {
render(
<RichTextEditor
label="Notes"
- plugins={
- <>
- <RichTextEditorToolbar promptForUrl={promptForUrl} />
- <CaptureEditor onReady={e => (editor = e)} />
- </>
- }
+ toolbar={<RichTextEditorToolbar promptForUrl={promptForUrl} />}
+ plugins={<CaptureEditor onReady={e => (editor = e)} />}
/>,
);
await waitFor(() => expect(editor).toBeDefined());
@@ -1172,12 +1464,8 @@ describe('RichTextEditorToolbar — links', () => {
render(
<RichTextEditor
label="Notes"
- plugins={
- <>
- <RichTextEditorToolbar promptForUrl={promptForUrl} />
- <CaptureEditor onReady={e => (editor = e)} />
- </>
- }
+ toolbar={<RichTextEditorToolbar promptForUrl={promptForUrl} />}
+ plugins={<CaptureEditor onReady={e => (editor = e)} />}
/>,
);
await waitFor(() => expect(editor).toBeDefined());
@@ -1286,12 +1574,8 @@ describe('RichTextEditorToolbar — new-tab links', () => {
render(
<RichTextEditor
label="Notes"
- plugins={
- <>
- <RichTextEditorToolbar promptForUrl={promptForUrl} />
- <CaptureEditor onReady={e => (editor = e)} />
- </>
- }
+ toolbar={<RichTextEditorToolbar promptForUrl={promptForUrl} />}
+ plugins={<CaptureEditor onReady={e => (editor = e)} />}
/>,
);
await waitFor(() => expect(editor).toBeDefined());
@@ -1340,15 +1624,13 @@ describe('RichTextEditorToolbar — new-tab links', () => {
render(
<RichTextEditor
label="Notes"
- plugins={
- <>
- <RichTextEditorToolbar
- promptForUrl={promptForUrl}
- linkOpensInNewTab={false}
- />
- <CaptureEditor onReady={e => (editor = e)} />
- </>
+ toolbar={
+ <RichTextEditorToolbar
+ promptForUrl={promptForUrl}
+ linkOpensInNewTab={false}
+ />
}
+ plugins={<CaptureEditor onReady={e => (editor = e)} />}
/>,
);
await waitFor(() => expect(editor).toBeDefined());
diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.tsx
index f82040ad1f..de2ce653a4 100644
--- a/packages/lab/src/RichTextEditor/RichTextEditor.tsx
+++ b/packages/lab/src/RichTextEditor/RichTextEditor.tsx
@@ -5,9 +5,10 @@
/**
* @file RichTextEditor.tsx
* @input Uses React, useId, Lexical (lexical + @lexical/react), Field,
- * VisuallyHidden, design tokens
- * @output Exports RichTextEditor component, RichTextEditorProps, RichTextEditorStatus,
- * RichTextEditorStatusType, RichTextEditorSize
+ * 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
* @position Experimental (lab) implementation; consumed by RichTextEditor/index.ts and
* re-exported from @astryxdesign/lab. Tested by RichTextEditor.test.tsx.
*
@@ -50,12 +51,13 @@ import {
inputStatusBorderStyles,
inputStatusHoverShadowStyles,
inputStatusFocusWithinStyles,
+ type FieldStatusVariant,
} from '@astryxdesign/core/Field';
import type {BaseProps} from '@astryxdesign/core';
+import {useInputStatusIcon} from '@astryxdesign/core/hooks';
import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
-import type {SizeValue} from '@astryxdesign/core/utils';
+import {mergeProps, themeProps, type SizeValue} from '@astryxdesign/core/utils';
import {useSize} from '@astryxdesign/core/SizeContext';
-import {themeProps} from '@astryxdesign/core/utils';
import {
LexicalComposer,
@@ -129,41 +131,73 @@ const EMPTY_EDITOR_STATE_JSON = JSON.stringify({
const styles = stylex.create({
wrapper: {
+ // Establish a new container boundary so Toolbar's Section does not escape
+ // padding inherited from an ancestor Section outside the editor field.
+ '--container-padding-inline-start': '0px',
+ '--container-padding-inline-end': '0px',
+ '--container-padding-block-start': '0px',
+ '--container-padding-block-end': '0px',
flexDirection: 'column',
alignItems: 'stretch',
- paddingBlock: spacingVars['--spacing-1'],
+ gap: spacingVars['--spacing-0'],
+ paddingBlock: spacingVars['--spacing-0'],
+ paddingInline: spacingVars['--spacing-0'],
minHeight: 'auto',
},
+ editorBody: {
+ position: 'relative',
+ boxSizing: 'border-box',
+ width: '100%',
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ },
+ editorBodyWithToolbar: {
+ borderTopWidth: 1,
+ borderTopStyle: 'solid',
+ borderTopColor: colorVars['--color-border'],
+ },
+ editorBodyWithStatus: {
+ // Reserve the same trailing space as TextArea: the normal text inset plus
+ // room for the 20px status icon and its gap.
+ paddingInlineEnd: `calc(${spacingVars['--spacing-2']} + ${spacingVars['--spacing-6']})`,
+ },
contentEditable: {
display: 'block',
width: '100%',
- minHeight: '4.5rem',
borderWidth: 0,
borderStyle: 'none',
padding: 0,
outline: 'none',
- fontFamily: typographyVars['--font-family-body'],
- fontSize: {
- default: typeScaleVars['--text-body-size'],
- '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,
- },
- lineHeight: typeScaleVars['--text-body-leading'],
color: colorVars['--color-text-primary'],
},
placeholder: {
position: 'absolute',
- top: spacingVars['--spacing-1'],
+ top: spacingVars['--spacing-0'],
insetInlineStart: 0,
pointerEvents: 'none',
userSelect: 'none',
color: colorVars['--color-text-secondary'],
- fontFamily: typographyVars['--font-family-body'],
- fontSize: typeScaleVars['--text-body-size'],
- lineHeight: typeScaleVars['--text-body-leading'],
},
editorRoot: {
position: 'relative',
width: '100%',
+ // ContentEditable and Lexical's sibling placeholder inherit one shared
+ // text style. This keeps their leading and coarse-pointer sizing identical
+ // to TextInput/TextArea without duplicating placeholder typography.
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: {
+ default: typeScaleVars['--text-body-size'],
+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,
+ },
+ lineHeight: typeScaleVars['--text-body-leading'],
+ },
+ statusIcon: {
+ position: 'absolute',
+ top: spacingVars['--spacing-2'],
+ insetInlineEnd: spacingVars['--spacing-2'],
+ zIndex: 1,
+ display: 'flex',
+ alignItems: 'center',
},
disabled: {
cursor: 'not-allowed',
@@ -181,7 +215,11 @@ const styles = stylex.create({
},
});
-const sizeStyles = stylex.create({
+const dynamicStyles = stylex.create({
+ contentEditableMinHeight: (minHeight: SizeValue) => ({minHeight}),
+});
+
+const editorBodySizeStyles = stylex.create({
sm: {},
md: {},
lg: {
@@ -302,11 +340,27 @@ export interface RichTextEditorProps extends Omit<
* provided, displays a message box below the editor.
*/
status?: RichTextEditorStatus;
+ /**
+ * How the status message is placed relative to the editor.
+ * - 'attached': message overlaps directly below the editor and the status
+ * icon remains inside the editing surface
+ * - 'detached': message floats below with its own leading status icon
+ * - 'tooltip': no message box; the in-editor status icon becomes a focusable
+ * info-tip button that reveals the message
+ * @default 'attached'
+ */
+ statusVariant?: FieldStatusVariant;
/**
* Width of the field. Numbers are treated as pixels, strings are used as-is
* (e.g. `'100%'`).
*/
width?: SizeValue;
+ /**
+ * Minimum height of the editable content surface. Numbers are treated as
+ * pixels, strings are used as CSS lengths.
+ * @default '4.5rem'
+ */
+ minHeight?: SizeValue;
/** Tooltip text to display in an info icon at the end of the label. */
labelTooltip?: string;
/**
@@ -320,10 +374,17 @@ export interface RichTextEditorProps extends Omit<
* custom nodes (e.g. mentions, images) without forking the editor.
*/
nodes?: ReadonlyArray<Klass<LexicalNode>>;
+ /**
+ * Toolbar content rendered edge-to-edge at the top of the field, before the
+ * padded editing surface. Pass `<RichTextEditorToolbar />` here so the
+ * toolbar stays inside the Lexical composer while retaining correct visual
+ * and keyboard order.
+ */
+ toolbar?: ReactNode;
/**
* Additional Lexical plugins to render inside the composer. Use this to
- * compose extra behaviour (toolbars, mentions, autolink, etc.) on top of the
- * base editor. Plugins receive the editor via `useLexicalComposerContext()`.
+ * compose extra behaviour (mentions, autolink, etc.) on top of the base
+ * editor. Plugins receive the editor via `useLexicalComposerContext()`.
*/
plugins?: ReactNode;
/**
@@ -383,9 +444,9 @@ export interface RichTextEditorProps extends Omit<
* `@lexical/*` are optional peer dependencies — install them to use this
* component.
*
- * The editor is intentionally minimal and extensible: pass `nodes` and
- * `plugins` to layer richer behaviour (toolbars, mentions, hover cards) on top
- * without forking.
+ * The editor is intentionally minimal and extensible: pass `toolbar`, `nodes`,
+ * and `plugins` to layer richer behaviour (formatting, mentions, hover cards)
+ * on top without forking.
*
* The forwarded `RichTextEditorRef` exposes imperative `focus()` and `clear()`
* methods for callers that manage the editor from outside.
@@ -418,10 +479,13 @@ export const RichTextEditor = forwardRef<
isReadOnly = false,
isDisabled = false,
status,
+ statusVariant = 'attached',
width,
+ minHeight = '4.5rem',
labelTooltip,
size: sizeProp,
nodes,
+ toolbar,
plugins,
hasMarkdownShortcuts = true,
transformers = TRANSFORMERS,
@@ -437,7 +501,8 @@ export const RichTextEditor = forwardRef<
ref: Ref<RichTextEditorRef>,
) {
const size = useSize(sizeProp, 'md');
- const id = useId();
+ const inputID = useId();
+ const labelID = useId();
const descriptionID = useId();
const statusMessageID = useId();
const placeholderID = useId();
@@ -475,11 +540,21 @@ export const RichTextEditor = forwardRef<
};
const hasTabEscapeHint = editable && tabEscapeHint !== '';
+ const hasToolbar = toolbar != null && typeof toolbar !== 'boolean';
+
+ const {statusIcon, describedBy: statusTooltipDescribedBy} =
+ useInputStatusIcon({
+ status,
+ statusVariant,
+ });
const ariaDescribedBy =
[
description ? descriptionID : null,
- status?.message ? statusMessageID : null,
+ statusVariant !== 'tooltip' && status?.message ? statusMessageID : null,
+ // Tooltip status renders no FieldStatus message box. Reference the
+ // tooltip layer so assistive technology still receives the message.
+ statusTooltipDescribedBy,
placeholder ? placeholderID : null,
maxLength != null ? counterID : null,
hasTabEscapeHint ? tabEscapeHintID : null,
@@ -492,7 +567,8 @@ export const RichTextEditor = forwardRef<
label={label}
isLabelHidden={isLabelHidden}
description={description}
- inputID={id}
+ inputID={inputID}
+ labelID={labelID}
descriptionID={description ? descriptionID : undefined}
isOptional={isOptional}
isRequired={isRequired}
@@ -506,68 +582,87 @@ export const RichTextEditor = forwardRef<
}
: undefined
}
+ statusVariant={statusVariant}
labelTooltip={labelTooltip}
width={width}>
<div
- {...themeProps('rich-text-editor', {
- size,
- status: status?.type ?? null,
- })}
- {...stylex.props(
- inputWrapperStyles.base,
- styles.wrapper,
- sizeStyles[size],
- (isDisabled || isReadOnly) && inputWrapperStyles.disabled,
- isDisabled && styles.disabled,
- status && inputStatusBorderStyles[status.type],
- status && inputStatusHoverShadowStyles[status.type],
- status && inputStatusFocusWithinStyles[status.type],
- xstyle,
- )}
- className={className}
- style={style}>
+ {...mergeProps(
+ themeProps('rich-text-editor', {
+ size,
+ status: status?.type ?? null,
+ }),
+ stylex.props(
+ inputWrapperStyles.base,
+ styles.wrapper,
+ (isDisabled || isReadOnly) && inputWrapperStyles.disabled,
+ isDisabled && styles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status &&
+ !isDisabled &&
+ !isReadOnly &&
+ inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
<LexicalComposer initialConfig={initialConfig}>
- <div {...stylex.props(styles.editorRoot)}>
- <RichTextPlugin
- contentEditable={
- <EditorContentEditable
- ariaLabel={isLabelHidden ? label : undefined}
- ariaLabelledBy={isLabelHidden ? undefined : id}
- ariaDescribedBy={ariaDescribedBy}
- ariaRequired={isRequired && !isOptional}
- ariaInvalid={status?.type === 'error'}
- placeholderText={placeholder}
- placeholderID={placeholderID}
- rest={rest}
+ {hasToolbar ? toolbar : null}
+ <div
+ {...stylex.props(
+ styles.editorBody,
+ hasToolbar && styles.editorBodyWithToolbar,
+ !!statusIcon && styles.editorBodyWithStatus,
+ editorBodySizeStyles[size],
+ )}>
+ <div {...stylex.props(styles.editorRoot)}>
+ <RichTextPlugin
+ contentEditable={
+ <EditorContentEditable
+ id={inputID}
+ ariaLabel={isLabelHidden ? label : undefined}
+ ariaLabelledBy={isLabelHidden ? undefined : labelID}
+ ariaDescribedBy={ariaDescribedBy}
+ ariaRequired={isRequired && !isOptional}
+ ariaInvalid={status?.type === 'error'}
+ placeholderText={placeholder}
+ placeholderID={placeholderID}
+ minHeight={minHeight}
+ rest={rest}
+ />
+ }
+ placeholder={null}
+ ErrorBoundary={LexicalErrorBoundary}
+ />
+ <HistoryPlugin />
+ <ListPlugin />
+ <LinkPlugin />
+ <TabIndentationPlugin />
+ <TabFocusEscapePlugin />
+ {hasMarkdownShortcuts && (
+ <MarkdownShortcutPlugin transformers={markdownTransformers} />
+ )}
+ {hasAutoFocus && <AutoFocusOnMount />}
+ {onChange && (
+ <OnChangePlugin
+ onChange={onChange}
+ ignoreHistoryMergeTagChange
+ ignoreSelectionChange
/>
- }
- placeholder={null}
- ErrorBoundary={LexicalErrorBoundary}
- />
- <HistoryPlugin />
- <ListPlugin />
- <LinkPlugin />
- <TabIndentationPlugin />
- <TabFocusEscapePlugin />
- {hasMarkdownShortcuts && (
- <MarkdownShortcutPlugin transformers={markdownTransformers} />
- )}
- {hasAutoFocus && <AutoFocusOnMount />}
- {onChange && (
- <OnChangePlugin
- onChange={onChange}
- ignoreHistoryMergeTagChange
- ignoreSelectionChange
+ )}
+ {plugins}
+ <EditorRefBridge
+ editorRef={ref}
+ editable={editable}
+ transformers={markdownTransformers}
/>
- )}
- {plugins}
- <EditorRefBridge
- editorRef={ref}
- editable={editable}
- transformers={markdownTransformers}
- />
- {maxLength != null && (
- <CharCountPlugin onCountChange={setCharCount} />
+ {maxLength != null && (
+ <CharCountPlugin onCountChange={setCharCount} />
+ )}
+ </div>
+ {statusIcon && (
+ <div {...stylex.props(styles.statusIcon)}>{statusIcon}</div>
)}
</div>
</LexicalComposer>
@@ -748,7 +843,9 @@ function EditorRefBridge({
// $generateHtmlFromNodes serializes the whole document (null selection)
// to HTML; must run in a read context and requires a DOM.
// `@lexical/html` is a subpackage (built dist) — safe.
- editor.getEditorState().read(() => $generateHtmlFromNodes(editor, null)),
+ editor
+ .getEditorState()
+ .read(() => $generateHtmlFromNodes(editor, null)),
getEditor: () => editor,
}),
[editor, editable, transformers],
@@ -778,7 +875,7 @@ function CharCountPlugin({
// `declare` class fields) and fails. Both APIs used here are methods on the
// editor instance, so no top-level `lexical` value import is needed.
onCountChange(editor.getRootElement()?.textContent?.length ?? 0);
- return editor.registerTextContentListener((textContent) => {
+ return editor.registerTextContentListener(textContent => {
onCountChange(textContent.length);
});
}, [editor, onCountChange]);
@@ -791,6 +888,7 @@ function CharCountPlugin({
* neither) is satisfied by two concrete branches rather than a spread.
*/
function EditorContentEditable({
+ id,
ariaLabel,
ariaLabelledBy,
ariaDescribedBy,
@@ -798,8 +896,10 @@ function EditorContentEditable({
ariaInvalid,
placeholderText,
placeholderID,
+ minHeight,
rest,
}: {
+ id: string;
ariaLabel?: string;
ariaLabelledBy?: string;
ariaDescribedBy?: string;
@@ -807,9 +907,11 @@ function EditorContentEditable({
ariaInvalid: boolean;
placeholderText?: string;
placeholderID: string;
+ minHeight: SizeValue;
rest: Record<string, unknown>;
}) {
const shared = {
+ id,
role: 'textbox' as const,
'aria-multiline': 'true' as const,
'aria-label': ariaLabel,
@@ -817,7 +919,10 @@ function EditorContentEditable({
'aria-describedby': ariaDescribedBy,
'aria-required': ariaRequired ? ('true' as const) : undefined,
'aria-invalid': ariaInvalid ? ('true' as const) : undefined,
- ...stylex.props(styles.contentEditable),
+ ...stylex.props(
+ styles.contentEditable,
+ dynamicStyles.contentEditableMinHeight(minHeight),
+ ),
...rest,
};
if (placeholderText) {
diff --git a/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx b/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx
index c1b542382d..8fe16e9d20 100644
--- a/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx
+++ b/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx
@@ -6,12 +6,13 @@
* @file RichTextEditorToolbar.tsx
* @input Uses React, @lexical/react (composer context), @lexical/rich-text,
* @lexical/selection, @lexical/list, @lexical/utils, and the lexical core
- * command constants, plus Astryx Toolbar / ToggleButton / Divider primitives.
- * @output Exports RichTextEditorToolbar (a composable formatting toolbar) and
- * RichTextEditorToolbarProps.
- * @position Experimental (lab). Drop into RichTextEditor's `plugins` slot to add
- * a formatting toolbar. Themed via Astryx Toolbar/ToggleButton, so it inherits
- * the active theme with no extra styling.
+ * command constants, plus Astryx Toolbar / IconButton / Selector /
+ * ToggleButton / Divider / Dialog / TextInput / Button / Layout primitives.
+ * @output Exports RichTextEditorToolbar (a compact formatting toolbar with a
+ * horizontally scrollable action row) and RichTextEditorToolbarProps.
+ * @position Experimental (lab). Drop into RichTextEditor's `toolbar` slot to
+ * add a flush top formatting toolbar. Themed via Astryx Toolbar, Selector,
+ * IconButton, and ToggleButton, so it inherits the active theme.
*
* SYNC: When modified, update:
* - /packages/lab/src/RichTextEditor/index.ts (exports)
@@ -33,7 +34,15 @@
* registerIcons({'richtext:bold': <MyBoldIcon />});
*/
-import {useCallback, useEffect, useState, type ReactNode} from 'react';
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type FormEvent,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import {$setBlocksType} from '@lexical/selection';
import {
@@ -48,13 +57,24 @@ import {
ListNode,
INSERT_ORDERED_LIST_COMMAND,
INSERT_UNORDERED_LIST_COMMAND,
- REMOVE_LIST_COMMAND,
} from '@lexical/list';
import {$getNearestNodeOfType, mergeRegister} from '@lexical/utils';
import {TOGGLE_LINK_COMMAND, $isLinkNode, $createLinkNode} from '@lexical/link';
import {Toolbar} from '@astryxdesign/core/Toolbar';
+import {IconButton} from '@astryxdesign/core/IconButton';
+import {Selector, type SelectorOptionType} from '@astryxdesign/core/Selector';
import {ToggleButton} from '@astryxdesign/core/ToggleButton';
import {Divider} from '@astryxdesign/core/Divider';
+import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {Button} from '@astryxdesign/core/Button';
+import {Stack} from '@astryxdesign/core/Stack';
+import {
+ HStack,
+ Layout,
+ LayoutContent,
+ LayoutFooter,
+} from '@astryxdesign/core/Layout';
import {getExtendedIcon} from '@astryxdesign/core/Icon';
import {
FORMAT_TEXT_COMMAND,
@@ -70,12 +90,14 @@ import {
isExactShortcutMatch,
$getSelection,
$isRangeSelection,
+ $setSelection,
$createParagraphNode,
$createTextNode,
+ type RangeSelection,
} from 'lexical';
import {sanitizeUrl} from './linkUtils';
-/** Block types the toolbar can toggle. */
+/** Block types exposed by the toolbar's format selector. */
type BlockType =
'paragraph' | 'h1' | 'h2' | 'h3' | 'quote' | 'bullet' | 'number';
@@ -92,6 +114,35 @@ const HEADING_LABELS: Record<'h1' | 'h2' | 'h3', string> = {
*/
const CONTROL_OR_META = {ctrlKey: !IS_APPLE, metaKey: IS_APPLE};
+interface LinkContext {
+ selectedText: string;
+ url: string;
+ isLink: boolean;
+}
+
+// A vertical Divider's default 100% height needs a definite parent height.
+// Toolbar slots are sized by their controls instead, so let flexbox stretch
+// these group separators across the slot's resolved height.
+const toolbarDividerStyles = stylex.create({
+ vertical: {
+ alignSelf: 'stretch',
+ height: 'auto',
+ },
+});
+
+const toolbarScrollStyles = stylex.create({
+ actions: {
+ flex: '1 1 0%',
+ width: 0,
+ maxWidth: '100%',
+ minWidth: 0,
+ overflowX: 'auto',
+ overflowY: 'hidden',
+ overscrollBehaviorX: 'contain',
+ scrollbarWidth: 'thin',
+ },
+});
+
/**
* Whether `event` is the insert-link shortcut (Cmd/Ctrl+K). Uses Lexical's
* `isExactShortcutMatch`, which — unlike a loose `metaKey || ctrlKey` check —
@@ -115,6 +166,7 @@ export const RICHTEXT_ICON_KEYS = {
strikethrough: 'richtext:strikethrough',
code: 'richtext:code',
link: 'richtext:link',
+ paragraph: 'richtext:paragraph',
h1: 'richtext:h1',
h2: 'richtext:h2',
h3: 'richtext:h3',
@@ -125,6 +177,20 @@ export const RICHTEXT_ICON_KEYS = {
redo: 'richtext:redo',
} as const;
+const INLINE_FORMAT_ACTIONS = [
+ {format: 'bold', label: 'Bold', icon: 'bold'},
+ {format: 'italic', label: 'Italic', icon: 'italic'},
+ {format: 'underline', label: 'Underline', icon: 'underline'},
+ {
+ format: 'strikethrough',
+ label: 'Strikethrough',
+ icon: 'strikethrough',
+ },
+ {format: 'code', label: 'Inline code', icon: 'code'},
+] as const;
+
+type InlineFormat = (typeof INLINE_FORMAT_ACTIONS)[number]['format'];
+
/**
* Bundled 16px inline default icons — no external icon dependency. These are
* the fallbacks used when a theme hasn't registered an override for the
@@ -223,6 +289,7 @@ const defaultToolbarIcons: Record<string, ReactNode> = {
/>
</svg>
),
+ paragraph: <TextGlyph label="¶" />,
h1: <TextGlyph label="H1" />,
h2: <TextGlyph label="H2" />,
h3: <TextGlyph label="H3" />,
@@ -347,17 +414,20 @@ export interface RichTextEditorToolbarProps {
*/
label?: string;
/**
- * Which heading levels to expose as block-type buttons, in order.
+ * Which heading levels to expose in the block-format selector, in order.
* @default ['h1', 'h2', 'h3']
*/
headingLevels?: ReadonlyArray<'h1' | 'h2' | 'h3'>;
- /** Toolbar size, forwarded to the Astryx Toolbar. @default 'sm' */
+ /**
+ * Toolbar size. Cascades to formatting controls and coordinates the
+ * Toolbar's internal padding.
+ * @default 'sm'
+ */
size?: 'sm' | 'md' | 'lg';
/**
- * Whether to show the insert/edit-link button. When enabled, pressing it on a
- * collapsed or non-link selection prompts for a URL (via `promptForUrl`,
- * `window.prompt` by default) and wraps the selection in a link; pressing it
- * while a link is selected removes the link.
+ * Whether to show the insert/edit-link button. By default, pressing it opens
+ * an Astryx Dialog. The form can add, update, or remove a link without
+ * losing the editor selection.
*
* Requires `LinkNode` to be registered (it is, by default) — no extra setup.
* The entered URL is sanitized (see `sanitizeUrl`) so only
@@ -368,8 +438,9 @@ export interface RichTextEditorToolbarProps {
/**
* Called to obtain a URL when the link button is pressed on a non-link
* selection. Return the URL string to link, or `null`/`''` to cancel.
- * Receives the currently selected text as a hint. Defaults to
- * `window.prompt`. Override to plug in a custom (e.g. Astryx Dialog) prompt.
+ * Receives the currently selected text as a hint. When omitted, the built-in
+ * Astryx Dialog is used. This synchronous override is retained
+ * for consumers that already provide their own URL UI.
*/
promptForUrl?: (selectedText: string) => string | null | undefined;
/**
@@ -395,7 +466,7 @@ export interface RichTextEditorToolbarProps {
* the current selection to keep the active states in sync and dispatches the
* standard Lexical formatting commands.
*
- * Render it inside the editor's `plugins` slot — it uses
+ * Render it inside the editor's `toolbar` slot — it uses
* `useLexicalComposerContext()` to reach the editor, so it must live within the
* `LexicalComposer` the editor sets up.
*
@@ -405,7 +476,7 @@ export interface RichTextEditorToolbarProps {
*
* <RichTextEditor
* label="Notes"
- * plugins={<RichTextEditorToolbar />}
+ * toolbar={<RichTextEditorToolbar />}
* />
* ```
*/
@@ -425,6 +496,16 @@ export function RichTextEditorToolbar({
const [canUndo, setCanUndo] = useState(false);
const [canRedo, setCanRedo] = useState(false);
const [isEditable, setIsEditable] = useState(() => editor.isEditable());
+ const savedSelectionRef = useRef<RangeSelection | null>(null);
+ const lastLinkContextRef = useRef<LinkContext>({
+ selectedText: '',
+ url: '',
+ isLink: false,
+ });
+ const [isLinkDialogOpen, setIsLinkDialogOpen] = useState(false);
+ const [isEditingLink, setIsEditingLink] = useState(false);
+ const [linkUrl, setLinkUrl] = useState('');
+ const [linkError, setLinkError] = useState('');
const $syncToolbar = useCallback(() => {
const selection = $getSelection();
@@ -450,8 +531,20 @@ export function RichTextEditorToolbar({
// eps-lexical toolbar (`$isLinkNode(parent) || $isLinkNode(node)`), which is
// the implementation astryx aims to be swappable with.
const node = selection.anchor.getNode();
- setIsLink($isLinkNode(node.getParent()) || $isLinkNode(node));
-
+ const parent = node.getParent();
+ const linkNode = $isLinkNode(node)
+ ? node
+ : $isLinkNode(parent)
+ ? parent
+ : null;
+ const selectionIsLink = linkNode != null;
+ setIsLink(selectionIsLink);
+ savedSelectionRef.current = selection.clone();
+ lastLinkContextRef.current = {
+ selectedText: selection.getTextContent(),
+ url: linkNode?.getURL() ?? '',
+ isLink: selectionIsLink,
+ };
const anchorNode = selection.anchor.getNode();
const element =
anchorNode.getKey() === 'root'
@@ -472,90 +565,138 @@ export function RichTextEditorToolbar({
}
}, []);
- /**
- * Toggle a link on the current selection.
- *
- * - On an existing (non-auto) link: removes it (`TOGGLE_LINK_COMMAND` with
- * `null`).
- * - Otherwise: reads the currently selected text, asks `promptForUrl`
- * (default `window.prompt`) for a URL, sanitizes it, then either wraps the
- * selection in a link or — for a collapsed caret with no selected text —
- * inserts a new link whose text and href are both the URL.
- *
- * Semantics deliberately mirror EPS eps-lexical's `LinkPopoverPlugin.
- * handleSubmit`: both dispatch the OSS `TOGGLE_LINK_COMMAND` and fall back to
- * `$createLinkNode` for a collapsed selection. astryx keeps the *command +
- * node contract* identical so EPS can later replace astryx's default prompt
- * with its own floating popover without changing behaviour.
- */
- const toggleLink = useCallback(() => {
- if (!editor.isEditable()) {
- return;
- }
-
- // Removing an existing (manually-created) link doesn't need a URL.
- if (isLink) {
- editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
- return;
- }
-
- // Read the selected text (as a prompt hint) inside a read context.
- let selectedText = '';
+ const readLinkContext = useCallback((): LinkContext => {
+ let context = lastLinkContextRef.current;
editor.getEditorState().read(() => {
const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selectedText = selection.getTextContent();
+ if (!$isRangeSelection(selection)) {
+ return;
}
+ const node = selection.anchor.getNode();
+ const parent = node.getParent();
+ const linkNode = $isLinkNode(node)
+ ? node
+ : $isLinkNode(parent)
+ ? parent
+ : null;
+ savedSelectionRef.current = selection.clone();
+ context = {
+ selectedText: selection.getTextContent(),
+ url: linkNode?.getURL() ?? '',
+ isLink: linkNode != null,
+ };
+ lastLinkContextRef.current = context;
});
+ return context;
+ }, [editor]);
- const ask =
- promptForUrl ??
- ((hint: string) =>
- typeof window !== 'undefined'
- ? window.prompt(
- 'Enter a URL',
- hint.startsWith('http') ? hint : 'https://',
- )
- : null);
- const entered = ask(selectedText);
- if (entered == null || entered.trim() === '') {
+ const restoreLinkSelection = useCallback(() => {
+ const savedSelection = savedSelectionRef.current;
+ if (!savedSelection) {
return;
}
- const url = sanitizeUrl(entered);
- if (url === 'about:blank') {
- // Sanitizer rejected the input (empty / unsafe scheme) — do nothing
- // rather than write a dead link.
+ editor.update(() => {
+ $setSelection(savedSelection.clone());
+ });
+ }, [editor]);
+
+ const applyLinkValue = useCallback(
+ (entered: string): boolean => {
+ const trimmed = entered.trim();
+ const url = sanitizeUrl(trimmed);
+ if (url === 'about:blank') {
+ return false;
+ }
+
+ restoreLinkSelection();
+ const linkAttributes = linkOpensInNewTab
+ ? {target: '_blank', rel: 'noopener noreferrer'}
+ : {};
+ const handled = editor.dispatchCommand(TOGGLE_LINK_COMMAND, {
+ url,
+ ...linkAttributes,
+ });
+ if (!handled) {
+ editor.update(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection) && selection.isCollapsed()) {
+ const linkNode = $createLinkNode(url, linkAttributes);
+ linkNode.append($createTextNode(trimmed));
+ selection.insertNodes([linkNode]);
+ }
+ });
+ }
+ return true;
+ },
+ [editor, linkOpensInNewTab, restoreLinkSelection],
+ );
+
+ const toggleLink = useCallback(() => {
+ if (!editor.isEditable()) {
return;
}
- // New-tab attributes are baked into the LINK NODE DATA (not patched onto
- // the DOM): TOGGLE_LINK_COMMAND accepts `{url, target, rel}` and stores
- // them on the node, so they serialize and round-trip. rel="noopener
- // noreferrer" is required whenever target="_blank" (reverse-tabnabbing).
- const linkAttributes = linkOpensInNewTab
- ? {target: '_blank', rel: 'noopener noreferrer'}
- : {};
-
- // Dispatch TOGGLE_LINK_COMMAND so any DecoratorNode handlers can intercept
- // first (parity with eps-lexical). If nothing consumes it, the built-in
- // @lexical/link handler wraps the selection. `dispatchCommand` returns
- // whether a handler ran; on a collapsed caret the built-in handler is a
- // no-op, so we insert an explicit link node as a fallback.
- const handled = editor.dispatchCommand(TOGGLE_LINK_COMMAND, {
- url,
- ...linkAttributes,
- });
- if (!handled) {
- editor.update(() => {
- const selection = $getSelection();
- if ($isRangeSelection(selection) && selection.isCollapsed()) {
- const linkNode = $createLinkNode(url, linkAttributes);
- linkNode.append($createTextNode(entered.trim()));
- selection.insertNodes([linkNode]);
- }
- });
+ const context = readLinkContext();
+ if (promptForUrl) {
+ // Preserve the existing synchronous extension point for consumers that
+ // already provide their own URL UI.
+ if (context.isLink) {
+ restoreLinkSelection();
+ editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
+ return;
+ }
+ const entered = promptForUrl(context.selectedText);
+ if (entered != null && entered.trim() !== '') {
+ applyLinkValue(entered);
+ }
+ return;
}
- }, [editor, isLink, promptForUrl, linkOpensInNewTab]);
+
+ setLinkUrl(
+ context.url ||
+ (context.selectedText.startsWith('http')
+ ? context.selectedText
+ : 'https://'),
+ );
+ setIsEditingLink(context.isLink);
+ setLinkError('');
+ setIsLinkDialogOpen(true);
+ }, [
+ applyLinkValue,
+ editor,
+ promptForUrl,
+ readLinkContext,
+ restoreLinkSelection,
+ ]);
+
+ const handleLinkDialogOpenChange = useCallback((open: boolean) => {
+ setIsLinkDialogOpen(open);
+ setLinkError('');
+ }, []);
+
+ const closeLinkDialogToEditor = useCallback(() => {
+ setIsLinkDialogOpen(false);
+ setLinkError('');
+ requestAnimationFrame(() => editor.focus());
+ }, [editor]);
+
+ const handleLinkSubmit = useCallback(
+ (event: FormEvent<HTMLElement>) => {
+ event.preventDefault();
+ if (!applyLinkValue(linkUrl)) {
+ setLinkError('Enter a valid http, https, mailto, or tel URL.');
+ return;
+ }
+ closeLinkDialogToEditor();
+ },
+ [applyLinkValue, closeLinkDialogToEditor, linkUrl],
+ );
+
+ const removeLink = useCallback(() => {
+ restoreLinkSelection();
+ editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
+ closeLinkDialogToEditor();
+ }, [closeLinkDialogToEditor, editor, restoreLinkSelection]);
useEffect(() => {
return mergeRegister(
@@ -612,7 +753,7 @@ export function RichTextEditorToolbar({
);
}, [editor, $syncToolbar, hasLink, toggleLink]);
- const toggleInlineFormat = (format: string) => {
+ const toggleInlineFormat = (format: InlineFormat) => {
// FORMAT_TEXT_COMMAND payload is a TextFormatType; the values we pass are
// all valid members.
editor.dispatchCommand(
@@ -623,166 +764,207 @@ export function RichTextEditorToolbar({
};
const setBlock = (next: BlockType) => {
+ // Selector choices are idempotent: choosing the active block format keeps
+ // it active instead of toggling it back to paragraph.
+ if (!isEditable || blockType === next) {
+ return;
+ }
if (next === 'bullet') {
- editor.dispatchCommand(
- blockType === 'bullet'
- ? REMOVE_LIST_COMMAND
- : INSERT_UNORDERED_LIST_COMMAND,
- undefined,
- );
+ editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
return;
}
if (next === 'number') {
- editor.dispatchCommand(
- blockType === 'number'
- ? REMOVE_LIST_COMMAND
- : INSERT_ORDERED_LIST_COMMAND,
- undefined,
- );
+ editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
return;
}
- // Heading / quote / paragraph — toggle back to paragraph when already set.
- const target = blockType === next ? 'paragraph' : next;
editor.update(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) {
return;
}
$setBlocksType(selection, () => {
- if (target === 'quote') {
+ if (next === 'quote') {
return $createQuoteNode();
}
- if (target === 'h1' || target === 'h2' || target === 'h3') {
- return $createHeadingNode(target as HeadingTagType);
+ if (next === 'h1' || next === 'h2' || next === 'h3') {
+ return $createHeadingNode(next as HeadingTagType);
}
return $createParagraphNode();
});
});
};
+ const blockOptions: SelectorOptionType[] = [
+ {
+ value: 'paragraph',
+ label: 'Paragraph',
+ icon: resolveIcon('paragraph'),
+ },
+ ...headingLevels.map(level => ({
+ value: level,
+ label: HEADING_LABELS[level],
+ icon: resolveIcon(level),
+ })),
+ {
+ value: 'bullet',
+ label: 'Bulleted list',
+ icon: resolveIcon('bullet'),
+ },
+ {
+ value: 'number',
+ label: 'Numbered list',
+ icon: resolveIcon('number'),
+ },
+ {value: 'quote', label: 'Block quote', icon: resolveIcon('quote')},
+ ];
+
return (
- <Toolbar
- label={label}
- size={size}
- startContent={
- <>
- <ToggleButton
- label="Undo"
- icon={resolveIcon('undo')}
- isIconOnly
- isPressed={false}
- isDisabled={!isEditable || !canUndo}
- onPressedChange={() =>
- editor.dispatchCommand(UNDO_COMMAND, undefined)
- }
- />
- <ToggleButton
- label="Redo"
- icon={resolveIcon('redo')}
- isIconOnly
- isPressed={false}
- isDisabled={!isEditable || !canRedo}
- onPressedChange={() =>
- editor.dispatchCommand(REDO_COMMAND, undefined)
- }
- />
- <Divider orientation="vertical" />
- <ToggleButton
- label="Bold"
- icon={resolveIcon('bold')}
- isIconOnly
- isPressed={activeFormats.has('bold')}
- isDisabled={!isEditable}
- onPressedChange={() => toggleInlineFormat('bold')}
- />
- <ToggleButton
- label="Italic"
- icon={resolveIcon('italic')}
- isIconOnly
- isPressed={activeFormats.has('italic')}
- isDisabled={!isEditable}
- onPressedChange={() => toggleInlineFormat('italic')}
- />
- <ToggleButton
- label="Underline"
- icon={resolveIcon('underline')}
- isIconOnly
- isPressed={activeFormats.has('underline')}
- isDisabled={!isEditable}
- onPressedChange={() => toggleInlineFormat('underline')}
- />
- <ToggleButton
- label="Strikethrough"
- icon={resolveIcon('strikethrough')}
- isIconOnly
- isPressed={activeFormats.has('strikethrough')}
- isDisabled={!isEditable}
- onPressedChange={() => toggleInlineFormat('strikethrough')}
- />
- <ToggleButton
- label="Inline code"
- icon={resolveIcon('code')}
- isIconOnly
- isPressed={activeFormats.has('code')}
- isDisabled={!isEditable}
- onPressedChange={() => toggleInlineFormat('code')}
- />
- {hasLink && (
- <ToggleButton
- label="Link"
- icon={resolveIcon('link')}
- isIconOnly
- isPressed={isLink}
- isDisabled={!isEditable}
- onPressedChange={toggleLink}
+ <>
+ <Toolbar
+ label={label}
+ size={size}
+ startContent={
+ <HStack
+ gap={1}
+ role="group"
+ aria-label="Formatting actions"
+ xstyle={toolbarScrollStyles.actions}>
+ <IconButton
+ label="Undo"
+ icon={resolveIcon('undo')}
+ variant="ghost"
+ tooltip="Undo"
+ isDisabled={!isEditable || !canUndo}
+ onClick={() => editor.dispatchCommand(UNDO_COMMAND, undefined)}
+ />
+ <IconButton
+ label="Redo"
+ icon={resolveIcon('redo')}
+ variant="ghost"
+ tooltip="Redo"
+ isDisabled={!isEditable || !canRedo}
+ onClick={() => editor.dispatchCommand(REDO_COMMAND, undefined)}
+ />
+ <Divider
+ orientation="vertical"
+ aria-label="History and block formats"
+ xstyle={toolbarDividerStyles.vertical}
/>
- )}
- <Divider orientation="vertical" />
- {headingLevels.map(level => (
- <ToggleButton
- key={level}
- label={HEADING_LABELS[level]}
- icon={resolveIcon(level)}
- isIconOnly
- isPressed={blockType === level}
+ <Selector
+ label="Block format"
+ isLabelHidden
+ variant="ghost"
+ size={size}
+ value={blockType}
+ options={blockOptions}
+ startIcon={resolveIcon(blockType)}
isDisabled={!isEditable}
- onPressedChange={() => setBlock(level)}
+ onChange={value => setBlock(value as BlockType)}
/>
- ))}
- <ToggleButton
- label="Quote"
- icon={resolveIcon('quote')}
- isIconOnly
- isPressed={blockType === 'quote'}
- isDisabled={!isEditable}
- onPressedChange={() => setBlock('quote')}
- />
- <Divider orientation="vertical" />
- <ToggleButton
- label="Bulleted list"
- icon={resolveIcon('bullet')}
- isIconOnly
- isPressed={blockType === 'bullet'}
- isDisabled={!isEditable}
- onPressedChange={() => setBlock('bullet')}
- />
- <ToggleButton
- label="Numbered list"
- icon={resolveIcon('number')}
- isIconOnly
- isPressed={blockType === 'number'}
- isDisabled={!isEditable}
- onPressedChange={() => setBlock('number')}
- />
- {endContent != null && (
- <>
- <Divider orientation="vertical" />
- {endContent}
- </>
- )}
- </>
- }
- />
+ <Divider
+ orientation="vertical"
+ aria-label="Block and inline formats"
+ xstyle={toolbarDividerStyles.vertical}
+ />
+ {INLINE_FORMAT_ACTIONS.map(action => (
+ <ToggleButton
+ key={action.format}
+ label={action.label}
+ icon={resolveIcon(action.icon)}
+ size={size}
+ isIconOnly
+ isPressed={activeFormats.has(action.format)}
+ isDisabled={!isEditable}
+ onPressedChange={() => toggleInlineFormat(action.format)}
+ />
+ ))}
+ {hasLink && (
+ <ToggleButton
+ key="link"
+ label="Link"
+ icon={resolveIcon('link')}
+ size={size}
+ isIconOnly
+ isPressed={isLink || isLinkDialogOpen}
+ isDisabled={!isEditable}
+ aria-haspopup="dialog"
+ aria-expanded={isLinkDialogOpen}
+ onMouseDown={event => event.preventDefault()}
+ onPressedChange={toggleLink}
+ />
+ )}
+ {endContent != null && (
+ <>
+ <Divider orientation="vertical" />
+ {endContent}
+ </>
+ )}
+ </HStack>
+ }
+ />
+ {hasLink && (
+ <Dialog
+ isOpen={isLinkDialogOpen}
+ onOpenChange={handleLinkDialogOpenChange}
+ purpose="form"
+ width={400}>
+ <Stack as="form" onSubmit={handleLinkSubmit}>
+ <Layout
+ height="auto"
+ header={
+ <DialogHeader
+ title={isEditingLink ? 'Edit link' : 'Insert link'}
+ onOpenChange={handleLinkDialogOpenChange}
+ />
+ }
+ content={
+ <LayoutContent>
+ <TextInput
+ label="URL"
+ value={linkUrl}
+ width="100%"
+ hasAutoFocus
+ status={
+ linkError
+ ? {type: 'error', message: linkError}
+ : undefined
+ }
+ statusVariant="detached"
+ onChange={value => {
+ setLinkUrl(value);
+ setLinkError('');
+ }}
+ />
+ </LayoutContent>
+ }
+ footer={
+ <LayoutFooter>
+ <HStack gap={2} hAlign="end">
+ {isEditingLink && (
+ <Button
+ label="Remove link"
+ variant="destructive"
+ onClick={removeLink}
+ />
+ )}
+ <Button
+ label="Cancel"
+ variant="secondary"
+ onClick={() => handleLinkDialogOpenChange(false)}
+ />
+ <Button
+ label={isEditingLink ? 'Update link' : 'Add link'}
+ variant="primary"
+ type="submit"
+ />
+ </HStack>
+ </LayoutFooter>
+ }
+ />
+ </Stack>
+ </Dialog>
+ )}
+ </>
);
}
diff --git a/packages/lab/src/RichTextEditor/editorTheme.ts b/packages/lab/src/RichTextEditor/editorTheme.ts
index 6d85b43e2c..884188f254 100644
--- a/packages/lab/src/RichTextEditor/editorTheme.ts
+++ b/packages/lab/src/RichTextEditor/editorTheme.ts
@@ -4,7 +4,8 @@
* @file editorTheme.ts
* @input Uses StyleX + Astryx design tokens
* @output Exports sharedEditorTheme(), which builds a Lexical EditorThemeClasses
- * object mapping Lexical's theme slots to StyleX-generated class names.
+ * object mapping Lexical's theme slots to StyleX-generated class names and
+ * normalizes paragraph spacing for editor/view alignment.
* @position Shared by RichTextEditor.tsx and RichTextView.tsx so editor and
* read-only view render identically.
*
@@ -24,7 +25,11 @@ import type {EditorThemeClasses} from 'lexical';
const editorTheme = stylex.create({
paragraph: {
- marginBlock: spacingVars['--spacing-1'],
+ // A leading margin collapses through Lexical's wrapper and stacks with the
+ // input inset. Keep the same between-paragraph rhythm on the end edge so
+ // the first line aligns with TextArea and the empty-editor placeholder.
+ marginBlockStart: spacingVars['--spacing-0'],
+ marginBlockEnd: spacingVars['--spacing-1'],
},
h1: {
fontFamily: typographyVars['--font-family-heading'],