An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): harden ListInput to the states its props already promise (#5200)
Ernestbc3423808023
diff --git a/apps/storybook/stories/ListInput.stories.tsx b/apps/storybook/stories/ListInput.stories.tsxindex e5d1f56d61..d36310a2b7 100644--- a/apps/storybook/stories/ListInput.stories.tsx+++ b/apps/storybook/stories/ListInput.stories.tsx@@ -2,8 +2,8 @@/*** @file ListInput.stories.tsx- * @input Uses ListInput with controlled data, Astryx field controls, column width helpers, React, and StyleX- * @output Storybook examples spanning realistic use cases, validation scopes, density, responsiveness, tokenized collection motion, and reordering+ * @input Uses ListInput with controlled data, Astryx field controls, column width helpers, the Theme provider, React, and StyleX+ * @output Storybook examples spanning realistic use cases, validation scopes, density, responsiveness, tokenized collection motion, reordering, the disabled and loading states, row volume, and a pinned light/dark theme matrix* @position Lab component stories; documents the consumer-facing ListInput API*/@@ -15,7 +15,11 @@ import {DateInput} from '@astryxdesign/core/DateInput';import {NumberInput} from '@astryxdesign/core/NumberInput';import {Selector} from '@astryxdesign/core/Selector';import {pixel, proportional} from '@astryxdesign/core/Table';+import {Text} from '@astryxdesign/core/Text';import {TextInput} from '@astryxdesign/core/TextInput';+import {Theme} from '@astryxdesign/core';+import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';+import {neutralTheme} from '@astryxdesign/theme-neutral';import {ListInput, type ListInputColumn} from '@astryxdesign/lab';const storyStyles = stylex.create({canvas: {@@ -30,6 +34,22 @@ const storyStyles = stylex.create({width: 360,maxWidth: '100%',},+ stack: {+ display: 'flex',+ flexDirection: 'column',+ gap: 32,+ },+ themePane: {+ display: 'flex',+ flexDirection: 'column',+ gap: 12,+ padding: 20,+ borderRadius: 8,+ // Must be a token, not a literal: the pane's whole job is to render the+ // surface each nested Theme resolves to, so a hardcoded colour would sit+ // under text that follows the theme and fail contrast in one of the modes.+ backgroundColor: colorVars['--color-background-body'],+ },});const meta: Meta<typeof ListInput> = {@@ -905,3 +925,168 @@ export const ResponsiveItinerary: Story = {},},};++/**+ * A read-only rendering of the tag editor, used by the disabled, loading, and+ * theme stories so each one differs by exactly the prop it demonstrates.+ */+function StaticTagsExample({+ isDisabled,+ isLoading,+ status,+}: {+ isDisabled?: boolean;+ isLoading?: boolean;+ status?: React.ComponentProps<typeof ListInput<TagOption>>['status'];+}) {+ const [tags, setTags] = useState(INITIAL_TAGS.slice(0, 3));+ const columns = useMemo(() => createTagColumns(() => {}), []);++ return (+ <ListInput<TagOption>+ label="Tag options"+ description="Each row keeps its colour and label."+ value={tags}+ onChange={setTags}+ getItemKey={tag => tag.id}+ createItem={() => ({id: crypto.randomUUID(), color: 'blue', label: ''})}+ columns={columns}+ itemName="tag"+ isDisabled={isDisabled}+ isLoading={isLoading}+ status={status}+ isReorderable+ />+ );+}++/** Every field and mutation control locked while the list stays readable. */+export const Disabled: Story = {+ render: () => <StaticTagsExample isDisabled />,+ parameters: {+ docs: {+ description: {+ story:+ 'Sets `aria-disabled` on the group and disables each field, the reorder handle, the remove action, and Add. The values stay legible rather than being hidden, so a disabled list still communicates its contents.',+ },+ },+ },+};++/** The list marked busy while an async operation settles. */+export const Loading: Story = {+ render: () => <StaticTagsExample isLoading />,+ parameters: {+ docs: {+ description: {+ story:+ 'Sets `aria-busy` on the group and locks the same controls `isDisabled` does. Loading is distinct from disabled: it means the current values may still change, so an in-flight keyboard reorder is cancelled rather than committed.',+ },+ },+ },+};++/** The three list-level status types side by side. */+export const ValidationStatuses: Story = {+ render: () => (+ <div {...stylex.props(storyStyles.stack)}>+ <StaticTagsExample+ status={{type: 'error', message: 'Add at least five tag options.'}}+ />+ <StaticTagsExample+ status={{+ type: 'warning',+ message: 'Two tags share a colour, which may be hard to tell apart.',+ }}+ />+ <StaticTagsExample+ status={{type: 'success', message: 'All tag options are valid.'}}+ />+ </div>+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'The other stories only exercise `error`. `warning` and `success` use the same list-level slot and are described by the group, so a screen reader reaches them from any field inside the list.',+ },+ },+ },+};++const STRESS_TAGS: TagOption[] = Array.from({length: 25}, (_, index) => ({+ id: `stress-${index}`,+ color: COLOR_OPTIONS[index % COLOR_OPTIONS.length].value,+ label:+ index % 5 === 0+ ? `Extremely long tag label ${index} that has to wrap or truncate rather than widen the row past its container`+ : `Tag ${index}`,+}));++function StressExample() {+ const [tags, setTags] = useState(STRESS_TAGS);+ const columns = useMemo(() => createTagColumns(() => {}), []);++ return (+ <ListInput<TagOption>+ label="Tag options at volume"+ description="Twenty-five records, every fifth one carrying an over-long label."+ value={tags}+ onChange={setTags}+ getItemKey={tag => tag.id}+ createItem={() => ({id: crypto.randomUUID(), color: 'blue', label: ''})}+ columns={columns}+ itemName="tag"+ isReorderable+ />+ );+}++/** Row volume and over-long values in one place. */+export const Stress: Story = {+ render: () => <StressExample />,+ parameters: {+ docs: {+ description: {+ story:+ 'Checks that column tracks stay stable as row count grows, that an over-long label cannot widen the row past its container, and that reorder stays usable when the list is taller than the viewport.',+ },+ },+ },+};++/** The same list pinned to light and dark, including a nested override. */+export const ThemeMatrix: Story = {+ render: () => (+ <div {...stylex.props(storyStyles.stack)}>+ <Theme theme={neutralTheme} mode="light">+ <div {...stylex.props(storyStyles.themePane)}>+ <Text weight="bold">Light</Text>+ <StaticTagsExample />+ </div>+ </Theme>+ <Theme theme={neutralTheme} mode="dark">+ <div {...stylex.props(storyStyles.themePane)}>+ <Text weight="bold">Dark</Text>+ <StaticTagsExample />+ <Theme theme={neutralTheme} mode="light">+ <div {...stylex.props(storyStyles.themePane)}>+ <Text weight="bold">Light nested inside dark</Text>+ <StaticTagsExample+ status={{type: 'error', message: 'Add at least five tags.'}}+ />+ </div>+ </Theme>+ </div>+ </Theme>+ </div>+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'Pins both modes into one frame so a theme regression is visible without toggling the toolbar, and nests a light theme inside a dark one to confirm the component reads its colours from the nearest provider rather than the document root.',+ },+ },+ },+};diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 7446617197..6a8b94d5d2 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -439,6 +439,10 @@"defaultMessage": "Remove {itemName} {position, number}","description": "Accessible label and tooltip on the button that deletes one record from a lab ListInput. `{itemName}` is the consumer's singular noun for one record; `{position}` is its 1-based row number (e.g. \"Remove guest 2\")."},+ "@astryx.listInput.removeUnavailable": {+ "defaultMessage": "Remove is unavailable while the list is disabled",+ "description": "Tooltip shown on the Remove button when the ListInput is disabled or loading, explaining why the action cannot be performed."+ },"@astryx.listInput.reorderItem": {"defaultMessage": "Reorder {itemName} {position, number}","description": "Accessible label on the drag-handle button that reorders one record in a lab ListInput. `{itemName}` is the consumer's singular noun for one record; `{position}` is its 1-based row number (e.g. \"Reorder guest 2\")."diff --git a/packages/lab/src/ListInput/ListInput.test.tsx b/packages/lab/src/ListInput/ListInput.test.tsxindex bc2f4c5070..4eafdc88ca 100644--- a/packages/lab/src/ListInput/ListInput.test.tsx+++ b/packages/lab/src/ListInput/ListInput.test.tsx@@ -1123,6 +1123,223 @@ describe('ListInput', () => {).toEqual(['Ada', 'Grace']);});+ it('locks every field and mutation control when isDisabled is set', () => {+ const onChange = vi.fn();+ renderListInput({isDisabled: true, isReorderable: true, onChange});++ const group = screen.getByRole('group');+ expect(group).toHaveAttribute('aria-disabled', 'true');+ expect(group).not.toHaveAttribute('aria-busy');++ for (const field of screen.getAllByRole('textbox')) {+ expect(field).toBeDisabled();+ }+ expect(screen.getByRole('button', {name: /add guest/i})).toBeDisabled();+ expect(+ screen.getByRole('button', {name: 'Reorder guest 1'}),+ ).toBeDisabled();+ // Remove carries a tooltip, so it is disabled via aria and stays focusable+ // rather than dropping out of the tab order with its explanation.+ expect(+ screen.getByRole('button', {name: 'Remove guest 1'}),+ ).toHaveAttribute('aria-disabled', 'true');++ // The values stay readable — a disabled list still communicates content.+ expect(screen.getAllByRole('textbox')[0]).toHaveValue('Ada');+ expect(onChange).not.toHaveBeenCalled();+ });++ it('marks the list busy and locks the same controls when isLoading is set', () => {+ renderListInput({isLoading: true, isReorderable: true});++ const group = screen.getByRole('group');+ expect(group).toHaveAttribute('aria-busy', 'true');+ // Loading is not disabled: the values may still change, so the group is+ // never reported as disabled to assistive technology.+ expect(group).not.toHaveAttribute('aria-disabled');++ for (const field of screen.getAllByRole('textbox')) {+ expect(field).toBeDisabled();+ }+ expect(screen.getByRole('button', {name: /add guest/i})).toBeDisabled();+ expect(+ screen.getByRole('button', {name: 'Reorder guest 1'}),+ ).toBeDisabled();+ expect(+ screen.getByRole('button', {name: 'Remove guest 1'}),+ ).toHaveAttribute('aria-disabled', 'true');+ });++ it('cancels an in-flight keyboard reorder when the list becomes busy', () => {+ const onChange = vi.fn();+ const {rerender} = render(+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={guests}+ onChange={onChange}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ isReorderable+ />,+ );++ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});+ handle.focus();+ fireEvent.keyDown(handle, {key: ' ', code: 'Space'});+ expect(+ document.querySelector('[data-list-input-reorder-source]'),+ ).toBeInTheDocument();++ rerender(+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={guests}+ onChange={onChange}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ isReorderable+ isLoading+ />,+ );++ // The pick-up is abandoned rather than committed, so no order change escapes.+ expect(+ document.querySelector('[data-list-input-reorder-source]'),+ ).not.toBeInTheDocument();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('describes warning and success list statuses from the group', () => {+ const {rerender} = renderListInput({+ status: {type: 'warning', message: 'Two guests share a name.'},+ });++ const describedBy = screen+ .getByRole('group')+ .getAttribute('aria-describedby');+ expect(describedBy).toBeTruthy();+ expect(document.getElementById(describedBy!)).toHaveTextContent(+ 'Two guests share a name.',+ );++ rerender(+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={guests}+ onChange={() => {}}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ status={{type: 'success', message: 'Every guest is confirmed.'}}+ />,+ );+ expect(screen.getByText('Every guest is confirmed.')).toBeInTheDocument();+ });++ it('associates list status with the group and item status with its row', () => {+ renderListInput({+ status: {type: 'error', message: 'Add at least three guests.'},+ getItemStatus: guest =>+ guest.id === 'grace'+ ? {type: 'error', message: 'Grace is already invited.'}+ : undefined,+ });++ const listDescribedBy = screen+ .getByRole('group')+ .getAttribute('aria-describedby');+ expect(document.getElementById(listDescribedBy!)).toHaveTextContent(+ 'Add at least three guests.',+ );++ // Row-scoped status belongs to the row, not the list, so a reader on the+ // second record does not inherit the first record's message.+ const rows = screen.getAllByRole('listitem');+ expect(rows[0]).not.toHaveAttribute('aria-invalid');+ expect(rows[1]).toHaveAttribute('aria-invalid', 'true');+ const rowDescribedBy = rows[1].getAttribute('aria-describedby');+ expect(document.getElementById(rowDescribedBy!)).toHaveTextContent(+ 'Grace is already invited.',+ );+ });++ it('moves a picked-up record to the first and last positions with Home and End', () => {+ const onChange = vi.fn();+ const threeGuests = [...guests, createdGuest];+ render(+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={threeGuests}+ onChange={onChange}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ isReorderable+ />,+ );++ const handle = screen.getByRole('button', {name: 'Reorder guest 3'});+ handle.focus();+ fireEvent.keyDown(handle, {key: ' ', code: 'Space'});++ fireEvent.keyDown(handle, {key: 'Home'});+ expect(+ document.querySelector('[data-list-input-reorder-source]')?.closest('li'),+ ).toHaveAttribute('aria-posinset', '1');++ fireEvent.keyDown(handle, {key: 'End'});+ expect(+ document.querySelector('[data-list-input-reorder-source]')?.closest('li'),+ ).toHaveAttribute('aria-posinset', '3');++ fireEvent.keyDown(handle, {key: 'Home'});+ fireEvent.keyDown(handle, {key: 'Enter'});+ expect(onChange).toHaveBeenCalledWith(+ [createdGuest, guests[0], guests[1]],+ {type: 'reorder', item: createdGuest, fromIndex: 2, toIndex: 0},+ );+ });++ it('moves focus to the next record after a removal, and to Add when the list empties', async () => {+ function ControlledList() {+ const [value, setValue] = useState(guests);+ return (+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={value}+ onChange={setValue}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ />+ );+ }+ render(<ControlledList />);++ // Removing the first of two lands on the record that took its place, so a+ // keyboard user can delete consecutively without re-tabbing.+ fireEvent.click(screen.getByRole('button', {name: 'Remove guest 1'}));+ await waitFor(() => {+ expect(+ screen.getByRole('button', {name: 'Remove guest 1'}),+ ).toHaveFocus();+ });+ expect(screen.getAllByRole('listitem')).toHaveLength(1);++ // Removing the last record leaves nothing to focus, so focus falls back to Add.+ fireEvent.click(screen.getByRole('button', {name: 'Remove guest 1'}));+ await waitFor(() => {+ expect(screen.getByRole('button', {name: /add guest/i})).toHaveFocus();+ });+ });+it('warns in development when getItemKey returns a duplicate key', () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});renderListInput({diff --git a/packages/lab/src/ListInput/ListInput.tsx b/packages/lab/src/ListInput/ListInput.tsxindex 4b5f277081..ce7b2e4ab4 100644--- a/packages/lab/src/ListInput/ListInput.tsx+++ b/packages/lab/src/ListInput/ListInput.tsx@@ -1638,10 +1638,17 @@ export function ListInput<T>({itemName,position: index + 1,})}- tooltip={t('@astryx.listInput.removeItem', {- itemName,- position: index + 1,- })}+ tooltip={+ isDisabled || isLoading+ ? t(+ '@astryx.listInput.removeUnavailable',+ {itemName},+ )+ : t('@astryx.listInput.removeItem', {+ itemName,+ position: index + 1,+ })+ }icon={<Icon icon="close" size="sm" />}variant="ghost"size="md"