Skip to content

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

TypeScript

fix(richtext): read angle-bracket link destinations as core does, and write spaces in them (#7070)

Cindy Zhanga9c080d738c2
diff --git a/packages/richtext/src/markdownAngleDestinations.test.ts b/packages/richtext/src/markdownAngleDestinations.test.ts
new file mode 100644
index 0000000000..af0b88e34e
--- /dev/null
+++ b/packages/richtext/src/markdownAngleDestinations.test.ts
@@ -0,0 +1,134 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {createHeadlessEditor} from '@lexical/headless';
+import {$createLinkNode} from '@lexical/link';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $isTextNode,
+} from 'lexical';
+import {parseInlineAst} from '@astryxdesign/core/Markdown/parser';
+import {DEFAULT_NODES} from './editorNodes';
+import {DEFAULT_TRANSFORMERS} from './markdownTable';
+import {
+ $exportMarkdownKeepingSource,
+ importMarkdownKeepingSource,
+} from './markdownSource';
+import {
+ editorStateJSONToMarkdown,
+ markdownToEditorStateJSON,
+} from './markdownSerializers';
+
+type Json = Record<string, unknown>;
+
+/** Each link's URL and title, as RichText imports it. */
+function richLinks(
+ markdown: string,
+): Array<{url: string; title: string | null}> {
+ const links: Array<{url: string; title: string | null}> = [];
+ const visit = (node: Json) => {
+ if (node.type === 'link') {
+ links.push({
+ url: node.url as string,
+ title: (node.title as string | null | undefined) ?? null,
+ });
+ }
+ ((node.children as Json[]) ?? []).forEach(visit);
+ };
+ visit((JSON.parse(markdownToEditorStateJSON(markdown)) as {root: Json}).root);
+ return links;
+}
+
+/** Each link's URL, as core reads it. */
+function coreUrls(markdown: string): string[] {
+ const urls: string[] = [];
+ const visit = (node: Json) => {
+ if (node.type === 'link') {
+ urls.push(node.url as string);
+ }
+ ((node.children as Json[]) ?? []).forEach(visit);
+ };
+ (parseInlineAst(markdown) as unknown as Json[]).forEach(visit);
+ return urls;
+}
+
+function newEditor() {
+ return createHeadlessEditor({
+ nodes: [...DEFAULT_NODES],
+ onError(error) {
+ throw error;
+ },
+ });
+}
+
+describe('angle-bracket link destinations (CommonMark 0.31 §6.3)', () => {
+ it.each([
+ 'See [c](<https://e.com/a b>) here',
+ 'See [c](<https://e.com/a b> "t") here',
+ 'See [c](<https://e.com/x>) here',
+ 'See [c](<a b>) and [d](https://e.com) here',
+ ])('reads %j with the address core reads, and round-trips it', markdown => {
+ expect(richLinks(markdown).map(({url}) => url)).toEqual(coreUrls(markdown));
+ expect(
+ editorStateJSONToMarkdown(markdownToEditorStateJSON(`${markdown}\n`)),
+ ).toBe(`${markdown}\n`);
+ });
+
+ it('keeps the title of an angle-bracket destination', () => {
+ expect(richLinks('[c](<a b> "t")')).toEqual([{url: 'a b', title: 't'}]);
+ });
+
+ it('writes an address holding a space in angle brackets after an edit, so it reads back', () => {
+ const editor = newEditor();
+ importMarkdownKeepingSource(editor, 'See [c](<https://e.com/a b>) here\n', [
+ ...DEFAULT_TRANSFORMERS,
+ ]);
+ editor.update(
+ () => {
+ const last = $getRoot().getAllTextNodes().at(-1);
+ if (!$isTextNode(last)) {
+ throw new Error('No text');
+ }
+ last.setTextContent(' there');
+ },
+ {discrete: true},
+ );
+ const exported = editor
+ .getEditorState()
+ .read(() => $exportMarkdownKeepingSource([...DEFAULT_TRANSFORMERS]));
+ expect(exported).toBe('See [c](<https://e.com/a b>) there\n');
+ expect(richLinks(exported)).toEqual([
+ {url: 'https://e.com/a b', title: null},
+ ]);
+ });
+
+ it('writes a link made in the editor with a space in its address so it reads back', () => {
+ const editor = newEditor();
+ editor.update(
+ () => {
+ $getRoot()
+ .clear()
+ .append(
+ $createParagraphNode().append(
+ $createLinkNode('https://e.com/a b').append($createTextNode('c')),
+ ),
+ );
+ },
+ {discrete: true},
+ );
+ const exported = editor
+ .getEditorState()
+ .read(() => $exportMarkdownKeepingSource([...DEFAULT_TRANSFORMERS]));
+ expect(exported).toBe('[c](<https://e.com/a b>)');
+ expect(richLinks(exported)).toEqual([
+ {url: 'https://e.com/a b', title: null},
+ ]);
+ });
+
+ it('still refuses an unsafe address in angle brackets', () => {
+ expect(richLinks('[x](<javascript:alert(1)>)')).toEqual([]);
+ expect(richLinks('[x](<data: text/html,hi>)')).toEqual([]);
+ });
+});
diff --git a/packages/richtext/src/markdownLink.ts b/packages/richtext/src/markdownLink.ts
index bb940ae489..915ceab236 100644
--- a/packages/richtext/src/markdownLink.ts
+++ b/packages/richtext/src/markdownLink.ts
@@ -4,8 +4,10 @@
* @file markdownLink.ts
* @input Uses @lexical/link and @lexical/markdown (LINK).
* @output Exports LINK_KEEPING_DESTINATIONS, Lexical's link transformer with
- * one change: a destination whose parentheses do not balance is written
- * with each parenthesis escaped.
+ * two changes: it reads an angle-bracket destination (`<https://e.com/a b>`)
+ * as core Markdown does, without its brackets, and it writes a destination
+ * so it reads back: one holding a space in angle brackets, and one whose
+ * parentheses do not balance with each parenthesis escaped.
* @position Replaces Lexical's LINK in DEFAULT_TRANSFORMERS and in table
* cells (markdownTable.ts). Import reads balanced parentheses in a
* destination and backslash escapes (markdownCharacterReferences.ts), so a
@@ -36,11 +38,36 @@ function isBalanced(url: string): boolean {
/** `url` as a Markdown destination that reads back as `url`. */
export function markdownDestination(url: string): string {
+ if (/\s/.test(url)) {
+ // Only an angle-bracket destination may hold a space (CommonMark §6.3).
+ return `<${url.replace(/[<>]/g, '\\$&')}>`;
+ }
return isBalanced(url) ? url : url.replace(/[()]/g, '\\$&');
}
+/**
+ * Lexical's link pattern, with a destination in angle brackets too: any
+ * characters but brackets and line endings, spaces included.
+ */
+const LINK_WITH_ANGLE_DESTINATION =
+ /(?:\[(.+?)\])(?:\((?:(<[^<>\n]*>|[^()\s]+)(?:\s"((?:[^"]*\\")*[^"]*)"\s*)?)\))/;
+
export const LINK_KEEPING_DESTINATIONS: TextMatchTransformer = {
...LINK,
+ importRegExp: LINK_WITH_ANGLE_DESTINATION,
+ replace: (textNode, match) => {
+ const destination = match[2];
+ if (destination?.startsWith('<') !== true) {
+ return LINK.replace?.(textNode, match);
+ }
+ // The link's address is what the angle brackets hold.
+ const withoutBrackets = Object.assign([...match], {
+ index: match.index,
+ input: match.input,
+ }) as RegExpMatchArray;
+ withoutBrackets[2] = destination.slice(1, -1);
+ return LINK.replace?.(textNode, withoutBrackets);
+ },
export: (node, exportChildren, exportFormat) => {
if (!$isLinkNode(node) || $isAutoLinkNode(node)) {
return null;