An open source design system that's fully customizable and agent ready
TypeScript
fix(Markdown): find link destinations in linear time (#7074)
Cindy Zhang3d6d1f04dcee
diff --git a/.changeset/markdown-link-destination-linear.md b/.changeset/markdown-link-destination-linear.mdnew file mode 100644index 0000000000..d01fc35134--- /dev/null+++ b/.changeset/markdown-link-destination-linear.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+---++[fix] Markdown: find link destinations in linear time+@cixzhang++`Markdown` no longer searches the rest of the text for every link or image whose destination never closes, which made a message with many of them take seconds to render. Each parenthesis now pairs once per text, so such input renders in milliseconds; links read as before.diff --git a/packages/core/src/Markdown/linkDestinationLinear.test.tsx b/packages/core/src/Markdown/linkDestinationLinear.test.tsxnew file mode 100644index 0000000000..6d9a0476fa--- /dev/null+++ b/packages/core/src/Markdown/linkDestinationLinear.test.tsx@@ -0,0 +1,54 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {parseInlineAst} from './parser';++type Json = {type: string; url?: string; value?: string; children?: Json[]};++/** Each link's or image's URL, in order. */+function urls(markdown: string): string[] {+ const found: string[] = [];+ const visit = (node: Json) => {+ if (node.type === 'link' || node.type === 'image') {+ found.push(node.url ?? '');+ }+ (node.children ?? []).forEach(visit);+ };+ (parseInlineAst(markdown) as unknown as Json[]).forEach(visit);+ return found;+}++/** The fastest of three parses of `markdown`, in milliseconds. */+function parseTime(markdown: string): number {+ parseInlineAst(markdown);+ let fastest = Number.POSITIVE_INFINITY;+ for (let round = 0; round < 3; round++) {+ const started = performance.now();+ parseInlineAst(markdown);+ fastest = Math.min(fastest, performance.now() - started);+ }+ return fastest;+}++describe('link destinations end where their parentheses balance', () => {+ it.each([+ ['[a](b(c)d)', ['b(c)d']],+ ['[a](b((c))d) and [e](f)', ['b((c))d', 'f']],+ ['[a](b\\)c)', ['b)c']],+ ['c)', ['a(b)c']],+ ['[a](b(c) and [e](f)', ['f']],+ ])('reads %j', (markdown, expected) => {+ expect(urls(markdown)).toEqual(expected);+ });++ it.each([+ ['links with unclosed destinations', '[a](b '.repeat(20_000)],+ ['images with unclosed destinations', '],+ ['unclosed nested parentheses', '[a](('.repeat(20_000)],+ ['one closing parenthesis at the end', `${'[a]('.repeat(20_000)})`],+ ])('reads %s in linear time', (_, markdown) => {+ // Alone, each takes about 10 ms; the budget leaves room for a loaded+ // test machine. Searching every destination to the end took 4 to 13 s.+ expect(parseTime(markdown)).toBeLessThan(1000);+ });+});diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.tsindex 81e20d9fd8..ed4e88e6d7 100644--- a/packages/core/src/Markdown/parser.ts+++ b/packages/core/src/Markdown/parser.ts@@ -1138,6 +1138,12 @@ interface InlineIndex {* as code.*/closingBracket(from: number): number;+ /**+ * The index of the `)` that closes the `(` at `open`, by nesting and+ * skipping escaped parentheses, or -1: where an inline link's or image's+ * destination ends.+ */+ closingParen(open: number): number;}function inlineIndexOf(text: string): InlineIndex {@@ -1204,27 +1210,30 @@ function inlineIndexOf(text: string): InlineIndex {}return from < text.length ? nextClosingBracket[from] : -1;};- return {backtickCloser, closingBracket};-}--function findClosingParen(text: string, start: number): number {- let depth = 1;- for (let index = start; index < text.length; index++) {- // An escaped parenthesis is part of the destination, not its end.- if (text[index] === '\\') {- index++;- continue;- }- if (text[index] === '(') {- depth++;- } else if (text[index] === ')') {- depth--;- if (depth === 0) {- return index;+ let parenPartners: Int32Array | null = null;+ const closingParen = (open: number): number => {+ if (parenPartners == null) {+ // Every parenthesis pairs once, by nesting, so no destination search+ // rescans the text after an unclosed one.+ parenPartners = new Int32Array(text.length).fill(-1);+ const opens: number[] = [];+ for (let index = 0; index < text.length; index++) {+ const character = text[index];+ if (character === '\\') {+ index++;+ } else if (character === '(') {+ opens.push(index);+ } else if (character === ')') {+ const opened = opens.pop();+ if (opened !== undefined) {+ parenPartners[opened] = index;+ }+ }}}- }- return -1;+ return text[open] === '(' ? parenPartners[open] : -1;+ };+ return {backtickCloser, closingBracket, closingParen};}// ---------------------------------------------------------------------------@@ -2050,7 +2059,7 @@ function parseInlineImpl(if (text[i] === '!' && text[i + 1] === '[') {const altClose = inlineIndex.closingBracket(i + 2);if (altClose !== -1 && text[altClose + 1] === '(') {- const srcClose = findClosingParen(text, altClose + 2);+ const srcClose = inlineIndex.closingParen(altClose + 1);if (srcClose !== -1) {const src = decodeLinkDestination(inlineDestination(text.slice(altClose + 2, srcClose)),@@ -2095,7 +2104,7 @@ function parseInlineImpl(if (text[i] === '[') {const textClose = inlineIndex.closingBracket(i + 1);if (textClose !== -1 && text[textClose + 1] === '(') {- const urlClose = findClosingParen(text, textClose + 2);+ const urlClose = inlineIndex.closingParen(textClose + 1);if (urlClose !== -1) {const href = decodeLinkDestination(inlineDestination(text.slice(textClose + 2, urlClose)),