An open source design system that's fully customizable and agent ready
TypeScript
feat(Table): the row-expansion toggle resolves its glyph through the table-row-expand icon slot (#9834)
Xinzi Zhouc037450fc43f
diff --git a/.changeset/component-icon-slot-table-row-expand.md b/.changeset/component-icon-slot-table-row-expand.mdnew file mode 100644index 0000000000..8d7c9de982--- /dev/null+++ b/.changeset/component-icon-slot-table-row-expand.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Table: the row-expansion toggle resolves its glyph through the `table-row-expand` component icon slot with state `{expanded}`. With no theme entry it draws `chevronRight`, as before. The toggle still turns the glyph a quarter turn while expanded and mirrors it in right-to-left layouts, whatever the slot resolves. A theme maps it with `defineTheme({componentIcons: {'table-row-expand': …}})`; `null` hides only the glyph, and the toggle keeps its name, `aria-expanded`, and its toggling.++@imdreamrunnerdiff --git a/apps/storybook/stories/TableRowExpansion.stories.tsx b/apps/storybook/stories/TableRowExpansion.stories.tsxindex c5472c9c08..02c9e31fd9 100644--- a/apps/storybook/stories/TableRowExpansion.stories.tsx+++ b/apps/storybook/stories/TableRowExpansion.stories.tsx@@ -11,7 +11,7 @@ import {} from '@astryxdesign/core/Table';import {useAnimatedLayout} from '@astryxdesign/core/hooks';import type {TableColumn} from '@astryxdesign/core/Table';-import {Theme} from '@astryxdesign/core/theme';+import {Theme, defineTheme} from '@astryxdesign/core/theme';import {neutralTheme} from '@astryxdesign/theme-neutral';import {VStack, HStack} from '@astryxdesign/core/Stack';import {Text, Heading} from '@astryxdesign/core/Text';@@ -331,3 +331,60 @@ export const GlidingRowsLongTable: StoryObj<{glide?: boolean}> = {);},};++const rowExpandSlotThemes = [+ {label: 'default', theme: null},+ ...(['sm', 'md', 'lg'] as const).map(size => ({+ label: size,+ theme: defineTheme({+ name: `story-row-expand-${size}`,+ componentIcons: {'table-row-expand': {size}},+ }),+ })),+ {+ label: 'hidden',+ theme: defineTheme({+ name: 'story-row-expand-hidden',+ componentIcons: {'table-row-expand': null},+ }),+ },+];++function SlotTable() {+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(+ () => new Set(),+ );+ const expansion = useTableRowExpansion<Order>({+ expandedKeys,+ onToggle: key => setExpandedKeys(prev => toggleKey(prev, key)),+ getRowKey: item => item.id,+ getRowLabel: item => item.customer,+ renderExpanded: item => <OrderItems order={item} />,+ });+ return (+ <Table data={orders} columns={columns} idKey="id" plugins={{expansion}} />+ );+}++/**+ * The same table with the default expansion glyph, with a theme that asks the+ * `table-row-expand` slot for each glyph size, and with a theme that hides it.+ * The glyph changes; the rows keep their height.+ */+export const IconSlotRowHeight: Story = {+ render: () => (+ <VStack gap={4}>+ {rowExpandSlotThemes.map(({label, theme}) => (+ <div key={label} data-testid={`row-expand-${label}`}>+ {theme ? (+ <Theme theme={theme}>+ <SlotTable />+ </Theme>+ ) : (+ <SlotTable />+ )}+ </div>+ ))}+ </VStack>+ ),+};diff --git a/packages/core/src/Icon/componentIcons.test.tsx b/packages/core/src/Icon/componentIcons.test.tsxindex f5a6d1be11..35ffb56b08 100644--- a/packages/core/src/Icon/componentIcons.test.tsx+++ b/packages/core/src/Icon/componentIcons.test.tsx@@ -350,6 +350,7 @@ describe('component icon slot types', () => {| 'code-block-copy'| 'timestamp-copy'| 'table-sort-indicator'+ | 'table-row-expand'| 'example-panel-dismiss'| 'example-nav-item-leading'>();diff --git a/packages/core/src/Icon/index.ts b/packages/core/src/Icon/index.tsindex 520f80602a..81ecabfd9a 100644--- a/packages/core/src/Icon/index.ts+++ b/packages/core/src/Icon/index.ts@@ -70,6 +70,8 @@ export interface ComponentIconSlotMap {'table-sort-indicator': {readonly direction: 'ascending' | 'descending' | 'none';};+ /** A Table row's expansion toggle (`useTableRowExpansion`), by whether the row is expanded. */+ 'table-row-expand': {readonly expanded: boolean};}/** A slot name from the augmentable {@link ComponentIconSlotMap}. */diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjsindex df87dec2dc..9d527d4fb9 100644--- a/packages/core/src/Table/Table.doc.mjs+++ b/packages/core/src/Table/Table.doc.mjs@@ -161,6 +161,21 @@ export const docs = {whenNull:'Hides the glyph. The Sort control keeps its label and its click and keyboard sorting; the column header keeps `aria-sort`.',},+ {+ slot: 'table-row-expand',+ description:+ "The glyph in a row's expansion toggle (`useTableRowExpansion`). The toggle turns the glyph a quarter turn while the row is expanded and mirrors it in right-to-left layouts, so map a glyph that points toward the inline end.",+ fallback: '`chevronRight`, turned while expanded',+ state: [+ {+ name: 'expanded',+ type: 'boolean',+ description: "True while the row's detail panel is open.",+ },+ ],+ whenNull:+ 'Hides the glyph. The toggle keeps its size, its "Expand row" or "Collapse row" name, `aria-expanded`, and its click and keyboard toggling.',+ },],},description:diff --git a/packages/core/src/Table/__tests__/TableRowExpandSlot.a11y.browser.spec.ts b/packages/core/src/Table/__tests__/TableRowExpandSlot.a11y.browser.spec.tsnew file mode 100644index 0000000000..5051784b41--- /dev/null+++ b/packages/core/src/Table/__tests__/TableRowExpandSlot.a11y.browser.spec.ts@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^packages/core/src/Table/plugins/rowExpansion/ ^packages/core/src/Icon/ComponentIcon ^apps/storybook/stories/TableRowExpansion++/**+ * @file TableRowExpandSlot.a11y.browser.spec.ts+ * @input The built TableRowExpansion IconSlotRowHeight story in real Chromium+ * and WebKit+ * @output Browser evidence that a theme's `table-row-expand` size request or+ * `null` changes only the glyph (component:Table FR7): every expandable row+ * keeps the height it has with the default glyph+ * @position Regression proof for the expansion toggle's vertical alignment+ */++import {expect, test} from '@astryxdesign/a11y-spec/playwright';+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 () => {+ await storybook?.close();+});++test('a theme glyph size or a hidden glyph keeps every expandable row height', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tablerowexpansion--icon-slot-row-height&viewMode=story`,+ );+ const rowHeight = async (label: string) => {+ const toggle = page+ .getByTestId(`row-expand-${label}`)+ .locator('[data-expansion-toggle]')+ .first();+ await expect(toggle).toBeVisible();+ return toggle.evaluate(+ button => button.closest('tr')?.getBoundingClientRect().height ?? 0,+ );+ };++ const expected = await rowHeight('default');+ expect(expected).toBeGreaterThan(0);+ for (const label of ['sm', 'md', 'lg', 'hidden']) {+ expect(await rowHeight(label), label).toBeCloseTo(expected, 1);+ }+ await expect(+ page+ .getByTestId('row-expand-hidden')+ .locator('[data-expansion-toggle] .astryx-icon'),+ ).toHaveCount(0);+});diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsxindex 32ae66d319..60804f452e 100644--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx@@ -7,6 +7,9 @@ import {Table} from '../../Table';import type {TableColumn} from '../../types';import {useTableRowExpansion} from './useTableRowExpansion';import {InternationalizationProvider} from '../../../i18n';+import type {ComponentIconMap} from '../../../Icon/index';+import {defineTheme} from '../../../theme/defineTheme';+import {Theme} from '../../../theme/Theme';// popover mock for context-menu testsbeforeEach(() => {@@ -338,7 +341,9 @@ describe('useTableRowExpansion (detail panel)', () => {// has to sit on the glyph instead.render(<Harness initialExpanded={new Set(['a'])} />);const button = screen.getAllByRole('button', {name: /collapse row/i})[0];- const glyph = button.querySelector('svg')?.parentElement;+ // The glyph's box, the button's first child, turns with the glyph in it.+ const glyph = button.querySelector<HTMLElement>(':scope > *');+ expect(glyph?.querySelector('svg')).not.toBeNull();expect(glyph).toHaveStyle({transform: 'rotate(90deg)'});expect(button).not.toHaveStyle({transform: 'rotate(90deg)'});});@@ -793,3 +798,82 @@ describe('useTableRowExpansion (detail panel)', () => {).toBeGreaterThan(0);});});++describe('row expansion icon slot', () => {+ // Label each shared icon's artwork, so a test reads which name rendered.+ const icons = {+ chevronRight: <span data-icon="chevronRight" />,+ chevronDown: <span data-icon="chevronDown" />,+ menu: <span data-icon="menu" />,+ };+ let themeCount = 0;++ function renderInTheme(componentIcons?: ComponentIconMap<never>) {+ const theme = defineTheme({+ name: `table-row-expand-slot-${themeCount++}`,+ icons,+ componentIcons,+ });+ render(+ <Theme theme={theme}>+ <Harness initialExpanded={new Set(['a'])} />+ </Theme>,+ );+ }++ const toggles = () =>+ screen.getAllByRole('button', {name: /(expand|collapse) row/i});+ const glyph = (button: HTMLElement) =>+ button.querySelector('[data-icon]')?.getAttribute('data-icon') ?? null;++ it('draws chevronRight in both states when the theme maps nothing, turned while expanded', () => {+ renderInTheme();+ const [expanded, collapsed] = toggles();++ expect(glyph(expanded)).toBe('chevronRight');+ expect(glyph(collapsed)).toBe('chevronRight');+ // The component keeps the turn on the toggle's first child, the element+ // the glide gives its spring: the two states style it apart.+ const turned = (toggle: HTMLElement) => toggle.querySelector(':scope > *');+ expect(turned(expanded)?.className).not.toBe(turned(collapsed)?.className);+ expect(+ turned(expanded)?.contains(expanded.querySelector('.astryx-icon')),+ ).toBe(true);+ });++ it('passes `expanded` to a slot function and draws the name it returns', () => {+ const slot = vi.fn(({expanded}: {expanded: boolean}) => ({+ icon: expanded ? ('menu' as const) : ('chevronRight' as const),+ }));+ renderInTheme({'table-row-expand': slot});+ const [expanded, collapsed] = toggles();++ expect(glyph(expanded)).toBe('menu');+ expect(glyph(collapsed)).toBe('chevronRight');+ expect(slot).toHaveBeenCalledWith({expanded: true});+ expect(slot).toHaveBeenCalledWith({expanded: false});+ fireEvent.click(collapsed);+ expect(glyph(toggles()[1])).toBe('menu');+ });++ it('hides only the glyph for null; the toggle keeps its name, state, and action', () => {+ renderInTheme({'table-row-expand': null});+ const [expanded, collapsed] = toggles();++ expect(expanded.querySelector('.astryx-icon')).toBeNull();+ expect(expanded).toHaveAttribute('aria-expanded', 'true');+ expect(collapsed).toHaveAccessibleName(/expand row/i);+ fireEvent.click(collapsed);+ expect(screen.getAllByTestId('panel')).toHaveLength(2);+ });++ it('changes only the icon size for a size request', () => {+ renderInTheme({'table-row-expand': {size: 'sm'}});++ expect(toggles()[0].querySelector('.astryx-icon')).toHaveAttribute(+ 'data-size',+ 'sm',+ );+ expect(glyph(toggles()[0])).toBe('chevronRight');+ });+});diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsxindex 42e82bfddb..949994e1d5 100644--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx@@ -4,7 +4,8 @@/*** @file useTableRowExpansion.tsx- * @input React, StyleX, Icon, Table types, table context (density), i18n+ * @input React, StyleX, Icon, the theme's `table-row-expand` icon slot, Table+ * types, table context (density), i18n* (useComponentTranslator)* @output Exports useTableRowExpansion hook + config type* @position Row-expansion plugin (detail panel); consumed by Table via plugins prop@@ -39,6 +40,8 @@ import {tableRowMarker} from '../../table.stylex';import {panelDividerFor} from '../../rowDivider';import {useTheme, useThemeName} from '../../../theme/useTheme';import {Icon} from '../../../Icon';+import {ComponentIcon} from '../../../Icon/ComponentIcon';+import {iconBoxSizeStyles} from '../../../Icon/IconSize.stylex';import {VisuallyHidden} from '../../../VisuallyHidden';import {resolveContextActions} from '../../tableContextMenu';import {useTableContext} from '../../useTableCellStyles';@@ -216,6 +219,21 @@ const expansionStyles = stylex.create({color: colorVars['--color-icon-primary'],},},+ // The button takes its baseline from this fixed box. A theme's glyph size+ // or a hidden glyph then keeps the row height. The box is the toggle's+ // first child, which the glide gives its spring, so it carries the turn.+ glyphBox: {+ display: 'inline-block',+ position: 'relative',+ flexShrink: 0,+ },+ glyphCenter: {+ position: 'absolute',+ inset: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ },chevron: {transitionProperty: 'transform',transitionDuration: durationVars['--duration-fast'],@@ -387,16 +405,23 @@ function ExpansionChevron({}}aria-label={ariaLabel}aria-expanded={isExpanded}>- <Icon- icon="chevronRight"- size="xsm"- xstyle={[+ <span+ {...stylex.props(+ expansionStyles.glyphBox,+ iconBoxSizeStyles.xsm,expansionStyles.chevron,isExpanded? expansionStyles.chevronExpanded: expansionStyles.chevronCollapsed,- ]}- />+ )}>+ <span {...stylex.props(expansionStyles.glyphCenter)}>+ <ComponentIcon+ slot="table-row-expand"+ state={{expanded: isExpanded}}+ fallback={{icon: 'chevronRight', size: 'xsm'}}+ />+ </span>+ </span></button>);}