Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/typeahead-disabled-result.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[fix] Typeahead: a Typeahead result that renders as a `TypeaheadItem` with `isDisabled` (`renderItem` returns it directly, or the default rendering), in its usual layout (not `item.element`), is now announced as disabled, and Enter, click or tap on it picks nothing and leaves the list open, also inside a shadow root. The pointer does not highlight it; arrow keys still reach it.

@cixzhang
2 changes: 2 additions & 0 deletions docs/specs/components/Typeahead/BaseTypeahead.spec.md

Large diffs are not rendered by default.

52 changes: 29 additions & 23 deletions docs/specs/components/Typeahead/TypeaheadItem.spec.md

Large diffs are not rendered by default.

203 changes: 203 additions & 0 deletions packages/core/src/Typeahead/BaseTypeahead.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import * as stylex from '@stylexjs/stylex';
import {BaseTypeahead, type BaseTypeaheadHandle} from './BaseTypeahead';
import {CommittedChoicesKeyContext} from './committedChoicesKey';
import {Typeahead} from './Typeahead';
import {TypeaheadItem} from './TypeaheadItem';
import {Tokenizer} from '../Tokenizer';
import {InternationalizationProvider} from '../i18n';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
Expand Down Expand Up @@ -1754,3 +1755,205 @@ describe('BaseTypeahead pending work after a dismissal', () => {
}
});
});

describe('a disabled TypeaheadItem result', () => {
const people: SearchSource<SearchableItem> = {
search: () => [
{id: 'ana', label: 'Ana'},
{id: 'ben', label: 'Ben'},
{id: 'cy', label: 'Cy'},
],
bootstrap: () => [],
};
function People({
disabledId,
onChange,
}: {
disabledId: string | null;
onChange: (item: SearchableItem | null) => void;
}) {
return (
<Typeahead
label="Add people"
searchSource={people}
value={null}
onChange={onChange}
debounceMs={0}
renderItem={item => (
<TypeaheadItem item={item} isDisabled={item.id === disabledId} />
)}
/>
);
}

it('is announced as disabled, and Enter, click and tap pick nothing and keep the list open', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(<People disabledId="ben" onChange={onChange} />);
await user.type(screen.getByRole('combobox'), 'a');
const ben = await screen.findByRole('option', {name: 'Ben', hidden: true});
expect(ben).toHaveAttribute('aria-disabled', 'true');
expect(
screen.getByRole('option', {name: 'Ana', hidden: true}),
).not.toHaveAttribute('aria-disabled');

await user.click(ben);
fireEvent.pointerDown(ben, {pointerType: 'touch'});
fireEvent.click(ben);
expect(onChange).not.toHaveBeenCalled();
expect(screen.getByRole('combobox')).toHaveAttribute(
'aria-expanded',
'true',
);

// Arrow keys still reach it; Enter on it picks nothing.
const combobox = screen.getByRole('combobox');
for (
let step = 0;
step < 3 && combobox.getAttribute('aria-activedescendant') !== ben.id;
step++
) {
await user.keyboard('{ArrowDown}');
}
expect(combobox).toHaveAttribute('aria-activedescendant', ben.id);
await user.keyboard('{Enter}');
expect(onChange).not.toHaveBeenCalled();
expect(screen.getByRole('combobox')).toHaveAttribute(
'aria-expanded',
'true',
);

// The next result is still reached and picked.
await user.keyboard('{ArrowDown}{Enter}');
expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange.mock.calls[0][0]).toMatchObject({id: 'cy'});
});

it('takes no hover highlight', async () => {
const user = userEvent.setup();
render(<People disabledId="ben" onChange={() => {}} />);
const combobox = screen.getByRole('combobox');
await user.type(combobox, 'a');
const ben = await screen.findByRole('option', {name: 'Ben', hidden: true});
const cy = screen.getByRole('option', {name: 'Cy', hidden: true});
// A real pointer move releases the hover hold, then each row the pointer
// moves over takes the highlight.
const moveOver = (option: HTMLElement, y: number) => {
fireEvent.pointerMove(option, {screenX: 10, screenY: y});
fireEvent.mouseMove(option, {screenX: 10, screenY: y});
};
moveOver(cy, 10);
moveOver(cy, 20);
expect(combobox).toHaveAttribute('aria-activedescendant', cy.id);
moveOver(ben, 30);
expect(combobox).toHaveAttribute('aria-activedescendant', cy.id);
});

