An open source design system that's fully customizable and agent ready
TypeScript
fix(Markdown): recognize hard line breaks before CRLF line endings (#6998)
Cindy Zhang5058d27cd38b
diff --git a/.changeset/markdown-crlf-hard-breaks.md b/.changeset/markdown-crlf-hard-breaks.mdnew file mode 100644index 0000000000..631ae1ba87--- /dev/null+++ b/.changeset/markdown-crlf-hard-breaks.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] Markdown makes a hard line break from two spaces or a backslash before a Windows (CRLF) line ending++Documents saved with CRLF line endings lost their hard line breaks: the carriage return sat between the trailing spaces or backslash and the line feed, so neither was recognized and the lines ran together. Both now break the line exactly as they do in an LF document, in paragraphs, links, and block quotes and while streaming; code spans, code blocks, and table cells are unchanged.++@cixzhangdiff --git a/packages/core/src/Markdown/parser.test.ts b/packages/core/src/Markdown/parser.test.tsindex 563994cafa..aca90bfea3 100644--- a/packages/core/src/Markdown/parser.test.ts+++ b/packages/core/src/Markdown/parser.test.ts@@ -380,6 +380,25 @@ describe('parseInline', () => {]);});+ it('makes two spaces or a backslash before a CRLF line ending a hard break', () => {+ expect(parseInline('two \r\nspaces')).toEqual([+ {type: 'text', content: 'two'},+ {type: 'break'},+ {type: 'text', content: 'spaces'},+ ]);+ expect(parseInline('back\\\r\nslash')).toEqual([+ {type: 'text', content: 'back'},+ {type: 'break'},+ {type: 'text', content: 'slash'},+ ]);+ // A Windows path ending a line keeps its other backslashes.+ expect(parseInline('C:\\Users\\Ada\\\r\nnext')).toEqual([+ {type: 'text', content: 'C:\\Users\\Ada'},+ {type: 'break'},+ {type: 'text', content: 'next'},+ ]);+ });+it('escapes only ASCII punctuation and keeps other backslashes literal', () => {const textOf = (source: string) =>parseInline(source)@@ -435,6 +454,77 @@ describe('parseInline', () => {});describe('parseMarkdown', () => {+ describe('hard breaks in CRLF documents', () => {+ const hasBreak = (value: unknown): boolean =>+ JSON.stringify(value).includes('"type":"break"');+ const lf = (source: string) => source.replace(/\r\n/g, '\n');+ // The parser keeps each CRLF line's `\r` in its text; drop it, and any text+ // node left empty, to compare structure with the LF document. Parsed+ // blocks are plain JSON data, so the comparison works on that shape.+ type Json =+ string | number | boolean | null | Json[] | {[key: string]: Json};+ const isEmptyText = (node: Json): boolean =>+ typeof node === 'object' &&+ node !== null &&+ !Array.isArray(node) &&+ node.type === 'text' &&+ node.content === '';+ const withoutCarriageReturns = (value: Json): Json => {+ if (Array.isArray(value)) {+ return value+ .map(withoutCarriageReturns)+ .filter(node => !isEmptyText(node));+ }+ if (typeof value === 'object' && value !== null) {+ return Object.fromEntries(+ Object.entries(value).map(([key, entry]) => [+ key,+ withoutCarriageReturns(entry),+ ]),+ );+ }+ return typeof value === 'string' ? value.replace(/\r/g, '') : value;+ };+ const asJson = (blocks: ReadonlyArray<BlockNode>): Json =>+ JSON.parse(JSON.stringify(blocks)) as Json;++ it('breaks lines the same way as the LF document', () => {+ for (const source of [+ 'Line one \r\nLine two\r\n',+ 'C:\\Users\\Ada\\\r\nnext\r\n',+ '[two \r\nlines](https://example.com)\r\n',+ '> quoted \r\n> lines\r\n',+ ]) {+ const crlf = parseMarkdown(source);+ expect(hasBreak(crlf), source).toBe(true);+ expect(withoutCarriageReturns(asJson(crlf)), source).toEqual(+ asJson(parseMarkdown(lf(source))),+ );+ }+ });++ it('leaves code spans, code blocks, and table cells without breaks', () => {+ for (const source of [+ '`a \r\nb` and `c\\\r\nd`\r\n',+ '```\r\ncode \r\nmore\\\r\n```\r\n',+ '| a |\r\n| --- |\r\n| x |\r\n',+ ]) {+ expect(hasBreak(parseMarkdown(source)), source).toBe(false);+ }+ });++ it('streams to the same result when chunks split the line ending', () => {+ const source = 'One \r\ntwo\\\r\nthree\r\n\r\nC:\\Users\r\n';+ const state = createIncrementalState();+ let blocks: BlockNode[] = [];+ for (let end = 1; end <= source.length; end++) {+ blocks = parseMarkdownIncremental(source.slice(0, end), state);+ }+ expect(blocks).toEqual(parseMarkdown(source));+ expect(hasBreak(blocks)).toBe(true);+ });+ });+it('parses headings', () => {const result = parseMarkdown('# Hello');expect(result[0].type).toBe('heading');diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.tsindex ef2815bb18..fc3f43943a 100644--- a/packages/core/src/Markdown/parser.ts+++ b/packages/core/src/Markdown/parser.ts@@ -1364,6 +1364,17 @@ type IncrementalMathParseOptionsWithoutPlugins = Omit<'plugins'>;+/**+ * The length of the line ending at `index` in inline text: 1 for LF, 2 for+ * CRLF (the parser keeps a CRLF line's `\r`), or 0 when none starts there.+ */+function lineEndingLengthAt(text: string, index: number): number {+ if (text[index] === '\n') {+ return 1;+ }+ return text[index] === '\r' && text[index + 1] === '\n' ? 2 : 0;+}+export function parseInline(text: string,sourceIds?: ReadonlySet<string>,@@ -1487,9 +1498,10 @@ function parseInlineImpl(// break it is a hard break; before anything else it is a literal// backslash (CommonMark 0.31, backslash escapes and hard line breaks).if (text[i] === '\\' && i + 1 < text.length) {- if (text[i + 1] === '\n') {+ const lineEnding = lineEndingLengthAt(text, i + 1);+ if (lineEnding > 0) {nodes.push({type: 'break'});- i += 2;+ i += 1 + lineEnding;continue;}if (isAsciiPunctuation(text[i + 1])) {@@ -1773,10 +1785,13 @@ function parseInlineImpl(const content = text.slice(i, end);- // Detect trailing-space line break: 2+ spaces immediately before \n+ // Detect trailing-space line break: 2+ spaces immediately before the+ // line ending. A CRLF line keeps its `\r` in the text; it belongs to the+ // line ending, not to the spaces before it.if (end < text.length && text[end] === '\n') {- const trimmed = content.replace(/ +$/, '');- if (content.length - trimmed.length >= 2) {+ const line = content.endsWith('\r') ? content.slice(0, -1) : content;+ const trimmed = line.replace(/ +$/, '');+ if (line.length - trimmed.length >= 2) {if (trimmed.length > 0) {const last = nodes[nodes.length - 1];if (last?.type === 'text') {