An open source design system that's fully customizable and agent ready
TypeScript
fix(Markdown): close a code span only at a backtick string of the same length (#7068)
Cindy Zhang0978d0a4b6b0
diff --git a/.changeset/markdown-code-span-runs.md b/.changeset/markdown-code-span-runs.mdnew file mode 100644index 0000000000..2796fdab81--- /dev/null+++ b/.changeset/markdown-code-span-runs.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+---++[fix] Markdown: close a code span only at a backtick string of the same length+@cixzhang++`Markdown` now ends a code span at the next run of exactly as many backticks as opened it, never at part of a longer run, and reads runs of any length, as CommonMark specifies. `` `one`` two` `` is one code span holding ` `` `, and four or more backticks open and close spans too. A run with no closer of its length stays text.diff --git a/packages/core/src/Markdown/codeSpans.test.tsx b/packages/core/src/Markdown/codeSpans.test.tsxnew file mode 100644index 0000000000..f58518ddc6--- /dev/null+++ b/packages/core/src/Markdown/codeSpans.test.tsx@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {parseInlineAst, parseMarkdownAst} from './parser';++type Json = {type: string; value?: string; children?: Json[]};++/** Each inline node as `code(…)` or its text, in order. */+function spans(markdown: string): string[] {+ const out: string[] = [];+ const visit = (node: Json) => {+ if (node.type === 'inlineCode') {+ out.push(`code(${node.value})`);+ } else if (node.type === 'text') {+ out.push(node.value ?? '');+ } else {+ (node.children ?? []).forEach(visit);+ }+ };+ (parseInlineAst(markdown) as unknown as Json[]).forEach(visit);+ return out;+}++describe('code spans close at a backtick string of the same length (CommonMark 0.31 §6.1)', () => {+ it.each([+ ['`foo`', ['code(foo)']],+ ['``foo`bar``', ['code(foo`bar)']],+ ['`one`` & two`', ['code(one`` & two)']],+ ['`foo``bar``', ['`foo', 'code(bar)']],+ ['````x````', ['code(x)']],+ ['````x``` y````', ['code(x``` y)']],+ ['```foo``', ['```foo``']],+ ['`foo', ['`foo']],+ ['a `` b ` c `` d', ['a ', 'code( b ` c )', ' d']],+ [+ '`a` and ``b`` and `c`',+ ['code(a)', ' and ', 'code(b)', ' and ', 'code(c)'],+ ],+ ])('reads %j', (markdown, expected) => {+ expect(spans(markdown)).toEqual(expected);+ });++ it('closes a span in a table cell at the same length, with an escaped pipe as a pipe', () => {+ const table = parseMarkdownAst('| a |\n| --- |\n| ``x`y \\| z`` |\n')+ .children[0] as unknown as Json;+ const cell = table.children?.[1]?.children?.[0];+ expect(cell?.children).toEqual([{type: 'inlineCode', value: 'x`y | z'}]);+ });++ it('finds every closer in linear time, even with no closer for most strings', () => {+ // Backtick strings of every length up to 400, none with a closer but the+ // last pair: a scan per string would read the rest of the text each time.+ const markdown = `${Array.from({length: 400}, (_, n) => `${'`'.repeat(n + 1)}a`).join(' ')} \`\`\`\`\`b\`\`\`\`\``;+ 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);+ }+ // Alone it takes a few milliseconds; the budget leaves room for a+ // loaded test machine.+ expect(fastest).toBeLessThan(1000);+ });+});diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.tsindex 6cb0be9c7e..fefbb77520 100644--- a/packages/core/src/Markdown/parser.ts+++ b/packages/core/src/Markdown/parser.ts@@ -1890,6 +1890,13 @@ function parseInlineImpl(// resolveEmphasis pairs it. Created only when a run appears.let delimiters: DelimiterRun[] | null = null;let delimiterNodes: Set<object> | null = null;+ // Where each backtick string of `text` starts, by length, with how far the+ // search for a closer of that length has come: built when the first one+ // appears, so finding every code span's closer is linear.+ let backtickStrings: Map<+ number,+ {readonly starts: number[]; searched: number}+ > | null = null;// Only a plugin that actually contributes INLINE syntax may cost anything// per source position. A transform-only list contributes none, so it takes// the same path as an omitted or empty one: no candidate probe per@@ -1918,22 +1925,58 @@ function parseInlineImpl(}}- // --- Inline code ---+ // --- Inline code: a backtick string closes at the next backtick string+ // of the same length, never part of a longer one; with none, it is text+ // (CommonMark 0.31 §6.1).if (text[i] === '`') {- const tickCount = text[i + 1] === '`' ? (text[i + 2] === '`' ? 3 : 2) : 1;- const openIndex = i + tickCount;- const closeIndex = text.indexOf('`'.repeat(tickCount), openIndex);- if (closeIndex !== -1) {- nodes.push({- type: 'inlineCode',- value:- context === 'tableCell'- ? text.slice(openIndex, closeIndex).replace(/\\\|/g, '|')- : text.slice(openIndex, closeIndex),- });- i = closeIndex + tickCount;+ let openIndex = i;+ while (text[openIndex] === '`') {+ openIndex++;+ }+ const tickCount = openIndex - i;+ if (backtickStrings == null) {+ backtickStrings = new Map();+ for (let start = i; start !== -1;) {+ let end = start;+ while (text[end] === '`') {+ end++;+ }+ const sameLength = backtickStrings.get(end - start);+ if (sameLength == null) {+ backtickStrings.set(end - start, {starts: [start], searched: 0});+ } else {+ sameLength.starts.push(start);+ }+ start = text.indexOf('`', end);+ }+ }+ const sameLength = backtickStrings.get(tickCount);+ if (sameLength != null) {+ while (+ sameLength.searched < sameLength.starts.length &&+ sameLength.starts[sameLength.searched] < openIndex+ ) {+ sameLength.searched++;+ }+ }+ const closeIndex =+ sameLength != null && sameLength.searched < sameLength.starts.length+ ? sameLength.starts[sameLength.searched]+ : -1;+ if (closeIndex === -1) {+ appendInlineText(nodes, delimiterNodes, text.slice(i, openIndex));+ i = openIndex;continue;}+ nodes.push({+ type: 'inlineCode',+ value:+ context === 'tableCell'+ ? text.slice(openIndex, closeIndex).replace(/\\\|/g, '|')+ : text.slice(openIndex, closeIndex),+ });+ i = closeIndex + tickCount;+ continue;}// --- Inline math (opt-in; code takes precedence) ---