it('reads the mark from the row it acts on when two results share an id', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const twins: SearchSource<SearchableItem> = {
search: () => [
{id: 'ben', label: 'Ben A'},
{id: 'ben', label: 'Ben B'},
],
bootstrap: () => [],
};
render(
<Typeahead
label="Add people"
searchSource={twins}
value={null}
onChange={onChange}
debounceMs={0}
renderItem={item => (
<TypeaheadItem item={item} isDisabled={item.label === 'Ben B'} />
)}
/>,
);
await user.type(screen.getByRole('combobox'), 'b');
const second = await screen.findByRole('option', {
name: 'Ben B',
hidden: true,
});
await user.click(second);
expect(onChange).not.toHaveBeenCalled();
await user.click(screen.getByRole('option', {name: 'Ben A', hidden: true}));
expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange.mock.calls[0][0]).toMatchObject({label: 'Ben A'});
});

it('is not picked inside a shadow root', async () => {
const onChange = vi.fn();
const host = document.createElement('div');
document.body.append(host);
const mount = document.createElement('div');
host.attachShadow({mode: 'open'}).append(mount);
try {
render(<People disabledId="ben" onChange={onChange} />, {
container: mount,
});
const field = within(mount);
const combobox = field.getByRole('combobox');
// user-event types into the document's active element, which is the
// shadow host here, so the input event goes to the field directly.
act(() => {
combobox.focus();
});
fireEvent.change(combobox, {target: {value: 'a'}});
const ben = await field.findByRole('option', {name: 'Ben', hidden: true});
expect(ben).toHaveAttribute('aria-disabled', 'true');
fireEvent.click(ben);
expect(onChange).not.toHaveBeenCalled();
fireEvent.click(field.getByRole('option', {name: 'Ana', hidden: true}));
expect(onChange).toHaveBeenCalledTimes(1);
} finally {
host.remove();
}
});

it('is picked again once it is no longer disabled', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const {rerender} = render(<People disabledId="ben" onChange={onChange} />);
await user.type(screen.getByRole('combobox'), 'a');
const ben = await screen.findByRole('option', {name: 'Ben', hidden: true});
expect(ben).toHaveAttribute('aria-disabled', 'true');
rerender(<People disabledId={null} onChange={onChange} />);
expect(
screen.getByRole('option', {name: 'Ben', hidden: true}),
).not.toHaveAttribute('aria-disabled');
await user.click(screen.getByRole('option', {name: 'Ben', hidden: true}));
expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange.mock.calls[0][0]).toMatchObject({id: 'ben'});
});

it('marks a result whose element is false, which TypeaheadItem lays out as usual', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const source: SearchSource<SearchableItem> = {
search: () => [
{id: 'ana', label: 'Ana'},
{id: 'ben', label: 'Ben', element: false},
],
bootstrap: () => [],
};
render(
<Typeahead
label="Add people"
searchSource={source}
value={null}
onChange={onChange}
debounceMs={0}
renderItem={item => (
<TypeaheadItem item={item} isDisabled={item.id === 'ben'} />
)}
/>,
);
await user.type(screen.getByRole('combobox'), 'a');
const ben = await screen.findByRole('option', {name: 'Ben', hidden: true});
expect(ben).toHaveAttribute('aria-disabled', 'true');
await user.click(ben);
expect(onChange).not.toHaveBeenCalled();
});
});
67 changes: 54 additions & 13 deletions packages/core/src/Typeahead/BaseTypeahead.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
*/

