An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): render a thematic break inside a list item as a break, keeping every item (#7088)
Cindy Zhang9ad52e7a8b4f
diff --git a/packages/richtext/src/markdownListIndentation.ts b/packages/richtext/src/markdownListIndentation.tsindex 52cde72da1..92b4569387 100644--- a/packages/richtext/src/markdownListIndentation.ts+++ b/packages/richtext/src/markdownListIndentation.ts@@ -17,6 +17,8 @@const LIST_ITEM = /^([ \t]*)([-+*]|\d{1,9}[.)])( {1,4}|\t|$)/;const FENCE_OPEN = /^[ \t]*(`{3,}|~{3,})/;const BLANK_LINE = /^[ \t]*\r?$/;+/** A thematic break after its indentation: three or more of one marker. */+const THEMATIC_BREAK_CONTENT = /^([-*_])(?:[ \t]*\1){2,}[ \t]*\r?$/;/** Columns of leading whitespace, with tabs stopping every four columns. */function columnsOf(whitespace: string): number {@@ -55,8 +57,22 @@ export function normalizeListIndentation(markdown: string): string {afterBlankLine = true;continue;}+ const leading = /^[ \t]*/.exec(line)?.[0] ?? '';+ const indent = columnsOf(leading);+ if (THEMATIC_BREAK_CONTENT.test(line.slice(leading.length))) {+ // A thematic break, never an item, even where an item could start+ // (CommonMark 0.31 §4.1). Lexical shows it only as a block of its own,+ // so a break inside an item loses its indentation and reads as one.+ while (open.length > 0 && indent < open[open.length - 1]) {+ open.pop();+ }+ if (open.length > 0) {+ lines[index] = line.slice(leading.length);+ }+ afterBlankLine = false;+ continue;+ }const item = LIST_ITEM.exec(line);- const indent = columnsOf(/^[ \t]*/.exec(line)?.[0] ?? '');if (item == null) {const opening = FENCE_OPEN.exec(line);if (opening != null) {diff --git a/packages/richtext/src/markdownListThematicBreakInside.test.ts b/packages/richtext/src/markdownListThematicBreakInside.test.tsnew file mode 100644index 0000000000..ca1f581dfe--- /dev/null+++ b/packages/richtext/src/markdownListThematicBreakInside.test.ts@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {+ editorStateJSONToMarkdown,+ markdownToEditorStateJSON,+} from './markdownSerializers';++type Json = {type: string; text?: string; children?: Json[]};++/** The editor's blocks, and every text in document order. */+function read(markdown: string): {blocks: string[]; texts: string[]} {+ const root = (JSON.parse(markdownToEditorStateJSON(markdown)) as {root: Json})+ .root;+ const texts: string[] = [];+ const visit = (node: Json) => {+ if (node.type === 'text') {+ texts.push((node.text ?? '').trim());+ }+ (node.children ?? []).forEach(visit);+ };+ visit(root);+ return {blocks: (root.children ?? []).map(node => node.type), texts};+}++describe('a thematic break indented into a list item', () => {+ it.each([+ ['under a top-level item', '- a\n * * *\n b', ['a', 'b']],+ ['before a sibling item', '- a\n ***\n- c', ['a', 'c']],+ [+ 'under a nested item',+ '- a\n - b\n ---\n - c',+ ['a', 'b', 'c'],+ ],+ [+ 'under a nested item, two spaces a level',+ '- a\n - b\n ---\n - c',+ ['a', 'b', 'c'],+ ],+ [+ 'with CRLF line endings',+ '- a\r\n - b\r\n ---\r\n - c\r\n',+ ['a', 'b', 'c'],+ ],+ ])(+ 'renders as a break, never as its source, and keeps every item: %s',+ (_, markdown, texts) => {+ const read_ = read(markdown);+ expect(read_.blocks).toContain('horizontalrule');+ expect(read_.texts).toEqual(texts);+ expect(+ editorStateJSONToMarkdown(markdownToEditorStateJSON(markdown)),+ ).toBe(markdown);+ },+ );++ it.each([+ ['a break alone', '* * *', ['horizontalrule']],+ ['two items', '- a\n- b', ['list']],+ ['a break before a list', '- - -\n- a', ['horizontalrule', 'list']],+ ])('leaves %s as it was', (_, markdown, blocks) => {+ expect(read(markdown).blocks).toEqual(blocks);+ });+});diff --git a/packages/richtext/src/markdownSource.ts b/packages/richtext/src/markdownSource.tsindex 9fccddf817..5596f1c71b 100644--- a/packages/richtext/src/markdownSource.ts+++ b/packages/richtext/src/markdownSource.ts@@ -208,6 +208,28 @@ const BLOCK_START =* instead, and stays with them. Joining every chunk's leading, content, and* trailing text gives back the input exactly.*/+/**+ * The chunks of `markdown` that cover the same lines as `like`, the chunks of+ * text with the same line count. Rewriting indentation can move a line across+ * a chunk boundary rule — a thematic break indented into a list item becomes+ * a break of its own — so the chunks follow the authored text, not the rule.+ */+function sameLines(+ markdown: string,+ like: ReadonlyArray<MarkdownChunk>,+): Array<MarkdownChunk> {+ const lines = markdown.split('\n');+ const lineEndings = (text: string) => text.split('\n').length - 1;+ let line = 0;+ return like.map(chunk => {+ line += lineEndings(chunk.leading);+ const count = lineEndings(chunk.content) + 1;+ const content = lines.slice(line, line + count).join('\n');+ line += count - 1 + lineEndings(chunk.trailing);+ return {...chunk, content};+ });+}+export function splitMarkdownChunks(markdown: string): Array<MarkdownChunk> {const lines = markdown.split('\n');const chunks: Array<MarkdownChunk> = [];@@ -348,9 +370,9 @@ export function importMarkdownKeepingSource(const body = byteOrderMark ? markdown.slice(1) : markdown;const chunks = splitMarkdownChunks(body);// Lexical reads the same chunks with list nesting spelled its way; the- // records keep the authored bytes. Only list item indentation changes, so- // the chunks line up one for one.- const importChunks = splitMarkdownChunks(normalizeListIndentation(body));+ // records keep the authored bytes. Only indentation changes, so each chunk+ // is the same lines of the rewritten text.+ const importChunks = sameLines(normalizeListIndentation(body), chunks);const lineEnding = lineEndingOf(body, '\n');editor.update(() => {