An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): the auto-link plugin never links text inside a code block (#10664)
Cindy Zhang590d90164198
diff --git a/.changeset/richtext-autolink-skips-code.md b/.changeset/richtext-autolink-skips-code.mdnew file mode 100644index 0000000000..3516940f18--- /dev/null+++ b/.changeset/richtext-autolink-skips-code.md@@ -0,0 +1,7 @@+---+'@astryxdesign/richtext': patch+---++[fix] `RichTextEditorAutoLinkPlugin` no longer turns a URL inside a code block into a link. A URL typed or pasted into a code block, or one in an imported fence, now stays code. Before, the link nested inside the code block, and the exported Markdown fence lost it.++@cixzhangdiff --git a/packages/richtext/src/RichTextEditorAutoLinkPlugin.doc.mjs b/packages/richtext/src/RichTextEditorAutoLinkPlugin.doc.mjsindex 2d36114fae..de8423477e 100644--- a/packages/richtext/src/RichTextEditorAutoLinkPlugin.doc.mjs+++ b/packages/richtext/src/RichTextEditorAutoLinkPlugin.doc.mjs@@ -26,7 +26,7 @@ export const docs = {],usage: {description:- "Turns typed and pasted URLs and email addresses into links. Render it in RichTextEditor's plugins slot; it reaches the editor through the editor's Lexical composer and uses AutoLinkNode, which the editor registers by default.",+ "Turns typed and pasted URLs and email addresses into links. Text inside a code block stays code and is never linked. Render it in RichTextEditor's plugins slot; it reaches the editor through the editor's Lexical composer and uses AutoLinkNode, which the editor registers by default.",bestPractices: [{guidance: true,diff --git a/packages/richtext/src/RichTextEditorAutoLinkPlugin.test.tsx b/packages/richtext/src/RichTextEditorAutoLinkPlugin.test.tsxnew file mode 100644index 0000000000..13a1d3e830--- /dev/null+++ b/packages/richtext/src/RichTextEditorAutoLinkPlugin.test.tsx@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file RichTextEditorAutoLinkPlugin.test.tsx+ * @input RichTextEditor with RichTextEditorAutoLinkPlugin mounted+ * @output Proof that auto-linking skips code blocks, on import and on paste,+ * and still links a URL in ordinary text (spec:AST-062 FR3, FR6)+ * @position Colocated tests for the auto-link plugin+ */++import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest';+import {act, render, waitFor} from '@testing-library/react';+import {useEffect} from 'react';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';+import {$isCodeNode, type CodeNode} from '@lexical/code';+import {$isAutoLinkNode} from '@lexical/link';+import {+ $getRoot,+ $getSelection,+ $isElementNode,+ $isRangeSelection,+ PASTE_COMMAND,+ type LexicalEditor,+ type LexicalNode,+} from 'lexical';+import {RichTextEditor} from './RichTextEditor';+import {RichTextEditorAutoLinkPlugin} from './RichTextEditorAutoLinkPlugin';+import {markdownToEditorStateJSON} from './markdown';++// jsdom has no clipboard or drag events; Lexical tells a paste from a drop+// by these classes.+beforeAll(() => {+ if (typeof ClipboardEvent === 'undefined') {+ vi.stubGlobal('ClipboardEvent', class ClipboardEvent extends Event {});+ }+ if (typeof DragEvent === 'undefined') {+ vi.stubGlobal('DragEvent', class DragEvent extends Event {});+ }+});+afterAll(() => {+ vi.unstubAllGlobals();+});++async function renderEditor(document: string): Promise<LexicalEditor> {+ let captured: LexicalEditor | undefined;+ function CaptureEditor() {+ const [editor] = useLexicalComposerContext();+ useEffect(() => {+ captured = editor;+ }, [editor]);+ return null;+ }+ render(+ <RichTextEditor+ label="Notes"+ defaultValue={markdownToEditorStateJSON(document)}+ plugins={+ <>+ <RichTextEditorAutoLinkPlugin />+ <CaptureEditor />+ </>+ }+ />,+ );+ await waitFor(() => expect(captured).toBeDefined());+ // Let the node transforms run on the imported state.+ act(() => {+ captured!.update(() => undefined, {discrete: true});+ });+ return captured!;+}++function $codeBlock(): CodeNode {+ const code = $getRoot().getChildren().find($isCodeNode);+ if (code == null) {+ throw new Error('The editor holds no code block');+ }+ return code;+}++function $autoLinks(node: LexicalNode): number {+ if ($isAutoLinkNode(node)) {+ return 1;+ }+ return $isElementNode(node)+ ? node.getChildren().reduce((sum, child) => sum + $autoLinks(child), 0)+ : 0;+}++function paste(editor: LexicalEditor, data: Record<string, string>) {+ const event = new ClipboardEvent('paste', {cancelable: true});+ Object.defineProperty(event, 'clipboardData', {+ value: {+ getData: (type: string) => data[type] ?? '',+ types: Object.keys(data),+ files: [],+ },+ });+ act(() => {+ editor.dispatchCommand(PASTE_COMMAND, event);+ editor.read(() => undefined);+ });+}++describe('RichTextEditorAutoLinkPlugin and code blocks', () => {+ it('leaves a URL in an imported fence as code', async () => {+ const editor = await renderEditor(+ '```sh\ncurl https://example.com/api\n```\n',+ );+ expect(editor.read(() => $autoLinks($codeBlock()))).toBe(0);+ expect(editor.read(() => $codeBlock().getTextContent())).toBe(+ 'curl https://example.com/api',+ );+ });++ it('leaves a URL in a rich paste into a code block as code', async () => {+ const editor = await renderEditor('```ts\nconst x = 1;\n\n```\n');+ act(() => {+ editor.update(() => $codeBlock().selectEnd(), {discrete: true});+ });+ paste(editor, {+ 'text/html': '<p>See https://example.com</p>',+ 'text/plain': 'See https://example.com',+ });+ expect(editor.read(() => $codeBlock().getTextContent())).toBe(+ 'const x = 1;\nSee https://example.com',+ );+ expect(editor.read(() => $autoLinks($codeBlock()))).toBe(0);+ });++ it('leaves a URL typed into a code block as code', async () => {+ const editor = await renderEditor('```ts\nconst x = 1;\n\n```\n');+ act(() => {+ editor.update(+ () => {+ $codeBlock().selectEnd();+ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selection.insertText('// see https://example.com ');+ }+ },+ {discrete: true},+ );+ });+ expect(editor.read(() => $codeBlock().getTextContent())).toBe(+ 'const x = 1;\n// see https://example.com ',+ );+ expect(editor.read(() => $autoLinks($codeBlock()))).toBe(0);+ });++ it('still links a URL in ordinary text', async () => {+ const editor = await renderEditor('See https://example.com today.\n');+ expect(editor.read(() => $autoLinks($getRoot()))).toBe(1);+ });+});diff --git a/packages/richtext/src/RichTextEditorAutoLinkPlugin.tsx b/packages/richtext/src/RichTextEditorAutoLinkPlugin.tsxindex 3dd7c5c03a..e6821b8ff7 100644--- a/packages/richtext/src/RichTextEditorAutoLinkPlugin.tsx+++ b/packages/richtext/src/RichTextEditorAutoLinkPlugin.tsx@@ -10,8 +10,9 @@* @output Exports `RichTextEditorAutoLinkPlugin` and its props type, plus the* default `DEFAULT_LINK_MATCHERS`.* @position @astryxdesign/richtext. 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).+ * auto-linkify URLs and emails as they are typed or pasted, except inside+ * a code block. Requires `AutoLinkNode` to be registered (it is, by+ * default).** SYNC: When modified, update:* - /packages/richtext/src/index.ts (exports / barrel)@@ -28,9 +29,8 @@* and new-tab defaults, so a consumer supplies a richer matcher set — an* application-specific identifier or ticket syntax, say — through the* `matchers` prop without changing the contract. An application needing a- * hardened transform (expanded separators, code-block exclusion) substitutes- * its own plugin in the same slot; astryx stays on the upstream- * `AutoLinkPlugin`.+ * hardened transform (expanded separators, say) substitutes its own plugin in+ * the same slot; astryx stays on the upstream `AutoLinkPlugin`.*/import {@@ -38,6 +38,8 @@ import {createLinkMatcherWithRegExp,type LinkMatcher,} from '@lexical/react/LexicalAutoLinkPlugin';+import {$isCodeNode} from '@lexical/code';+import type {ElementNode} from 'lexical';import {URL_MATCHER, EMAIL_MATCHER, sanitizeUrl} from './linkUtils';/**@@ -72,6 +74,10 @@ export const DEFAULT_LINK_MATCHERS: LinkMatcher[] = [},];+// Text in a code block is never linked. The upstream plugin registers again+// when this array changes. Keep it a module constant.+const EXCLUDE_PARENTS: ((parent: ElementNode) => boolean)[] = [$isCodeNode];+export interface RichTextEditorAutoLinkPluginProps {/*** Link matchers to use. Defaults to {@link DEFAULT_LINK_MATCHERS} (URLs +@@ -108,7 +114,13 @@ export function RichTextEditorAutoLinkPlugin({matchers = DEFAULT_LINK_MATCHERS,onChange,}: RichTextEditorAutoLinkPluginProps) {- return <AutoLinkPlugin matchers={matchers} onChange={onChange} />;+ return (+ <AutoLinkPlugin+ matchers={matchers}+ onChange={onChange}+ excludeParents={EXCLUDE_PARENTS}+ />+ );}RichTextEditorAutoLinkPlugin.displayName = 'RichTextEditorAutoLinkPlugin';