An open source design system that's fully customizable and agent ready
TypeScript
Polish MobileTokenizer touch flow (#6853)
rubyycheung13fdb14a5fb8
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjsindex 37fcb09fd9..2340178e1c 100644--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs@@ -25,7 +25,7 @@ export const docs = {],anatomy: [{name: 'Trigger field', required: true, description: 'Button showing tokens as a summary, with chevron.'},- {name: 'Manage sheet', required: true, description: 'Selected rows with remove, Clear all footer, Add item.'},+ {name: 'Manage sheet', required: true, description: 'Selected rows with remove controls, guided empty states, and equal-width footer actions.'},{name: 'Add sheet', required: true, description: 'Stacked sheet: result rows with +/check toggles, bottom filter + Done row.'},],},diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsxindex 381865f7eb..ea2dba0751 100644--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx@@ -19,25 +19,70 @@ const ITEMS: SearchableItem[] = [{id: 'energizer', label: 'Energizer'},];const source: SearchSource<SearchableItem> = {- search: q => ITEMS.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),+ search: q =>+ ITEMS.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),bootstrap: () => ITEMS,};-function Harness({spy}: {spy?: (i: SearchableItem[], c: MobileTokenizerChange<SearchableItem>) => void}) {+function Harness({+ spy,+}: {+ spy?: (i: SearchableItem[], c: MobileTokenizerChange<SearchableItem>) => void;+}) {const [value, setValue] = useState<SearchableItem[]>([ITEMS[0], ITEMS[1]]);return (- <MobileTokenizer label="Tags" searchSource={source} value={value} debounceMs={0} placeholder="Add tags"- onChange={(items, change) => { setValue(items); spy?.(items, change); }} />+ <MobileTokenizer+ label="Tags"+ searchSource={source}+ value={value}+ debounceMs={0}+ placeholder="Add tags"+ onChange={(items, change) => {+ setValue(items);+ spy?.(items, change);+ }}+ />);}beforeEach(() => {- HTMLDialogElement.prototype.showModal = vi.fn(function (this: HTMLDialogElement) { this.setAttribute('open', ''); });- HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) { this.setAttribute('open', ''); });- HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) { this.removeAttribute('open'); });- if (!Element.prototype.setPointerCapture) { Element.prototype.setPointerCapture = vi.fn(); Element.prototype.releasePointerCapture = vi.fn(); }- vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({matches: false, media: '', onchange: null, addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: vi.fn()}));- vi.stubGlobal('requestAnimationFrame', vi.fn((cb: FrameRequestCallback) => { cb(0); return 1; }));+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+ if (!Element.prototype.setPointerCapture) {+ Element.prototype.setPointerCapture = vi.fn();+ Element.prototype.releasePointerCapture = vi.fn();+ }+ vi.stubGlobal(+ 'matchMedia',+ vi+ .fn()+ .mockReturnValue({+ matches: false,+ media: '',+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ }),+ );+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn((cb: FrameRequestCallback) => {+ cb(0);+ return 1;+ }),+ );});afterEach(() => vi.unstubAllGlobals());@@ -48,16 +93,70 @@ describe('MobileTokenizer (Lab, sketch flow)', () => {const trigger = screen.getByRole('button', {name: /Tags/});expect(trigger.getAttribute('aria-haspopup')).toBe('dialog');fireEvent.click(trigger);- expect((await screen.findByTestId('mobile-tokenizer-manage-list')).textContent).toContain('Design');+ expect(+ (await screen.findByTestId('mobile-tokenizer-manage-list')).textContent,+ ).toContain('Design');fireEvent.click(screen.getByRole('button', {name: 'Add item'}));const search = await screen.findByLabelText('Search Tags');fireEvent.change(search, {target: {value: 'E'}});- const engineer = await screen.findByRole('option', {name: /Engineer/});+ const engineer = await screen.findByRole('button', {name: 'Add Engineer'});+ expect(engineer).toHaveAttribute('data-variant', 'secondary');fireEvent.click(engineer);- expect(spy).toHaveBeenCalledWith([ITEMS[0], ITEMS[1], ITEMS[2]], expect.objectContaining({type: 'add'}));- await waitFor(() => expect(screen.getByRole('option', {name: /Engineer/}).getAttribute('aria-selected')).toBe('true'));+ expect(spy).toHaveBeenCalledWith(+ [ITEMS[0], ITEMS[1], ITEMS[2]],+ expect.objectContaining({type: 'add'}),+ );+ await waitFor(() =>+ expect(+ screen.getByRole('button', {name: 'Remove Engineer'}),+ ).toBeInTheDocument(),+ );fireEvent.click(screen.getByRole('button', {name: 'Done'}));- expect((await screen.findByTestId('mobile-tokenizer-manage-list')).textContent).toContain('Engineer');+ expect(+ (await screen.findByTestId('mobile-tokenizer-manage-list')).textContent,+ ).toContain('Engineer');+ });+ it('uses guided empty states and large actions', async () => {+ render(+ <MobileTokenizer+ label="Tags"+ searchSource={source}+ value={[]}+ debounceMs={0}+ onChange={() => {}}+ />,+ );+ fireEvent.click(screen.getByRole('button', {name: /Tags/}));+ const manageTitle = await screen.findByRole('heading', {+ name: 'No items yet',+ });+ expect(+ manageTitle.closest('[role="status"]')?.querySelector('.astryx-icon'),+ ).toHaveAttribute('data-size', 'lg');+ expect(screen.getByRole('button', {name: 'Clear all'})).toHaveAttribute(+ 'data-size',+ 'lg',+ );+ expect(+ screen.queryByRole('button', {name: 'Close'}),+ ).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', {name: 'Add item'}));+ const search = await screen.findByLabelText('Search Tags');+ expect(search.closest('.astryx-text-input')).toHaveAttribute(+ 'data-size',+ 'lg',+ );+ expect(screen.getByRole('button', {name: 'Done'})).toHaveAttribute(+ 'data-size',+ 'lg',+ );+ fireEvent.change(search, {target: {value: 'zzz'}});+ const searchTitle = await screen.findByRole('heading', {+ name: 'No results found',+ });+ expect(searchTitle.closest('[role="status"]')).toHaveTextContent(+ 'Try a different search.',+ );});it('manage sheet removes and clears', async () => {const spy = vi.fn();@@ -65,8 +164,14 @@ describe('MobileTokenizer (Lab, sketch flow)', () => {fireEvent.click(screen.getByRole('button', {name: /Tags/}));await screen.findByTestId('mobile-tokenizer-manage-list');fireEvent.click(screen.getByRole('button', {name: 'Remove Eng'}));- expect(spy).toHaveBeenCalledWith([ITEMS[0]], expect.objectContaining({type: 'remove'}));+ expect(spy).toHaveBeenCalledWith(+ [ITEMS[0]],+ expect.objectContaining({type: 'remove'}),+ );fireEvent.click(screen.getByRole('button', {name: 'Clear all'}));- expect(spy).toHaveBeenLastCalledWith([], expect.objectContaining({type: 'remove'}));+ expect(spy).toHaveBeenLastCalledWith(+ [],+ expect.objectContaining({type: 'remove'}),+ );});});diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsxindex cfec4323e1..369b32c7f3 100644--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx@@ -5,7 +5,7 @@/*** @file MobileTokenizer.tsx* @input Uses public @astryxdesign/core components only (BottomSheet,- * BottomSheetSwitcher, Button, Field, Heading, Icon, IconButton, Text,+ * BottomSheetSwitcher, Button, EmptyState, Field, Icon, IconButton, Text,* TextInput, Token)* @output Exports MobileTokenizer — Lab prototype of the touch Tokenizer* flow (stacked manage + add sheets)@@ -26,26 +26,25 @@ import {useRef,useState,type ReactNode,+ type SVGProps,} from 'react';import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '@astryxdesign/core';import {BottomSheet} from '@astryxdesign/core/BottomSheet';import {BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';import {Button} from '@astryxdesign/core/Button';-import {Divider} from '@astryxdesign/core/Divider';+import {EmptyState} from '@astryxdesign/core/EmptyState';import {Field} from '@astryxdesign/core/Field';import {Icon} from '@astryxdesign/core/Icon';import {IconButton} from '@astryxdesign/core/IconButton';import {Text} from '@astryxdesign/core/Text';import {TextInput} from '@astryxdesign/core/TextInput';import {Token} from '@astryxdesign/core/Token';-import type {- SearchableItem,- SearchSource,-} from '@astryxdesign/core/Typeahead';+import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';import {colorVars,radiusVars,+ sizeVars,spacingVars,} from '@astryxdesign/core/theme/tokens.stylex';@@ -80,6 +79,22 @@ export interface MobileTokenizerProps<T extends SearchableItem> extends Omit<type SheetId = 'manage' | 'add';const CREATABLE_ID_PREFIX = '__xds_create__';+function ListBulletIcon(props: SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" {...props}>+ <path+ d="M8.5 6h11M8.5 12h11M8.5 18h11"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ />+ <circle cx="4.5" cy="6" r="1" fill="currentColor" />+ <circle cx="4.5" cy="12" r="1" fill="currentColor" />+ <circle cx="4.5" cy="18" r="1" fill="currentColor" />+ </svg>+ );+}+const styles = stylex.create({trigger: {display: 'flex',@@ -118,20 +133,17 @@ const styles = stylex.create({paddingBlockStart: spacingVars['--spacing-3'],paddingBlockEnd: spacingVars['--spacing-3'],},- // Sketch has no visible sheet headings — manage is rows + a top-end- // close affordance only. The sheet's accessible name still comes from- // BottomSheet's `label`, not a rendered heading.- closeRow: {- display: 'flex',- justifyContent: 'flex-end',- marginBlockEnd: spacingVars['--spacing-2'],- },+ // The manage sheet intentionally has no dedicated close button; the sheet+ // keeps its standard gesture, scrim, and Escape dismissal paths.list: {display: 'flex',flexDirection: 'column',overflowY: 'auto',minHeight: 0,},+ addList: {+ flexGrow: 1,+ },row: {display: 'flex',alignItems: 'center',@@ -144,35 +156,20 @@ const styles = stylex.create({backgroundColor: 'transparent',borderWidth: 0,color: colorVars['--color-text-primary'],- cursor: {- default: 'pointer',- ':is(:disabled,[aria-disabled="true"])': 'default',- },},rowDisabled: {opacity: 0.5},rowLabel: {flexGrow: 1, minWidth: 0},- toggleMark: {- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- width: 28,- height: 28,- flexShrink: 0,- borderRadius: radiusVars['--radius-full'],- borderWidth: 1,- borderStyle: 'solid',- borderColor: colorVars['--color-border'],- fontSize: 18,- lineHeight: 1,- },footer: {display: 'flex',alignItems: 'center',- justifyContent: 'space-between',gap: spacingVars['--spacing-2'],paddingBlockStart: spacingVars['--spacing-3'],marginTop: 'auto',},+ footerAction: {+ flexGrow: 1,+ flexBasis: 0,+ },filterRow: {display: 'flex',alignItems: 'flex-end',@@ -182,8 +179,18 @@ const styles = stylex.create({},// TextInput renders Field (block, shrink-to-fit); xstyle lands on that// root, so it must flex — the filter takes all row space minus Done+gap.- filterInput: {flexGrow: 1, flexShrink: 1, flexBasis: 0, minWidth: 0},+ filterInput: {+ flexGrow: 1,+ flexShrink: 1,+ flexBasis: 0,+ minWidth: 0,+ height: sizeVars['--size-element-lg'],+ minHeight: sizeVars['--size-element-lg'],+ },empty: {paddingBlock: spacingVars['--spacing-4']},+ searchEmpty: {+ flexGrow: 1,+ },});export function MobileTokenizer<T extends SearchableItem>({@@ -223,7 +230,8 @@ export function MobileTokenizer<T extends SearchableItem>({if (selectedIds.has(created)) {return;}- const real = {id: created, label: created} as T;+ const createdItem: SearchableItem = {id: created, label: created};+ const real = createdItem as T;onChange([...value, real], {item: real, type: 'create'});return;}@@ -281,7 +289,14 @@ export function MobileTokenizer<T extends SearchableItem>({return () => clearTimeout(timer);}void run();- }, [isAddOpen, query, searchSource, minQueryLength, maxMenuItems, debounceMs]);+ }, [+ isAddOpen,+ query,+ searchSource,+ minQueryLength,+ maxMenuItems,+ debounceMs,+ ]);const createItem = useMemo<T | null>(() => {const trimmed = query.trim();@@ -337,24 +352,22 @@ export function MobileTokenizer<T extends SearchableItem>({onActiveSheetChange={id => setActiveSheet(id as SheetId | null)}><BottomSheet sheetId="manage" label={label} height="hug"><div {...stylex.props(styles.sheetBody)}>- <div {...stylex.props(styles.closeRow)}>- <IconButton- label="Close"- icon={<Icon icon="close" />}- variant="ghost"- size="sm"- onClick={() => setActiveSheet(null)}- />- </div>- <div {...stylex.props(styles.list)} data-testid="mobile-tokenizer-manage-list">+ <div+ {...stylex.props(styles.list)}+ data-testid="mobile-tokenizer-manage-list">{value.length === 0 ? (- <Text type="supporting" color="secondary" xstyle={styles.empty}>- No items yet- </Text>+ <EmptyState+ icon={+ <Icon icon={ListBulletIcon} size="lg" color="secondary" />+ }+ title="No items yet"+ description="Add an item to get started."+ isCompact+ xstyle={styles.empty}+ />) : (- value.map((item, i) => (+ value.map(item => (<div key={item.id}>- {i > 0 && <Divider />}<div {...stylex.props(styles.row)}><span {...stylex.props(styles.rowLabel)}><Text type="body">{item.label}</Text>@@ -374,15 +387,19 @@ export function MobileTokenizer<T extends SearchableItem>({<div {...stylex.props(styles.footer)}><Buttonlabel="Clear all"- variant="ghost"+ variant="secondary"+ size="lg"isDisabled={value.length === 0}onClick={handleClearAll}+ xstyle={styles.footerAction}/><Buttonlabel="Add item"variant="primary"+ size="lg"isDisabled={isAtMax}onClick={() => setActiveSheet('add')}+ xstyle={styles.footerAction}/></div></div>@@ -391,64 +408,80 @@ export function MobileTokenizer<T extends SearchableItem>({<BottomSheet sheetId="add" label="Add item" height="tall"><div {...stylex.props(styles.sheetBody)}><div- {...stylex.props(styles.list)}- role="listbox"- aria-multiselectable="true"+ {...stylex.props(styles.list, styles.addList)}+ role="list"aria-label={label}data-testid="mobile-tokenizer-add-list">{createItem != null && (- <button- type="button"- role="option"- aria-selected={false}- {...stylex.props(styles.row)}- onClick={() => {- handleAdd(createItem);- setQuery('');- }}>+ <div role="listitem" {...stylex.props(styles.row)}><span {...stylex.props(styles.rowLabel)}><Text type="body">{createItem.label}</Text></span>- <span {...stylex.props(styles.toggleMark)} aria-hidden="true">+</span>- </button>+ <IconButton+ label={createItem.label}+ icon={<span aria-hidden="true">+</span>}+ variant="secondary"+ onClick={() => {+ handleAdd(createItem);+ setQuery('');+ }}+ />+ </div>)}{!isSearching && results.length === 0 && createItem == null ? (- <Text type="supporting" color="secondary" xstyle={styles.empty}>- {emptySearchResultsText}- </Text>+ <EmptyState+ icon={<Icon icon="search" size="lg" color="secondary" />}+ title={emptySearchResultsText}+ description="Try a different search."+ isCompact+ xstyle={styles.searchEmpty}+ />) : (results.map(item => {const isSelected = selectedIds.has(item.id);const rowDisabled = !isSelected && isAtMax;return (- <button+ <divkey={item.id}- type="button"- role="option"- aria-selected={isSelected}- aria-disabled={rowDisabled || undefined}- {...stylex.props(styles.row, rowDisabled && styles.rowDisabled)}- onClick={() =>- isSelected ? handleRemove(item) : handleAdd(item)- }>+ role="listitem"+ {...stylex.props(+ styles.row,+ rowDisabled && styles.rowDisabled,+ )}><span {...stylex.props(styles.rowLabel)}>- {renderItem ? renderItem(item) : <Text type="body">{item.label}</Text>}- </span>- <span {...stylex.props(styles.toggleMark)} aria-hidden="true">- {isSelected ? <Icon icon="check" size="sm" /> : '+'}+ {renderItem ? (+ renderItem(item)+ ) : (+ <Text type="body">{item.label}</Text>+ )}</span>- </button>+ <IconButton+ label={`${isSelected ? 'Remove' : 'Add'} ${item.label}`}+ icon={+ isSelected ? (+ <Icon icon="close" size="sm" />+ ) : (+ <span aria-hidden="true">+</span>+ )+ }+ variant={isSelected ? 'ghost' : 'secondary'}+ isDisabled={rowDisabled}+ onClick={() =>+ isSelected ? handleRemove(item) : handleAdd(item)+ }+ />+ </div>);}))}</div>- <Divider /><div {...stylex.props(styles.filterRow)}><TextInputlabel={`Search ${label}`}isLabelHiddenplaceholder="Search..."value={query}+ size="lg"width="100%"hasClearonChange={next => {@@ -460,6 +493,7 @@ export function MobileTokenizer<T extends SearchableItem>({<Buttonlabel="Done"variant="primary"+ size="lg"onClick={() => setActiveSheet('manage')}/></div>