An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): add composable RichTextEditorToolbar (#4551)
Sherrye424a04e2a55
diff --git a/.changeset/richtext-toolbar-themeable-icons.md b/.changeset/richtext-toolbar-themeable-icons.mdnew file mode 100644index 0000000000..273a74eb9a--- /dev/null+++ b/.changeset/richtext-toolbar-themeable-icons.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] Icon registry: `registerIcons()` now accepts arbitrary extension keys (not just built-in `IconName`s), so libraries can augment the icon map with their own keys. Add `getExtendedIcon(name, fallback)` — resolves an extension key, preferring a theme-registered icon over a caller-supplied default. This lets library-shipped icons (e.g. the lab `RichTextEditorToolbar`'s `richtext:*` glyphs) be overridden per-theme without forking.+@potatowagondiff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.jsonindex e28e768905..84e9c710ad 100644--- a/.github/a11y-baseline.json+++ b/.github/a11y-baseline.json@@ -863,6 +863,11 @@"impact": "serious","helpUrl": "https://dequeuniversity.com/rules/axe/4.12/aria-input-field-name?application=playwright"},+ {+ "key": "RichTextEditor::With Toolbar::aria-input-field-name",+ "impact": "serious",+ "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/aria-input-field-name?application=playwright"+ },{"key": "Schedule::Async Loader::color-contrast","impact": "serious",diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex 11487e8639..9d65dca39b 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -7,6 +7,7 @@ import {RichTextView,markdownToEditorStateJSON,editorStateJSONToMarkdown,+ RichTextEditorToolbar,type RichTextEditorRef,} from '@astryxdesign/lab';import type {EditorState} from 'lexical';@@ -43,6 +44,14 @@ export const Default: Story = {},};+export const WithToolbar: Story = {+ args: {+ label: 'Notes',+ placeholder: 'Format with the toolbar above…',+ plugins: <RichTextEditorToolbar />,+ },+};+export const WithDescription: Story = {args: {label: 'Release notes',diff --git a/packages/build/src/config.js b/packages/build/src/config.jsindex 16ab250849..e47e2ecf8b 100644--- a/packages/build/src/config.js+++ b/packages/build/src/config.js@@ -58,7 +58,19 @@ function stylexOptions(rootDir, overrides = {}) {*/function babel(rootDir, overrides = {}) {return {- presets: ['next/babel'],+ presets: [+ // Enable `allowDeclareFields` on the TypeScript preset. Next's+ // `next/babel` preset does not set this by default, so any raw `.ts`+ // that uses `declare` class fields (a TS 3.7+ construct) fails to+ // compile. Astryx source builds resolve dependencies via the `source`+ // export condition, so a `source`-shipping dependency imported from an+ // Astryx package (e.g. `lexical`/`@lexical/*`, pulled in by the lab+ // RichTextEditor) is fed its untranspiled `.ts` — including+ // `declare ['constructor']: …` fields — straight to Babel. Accepting+ // `declare` fields is correct TS semantics (they are type-only and+ // dropped from output) and is safe for all files, not just lexical.+ ['next/babel', {'preset-typescript': {allowDeclareFields: true}}],+ ],plugins: [[require.resolve('./babel.js'), stylexOptions(rootDir, overrides)],],diff --git a/packages/core/src/Icon/Icon.doc.mjs b/packages/core/src/Icon/Icon.doc.mjsindex e8d508e249..8e798bdf7f 100644--- a/packages/core/src/Icon/Icon.doc.mjs+++ b/packages/core/src/Icon/Icon.doc.mjs@@ -55,6 +55,7 @@ export const docs = {description: 'Icons are small visual symbols that represent actions, objects, or concepts. They improve scannability and reinforce meaning alongside text. Supports both direct SVG components and semantic icon names that adapt to the active theme.',bestPractices: [{ guidance: true, description: 'Use semantic icon names when available; they adapt to theme changes automatically.' },+ { guidance: true, description: "Libraries can augment the icon map with their own keys: registerIcons({'richtext:bold': <MyIcon />}) accepts arbitrary extension keys (not just the built-in IconName set). Resolve them with getExtendedIcon(key, fallback), which prefers a theme-registered icon and falls back to a bundled default — the seam that makes library-shipped icons theme-overridable." },{ guidance: true, description: 'Pair icons with text labels for accessibility; icon-only elements need an accessible label.' },{ guidance: true, description: 'For a meaningful standalone icon (no adjacent text), give it an accessible name via the `label` prop: it sets role="img" + aria-label and unhides the icon.' },{ guidance: true, description: 'Use color tokens for icon colors, not hardcoded hex values.' },diff --git a/packages/core/src/Icon/globalIconRegistry.test.tsx b/packages/core/src/Icon/globalIconRegistry.test.tsxindex c51ba59ac2..84f5d7bc21 100644--- a/packages/core/src/Icon/globalIconRegistry.test.tsx+++ b/packages/core/src/Icon/globalIconRegistry.test.tsx@@ -9,6 +9,7 @@ import {registerIcons,getIconRegistry,getIcon,+ getExtendedIcon,resetIcons,} from './globalIconRegistry';@@ -123,4 +124,38 @@ describe('iconRegistry (global, RSC-compatible)', () => {// Should fall back to defaultexpect(getIcon('close')).not.toBe('custom');});++ describe('extension keys', () => {+ it('registers and resolves library-contributed keys', () => {+ registerIcons({'richtext:bold': 'my-bold'});+ expect(getIcon('richtext:bold')).toBe('my-bold');+ expect(getExtendedIcon('richtext:bold')).toBe('my-bold');+ });++ it('getExtendedIcon returns the caller fallback when unregistered', () => {+ expect(getExtendedIcon('richtext:bold', 'inline-svg')).toBe('inline-svg');+ });++ it('getExtendedIcon prefers a registered icon over the fallback', () => {+ registerIcons({'richtext:bold': 'theme-bold'});+ expect(getExtendedIcon('richtext:bold', 'inline-svg')).toBe('theme-bold');+ });++ it('getExtendedIcon still resolves built-in defaults', () => {+ expect(getExtendedIcon('close', 'fallback')).toBe(defaultIcons.close);+ });++ it('extension keys do not leak into the built-in registry snapshot', () => {+ registerIcons({'richtext:bold': 'my-bold'});+ // getIconRegistry() is the built-in IconName snapshot; extension keys+ // are resolved via getIcon/getExtendedIcon, not surfaced here.+ expect(Object.keys(getIconRegistry())).toEqual(Object.keys(defaultIcons));+ });++ it('extension keys are cleared by resetIcons', () => {+ registerIcons({'richtext:bold': 'my-bold'});+ resetIcons();+ expect(getExtendedIcon('richtext:bold', 'fallback')).toBe('fallback');+ });+ });});diff --git a/packages/core/src/Icon/globalIconRegistry.tsx b/packages/core/src/Icon/globalIconRegistry.tsxindex 7a59ede6d4..03dfe86d98 100644--- a/packages/core/src/Icon/globalIconRegistry.tsx+++ b/packages/core/src/Icon/globalIconRegistry.tsx@@ -55,6 +55,17 @@ export type IconName =| 'stop'| 'microphone';+/**+ * A semantic icon name — either one of the built-in {@link IconName}s or an+ * arbitrary string key contributed by a library/app.+ *+ * The `(string & {})` intersection keeps the built-in names available for+ * autocomplete while still allowing any string, so downstream libraries can+ * register and resolve their own keys (e.g. `'richtext:bold'`) without having+ * to widen the core `IconName` union.+ */+export type ExtendedIconName = IconName | (string & {});+/*** Icon registry mapping semantic names to React nodes.*/@@ -66,7 +77,7 @@ export type IconRegistrySource = DefinedTheme | string | null | undefined;// Global Registry// =============================================================================-let globalRegistry: Partial<IconRegistry> = {};+let globalRegistry: Record<string, ReactNode> = {};function getThemeIconOverrides(source: IconRegistrySource,@@ -95,8 +106,19 @@ function getThemeIconOverrides(* import { brandIcons } from './brand-icons';* registerIcons(brandIcons);* ```+ *+ * Libraries may also register their own extension keys (any string), so a+ * theme can override them the same way it overrides built-in icons:+ * @example+ * ```+ * // In a library that ships its own icons:+ * registerIcons({ 'richtext:bold': <MyBoldIcon /> });+ * // resolve with getIcon('richtext:bold')+ * ```*/-export function registerIcons(icons: Partial<IconRegistry>): void {+export function registerIcons(+ icons: Partial<Record<ExtendedIconName, ReactNode>>,+): void {warnOnce('icon-registry:global-register-icons','Icon',@@ -118,7 +140,10 @@ export function getIconRegistry(): Readonly<IconRegistry> {const registry = {...defaultIcons};- for (const name of Object.keys(globalRegistry) as IconName[]) {+ // Only surface built-in IconName keys here — extension keys registered by+ // libraries are resolved via getIcon/getExtendedIcon and intentionally kept+ // out of the typed IconRegistry snapshot.+ for (const name of Object.keys(defaultIcons) as IconName[]) {registry[name] = globalRegistry[name] ?? defaultIcons[name];}@@ -137,13 +162,51 @@ export function getIconRegistry(** Works in both server and client environments.* Falls back to built-in default icons when no override is registered.+ *+ * Accepts extension keys (any string) in addition to the built-in+ * {@link IconName}s — useful for library-contributed icons. For a+ * caller-supplied fallback when a key isn't registered, use+ * {@link getExtendedIcon}.*/export function getIcon(- name: IconName,+ name: ExtendedIconName,source?: IconRegistrySource,): ReactNode {const themeIcons = getThemeIconOverrides(source);- return themeIcons?.[name] ?? globalRegistry[name] ?? defaultIcons[name];+ return (+ themeIcons?.[name as IconName] ??+ globalRegistry[name] ??+ defaultIcons[name as IconName]+ );+}++/**+ * Resolve an extension icon by an arbitrary string key, falling back to a+ * caller-supplied default when nothing is registered.+ *+ * This is the seam libraries use to make their own icons themeable: ship the+ * inline SVG as `fallback`, resolve through this function, and a theme can+ * override the key via {@link registerIcons} without the library having to+ * widen the core {@link IconName} union.+ *+ * @example+ * ```+ * // Library default, overridable by a theme registering 'richtext:bold':+ * getExtendedIcon('richtext:bold', <BoldGlyph />)+ * ```+ */+export function getExtendedIcon(+ name: ExtendedIconName,+ fallback?: ReactNode,+ source?: IconRegistrySource,+): ReactNode {+ const themeIcons = getThemeIconOverrides(source);+ return (+ themeIcons?.[name as IconName] ??+ globalRegistry[name] ??+ defaultIcons[name as IconName] ??+ fallback+ );}/**diff --git a/packages/core/src/Icon/index.ts b/packages/core/src/Icon/index.tsindex b09300d314..4dbff80266 100644--- a/packages/core/src/Icon/index.ts+++ b/packages/core/src/Icon/index.ts@@ -20,10 +20,12 @@ export {registerIcons,getIconRegistry,getIcon,+ getExtendedIcon,resetIcons,} from './globalIconRegistry';export type {IconName,+ ExtendedIconName,IconRegistry,IconRegistrySource,} from './globalIconRegistry';diff --git a/packages/lab/package.json b/packages/lab/package.jsonindex 32247462aa..522f5bf569 100644--- a/packages/lab/package.json+++ b/packages/lab/package.json@@ -69,6 +69,7 @@"@lexical/link": "^0.46.0","@lexical/list": "^0.46.0","@lexical/rich-text": "^0.46.0",+ "@lexical/selection": "^0.46.0","@lexical/code": "^0.46.0","@lexical/utils": "^0.46.0"},@@ -87,6 +88,7 @@"@lexical/markdown": "^0.46.0","@lexical/react": "^0.46.0","@lexical/rich-text": "^0.46.0",+ "@lexical/selection": "^0.46.0","@lexical/utils": "^0.46.0","@types/d3-array": "^3.2.2","@types/d3-scale": "^4.0.9",@@ -118,6 +120,9 @@"@lexical/rich-text": {"optional": true},+ "@lexical/selection": {+ "optional": true+ },"@lexical/code": {"optional": true},diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjsindex 547b2adb6c..5df1961b3b 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs+++ b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs@@ -160,6 +160,16 @@ export const docs = {description:'To produce a defaultValue from Markdown without mounting an editor (e.g. on the server), use markdownToEditorStateJSON(markdown). Convert the other way with editorStateJSONToMarkdown(json). Both run headless via @lexical/headless and accept the same transformers/nodes options as the editor.',},+ {+ 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, headings, quote, lists, and undo/redo. Compose extra controls via its endContent prop.',+ },+ {+ guidance: true,+ description:+ "The toolbar's glyphs are themeable. Each control resolves its icon from the core icon registry under a stable richtext:* key (see RICHTEXT_ICON_KEYS), falling back to a bundled inline SVG. A theme can restyle any glyph without forking the toolbar: registerIcons({'richtext:bold': <MyBoldIcon />}) from @astryxdesign/core/Icon. registerIcons now accepts arbitrary extension keys, and getExtendedIcon(key, fallback) resolves them — the same pattern any library can use to make its own icons theme-overridable.",+ },{guidance: false,description:diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsxindex 81045e8dc4..def7235ed8 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx@@ -16,24 +16,19 @@ import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';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 {TRANSFORMERS, $convertFromMarkdownString} from '@lexical/markdown';import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';import {RichTextView} from './RichTextView';import {markdownToEditorStateJSON,editorStateJSONToMarkdown,} from './markdownSerializers';+import {RichTextEditorToolbar} from './RichTextEditorToolbar';+import {registerIcons, resetIcons} from '@astryxdesign/core/Icon';// 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;-}) {+function CaptureEditor({onReady}: {onReady: (editor: LexicalEditor) => void}) {const [editor] = useLexicalComposerContext();useEffect(() => {onReady(editor);@@ -403,9 +398,7 @@ describe('RichTextEditor', () => {editorRef!.update(() => {$convertFromMarkdownString('# Title', TRANSFORMERS);});- await waitFor(() =>- expect(ref.current?.getMarkdown()).toBe('# Title'),- );+ await waitFor(() => expect(ref.current?.getMarkdown()).toBe('# Title'));});it('ref.getMarkdown() honors a custom transformers prop', async () => {@@ -532,11 +525,13 @@ describe('RichTextEditor', () => {it('renders a character counter reflecting the seeded content length', async () => {// HELLO_STATE is "Hello world" (11 chars).render(- <RichTextEditor label="Notes" defaultValue={HELLO_STATE} maxLength={100} />,- );- await waitFor(() =>- expect(screen.getByText('11/100')).toBeInTheDocument(),+ <RichTextEditor+ label="Notes"+ defaultValue={HELLO_STATE}+ maxLength={100}+ />,);+ await waitFor(() => expect(screen.getByText('11/100')).toBeInTheDocument());});it('shows an over-limit counter when content exceeds maxLength', async () => {@@ -551,7 +546,11 @@ describe('RichTextEditor', () => {it('associates the counter with the editor via aria-describedby', async () => {render(- <RichTextEditor label="Notes" defaultValue={HELLO_STATE} maxLength={100} />,+ <RichTextEditor+ label="Notes"+ defaultValue={HELLO_STATE}+ maxLength={100}+ />,);const counter = await screen.findByText('11/100');const describedBy = screen@@ -619,7 +618,9 @@ describe('RichTextView', () => {});it('renders bullet lists with a disc marker (not bare indentation)', async () => {- const {container} = render(<RichTextView value={makeListState('bullet')} />);+ const {container} = render(+ <RichTextView value={makeListState('bullet')} />,+ );await waitFor(() =>expect(screen.getByText('Item one')).toBeInTheDocument(),);@@ -633,7 +634,9 @@ describe('RichTextView', () => {});it('renders numbered lists with a decimal marker (not bare indentation)', async () => {- const {container} = render(<RichTextView value={makeListState('number')} />);+ const {container} = render(+ <RichTextView value={makeListState('number')} />,+ );await waitFor(() =>expect(screen.getByText('Item one')).toBeInTheDocument(),);@@ -704,3 +707,98 @@ describe('markdown serializers', () => {);});});++describe('RichTextEditorToolbar', () => {+ it('renders inside the editor plugins slot with formatting controls', () => {+ render(+ <RichTextEditor label="Notes" plugins={<RichTextEditorToolbar />} />,+ );+ // Toolbar landmark with its accessible label.+ expect(+ screen.getByRole('toolbar', {name: 'Text formatting'}),+ ).toBeInTheDocument();+ // A representative set of format buttons are present and labelled.+ for (const name of [+ 'Bold',+ 'Italic',+ 'Underline',+ 'Strikethrough',+ 'Inline code',+ 'Quote',+ 'Bulleted list',+ 'Numbered list',+ 'Undo',+ 'Redo',+ ]) {+ expect(screen.getByRole('button', {name})).toBeInTheDocument();+ }+ });++ it('renders one heading button per configured level', () => {+ render(+ <RichTextEditor+ label="Notes"+ plugins={<RichTextEditorToolbar headingLevels={['h1', 'h2']} />}+ />,+ );+ expect(screen.getByRole('button', {name: 'Heading 1'})).toBeInTheDocument();+ expect(screen.getByRole('button', {name: 'Heading 2'})).toBeInTheDocument();+ expect(+ screen.queryByRole('button', {name: 'Heading 3'}),+ ).not.toBeInTheDocument();+ });++ it('accepts a custom accessible label', () => {+ render(+ <RichTextEditor+ label="Notes"+ plugins={<RichTextEditorToolbar label="Editor controls" />}+ />,+ );+ expect(+ screen.getByRole('toolbar', {name: 'Editor controls'}),+ ).toBeInTheDocument();+ });++ it('renders composed endContent', () => {+ render(+ <RichTextEditor+ label="Notes"+ plugins={+ <RichTextEditorToolbar+ endContent={<button type="button">Custom</button>}+ />+ }+ />,+ );+ expect(screen.getByRole('button', {name: 'Custom'})).toBeInTheDocument();+ });++ it('disables formatting controls when the editor is read-only', () => {+ render(+ <RichTextEditor+ label="Notes"+ isReadOnly+ plugins={<RichTextEditorToolbar />}+ />,+ );+ expect(screen.getByRole('button', {name: 'Bold'})).toBeDisabled();+ });++ it('renders a theme-registered icon override for a richtext:* key', () => {+ registerIcons({+ 'richtext:bold': <span data-testid="themed-bold">B!</span>,+ });+ try {+ render(+ <RichTextEditor label="Notes" plugins={<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'));+ } finally {+ resetIcons();+ }+ });+});diff --git a/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx b/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsxnew file mode 100644index 0000000000..1002d5387e--- /dev/null+++ b/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx@@ -0,0 +1,594 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @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.+ *+ * SYNC: When modified, update:+ * - /packages/lab/src/RichTextEditor/index.ts (exports)+ * - /packages/lab/src/index.ts (barrel re-export)+ * - /packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs (usage notes)+ * - /packages/lab/src/RichTextEditor/RichTextEditor.test.tsx (tests)+ * - /apps/storybook/stories/RichTextEditor.stories.tsx (WithToolbar story)+ *+ * NOTE: Experimental `@astryxdesign/lab` component (canary). `lexical` and+ * `@lexical/*` are OPTIONAL peer dependencies — install them to use this.+ * Behavior mirrors the Lexical playground toolbar (selection sync + format+ * commands); the UI is built from Astryx primitives so it matches the theme.+ *+ * ICONS: Each control resolves its glyph through the core icon registry under a+ * stable `richtext:*` key (see {@link RICHTEXT_ICON_KEYS}), falling back to the+ * bundled inline SVGs below. A theme can restyle any glyph by registering its+ * own icon for that key — no need to fork the toolbar:+ * import {registerIcons} from '@astryxdesign/core/Icon';+ * registerIcons({'richtext:bold': <MyBoldIcon />});+ */++import {useCallback, useEffect, useState, type ReactNode} from 'react';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';+import {$setBlocksType} from '@lexical/selection';+import {+ $createHeadingNode,+ $createQuoteNode,+ $isHeadingNode,+ $isQuoteNode,+ type HeadingTagType,+} from '@lexical/rich-text';+import {+ $isListNode,+ ListNode,+ INSERT_ORDERED_LIST_COMMAND,+ INSERT_UNORDERED_LIST_COMMAND,+ REMOVE_LIST_COMMAND,+} from '@lexical/list';+import {$getNearestNodeOfType, mergeRegister} from '@lexical/utils';+import {Toolbar} from '@astryxdesign/core/Toolbar';+import {ToggleButton} from '@astryxdesign/core/ToggleButton';+import {Divider} from '@astryxdesign/core/Divider';+import {getExtendedIcon} from '@astryxdesign/core/Icon';+import {+ FORMAT_TEXT_COMMAND,+ UNDO_COMMAND,+ REDO_COMMAND,+ CAN_UNDO_COMMAND,+ CAN_REDO_COMMAND,+ SELECTION_CHANGE_COMMAND,+ COMMAND_PRIORITY_CRITICAL,+ $getSelection,+ $isRangeSelection,+ $createParagraphNode,+} from 'lexical';++/** Block types the toolbar can toggle. */+type BlockType =+ 'paragraph' | 'h1' | 'h2' | 'h3' | 'quote' | 'bullet' | 'number';++const HEADING_LABELS: Record<'h1' | 'h2' | 'h3', string> = {+ h1: 'Heading 1',+ h2: 'Heading 2',+ h3: 'Heading 3',+};++/**+ * Stable icon-registry keys for the toolbar's controls. Themes can override any+ * of these via `registerIcons({'richtext:bold': <MyIcon />})` from+ * `@astryxdesign/core/Icon`. Keys are namespaced (`richtext:*`) to avoid+ * collisions with the core semantic icon set.+ */+export const RICHTEXT_ICON_KEYS = {+ bold: 'richtext:bold',+ italic: 'richtext:italic',+ underline: 'richtext:underline',+ strikethrough: 'richtext:strikethrough',+ code: 'richtext:code',+ h1: 'richtext:h1',+ h2: 'richtext:h2',+ h3: 'richtext:h3',+ quote: 'richtext:quote',+ bullet: 'richtext:bullet',+ number: 'richtext:number',+ undo: 'richtext:undo',+ redo: 'richtext:redo',+} as const;++/**+ * Bundled 16px inline default icons — no external icon dependency. These are+ * the fallbacks used when a theme hasn't registered an override for the+ * corresponding {@link RICHTEXT_ICON_KEYS} entry.+ */+const defaultToolbarIcons: Record<string, ReactNode> = {+ bold: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6z"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinejoin="round"+ />+ </svg>+ ),+ italic: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M10 4h6M8 20h6M14 4l-4 16"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ </svg>+ ),+ underline: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M6 4v6a6 6 0 0 0 12 0V4M5 21h14"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ </svg>+ ),+ strikethrough: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M4 12h16M8 6a4 3 0 0 1 8 0M8 16a4 3 0 0 0 8 0"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ </svg>+ ),+ code: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M9 8l-4 4 4 4M15 8l4 4-4 4"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ ),+ h1: <TextGlyph label="H1" />,+ h2: <TextGlyph label="H2" />,+ h3: <TextGlyph label="H3" />,+ quote: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M6 17h3l2-4V7H5v6h3zM15 17h3l2-4V7h-6v6h3z"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinejoin="round"+ />+ </svg>+ ),+ bullet: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M9 6h11M9 12h11M9 18h11"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ <circle cx="4.5" cy="6" r="1.5" fill="currentColor" />+ <circle cx="4.5" cy="12" r="1.5" fill="currentColor" />+ <circle cx="4.5" cy="18" r="1.5" fill="currentColor" />+ </svg>+ ),+ number: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M10 6h10M10 12h10M10 18h10"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ <text x="2" y="8" fontSize="6" fill="currentColor">+ 1+ </text>+ <text x="2" y="14" fontSize="6" fill="currentColor">+ 2+ </text>+ <text x="2" y="20" fontSize="6" fill="currentColor">+ 3+ </text>+ </svg>+ ),+ undo: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M9 7L4 12l5 5M4 12h11a5 5 0 0 1 0 10"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ ),+ redo: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ ),+};++/** Renders a short text label as a toolbar glyph (for heading buttons). */+function TextGlyph({label}: {label: string}) {+ return (+ <span+ aria-hidden="true"+ style={{+ fontSize: '0.75rem',+ fontWeight: 700,+ fontVariantNumeric: 'tabular-nums',+ }}>+ {label}+ </span>+ );+}++/**+ * Resolve a toolbar glyph: prefer a theme-registered icon for the stable+ * `richtext:*` key, otherwise fall back to the bundled inline default.+ */+function resolveIcon(name: keyof typeof RICHTEXT_ICON_KEYS): ReactNode {+ return getExtendedIcon(RICHTEXT_ICON_KEYS[name], defaultToolbarIcons[name]);+}++export interface RichTextEditorToolbarProps {+ /**+ * Accessible label for the toolbar element.+ * @default 'Text formatting'+ */+ label?: string;+ /**+ * Which heading levels to expose as block-type buttons, in order.+ * @default ['h1', 'h2', 'h3']+ */+ headingLevels?: ReadonlyArray<'h1' | 'h2' | 'h3'>;+ /** Toolbar size, forwarded to the Astryx Toolbar. @default 'sm' */+ size?: 'sm' | 'md' | 'lg';+ /**+ * Extra items rendered at the end of the toolbar (after a divider). Use this+ * to compose product-specific controls (e.g. mentions, AI) alongside the+ * default formatting buttons.+ */+ endContent?: ReactNode;+}++/**+ * A composable formatting toolbar for {@link RichTextEditor}, built from Astryx+ * `Toolbar` / `ToggleButton` primitives so it matches the active theme. Reads+ * 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+ * `useLexicalComposerContext()` to reach the editor, so it must live within the+ * `LexicalComposer` the editor sets up.+ *+ * @example+ * ```+ * import {RichTextEditor, RichTextEditorToolbar} from '@astryxdesign/lab';+ *+ * <RichTextEditor+ * label="Notes"+ * plugins={<RichTextEditorToolbar />}+ * />+ * ```+ */+export function RichTextEditorToolbar({+ label = 'Text formatting',+ headingLevels = ['h1', 'h2', 'h3'],+ size = 'sm',+ endContent,+}: RichTextEditorToolbarProps) {+ const [editor] = useLexicalComposerContext();+ const [activeFormats, setActiveFormats] = useState<Set<string>>(new Set());+ const [blockType, setBlockType] = useState<BlockType>('paragraph');+ const [canUndo, setCanUndo] = useState(false);+ const [canRedo, setCanRedo] = useState(false);+ const [isEditable, setIsEditable] = useState(() => editor.isEditable());++ const $syncToolbar = useCallback(() => {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) {+ return;+ }+ const formats = new Set<string>();+ for (const fmt of [+ 'bold',+ 'italic',+ 'underline',+ 'strikethrough',+ 'code',+ ] as const) {+ if (selection.hasFormat(fmt)) {+ formats.add(fmt);+ }+ }+ setActiveFormats(formats);++ const anchorNode = selection.anchor.getNode();+ const element =+ anchorNode.getKey() === 'root'+ ? anchorNode+ : anchorNode.getTopLevelElementOrThrow();+ if ($isListNode(element)) {+ const parentList = $getNearestNodeOfType<ListNode>(anchorNode, ListNode);+ const type = parentList+ ? parentList.getListType()+ : element.getListType();+ setBlockType(type === 'number' ? 'number' : 'bullet');+ } else if ($isHeadingNode(element)) {+ setBlockType(element.getTag() as BlockType);+ } else if ($isQuoteNode(element)) {+ setBlockType('quote');+ } else {+ setBlockType('paragraph');+ }+ }, []);++ useEffect(() => {+ return mergeRegister(+ editor.registerUpdateListener(({editorState}) => {+ editorState.read($syncToolbar);+ }),+ editor.registerCommand(+ SELECTION_CHANGE_COMMAND,+ () => {+ $syncToolbar();+ return false;+ },+ COMMAND_PRIORITY_CRITICAL,+ ),+ editor.registerCommand(+ CAN_UNDO_COMMAND,+ payload => {+ setCanUndo(payload);+ return false;+ },+ COMMAND_PRIORITY_CRITICAL,+ ),+ editor.registerCommand(+ CAN_REDO_COMMAND,+ payload => {+ setCanRedo(payload);+ return false;+ },+ COMMAND_PRIORITY_CRITICAL,+ ),+ editor.registerEditableListener(editable => {+ setIsEditable(editable);+ }),+ );+ }, [editor, $syncToolbar]);++ const toggleInlineFormat = (format: string) => {+ // FORMAT_TEXT_COMMAND payload is a TextFormatType; the values we pass are+ // all valid members.+ editor.dispatchCommand(+ FORMAT_TEXT_COMMAND,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ format as any,+ );+ };++ const setBlock = (next: BlockType) => {+ if (next === 'bullet') {+ editor.dispatchCommand(+ blockType === 'bullet'+ ? REMOVE_LIST_COMMAND+ : INSERT_UNORDERED_LIST_COMMAND,+ undefined,+ );+ return;+ }+ if (next === 'number') {+ editor.dispatchCommand(+ blockType === 'number'+ ? REMOVE_LIST_COMMAND+ : 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') {+ return $createQuoteNode();+ }+ if (target === 'h1' || target === 'h2' || target === 'h3') {+ return $createHeadingNode(target as HeadingTagType);+ }+ return $createParagraphNode();+ });+ });+ };++ 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')}+ />+ <Divider orientation="vertical" />+ {headingLevels.map(level => (+ <ToggleButton+ key={level}+ label={HEADING_LABELS[level]}+ icon={resolveIcon(level)}+ isIconOnly+ isPressed={blockType === level}+ isDisabled={!isEditable}+ onPressedChange={() => setBlock(level)}+ />+ ))}+ <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}+ </>+ )}+ </>+ }+ />+ );+}++RichTextEditorToolbar.displayName = 'RichTextEditorToolbar';diff --git a/packages/lab/src/RichTextEditor/index.ts b/packages/lab/src/RichTextEditor/index.tsindex 87fac513d6..08487f56d8 100644--- a/packages/lab/src/RichTextEditor/index.ts+++ b/packages/lab/src/RichTextEditor/index.ts@@ -32,3 +32,9 @@ export {editorStateJSONToMarkdown,} from './markdownSerializers';export type {MarkdownSerializerOptions} from './markdownSerializers';++export {+ RichTextEditorToolbar,+ RICHTEXT_ICON_KEYS,+} from './RichTextEditorToolbar';+export type {RichTextEditorToolbarProps} from './RichTextEditorToolbar';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex afe37523c1..16a676adbd 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -249,4 +249,7 @@ export {markdownToEditorStateJSON,editorStateJSONToMarkdown,type MarkdownSerializerOptions,+ RichTextEditorToolbar,+ type RichTextEditorToolbarProps,+ RICHTEXT_ICON_KEYS,} from './RichTextEditor';diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2d55c3e9d3..92eac75f3b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -716,6 +716,9 @@ importers:'@lexical/rich-text':specifier: ^0.46.0version: 0.46.0([email protected])+ '@lexical/selection':+ specifier: ^0.46.0+ version: 0.46.0([email protected])'@lexical/utils':specifier: ^0.46.0version: 0.46.0([email protected])