An open source design system that's fully customizable and agent ready
TypeScript
fix(Markdown): show each task item's checkbox in a list that mixes task and plain items (#7045)
Cindy Zhang0353bb2bbb27
diff --git a/.changeset/markdown-mixed-task-list.md b/.changeset/markdown-mixed-task-list.mdnew file mode 100644index 0000000000..207089a509--- /dev/null+++ b/.changeset/markdown-mixed-task-list.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+---++[fix] Markdown: a list that mixes task and plain items shows each task item's checkbox+@cixzhang++In a list such as `- [x] Done`, `- Plain`, `- [ ] Open`, each task item now shows its own read-only checkbox, checked or open and named by its text, where its marker would be, and each plain item keeps its marker; the list stays one list. Before, the task items lost their checked state and showed bullets. Lists of only task items are unchanged.diff --git a/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts b/apps/storybook/stories/RichTextEditor.markdownParityFixture.tsindex 8aaffeb6c3..04d2448baa 100644--- a/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts+++ b/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts@@ -10,7 +10,8 @@** Coverage: ATX headings 1-4; emphasis, strong, strikethrough, inline code,* titled and bare links; soft and hard line breaks; a blockquote; nested- * unordered (2-space) and ordered (3-space) lists; a GFM task list; a fenced+ * unordered (2-space) and ordered (3-space) lists; a GFM task list, and a+ * list that mixes task and plain items; a fenced* code block with an info string; a GFM table with column alignment; a* thematic break; backslash escapes and character references; a right-to-left* paragraph; and the Storybook demo plugins' mention, TODO, and callout syntax.@@ -123,6 +124,17 @@ export const MARKDOWN_PARITY_BLOCKS: readonly MarkdownParityBlock[] = ['```',),},+ {+ key: 'list-task-mixed',+ label: 'Task and plain items',+ probe: 'Mixed open task',+ // Not right after the task list, which it would continue as one list.+ markdown: lines(+ '- [ ] Mixed open task',+ '- Mixed plain item',+ '- [x] Mixed done task',+ ),+ },// Fences that show no language label, as core CodeBlock decides: no info// string, a blank one, and `plaintext`; and an unknown language, which// shows its name.diff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsxindex ce1b553ea6..fdee002012 100644--- a/packages/core/src/List/List.test.tsx+++ b/packages/core/src/List/List.test.tsx@@ -876,6 +876,40 @@ describe('List', () => {expect(container.querySelector('ul')).not.toBeNull();});+ it("draws a task item's read-only checkbox in place of its marker", () => {+ const {container} = render(+ <List listStyle="disc">+ <ListMarkerScope+ marker="disc"+ task={{isChecked: true, label: 'Done'}}>+ <ListItem label="Done" />+ </ListMarkerScope>+ <ListItem label="Plain" />+ </List>,+ );+ const checkbox = screen.getByRole('checkbox', {name: 'Done'});+ expect(checkbox).toBeChecked();+ expect(checkbox).toHaveAttribute('aria-readonly', 'true');+ const [task, plain] = container.querySelectorAll('li');+ expect(task?.contains(checkbox)).toBe(true);+ // The task item has no dot in its marker box; the plain item keeps it.+ expect(task?.querySelector(':scope > span > span:empty')).toBeNull();+ expect(plain?.querySelector(':scope > span > span:empty')).not.toBeNull();+ });++ it('draws no task checkbox in a list without markers', () => {+ render(+ <List>+ <ListMarkerScope+ marker="disc"+ task={{isChecked: true, label: 'Done'}}>+ <ListItem label="Done" />+ </ListMarkerScope>+ </List>,+ );+ expect(screen.queryByRole('checkbox')).toBeNull();+ });+it('keeps a numbered list ordered with a letter marker', () => {render(<List listStyle="decimal" start={3}>diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsxindex d10e53fd7f..455c4d036c 100644--- a/packages/core/src/List/ListContext.tsx+++ b/packages/core/src/List/ListContext.tsx@@ -7,7 +7,8 @@* @input Layer-scoped React context* @output Exports ListContext for sharing density, dividers, marker style,* and optional inline edge compensation between List and ListItem, and- * ListMarkerScope, which sets the marker for the items inside it+ * ListMarkerScope, which sets the marker for the items inside it, or a+ * task item's checkbox in its place* @position Internal context; consumed by List.tsx and ListItem.tsx*/@@ -24,6 +25,13 @@ export type ListMarkerStyle = 'none' | 'disc' | 'decimal' | 'circle';export type ListMarker ='disc' | 'circle' | 'square' | 'decimal' | 'lower-alpha' | 'lower-roman';+/** A task item's state, drawn as a read-only checkbox in the marker's place. */+export interface ListTaskMarker {+ readonly isChecked: boolean;+ /** The checkbox's accessible name: the item's text. */+ readonly label: string;+}+export interface ListContextValue {density: ListDensity;hasDividers: boolean;@@ -34,6 +42,12 @@ export interface ListContextValue {* ListMarkerScope; internal. Ignored when `listStyle` is `'none'`.*/marker?: ListMarker;+ /**+ * A task item's state, set by ListMarkerScope; internal. The item draws a+ * read-only checkbox instead of its marker. Ignored when `listStyle` is+ * `'none'`.+ */+ task?: ListTaskMarker;}export const ListContext = createContext<ListContextValue | null>(null);@@ -41,20 +55,23 @@ ListContext.displayName = 'ListContext';/*** Draws `marker` on the List items inside it, in place of the marker their- * List's `listStyle` names; internal, for Markdown's nested lists. Outside a- * List, or in a List without markers, it changes nothing.+ * List's `listStyle` names, or `task`'s read-only checkbox in place of either;+ * internal, for Markdown's nested lists and task items in mixed lists. Outside+ * a List, or in a List without markers, it changes nothing.*/export function ListMarkerScope({marker,+ task,children,}: {readonly marker: ListMarker;+ readonly task?: ListTaskMarker;readonly children: ReactNode;}): ReactNode {const context = use(ListContext);const value = useMemo(- () => (context == null ? null : {...context, marker}),- [context, marker],+ () => (context == null ? null : {...context, marker, task}),+ [context, marker, task],);return value == null ? (childrendiff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsxindex a272d53cff..ebf56340c4 100644--- a/packages/core/src/List/ListItem.tsx+++ b/packages/core/src/List/ListItem.tsx@@ -5,7 +5,8 @@/*** @file ListItem.tsx* @input Uses React, ReactNode, StyleXStyles, theme tokens, List edge compensation,- * and the marker a ListMarkerScope sets (Markdown's nested lists)+ * CheckboxInput, and the marker or task checkbox a ListMarkerScope sets+ * (Markdown's nested lists and the task items of mixed lists)* @output Exports ListItem component, ListItemProps type* @position Core implementation; consumed by List, index.ts, tested by List.test.tsx*@@ -30,6 +31,7 @@ import {} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';import {ListContext, type ListMarker} from './ListContext';+import {CheckboxInput} from '../CheckboxInput';import {mergeProps} from '../utils';import {Item} from '../Item';import {themeProps} from '../utils/themeProps';@@ -222,6 +224,20 @@ const markerStyles = stylex.create({},});+/** The width and height of CheckboxInput's small control. */+const TASK_CHECKBOX_SIZE = 20;++const taskMarkerStyles = stylex.create({+ // A task item's checkbox stands where the marker would, centered on the+ // item's first line, as a task list's checkboxes are.+ container: {+ alignSelf: 'flex-start',+ display: 'flex',+ flexShrink: 0,+ marginTop: `calc((1em * ${typeScaleVars['--text-body-leading']} - ${TASK_CHECKBOX_SIZE}px) / 2)`,+ },+});+/** The number styles, by marker. */const NUMBER_STYLES = {decimal: markerStyles.decimal,@@ -281,10 +297,23 @@ export function ListItem({const markerKind: ListMarker | null =listStyle === 'none' ? null : (ctx?.marker ?? listStyle);+ // A task item in a list with markers shows its checkbox instead.+ const task = markerKind == null ? undefined : ctx?.task;+const marker =- markerKind === 'disc' ||- markerKind === 'circle' ||- markerKind === 'square' ? (+ task != null ? (+ <span {...stylex.props(taskMarkerStyles.container)}>+ <CheckboxInput+ size="sm"+ value={task.isChecked}+ label={task.label}+ isLabelHidden+ isReadOnly+ />+ </span>+ ) : markerKind === 'disc' ||+ markerKind === 'circle' ||+ markerKind === 'square' ? (<span {...stylex.props(markerStyles.container)}><span{...stylex.props(diff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsxindex d6705df48b..79dfb8cb3b 100644--- a/packages/core/src/Markdown/Markdown.test.tsx+++ b/packages/core/src/Markdown/Markdown.test.tsx@@ -491,6 +491,60 @@ describe('Markdown', () => {expect((checkboxes[1] as HTMLInputElement).checked).toBe(false);});+ it('keeps each task item checked or open in a list that mixes task and plain items (FR23)', () => {+ render(+ <Markdown>+ {'- [x] Done **task**\n- Plain item\n- [ ] Open task\n'}+ </Markdown>,+ );+ // One list, in document order.+ expect(document.querySelectorAll('ul, ol')).toHaveLength(1);+ const items = [...document.querySelectorAll('li')];+ expect(items.map(item => item.textContent)).toEqual([+ expect.stringContaining('Done task'),+ 'Plain item',+ expect.stringContaining('Open task'),+ ]);+ const checkbox = (item: Element | undefined) =>+ item?.querySelector<HTMLInputElement>('input[type="checkbox"]') ?? null;+ // Each task item shows its own read-only checkbox, named by its text.+ expect(checkbox(items[0])?.checked).toBe(true);+ expect(checkbox(items[2])?.checked).toBe(false);+ expect(screen.getByRole('checkbox', {name: 'Done task'})).toBe(+ checkbox(items[0]),+ );+ expect(screen.getByRole('checkbox', {name: 'Open task'})).toBe(+ checkbox(items[2]),+ );+ for (const input of [checkbox(items[0]), checkbox(items[2])]) {+ expect(input?.getAttribute('aria-readonly')).toBe('true');+ }+ // A plain item keeps its marker and has no checkbox.+ expect(checkbox(items[1])).toBeNull();+ });++ it('keeps task state in mixed ordered and nested lists', () => {+ render(+ <Markdown>+ {+ '1. [ ] First step\n2. Second step\n - [x] Nested done\n - Nested plain\n'+ }+ </Markdown>,+ );+ expect(+ document.querySelector('ol')?.querySelectorAll(':scope > li'),+ ).toHaveLength(2);+ expect(+ screen.getByRole<HTMLInputElement>('checkbox', {name: 'First step'})+ .checked,+ ).toBe(false);+ expect(+ screen.getByRole<HTMLInputElement>('checkbox', {name: 'Nested done'})+ .checked,+ ).toBe(true);+ expect(document.querySelectorAll('input[type="checkbox"]')).toHaveLength(2);+ });+it('renders tables', () => {render(<Markdown>{'| A | B |\n| --- | --- |\n| 1 | 2 |'}</Markdown>);expect(document.querySelector('table')).toBeInTheDocument();diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex e88f46b640..6f66b41384 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -56,7 +56,7 @@ import {trimStreamingArtifacts,} from './parser';import type {IncrementalState, MathParseOptions, ParseOptions} from './parser';-import {getMarkdownAstLegacyCodeLanguage} from './ast';+import {getMarkdownAstLegacyCodeLanguage, markdownAstText} from './ast';import type {MarkdownAstBlockContent,MarkdownAstPhrasingContent,@@ -1712,6 +1712,30 @@ function renderBlock(</>);+ // A task item beside plain items keeps its own checked state+ // (FR23): it shows a read-only checkbox where its marker+ // would be, named by its text.+ const firstParagraph = item.children.find(+ block => block.type === 'paragraph',+ );+ const task =+ item.checked == null+ ? undefined+ : {+ isChecked: item.checked,+ label:+ firstParagraph?.type === 'paragraph'+ ? markdownAstText(+ firstParagraph.children,+ extension =>+ markdownExtensionText(+ preparedPlugins,+ extension,+ ),+ )+ : t('@astryx.markdown.taskList'),+ };+return (<ListMarkerScope// eslint-disable-next-line @eslint-react/no-array-index-key -- markdown list items are rendered from positional AST nodes@@ -1720,7 +1744,8 @@ function renderBlock((node.ordered ? NUMBER_MARKERS : BULLET_MARKERS)[listDepth % 3]- }>+ }+ task={task}><ListItem label={label} /></ListMarkerScope>);diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.tsindex 073041fced..eacdc9550c 100644--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts@@ -342,6 +342,113 @@ test('a rule at either edge of the document adds no outer margin', async ({]);});+// component:Markdown FR23 and spec:AST-061 FR5: in a list that mixes task+// and plain items, each task item keeps its checked state as a checkbox where+// its marker would be, each plain item keeps its marker, and the list stays+// one list — on both surfaces, in the same places.+test('side by side: a list of task and plain items keeps each task checkbox and each marker', async ({+ page,+}) => {+ const errors = await openStory(page, STORY.sideBySide, DESKTOP);+ await waitForDocument(page, MARKDOWN);+ await waitForDocument(page, RICH_TEXT);+ const layout = (selector: string) =>+ page.evaluate(surface => {+ const block = document.querySelector(+ `${surface} [data-parity-block="list-task-mixed"]`,+ );+ const origin = block?.getBoundingClientRect().left ?? 0;+ const items = [...(block?.querySelectorAll('li') ?? [])];+ const left = (element: Element | null | undefined) =>+ element == null+ ? null+ : Math.round(element.getBoundingClientRect().left - origin);+ // An item's visible text nodes: not its checkbox's label, which names+ // the checkbox for assistive technology.+ const visibleText = (item: Element) => {+ const nodes: Text[] = [];+ const walker = document.createTreeWalker(item, NodeFilter.SHOW_TEXT);+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ if (+ node.textContent?.trim() &&+ node.parentElement?.closest('label') == null+ ) {+ nodes.push(node as Text);+ }+ }+ return nodes;+ };+ // Where an item's first rendered line of text starts.+ const textStart = (item: Element) => {+ const [first] = visibleText(item);+ if (first == null) {+ return null;+ }+ const range = document.createRange();+ range.selectNodeContents(first);+ return Math.round(range.getBoundingClientRect().left - origin);+ };+ // RichText draws each task checkbox beside the editable text and gives+ // the item it belongs to through aria-owns.+ const checkboxOf = (item: Element) => {+ const owned = item.getAttribute('aria-owns');+ const target = owned == null ? null : document.getElementById(owned);+ return (+ item.querySelector<HTMLInputElement>('input[type="checkbox"]') ??+ (target instanceof HTMLInputElement+ ? target+ : (target?.querySelector<HTMLInputElement>(+ 'input[type="checkbox"]',+ ) ?? null))+ );+ };+ return {+ // RichText marks the list itself; Markdown, the block around it.+ lists:+ (block?.matches('ul, ol') ? 1 : 0) ++ (block?.querySelectorAll('ul, ol').length ?? 0),+ items: items.map(item => {+ const box = checkboxOf(item);+ return {+ text: visibleText(item)+ .map(node => node.textContent)+ .join('')+ .trim(),+ checked: box?.checked ?? null,+ box: left(box),+ textStart: textStart(item),+ };+ }),+ };+ }, selector);+ const markdown = await layout(MARKDOWN);+ const richText = await layout(RICH_TEXT);+ expect(markdown.lists).toBe(1);+ expect(richText.lists).toBe(1);+ expect(markdown.items.map(({text, checked}) => [text, checked])).toEqual([+ ['Mixed open task', false],+ ['Mixed plain item', null],+ ['Mixed done task', true],+ ]);+ expect(richText.items.map(({text, checked}) => [text, checked])).toEqual(+ markdown.items.map(({text, checked}) => [text, checked]),+ );+ markdown.items.forEach((item, index) => {+ const other = richText.items[index];+ expect(+ Math.abs((other?.textStart ?? 0) - (item.textStart ?? 0)),+ `text of ${item.text}`,+ ).toBeLessThanOrEqual(1);+ if (item.box != null) {+ expect(+ Math.abs((other?.box ?? 0) - item.box),+ `checkbox of ${item.text}`,+ ).toBeLessThanOrEqual(1);+ }+ });+ expect(errors).toEqual([]);+});+// 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.@@ -351,24 +458,30 @@ test('side by side: task items have one checkbox each, and list rows one markerconst errors = await openStory(page, STORY.sideBySide, DESKTOP);await waitForDocument(page, MARKDOWN);await waitForDocument(page, RICH_TEXT);+ // Two in the task list, two in the list that mixes task and plain items.await expect(page.locator(`${RICH_TEXT} [data-richtext-task-checkbox] input`),- ).toHaveCount(2);+ ).toHaveCount(4);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,- );+ // Each item's checkbox: inside it in Markdown; in RichText, beside the+ // editable text, given to the item through aria-owns.+ const boxes = [...(block?.querySelectorAll('li') ?? [])].flatMap(item => {+ const owned = item.getAttribute('aria-owns');+ const target = owned == null ? null : document.getElementById(owned);+ const box =+ item.querySelector<HTMLInputElement>('input[type="checkbox"]') ??+ (target instanceof HTMLInputElement+ ? target+ : (target?.querySelector<HTMLInputElement>(+ 'input[type="checkbox"]',+ ) ?? null));+ return box == null ? [] : [box];+ });const label = [...(block?.querySelectorAll('li span') ?? [])].find(span =>span.textContent?.startsWith('Open task'),);