An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): add link support to RichTextEditor (#4670)
Sherry0d8d5ba507e6
diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex 9d65dca39b..1a46309526 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -8,6 +8,7 @@ import {markdownToEditorStateJSON,editorStateJSONToMarkdown,RichTextEditorToolbar,+ RichTextEditorAutoLinkPlugin,type RichTextEditorRef,} from '@astryxdesign/lab';import type {EditorState} from 'lexical';@@ -52,6 +53,31 @@ export const WithToolbar: Story = {},};+export const WithLinks: Story = {+ args: {+ label: 'Notes',+ placeholder:+ '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 />,+ },+};++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 />+ </>+ ),+ },+};+export const WithDescription: Story = {args: {label: 'Release notes',@@ -72,7 +98,8 @@ export const WithCharacterLimit: Story = {args: {label: 'Bio',maxLength: 80,- description: 'A character counter appears below the editor when maxLength is set.',+ description:+ 'A character counter appears below the editor when maxLength is set.',placeholder: 'Type past 80 characters to see the counter turn red…',},};@@ -190,7 +217,9 @@ export const ImperativeRef = {onClick={() => {const state = ref.current?.getEditorState();const text = state?.read(() => $getRoot().getTextContent());- setReadout(`getEditorState() text content: ${JSON.stringify(text)}`);+ setReadout(+ `getEditorState() text content: ${JSON.stringify(text)}`,+ );}}>getEditorState()</button>@@ -282,7 +311,7 @@ export const MarkdownSerializers = {</div><textareavalue={markdown}- onChange={(e) => setMarkdown(e.target.value)}+ onChange={e => setMarkdown(e.target.value)}rows={10}style={{width: '100%',diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjsindex 5df1961b3b..7593e67290 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs+++ b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs@@ -163,7 +163,17 @@ 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, headings, quote, lists, and undo/redo. Compose extra controls via its endContent prop.',+ '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.',+ },+ {+ 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.',+ },+ {+ guidance: true,+ description:+ 'Auto-linking: render RichTextEditorAutoLinkPlugin in the plugins slot to turn typed/pasted URLs and emails into links automatically. Created links open in a new tab by default (target=_blank, rel=noopener noreferrer, baked into the node). Pass matchers to recognize additional patterns (build them with createLinkMatcherWithRegExp).',},{guidance: true,diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsxindex def7235ed8..bbaa948cd4 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx@@ -10,11 +10,16 @@*/import {describe, it, expect, vi} from 'vitest';-import {render, screen, waitFor} from '@testing-library/react';+import {render, screen, waitFor, fireEvent} from '@testing-library/react';import {createRef, useEffect} from 'react';import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';import type {EditorState, LexicalEditor} from 'lexical';-import {$getRoot, $createParagraphNode, $createTextNode} from 'lexical';+import {+ $getRoot,+ $createParagraphNode,+ $createTextNode,+ $isElementNode,+} from 'lexical';import {HeadingNode} from '@lexical/rich-text';import {TRANSFORMERS, $convertFromMarkdownString} from '@lexical/markdown';import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';@@ -25,6 +30,12 @@ import {} from './markdownSerializers';import {RichTextEditorToolbar} from './RichTextEditorToolbar';import {registerIcons, resetIcons} from '@astryxdesign/core/Icon';+import {+ RichTextEditorAutoLinkPlugin,+ DEFAULT_LINK_MATCHERS,+ NEW_TAB_LINK_ATTRIBUTES,+} from './RichTextEditorAutoLinkPlugin';+import {sanitizeUrl, validateUrl} from './linkUtils';// Small plugin that captures the editor instance so tests can drive real// Lexical updates (jsdom does not implement contenteditable editing).@@ -802,3 +813,367 @@ describe('RichTextEditorToolbar', () => {}});});++describe('linkUtils', () => {+ describe('sanitizeUrl', () => {+ it('passes through http/https URLs', () => {+ expect(sanitizeUrl('https://example.com')).toBe('https://example.com/');+ expect(sanitizeUrl('http://example.com/x')).toBe('http://example.com/x');+ });++ it('defaults a scheme-less host to https', () => {+ expect(sanitizeUrl('example.com')).toBe('https://example.com/');+ });++ it('preserves mailto and tel schemes', () => {+ expect(sanitizeUrl('mailto:[email protected]')).toBe('mailto:[email protected]');+ expect(sanitizeUrl('tel:+15551234')).toBe('tel:+15551234');+ });++ it('rejects javascript: and other unsafe schemes as about:blank', () => {+ expect(sanitizeUrl('javascript:alert(1)')).toBe('about:blank');+ expect(sanitizeUrl('data:text/html,<script>')).toBe('about:blank');+ expect(sanitizeUrl('vbscript:msgbox')).toBe('about:blank');+ });++ it('rejects empty/whitespace input as about:blank', () => {+ expect(sanitizeUrl('')).toBe('about:blank');+ expect(sanitizeUrl(' ')).toBe('about:blank');+ });+ });++ describe('validateUrl', () => {+ it('accepts safe URLs (with or without scheme)', () => {+ expect(validateUrl('https://example.com')).toBe(true);+ expect(validateUrl('example.com')).toBe(true);+ expect(validateUrl('mailto:[email protected]')).toBe(true);+ });++ it('rejects unsafe schemes and empty input', () => {+ expect(validateUrl('javascript:alert(1)')).toBe(false);+ expect(validateUrl('')).toBe(false);+ });+ });+});++describe('RichTextEditorToolbar — links', () => {+ it('renders a Link button by default', () => {+ render(+ <RichTextEditor label="Notes" plugins={<RichTextEditorToolbar />} />,+ );+ expect(screen.getByRole('button', {name: 'Link'})).toBeInTheDocument();+ });++ it('omits the Link button when hasLink is false', () => {+ render(+ <RichTextEditor+ label="Notes"+ plugins={<RichTextEditorToolbar hasLink={false} />}+ />,+ );+ expect(+ screen.queryByRole('button', {name: 'Link'}),+ ).not.toBeInTheDocument();+ });++ it('opens link insertion on Cmd/Ctrl+K but ignores Cmd/Ctrl+Shift+K', async () => {+ const promptForUrl = vi.fn(() => null);+ render(+ <RichTextEditor+ label="Notes"+ plugins={<RichTextEditorToolbar promptForUrl={promptForUrl} />}+ />,+ );+ const textbox = screen.getByRole('textbox');++ // Cmd+K (mac) / Ctrl+K (others) — matches isExactShortcutMatch, so the+ // link flow runs and asks for a URL. Fire both modifier variants so the+ // test is platform-agnostic.+ fireEvent.keyDown(textbox, {key: 'k', metaKey: true});+ fireEvent.keyDown(textbox, {key: 'k', ctrlKey: true});+ expect(promptForUrl).toHaveBeenCalled();++ // Adding Shift must NOT trigger it (exact-match semantics, matching the+ // Lexical playground).+ promptForUrl.mockClear();+ fireEvent.keyDown(textbox, {key: 'k', metaKey: true, shiftKey: true});+ fireEvent.keyDown(textbox, {key: 'k', ctrlKey: true, shiftKey: true});+ expect(promptForUrl).not.toHaveBeenCalled();+ });++ it('creates a sanitized link over the selected text via promptForUrl', async () => {+ let editor!: LexicalEditor;+ const promptForUrl = vi.fn(() => 'example.com');+ render(+ <RichTextEditor+ label="Notes"+ plugins={+ <>+ <RichTextEditorToolbar promptForUrl={promptForUrl} />+ <CaptureEditor onReady={e => (editor = e)} />+ </>+ }+ />,+ );+ await waitFor(() => expect(editor).toBeDefined());++ // Seed "hello" and select all of it so the toggle wraps a real range.+ // Seed + select in a single update so the RangeSelection is live when the+ // toolbar reads it.+ editor.update(() => {+ const root = $getRoot();+ root.clear();+ const paragraph = $createParagraphNode();+ const textNode = $createTextNode('hello');+ paragraph.append(textNode);+ root.append(paragraph);+ textNode.select(0, 5);+ });++ fireEvent.click(screen.getByRole('button', {name: 'Link'}));++ expect(promptForUrl).toHaveBeenCalled();+ // The selection text is passed to the prompt (empty string is acceptable+ // if jsdom drops the range; the important contract is the sanitized href).+ // The link node exists with the sanitized (https, scheme-added) href.+ await waitFor(() => {+ let href: string | null = null;+ editor.getEditorState().read(() => {+ const root = $getRoot();+ const paragraph = root.getFirstChild();+ // Find the first LinkNode-like descendant (has getURL()).+ const descendants = $isElementNode(paragraph)+ ? paragraph.getChildren()+ : [];+ for (const child of descendants) {+ if ('getURL' in child) {+ href = (child as {getURL(): string}).getURL();+ break;+ }+ }+ });+ expect(href).toBe('https://example.com/');+ });+ });++ it('does not create a link when promptForUrl returns an unsafe scheme', async () => {+ let editor!: LexicalEditor;+ const promptForUrl = vi.fn(() => 'javascript:alert(1)');+ render(+ <RichTextEditor+ label="Notes"+ plugins={+ <>+ <RichTextEditorToolbar promptForUrl={promptForUrl} />+ <CaptureEditor onReady={e => (editor = e)} />+ </>+ }+ />,+ );+ await waitFor(() => expect(editor).toBeDefined());+ editor.update(() => {+ const root = $getRoot();+ root.clear();+ const paragraph = $createParagraphNode();+ const textNode = $createTextNode('hello');+ paragraph.append(textNode);+ root.append(paragraph);+ textNode.select(0, 5);+ });++ fireEvent.click(screen.getByRole('button', {name: 'Link'}));+ expect(promptForUrl).toHaveBeenCalled();++ // No link node was created — no descendant exposes getURL().+ let hasLinkNode = false;+ editor.getEditorState().read(() => {+ const root = $getRoot();+ const paragraph = root.getFirstChild();+ const descendants = $isElementNode(paragraph)+ ? paragraph.getChildren()+ : [];+ for (const child of descendants) {+ if ('getURL' in child) {+ hasLinkNode = true;+ }+ }+ });+ expect(hasLinkNode).toBe(false);+ });+});++describe('RichTextEditorAutoLinkPlugin', () => {+ it('renders without crashing inside the editor', () => {+ render(+ <RichTextEditor+ label="Notes"+ plugins={<RichTextEditorAutoLinkPlugin />}+ />,+ );+ expect(screen.getByRole('textbox')).toBeInTheDocument();+ });++ it('exposes URL + email default matchers that open in a new tab', () => {+ expect(DEFAULT_LINK_MATCHERS).toHaveLength(2);+ const urlMatch = DEFAULT_LINK_MATCHERS[0]('see https://example.com now');+ expect(urlMatch).not.toBeNull();+ expect(urlMatch?.url).toBe('https://example.com/');+ expect(urlMatch?.attributes).toEqual(NEW_TAB_LINK_ATTRIBUTES);++ const emailMatch = DEFAULT_LINK_MATCHERS[1]('ping [email protected] please');+ expect(emailMatch).not.toBeNull();+ expect(emailMatch?.url).toBe('mailto:[email protected]');+ expect(emailMatch?.attributes).toEqual(NEW_TAB_LINK_ATTRIBUTES);+ });++ it('auto-links a typed URL as an AutoLinkNode', async () => {+ let editor!: LexicalEditor;+ render(+ <RichTextEditor+ label="Notes"+ plugins={+ <>+ <RichTextEditorAutoLinkPlugin />+ <CaptureEditor onReady={e => (editor = e)} />+ </>+ }+ />,+ );+ await waitFor(() => expect(editor).toBeDefined());++ // A URL followed by a separator triggers the AutoLink transform.+ editor.update(() => {+ const root = $getRoot();+ root.clear();+ const paragraph = $createParagraphNode();+ paragraph.append($createTextNode('visit https://example.com '));+ root.append(paragraph);+ });++ await waitFor(() => {+ let hasAutoLink = false;+ editor.getEditorState().read(() => {+ const root = $getRoot();+ const paragraph = root.getFirstChild();+ const children = $isElementNode(paragraph)+ ? paragraph.getChildren()+ : [];+ children.forEach(child => {+ if (child.getType() === 'autolink') {+ hasAutoLink = true;+ }+ });+ });+ expect(hasAutoLink).toBe(true);+ });+ });+});++describe('RichTextEditorToolbar — new-tab links', () => {+ it('bakes target=_blank + rel into the created link node by default', async () => {+ let editor!: LexicalEditor;+ const promptForUrl = vi.fn(() => 'example.com');+ render(+ <RichTextEditor+ label="Notes"+ plugins={+ <>+ <RichTextEditorToolbar promptForUrl={promptForUrl} />+ <CaptureEditor onReady={e => (editor = e)} />+ </>+ }+ />,+ );+ await waitFor(() => expect(editor).toBeDefined());+ editor.update(() => {+ const root = $getRoot();+ root.clear();+ const paragraph = $createParagraphNode();+ const textNode = $createTextNode('hello');+ paragraph.append(textNode);+ root.append(paragraph);+ textNode.select(0, 5);+ });++ fireEvent.click(screen.getByRole('button', {name: 'Link'}));++ // The attributes live on the NODE (not patched onto the DOM), so they are+ // readable from editor state and will serialize.+ await waitFor(() => {+ let target: string | null = null;+ let rel: string | null = null;+ editor.getEditorState().read(() => {+ const root = $getRoot();+ const paragraph = root.getFirstChild();+ const children = $isElementNode(paragraph)+ ? paragraph.getChildren()+ : [];+ for (const child of children) {+ if ('getTarget' in child) {+ const linkNode = child as unknown as {+ getTarget(): string | null;+ getRel(): string | null;+ };+ target = linkNode.getTarget();+ rel = linkNode.getRel();+ }+ }+ });+ expect(target).toBe('_blank');+ expect(rel).toBe('noopener noreferrer');+ });+ });++ it('omits new-tab attributes when linkOpensInNewTab is false', async () => {+ let editor!: LexicalEditor;+ const promptForUrl = vi.fn(() => 'example.com');+ render(+ <RichTextEditor+ label="Notes"+ plugins={+ <>+ <RichTextEditorToolbar+ promptForUrl={promptForUrl}+ linkOpensInNewTab={false}+ />+ <CaptureEditor onReady={e => (editor = e)} />+ </>+ }+ />,+ );+ await waitFor(() => expect(editor).toBeDefined());+ editor.update(() => {+ const root = $getRoot();+ root.clear();+ const paragraph = $createParagraphNode();+ const textNode = $createTextNode('hello');+ paragraph.append(textNode);+ root.append(paragraph);+ textNode.select(0, 5);+ });++ fireEvent.click(screen.getByRole('button', {name: 'Link'}));++ await waitFor(() => {+ let target: string | null | undefined = undefined;+ let sawLink = false;+ editor.getEditorState().read(() => {+ const root = $getRoot();+ const paragraph = root.getFirstChild();+ const children = $isElementNode(paragraph)+ ? paragraph.getChildren()+ : [];+ for (const child of children) {+ if ('getTarget' in child) {+ sawLink = true;+ target = (+ child as unknown as {getTarget(): string | null}+ ).getTarget();+ }+ }+ });+ expect(sawLink).toBe(true);+ expect(target).toBeNull();+ });+ });+});diff --git a/packages/lab/src/RichTextEditor/RichTextEditorAutoLinkPlugin.tsx b/packages/lab/src/RichTextEditor/RichTextEditorAutoLinkPlugin.tsxnew file mode 100644index 0000000000..7a29c9f819--- /dev/null+++ b/packages/lab/src/RichTextEditor/RichTextEditorAutoLinkPlugin.tsx@@ -0,0 +1,116 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file RichTextEditorAutoLinkPlugin.tsx+ * @input Uses `@lexical/react/LexicalAutoLinkPlugin` (`AutoLinkPlugin`,+ * `createLinkMatcherWithRegExp`) and the shared URL/email matchers from+ * `linkUtils`.+ * @output Exports `RichTextEditorAutoLinkPlugin` and its props type, plus the+ * default `DEFAULT_LINK_MATCHERS`.+ * @position Experimental (lab). Drop into RichTextEditor's `plugins` slot to+ * auto-linkify URLs and emails as they are typed or pasted. Requires+ * `AutoLinkNode` to be registered (it is, by default).+ *+ * 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 (story)+ *+ * NOTE: Experimental `@astryxdesign/lab` component (canary). `lexical` and+ * `@lexical/*` are OPTIONAL peer dependencies — install them to use this.+ *+ * COMPATIBILITY: astryx aims for its RichTextEditor internals to eventually+ * back Meta's EPS `EPSRichTextArea` (nest/libs/eps-lexical). EPS's auto-link is+ * matcher-driven and applies `target="_blank"` + `rel="noopener noreferrer"` to+ * created links (its `NEW_TAB_LINK_ATTRIBUTES`). This plugin uses the same+ * matcher shape (`createLinkMatcherWithRegExp` + `attributes`) and the same+ * new-tab defaults, so EPS can pass its own richer matcher set (e.g. shortform+ * `D123` / `T456` / `S789` intern URLs) through the `matchers` prop without+ * changing the contract. EPS ships a hardened fork of the transform itself+ * (expanded separators, code-block exclusion) — astryx stays on the OSS+ * `AutoLinkPlugin`, and EPS can substitute its own plugin in the same slot.+ */++import {+ AutoLinkPlugin,+ createLinkMatcherWithRegExp,+ type LinkMatcher,+} from '@lexical/react/LexicalAutoLinkPlugin';+import {URL_MATCHER, EMAIL_MATCHER, sanitizeUrl} from './linkUtils';++/**+ * Attributes written onto every auto-created link so it opens in a new tab.+ * `rel="noopener noreferrer"` is required whenever `target="_blank"` is set, to+ * prevent reverse-tabnabbing. Matches EPS eps-lexical's `NEW_TAB_LINK_ATTRIBUTES`.+ */+export const NEW_TAB_LINK_ATTRIBUTES = {+ target: '_blank',+ rel: 'noopener noreferrer',+} as const;++/**+ * Default matchers: bare URLs (defaulting to `https://` when scheme-less) and+ * email addresses (as `mailto:` links). Both carry {@link NEW_TAB_LINK_ATTRIBUTES}.+ * URLs are passed through {@link sanitizeUrl} so only http/https/mailto/tel+ * schemes are ever written.+ */+export const DEFAULT_LINK_MATCHERS: LinkMatcher[] = [+ text => {+ const match = createLinkMatcherWithRegExp(URL_MATCHER, url =>+ sanitizeUrl(url),+ )(text);+ return match ? {...match, attributes: NEW_TAB_LINK_ATTRIBUTES} : null;+ },+ text => {+ const match = createLinkMatcherWithRegExp(+ EMAIL_MATCHER,+ email => `mailto:${email}`,+ )(text);+ return match ? {...match, attributes: NEW_TAB_LINK_ATTRIBUTES} : null;+ },+];++export interface RichTextEditorAutoLinkPluginProps {+ /**+ * Link matchers to use. Defaults to {@link DEFAULT_LINK_MATCHERS} (URLs ++ * emails, opening in a new tab). Provide a custom array to recognize+ * additional patterns (e.g. product-specific shortform references) — build+ * each with `createLinkMatcherWithRegExp` from+ * `@lexical/react/LexicalAutoLinkPlugin`.+ */+ matchers?: LinkMatcher[];+ /**+ * Called when a link is created, updated, or removed by auto-linking.+ * Receives the new URL (or `null` when removed) and the previous URL.+ */+ onChange?: (url: string | null, prevUrl: string | null) => void;+}++/**+ * Automatically converts typed/pasted URLs and email addresses into links.+ * Render it inside the editor's `plugins` slot — it reaches the editor via+ * `useLexicalComposerContext()`, so it must live within the editor's+ * `LexicalComposer`. Requires `AutoLinkNode` (registered by default).+ *+ * @example+ * ```+ * import {RichTextEditor, RichTextEditorAutoLinkPlugin} from '@astryxdesign/lab';+ *+ * <RichTextEditor+ * label="Notes"+ * plugins={<RichTextEditorAutoLinkPlugin />}+ * />+ * ```+ */+export function RichTextEditorAutoLinkPlugin({+ matchers = DEFAULT_LINK_MATCHERS,+ onChange,+}: RichTextEditorAutoLinkPluginProps) {+ return <AutoLinkPlugin matchers={matchers} onChange={onChange} />;+}++RichTextEditorAutoLinkPlugin.displayName = 'RichTextEditorAutoLinkPlugin';diff --git a/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx b/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsxindex 1002d5387e..c1b542382d 100644--- a/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx@@ -51,6 +51,7 @@ import {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 {ToggleButton} from '@astryxdesign/core/ToggleButton';import {Divider} from '@astryxdesign/core/Divider';@@ -62,11 +63,17 @@ import {CAN_UNDO_COMMAND,CAN_REDO_COMMAND,SELECTION_CHANGE_COMMAND,+ KEY_DOWN_COMMAND,COMMAND_PRIORITY_CRITICAL,+ COMMAND_PRIORITY_NORMAL,+ IS_APPLE,+ isExactShortcutMatch,$getSelection,$isRangeSelection,$createParagraphNode,+ $createTextNode,} from 'lexical';+import {sanitizeUrl} from './linkUtils';/** Block types the toolbar can toggle. */type BlockType =@@ -78,6 +85,23 @@ const HEADING_LABELS: Record<'h1' | 'h2' | 'h3', string> = {h3: 'Heading 3',};+/**+ * The platform-primary modifier for shortcuts: Cmd on Apple, Ctrl elsewhere.+ * Mirrors the Lexical playground's `CONTROL_OR_META`+ * (packages/lexical-playground/src/plugins/ShortcutsPlugin/shortcuts.ts).+ */+const CONTROL_OR_META = {ctrlKey: !IS_APPLE, metaKey: IS_APPLE};++/**+ * Whether `event` is the insert-link shortcut (Cmd/Ctrl+K). Uses Lexical's+ * `isExactShortcutMatch`, which — unlike a loose `metaKey || ctrlKey` check —+ * requires exactly the primary modifier and rejects the combo when other+ * modifiers (Shift/Alt) are also held. Matches the playground's `isInsertLink`.+ */+function isInsertLink(event: KeyboardEvent): boolean {+ return isExactShortcutMatch(event, 'k', CONTROL_OR_META);+}+/*** Stable icon-registry keys for the toolbar's controls. Themes can override any* of these via `registerIcons({'richtext:bold': <MyIcon />})` from@@ -90,6 +114,7 @@ export const RICHTEXT_ICON_KEYS = {underline: 'richtext:underline',strikethrough: 'richtext:strikethrough',code: 'richtext:code',+ link: 'richtext:link',h1: 'richtext:h1',h2: 'richtext:h2',h3: 'richtext:h3',@@ -182,6 +207,22 @@ const defaultToolbarIcons: Record<string, ReactNode> = {/></svg>),+ link: (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden="true">+ <path+ d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1.5 1.5M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1.5-1.5"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ ),h1: <TextGlyph label="H1" />,h2: <TextGlyph label="H2" />,h3: <TextGlyph label="H3" />,@@ -312,6 +353,34 @@ export interface RichTextEditorToolbarProps {headingLevels?: ReadonlyArray<'h1' | 'h2' | 'h3'>;/** Toolbar size, forwarded to the Astryx Toolbar. @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.+ *+ * Requires `LinkNode` to be registered (it is, by default) — no extra setup.+ * The entered URL is sanitized (see `sanitizeUrl`) so only+ * http/https/mailto/tel links are written.+ * @default true+ */+ hasLink?: boolean;+ /**+ * 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.+ */+ promptForUrl?: (selectedText: string) => string | null | undefined;+ /**+ * Whether links created via the toolbar open in a new tab. When `true`+ * (default), the created link carries `target="_blank"` and+ * `rel="noopener noreferrer"` — written into the link node's data (so it+ * serializes and round-trips), not patched onto the DOM. Set `false` to+ * create same-tab links.+ * @default true+ */+ linkOpensInNewTab?: boolean;/*** 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@@ -344,11 +413,15 @@ export function RichTextEditorToolbar({label = 'Text formatting',headingLevels = ['h1', 'h2', 'h3'],size = 'sm',+ hasLink = true,+ promptForUrl,+ linkOpensInNewTab = true,endContent,}: RichTextEditorToolbarProps) {const [editor] = useLexicalComposerContext();const [activeFormats, setActiveFormats] = useState<Set<string>>(new Set());const [blockType, setBlockType] = useState<BlockType>('paragraph');+ const [isLink, setIsLink] = useState(false);const [canUndo, setCanUndo] = useState(false);const [canRedo, setCanRedo] = useState(false);const [isEditable, setIsEditable] = useState(() => editor.isEditable());@@ -372,6 +445,13 @@ export function RichTextEditorToolbar({}setActiveFormats(formats);+ // Link active state — a link is "active" when the caret/selection anchor+ // sits inside a LinkNode (or its immediate parent is one). Mirrors the EPS+ // 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 anchorNode = selection.anchor.getNode();const element =anchorNode.getKey() === 'root'@@ -392,6 +472,91 @@ 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 = '';+ editor.getEditorState().read(() => {+ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selectedText = selection.getTextContent();+ }+ });++ 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() === '') {+ return;+ }+ const url = sanitizeUrl(entered);+ if (url === 'about:blank') {+ // Sanitizer rejected the input (empty / unsafe scheme) — do nothing+ // rather than write a dead link.+ 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]);+ }+ });+ }+ }, [editor, isLink, promptForUrl, linkOpensInNewTab]);+useEffect(() => {return mergeRegister(editor.registerUpdateListener(({editorState}) => {@@ -424,8 +589,28 @@ export function RichTextEditorToolbar({editor.registerEditableListener(editable => {setIsEditable(editable);}),+ // Cmd/Ctrl+K opens link insertion. Detection mirrors the Lexical+ // playground's ShortcutsPlugin (isInsertLink → isExactShortcutMatch with+ // CONTROL_OR_META), so it fires only on the exact primary-modifier combo+ // and ignores Cmd+Shift+K etc. Only registered when the link button is+ // enabled. Returns true to consume the event so the browser's own+ // shortcut doesn't also fire.+ hasLink+ ? editor.registerCommand(+ KEY_DOWN_COMMAND,+ (event: KeyboardEvent) => {+ if (isInsertLink(event)) {+ event.preventDefault();+ toggleLink();+ return true;+ }+ return false;+ },+ COMMAND_PRIORITY_NORMAL,+ )+ : () => {},);- }, [editor, $syncToolbar]);+ }, [editor, $syncToolbar, hasLink, toggleLink]);const toggleInlineFormat = (format: string) => {// FORMAT_TEXT_COMMAND payload is a TextFormatType; the values we pass are@@ -542,6 +727,16 @@ export function RichTextEditorToolbar({isDisabled={!isEditable}onPressedChange={() => toggleInlineFormat('code')}/>+ {hasLink && (+ <ToggleButton+ label="Link"+ icon={resolveIcon('link')}+ isIconOnly+ isPressed={isLink}+ isDisabled={!isEditable}+ onPressedChange={toggleLink}+ />+ )}<Divider orientation="vertical" />{headingLevels.map(level => (<ToggleButtondiff --git a/packages/lab/src/RichTextEditor/index.ts b/packages/lab/src/RichTextEditor/index.tsindex 08487f56d8..78d4e01183 100644--- a/packages/lab/src/RichTextEditor/index.ts+++ b/packages/lab/src/RichTextEditor/index.ts@@ -38,3 +38,17 @@ export {RICHTEXT_ICON_KEYS,} from './RichTextEditorToolbar';export type {RichTextEditorToolbarProps} from './RichTextEditorToolbar';++export {+ RichTextEditorAutoLinkPlugin,+ DEFAULT_LINK_MATCHERS,+ NEW_TAB_LINK_ATTRIBUTES,+} from './RichTextEditorAutoLinkPlugin';+export type {RichTextEditorAutoLinkPluginProps} from './RichTextEditorAutoLinkPlugin';++export {+ sanitizeUrl,+ validateUrl,+ URL_MATCHER,+ EMAIL_MATCHER,+} from './linkUtils';diff --git a/packages/lab/src/RichTextEditor/linkUtils.ts b/packages/lab/src/RichTextEditor/linkUtils.tsnew file mode 100644index 0000000000..e161428a3b--- /dev/null+++ b/packages/lab/src/RichTextEditor/linkUtils.ts@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file linkUtils.ts+ * @input Uses only the DOM URL constructor (guarded via try/catch for SSR/edge).+ * @output Exports `sanitizeUrl`, `validateUrl`, and the URL/email matcher regexes+ * used by the AutoLink wiring.+ * @position Experimental (lab) helper shared by RichTextEditorToolbar (link+ * button) and the AutoLink matchers in RichTextEditor. Kept dependency-free so+ * both can import it without pulling in extra `@lexical/*` surface.+ *+ * SYNC: When modified, update:+ * - /packages/lab/src/RichTextEditor/RichTextEditorToolbar.tsx (link button)+ * - /packages/lab/src/RichTextEditor/RichTextEditor.tsx (AutoLink matchers)+ * - /packages/lab/src/RichTextEditor/RichTextEditor.test.tsx (tests)+ * - /packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs (link docs)+ * - /packages/lab/src/RichTextEditor/index.ts (exports)+ * - /packages/lab/src/index.ts (barrel re-export)+ *+ * NOTE: Mirrors the Lexical playground's url.ts (`sanitizeUrl` / `validateUrl`+ * / `URL_REGEX` / `EMAIL_REGEX`). Sanitization is the security-critical part:+ * it blocks `javascript:`, `data:`, and other non-http(s)/mailto/tel schemes+ * from being written into a LinkNode's href, so an inserted link can never+ * smuggle in an executable URL.+ */++/**+ * Schemes a link is allowed to carry. Anything else (notably `javascript:`,+ * `data:`, `vbscript:`) is rejected by {@link validateUrl} and coerced to+ * `about:blank` by {@link sanitizeUrl}, so a malicious paste can't produce a+ * clickable code-execution link.+ */+const SAFE_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:']);++/** Matches a scheme prefix like `https:` / `mailto:` at the start of a string. */+const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;++/**+ * Matches a bare URL for AutoLink. Adapted from the Lexical playground.+ * Intentionally permissive on path/query so real-world URLs linkify.+ */+export const URL_MATCHER =+ /((https?:\/\/(www\.)?)|(www\.))[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)/;++/** Matches a bare email address for AutoLink (rendered as a `mailto:` link). */+export const EMAIL_MATCHER =+ /(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;++/** Prepend a default `https://` scheme to a bare host so it parses as absolute. */+function withDefaultScheme(url: string): string {+ return HAS_SCHEME.test(url) ? url : `https://${url}`;+}++/**+ * Return a safe href for `url`, or `'about:blank'` if it can't be parsed or uses+ * a disallowed scheme. A scheme-less input like `example.com` is treated as+ * `https://example.com`. Use this before writing any user-supplied string into+ * a link's href.+ */+export function sanitizeUrl(url: string): string {+ const trimmed = url.trim();+ if (trimmed === '') {+ return 'about:blank';+ }+ try {+ const parsed = new URL(withDefaultScheme(trimmed));+ if (!SAFE_PROTOCOLS.has(parsed.protocol.toLowerCase())) {+ return 'about:blank';+ }+ return parsed.href;+ } catch {+ return 'about:blank';+ }+}++/**+ * Whether `url` is a well-formed, safe (http/https/mailto/tel) URL. Used to+ * decide whether an entered link value is acceptable before dispatching the+ * toggle-link command. Shares the {@link SAFE_PROTOCOLS} allowlist with+ * {@link sanitizeUrl} so the two never disagree.+ */+export function validateUrl(url: string): boolean {+ const trimmed = url.trim();+ if (trimmed === '') {+ return false;+ }+ try {+ const parsed = new URL(withDefaultScheme(trimmed));+ return SAFE_PROTOCOLS.has(parsed.protocol.toLowerCase());+ } catch {+ return false;+ }+}diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 16a676adbd..79f1744ef7 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -252,4 +252,12 @@ export {RichTextEditorToolbar,type RichTextEditorToolbarProps,RICHTEXT_ICON_KEYS,+ RichTextEditorAutoLinkPlugin,+ type RichTextEditorAutoLinkPluginProps,+ DEFAULT_LINK_MATCHERS,+ NEW_TAB_LINK_ATTRIBUTES,+ sanitizeUrl,+ validateUrl,+ URL_MATCHER,+ EMAIL_MATCHER,} from './RichTextEditor';