import React, {
isValidElement,
use,
useCallback,
useEffect,
Expand Down Expand Up @@ -54,7 +55,7 @@ import {
useOutsidePress,
} from '../Layer/outsidePress';
import {isImeKeyEvent} from '../utils/ime';
import {TypeaheadItem} from './TypeaheadItem';
import {TypeaheadItem, type TypeaheadItemProps} from './TypeaheadItem';
import {Icon} from '../Icon';
import {Spinner} from '../Spinner';
import {SpinnerOwnerContext} from '../Spinner/SpinnerOwnerContext';
Expand Down Expand Up @@ -90,6 +91,7 @@ import {
} from '../i18n/useComponentTranslator';
import english from '../i18n/generated-english/Typeahead/BaseTypeahead.generated';
import {textEntryTraitAttributes} from '../Field/textEntryTraits';
import {isDisabledControl} from '../utils/pressDisabled';

registerEnglishFallback(english);
// =============================================================================
Expand Down Expand Up @@ -591,6 +593,20 @@ function isBelowMinQueryLength(query: string, minQueryLength: number): boolean {
// Component
// =============================================================================

/**
* Whether a result's rendered content is a disabled TypeaheadItem in its
* usual layout. TypeaheadItem renders a truthy `item.element` as is, with no
* disabled state, so only a falsy one counts.
*/
function isDisabledTypeaheadItem(content: ReactNode): boolean {
return (
isValidElement<TypeaheadItemProps<SearchableItem>>(content) &&
content.type === TypeaheadItem &&
content.props.isDisabled === true &&
!content.props.item?.element
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
);
}

/**
* Combobox engine: input, search, keyboard navigation, and dropdown.
*
Expand Down Expand Up @@ -670,6 +686,9 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// screen-reader user something the sighted user is not reading
// (`spec:AST-056` AR1).
const emptyStateRef = useRef<HTMLDivElement>(null);
// A pick reads the disabled mark from the row it acts on, not from the
// item, so two results with the same id stay apart.
const optionElementsRef = useRef<(HTMLElement | null)[]>([]);
const generatedId = useId();
// Keep the released input-specific aliases authoritative when a caller uses
// them, but do not let an omitted alias erase the equivalent native BaseProp.
Expand Down Expand Up @@ -1684,7 +1703,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({

// Handle item selection
const handleSelect = useCallback(
(item: T) => {
(item: T, index: number) => {
// A disabled field changes nothing, also from a list that was open
// before it became disabled (spec:AST-085 FR2).
if (isDisabled) {
Expand All @@ -1698,6 +1717,10 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
const pickedIndex = displayedResults.findIndex(
other => other.id === item.id,
);
const option = optionElementsRef.current[index];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Miss (non-blocking): this check now sits between the focus-list comment and pickedIndex above and the keepsFocusList code that comment describes. Move these four lines up beside the isDisabled guard so the comment stays with its code.

if (option != null && isDisabledControl(option)) {
return;
}
const nextIndex =
pickedIndex + 1 < displayedResults.length
? pickedIndex + 1
Expand Down Expand Up @@ -2074,7 +2097,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
break;
}
if (highlightedIndex >= 0 && highlightedIndex < results.length) {
handleSelect(displayedResults[highlightedIndex]);
handleSelect(displayedResults[highlightedIndex], highlightedIndex);
}
break;
case 'Escape':
Expand Down Expand Up @@ -2327,21 +2350,45 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
const index = flatIndex++;
const itemKey = getKey(item.id, index);
const isSelected = itemKey === selectedKey;
const content = renderItem ? (
renderItem(item)
) : (
<TypeaheadItem item={item} xstyle={styles.defaultItem} />
);
return (
<div
key={itemKey}
ref={node => {
optionElementsRef.current[index] = node;
}}
id={getItemId(index)}
role="option"
aria-selected={isSelected}
aria-disabled={isDisabledTypeaheadItem(content) || undefined}
tabIndex={-1}
onMouseDown={canKeepFocusList ? preventOptionFocus : undefined}
onClick={() => handleSelect(item)}
onMouseDown={event => {
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
// A press on a disabled option keeps focus in the input,
// so the list stays open.
if (
canKeepFocusList ||
isDisabledControl(event.currentTarget)
) {
preventOptionFocus(event);
}
}}
onClick={() => handleSelect(item, index)}
// Highlight follows pointer movement, not pointer
// presence: a menu that opens or reflows under a resting
// pointer keeps its keyboard highlight, so Enter acts on
// the option the user was shown, not the one that
// happened to appear under the cursor.
onMouseMove={() => highlightOnHover(index)}
onMouseMove={event => {
// A disabled option takes no hover highlight: it cannot
// be picked.
if (!isDisabledControl(event.currentTarget)) {
highlightOnHover(index);
}
}}
{...mergeProps(
themeProps('typeahead-option', {
size,
Expand All @@ -2356,13 +2403,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
isSelected && styles.itemSelected,
),
)}>
<span {...stylex.props(styles.itemContent)}>
{renderItem ? (
renderItem(item)
) : (
<TypeaheadItem item={item} xstyle={styles.defaultItem} />
)}
</span>
<span {...stylex.props(styles.itemContent)}>{content}</span>
{isSelected && <Icon icon="check" size="sm" color="primary" />}
</div>
);
Expand Down
Loading