An open source design system that's fully customizable and agent ready
TypeScript
fix(lab): MobileTokenizer and CommentComposer stay focusable when disabled (#7903)
Cindy Zhang79fd9740d589
diff --git a/apps/storybook/stories/MobileTokenizer.stories.tsx b/apps/storybook/stories/MobileTokenizer.stories.tsxindex 5f69683e7d..8b2b0bd064 100644--- a/apps/storybook/stories/MobileTokenizer.stories.tsx+++ b/apps/storybook/stories/MobileTokenizer.stories.tsx@@ -57,3 +57,46 @@ export const TouchFlow: Story = {},name: 'Touch flow (single searchable management sheet)',};++export const Disabled: Story = {+ render: () => (+ <div style={{width: 350, display: 'grid', gap: 16}}>+ <MobileTokenizer+ label="Tags"+ searchSource={source}+ value={[tags[0], tags[1]]}+ onChange={() => {}}+ placeholder="Add tags"+ isDisabled+ />+ <MobileTokenizer+ label="Empty tags"+ searchSource={source}+ value={[]}+ onChange={() => {}}+ placeholder="Add tags"+ isDisabled+ />+ </div>+ ),+};++export const AtLimit: Story = {+ render: () => {+ const [value, setValue] = useState<SearchableItem[]>([tags[0], tags[1]]);+ return (+ <div style={{width: 350}}>+ <MobileTokenizer+ label="Tags"+ searchSource={source}+ value={value}+ onChange={items => setValue(items)}+ placeholder="Add tags"+ maxEntries={2}+ debounceMs={0}+ />+ </div>+ );+ },+ name: 'At the maxEntries limit',+};diff --git a/packages/lab/src/Comments/CommentComposer.test.tsx b/packages/lab/src/Comments/CommentComposer.test.tsxindex 320e28bcf9..e5287b606c 100644--- a/packages/lab/src/Comments/CommentComposer.test.tsx+++ b/packages/lab/src/Comments/CommentComposer.test.tsx@@ -185,6 +185,60 @@ describe('CommentComposer', () => {);});+ it('keeps the image picker free of native disabled and refuses files while busy (AST-085 FR1, FR2)', async () => {+ const onUploadImages = vi.fn();+ render(+ <CommentComposer+ value="Draft"+ onChange={() => {}}+ onSubmit={() => {}}+ onUploadImages={onUploadImages}+ isSubmitting+ />,+ );+ const input = document.querySelector('input[type="file"]');+ if (!(input instanceof HTMLInputElement)) {+ throw new Error('File input not found');+ }+ expect(input).not.toHaveAttribute('disabled');+ const file = new File(['png'], 'chart.png', {type: 'image/png'});+ await act(async () => {+ fireEvent.change(input, {target: {files: [file]}});+ await Promise.resolve();+ });+ expect(onUploadImages).not.toHaveBeenCalled();+ });++ it('does not open the image chooser from the error banner while busy', async () => {+ const onUploadImages = vi.fn();+ const props = {+ value: 'Draft',+ onChange: () => {},+ onSubmit: () => {},+ onUploadImages,+ };+ const view = render(<CommentComposer {...props} />);+ const input = document.querySelector('input[type="file"]');+ if (!(input instanceof HTMLInputElement)) {+ throw new Error('File input not found');+ }+ const openChooser = vi.spyOn(input, 'click').mockImplementation(() => {});+ await act(async () => {+ fireEvent.change(input, {+ target: {+ files: [new File(['%PDF'], 'doc.pdf', {type: 'application/pdf'})],+ },+ });+ });+ view.rerender(<CommentComposer {...props} isSubmitting />);+ fireEvent.click(screen.getByRole('button', {name: 'Choose images'}));+ expect(openChooser).not.toHaveBeenCalled();++ view.rerender(<CommentComposer {...props} />);+ fireEvent.click(screen.getByRole('button', {name: 'Choose images'}));+ expect(openChooser).toHaveBeenCalledTimes(1);+ });+it('refuses files that are not images', async () => {const onUploadImages = vi.fn();render(diff --git a/packages/lab/src/Comments/CommentComposer.tsx b/packages/lab/src/Comments/CommentComposer.tsxindex cc8431e2ee..a95aea13c8 100644--- a/packages/lab/src/Comments/CommentComposer.tsx+++ b/packages/lab/src/Comments/CommentComposer.tsx@@ -239,6 +239,8 @@ export function CommentComposerBase({latestValueRef.current = value;const isMountedRef = useRef(true);const actionPendingRef = useRef(false);+ const isSubmittingRef = useRef(isSubmitting);+ isSubmittingRef.current = isSubmitting;const imageInputRef = useRef<HTMLInputElement>(null);const inputRef = useRef<ChatComposerInputHandle | null>(null);// Focus lands once per `focusKey`, when the input attaches: the handle ref@@ -323,7 +325,15 @@ export function CommentComposerBase({setActionError({title: t('@astryx.commentComposer.imagesOnly'),actionLabel: t('@astryx.commentComposer.chooseImages'),- onAction: () => imageInputRef.current?.click(),+ onAction: () => {+ // The picker input is never natively disabled, so its click() would+ // open the file chooser while busy and the busy guard would drop+ // the pick.+ if (isSubmittingRef.current || actionPendingRef.current) {+ return;+ }+ imageInputRef.current?.click();+ },});return;}@@ -439,10 +449,12 @@ export function CommentComposerBase({accept="image/*"multiplehidden- disabled={isBusy}onChange={event => {const files = Array.from(event.currentTarget.files ?? []);event.currentTarget.value = '';+ if (isBusy) {+ return;+ }beginImageUpload(files);}}/>diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsxindex 5f24c20560..aad635abca 100644--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx@@ -15,6 +15,8 @@ import {within,} from '@testing-library/react';import {useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';import {MobileTokenizer, type MobileTokenizerChange} from './MobileTokenizer';import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';@@ -337,4 +339,140 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {expect.objectContaining({type: 'remove'}),);});++ it('keeps a disabled trigger focusable without opening the sheet (AST-085 FR1, FR2)', () => {+ render(+ <MobileTokenizer+ label="Tags"+ searchSource={source}+ value={[ITEMS[0]]}+ onChange={() => {}}+ isDisabled+ />,+ );+ const trigger = screen.getByRole('button', {name: /Tags/});+ expect(trigger).not.toHaveAttribute('disabled');+ expect(trigger).toHaveAttribute('aria-disabled', 'true');+ trigger.focus();+ expect(trigger).toHaveFocus();+ fireEvent.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(+ screen.queryByTestId('mobile-tokenizer-list'),+ ).not.toBeInTheDocument();+ });++ it('keeps an unselectable row at the limit focusable but inert (AST-085 FR1, FR2)', async () => {+ const spy = vi.fn();+ render(+ <MobileTokenizer+ label="Tags"+ searchSource={source}+ value={[ITEMS[0]]}+ maxEntries={1}+ debounceMs={0}+ onChange={spy}+ />,+ );+ fireEvent.click(screen.getByRole('button', {name: /Tags/}));+ const row = await screen.findByRole('checkbox', {name: 'Energizer'});+ expect(row).not.toHaveAttribute('disabled');+ expect(row).toHaveAttribute('aria-disabled', 'true');+ fireEvent.click(row);+ expect(spy).not.toHaveBeenCalled();+ expect(row).toHaveAttribute('aria-checked', 'false');+ // In forced colors its indicator border takes GrayText (AST-085 FR6).+ const indicatorClasses = stylex+ .props(+ stylex.create({+ border: {+ borderColor: {+ default: colorVars['--color-border'],+ '@media (forced-colors: active)': 'GrayText',+ },+ },+ }).border,+ )+ .className!.split(' ')+ .filter(name => !name.includes('__'));+ const indicator = row.querySelector('.astryx-checkbox-indicator')!;+ for (const name of indicatorClasses) {+ expect(indicator).toHaveClass(name);+ }+ });++ it('paints the placeholder of a disabled empty trigger GrayText in forced colors (AST-085 FR6)', () => {+ const placeholderClasses = stylex+ .props(+ stylex.create({+ placeholder: {+ color: {+ default: colorVars['--color-text-secondary'],+ '@media (forced-colors: active)': 'GrayText',+ },+ },+ }).placeholder,+ )+ .className!.split(' ')+ .filter(name => !name.includes('__'));+ render(+ <MobileTokenizer+ label="Tags"+ searchSource={source}+ value={[]}+ onChange={() => {}}+ placeholder="Add tags"+ isDisabled+ />,+ );+ const placeholder = screen.getByText('Add tags');+ for (const name of placeholderClasses) {+ expect(placeholder).toHaveClass(name);+ }+ });++ it('paints a disabled trigger and its tokens GrayText in forced colors (AST-085 FR6)', () => {+ // The same declarations as the component's styles compile to the same+ // atomic classes; without them the tokens keep their CanvasText label.+ const atoms = (style: stylex.StyleXStyles) =>+ stylex+ .props(style)+ .className!.split(' ')+ .filter(name => !name.includes('__'));+ const forced = stylex.create({+ trigger: {+ borderColor: {+ default: colorVars['--color-border'],+ '@media (forced-colors: active)': 'GrayText',+ },+ color: {default: null, '@media (forced-colors: active)': 'GrayText'},+ },+ token: {+ color: {+ default: colorVars['--color-text-primary'],+ '@media (forced-colors: active)': 'GrayText',+ },+ },+ });+ render(+ <MobileTokenizer+ label="Tags"+ searchSource={source}+ value={[ITEMS[0], ITEMS[1]]}+ onChange={() => {}}+ isDisabled+ />,+ );+ const trigger = screen.getByRole('button', {name: /Tags/});+ for (const name of atoms(forced.trigger)) {+ expect(trigger).toHaveClass(name);+ }+ const tokens = trigger.querySelectorAll('.astryx-token');+ expect(tokens).toHaveLength(2);+ for (const token of tokens) {+ for (const name of atoms(forced.token)) {+ expect(token).toHaveClass(name);+ }+ }+ });});diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsxindex af0d26561f..dec05a0d4f 100644--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx@@ -118,9 +118,28 @@ const styles = stylex.create({':is(:disabled,[aria-disabled="true"])': 'default',},},+ // An aria-disabled button gets no system disabled paint in forced colors;+ // GrayText is the platform's disabled affordance there. Defaults repeat the+ // base values, since StyleX merges per property.+ triggerDisabled: {+ borderColor: {+ default: colorVars['--color-border'],+ '@media (forced-colors: active)': 'GrayText',+ },+ color: {+ default: null,+ '@media (forced-colors: active)': 'GrayText',+ },+ },triggerPlaceholder: {color: colorVars['--color-text-secondary'],},+ triggerPlaceholderDisabled: {+ color: {+ default: colorVars['--color-text-secondary'],+ '@media (forced-colors: active)': 'GrayText',+ },+ },sheetBody: {display: 'flex',flexDirection: 'column',@@ -158,6 +177,29 @@ const styles = stylex.create({':is(:disabled,[aria-disabled="true"])': 'default',},},+ // A Token authors its own color, which forced colors replace with+ // CanvasText; GrayText marks the tokens of a disabled trigger as disabled.+ // The default repeats Token's own default color.+ tokenDisabled: {+ color: {+ default: colorVars['--color-text-primary'],+ '@media (forced-colors: active)': 'GrayText',+ },+ },+ // Same for the indicator's border: GrayText in forced colors, and the+ // default repeats the indicator's disabled border.+ indicatorDisabled: {+ borderColor: {+ default: colorVars['--color-border'],+ '@media (forced-colors: active)': 'GrayText',+ },+ },+ rowDisabled: {+ color: {+ default: colorVars['--color-text-primary'],+ '@media (forced-colors: active)': 'GrayText',+ },+ },rowLabel: {flexGrow: 1,minWidth: 0,@@ -376,20 +418,32 @@ export function MobileTokenizer<T extends SearchableItem>({aria-haspopup="dialog"aria-expanded={activeSheet != null}aria-label={label}- disabled={isDisabled}+ aria-disabled={isDisabled || undefined}onClick={() => {+ if (isDisabled) {+ return;+ }setSelectedItemsAtOpen(value);lastLoadScrollHeightRef.current = null;setRenderedItemCount(LIST_RENDER_BATCH_SIZE);setActiveSheet('manage');}}- {...stylex.props(styles.trigger)}>+ {...stylex.props(styles.trigger, isDisabled && styles.triggerDisabled)}>{value.length > 0 ? (value.map(item => (- <Token key={item.id} label={item.label} isDisabled={isDisabled} />+ <Token+ key={item.id}+ label={item.label}+ isDisabled={isDisabled}+ xstyle={isDisabled ? styles.tokenDisabled : undefined}+ />))) : (- <span {...stylex.props(styles.triggerPlaceholder)}>+ <span+ {...stylex.props(+ styles.triggerPlaceholder,+ isDisabled && styles.triggerPlaceholderDisabled,+ )}>{placeholder ?? ''}</span>)}@@ -500,18 +554,35 @@ export function MobileTokenizer<T extends SearchableItem>({role="checkbox"aria-checked={isSelected}aria-label={item.label}- disabled={rowDisabled}- onClick={() =>- isSelected ? handleRemove(item) : handleAdd(item)- }- {...stylex.props(styles.row)}>+ aria-disabled={rowDisabled || undefined}+ onClick={() => {+ if (rowDisabled) {+ return;+ }+ if (isSelected) {+ handleRemove(item);+ } else {+ handleAdd(item);+ }+ }}+ {...stylex.props(+ styles.row,+ rowDisabled && styles.rowDisabled,+ )}><span {...stylex.props(styles.rowLabel)}>- <Text type="body">{item.label}</Text>+ <Text+ type="body"+ color={rowDisabled ? 'inherit' : undefined}>+ {item.label}+ </Text></span><CheckboxIndicatorstate={isSelected ? 'checked' : 'unchecked'}size="md"isDisabled={rowDisabled}+ xstyle={+ rowDisabled ? styles.indicatorDisabled : undefined+ }/></button>);