An open source design system that's fully customizable and agent ready
TypeScript
feat(Markdown): give each list depth its own marker, as AST-061 DEC-6 defines (#7027)
Cindy Zhang310177296d63
diff --git a/.changeset/markdown-list-marker-cycle.md b/.changeset/markdown-list-marker-cycle.mdnew file mode 100644index 0000000000..d2ad3d34f1--- /dev/null+++ b/.changeset/markdown-list-marker-cycle.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+---++[feat] Markdown: nested lists draw a different marker at each depth+@cixzhang++Bulleted lists cycle disc, circle, and square, and numbered lists cycle decimal, lower-alpha, and lower-roman, by how many lists of either kind enclose them, so each level can be told apart from the levels beside it. Numbering keeps each list's start and items. `List` and `ListItem` keep their public marker styles.diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsxindex 7bb6f79871..e008707058 100644--- a/apps/storybook/stories/Markdown.stories.tsx+++ b/apps/storybook/stories/Markdown.stories.tsx@@ -226,6 +226,50 @@ export const LazyContinuations: Story = {},};+const NESTED_LIST_DEPTHS = Array.from({length: 9}, (_, depth) => depth);++export const NestedLists: Story = {+ name: 'Nested lists',+ parameters: {+ docs: {+ description: {+ story:+ 'Each nesting level draws its own marker: bulleted lists cycle disc, circle, square and numbered lists cycle decimal, lower-alpha, lower-roman, counting lists of either kind. A numbered list keeps its start.',+ },+ },+ },+ args: {+ children: [+ '## Bulleted',+ '',+ ...NESTED_LIST_DEPTHS.map(+ depth => `${' '.repeat(depth)}- Bullet at depth ${depth}`,+ ),+ '',+ '## Numbered',+ '',+ ...NESTED_LIST_DEPTHS.map(+ depth => `${' '.repeat(depth)}1. Number at depth ${depth}`,+ ),+ '',+ '## Mixed',+ '',+ '- Mixed at depth 0',+ ' 1. Mixed at depth 1',+ ' - Mixed at depth 2',+ ' 1. Mixed at depth 3',+ '',+ '## Starts',+ '',+ '26. Start 26',+ '',+ 'A paragraph ends that list.',+ '',+ '0. Start 0',+ ].join('\n'),+ },+};+export const ShiftedHeadings: Story = {name: 'Shifted Headings (start at h3)',args: {diff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsxindex 35c776bf51..ce1b553ea6 100644--- a/packages/core/src/List/List.test.tsx+++ b/packages/core/src/List/List.test.tsx@@ -14,6 +14,7 @@ import {render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {List} from './List';import {ListItem} from './ListItem';+import {ListMarkerScope} from './ListContext';describe('List', () => {// ===========================================================================@@ -843,4 +844,66 @@ describe('List', () => {);expect(screen.getByText('42')).toBeInTheDocument();});++ describe('ListMarkerScope (internal, for Markdown nested lists)', () => {+ /** The shape inside the item's marker box. */+ const markerShape = (container: HTMLElement) => {+ // The dot, ring, or square: an empty element in the marker box.+ const shape = container.querySelector('li > span > span:empty');+ return shape == null ? null : getComputedStyle(shape);+ };++ it('draws the list style marker without a scope', () => {+ const {container} = render(+ <List listStyle="disc">+ <ListItem label="Item" />+ </List>,+ );+ expect(markerShape(container)?.borderRadius).toBe('50%');+ });++ it('draws the scope marker in place of the list style', () => {+ const {container} = render(+ <List listStyle="disc">+ <ListMarkerScope marker="square">+ <ListItem label="Item" />+ </ListMarkerScope>+ </List>,+ );+ const shape = markerShape(container);+ expect(shape).not.toBeNull();+ expect(shape?.borderRadius).not.toBe('50%');+ expect(container.querySelector('ul')).not.toBeNull();+ });++ it('keeps a numbered list ordered with a letter marker', () => {+ render(+ <List listStyle="decimal" start={3}>+ <ListMarkerScope marker="lower-alpha">+ <ListItem label="Item" />+ </ListMarkerScope>+ </List>,+ );+ const list = screen.getByRole('list');+ expect(list.tagName).toBe('OL');+ expect(list).toHaveAttribute('start', '3');+ });++ it('draws no marker in a list without markers, or outside a list', () => {+ const {container} = render(+ <>+ <List>+ <ListMarkerScope marker="square">+ <ListItem label="In a plain list" />+ </ListMarkerScope>+ </List>+ <ListMarkerScope marker="square">+ <span>Outside a list</span>+ </ListMarkerScope>+ </>,+ );+ expect(markerShape(container)).toBeNull();+ expect(screen.getByText('Outside a list')).toBeInTheDocument();+ });+ });});diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsxindex 7ce456eaf9..d10e53fd7f 100644--- a/packages/core/src/List/ListContext.tsx+++ b/packages/core/src/List/ListContext.tsx@@ -6,21 +6,59 @@* @file ListContext.tsx* @input Layer-scoped React context* @output Exports ListContext for sharing density, dividers, marker style,- * and optional inline edge compensation between List and ListItem+ * and optional inline edge compensation between List and ListItem, and+ * ListMarkerScope, which sets the marker for the items inside it* @position Internal context; consumed by List.tsx and ListItem.tsx*/+import {use, useMemo, type ReactNode} from 'react';import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';export type ListDensity = 'compact' | 'balanced' | 'spacious';export type ListMarkerStyle = 'none' | 'disc' | 'decimal' | 'circle';+/**+ * Every marker ListItem draws: the public styles, and the square, letter,+ * and roman markers Markdown's nested lists use (spec:AST-061 DEC-6).+ */+export type ListMarker =+ 'disc' | 'circle' | 'square' | 'decimal' | 'lower-alpha' | 'lower-roman';+export interface ListContextValue {density: ListDensity;hasDividers: boolean;listStyle: ListMarkerStyle;edgeCompensation?: 'inline';+ /**+ * The marker items draw instead of the one `listStyle` names, set by+ * ListMarkerScope; internal. Ignored when `listStyle` is `'none'`.+ */+ marker?: ListMarker;}export const ListContext = createContext<ListContextValue | null>(null);ListContext.displayName = 'ListContext';++/**+ * Draws `marker` on the List items inside it, in place of the marker their+ * List's `listStyle` names; internal, for Markdown's nested lists. Outside a+ * List, or in a List without markers, it changes nothing.+ */+export function ListMarkerScope({+ marker,+ children,+}: {+ readonly marker: ListMarker;+ readonly children: ReactNode;+}): ReactNode {+ const context = use(ListContext);+ const value = useMemo(+ () => (context == null ? null : {...context, marker}),+ [context, marker],+ );+ return value == null ? (+ children+ ) : (+ <ListContext value={value}>{children}</ListContext>+ );+}diff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsxindex 668eae8826..a272d53cff 100644--- a/packages/core/src/List/ListItem.tsx+++ b/packages/core/src/List/ListItem.tsx@@ -4,7 +4,8 @@/*** @file ListItem.tsx- * @input Uses React, ReactNode, StyleXStyles, theme tokens, List edge compensation+ * @input Uses React, ReactNode, StyleXStyles, theme tokens, List edge compensation,+ * and the marker a ListMarkerScope sets (Markdown's nested lists)* @output Exports ListItem component, ListItemProps type* @position Core implementation; consumed by List, index.ts, tested by List.test.tsx*@@ -28,7 +29,7 @@ import {borderVars,} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';-import {ListContext} from './ListContext';+import {ListContext, type ListMarker} from './ListContext';import {mergeProps} from '../utils';import {Item} from '../Item';import {themeProps} from '../utils/themeProps';@@ -189,6 +190,11 @@ const markerStyles = stylex.create({borderColor: colorVars['--color-text-primary'],backgroundColor: 'transparent',},+ square: {+ width: MARKER_DOT_SIZE,+ height: MARKER_DOT_SIZE,+ backgroundColor: colorVars['--color-text-primary'],+ },number: {alignSelf: 'baseline',flexShrink: 0,@@ -196,12 +202,33 @@ const markerStyles = stylex.create({fontSize: typeScaleVars['--text-body-size'],lineHeight: typeScaleVars['--text-body-leading'],width: spacingVars['--spacing-4'],+ },+ // 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) "."',},},+ lowerAlpha: {+ '::before': {+ content: 'counter(astryx-list, lower-alpha) "."',+ },+ },+ lowerRoman: {+ '::before': {+ content: 'counter(astryx-list, lower-roman) "."',+ },+ },});+/** The number styles, by marker. */+const NUMBER_STYLES = {+ decimal: markerStyles.decimal,+ 'lower-alpha': markerStyles.lowerAlpha,+ 'lower-roman': markerStyles.lowerRoman,+} as const;+const embeddedStyles = stylex.create({noRadius: {borderRadius: 0,@@ -250,18 +277,27 @@ export function ListItem({const listStyle = ctx?.listStyle ?? 'none';const edgeCompensation = ctx?.edgeCompensation;const hasMarkers = listStyle !== 'none';+ // ListMarkerScope may name another marker for this item.+ const markerKind: ListMarker | null =+ listStyle === 'none' ? null : (ctx?.marker ?? listStyle);const marker =- listStyle === 'disc' ? (- <span {...stylex.props(markerStyles.container)}>- <span {...stylex.props(markerStyles.dot)} />- </span>- ) : listStyle === 'circle' ? (+ markerKind === 'disc' ||+ markerKind === 'circle' ||+ markerKind === 'square' ? (<span {...stylex.props(markerStyles.container)}>- <span {...stylex.props(markerStyles.circle)} />+ <span+ {...stylex.props(+ markerKind === 'disc'+ ? markerStyles.dot+ : markerKind === 'circle'+ ? markerStyles.circle+ : markerStyles.square,+ )}+ /></span>- ) : listStyle === 'decimal' ? (- <span {...stylex.props(markerStyles.number)} />+ ) : markerKind != null ? (+ <span {...stylex.props(markerStyles.number, NUMBER_STYLES[markerKind])} />) : null;return (diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex e2cf0e9ce6..de9df45214 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -32,6 +32,7 @@ import {CheckboxListItem} from '../CheckboxList/CheckboxListItem';import {Blockquote} from '../Blockquote/Blockquote';import {List} from '../List/List';import {ListItem} from '../List/ListItem';+import {ListMarkerScope, type ListMarker} from '../List/ListContext';import {Table} from '../Table/Table';import {TableRow} from '../Table/TableRow';import {TableCell} from '../Table/TableCell';@@ -90,6 +91,19 @@ type SyncReactNode = Exclude<React.ReactNode, Promise<unknown>>;type RenderExtensionNode = MarkdownExtensionNode;type RenderInlineNode = MarkdownAstPhrasingContent<RenderExtensionNode>;type RenderBlockNode = MarkdownAstBlockContent<RenderExtensionNode>;++// spec:AST-061 DEC-6: a list nested inside n lists, of either kind, draws the+// marker at n modulo 3.+const BULLET_MARKERS: readonly [ListMarker, ListMarker, ListMarker] = [+ 'disc',+ 'circle',+ 'square',+];+const NUMBER_MARKERS: readonly [ListMarker, ListMarker, ListMarker] = [+ 'decimal',+ 'lower-alpha',+ 'lower-roman',+];type RenderTable = MarkdownAstTable<RenderExtensionNode>;// ---------------------------------------------------------------------------@@ -1310,6 +1324,8 @@ function renderBlock(preparedPlugins: PreparedMarkdownPlugins | undefined,t: TranslatorFn,headingProjection?: MarkdownHeadingProjection,+ // How many lists enclose this block (spec:AST-061 DEC-6).+ listDepth = 0,): SyncReactNode {const blockAlignMargin = BLOCK_ALIGN_MARGIN[contentAlign];const blockAlignStyle =@@ -1551,6 +1567,7 @@ function renderBlock(preparedPlugins,t,headingProjection,+ listDepth,),);return <BlockquoteComp key={index}>{bqC}</BlockquoteComp>;@@ -1588,6 +1605,7 @@ function renderBlock(preparedPlugins,t,headingProjection,+ listDepth,),)}</Blockquote>@@ -1666,6 +1684,7 @@ function renderBlock(preparedPlugins,t,headingProjection,+ listDepth + 1,),)}</>@@ -1751,17 +1770,23 @@ function renderBlock(preparedPlugins,t,headingProjection,+ listDepth + 1,),)}</>);return (- <ListItem+ <ListMarkerScope// eslint-disable-next-line @eslint-react/no-array-index-key -- markdown list items are rendered from positional AST nodeskey={i}- label={label}- />+ marker={+ (node.ordered ? NUMBER_MARKERS : BULLET_MARKERS)[+ listDepth % 3+ ]+ }>+ <ListItem label={label} />+ </ListMarkerScope>);})}</List>diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.tsindex dbd5dd9609..d3e199d22a 100644--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts@@ -908,6 +908,99 @@ for (const globals of [});}+// spec:AST-061 DEC-6 in core Markdown: each level draws the marker for its+// depth modulo 3, counting lists of either kind; numbering keeps its start.+for (const globals of [+ 'colorMode:light;direction:ltr',+ 'colorMode:dark;direction:rtl',+]) {+ test(`core Markdown list markers cycle by depth (${globals})`, async ({+ page,+ }) => {+ await page.setViewportSize(DESKTOP);+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-markdown--nested-lists&viewMode=story&globals=astryxTheme:neutral;${globals}`,+ {waitUntil: 'load'},+ );+ await expect(page.getByText('Start 0', {exact: true})).toBeVisible();+ const lists = await page.evaluate(() => {+ const document_ = document.querySelector('[role="document"]');+ if (document_ == null) {+ throw new Error('No Markdown document');+ }+ const markerOf = (item: Element): string => {+ for (const span of item.querySelectorAll('span')) {+ if (span.closest('li') !== item) {+ continue;+ }+ const before = getComputedStyle(span, '::before').content;+ if (before.includes('counter(')) {+ return before.includes('lower-alpha')+ ? 'lower-alpha'+ : before.includes('lower-roman')+ ? 'lower-roman'+ : 'decimal';+ }+ const style = getComputedStyle(span);+ if (style.width === '6px') {+ if (style.borderTopLeftRadius === '0px') {+ return 'square';+ }+ return style.backgroundColor === 'rgba(0, 0, 0, 0)'+ ? 'circle'+ : 'disc';+ }+ }+ return 'none';+ };+ return [...document_.querySelectorAll('ul, ol')].map(list => {+ let depth = 0;+ for (+ let ancestor = list.parentElement;+ ancestor != null && ancestor !== document_;+ ancestor = ancestor.parentElement+ ) {+ if (ancestor.tagName === 'UL' || ancestor.tagName === 'OL') {+ depth++;+ }+ }+ const items = [...list.querySelectorAll(':scope > li')];+ return {+ tag: list.tagName,+ depth,+ markers: [...new Set(items.map(markerOf))],+ text: items[0]?.textContent ?? '',+ counterReset: getComputedStyle(list).counterReset,+ };+ });+ });+ for (const list of lists) {+ const markers = list.tag === 'UL' ? BULLET_MARKERS : NUMBER_MARKERS;+ expect(list.markers, `${list.tag} at depth ${list.depth}`).toEqual([+ markers[list.depth % 3],+ ]);+ }+ // Every depth from 0 to 8 of each kind.+ for (const tag of ['UL', 'OL']) {+ expect(+ lists+ .filter(+ list =>+ list.tag === tag &&+ (list.text.startsWith('Bullet') ||+ list.text.startsWith('Number')),+ )+ .map(list => list.depth),+ ).toEqual(Array.from({length: 9}, (_, depth) => depth));+ }+ // Numbering keeps its start.+ const startOf = (text: string) =>+ lists.find(list => list.text.startsWith(text));+ expect(startOf('Start 26')?.counterReset).toBe('astryx-list 25');+ expect(startOf('Start 0')?.counterReset).toBe('astryx-list -1');+ });+}+for (const viewport of [PHONE, {width: 1280, height: 900}] as const) {for (const globals of ['colorMode:light;direction:ltr',