Skip to content

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

TypeScript

fix(richtext): start a nested numbered list at the number its first item was written with (#7043)

Cindy Zhang4b7cb3aeac4a
diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
index 3449d1e007..073041fced 100644
--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
@@ -1214,6 +1214,50 @@ test('bold italic text is emphasis and strong in the editor and the view', async
}
});
+// spec:AST-061 DEC-6: a nested numbered list keeps its start, so `27.`
+// under `1.` reads as item 27 at its depth's marker ("aa." in lower-alpha).
+test('nested numbered lists keep their start in the editor and the view', async ({
+ page,
+}) => {
+ await page.setViewportSize(DESKTOP);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=lab-richtexteditor--markdown-serializers&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:ltr`,
+ {waitUntil: 'load'},
+ );
+ await page
+ .locator('textarea')
+ // `28. ` puts its content at column seven, so `0.` nests under it.
+ .fill('1. one\n 27. twenty-seven\n 28. twenty-eight\n 0. zero\n');
+ const surfaces = page.locator('[data-lexical-editor]:visible');
+ await expect(surfaces).toHaveCount(2);
+ for (const surface of [surfaces.nth(0), surfaces.nth(1)]) {
+ await expect(surface.getByText('zero', {exact: true})).toBeVisible();
+ const starts = await surface.evaluate(root =>
+ [...root.querySelectorAll('ol')].map(list => list.start),
+ );
+ expect(starts).toEqual([1, 27, 0]);
+ }
+ // The accessibility tree names each item by its own number.
+ const cdp = await page.context().newCDPSession(page);
+ const {nodes} = (await cdp.send('Accessibility.getFullAXTree')) as {
+ nodes: Array<{role?: {value?: string}; name?: {value?: string}}>;
+ };
+ const markers = nodes
+ .filter(node => node.role?.value === 'ListMarker')
+ .map(node => (node.name?.value ?? '').trim());
+ // Two surfaces, each: 1. / aa. ab. / 0. (the tree is not in DOM order).
+ expect(markers.sort()).toEqual([
+ '0.',
+ '0.',
+ '1.',
+ '1.',
+ 'aa.',
+ 'aa.',
+ 'ab.',
+ 'ab.',
+ ]);
+});
+
for (const viewport of [PHONE, {width: 1280, height: 900}] as const) {
for (const globals of [
'colorMode:light;direction:ltr',
diff --git a/packages/richtext/src/markdownOrderedList.test.ts b/packages/richtext/src/markdownOrderedList.test.ts
new file mode 100644
index 0000000000..4cacd2e821
--- /dev/null
+++ b/packages/richtext/src/markdownOrderedList.test.ts
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {
+ editorStateJSONToMarkdown,
+ markdownToEditorStateJSON,
+} from './markdownSerializers';
+
+interface ListShape {
+ readonly start: number;
+ readonly items: ReadonlyArray<string | ListShape>;
+}
+
+/** Each list's start and items, nesting as Markdown does. */
+function lists(markdown: string): Array<ListShape> {
+ const shape = (node: Record<string, unknown>): ListShape => ({
+ start: node.start as number,
+ items: (node.children as Array<Record<string, unknown>>).flatMap(item =>
+ (item.children as Array<Record<string, unknown>>).map(child =>
+ child.type === 'list' ? shape(child) : (child.text as string),
+ ),
+ ),
+ });
+ const root = (
+ JSON.parse(markdownToEditorStateJSON(markdown)) as {
+ root: {children: Array<Record<string, unknown>>};
+ }
+ ).root;
+ return root.children.filter(node => node.type === 'list').map(shape);
+}
+
+describe('ordered list starts (spec:AST-061 DEC-6)', () => {
+ it('starts a nested numbered list at the number its first item was written with', () => {
+ expect(lists('1. a\n 27. b\n 28. c\n')).toEqual([
+ {start: 1, items: ['a', {start: 27, items: ['b', 'c']}]},
+ ]);
+ expect(lists('3. a\n 0. b\n')).toEqual([
+ {start: 3, items: ['a', {start: 0, items: ['b']}]},
+ ]);
+ });
+
+ it('keeps nested starts at every depth, and continues an existing nested list', () => {
+ expect(lists('1. a\n 5. b\n 9. c\n 6. d\n')).toEqual([
+ {
+ start: 1,
+ items: ['a', {start: 5, items: ['b', {start: 9, items: ['c']}, 'd']}],
+ },
+ ]);
+ });
+
+ it('leaves top-level and kind-changing starts as they were, and round-trips', () => {
+ for (const markdown of [
+ '27. a\n28. b\n',
+ '- a\n 27. b\n',
+ '1. a\n 27. b\n 28. c\n',
+ ]) {
+ const json = markdownToEditorStateJSON(markdown);
+ expect(editorStateJSONToMarkdown(json)).toBe(markdown);
+ }
+ expect(lists('27. a\n28. b\n')).toEqual([{start: 27, items: ['a', 'b']}]);
+ });
+});
diff --git a/packages/richtext/src/markdownOrderedList.ts b/packages/richtext/src/markdownOrderedList.ts
new file mode 100644
index 0000000000..2d5f51fa75
--- /dev/null
+++ b/packages/richtext/src/markdownOrderedList.ts
@@ -0,0 +1,60 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file markdownOrderedList.ts
+ * @input Uses @lexical/list (ListNode, ListItemNode) and @lexical/markdown
+ * (ORDERED_LIST).
+ * @output Exports ORDERED_LIST_KEEPING_START, Lexical's ordered list
+ * transformer with one change: a nested numbered list starts at the number
+ * its first item was written with.
+ * @position Replaces Lexical's ORDERED_LIST in DEFAULT_TRANSFORMERS
+ * (markdownTable.ts). Lexical nests an indented item under a numbered list
+ * by indenting it into a new list that starts at 1, so `27.` written as the
+ * first item of a nested list read as `1.` (or `a.` under spec:AST-061
+ * DEC-6). Markdown keeps every list's start, nested or not (DEC-6), so this
+ * sets the new nested list's start from the marker. A later item in the same
+ * nested list continues its sequence, as Lexical's does.
+ */
+
+import {$isListItemNode, $isListNode, type ListNode} from '@lexical/list';
+import {ORDERED_LIST, type ElementTransformer} from '@lexical/markdown';
+
+/**
+ * The list `item` was indented into: the last item under `list`, followed
+ * down through the wrapper items Lexical nests lists in.
+ */
+function nestedListOfLastItem(list: ListNode): ListNode {
+ let current = list;
+ for (;;) {
+ const last = current.getLastChild();
+ const nested = $isListItemNode(last) ? last.getFirstChild() : null;
+ if (
+ !$isListItemNode(last) ||
+ last.getChildrenSize() !== 1 ||
+ !$isListNode(nested)
+ ) {
+ return current;
+ }
+ current = nested;
+ }
+}
+
+export const ORDERED_LIST_KEEPING_START: ElementTransformer = {
+ ...ORDERED_LIST,
+ replace: (parentNode, children, match, isImport) => {
+ const previous = parentNode.getPreviousSibling();
+ const result = ORDERED_LIST.replace(parentNode, children, match, isImport);
+ if ($isListNode(previous) && previous.getListType() === 'number') {
+ const nested = nestedListOfLastItem(previous);
+ // The new item opened this nested list: start it at its own number.
+ if (
+ nested !== previous &&
+ nested.getListType() === 'number' &&
+ nested.getChildrenSize() === 1
+ ) {
+ nested.setStart(Number(match[2]));
+ }
+ }
+ return result;
+ },
+};
diff --git a/packages/richtext/src/markdownTable.ts b/packages/richtext/src/markdownTable.ts
index de5bd37d29..9b4614aaca 100644
--- a/packages/richtext/src/markdownTable.ts
+++ b/packages/richtext/src/markdownTable.ts
@@ -20,6 +20,7 @@ import {
$convertToMarkdownString,
TEXT_FORMAT_TRANSFORMERS,
TEXT_MATCH_TRANSFORMERS,
+ ORDERED_LIST,
TRANSFORMERS,
type MultilineElementTransformer,
type Transformer,
@@ -41,6 +42,7 @@ import {HARD_LINE_BREAK} from './markdownHardLineBreak';
import {THEMATIC_BREAK} from './markdownThematicBreak';
import {LIST_EXPORT} from './markdownListExport';
import {TASK_LIST} from './markdownTaskList';
+import {ORDERED_LIST_KEEPING_START} from './markdownOrderedList';
/**
* Cells hold inline Markdown only, so they are imported and exported with the
@@ -240,8 +242,8 @@ export const TABLE: MultilineElementTransformer = {
/**
* The editor's default Markdown transformers: thematic breaks, list export
* that nests to each parent's content column, GFM task list items, Lexical's
- * standard set, hard line breaks for breaks typed in the editor, and GFM
- * tables. Thematic breaks come first so a line such as `* * *` is a rule
+ * standard set (its ordered list keeping each nested list's start), hard line
+ * breaks for breaks typed in the editor, and GFM tables. Thematic breaks come first so a line such as `* * *` is a rule
* rather than a list item, and task items before bullets so `- [ ] text` is a
* task rather than a bullet that starts with `[ ]`.
*/
@@ -249,7 +251,9 @@ export const DEFAULT_TRANSFORMERS: ReadonlyArray<Transformer> = [
THEMATIC_BREAK,
LIST_EXPORT,
TASK_LIST,
- ...TRANSFORMERS,
+ ...TRANSFORMERS.map(transformer =>
+ transformer === ORDERED_LIST ? ORDERED_LIST_KEEPING_START : transformer,
+ ),
HARD_LINE_BREAK,
TABLE,
];