An open source design system that's fully customizable and agent ready
TypeScript
fix(List): keep numbered markers whole and sibling text aligned (#7650)
Xinzi Zhou76cd3b89e771
diff --git a/.changeset/list-number-markers-right-aligned.md b/.changeset/list-number-markers-right-aligned.mdnew file mode 100644index 0000000000..8f96e1180c--- /dev/null+++ b/.changeset/list-number-markers-right-aligned.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Numbered List and Markdown markers end on one edge, with tabular figures, so every period in a list lines up as native list markers do. In List, a counter wider than its marker hangs toward the start before it widens the shared column. Markdown's non-swipe document lists instead keep the ordinary text inset and let whole counters paint outside it, matching RichText's native outside markers even beyond the marker gutter. Single-digit numbers, now right-aligned in their marker, sit a few pixels closer to their text.+@ernesttdiff --git a/.changeset/list-number-markers.md b/.changeset/list-number-markers.mdnew file mode 100644index 0000000000..9d08f73d3b--- /dev/null+++ b/.changeset/list-number-markers.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Keep multi-digit List and Markdown counters on one line in a shared number column, so sibling text and nested lists stay aligned. Bullets and the text inset of short-only lists without task items retain their existing spacing; numbered rows beside task items move to share the checkbox's text start. Short numbers are right-aligned in their marker, moving the digits a few pixels closer to their text. Markdown task lists with nested or other block content place each checkbox on its item's first line and name it by that item's own text, instead of centering it against the whole body and naming it by all nested content inside a “Task list” group; those lists retain list semantics without that extra group. Paragraph-only pure task lists are unchanged. Browsers without CSS subgrid keep readable, unbroken counters in the existing flex layout, without the shared-column alignment enhancement.+@imdreamrunnerdiff --git a/apps/storybook/stories/Item.stories.tsx b/apps/storybook/stories/Item.stories.tsxindex eb8c2d3655..a8c6e290e4 100644--- a/apps/storybook/stories/Item.stories.tsx+++ b/apps/storybook/stories/Item.stories.tsx@@ -1,6 +1,14 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file Item.stories.tsx+ * @input Item and composing rows, including numbered/bulleted marker anatomy+ * @output Reusable row examples and before/after DOM-count browser fixtures+ * @position Storybook examples and Item/List regression evidence+ */+import {useState, type ReactNode} from 'react';+import {Button} from '@astryxdesign/core/Button';import * as stylex from '@stylexjs/stylex';import type {Meta, StoryObj} from '@storybook/react';import {expect} from 'storybook/test';@@ -15,6 +23,13 @@ import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';import {StatusDot} from '@astryxdesign/core/StatusDot';const storyStyles = stylex.create({+ markerAnatomy: {+ display: 'flex',+ flexDirection: 'column',+ gap: 16,+ width: 320,+ maxWidth: '100%',+ },iconCircle: {display: 'flex',alignItems: 'center',@@ -51,6 +66,64 @@ const meta: Meta<typeof Item> = {export default meta;type Story = StoryObj<typeof Item>;+/** Numbered rows alone need the two-column marker/content grouping. */+export const MarkerAnatomy: Story = {+ tags: ['!autodocs'],+ render: function MarkerAnatomyStory() {+ const [isOpen, setOpen] = useState(false);+ const slots = {+ startContent: <span data-anatomy-slot="start">S</span>,+ label: (+ <span data-anatomy-slot="label">+ A row label that can wrap naturally+ </span>+ ),+ description: 'Secondary description',+ endContent: <span data-anatomy-slot="end">E</span>,+ align: 'first-line' as const,+ };+ const marker = <span data-anatomy-slot="marker">•</span>;+ return (+ <div data-marker-anatomy {...stylex.props(storyStyles.markerAnatomy)}>+ <div data-marker-case="numbered">+ <List listStyle="decimal" start={99}>+ <ListItem {...slots} />+ </List>+ </div>+ <div data-marker-case="bulleted">+ <List listStyle="disc">+ <ListItem {...slots} isSelected />+ </List>+ </div>+ <div data-marker-case="marked-item">+ <Item {...slots} marker={marker} />+ </div>+ <div data-marker-case="unmarked-item">+ <Item {...slots} />+ </div>+ <Button+ label="Toggle marker menu"+ onClick={() => setOpen(value => !value)}+ />+ {isOpen && (+ <div+ role="menu"+ aria-label="Marker anatomy menu"+ data-marker-case="menu">+ <Item+ {...slots}+ marker={marker}+ role="menuitem"+ tabIndex={0}+ onClick={() => {}}+ />+ </div>+ )}+ </div>+ );+ },+};+/** Basic item with all slots populated. */export const Default: Story = {render: () => (diff --git a/apps/storybook/stories/List.stories.tsx b/apps/storybook/stories/List.stories.tsxindex 881f53db54..fd49a67d67 100644--- a/apps/storybook/stories/List.stories.tsx+++ b/apps/storybook/stories/List.stories.tsx@@ -3,7 +3,7 @@/*** @file List.stories.tsx* @input List, ListItem, and Storybook args- * @output List examples, including the four row edge treatments+ * @output List examples, including row edge treatments and long number markers* @position Storybook demonstrations for List consumers*/@@ -276,6 +276,39 @@ export const OrderedList: Story = {),};+export const LongNumberMarkers: Story = {+ args: {listStyle: 'decimal', start: 98},+ render: args => (+ <List {...args}>+ <ListItem+ label={<>Review the migration before applying it to your project.</>}+ />+ <ListItem label={<>Check that existing behavior stays unchanged.</>} />+ <ListItem+ label={<>Verify that the complete number stays beside its label.</>}+ />+ </List>+ ),+};++export const NumberedFirstLine: Story = {+ args: {listStyle: 'decimal', start: 9},+ render: args => (+ <List {...args}>+ <ListItem+ align="first-line"+ startContent={<Avatar name="Ada Lovelace" size={40} />}+ label={<>A numbered row with a tall avatar and a wrapped first line.</>}+ />+ <ListItem+ align="first-line"+ startContent={<Avatar name="Grace Hopper" size={40} />}+ label={<>The number and avatar follow the same first text line.</>}+ />+ </List>+ ),+};+export const BulletedList: Story = {render: args => (<List listStyle="disc" {...args}>diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsxindex d2944e1da9..9b333ac7c1 100644--- a/apps/storybook/stories/Markdown.stories.tsx+++ b/apps/storybook/stories/Markdown.stories.tsx@@ -270,6 +270,30 @@ export const NestedLists: Story = {},};+export const LongNumberMarkers: Story = {+ args: {+ children: [+ '8. Eight',+ ' 1. Nested under eight',+ '9. Nine',+ ' 1. Nested under nine',+ '10. Ten',+ ' 1. Nested under ten',+ '11. Eleven',+ '12. Twelve',+ '',+ '## Roman counters',+ '',+ '1. Outer',+ ' 1. Middle',+ ...Array.from(+ {length: 8},+ (_, index) => ` ${index + 1}. Roman item ${index + 1}`,+ ),+ ].join('\n'),+ },+};+export const ShiftedHeadings: Story = {name: 'Shifted Headings (start at h3)',args: {diff --git a/apps/storybook/stories/RichTextEditor.markdownParity.tsx b/apps/storybook/stories/RichTextEditor.markdownParity.tsxindex 8ab137eb4d..5a4ac986e0 100644--- a/apps/storybook/stories/RichTextEditor.markdownParity.tsx+++ b/apps/storybook/stories/RichTextEditor.markdownParity.tsx@@ -4,10 +4,14 @@* @file RichTextEditor.markdownParity.tsx* @input Core Markdown for the read surface; RichTextEditor with its toolbar and* the Lexical plugins available today for the edit surface; the parity- * fixture; the Storybook demo Markdown plugins.+ * fixture; the Storybook demo Markdown plugins; 16px wide-counter fixtures+ * with ordered, unordered and pure-task ancestry.* @output `MarkdownParitySandbox`: one Markdown document rendered by both* surfaces side by side, swapped in place, or overlaid, with diagnostic* per-block geometry and the scroll anchor across a mode switch.+ * `WideNumberMarkerParity`, `MixedNumberMarkerParity` and+ * `TaskParentNumberMarkerParity` compare short and wide outside counters on+ * Markdown, RichTextView, and RichTextEditor.* @position Storybook-only diagnostic for RichTextEditor.stories.tsx. It shows* current behavior and fixes nothing: every difference it reports is a* finding, and none of its numbers is a target.@@ -33,9 +37,15 @@ import {Banner} from '@astryxdesign/core/Banner';import {Markdown} from '@astryxdesign/core/Markdown';import {Text} from '@astryxdesign/core/Text';import {ToggleButton} from '@astryxdesign/core/ToggleButton';-import {colorVars, spacingVars} from '@astryxdesign/core/theme/tokens.stylex';+import {defineTheme, Theme, useTheme} from '@astryxdesign/core/theme';+import {+ colorVars,+ spacingVars,+ typeScaleVars,+} from '@astryxdesign/core/theme/tokens.stylex';import {RichTextEditor,+ RichTextView,RichTextEditorAutoLinkPlugin,RichTextEditorToolbar,markdownToEditorStateJSON,@@ -804,3 +814,138 @@ export function MarkdownParitySandbox({</div>);}++// A real Theme override, not a font-size declaration on the story wrapper:+// both document text and generated counters must resolve to 16px.+const wideMarkerTheme = defineTheme({+ name: 'wide-number-marker-parity',+ typography: {scale: {base: 16, ratio: 1.2}},+});++const WIDE_MARKER_SOURCE = [+ 'Reference paragraph.',+ '',+ '9. Short decimal',+ '',+ 'A paragraph separates lists.',+ '',+ '999. Before four digits',+ '1000. Four digits',+ ' 1. Nested under four digits',+ '1001. Sibling after four digits',+ '',+ 'Another separate list.',+ '',+ '2024. Year counter',+ '',+ 'The widest decimal supported by Markdown source syntax.',+ '',+ '999999999. Nine digits',+ '',+ 'Nested counters resolve from their parent text line.',+ '',+ '1. Outer parent',+ ' 1. Middle parent',+ ' 1. Short roman',+ '2. Other outer parent',+ ' 1. Other middle parent',+ '',+ ' 27. Before long roman',+ ' 28. Long roman',+ ' 29. After long roman',+ '',+ 'A still wider roman counter.',+ '',+ '1. Last outer parent',+ ' 1. Last middle parent',+ '',+ ' 1888. Much wider roman',+].join('\n');++const wideMarkerStyles = stylex.create({+ editorFrame: {+ // The field's 8px inset and 1px border offset its document. Give the frame+ // that space outside the common measure, rather than testing unequal widths.+ width: `calc(100% + 2 * (${spacingVars['--spacing-2']} + 1px))`,+ marginInline: `calc(-1 * (${spacingVars['--spacing-2']} + 1px))`,+ },+ columns: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 320px), 1fr))',+ gap: spacingVars['--spacing-4'],+ },+ surface: {+ minWidth: 0,+ // Space to photograph outside ink, including nine-digit counters, without+ // the viewport cropping it. The document's ordinary list inset is unchanged.+ paddingInline: 96,+ fontSize: typeScaleVars['--text-body-size'],+ lineHeight: typeScaleVars['--text-body-leading'],+ },+});++const MIXED_MARKER_SOURCE = [+ 'Reference paragraph.',+ '',+ '- Outer bullet',+ ' - Inner bullet',+ '',+ ' 388. Mixed roman counter',+ ' 389. Roman sibling',+].join('\n');++const TASK_PARENT_MARKER_SOURCE = [+ 'Reference paragraph.',+ '',+ '- [ ] Outer task',+ ' - [x] Inner task',+ '',+ ' 388. Task roman counter',+ ' 389. Task roman sibling',+].join('\n');++/** Reusable comparison for a numbered list below two pure task ancestors. */+export function TaskParentNumberMarkerParity() {+ return <NumberMarkerParity source={TASK_PARENT_MARKER_SOURCE} />;+}++/** Reusable comparison for a numbered list below two unordered ancestors. */+export function MixedNumberMarkerParity() {+ return <NumberMarkerParity source={MIXED_MARKER_SOURCE} />;+}++/** Reusable short/wide-counter comparison in read and edit mode at 16px. */+export function WideNumberMarkerParity() {+ return <NumberMarkerParity source={WIDE_MARKER_SOURCE} />;+}++function NumberMarkerParity({source}: {source: string}) {+ const {mode} = useTheme();+ const state = useMemo(() => markdownToEditorStateJSON(source), [source]);+ return (+ <Theme theme={wideMarkerTheme} mode={mode}>+ <div {...stylex.props(wideMarkerStyles.columns)}>+ <div+ data-wide-marker-surface="markdown"+ {...stylex.props(wideMarkerStyles.surface)}>+ <Markdown>{source}</Markdown>+ </div>+ <div+ data-wide-marker-surface="view"+ {...stylex.props(wideMarkerStyles.surface)}>+ <RichTextView value={state} />+ </div>+ <div+ data-wide-marker-surface="editor"+ {...stylex.props(wideMarkerStyles.surface)}>+ <RichTextEditor+ label="Wide counters"+ isLabelHidden+ defaultValue={state}+ xstyle={wideMarkerStyles.editorFrame}+ />+ </div>+ </div>+ </Theme>+ );+}diff --git a/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts b/apps/storybook/stories/RichTextEditor.markdownParityFixture.tsindex dbd5a09a6d..9261f94eb0 100644--- a/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts+++ b/apps/storybook/stories/RichTextEditor.markdownParityFixture.ts@@ -10,7 +10,9 @@** 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, and a+ * unordered (2-space) and ordered (3-space) lists; an ordered list whose+ * counters widen (99 to 100, and i to viii two lists down); 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@@ -124,6 +126,29 @@ export const MARKDOWN_PARITY_BLOCKS: readonly MarkdownParityBlock[] = ['```',),},+ {+ key: 'list-ordered-wide',+ label: 'Ordered list with wide counters',+ probe: 'Wide step ninety-eight',+ // 99 to 100 at the top and i to viii two lists down: counters that+ // outgrow the ones before them. A nested list starts at 1, as only that+ // number may interrupt the item's paragraph. Not right after the ordered+ // list, which it would continue as one list.+ markdown: lines(+ '98. Wide step ninety-eight',+ '99. Wide step ninety-nine',+ ' 1. Lettered step a',+ ' 1. Roman step i',+ ' 2. Roman step ii',+ ' 3. Roman step iii',+ ' 4. Roman step iv',+ ' 5. Roman step v',+ ' 6. Roman step vi',+ ' 7. Roman step vii',+ ' 8. Roman step viii',+ '100. Wide step one hundred',+ ),+ },{key: 'list-task-mixed',label: 'Task and plain items',diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex 00243cdc80..788a87762d 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -19,6 +19,9 @@ import {$getRoot} from 'lexical';import {LONG_DOCUMENT_COPIES,MarkdownParitySandbox,+ WideNumberMarkerParity,+ MixedNumberMarkerParity,+ TaskParentNumberMarkerParity,type MarkdownParitySandboxProps,} from './RichTextEditor.markdownParity';import {MarkdownPluginsImportExport as MarkdownPluginsImportExportStory} from './RichTextEditor.markdownPluginsImportExport';@@ -563,6 +566,24 @@ export const MarkdownParity: MarkdownParityStory = {},};+export const MarkdownParityWideNumberMarkers: Story = {+ name: 'Markdown parity: wide number markers at 16px',+ tags: ['!autodocs'],+ render: () => <WideNumberMarkerParity />,+};++export const MarkdownParityMixedNumberMarkers: Story = {+ name: 'Markdown parity: mixed nested number markers at 16px',+ tags: ['!autodocs'],+ render: () => <MixedNumberMarkerParity />,+};++export const MarkdownParityTaskParentNumberMarkers: Story = {+ name: 'Markdown parity: pure task-parent number markers at 16px',+ tags: ['!autodocs'],+ render: () => <TaskParentNumberMarkerParity />,+};+export const MarkdownParityToggle: MarkdownParityStory = {...markdownParity,name: 'Markdown parity: read/edit toggle',diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsxindex 8358b096fb..acbe62f3a8 100644--- a/packages/core/src/Item/Item.test.tsx+++ b/packages/core/src/Item/Item.test.tsx@@ -3,7 +3,7 @@/*** @file Item.test.tsx* @input Uses vitest, @testing-library/react, Item component- * @output Unit tests for Item+ * @output Unit tests for Item, including flat marker DOM and numbered-row scope* @position Testing; validates Item component implementation** SYNC: When Item component changes, update tests to match new behavior@@ -31,6 +31,7 @@ import {rulesDeclaredFor} from '../__tests__/pressState';import userEvent from '@testing-library/user-event';import {Item} from './Item';import {ItemDescriptionContext} from './ItemDescriptionContext';+import {List, ListItem} from '../List';/*** Item in delegation mode: `interactiveRef` points at a nested control that@@ -479,6 +480,12 @@ describe('Item', () => {expect(root?.querySelector('[data-testid="marker"]')).toBeInTheDocument();expect(root?.querySelector('[data-testid="start"]')).toBeInTheDocument();expect(root?.querySelector('[data-testid="end"]')).toBeInTheDocument();+ // A bullet or caller-owned marker needs no extra formatting group: marker,+ // start, primary and end retain the released flat row structure.+ expect(root?.children).toHaveLength(4);+ expect(button?.parentElement).toBe(root);+ expect(screen.getByTestId('start').parentElement?.parentElement).toBe(root);+ expect(screen.getByTestId('end').parentElement?.parentElement).toBe(root);expect(button?.querySelector('[data-testid="marker"]'),).not.toBeInTheDocument();@@ -592,6 +599,38 @@ describe('Item', () => {expect(hasStrut()).toBe(false);});+ it('groups only the numbered composing row, not marked Items in its slots', () => {+ render(+ <List listStyle="decimal">+ <ListItem+ data-testid="numbered-row"+ label="Numbered"+ startContent={<span data-testid="numbered-start">S</span>}+ endContent={+ <Item+ data-testid="nested-row"+ label="Nested item"+ marker={<span>•</span>}+ startContent={<span data-testid="nested-start">S</span>}+ endContent={<span>E</span>}+ />+ }+ />+ </List>,+ );+ const numbered = screen.getByTestId('numbered-row');+ expect(numbered.children).toHaveLength(2);+ const group = numbered.children[1];+ expect(+ screen.getByTestId('numbered-start').parentElement?.parentElement,+ ).toBe(group);+ const nested = screen.getByTestId('nested-row');+ expect(nested.children).toHaveLength(4);+ expect(+ screen.getByTestId('nested-start').parentElement?.parentElement,+ ).toBe(nested);+ });+// ===========================================================================// Description rendering// ===========================================================================diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 34b264d001..34c3aed791 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -5,7 +5,11 @@/*** @file Item.tsx* @input Uses React, ReactNode, StyleXStyles, theme tokens, useClickableContainer- * @output Exports Item component, ItemProps type; publishes the shared inline inset+ * @output Exports Item component, ItemProps type; publishes the shared inline inset.+ * Only numbered composing rows keep their start/label/end slots in one flex+ * group, through Item's private exact-marker scope; other marked rows keep+ * their flat children. This lets List share a counter track without changing+ * those slots' own layout.* @position Core layout primitive; consumed by index.ts, tested by Item.test.tsx** The swipe actions live in ItemSwipeLayer, reached only through a dynamic@@ -28,6 +32,7 @@import {lazy,Suspense,+ use,useCallback,useId,useRef,@@ -45,6 +50,7 @@ import {import type {BaseProps} from '../BaseProps';import {isRenderable, mergeProps} from '../utils';import {ItemDescriptionContext} from './ItemDescriptionContext';+import {ItemMarkerColumnsContext} from './ItemMarkerColumnsContext';import {useMergedRefs} from '../hooks/useMergedRefs';import {computeTargetAndRel} from '../Link/computeTargetAndRel';import {useLinkComponent} from '../Link/useLinkComponent';@@ -352,6 +358,22 @@ const styles = stylex.create({textAlign: 'start',borderRadius: radiusVars['--radius-element'],},+ // One content cell beside the marker. Its slots retain the row's flex+ // alignment and gap, including first-line alignment and tall start content.+ // A numbered List can then subgrid the row into marker/content columns.+ markerContent: {+ display: 'flex',+ flex: 1,+ minWidth: 0,+ alignItems: 'inherit',+ alignSelf: 'stretch',+ gap: 'inherit',+ },+ markerContentFirstLine: {+ // A tall start/end slot moves the first text baseline down. The marker+ // must follow that baseline, not the stretched group's top edge.+ alignSelf: 'baseline',+ },alignStart: {alignItems: 'flex-start',},@@ -586,6 +608,7 @@ export function Item({...restProps}: ItemProps) {const pressable = usePressFeedback();+ const columnMarker = use(ItemMarkerColumnsContext);const LinkComponent = useLinkComponent();// Delegation mode: the row is an enlarged click/tap target for a nested@@ -738,9 +761,8 @@ export function Item({onClick?.(e);};- const innerContent = (+ const content = (<>- {marker}{startContent != null && (<span{...stylex.props(@@ -900,7 +922,18 @@ export function Item({onClick={rootOnClick}><ItemDescriptionContextvalue={hasRenderableDescription ? descriptionID : null}>- {innerContent}+ {isRenderable(marker) && marker}+ {isRenderable(marker) && columnMarker === marker ? (+ <span+ {...stylex.props(+ styles.markerContent,+ align === 'first-line' && styles.markerContentFirstLine,+ )}>+ {content}+ </span>+ ) : (+ content+ )}</ItemDescriptionContext>{hasSwipe && (// The panels: out-of-flow children of this root, so the DOM is the onediff --git a/packages/core/src/Item/ItemMarkerColumns.a11y.chromium.spec.ts b/packages/core/src/Item/ItemMarkerColumns.a11y.chromium.spec.tsnew file mode 100644index 0000000000..9b6f3b61f9--- /dev/null+++ b/packages/core/src/Item/ItemMarkerColumns.a11y.chromium.spec.ts@@ -0,0 +1,211 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/Item core/List core/Markdown core/DropdownMenu ^apps/storybook/stories/Item++/**+ * @file ItemMarkerColumns.a11y.chromium.spec.ts+ * @input Built Item marker anatomy, mixed task, and selectable menu stories+ * @output Minimal DOM counts and unchanged row pixels at rest/open, fine/coarse+ * @position Item/List browser regression; receipts and captures stay in test outputs+ */++import {createHash} from 'node:crypto';+import {readFile, writeFile} from 'node:fs/promises';+import {basename, join} from 'node:path';+import {expect, test, type Page} from '@playwright/test';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => storybook?.close());++async function open(page: Page, story: string, dir: string) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${story}&viewMode=story&globals=direction:${dir};colorMode:light;astryxTheme:neutral`,+ );+ await holdMotionStill(page);+ await page.evaluate(async () => document.fonts.ready);+}++async function capture(+ page: Page,+ selector: string,+ name: string,+ file: string,+) {+ const target = page.locator(selector);+ await expect(target).toBeVisible();+ const geometry = await target.evaluate(root => {+ const origin = root.getBoundingClientRect();+ const rect = (element: Element) => {+ const box = element.getBoundingClientRect();+ return {+ x: box.x - origin.x,+ y: box.y - origin.y,+ width: box.width,+ height: box.height,+ };+ };+ return {+ bodyElements: document.body.querySelectorAll('*').length,+ componentElements: root.querySelectorAll('*').length,+ rows: Array.from(root.querySelectorAll('.astryx-item')).map(row => ({+ case:+ row.closest('[data-marker-case]')?.getAttribute('data-marker-case') ??+ row.getAttribute('role') ??+ 'task',+ children: row.children.length,+ elements: row.querySelectorAll('*').length,+ rect: rect(row),+ slots: Array.from(+ row.querySelectorAll(+ '[data-anatomy-slot], input, [role="checkbox"], [role="radio"]',+ ),+ ).map(slot => ({+ name:+ slot.getAttribute('data-anatomy-slot') ??+ slot.getAttribute('role') ??+ slot.tagName,+ rect: rect(slot),+ })),+ startIsDirect:+ row.querySelector('[data-anatomy-slot="start"]')?.parentElement+ ?.parentElement === row,+ })),+ };+ });+ const image = await target.screenshot({path: file});+ return {+ name,+ ...geometry,+ pixelSha256: createHash('sha256').update(image).digest('hex'),+ };+}++for (const pointer of ['fine', 'coarse'] as const) {+ for (const dir of ['ltr', 'rtl'] as const) {+ test(`numbered marker scope preserves row pixels (${pointer}, ${dir})`, async ({+ browser,+ }, testInfo) => {+ const context = await browser.newContext({+ viewport: {width: 1280, height: 900},+ hasTouch: pointer === 'coarse',+ });+ const page = await context.newPage();+ try {+ const states: Awaited<ReturnType<typeof capture>>[] = [];+ await open(page, 'core-item--marker-anatomy', dir);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(pointer === 'coarse');+ const fixture = '[data-marker-anatomy]';+ states.push(+ await capture(+ page,+ fixture,+ 'anatomy-rest',+ testInfo.outputPath('anatomy-rest.png'),+ ),+ );+ await page.getByRole('button', {name: 'Toggle marker menu'}).click();+ await expect(page.getByRole('menuitem')).toBeVisible();+ await page.mouse.move(1200, 850);+ states.push(+ await capture(+ page,+ fixture,+ 'anatomy-open',+ testInfo.outputPath('anatomy-open.png'),+ ),+ );++ await open(page, 'a11y-menu--dropdown-selectable', dir);+ states.push(+ await capture(+ page,+ '[data-a11y-activations]',+ 'menu-rest',+ testInfo.outputPath('menu-rest.png'),+ ),+ );+ await page.getByRole('button', {name: 'View', exact: true}).click();+ await expect(page.getByRole('menuitemcheckbox')).toBeVisible();+ await expect(page.getByRole('menuitemradio')).toHaveCount(2);+ await page.mouse.move(1200, 850);+ states.push(+ await capture(+ page,+ '[role="menu"]',+ 'menu-open',+ testInfo.outputPath('menu-open.png'),+ ),+ );++ await open(page, 'richtext-richtexteditor--markdown-parity', dir);+ const task =+ '[data-parity-surface="markdown"] [data-parity-block="list-task-mixed"]';+ states.push(+ await capture(+ page,+ task,+ 'mixed-task',+ testInfo.outputPath('mixed-task.png'),+ ),+ );+ await writeFile(+ testInfo.outputPath('receipt.json'),+ JSON.stringify({pointer, dir, states}, null, 2),+ );++ for (const state of states.filter(state =>+ state.name.startsWith('anatomy'),+ )) {+ for (const row of state.rows) {+ expect(row.children, row.case).toBe(+ row.case === 'numbered'+ ? 2+ : row.case === 'unmarked-item'+ ? 3+ : 4,+ );+ expect(row.startIsDirect, row.case).toBe(row.case !== 'numbered');+ }+ }+ // Before/after pixels are compared only when the retained local receipt+ // is supplied. CI keeps the structural proof and emits its own receipt.+ const before = process.env.ASTRYX_MARKER_ANATOMY_BEFORE;+ if (before != null) {+ const prior = JSON.parse(+ await readFile(+ join(before, basename(testInfo.outputDir), 'receipt.json'),+ 'utf8',+ ),+ ) as {states: typeof states};+ for (const state of states) {+ const previous = prior.states.find(+ value => value.name === state.name,+ );+ expect(previous, state.name).toBeDefined();+ expect(state.pixelSha256, `${state.name}: unchanged pixels`).toBe(+ previous?.pixelSha256,+ );+ expect(+ state.rows.map(row => row.rect),+ `${state.name}: unchanged geometry`,+ ).toEqual(previous?.rows.map(row => row.rect));+ }+ }+ } finally {+ await context.close();+ }+ });+ }+}diff --git a/packages/core/src/Item/ItemMarkerColumnsContext.tsx b/packages/core/src/Item/ItemMarkerColumnsContext.tsxnew file mode 100644index 0000000000..b9ac4ee8d4--- /dev/null+++ b/packages/core/src/Item/ItemMarkerColumnsContext.tsx@@ -0,0 +1,20 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ItemMarkerColumnsContext.tsx+ * @input The exact marker element supplied by a numbered composing row+ * @output Private ItemMarkerColumnsContext; not part of the public Item exports+ * @position Item-owned seam for the marker/content formatting group+ *+ * Numbered ListItem rows need two subgrid cells. Other marked Items keep their+ * flat flex children. Marker identity, rather than an inherited boolean,+ * confines the group to that one row: an Item nested in a slot has a different+ * marker and does not inherit the formatting request.+ */++import {createContext, type ReactNode} from 'react';++export const ItemMarkerColumnsContext = createContext<ReactNode>(null);+ItemMarkerColumnsContext.displayName = 'ItemMarkerColumnsContext';diff --git a/packages/core/src/List/List.spec.md b/packages/core/src/List/List.spec.mdindex 5971db1767..c36e9f6e97 100644--- a/packages/core/src/List/List.spec.md+++ b/packages/core/src/List/List.spec.md@@ -32,6 +32,7 @@ system_specs:spec:AST-002/DEC-2,spec:AST-017/FR4,spec:AST-057/FR9,+ spec:AST-061/FR11,spec:AST-094,spec:AST-103,spec:AST-105,@@ -127,7 +128,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR6 | Missing or reset host inset MUST resolve to zero, so `outset` and `bleed` place content as `padded` does outside a padded host. No row paint MAY reach past the host's padding edge. | `architecture:container-padding/INV6`, `INV9` | Accepted contract || FR7 | Each row's retained inset MUST come from the same private density- and theme-derived source as Item's applied inline padding. A theme `item.paddingInline` override takes precedence over every treatment's row padding, as it does over density. A consumer override of row padding through `xstyle`, `className`, or `style` is outside the alignment guarantee. | Shared two-owner geometry contract | Accepted contract || FR8 | `outset` and `bleed` are valid only under a host state whose published inline inset matches its applied padding: a visually neutral host, such as a Layout region with explicit padding or a padded ScrollableArea, or the content area of a Card, Section (any variant), Dialog, or BottomSheet. Those hosts bound their padding with a border, background, or clip; FR6 keeps row paint inside the padding edge, so it never covers the border or changes the host's outline. Automatic LayoutContent/LayoutPanel states with a known publication mismatch are not eligible until that gap is fixed, and Drawer's content area is not admitted until it has its own evidence. | `architecture:container-padding/INV8–INV11`; real-browser evidence in each admitted host | Accepted contract |-| FR9 | The list element containing the rows MUST clip in the inline axis with `overflow-inline: clip`, never `hidden`. Under `outset` and `bleed` its inline edges MUST reach the host's padding edge, so the clip never cuts resting row paint and a swiped row paints no further than that edge. | `spec:AST-057/FR9` | Verified by `List.test.tsx` and real-browser geometry |+| FR9 | The list element containing the rows MUST clip in the inline axis with `overflow-inline: clip`, never `hidden`, except for static Markdown document lists that expose no swipe actions (DEC-5). Those Markdown lists, ordered or unordered, MAY use visible inline overflow so their own or descendant number markers remain whole while retaining AST-061 FR11's text starts and nested insets. General Lists and any collection with swipe-capable rows MUST retain the clip. Under `outset` and `bleed` its inline edges MUST reach the host's padding edge, so the clip never cuts resting row paint and a swiped row paints no further than that edge. | `spec:AST-057/FR9`; `component:List/DEC-5`; `spec:AST-061/FR11` | Verified by `List.test.tsx` and real-browser geometry || FR10 | Under a coarse primary pointer (`spec:AST-094` FR13), every ListItem row MUST offer a hit target at least 44 px tall, through its padding or an invisible hit area, with no visual change, where its neighbors leave room: the hit area never overlaps a neighboring row's or control's target, and between close neighbors it is clamped to half the gap; row height and geometry stay as they are at every density. A fine pointer keeps today's hit target. | Owner decision, 2026-10-26: no row-height change, a 44 px touch target | Accepted contract || FR11 | Under a coarse primary pointer, an interactive row's press MUST follow the cell profile (`spec:AST-094` FR11): it paints the `--color-overlay-pressed` token above the row's background and below its content without adding an element, and its release fades over the press model's release duration and curve on the compositor (`spec:AST-094` FR5). The row's dividers stay drawn while it is pressed, in every theme. At rest the row's paint and stacking are as they were. | `spec:AST-094` FR5, FR11 | Accepted contract || FR12 | List MUST take an `animatedLayout` handle (`spec:AST-105` FR1) and report each row inserted, removed, or moved between renders. With a handle, an inserted row enters, a removed row collapses in place, inert and hidden from assistive technology until it is gone, and a row crossing rows moving the other way rides above them on the list's surface, while the rows after a change glide to their new places (`spec:AST-105` FR3), all starting on one frame on the shared motion role (`spec:AST-105` FR4). Without a handle the list changes at once (`spec:AST-105` FR2). A row's identity is its `itemKey` (`spec:AST-103` DEC-4); a row without one changes at once. With a handle, a row also reports a change to its start or end content: content that appears enters, content that leaves exits (a slot that sets the row's height hides at once instead, and the row's other content and the rows after it take their final places at once, as `spec:AST-105`'s Coverage states), content replaced in the same slot swaps in place (`spec:AST-105` FR4, FR8), and the row's other content glides within the row; a slot whose content changes without changing size does not animate. The reorder handle's appearance (`spec:AST-103`) is such a change. A slot control that leaves is inert and hidden from assistive technology as its exit starts; if it held focus, focus moves to the row's focus target (or to the row, which takes focus programmatically for the handoff) without scrolling. | `spec:AST-105` FR1–FR5; `spec:AST-103` DEC-4; `spec:AST-105` FR8; `spec:AST-103` FR2 (the handle renders only with `reorderable`) | Accepted contract |@@ -142,6 +143,9 @@ Consumer migration instructions belong in consumer docs and release notes.resolves independently.- Labels, descriptions, markers, start/end content, interactivity, and selectionmay vary without changing the collection-wide treatment.+- Static Markdown document lists MAY omit inline clipping under DEC-5, including+ unordered ancestors of numbered lists. The exception does not apply to general+ Lists or to a list whose rows expose swipe actions.- Under a coarse primary pointer, a row's hit target grows toward 44 px whereits neighbors leave room (FR10); row geometry and appearance are unchanged.@@ -207,7 +211,8 @@ Consumer migration instructions belong in consumer docs and release notes.- `spec:AST-057` owns swipe actions on `Item` and the rule that the elementcontaining swipe-capable rows clips in the inline axis; List carries that clip(FR9) and `ListItem` passes `swipeActions` and `swipeBehavior` through to- `Item` unchanged.+ `Item` unchanged. Static Markdown document lists follow DEC-5's narrow exception;+ `spec:AST-061` FR11 owns their whole counters and cross-renderer indentation.- `spec:AST-094` owns the touch presentation gate (FR13), the press model(FR11), and motion roles (FR4); FR10 and FR11 apply the gate and the pressmodel to list rows, and FR12's motion plays an FR4 role.@@ -221,17 +226,18 @@ Consumer migration instructions belong in consumer docs and release notes.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |-| FR1–FR7, FR9 | List, Item, and theme-registry tests | every treatment; all densities; static and interactive rows; header; deprecated alias alone and with `edge`; ListItem outside a List | Removing context propagation, using one host edge for both inline edges, zeroing padding without the shared inset source, or dropping the list's reach or clip fails | `audit:List/layout` |-| FR2–FR6, FR8–FR9, AR1–AR2 | Real-browser List geometry evidence | each treatment in a Card at two paddings, a Section, an inline Dialog with and without Layout, a BottomSheet, a padded ScrollableArea scrolling vertically and in both axes, a LayoutContent with explicit padding, and standalone; header and dividers; LTR/RTL; hovered and selected rows; a swiped row under `outset` and `bleed` | Header movement, content off the expected line, paint past the host's padding edge, clipped resting paint, or a changed row box fails | `audit:List/visual` |-| FR10 | List tests of the touch hit target and real-browser hit-testing | every density; a row with a description; compact rows packed closer than 44 px; a row with an end control; a coarse and a fine pointer; a theme row padding | A coarse-pointer row whose target stays at its box where its neighbors leave room, a target that reaches a neighboring row's or control's target, a changed row box, or a changed fine-pointer target fails | `audit:List/layout` |-| FR11 | Item press-layer tests and real-browser pixel evidence | press, hold, and release; a release while the main thread is blocked; a mouse; a pressed row between two divided rows | A release that stops while script runs, an element added for the press, a divider hidden during a press, or paint or stacking changed at rest fails | `audit:List/visual` |-| FR12 | List update-motion tests and real-browser frame evidence | an insert, a removal, and a reorder, with and without a handle; reduced motion; a mouse; a start or end slot gaining, losing, and replacing content, and changing content at the same size; the reorder handle appearing; a focused slot control leaving; a leaving slot that sets the row's height | A staying row that jumps with a handle (other than after a leaving slot that sets the row's height), motion without one, a collapsing removed row that takes focus, pointer input or an accessibility-tree node, a removed row left after its collapse ends, or layout or paint per frame fails. Also fails: a slot change that jumps with a handle (other than a leaving slot that sets the row's height), a same-size slot change that animates, a leaving slot control that keeps focus or stays reachable, a focus move that scrolls, focus that lands on the page body, or a height-setting slot that plays an exit. | `audit:List/visual` |-| Migration | `astryx upgrade` codemod tests | static, aliased, already-migrated, dynamic, and computed-`edge` callsites; a second run | A dynamic value or a computed `edge` rewritten, a static one missed, or a second run that changes output fails | `audit:List/docs` |-| Documentation | `List.doc.mjs`, Storybook, and `scripts/check-knowledge.mjs` | public prop, values, default, deprecation, and representative composition | Missing or stale contract, docs, or example fails | `audit:List/docs` |-| FR13 | List tests and real-browser tests of a row menu with a mouse, a finger, and the keyboard | a plain row, a row with `onClick`, a row with `href`; a right click, a long press, Shift+F10, the context-menu key; close by Escape and by choice; a finger's hold, a mouse's right click, the keyboard, and `presentation: 'popover'` | A wrapper element around the `<li>`, a row a context request does not open, focus left in a closed menu or not returned to the row or its button, a plain row without a named "More actions" button, or a focusable row that ignores Shift+F10 fails. A lift or press paint under a mouse, the keyboard, or `presentation: 'popover'`, or a finger's hold on a focusable row without them, fails. | `audit:List/layout` |-| FR13 reorder | Real-browser tests with a finger and a mouse on a reorderable row with a menu | a hold on the handle and on the row body of a reorderable row with a menu | A handle hold that opens the menu, or a body hold that picks the row up, fails | `audit:List/layout` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |+| FR1–FR7, FR9 | List, Item, and theme-registry tests | every treatment; all densities; static and interactive rows; header; deprecated alias alone and with `edge`; ListItem outside a List | Removing context propagation, using one host edge for both inline edges, zeroing padding without the shared inset source, or dropping the list's reach or its clip outside DEC-5's static Markdown exception fails | `audit:List/layout` |+| FR2–FR6, FR8–FR9, AR1–AR2 | Real-browser List geometry evidence | each treatment in a Card at two paddings, a Section, an inline Dialog with and without Layout, a BottomSheet, a padded ScrollableArea scrolling vertically and in both axes, a LayoutContent with explicit padding, and standalone; header and dividers; LTR/RTL; hovered and selected rows; a swiped row under `outset` and `bleed` | Header movement, content off the expected line, paint past the host's padding edge, clipped resting paint, or a changed row box fails | `audit:List/visual` |+| FR10 | List tests of the touch hit target and real-browser hit-testing | every density; a row with a description; compact rows packed closer than 44 px; a row with an end control; a coarse and a fine pointer; a theme row padding | A coarse-pointer row whose target stays at its box where its neighbors leave room, a target that reaches a neighboring row's or control's target, a changed row box, or a changed fine-pointer target fails | `audit:List/layout` |+| FR11 | Item press-layer tests and real-browser pixel evidence | press, hold, and release; a release while the main thread is blocked; a mouse; a pressed row between two divided rows | A release that stops while script runs, an element added for the press, a divider hidden during a press, or paint or stacking changed at rest fails | `audit:List/visual` |+| FR12 | List update-motion tests and real-browser frame evidence | an insert, a removal, and a reorder, with and without a handle; reduced motion; a mouse; a start or end slot gaining, losing, and replacing content, and changing content at the same size; the reorder handle appearing; a focused slot control leaving; a leaving slot that sets the row's height | A staying row that jumps with a handle (other than after a leaving slot that sets the row's height), motion without one, a collapsing removed row that takes focus, pointer input or an accessibility-tree node, a removed row left after its collapse ends, or layout or paint per frame fails. Also fails: a slot change that jumps with a handle (other than a leaving slot that sets the row's height), a same-size slot change that animates, a leaving slot control that keeps focus or stays reachable, a focus move that scrolls, focus that lands on the page body, or a height-setting slot that plays an exit. | `audit:List/visual` |+| Migration | `astryx upgrade` codemod tests | static, aliased, already-migrated, dynamic, and computed-`edge` callsites; a second run | A dynamic value or a computed `edge` rewritten, a static one missed, or a second run that changes output fails | `audit:List/docs` |+| Documentation | `List.doc.mjs`, Storybook, and `scripts/check-knowledge.mjs` | public prop, values, default, deprecation, and representative composition | Missing or stale contract, docs, or example fails | `audit:List/docs` |+| FR13 | List tests and real-browser tests of a row menu with a mouse, a finger, and the keyboard | a plain row, a row with `onClick`, a row with `href`; a right click, a long press, Shift+F10, the context-menu key; close by Escape and by choice; a finger's hold, a mouse's right click, the keyboard, and `presentation: 'popover'` | A wrapper element around the `<li>`, a row a context request does not open, focus left in a closed menu or not returned to the row or its button, a plain row without a named "More actions" button, or a focusable row that ignores Shift+F10 fails. A lift or press paint under a mouse, the keyboard, or `presentation: 'popover'`, or a finger's hold on a focusable row without them, fails. | `audit:List/layout` |+| FR13 reorder | Real-browser tests with a finger and a mouse on a reorderable row with a menu | a hold on the handle and on the row body of a reorderable row with a menu | A handle hold that opens the menu, or a body hold that picks the row up, fails | `audit:List/layout` |+| FR9, DEC-5 | Real-browser whole-counter ink, unordered-parent renderer parity and read-only task geometry | Static Markdown ordered lists nested in unordered and read-only task lists, LTR/RTL; general and swipe-capable Lists | Reinstating a Markdown ancestor clip cuts leading counter ink. Under unordered parents, mismatched Markdown/RichText text starts or nested insets fail. Under read-only task parents, checkbox occlusion of counters, changed checked states or incorrect Markdown parent-text anchors fail; this row does not claim task-parent cross-renderer parity coverage. Removing general List clipping lets moving rows paint outside their group. | `audit:List/visual` |## Decision log@@ -289,6 +295,22 @@ their geometry.Rejected: bleed as the default inside padded hosts, because it would move everyexisting list in a container.+### DEC-5 — Static Markdown lists preserve complete outside counters++**Reference:** `component:List/DEC-5`++**Decider:** imdreamrunner, 2026-10-29++Static Markdown document lists, ordered and unordered, MAY omit inline clipping+when their rows expose no swipe actions. Full number markers may paint toward+inline-start beyond their own list and any enclosing Markdown list, while text+starts and nested anchors follow `spec:AST-061` FR11. General Lists and+collections with swipe-capable rows retain FR9's inline clip so moving row paint+stays inside the collection's bounds. The exception does not remove a host's own+clipping or change list source, numbering, marker styles, or public APIs.++Rejected: widening a finite marker gutter, because it only moves the counter-width failure threshold.+## Open questions- **OQ1 — A caller's `::before` through a press.** The press paint takes thediff --git a/packages/core/src/List/List.tsx b/packages/core/src/List/List.tsxindex b2379d9104..1369cac627 100644--- a/packages/core/src/List/List.tsx+++ b/packages/core/src/List/List.tsx@@ -5,7 +5,8 @@/*** @file List.tsx* @input Uses React, ReactNode, StyleXStyles, theme tokens, useDevWarning,- * and ListContext with the row edge treatment+ * and ListContext with the row edge treatment. Numbered rows share one+ * intrinsic marker column, including when a counter changes digit count.* @output Exports List component, ListProps, ListDensity, ListEdge, ListStyle* types* @position Core implementation; consumed by index.ts, tested by List.test.tsx@@ -148,6 +149,16 @@ const styles = stylex.create({// vertical scroller. (StyleX emits the physical longhand of this axis.)overflowInline: 'clip',},+ // Subgridded numbered rows contribute their marker's intrinsic width to+ // one column, so text and nested lists never move with an individual number.+ numberColumns: {+ display: {+ default: 'flex',+ '@supports (grid-template-columns: subgrid)': 'grid',+ },+ gridTemplateColumns: 'max-content minmax(0, 1fr)',+ columnGap: spacingVars['--spacing-2'],+ },// 'outset' and 'bleed' rows reach into the container's padding. The list// reaches the container's padding edge on each inline edge first, so its// inline clip (above) moves out with the rows instead of cutting them; each@@ -265,6 +276,7 @@ export function List({themeProps('list', {density, listStyle}),stylex.props(styles.list,+ isOrdered && styles.numberColumns,hasDividers && styles.withDividers,reachesContainerPadding && styles.reachesContainerPadding,listStyle !== 'none' &&diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsxindex 2d48ed47e1..f90cd1dfad 100644--- a/packages/core/src/List/ListContext.tsx+++ b/packages/core/src/List/ListContext.tsx@@ -8,7 +8,8 @@* @output Exports ListContext for sharing density, dividers, the row edge* treatment, and marker style between List and ListItem, and* ListMarkerScope, which sets the marker for the items inside it, or a- * task item's checkbox in its place+ * task item's checkbox in its place, and whether their List has a marker+ * gutter whose outside counters keep the ordinary themed text inset* @position Internal context; consumed by List.tsx and ListItem.tsx*/@@ -54,6 +55,14 @@ export interface ListContextValue {* `'none'`.*/task?: ListTaskMarker;+ /**+ * Whether the List has Markdown's outside-marker gutter, set by+ * ListMarkerScope; internal. Its number column keeps the ordinary themed+ * width, while whole counters may paint toward inline-start beyond it.+ * Markdown sets this on its non-swipe numbered rows and allows outside ink+ * on their List, so its text starts match RichText without a width threshold.+ */+ hasMarkerGutter?: boolean;}export const ListContext = createContext<ListContextValue | null>(null);@@ -62,22 +71,27 @@ ListContext.displayName = 'ListContext';/*** Draws `marker` on the List items inside it, in place of the marker their* 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.+ * internal, for Markdown's nested lists and task items in mixed lists. With+ * `hasMarkerGutter`, counters keep the ordinary marker column and may paint+ * outside it toward inline-start. Outside a List, or in a List without markers, it+ * changes nothing.*/export function ListMarkerScope({marker,task,+ hasMarkerGutter = false,children,}: {readonly marker: ListMarker;readonly task?: ListTaskMarker;+ readonly hasMarkerGutter?: boolean;readonly children: ReactNode;}): ReactNode {const context = use(ListContext);const value = useMemo(- () => (context == null ? null : {...context, marker, task}),- [context, marker, task],+ () =>+ context == null ? null : {...context, marker, task, hasMarkerGutter},+ [context, marker, task, hasMarkerGutter],);return value == null ? (childrendiff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsxindex 249d20f960..7433a24c6c 100644--- a/packages/core/src/List/ListItem.tsx+++ b/packages/core/src/List/ListItem.tsx@@ -7,7 +7,13 @@* @input Uses React, ReactNode, StyleXStyles, theme tokens, the List row edge* treatment, CheckboxInput, and the marker or task checkbox a* ListMarkerScope sets (Markdown's nested lists and the task items of mixed- * lists)+ * lists), and Item's private exact-marker formatting scope for numbered+ * rows. Number markers stay on one line in the List's shared column,+ * keeping every sibling's text and nested list on the same start line;+ * they end on one line too, right-aligned with tabular figures, and hang+ * into the row's inline inset before they widen that column. Markdown's+ * outside counters keep the themed column and may paint beyond it, matching+ * RichText's native outside markers without a finite width threshold.* @output Exports ListItem component, ListItemProps type* @position Core implementation; consumed by List, index.ts, tested by List.test.tsx*@@ -22,7 +28,7 @@* - /packages/cli/assets/templates/blocks/components/List/ (showcase blocks)*/-import {use, type ReactNode} from 'react';+import {use, useMemo, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {@@ -36,6 +42,7 @@ import {ListContext, type ListMarker} from './ListContext';import {CheckboxInput} from '../CheckboxInput';import {mergeProps} from '../utils';import {Item} from '../Item';+import {ItemMarkerColumnsContext} from '../Item/ItemMarkerColumnsContext';import type {ItemAlign, ItemSwipeActions, ItemSwipeBehavior} from '../Item';import {themeProps} from '../utils/themeProps';@@ -148,6 +155,14 @@ export interface ListItemProps extends BaseProps<HTMLLIElement> {// =============================================================================const styles = stylex.create({+ numberColumns: {+ display: {+ default: 'flex',+ '@supports (grid-template-columns: subgrid)': 'grid',+ },+ gridTemplateColumns: 'subgrid',+ gridColumn: '1 / -1',+ },withCounter: {counterIncrement: 'astryx-list',},@@ -204,6 +219,16 @@ const styles = stylex.create({const MARKER_DOT_SIZE = 6;+/**+ * How far a counter wider than its marker reaches toward the row's edge: the+ * row's whole inline inset, the way a native outside marker hangs into its+ * list's padding. Up to that width the item's text keeps its usual start; a+ * wider counter widens the List's shared column instead. It is never+ * clipped: the inset is inside the row, and the row inside the List's inline+ * clip. Markdown's outside counters use a separate rule (`gutterHang`).+ */+const COUNTER_HANG = 'calc(-1 * var(--_item-inset-inline))';+const markerStyles = stylex.create({container: {alignSelf: 'baseline',@@ -237,27 +262,53 @@ const markerStyles = stylex.create({},number: {alignSelf: 'baseline',+ // The counter ends where the marker ends, so every period in a list lines+ // up, as a native outside marker's does. Tabular figures give each digit+ // the same width down the list.+ display: 'flex',+ justifyContent: 'flex-end',flexShrink: 0,color: colorVars['--color-text-primary'],fontSize: typeScaleVars['--text-body-size'],lineHeight: typeScaleVars['--text-body-leading'],- width: spacingVars['--spacing-4'],+ fontVariantNumeric: 'tabular-nums',+ // Short counters retain their inset. A longer counter first reaches into+ // the row's inline inset (COUNTER_HANG) and only then sizes the List's+ // shared grid column, so no single number moves its item's text.+ minWidth: spacingVars['--spacing-4'],+ width: 'auto',+ whiteSpace: 'nowrap',},// A number outside a counter style's range (zero or below, or past 3999// in roman) is written in decimal, as CSS counter styles fall back.decimal: {'::before': {content: 'counter(astryx-list) "."',+ marginInlineStart: COUNTER_HANG,},},lowerAlpha: {'::before': {content: 'counter(astryx-list, lower-alpha) "."',+ marginInlineStart: COUNTER_HANG,},},lowerRoman: {'::before': {content: 'counter(astryx-list, lower-roman) "."',+ marginInlineStart: COUNTER_HANG,+ },+ },+ // Markdown's non-swipe lists allow outside marker paint. Keep their marker+ // column at the ordinary themed width, as RichText's native outside markers+ // do (spec:AST-061 FR11). The counter itself stays intrinsic and unbroken;+ // flex-end aligns its end even when it overflows toward inline-start. A+ // larger finite negative margin would only move the parity failure threshold.+ gutterHang: {+ width: spacingVars['--spacing-4'],+ '::before': {+ marginInlineStart: 0,+ flexShrink: 0,},},});@@ -339,36 +390,46 @@ export function ListItem({// A task item in a list with markers shows its checkbox instead.const task = markerKind == null ? undefined : ctx?.task;- const marker =- 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)}>+ const hasMarkerGutter = ctx?.hasMarkerGutter === true;+ const marker = useMemo(+ () =>+ 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(+ markerKind === 'disc'+ ? markerStyles.dot+ : markerKind === 'circle'+ ? markerStyles.circle+ : markerStyles.square,+ )}+ />+ </span>+ ) : markerKind != null ? (<span{...stylex.props(- markerKind === 'disc'- ? markerStyles.dot- : markerKind === 'circle'- ? markerStyles.circle- : markerStyles.square,+ markerStyles.number,+ NUMBER_STYLES[markerKind],+ hasMarkerGutter && markerStyles.gutterHang,)}/>- </span>- ) : markerKind != null ? (- <span {...stylex.props(markerStyles.number, NUMBER_STYLES[markerKind])} />- ) : null;+ ) : null,+ [task, markerKind, hasMarkerGutter],+ );- return (+ const item = (<Itemas="li"ref={ref}@@ -388,6 +449,7 @@ export function ListItem({density={density}xstyle={[+ listStyle === 'decimal' && styles.numberColumns,hasMarkers && styles.withCounter,hasDividers && styles.withDivider,hasDividers && embeddedStyles.noRadius,@@ -401,6 +463,13 @@ export function ListItem({{...restProps}/>);+ // Only numbered rows contribute two cells to List's shared counter grid.+ // Passing the marker identity keeps this request off unrelated Items in slots.+ return listStyle === 'decimal' ? (+ <ItemMarkerColumnsContext value={marker}>{item}</ItemMarkerColumnsContext>+ ) : (+ item+ );}ListItem.displayName = 'ListItem';diff --git a/packages/core/src/List/ListMarkers.a11y.chromium.spec.ts b/packages/core/src/List/ListMarkers.a11y.chromium.spec.tsnew file mode 100644index 0000000000..3076258287--- /dev/null+++ b/packages/core/src/List/ListMarkers.a11y.chromium.spec.ts@@ -0,0 +1,904 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/List core/Markdown richtext/* ^apps/storybook/stories/(List|Markdown|RichTextEditor)++/**+ * @file ListMarkers.a11y.chromium.spec.ts+ * @input Built Storybook's long List and nested Markdown counter examples,+ * plus a 16px Theme-provider comparison with both RichText surfaces+ * @output Rendered proof that counters, item text, and nested lists stay+ * aligned: counters on one line, ending on one edge, never clipped, and+ * Markdown's text starts matching RichText for counters beyond the gutter+ * @position Core browser regression; no declaration snapshots or committed images+ */++import {writeFile} from 'node:fs/promises';+import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => storybook?.close());++/** A list's rows: each counter's marker box, in page coordinates. */+interface MarkerBox {+ readonly top: number;+ readonly bottom: number;+ readonly left: number;+ readonly right: number;+ /** Intrinsic rendered counter width, including ink outside the marker box. */+ readonly counterWidth: number;+ readonly textStart: number;+}++/** Paints every counter red and everything else transparent. */+const COUNTERS_ONLY = `+ #storybook-root, #storybook-root * { color: transparent !important; }+ #storybook-root ol > li > :first-child { color: rgb(255, 0, 0) !important; }+`;++/** Takes the lists' inline clip away, to tell a clipped counter from a whole one. */+const UNCLIPPED = '#storybook-root ol { overflow: visible !important; }';++/** Where a counter's ink starts and ends, in page pixels. */+interface Ink {+ readonly start: number;+ readonly end: number;+ readonly top: number;+ readonly bottom: number;+}++/**+ * The inline extent of each counter's ink: the red pixels within a band+ * reaching from its marker toward the inline start, wide enough for any+ * counter that hangs past it, and stopping just past the marker's end so it+ * never takes in the row's own content. The page decodes the screenshot.+ */+async function inkOf(+ page: Page,+ screenshot: Buffer,+ boxes: ReadonlyArray<MarkerBox>,+ dir: 'ltr' | 'rtl',+): Promise<Ink[]> {+ return page.evaluate(+ async ({png, rows, rtl}) => {+ const image = new Image();+ image.src = `data:image/png;base64,${png}`;+ await image.decode();+ const canvas = document.createElement('canvas');+ canvas.width = image.naturalWidth;+ canvas.height = image.naturalHeight;+ const context = canvas.getContext('2d', {willReadFrequently: true});+ if (context == null) {+ throw new Error('no 2d canvas');+ }+ context.drawImage(image, 0, 0);+ const {data, width} = context.getImageData(+ 0,+ 0,+ canvas.width,+ canvas.height,+ );+ return rows.map(box => {+ let start = Infinity;+ let end = -Infinity;+ let top = Infinity;+ let bottom = -Infinity;+ const from = Math.max(+ 0,+ Math.floor(rtl ? box.left - 2 : box.right - box.counterWidth - 2),+ );+ const to = Math.min(+ width,+ Math.ceil(rtl ? box.left + box.counterWidth + 2 : box.right + 2),+ );+ for (let y = Math.floor(box.top); y < Math.ceil(box.bottom); y++) {+ for (let x = from; x < to; x++) {+ const i = (y * width + x) * 4;+ if (data[i] - Math.max(data[i + 1], data[i + 2]) > 80) {+ start = Math.min(start, x);+ end = Math.max(end, x + 1);+ top = Math.min(top, y);+ bottom = Math.max(bottom, y + 1);+ }+ }+ }+ return {start, end, top, bottom};+ });+ },+ {+ png: screenshot.toString('base64'),+ rows: boxes,+ rtl: dir === 'rtl',+ },+ );+}++/** Each list's marker boxes, outermost list first, in page coordinates. */+async function markerBoxes(+ page: Page,+ selector = '#storybook-root ol',+): Promise<MarkerBox[][]> {+ return page.locator(selector).evaluateAll(lists =>+ lists.map(list =>+ Array.from(list.children, item => {+ const marker = item.firstElementChild;+ if (marker == null) {+ throw new Error('missing marker');+ }+ const box = marker.getBoundingClientRect();+ const pseudoWidth = Number.parseFloat(+ getComputedStyle(marker, '::before').width,+ );+ const content = marker.nextElementSibling?.getBoundingClientRect();+ if (content == null) {+ throw new Error('missing item content');+ }+ const rtl = getComputedStyle(item).direction === 'rtl';+ return {+ top: box.top + window.scrollY,+ bottom: box.bottom + window.scrollY,+ left: box.left + window.scrollX,+ right: box.right + window.scrollX,+ counterWidth: Number.isFinite(pseudoWidth) ? pseudoWidth : box.width,+ textStart: (rtl ? content.right : content.left) + window.scrollX,+ };+ }),+ ),+ );+}++for (const {width, mode} of [+ {width: 1280, mode: 'light'},+ {width: 390, mode: 'dark'},+] as const) {+ for (const dir of ['ltr', 'rtl'] as const) {+ for (const story of [+ 'core-list--long-number-markers',+ 'core-list--numbered-first-line',+ 'core-markdown--long-number-markers',+ ]) {+ test(`${story}: shared counter column (${width}px, ${mode}, ${dir})`, async ({+ page,+ }, testInfo) => {+ await page.setViewportSize({width, height: 900});+ await page.goto(+ `${storybook.origin}/iframe.html?id=${story}&viewMode=story&globals=direction:${dir};colorMode:${mode}`,+ );+ await expect(page.locator('#storybook-root ol').first()).toBeVisible();+ await expect+ .poll(async () =>+ page.evaluate(+ () => getComputedStyle(document.documentElement).colorScheme,+ ),+ )+ .toBe(mode);+ await page.evaluate(async () => document.fonts.ready);+ const lists = await page+ .locator('#storybook-root ol')+ .evaluateAll(elements =>+ elements.map(list => {+ let depth = 0;+ for (let up = list.parentElement; up; up = up.parentElement) {+ if (up.tagName === 'OL' || up.tagName === 'UL') {+ depth += 1;+ }+ }+ const items = Array.from(list.children).map(item => {+ const marker = item.firstElementChild;+ const content = marker?.nextElementSibling;+ if (marker == null || content == null) {+ throw new Error('missing marker or content');+ }+ const m = marker.getBoundingClientRect();+ const c = content.getBoundingClientRect();+ const rtl = getComputedStyle(item).direction === 'rtl';+ const nested = content+ .querySelector('ol')+ ?.getBoundingClientRect();+ const label = content.querySelector(':scope > span > span');+ const labelRect = label?.getBoundingClientRect();+ const labelLine =+ label == null+ ? 0+ : Number.parseFloat(getComputedStyle(label).lineHeight);+ const firstLineOffset =+ labelRect == null+ ? null+ : m.top ++ Number.parseFloat(getComputedStyle(marker).lineHeight) /+ 2 -+ (labelRect.top + labelLine / 2);+ return {+ direction: getComputedStyle(item).direction,+ firstLineOffset,+ textStart: rtl ? c.right : c.left,+ markerHeight: m.height,+ lineHeight: Number.parseFloat(+ getComputedStyle(marker).lineHeight,+ ),+ markerWidth: m.width,+ markerScrollWidth: marker.scrollWidth,+ numerals: getComputedStyle(marker).fontVariantNumeric,+ gap: rtl ? m.left - c.right : c.left - m.right,+ nestedStart:+ nested == null ? null : rtl ? nested.right : nested.left,+ };+ });+ return {depth, items};+ }),+ );+ expect(lists.length).toBeGreaterThan(0);+ for (const {items} of lists) {+ const starts = items.map(item => item.textStart);+ expect(Math.max(...starts) - Math.min(...starts)).toBeLessThanOrEqual(+ 1,+ );+ for (const item of items) {+ expect(item.direction).toBe(dir);+ expect(item.markerHeight).toBeLessThanOrEqual(item.lineHeight + 1);+ expect(item.markerScrollWidth).toBeLessThanOrEqual(+ item.markerWidth + 1,+ );+ expect(item.gap).toBeGreaterThan(0);+ }+ }+ if (story === 'core-list--numbered-first-line') {+ expect(lists[0].items).toHaveLength(2);+ for (const item of lists[0].items) {+ expect(item.firstLineOffset).not.toBeNull();+ expect(+ Math.abs(item.firstLineOffset ?? Infinity),+ ).toBeLessThanOrEqual(1);+ }+ } else if (story === 'core-list--long-number-markers') {+ expect(lists[0].items).toHaveLength(3);+ } else {+ expect(lists[0].items).toHaveLength(5);+ const nested = lists[0].items+ .map(item => item.nestedStart)+ .filter(value => value != null);+ expect(nested).toHaveLength(3);+ expect(Math.max(...nested) - Math.min(...nested)).toBeLessThanOrEqual(+ 1,+ );+ expect(lists.some(({items}) => items.length === 8)).toBe(true);+ // spec:AST-061 FR11: a list whose counters reach `12.` starts its+ // text where a list of one short counter does, as RichText's native+ // markers leave it: the wide counters hang toward the start.+ const outer = lists+ .filter(({depth}) => depth === 0)+ .map(({items}) => items[0].textStart);+ expect(outer).toHaveLength(2);+ expect(Math.abs(outer[0] - outer[1])).toBeLessThanOrEqual(1);+ }+ await page.screenshot({+ path: testInfo.outputPath(`${story}-${width}-${mode}-${dir}.png`),+ });++ // The counters' own ink: each ends on the list's one counter edge, as+ // native outside markers do, and each is whole: lifting the lists'+ // inline clip shows no more of it.+ const boxes = await markerBoxes(page);+ await page.addStyleTag({content: COUNTERS_ONLY});+ const clipped = await page.screenshot({fullPage: true});+ await page.addStyleTag({content: UNCLIPPED});+ const whole = await page.screenshot({fullPage: true});+ for (const [index, list] of boxes.entries()) {+ const ink = await inkOf(page, clipped, list, dir);+ expect(ink, `list ${index}: whole counters`).toEqual(+ await inkOf(page, whole, list, dir),+ );+ for (const {start, end} of ink) {+ expect(Number.isFinite(start) && Number.isFinite(end)).toBe(true);+ }+ const edges = ink.map(({start, end}) =>+ dir === 'rtl' ? start : end,+ );+ expect(+ Math.max(...edges) - Math.min(...edges),+ `list ${index}: counters end together`,+ ).toBeLessThanOrEqual(1);+ }+ // Every digit is one width, so numbers line up digit by digit.+ for (const {items} of lists) {+ for (const item of items) {+ expect(item.numerals).toContain('tabular-nums');+ }+ }+ });+ }+ }+}++// FR11 has no counter-width exemption. A fixed larger gutter would only move+// the failure threshold: exercise four and nine digits and long roman counters+// with the actual body theme at 16px, not the default 14px desktop theme.+for (const {width, mode} of [+ {width: 1440, mode: 'light'},+ {width: 390, mode: 'dark'},+] as const) {+ for (const dir of ['ltr', 'rtl'] as const) {+ test(`16px outside counters match all document surfaces (${width}px, ${mode}, ${dir})`, async ({+ page,+ browser,+ }, testInfo) => {+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.setViewportSize({width, height: 900});+ await page.goto(+ `${storybook.origin}/iframe.html?id=richtext-richtexteditor--markdown-parity-wide-number-markers&viewMode=story&globals=direction:${dir};colorMode:${mode}`,+ );+ await expect(+ page.locator('[data-wide-marker-surface="editor"] li').last(),+ ).toBeVisible();+ await page.evaluate(async () => document.fonts.ready);+ const surfaces = await page+ .locator('[data-wide-marker-surface]')+ .evaluateAll(roots =>+ roots.map(root => {+ const rtl = getComputedStyle(root).direction === 'rtl';+ const firstOwnText = (element: Element): Text | null => {+ const walker = document.createTreeWalker(+ element,+ NodeFilter.SHOW_TEXT,+ );+ for (+ let node = walker.nextNode();+ node;+ node = walker.nextNode()+ ) {+ if (+ node.textContent?.trim() &&+ node.parentElement?.closest('li') ===+ (element.tagName === 'LI' ? element : null)+ ) {+ return node as Text;+ }+ }+ return null;+ };+ const line = (node: Text) => {+ const range = document.createRange();+ range.selectNodeContents(node);+ const boxes = Array.from(range.getClientRects());+ // A wrapped text node can expose multiple bidi fragments on one+ // line; count distinct line tops, not Range fragment rectangles.+ return {+ start: rtl+ ? Math.max(+ ...boxes+ .filter(box => box.top === boxes[0].top)+ .map(box => box.right),+ )+ : Math.min(+ ...boxes+ .filter(box => box.top === boxes[0].top)+ .map(box => box.left),+ ),+ lines: new Set(+ boxes.filter(box => box.width > 0).map(box => box.top),+ ).size,+ };+ };+ const references = document.createTreeWalker(+ root,+ NodeFilter.SHOW_TEXT,+ );+ let reference: Text | null = null;+ for (+ let node = references.nextNode();+ node;+ node = references.nextNode()+ ) {+ if (node.textContent?.trim() === 'Reference paragraph.') {+ reference = node as Text;+ break;+ }+ }+ if (reference == null) {+ throw new Error('missing reference paragraph');+ }+ const origin = line(reference).start;+ return {+ surface: root.getAttribute('data-wide-marker-surface'),+ measure: (+ root.querySelector('[data-lexical-editor]') ??+ root.firstElementChild+ )?.getBoundingClientRect().width,+ direction: getComputedStyle(root).direction,+ items: Array.from(root.querySelectorAll('li')).flatMap(item => {+ const node = firstOwnText(item);+ if (node?.parentElement == null) {+ return [];+ }+ const font = getComputedStyle(node.parentElement);+ const {start, lines} = line(node);+ return [+ {+ text: node.textContent.trim(),+ start: start - origin,+ lines,+ fontSize: font.fontSize,+ fontFamily: font.fontFamily,+ },+ ];+ }),+ counters:+ root.getAttribute('data-wide-marker-surface') !== 'markdown'+ ? []+ : Array.from(+ root.querySelectorAll('ol > li > :first-child'),+ ).map(marker => {+ const style = getComputedStyle(marker);+ return {+ fontSize: style.fontSize,+ height: marker.getBoundingClientRect().height,+ lineHeight: Number.parseFloat(style.lineHeight),+ };+ }),+ };+ }),+ );+ // Bank the unmodified pixels and measured fonts/line starts even on red.+ await page.screenshot({+ path: testInfo.outputPath('surfaces.png'),+ fullPage: true,+ });+ await writeFile(+ testInfo.outputPath('geometry.json'),+ JSON.stringify(+ {browser: browser.version(), width, mode, dir, surfaces},+ null,+ 2,+ ),+ );+ expect(surfaces.map(({surface}) => surface)).toEqual([+ 'markdown',+ 'view',+ 'editor',+ ]);+ const [markdown] = surfaces;+ expect(markdown.items.map(({text}) => text)).toContain('Four digits');+ expect(markdown.items.map(({text}) => text)).toContain('Long roman');+ expect(markdown.items.map(({text}) => text)).toContain(+ 'Much wider roman',+ );+ for (const surface of surfaces) {+ expect(surface.direction).toBe(dir);+ expect(surface.items.map(({text}) => text)).toEqual(+ markdown.items.map(({text}) => text),+ );+ for (const [index, item] of surface.items.entries()) {+ expect(item.fontSize, `${surface.surface}: ${item.text}`).toBe(+ '16px',+ );+ expect(item.fontFamily).toBe(markdown.items[index].fontFamily);+ expect(+ Math.abs((surface.measure ?? 0) - (markdown.measure ?? 0)),+ ).toBeLessThanOrEqual(0.5);+ expect(item.lines, `${surface.surface}: lines of ${item.text}`).toBe(+ markdown.items[index].lines,+ );+ expect(+ Math.abs(item.start - markdown.items[index].start),+ `${surface.surface}: ${item.text}`,+ ).toBeLessThanOrEqual(0.5);+ }+ }+ // Siblings and the nested anchors stay at their depth's ordinary inset.+ // This is rendered geometry, not a declaration-only assertion.+ const starts = new Map(+ markdown.items.map(item => [item.text, item.start]),+ );+ const startOf = (text: string): number => {+ const start = starts.get(text);+ if (start == null) {+ throw new Error(`missing item: ${text}`);+ }+ return start;+ };+ for (const text of [+ 'Before four digits',+ 'Four digits',+ 'Sibling after four digits',+ 'Year counter',+ 'Nine digits',+ ]) {+ expect(+ Math.abs(startOf(text) - startOf('Short decimal')),+ text,+ ).toBeLessThanOrEqual(0.5);+ }+ expect(+ Math.abs(startOf('Outer parent') - startOf('Other outer parent')),+ ).toBeLessThanOrEqual(0.5);+ expect(+ Math.abs(startOf('Middle parent') - startOf('Other middle parent')),+ ).toBeLessThanOrEqual(0.5);+ for (const text of [+ 'Before long roman',+ 'Long roman',+ 'After long roman',+ 'Much wider roman',+ ]) {+ expect(+ Math.abs(startOf(text) - startOf('Short roman')),+ text,+ ).toBeLessThanOrEqual(0.5);+ }+ for (const counter of markdown.counters) {+ expect(counter.fontSize).toBe('16px');+ expect(counter.height).toBeLessThanOrEqual(counter.lineHeight + 1);+ }+ const boxes = await markerBoxes(+ page,+ '[data-wide-marker-surface="markdown"] ol',+ );+ await page.addStyleTag({+ content: `#storybook-root, #storybook-root * {color: transparent !important;} #storybook-root [data-wide-marker-surface="markdown"] ol > li > :first-child {color: rgb(255, 0, 0) !important;}`,+ });+ const resting = await page.screenshot({+ path: testInfo.outputPath('counter-ink.png'),+ fullPage: true,+ });+ await page.addStyleTag({content: UNCLIPPED});+ const unclipped = await page.screenshot({fullPage: true});+ for (const list of boxes) {+ for (const box of list) {+ expect(box.counterWidth).toBeGreaterThan(0);+ // Outside ink must be within the photographed viewport; otherwise+ // two equally cropped frames would not prove a whole counter.+ expect(+ dir === 'rtl' ? box.left : box.right - box.counterWidth,+ ).toBeGreaterThanOrEqual(0);+ expect(+ dir === 'rtl' ? box.left + box.counterWidth : box.right,+ ).toBeLessThanOrEqual(width);+ }+ const ink = await inkOf(page, resting, list, dir);+ expect(ink).toEqual(await inkOf(page, unclipped, list, dir));+ expect(+ ink.every(+ ({start, end}) => Number.isFinite(start) && Number.isFinite(end),+ ),+ ).toBe(true);+ for (const [index, extent] of ink.entries()) {+ const gap =+ dir === 'rtl'+ ? extent.start - list[index].textStart+ : list[index].textStart - extent.end;+ expect(gap, 'counter ink never overlaps item text').toBeGreaterThan(+ 0,+ );+ }+ const ends = ink.map(({start, end}) => (dir === 'rtl' ? start : end));+ expect(Math.max(...ends) - Math.min(...ends)).toBeLessThanOrEqual(1);+ }+ expect(errors).toEqual([]);+ });+ }+}++// Static Markdown's outside-paint exception must not weaken general List or+// the clip containing swipe-capable rows (component:List FR9).+test('general and swipe-capable Lists retain their inline clip', async ({+ page,+}, testInfo) => {+ const states = [];+ for (const dir of ['ltr', 'rtl'] as const) {+ for (const story of [+ 'core-list--long-number-markers',+ 'core-item--swipe-actions',+ 'core-checkboxlist--default',+ ]) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${story}&viewMode=story&globals=direction:${dir};colorMode:light`,+ );+ await expect(+ page.locator('#storybook-root .astryx-list').first(),+ ).toBeVisible();+ const lists = await page+ .locator('#storybook-root .astryx-list')+ .evaluateAll(elements =>+ elements.map(element => ({+ direction: getComputedStyle(element).direction,+ overflowX: getComputedStyle(element).overflowX,+ })),+ );+ expect(lists.length).toBeGreaterThan(0);+ for (const list of lists) {+ expect(list.direction).toBe(dir);+ expect(list.overflowX).toBe('clip');+ }+ states.push({story, dir, lists});+ }+ }+ await writeFile(+ testInfo.outputPath('general-list-clipping.json'),+ JSON.stringify(states, null, 2),+ );+});++// A numbered list's outside counter must not be cut by an unordered ancestor.+// Removing only OL clipping misses this mixed nesting path (AST-061 FR11).+for (const {name, story, probe, hasTasks} of [+ {+ name: 'mixed',+ story: 'mixed-number-markers',+ probe: 'Mixed roman counter',+ hasTasks: false,+ },+ {+ name: 'pure task-parent',+ story: 'task-parent-number-markers',+ probe: 'Task roman counter',+ hasTasks: true,+ },+] as const) {+ for (const dir of ['ltr', 'rtl'] as const) {+ test(`${name} nested counter stays whole (${dir})`, async ({+ page,+ }, testInfo) => {+ await page.setViewportSize({width: 1440, height: 900});+ await page.goto(+ `${storybook.origin}/iframe.html?id=richtext-richtexteditor--markdown-parity-${story}&viewMode=story&globals=direction:${dir};colorMode:light`,+ );+ const root = '[data-wide-marker-surface="markdown"]';+ await expect(page.locator(`${root} ol > li`)).toHaveCount(2);+ await expect(+ page.locator('[data-wide-marker-surface="view"]'),+ ).toContainText(probe);+ await page.evaluate(async () => document.fonts.ready);+ const labels = hasTasks+ ? [+ 'Reference paragraph.',+ 'Outer task',+ 'Inner task',+ 'Task roman counter',+ 'Task roman sibling',+ ]+ : [+ 'Reference paragraph.',+ 'Outer bullet',+ 'Inner bullet',+ 'Mixed roman counter',+ 'Roman sibling',+ ];+ const geometry = await page+ .locator('[data-wide-marker-surface]')+ .evaluateAll(+ (roots, labels) =>+ roots.map(surface => {+ const rtl = getComputedStyle(surface).direction === 'rtl';+ const rows = new Map<+ string,+ {start: number; top: number; lines: number; fontSize: string}+ >();+ const walker = document.createTreeWalker(+ surface,+ NodeFilter.SHOW_TEXT,+ );+ for (+ let node = walker.nextNode();+ node;+ node = walker.nextNode()+ ) {+ const text = node.textContent?.trim() ?? '';+ const parent = node.parentElement;+ if (+ !labels.includes(text) ||+ parent == null ||+ parent.closest('label') != null+ ) {+ continue;+ }+ const range = document.createRange();+ range.selectNodeContents(node);+ const rects = Array.from(range.getClientRects()).filter(+ rect => rect.width > 0,+ );+ const first = rects.filter(rect => rect.top === rects[0].top);+ rows.set(text, {+ start: rtl+ ? Math.max(...first.map(rect => rect.right))+ : Math.min(...first.map(rect => rect.left)),+ top: rects[0].top + window.scrollY,+ lines: new Set(rects.map(rect => rect.top)).size,+ fontSize: getComputedStyle(parent).fontSize,+ });+ }+ const origin = rows.get('Reference paragraph.')?.start ?? NaN;+ return {+ surface: surface.getAttribute('data-wide-marker-surface'),+ origin,+ lists: Array.from(surface.querySelectorAll('ul, ol')).map(+ list => {+ const box = list.getBoundingClientRect();+ const style = getComputedStyle(list);+ return {+ tag: list.tagName,+ start: (rtl ? box.right : box.left) - origin,+ paddingStart: style.paddingInlineStart,+ marker: style.listStyleType,+ overflow: style.overflowX,+ };+ },+ ),+ measure:+ (+ surface.querySelector('[data-lexical-editor]') ??+ surface.firstElementChild+ )?.getBoundingClientRect().width ?? NaN,+ text: Array.from(rows, ([label, line]) => ({+ label,+ ...line,+ start: line.start - origin,+ })),+ checkboxes: Array.from(+ surface.querySelectorAll<HTMLInputElement>(+ 'input[type="checkbox"]',+ ),+ ).map((input, index) => {+ const box = input.getBoundingClientRect();+ const parentText = rows.get(+ index === 0 ? 'Outer task' : 'Inner task',+ );+ return {+ checked: input.checked,+ width: box.width,+ gap:+ parentText == null+ ? null+ : rtl+ ? box.left - parentText.start+ : parentText.start - box.right,+ top: box.top + window.scrollY,+ bottom: box.bottom + window.scrollY,+ left: box.left + window.scrollX,+ right: box.right + window.scrollX,+ };+ }),+ };+ }),+ labels,+ );+ const boxes = await markerBoxes(page, `${root} ol`);+ await page.screenshot({+ path: testInfo.outputPath('mixed-surfaces.png'),+ fullPage: true,+ });+ await page.addStyleTag({+ content: `#storybook-root, #storybook-root * {color: transparent !important;} #storybook-root ${root} ol > li > :first-child {color: rgb(255, 0, 0) !important;}`,+ });+ const resting = await page.screenshot({+ path: testInfo.outputPath('mixed-resting-ink.png'),+ fullPage: true,+ });+ // This diagnostic lifts ALL list ancestors, not just numbered lists.+ await page.addStyleTag({+ content:+ '#storybook-root ul, #storybook-root ol {overflow: visible !important;}',+ });+ const whole = await page.screenshot({+ path: testInfo.outputPath('mixed-whole-ink.png'),+ fullPage: true,+ });+ const ink = await inkOf(page, resting, boxes[0], dir);+ const unclipped = await inkOf(page, whole, boxes[0], dir);+ const overlaps =+ geometry?.[0].checkboxes.flatMap(checkbox =>+ unclipped.map(counter => ({+ width: Math.max(+ 0,+ Math.min(counter.end, checkbox.right) -+ Math.max(counter.start, checkbox.left),+ ),+ height: Math.max(+ 0,+ Math.min(counter.bottom, checkbox.bottom) -+ Math.max(counter.top, checkbox.top),+ ),+ })),+ ) ?? [];+ await writeFile(+ testInfo.outputPath('mixed-counter-receipt.json'),+ JSON.stringify(+ {dir, boxes, ink, unclipped, geometry, overlaps},+ null,+ 2,+ ),+ );+ for (const box of boxes[0]) {+ expect(box.counterWidth).toBeGreaterThan(40);+ expect(+ dir === 'rtl' ? box.left : box.right - box.counterWidth,+ ).toBeGreaterThanOrEqual(0);+ expect(+ dir === 'rtl' ? box.left + box.counterWidth : box.right,+ ).toBeLessThanOrEqual(1440);+ }+ expect(ink, 'unordered ancestors do not clip roman counters').toEqual(+ unclipped,+ );+ {+ const markdown = geometry[0];+ for (const surface of geometry) {+ expect(surface.checkboxes.map(input => input.checked)).toEqual(+ hasTasks ? [false, true] : [],+ );+ expect(surface.text).toHaveLength(5);+ expect(+ Math.abs(surface.measure - markdown.measure),+ ).toBeLessThanOrEqual(0.5);+ for (const text of surface.text) {+ const other = markdown.text.find(line => line.label === text.label);+ expect(text.fontSize).toBe('16px');+ expect(+ text.lines,+ `${surface.surface}: ${text.label} line count`,+ ).toBe(other?.lines);+ if (!hasTasks) {+ expect(+ Math.abs(text.start - (other?.start ?? NaN)),+ `${surface.surface}: ${text.label} text start / nested inset`,+ ).toBeLessThanOrEqual(1);+ }+ // The inherited task-parent inset mismatch is recorded separately.+ // This task receipt stays diagnostic for cross-renderer starts;+ // Markdown's parent-text anchors are asserted below.+ }+ }+ if (hasTasks) {+ const starts = new Map(+ markdown.text.map(line => [line.label, line.start]),+ );+ const direction = dir === 'rtl' ? -1 : 1;+ expect(starts.get('Outer task')).toBe(direction * 28);+ expect(starts.get('Inner task')).toBe(direction * 56);+ expect(starts.get('Task roman counter')).toBe(direction * 80);+ expect(starts.get('Task roman sibling')).toBe(direction * 80);+ for (const overlap of overlaps) {+ expect(+ overlap.width * overlap.height,+ 'checkbox never covers counter ink',+ ).toBe(0);+ }+ for (const [index, checkbox] of markdown.checkboxes.entries()) {+ const label = markdown.text.find(+ line =>+ line.label === (index === 0 ? 'Outer task' : 'Inner task'),+ );+ if (label == null) {+ throw new Error('missing task parent text');+ }+ expect(+ checkbox.top,+ 'checkbox stays on the parent text line',+ ).toBeLessThan(label.top + 24);+ expect(checkbox.bottom).toBeGreaterThan(label.top);+ }+ const inputs = page.locator(`${root} input[type="checkbox"]`);+ for (const input of await inputs.all()) {+ await expect(input).toHaveAttribute('aria-readonly', 'true');+ await input.click({force: true});+ await input.focus();+ await page.keyboard.press('Space');+ }+ expect(+ await inputs.evaluateAll(elements =>+ elements.map(element => (element as HTMLInputElement).checked),+ ),+ ).toEqual([false, true]);+ }+ }+ });+ }+}diff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsxindex bccaf0eec3..2a7a52c1d0 100644--- a/packages/core/src/Markdown/Markdown.test.tsx+++ b/packages/core/src/Markdown/Markdown.test.tsx@@ -1,5 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file Markdown.test.tsx+ * @input Markdown renderer, supported blocks and source-line plugin+ * @output Semantic, flat-task identity and nested flow-task regressions+ * @position Core Markdown unit tests+ */+import {describe,it,@@ -13,6 +20,7 @@ import {render, screen, fireEvent} from '@testing-library/react';import type {ComponentProps, ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {Markdown} from './Markdown';+import {markdownSourceLinesPlugin} from './plugins';import type {MarkdownComponents,MarkdownInlinePlugin,@@ -531,6 +539,48 @@ describe('Markdown', () => {expect(checkboxes).toHaveLength(2);expect((checkboxes[0] as HTMLInputElement).checked).toBe(true);expect((checkboxes[1] as HTMLInputElement).checked).toBe(false);+ // Preserve the released flat pure-task grouping/naming path.+ expect(document.querySelector('.astryx-checkbox-list')).not.toBeNull();+ expect(screen.getByRole('group')).toHaveAttribute('aria-labelledby');+ });++ it('keeps nested pure-task rows on the static marker path with source lines', () => {+ render(+ <Markdown plugins={[markdownSourceLinesPlugin]}>+ {+ '- [ ] Outer task\n - [x] Inner task\n\n 388. Counter\n 389. Sibling'+ }+ </Markdown>,+ );+ expect(document.querySelector('.astryx-checkbox-list')).toBeNull();+ const checkboxes = screen.getAllByRole<HTMLInputElement>('checkbox');+ expect(checkboxes.map(input => input.checked)).toEqual([false, true]);+ for (const input of checkboxes) {+ expect(input).toHaveAttribute('aria-readonly', 'true');+ }+ expect(+ Array.from(document.querySelectorAll('li'), item =>+ item.getAttribute('data-source-line'),+ ),+ ).toEqual(['1', '2', '4', '5']);+ });++ it('uses the static task marker path for lists nested through a blockquote', () => {+ render(+ <Markdown>+ {'- [ ] Outer task\n\n > 388. Quoted counter\n > 389. Quoted sibling'}+ </Markdown>,+ );+ expect(document.querySelector('.astryx-checkbox-list')).toBeNull();+ expect(screen.getAllByRole('checkbox')).toHaveLength(1);+ expect(screen.getByRole('checkbox')).toHaveAttribute(+ 'aria-readonly',+ 'true',+ );+ expect(document.querySelector('blockquote ol')).toHaveAttribute(+ 'start',+ '388',+ );});it('keeps each task item checked or open in a list that mixes task and plain items (FR23)', () => {diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex e33a355583..768853b91f 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -4,7 +4,11 @@/*** @file Markdown.tsx- * @input Markdown string, canonical AST, optional plugins and custom renderers+ * @input Markdown string, canonical AST, optional plugins and custom renderers;+ * static document lists permit outside counter paint through ordered and+ * unordered ancestors. Flow-task+ * bodies use per-item first-line markers; paragraph-only task lists retain+ * their CheckboxList representation.* @output Exports Markdown component, MarkdownProps, and renderer contracts* @position Core implementation; renders markdown as Astryx components*/@@ -587,8 +591,20 @@ const styles = stylex.create({'--container-padding-block-start': '0px','--container-padding-block-end': '0px',},+ // Static Markdown lists never host swipe actions. Let outside counter ink+ // paint through both ordered and unordered ancestors; general List and+ // swipe-capable rows retain their own inline clip (component:List FR9).blockIndent: {marginInline: `calc(-1 * ${spacingVars['--spacing-2']})`,+ overflowInline: 'visible',+ },+ // Numbered document lists keep their ordinary text inset regardless of+ // counter width, matching RichText's native outside markers (AST-061 FR11).+ // These rows have no swipe actions: unlike general List, their outside ink+ // may paint past the gutter instead of being clipped at a finite threshold.+ markerGutter: {+ marginInlineStart: `calc(-1 * (${spacingVars['--spacing-2']} + ${spacingVars['--spacing-4']}))`,+ paddingInlineStart: spacingVars['--spacing-4'],},// HRhr: {@@ -1686,10 +1702,16 @@ function renderBlock();}case 'list': {- // Detect task lists: all items have a checked state+ // Preserve the released CheckboxList representation for paragraph-only+ // pure task lists. Flow/nested task bodies use the shared per-item marker+ // path below, which owns first-line placement and static outside paint.const isTaskList =node.children.length > 0 &&- node.children.every(item => item.checked != null);+ node.children.every(+ item =>+ item.checked != null &&+ item.children.every(block => block.type === 'paragraph'),+ );if (isTaskList) {// Extract labels from task items — render as rich inline content@@ -1803,7 +1825,7 @@ function renderBlock(listStyle={node.ordered ? 'decimal' : 'disc'}density="compact"start={node.ordered ? node.start : undefined}- xstyle={styles.blockIndent}>+ xstyle={[styles.blockIndent, node.ordered && styles.markerGutter]}>{node.children.map((item, i) => {const firstChild = item.children[0];const isInline =@@ -1855,7 +1877,7 @@ function renderBlock(</>);- // A task item beside plain items keeps its own checked state+ // Each task item on this shared list path keeps its checked state// (FR23): it shows a read-only checkbox where its marker// would be, named by its text.const firstParagraph = item.children.find(@@ -1888,7 +1910,8 @@ function renderBlock(listDepth % 3]}- task={task}>+ task={task}+ hasMarkerGutter={node.ordered}><ListItemlabel={label}{...(recordsSourceLinesdiff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.tsindex f1bcb4664d..1171967aa1 100644--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts@@ -450,6 +450,71 @@ test('side by side: a list of task and plain items keeps each task checkbox andexpect(errors).toEqual([]);});+// spec:AST-061 FR11: however wide a numbered list's counters grow, from `99.`+// to `100.` or from `i.` to `viii.` two lists down, each item's text, and each+// nested list's, starts in the same place on both surfaces.+test('side by side: wide counters start the text where RichText starts it', async ({+ page,+}) => {+ const errors = await openStory(page, STORY.sideBySide, DESKTOP);+ await waitForDocument(page, MARKDOWN);+ await waitForDocument(page, RICH_TEXT);+ const textStarts = (surface: string) =>+ page.evaluate(selector => {+ const block = document.querySelector(+ `${selector} [data-parity-block="list-ordered-wide"]`,+ );+ const origin = block?.getBoundingClientRect().left ?? 0;+ const starts: Array<[string, number]> = [];+ for (const item of block?.querySelectorAll('li') ?? []) {+ // The item's own first text; RichText holds a nested list in an item+ // of its own, which has none.+ const walker = document.createTreeWalker(item, NodeFilter.SHOW_TEXT);+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ if (!node.textContent?.trim()) {+ continue;+ }+ if (node.parentElement?.closest('li') === item) {+ const range = document.createRange();+ range.selectNodeContents(node);+ starts.push([+ node.textContent.trim(),+ range.getBoundingClientRect().left - origin,+ ]);+ }+ break;+ }+ }+ return starts;+ }, surface);+ const markdown = await textStarts(MARKDOWN);+ const richText = new Map(await textStarts(RICH_TEXT));+ expect(markdown.map(([text]) => text)).toEqual([+ 'Wide step ninety-eight',+ 'Wide step ninety-nine',+ 'Lettered step a',+ 'Roman step i',+ 'Roman step ii',+ 'Roman step iii',+ 'Roman step iv',+ 'Roman step v',+ 'Roman step vi',+ 'Roman step vii',+ 'Roman step viii',+ 'Wide step one hundred',+ ]);+ expect([...richText.keys()].sort()).toEqual(+ markdown.map(([text]) => text).sort(),+ );+ for (const [text, start] of markdown) {+ expect(+ Math.abs((richText.get(text) ?? Number.NaN) - start),+ `text of ${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.