Skip to content

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

TypeScript

feat(richtext): import GFM task lists exactly as Markdown does, with a checkbox each item owns (#7007)

Cindy Zhang258ff023681e
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsx
index 3a7a6f4b76..7e1a1fdb2f 100644
--- a/packages/richtext/src/RichTextEditor.tsx
+++ b/packages/richtext/src/RichTextEditor.tsx
@@ -75,6 +75,7 @@ import {TablePlugin} from '@lexical/react/LexicalTablePlugin';
import {HorizontalRuleExtension} from '@lexical/extension';
import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';
import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';
+import {TaskCheckboxPlugin} from './TaskCheckboxPlugin';
import {type Transformer} from '@lexical/markdown';
export type {Transformer} from '@lexical/markdown';
import {$generateHtmlFromNodes} from '@lexical/html';
@@ -677,6 +678,7 @@ export const RichTextEditor = forwardRef<
/>
<HistoryPlugin />
<ListPlugin />
+ <TaskCheckboxPlugin isReadOnly={isReadOnly || isDisabled} />
<LinkPlugin />
{/* Tab keeps its editor meaning inside a table (indent, and
Escape then Tab to leave the editor); arrow keys move
diff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsx
index cca8773fa6..c53ae1e137 100644
--- a/packages/richtext/src/RichTextView.tsx
+++ b/packages/richtext/src/RichTextView.tsx
@@ -33,6 +33,7 @@ import {TablePlugin} from '@lexical/react/LexicalTablePlugin';
import {TableScrollRegionPlugin} from './TableScrollRegionPlugin';
import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';
import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';
+import {TaskCheckboxPlugin} from './TaskCheckboxPlugin';
import type {
AnyLexicalExtension,
Klass,
@@ -46,7 +47,8 @@ import {DEFAULT_NODES} from './editorNodes';
const styles = stylex.create({
root: {
width: '100%',
- // Holds the code block headers drawn over the content.
+ // Holds the code block headers and task checkboxes drawn over the
+ // content.
position: 'relative',
},
});
@@ -288,8 +290,10 @@ export function RichTextView({
placeholder={null}
ErrorBoundary={LexicalErrorBoundary}
/>
- {/* After the content, so the copy buttons follow it in tab order. */}
+ {/* After the content, so the copy buttons and checkboxes follow it
+ in tab order. */}
<CodeBlockHeaderPlugin />
+ <TaskCheckboxPlugin isReadOnly />
{plugins}
</LexicalExtensionComposer>
</div>
diff --git a/packages/richtext/src/TaskCheckboxPlugin.tsx b/packages/richtext/src/TaskCheckboxPlugin.tsx
new file mode 100644
index 0000000000..d11160b91e
--- /dev/null
+++ b/packages/richtext/src/TaskCheckboxPlugin.tsx
@@ -0,0 +1,242 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TaskCheckboxPlugin.tsx
+ * @input Uses @lexical/react (composer context), @lexical/list, lexical, and
+ * core CheckboxInput.
+ * @output Exports TaskCheckboxPlugin, which draws a real checkbox beside every
+ * task list item: toggling it, or Mod+Enter in the item, checks the item in
+ * the editor, and it is read-only in RichTextView.
+ * @position Rendered by RichTextEditor and RichTextView inside the positioned
+ * element that holds the content editable, like core Markdown's task lists
+ * (spec:AST-061 FR5). A list item cannot take the checkbox role (Lexical's
+ * own checkbox lists give it one), and nothing can be added inside the
+ * editable text; so the item stays a list item, marked for the theme to
+ * make room, and the checkbox is a sibling of the editable text, positioned
+ * over the space at the start of the item. Plain items in the same list
+ * keep their markers. The item owns its checkbox (`aria-owns`), so
+ * assistive technology finds the checkbox and its state inside the item, in
+ * document order. The checkboxes take no tab stop of their own, which would
+ * come after the whole document: in the editor, Mod+Enter checks the item
+ * holding the caret, and in the view they are read-only.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {useEffect, useId, useState, type JSX} from 'react';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {$isListItemNode, $isListNode, type ListItemNode} from '@lexical/list';
+import {$getNodeByKey, $getRoot, type LexicalNode} from 'lexical';
+import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
+import {
+ $getTaskState,
+ $setTaskState,
+ registerTaskListEditing,
+ type TaskState,
+} from './markdownTaskList';
+
+/** Where one task item's checkbox goes, in the container's coordinates. */
+interface TaskPlacement {
+ readonly key: string;
+ readonly checked: boolean;
+ readonly label: string;
+ readonly top: number;
+ readonly left: number;
+}
+
+const styles = stylex.create({
+ checkbox: {
+ position: 'absolute',
+ },
+ placement: (top: number, left: number) => ({top, left}),
+});
+
+/** The width of core CheckboxInput's small control. */
+const CHECKBOX_SIZE = 20;
+
+/** Marks a task item for the theme (editorTheme.ts). */
+export const TASK_ATTRIBUTE = 'data-richtext-task';
+
+/**
+ * Every bulleted list item with text of its own, in document order, and
+ * whether it is a task (markdownTaskList.ts).
+ */
+function $bulletItems(): Array<{
+ readonly item: ListItemNode;
+ readonly task: TaskState | null;
+}> {
+ const items: Array<{item: ListItemNode; task: TaskState | null}> = [];
+ const visit = (node: LexicalNode) => {
+ if (!$isListNode(node)) {
+ return;
+ }
+ for (const item of node.getChildren()) {
+ if (!$isListItemNode(item)) {
+ continue;
+ }
+ const isWrapper =
+ item.getChildrenSize() === 1 && $isListNode(item.getFirstChild());
+ if (!isWrapper && node.getListType() !== 'number') {
+ items.push({item, task: $getTaskState(item)});
+ }
+ item.getChildren().forEach(visit);
+ }
+ };
+ $getRoot().getChildren().forEach(visit);
+ return items;
+}
+
+function samePlacements(
+ a: ReadonlyArray<TaskPlacement>,
+ b: ReadonlyArray<TaskPlacement>,
+): boolean {
+ return (
+ a.length === b.length &&
+ a.every(
+ (placement, index) =>
+ placement.key === b[index].key &&
+ placement.checked === b[index].checked &&
+ placement.label === b[index].label &&
+ placement.top === b[index].top &&
+ placement.left === b[index].left,
+ )
+ );
+}
+
+export function TaskCheckboxPlugin({
+ isReadOnly,
+}: {
+ readonly isReadOnly: boolean;
+}): JSX.Element {
+ const [editor] = useLexicalComposerContext();
+ const idPrefix = useId();
+ const [placements, setPlacements] = useState<ReadonlyArray<TaskPlacement>>(
+ [],
+ );
+
+ // Enter and Mod+Enter in task items (markdownTaskList.ts).
+ useEffect(
+ () => (isReadOnly ? undefined : registerTaskListEditing(editor)),
+ [editor, isReadOnly],
+ );
+
+ useEffect(() => {
+ let frame = 0;
+ const measure = () => {
+ frame = 0;
+ const root = editor.getRootElement();
+ const container = root?.parentElement;
+ if (root == null || container == null) {
+ setPlacements(current => (current.length === 0 ? current : []));
+ return;
+ }
+ const origin = container.getBoundingClientRect();
+ const next = editor.getEditorState().read(() =>
+ $bulletItems().flatMap(({item, task}) => {
+ const element = editor.getElementByKey(item.getKey());
+ if (element == null) {
+ return [];
+ }
+ if (task == null) {
+ // A plain item keeps its marker and owns no checkbox.
+ element.removeAttribute(TASK_ATTRIBUTE);
+ element.removeAttribute('aria-owns');
+ return [];
+ }
+ // The checkbox below carries the item's state, so the item keeps
+ // the list item role Lexical replaces, and owns the checkbox. The
+ // attribute lets the theme drop its marker and make room.
+ element.setAttribute(TASK_ATTRIBUTE, '');
+ element.removeAttribute('role');
+ element.removeAttribute('aria-checked');
+ element.removeAttribute('tabindex');
+ element.setAttribute(
+ 'aria-owns',
+ `${idPrefix}-task-${item.getKey()}`,
+ );
+ const box = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ const isRightToLeft = style.direction === 'rtl';
+ return [
+ {
+ key: item.getKey(),
+ checked: task === 'checked',
+ label: item.getTextContent(),
+ top: box.top - origin.top + parseFloat(style.paddingTop || '0'),
+ left:
+ (isRightToLeft ? box.right - CHECKBOX_SIZE : box.left) -
+ origin.left,
+ },
+ ];
+ }),
+ );
+ setPlacements(current =>
+ samePlacements(current, next) ? current : next,
+ );
+ };
+ const schedule = () => {
+ if (frame === 0) {
+ frame = requestAnimationFrame(measure);
+ }
+ };
+ const observer =
+ typeof ResizeObserver === 'undefined'
+ ? null
+ : new ResizeObserver(schedule);
+ const unregisterRoot = editor.registerRootListener(root => {
+ observer?.disconnect();
+ if (root != null) {
+ observer?.observe(root);
+ }
+ schedule();
+ });
+ const unregisterUpdate = editor.registerUpdateListener(schedule);
+ window.addEventListener('resize', schedule);
+ schedule();
+ return () => {
+ cancelAnimationFrame(frame);
+ observer?.disconnect();
+ unregisterRoot();
+ unregisterUpdate();
+ window.removeEventListener('resize', schedule);
+ };
+ }, [editor, idPrefix]);
+
+ return (
+ <>
+ {placements.map(placement => (
+ <div
+ key={placement.key}
+ id={`${idPrefix}-task-${placement.key}`}
+ data-richtext-task-checkbox=""
+ {...stylex.props(
+ styles.checkbox,
+ styles.placement(placement.top, placement.left),
+ )}>
+ <CheckboxInput
+ ref={(input: HTMLInputElement | null) => {
+ // No tab stop after the document; see the file header.
+ if (input != null) {
+ input.tabIndex = -1;
+ }
+ }}
+ size="sm"
+ label={placement.label}
+ isLabelHidden
+ value={placement.checked}
+ isReadOnly={isReadOnly}
+ onChange={(checked: boolean) => {
+ editor.update(() => {
+ const node = $getNodeByKey(placement.key);
+ if ($isListItemNode(node)) {
+ $setTaskState(node, checked ? 'checked' : 'unchecked');
+ }
+ });
+ }}
+ />
+ </div>
+ ))}
+ </>
+ );
+}
diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
index 272ebf211d..4ead436dbe 100644
--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
@@ -342,6 +342,217 @@ test('a rule at either edge of the document adds no outer margin', async ({
]);
});
+// spec:AST-061 FR5: each task item has one real checkbox where core
+// Markdown's is, the item stays a list item, and every list row has one
+// marker.
+test('side by side: task items have one checkbox each, and list rows one marker each', async ({
+ page,
+}) => {
+ const errors = await openStory(page, STORY.sideBySide, DESKTOP);
+ await waitForDocument(page, MARKDOWN);
+ await waitForDocument(page, RICH_TEXT);
+ await expect(
+ page.locator(`${RICH_TEXT} [data-richtext-task-checkbox] input`),
+ ).toHaveCount(2);
+ const layout = (selector: string) =>
+ page.evaluate(surface => {
+ const block = document.querySelector(
+ `${surface} [data-parity-block="list-task"]`,
+ );
+ const origin = block?.getBoundingClientRect();
+ const boxes = [
+ ...document.querySelectorAll<HTMLInputElement>(
+ `${surface} input[type="checkbox"]`,
+ ),
+ ].filter(
+ box =>
+ box.closest('[data-parity-block="list-task"]') != null ||
+ box.closest('[data-richtext-task-checkbox]') != null,
+ );
+ const label = [...(block?.querySelectorAll('li span') ?? [])].find(span =>
+ span.textContent?.startsWith('Open task'),
+ );
+ const rows = [
+ ...(document
+ .querySelector(`${surface} [data-parity-block="list-unordered"]`)
+ ?.querySelectorAll('li') ?? []),
+ ];
+ return {
+ checked: boxes.map(box => box.checked),
+ box: boxes[0]
+ ? Math.round(
+ (boxes[0].parentElement?.getBoundingClientRect().left ?? 0) -
+ (origin?.left ?? 0),
+ )
+ : null,
+ textStart: Math.round(
+ (label?.getBoundingClientRect().left ?? 0) - (origin?.left ?? 0),
+ ),
+ checkboxItems: block?.querySelectorAll('li[role="checkbox"]').length,
+ rowMarkers: rows.filter(
+ row => getComputedStyle(row).listStyleType !== 'none',
+ ).length,
+ rowsWithText: rows.filter(row => row.querySelector('ul, ol') == null)
+ .length,
+ };
+ }, selector);
+ const markdown = await layout(MARKDOWN);
+ const richText = await layout(RICH_TEXT);
+ expect(richText.checked).toEqual([false, true]);
+ expect(richText.checked).toEqual(markdown.checked);
+ // The checkbox and the text sit where core Markdown's do.
+ expect(
+ Math.abs((richText.box ?? 0) - (markdown.box ?? 0)),
+ ).toBeLessThanOrEqual(1);
+ expect(Math.abs(richText.textStart - markdown.textStart)).toBeLessThanOrEqual(
+ 1,
+ );
+ // The item is a list item, not a checkbox of its own.
+ expect(richText.checkboxItems).toBe(0);
+ // One marker per row with text; a wrapper around a nested list has none.
+ expect(richText.rowMarkers).toBe(richText.rowsWithText);
+ // The editor's checkbox checks its item.
+ const first = page
+ .locator(`${RICH_TEXT} [data-richtext-task-checkbox] input`)
+ .first();
+ await first.click();
+ await expect(first).toBeChecked();
+ expect(errors).toEqual([]);
+});
+
+// spec:AST-061 FR5: each task item exposes its checkbox and state inside
+// the item in the accessibility tree, the read-only checkboxes take no tab
+// stop between the view's links, and the editor checks an item by keyboard
+// (Mod+Enter) and undoes it.
+test('task items own their checkboxes, keep link tab order, and toggle by keyboard', 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')
+ .fill(
+ '[before](https://example.com/before)\n\n- [ ] Open task\n- [x] Done task\n - [ ] Nested task\n\n[after](https://example.com/after)',
+ );
+ await expect(page.locator('[data-richtext-task-checkbox] input')).toHaveCount(
+ 6,
+ );
+ // Chrome's accessibility tree: each task item holds one checkbox with the
+ // item's state, in document order, in the editor and the view.
+ const client = await page.context().newCDPSession(page);
+ const {nodes} = (await client.send('Accessibility.getFullAXTree')) as {
+ nodes: Array<{
+ nodeId: string;
+ role?: {value?: string};
+ childIds?: Array<string>;
+ properties?: Array<{name: string; value: {value?: unknown}}>;
+ }>;
+ };
+ const byId = new Map(nodes.map(node => [node.nodeId, node]));
+ const checkedOf = (node: (typeof nodes)[number]) =>
+ node.properties?.find(property => property.name === 'checked')?.value.value;
+ // The checkboxes inside one item, not inside the items nested in it.
+ const checkboxesIn = (id: string): Array<unknown> => {
+ const node = byId.get(id);
+ if (node == null || node.role?.value === 'listitem') {
+ return [];
+ }
+ if (node.role?.value === 'checkbox') {
+ return [checkedOf(node)];
+ }
+ return (node.childIds ?? []).flatMap(checkboxesIn);
+ };
+ const itemStates = nodes
+ .filter(node => node.role?.value === 'listitem')
+ .map(node => (node.childIds ?? []).flatMap(checkboxesIn))
+ .filter(states => states.length > 0);
+ // Six task items (three per surface), each holding exactly one checkbox;
+ // two are checked. Which item owns which checkbox is unit-tested.
+ expect(itemStates.map(states => states.length)).toEqual([1, 1, 1, 1, 1, 1]);
+ expect(itemStates.flat().map(String).sort()).toEqual([
+ 'false',
+ 'false',
+ 'false',
+ 'false',
+ 'true',
+ 'true',
+ ]);
+ // In the view, Tab goes from the link before the list to the link after it.
+ const view = page.locator('[contenteditable="false"]').filter({
+ has: page.locator('a'),
+ });
+ await view.getByRole('link', {name: 'before'}).focus();
+ await page.keyboard.press('Tab');
+ await expect(view.getByRole('link', {name: 'after'})).toBeFocused();
+ // In the editor, Mod+Enter checks the item holding the caret; undo reverts.
+ const editor = page.locator('[contenteditable="true"]').first();
+ await editor.getByText('Open task').click();
+ await page.keyboard.press('ControlOrMeta+Enter');
+ const editorBoxes = page
+ .locator('[data-richtext-task-checkbox] input')
+ .first();
+ await expect(editorBoxes).toBeChecked();
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect(editorBoxes).not.toBeChecked();
+ // Task and plain items written together are one list: one marker for each
+ // plain item, one checkbox for each task, and no gap between them.
+ await page
+ .locator('textarea')
+ .fill('- [ ] Task one\n- Plain item\n- [x] Task two');
+ await expect(page.locator('[data-richtext-task-checkbox] input')).toHaveCount(
+ 4,
+ );
+ const mixed = await page.evaluate(() =>
+ [...document.querySelectorAll('[data-lexical-editor]')].map(root => {
+ const lists = root.querySelectorAll(':scope > ul');
+ const rows = [...root.querySelectorAll(':scope > ul > li')];
+ return {
+ lists: lists.length,
+ markers: rows.map(row => getComputedStyle(row).listStyleType),
+ owned: rows.map(row => row.hasAttribute('aria-owns')),
+ pitch: rows
+ .slice(1)
+ .map(
+ (row, index) =>
+ row.getBoundingClientRect().top -
+ rows[index].getBoundingClientRect().top,
+ ),
+ };
+ }),
+ );
+ for (const surface of mixed) {
+ expect(surface.lists).toBe(1);
+ expect(surface.markers).toEqual(['none', 'disc', 'none']);
+ expect(surface.owned).toEqual([true, false, true]);
+ // Every row the same pitch: no block gap splits the list.
+ expect(new Set(surface.pitch.map(Math.round)).size).toBe(1);
+ }
+ // Enter at the end of a checked task makes a new, unchecked task the list
+ // owns; undo removes it and redo brings it back unchecked.
+ const boxes = page.locator('[data-richtext-task-checkbox] input');
+ await editor.getByText('Task two').click();
+ await page.keyboard.press('End');
+ await page.keyboard.press('Enter');
+ await page.keyboard.type('Task three');
+ await expect(boxes).toHaveCount(5);
+ await expect(boxes.nth(1)).toBeChecked();
+ await expect(boxes.nth(2)).not.toBeChecked();
+ await expect(editor.locator('li[aria-owns]')).toHaveCount(3);
+ for (let undo = 0; undo < 3 && (await boxes.count()) > 4; undo++) {
+ await page.keyboard.press('ControlOrMeta+z');
+ }
+ await expect(boxes).toHaveCount(4);
+ await page.keyboard.press('ControlOrMeta+Shift+z');
+ await expect(boxes).toHaveCount(5);
+ await expect(boxes.nth(2)).not.toBeChecked();
+ // The view's checkboxes are read-only.
+ const viewBox = page.locator('[data-richtext-task-checkbox] input').nth(3);
+ await expect(viewBox).toHaveAttribute('aria-readonly', 'true');
+});
+
// spec:AST-061 FR8: a fenced code block has the same frame and header on
// both surfaces, so the code sits at the same place; the header is not part
// of the editable text.
diff --git a/packages/richtext/src/editorTheme.ts b/packages/richtext/src/editorTheme.ts
index f482328553..85dd04f47b 100644
--- a/packages/richtext/src/editorTheme.ts
+++ b/packages/richtext/src/editorTheme.ts
@@ -43,6 +43,7 @@ const MINOR_HEADING_AFTER = `calc(${spacingVars['--spacing-2']})`;
const TEXT_BLOCK_SPACE = `calc(${spacingVars['--spacing-3']})`;
const WIDE_BLOCK_SPACE = `calc(${spacingVars['--spacing-4']})`;
const LIST_ITEM_SPACE = `calc(${spacingVars['--spacing-1']})`;
+const TASK_BOX_SIZE = '20px';
const LIST_ROW_GAP = `calc(${spacingVars['--spacing-0-5']})`;
const LIST_ROW_FLUSH = `calc(${spacingVars['--spacing-0']})`;
const NESTED_LIST_SPACE = `calc(${spacingVars['--spacing-2']})`;
@@ -238,11 +239,10 @@ const editorTheme = stylex.create({
olDepth3: {
listStyleType: 'lower-roman',
},
- // Checklists render as a <ul listtype="check">; Lexical draws checkbox
- // affordances on the list items, so suppress the disc marker here.
+ // Lexical's own checkbox lists (`<ul __lexicallisttype="check">`): every
+ // item is a task, laid out like the task items of a bulleted list below.
checklist: {
listStyleType: 'none',
- paddingInlineStart: spacingVars['--spacing-2'],
},
// List items space like core Markdown's compact list rows: 4px padding and
// a 2px gap between rows. Lexical puts a nested list in an item of its own
@@ -266,10 +266,23 @@ const editorTheme = stylex.create({
':last-child': spacingVars['--spacing-0'],
},
// Ensure the marker is shown (some CSS resets set list-style: none on li).
+ // A task item (TaskCheckboxPlugin marks it) shows a checkbox instead.
listStyleType: {
default: 'inherit',
':has(ul)': 'none',
':has(ol)': 'none',
+ ':is([data-richtext-task])': 'none',
+ },
+ // A task item's text starts 28px in from the list's edge, after core's
+ // small checkbox (20px) and its 8px gap, like core Markdown's task lists:
+ // the item cancels the list's bullet indent and pads for the checkbox.
+ marginInlineStart: {
+ default: LIST_ROW_FLUSH,
+ ':is([data-richtext-task])': `calc(-1 * ${spacingVars['--spacing-6']})`,
+ },
+ paddingInlineStart: {
+ default: LIST_ROW_FLUSH,
+ ':is([data-richtext-task])': `calc(${TASK_BOX_SIZE} + ${spacingVars['--spacing-2']})`,
},
},
link: {
diff --git a/packages/richtext/src/markdownListExport.ts b/packages/richtext/src/markdownListExport.ts
index 48aa318b3a..2a8c7841c1 100644
--- a/packages/richtext/src/markdownListExport.ts
+++ b/packages/richtext/src/markdownListExport.ts
@@ -6,7 +6,8 @@
* (ElementTransformer).
* @output Exports LIST_EXPORT, which writes lists the way Lexical's list
* transformers do except for nesting: a nested list is indented to its
- * parent item's content column instead of four spaces per level.
+ * parent item's content column instead of four spaces per level, and each
+ * task item writes `[ ]` or `[x]` (markdownTaskList.ts).
* @position Part of DEFAULT_TRANSFORMERS (markdownTable.ts), ahead of
* Lexical's list transformers, which still import. Import reads nesting the
* CommonMark way (markdownListIndentation.ts), so a child written four
@@ -23,6 +24,7 @@ import {
} from '@lexical/list';
import type {ElementTransformer} from '@lexical/markdown';
import type {ElementNode} from 'lexical';
+import {$getTaskState} from './markdownTaskList';
/** The bullet Lexical recorded for a list on import (`-`, `*`, or `+`). */
function bulletOf(list: ListNode): string {
@@ -52,8 +54,9 @@ function exportList(
}
const marker =
type === 'number' ? `${list.getStart() + index}. ` : `${bulletOf(list)} `;
- const checkbox =
- type === 'check' ? `[${item.getChecked() === true ? 'x' : ' '}] ` : '';
+ // A task item, in any bulleted list, writes its box.
+ const task = type === 'number' ? null : $getTaskState(item);
+ const checkbox = task == null ? '' : `[${task === 'checked' ? 'x' : ' '}] `;
let text = exportChildren(item);
if (type !== 'number') {
// As Lexical does: keep `1. ` at the start of a bullet item literal.
diff --git a/packages/richtext/src/markdownTable.ts b/packages/richtext/src/markdownTable.ts
index 1cc303c9e8..de5bd37d29 100644
--- a/packages/richtext/src/markdownTable.ts
+++ b/packages/richtext/src/markdownTable.ts
@@ -40,6 +40,7 @@ import type {ElementFormatType} from 'lexical';
import {HARD_LINE_BREAK} from './markdownHardLineBreak';
import {THEMATIC_BREAK} from './markdownThematicBreak';
import {LIST_EXPORT} from './markdownListExport';
+import {TASK_LIST} from './markdownTaskList';
/**
* Cells hold inline Markdown only, so they are imported and exported with the
@@ -238,13 +239,16 @@ export const TABLE: MultilineElementTransformer = {
/**
* The editor's default Markdown transformers: thematic breaks, list export
- * that nests to each parent's content column, 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 rather than a list item.
+ * 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
+ * rather than a list item, and task items before bullets so `- [ ] text` is a
+ * task rather than a bullet that starts with `[ ]`.
*/
export const DEFAULT_TRANSFORMERS: ReadonlyArray<Transformer> = [
THEMATIC_BREAK,
LIST_EXPORT,
+ TASK_LIST,
...TRANSFORMERS,
HARD_LINE_BREAK,
TABLE,
diff --git a/packages/richtext/src/markdownTaskList.test.tsx b/packages/richtext/src/markdownTaskList.test.tsx
new file mode 100644
index 0000000000..f4e312ee1b
--- /dev/null
+++ b/packages/richtext/src/markdownTaskList.test.tsx
@@ -0,0 +1,445 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {createRef} from 'react';
+import {act, fireEvent, render, waitFor} from '@testing-library/react';
+import {createHeadlessEditor} from '@lexical/headless';
+import {$isListItemNode, registerList} from '@lexical/list';
+import {registerRichText} from '@lexical/rich-text';
+import {
+ $getRoot,
+ $getSelection,
+ $isRangeSelection,
+ INSERT_PARAGRAPH_COMMAND,
+ SKIP_SCROLL_INTO_VIEW_TAG,
+ UNDO_COMMAND,
+} from 'lexical';
+import {$setTaskState, registerTaskListEditing} from './markdownTaskList';
+import {parseMarkdown} from '@astryxdesign/core/Markdown/parser';
+import {DEFAULT_NODES} from './editorNodes';
+import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';
+import {RichTextView} from './RichTextView';
+import {
+ editorStateJSONToMarkdown,
+ markdownToEditorStateJSON,
+} from './markdownSerializers';
+
+interface SerializedNode {
+ readonly type: string;
+ readonly listType?: string;
+ readonly checked?: boolean;
+ readonly text?: string;
+ readonly $?: {
+ readonly astryxTask?: boolean;
+ readonly astryxTaskChecked?: boolean;
+ };
+ readonly children?: ReadonlyArray<SerializedNode>;
+}
+
+/** Each list item's checked state in document order, as RichText imports it. */
+function richTextTasks(markdown: string): Array<boolean | undefined> {
+ const {root} = JSON.parse(markdownToEditorStateJSON(markdown)) as {
+ root: SerializedNode;
+ };
+ const states: Array<boolean | undefined> = [];
+ const visit = (node: SerializedNode, listType?: string) => {
+ if (node.type === 'listitem') {
+ const isWrapper =
+ node.children?.length === 1 && node.children[0].type === 'list';
+ if (!isWrapper) {
+ states.push(
+ listType === 'check'
+ ? node.checked === true
+ : node.$?.astryxTask === true
+ ? node.$.astryxTaskChecked === true
+ : undefined,
+ );
+ }
+ }
+ for (const child of node.children ?? []) {
+ visit(child, node.type === 'list' ? node.listType : listType);
+ }
+ };
+ visit(root);
+ return states;
+}
+
+/** Each list item's checked state in document order, as core Markdown parses it. */
+function coreTasks(markdown: string): Array<boolean | undefined> {
+ const states: Array<boolean | undefined> = [];
+ const visit = (nodes: ReadonlyArray<unknown>) => {
+ for (const node of nodes as ReadonlyArray<{
+ type: string;
+ children?: ReadonlyArray<unknown>;
+ items?: ReadonlyArray<{
+ checked?: boolean;
+ children?: ReadonlyArray<unknown>;
+ }>;
+ }>) {
+ if (node.type === 'list') {
+ for (const item of node.items ?? []) {
+ states.push(item.checked);
+ visit(item.children ?? []);
+ }
+ } else if (Array.isArray(node.children)) {
+ visit(node.children);
+ }
+ }
+ };
+ visit(parseMarkdown(markdown) as ReadonlyArray<unknown>);
+ return states;
+}
+
+function topLevelTypes(markdown: string): Array<string> {
+ const {root} = JSON.parse(markdownToEditorStateJSON(markdown)) as {
+ root: SerializedNode;
+ };
+ return (root.children ?? []).map(node =>
+ node.type === 'list' ? `list:${node.listType}` : node.type,
+ );
+}
+
+function editAndExport(markdown: string, edit: () => void): string {
+ const editor = createHeadlessEditor({
+ namespace: 'astryx-task-list-test',
+ nodes: [...DEFAULT_NODES],
+ onError(error: Error) {
+ throw error;
+ },
+ });
+ editor.setEditorState(
+ editor.parseEditorState(markdownToEditorStateJSON(markdown)),
+ );
+ editor.update(edit, {discrete: true});
+ return editorStateJSONToMarkdown(
+ JSON.stringify(editor.getEditorState().toJSON()),
+ );
+}
+
+describe('task lists (spec:AST-061 FR5)', () => {
+ it('reads exactly the task items core Markdown reads', () => {
+ for (const markdown of [
+ '- [ ] open\n- [x] done\n',
+ '* [x] star\n',
+ '+ [X] plus, uppercase\n',
+ '- [ ] a\r\n- [X] b\r\n',
+ '- [ ] parent\n - [x] child\n',
+ '- plain\n- [ ] task\n',
+ '- [] empty brackets\n',
+ '- [ ]no space\n',
+ '- [y] other letter\n',
+ ]) {
+ expect(richTextTasks(markdown), JSON.stringify(markdown)).toEqual(
+ coreTasks(markdown),
+ );
+ }
+ // Uppercase X is checked.
+ expect(richTextTasks('+ [X] plus\n')).toEqual([true]);
+ // Brackets with no bullet stay a paragraph.
+ expect(topLevelTypes('[ ] not a task\n')).toEqual(['paragraph']);
+ expect(topLevelTypes('[x] not a task\n')).toEqual(['paragraph']);
+ // An empty pair of brackets is an ordinary bullet that shows them.
+ expect(topLevelTypes('- [] text\n')).toEqual(['list:bullet']);
+ expect(
+ editorStateJSONToMarkdown(markdownToEditorStateJSON('- [] text\n')),
+ ).toBe('- [] text\n');
+ });
+
+ it('keeps task and plain items written together in one list', () => {
+ for (const markdown of [
+ '- [ ] task\n- plain\n- [x] done\n',
+ '- plain\n- [ ] task\n',
+ '- [ ] task\r\n- plain\r\n',
+ // Loose: blank lines between items still make one list.
+ '- [ ] task\n\n- plain\n\n- [X] done\n',
+ ]) {
+ expect(topLevelTypes(markdown), JSON.stringify(markdown)).toEqual([
+ 'list:bullet',
+ ]);
+ expect(richTextTasks(markdown), JSON.stringify(markdown)).toEqual(
+ coreTasks(markdown),
+ );
+ expect(
+ editorStateJSONToMarkdown(markdownToEditorStateJSON(markdown)),
+ JSON.stringify(markdown),
+ ).toBe(markdown);
+ }
+ // Nested: a plain child under a task, and a task child under a plain item.
+ const nested =
+ '- [ ] parent\n - plain child\n- plain\n - [x] task child\n';
+ expect(richTextTasks(nested)).toEqual(coreTasks(nested));
+ // Edited, the list writes each item as it is.
+ const edited = editAndExport('- [ ] task\n- plain\n', () => {
+ const plain = $getRoot()
+ .getAllTextNodes()
+ .find(node => node.getTextContent() === 'plain');
+ plain?.setTextContent('plain!');
+ });
+ expect(edited).toBe('- [ ] task\n- plain!\n');
+ expect(topLevelTypes(edited)).toEqual(['list:bullet']);
+ });
+
+ it('keeps untouched task lists exact and writes edited ones as GFM (spec:AST-062)', () => {
+ for (const markdown of [
+ '- [ ] Open task\n- [x] Completed task\n',
+ '* [X] Upper\r\n+ [ ] Plus\r\n',
+ ]) {
+ expect(
+ editorStateJSONToMarkdown(markdownToEditorStateJSON(markdown)),
+ ).toBe(markdown);
+ }
+ const edited = editAndExport('- [ ] Open task\n- [X] Done\n', () => {
+ const open = $getRoot()
+ .getAllTextNodes()
+ .find(node => node.getTextContent() === 'Open task');
+ open?.setTextContent('Open task!');
+ });
+ expect(edited).toBe('- [ ] Open task!\n- [x] Done\n');
+ expect(richTextTasks(edited)).toEqual([false, true]);
+ // A task turned plain, a plain item turned task, and back, in one list.
+ const items = () =>
+ $getRoot()
+ .getAllTextNodes()
+ .map(node => node.getParent())
+ .filter($isListItemNode);
+ const toPlain = editAndExport('- [ ] a\n- [x] b\n', () => {
+ $setTaskState(items()[0], null);
+ });
+ expect(toPlain).toBe('- a\n- [x] b\n');
+ expect(richTextTasks(toPlain)).toEqual([undefined, true]);
+ const toTask = editAndExport(toPlain, () => {
+ $setTaskState(items()[0], 'unchecked');
+ $setTaskState(items()[1], null);
+ });
+ expect(toTask).toBe('- [ ] a\n- b\n');
+ expect(richTextTasks(toTask)).toEqual([false, undefined]);
+ });
+
+ it('makes an unchecked task when Enter splits or ends a task, and a plain item after a plain one', () => {
+ /**
+ * Imports `markdown` into an editor with the editor's Enter handling,
+ * puts the caret in the text `needle` (at its end, or at `offset`),
+ * presses Enter `presses` times, types `typed`, and exports.
+ */
+ const enter = (
+ markdown: string,
+ needle: string,
+ {
+ offset,
+ presses = 1,
+ typed = '',
+ }: {offset?: number; presses?: number; typed?: string} = {},
+ ): string => {
+ const editor = createHeadlessEditor({
+ namespace: 'astryx-task-enter',
+ nodes: [...DEFAULT_NODES],
+ onError(error: Error) {
+ throw error;
+ },
+ });
+ registerRichText(editor);
+ registerList(editor);
+ registerTaskListEditing(editor);
+ editor.setEditorState(
+ editor.parseEditorState(markdownToEditorStateJSON(markdown)),
+ );
+ editor.update(
+ () => {
+ const text = $getRoot()
+ .getAllTextNodes()
+ .find(node => node.getTextContent() === needle);
+ const at = offset ?? needle.length;
+ text?.select(at, at);
+ for (let press = 0; press < presses; press++) {
+ editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, undefined);
+ }
+ const selection = $getSelection();
+ if (typed !== '' && $isRangeSelection(selection)) {
+ selection.insertText(typed);
+ }
+ },
+ {discrete: true},
+ );
+ return editorStateJSONToMarkdown(
+ JSON.stringify(editor.getEditorState().toJSON()),
+ );
+ };
+ // At the end of a checked or an unchecked task.
+ expect(enter('- [x] done\n', 'done', {typed: 'new'})).toBe(
+ '- [x] done\n- [ ] new\n',
+ );
+ expect(enter('- [ ] open\n', 'open', {typed: 'new'})).toBe(
+ '- [ ] open\n- [ ] new\n',
+ );
+ // In the middle of a checked task: the text after the caret moves to an
+ // unchecked task; the checked one keeps the rest.
+ expect(enter('- [x] doneafter\n', 'doneafter', {offset: 4})).toBe(
+ '- [x] done\n- [ ] after\n',
+ );
+ // At the start of a checked task: the text keeps its state, and the new,
+ // empty item before it is unchecked.
+ expect(enter('- [x] done\n', 'done', {offset: 0})).toBe(
+ '- [ ] \n- [x] done\n',
+ );
+ // Between tasks, and nested.
+ expect(enter('- [x] one\n- [x] two\n', 'one', {typed: 'new'})).toBe(
+ '- [x] one\n- [ ] new\n- [x] two\n',
+ );
+ expect(
+ enter('- [ ] parent\n - [x] child\n', 'child', {typed: 'new'}),
+ ).toBe('- [ ] parent\n - [x] child\n - [ ] new\n');
+ // A plain item makes a plain item, beside tasks too.
+ expect(enter('- [x] done\n- plain\n', 'plain', {typed: 'new'})).toBe(
+ '- [x] done\n- plain\n- new\n',
+ );
+ // Enter in the new, empty task leaves the list, as for any list item.
+ expect(enter('- [x] done\n', 'done', {presses: 2, typed: 'new'})).toBe(
+ '- [x] done\n\nnew\n',
+ );
+ // Nothing looks at content: an empty checked task written in the source
+ // stays checked.
+ const emptyChecked = '- [x] \n- [ ] b\n';
+ expect(richTextTasks(emptyChecked)).toEqual(coreTasks(emptyChecked));
+ });
+
+ it('gives each task item one checkbox it owns, read-only in the view and without a tab stop', async () => {
+ const value = markdownToEditorStateJSON(
+ '- [ ] Open task\n- [x] Completed task\n',
+ );
+ const {container} = render(
+ <>
+ <div data-surface="editor">
+ <RichTextEditor label="Notes" defaultValue={value} />
+ </div>
+ <div data-surface="view">
+ <RichTextView value={value} />
+ </div>
+ </>,
+ );
+ const boxes = (surface: string) => [
+ ...container.querySelectorAll<HTMLInputElement>(
+ `[data-surface="${surface}"] [data-richtext-task-checkbox] input[type="checkbox"]`,
+ ),
+ ];
+ await waitFor(() => {
+ expect(boxes('editor').map(box => box.checked)).toEqual([false, true]);
+ expect(boxes('view').map(box => box.checked)).toEqual([false, true]);
+ });
+ for (const surface of ['editor', 'view']) {
+ const items = [
+ ...container.querySelectorAll(
+ `[data-surface="${surface}"] [data-lexical-editor] li`,
+ ),
+ ];
+ // Each item is a list item that owns its checkbox.
+ expect(items.map(item => item.getAttribute('role'))).toEqual([
+ null,
+ null,
+ ]);
+ items.forEach((item, index) => {
+ const owned = item.getAttribute('aria-owns');
+ expect(owned).toBeTruthy();
+ const box = container.querySelector<HTMLInputElement>(
+ `[id="${owned}"] input`,
+ );
+ expect(box).toBe(boxes(surface)[index]);
+ expect(
+ box?.getAttribute('aria-label') ?? box?.labels?.[0]?.textContent,
+ ).toBeTruthy();
+ });
+ for (const box of boxes(surface)) {
+ expect(box.tabIndex).toBe(-1);
+ expect(box.closest('[contenteditable]')).toBeNull();
+ }
+ }
+ for (const box of boxes('view')) {
+ expect(box.getAttribute('aria-readonly')).toBe('true');
+ }
+ });
+
+ it('checks an item from its checkbox or with Mod+Enter, and undo reverts it', async () => {
+ const ref = createRef<RichTextEditorRef>();
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ ref={ref}
+ defaultValue={markdownToEditorStateJSON(
+ '- [ ] Open task\n- [ ] Next\n',
+ )}
+ />,
+ );
+ const box = await waitFor(() => {
+ const input = container.querySelector<HTMLInputElement>(
+ '[data-richtext-task-checkbox] input[type="checkbox"]',
+ );
+ expect(input).not.toBeNull();
+ return input as HTMLInputElement;
+ });
+ fireEvent.click(box);
+ await waitFor(() =>
+ expect(ref.current?.getMarkdown()).toBe('- [x] Open task\n- [ ] Next\n'),
+ );
+ // Undo reverts the toggle.
+ const editor = ref.current?.getEditor();
+ await act(async () => {
+ editor?.dispatchCommand(UNDO_COMMAND, undefined);
+ });
+ await waitFor(() =>
+ expect(ref.current?.getMarkdown()).toBe('- [ ] Open task\n- [ ] Next\n'),
+ );
+ // Mod+Enter in the second item checks it.
+ await act(async () => {
+ editor?.update(
+ () => {
+ const items = $getRoot()
+ .getAllTextNodes()
+ .map(node => node.getParent())
+ .filter($isListItemNode);
+ items[1]?.selectEnd();
+ },
+ // jsdom lays nothing out, so Lexical must not scroll to the caret.
+ {discrete: true, tag: SKIP_SCROLL_INTO_VIEW_TAG},
+ );
+ });
+ const root = container.querySelector<HTMLElement>('[data-lexical-editor]');
+ if (root == null) {
+ throw new Error('No editor root');
+ }
+ fireEvent.keyDown(root, {key: 'Enter', code: 'Enter', ctrlKey: true});
+ await waitFor(() =>
+ expect(ref.current?.getMarkdown()).toBe('- [ ] Open task\n- [x] Next\n'),
+ );
+ // Enter after the checked task makes an unchecked task the list owns.
+ await act(async () => {
+ editor?.update(
+ () => {
+ const items = $getRoot()
+ .getAllTextNodes()
+ .map(node => node.getParent())
+ .filter($isListItemNode);
+ items[1]?.selectEnd();
+ $getSelection()?.insertText('');
+ editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, undefined);
+ $getSelection()?.insertText('Third');
+ },
+ {discrete: true, tag: SKIP_SCROLL_INTO_VIEW_TAG},
+ );
+ });
+ await waitFor(() =>
+ expect(ref.current?.getMarkdown()).toBe(
+ '- [ ] Open task\n- [x] Next\n- [ ] Third\n',
+ ),
+ );
+ const third = await waitFor(() => {
+ const items = container.querySelectorAll('[data-lexical-editor] li');
+ expect(items).toHaveLength(3);
+ const owned = items[2].getAttribute('aria-owns');
+ const input = container.querySelector<HTMLInputElement>(
+ `[id="${owned}"] input`,
+ );
+ expect(input).not.toBeNull();
+ return input;
+ });
+ expect(third?.checked).toBe(false);
+ });
+});
diff --git a/packages/richtext/src/markdownTaskList.ts b/packages/richtext/src/markdownTaskList.ts
new file mode 100644
index 0000000000..1beebd859c
--- /dev/null
+++ b/packages/richtext/src/markdownTaskList.ts
@@ -0,0 +1,222 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file markdownTaskList.ts
+ * @input Uses lexical (node state), @lexical/list, and @lexical/markdown
+ * (ElementTransformer).
+ * @output Exports TASK_LIST, the transformer that imports GFM task list
+ * items; $getTaskState / $setTaskState, which read and set whether a list
+ * item is a task and whether it is checked; and registerTaskListEditing,
+ * the editor's Enter and Mod+Enter behavior for task items.
+ * @position Part of DEFAULT_TRANSFORMERS (markdownTable.ts), ahead of
+ * Lexical's bullet transformer. It reads exactly the task items core
+ * Markdown reads (spec:AST-061 FR5): a `-`, `*`, or `+` bullet, one space,
+ * `[ ]`, `[x]`, or `[X]`, and a space. Lexical's own CHECK_LIST also takes a
+ * line with no bullet, `[]`, and missing spaces, and reads `[X]` as
+ * unchecked; those stay a paragraph or an ordinary bullet here.
+ *
+ * A task is a property of an item, not of its list: GFM lets task and
+ * plain items share one list, and Lexical keeps a checked state only in its
+ * all-checkbox lists. So task items live in ordinary bullet lists, beside
+ * plain items, and carry their state as node state; LIST_EXPORT writes
+ * `[ ]` or `[x]` for each task item. TaskCheckboxPlugin draws them, and
+ * registers registerTaskListEditing in the editor.
+ */
+
+import {
+ $createListItemNode,
+ $createListNode,
+ $isListItemNode,
+ $isListNode,
+ ListItemNode,
+ ListNode,
+} from '@lexical/list';
+import type {ElementTransformer} from '@lexical/markdown';
+import {$findMatchingParent, mergeRegister} from '@lexical/utils';
+import {
+ $getSelection,
+ $getState,
+ $isRangeSelection,
+ $setState,
+ COMMAND_PRIORITY_LOW,
+ createState,
+ INSERT_PARAGRAPH_COMMAND,
+ KEY_ENTER_COMMAND,
+ type LexicalEditor,
+} from 'lexical';
+
+export type TaskState = 'checked' | 'unchecked';
+
+// Whether an item is a task. A copy keeps it, so the item Enter makes after
+// a task is a task too.
+const taskKind = createState('astryxTask', {
+ parse: (value: unknown): boolean => value === true,
+});
+
+// Whether a task is checked.
+const taskChecked = createState('astryxTaskChecked', {
+ parse: (value: unknown): boolean => value === true,
+});
+
+/**
+ * Whether `item` is a task and whether it is checked; null for a plain item.
+ * An item in one of Lexical's own checkbox lists is a task too.
+ */
+export function $getTaskState(item: ListItemNode): TaskState | null {
+ if ($getState(item, taskKind)) {
+ return $getState(item, taskChecked) ? 'checked' : 'unchecked';
+ }
+ const list = item.getParent();
+ if ($isListNode(list) && list.getListType() === 'check') {
+ return item.getChecked() === true ? 'checked' : 'unchecked';
+ }
+ return null;
+}
+
+/** Makes `item` a task in the given state, or a plain item for null. */
+export function $setTaskState(
+ item: ListItemNode,
+ state: TaskState | null,
+): void {
+ const list = item.getParent();
+ if ($isListNode(list) && list.getListType() === 'check') {
+ item.setChecked(state === 'checked');
+ return;
+ }
+ $setState(item, taskKind, state != null);
+ $setState(item, taskChecked, state === 'checked');
+}
+
+const TASK_ITEM = /^(\s*)([-*+])\s\[([ xX])\]\s/;
+
+/** Nesting depth from leading whitespace, counted as Lexical's lists do. */
+function indentOf(whitespace: string): number {
+ const tabs = whitespace.match(/\t/g)?.length ?? 0;
+ const spaces = whitespace.match(/ /g)?.length ?? 0;
+ return tabs + Math.floor(spaces / 4);
+}
+
+export const TASK_LIST: ElementTransformer = {
+ dependencies: [ListNode, ListItemNode],
+ // LIST_EXPORT writes every list, task items included.
+ export: () => null,
+ regExp: TASK_ITEM,
+ replace: (parentNode, children, match, isImport) => {
+ const item = $createListItemNode();
+ $setState(item, taskKind, true);
+ $setState(item, taskChecked, match[3] !== ' ');
+ // A task item joins the bullet list beside it, as a plain item does.
+ const previous = parentNode.getPreviousSibling();
+ const next = parentNode.getNextSibling();
+ if ($isListNode(next) && next.getListType() === 'bullet') {
+ const first = next.getFirstChild();
+ if (first == null) {
+ next.append(item);
+ } else {
+ first.insertBefore(item);
+ }
+ parentNode.remove();
+ } else if ($isListNode(previous) && previous.getListType() === 'bullet') {
+ previous.append(item);
+ parentNode.remove();
+ } else {
+ const list = $createListNode('bullet');
+ list.append(item);
+ parentNode.replace(list);
+ }
+ item.append(...children);
+ if (!isImport) {
+ item.select(0, 0);
+ }
+ const indent = indentOf(match[1]);
+ if (indent > 0) {
+ item.setIndent(indent);
+ }
+ },
+ type: 'element',
+};
+
+/** The task item holding the selection's anchor, if any. */
+function $selectedTaskItem(): ListItemNode | null {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) {
+ return null;
+ }
+ return $findMatchingParent(
+ selection.anchor.getNode(),
+ (node): node is ListItemNode =>
+ $isListItemNode(node) && $getTaskState(node) != null,
+ );
+}
+
+/**
+ * Task editing in an editor:
+ *
+ * - Enter in a task makes the new item a task, unchecked, as Lexical's own
+ * checkbox items do. Lexical copies the item to make the new one, state and
+ * all, so the new item's state is set here, where Enter makes it — never
+ * inferred later from content, which would uncheck a written `- [x]` with
+ * no text. Enter at the start of a task leaves its text, and its state, on
+ * the item that holds it, and puts the new, unchecked item before it. Enter
+ * in an empty task is left to the list, which ends the list there.
+ * - Mod+Enter checks or unchecks the task holding the caret.
+ */
+export function registerTaskListEditing(editor: LexicalEditor): () => void {
+ return mergeRegister(
+ editor.registerCommand(
+ INSERT_PARAGRAPH_COMMAND,
+ () => {
+ const selection = $getSelection();
+ const item = $selectedTaskItem();
+ if (
+ item == null ||
+ !$isRangeSelection(selection) ||
+ item.getTextContent().trim() === ''
+ ) {
+ return false;
+ }
+ const state = $getTaskState(item);
+ const isAtStart =
+ selection.isCollapsed() &&
+ selection.anchor.offset === 0 &&
+ (selection.anchor.getNode().is(item) ||
+ selection.anchor.getNode().is(item.getFirstDescendant()));
+ const created = selection.insertParagraph();
+ if (!$isListItemNode(created) || $getTaskState(created) == null) {
+ return true;
+ }
+ if (isAtStart) {
+ // The text moved to the new item: it keeps its state, and the item
+ // left empty before it is the new, unchecked one.
+ $setTaskState(created, state);
+ $setTaskState(item, 'unchecked');
+ } else {
+ $setTaskState(created, 'unchecked');
+ }
+ return true;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ editor.registerCommand(
+ KEY_ENTER_COMMAND,
+ event => {
+ const isModified =
+ event != null &&
+ (event.metaKey || event.ctrlKey) &&
+ !event.shiftKey &&
+ !event.altKey;
+ const item = isModified ? $selectedTaskItem() : null;
+ if (item == null) {
+ return false;
+ }
+ event?.preventDefault();
+ $setTaskState(
+ item,
+ $getTaskState(item) === 'checked' ? 'unchecked' : 'checked',
+ );
+ return true;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ );
+}