Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(useTypeahead): type-to-select ignores accents (#8864)

Ojas Mutrejaacfa52701f21
diff --git a/.changeset/typeahead-ignore-accents.md b/.changeset/typeahead-ignore-accents.md
new file mode 100644
index 0000000000..c55228dd00
--- /dev/null
+++ b/.changeset/typeahead-ignore-accents.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Type-to-select ignores accents in every locale. Pressing `d` now reaches "Đào", `a` reaches "Ánh" and "Åsa", `n` reaches "Ñandú", `l` reaches "Łódź", and `ı` now reaches "Isparta" and "İzmir". This applies to a closed Selector and to open DropdownMenu, ContextMenu, MultiSelector and TreeList lists, and to the public `useTypeahead` and `useTreeFocus` hooks. Before, a key typed without the mark skipped every item that starts with the marked letter. Matching ignores case, the combining accents U+0300–U+036F, the stroked letters đ ł ø ħ ŧ ƀ, and Turkish dotted and dotless i. It works the same way in every locale, because type-to-select is navigation, not sorting. When you type the accented letter itself, an exact match comes first. For Turkish, ı pairs with I and İ with i. A combining mark typed first is ignored; typed after a letter, it is part of that letter. Sorting and search filtering are unchanged. This meets `architecture:internationalization` INV17. No API changes.
+
+@HelloOjasMutreja @cixzhang
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 0d4b6c73a4..15acea880e 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -937,6 +937,38 @@ describe('DropdownMenu', () => {
).toHaveFocus();
});
+ it('typeahead reaches an accented item with a plain letter (INV17)', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Share'}}
+ items={[{label: 'Copy'}, {label: 'Ánh'}, {label: 'Łódź'}]}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: /Share/}));
+ const menu = screen.getByRole('menu', {hidden: true});
+ fireEvent.keyDown(menu, {key: 'l'});
+ expect(
+ screen.getByRole('menuitem', {name: 'Łódź', hidden: true}),
+ ).toHaveFocus();
+ });
+
+ it('typeahead puts the exact item first for a typed mark (INV17)', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'People'}}
+ items={[{label: 'Anh'}, {label: 'Dung'}, {label: 'Đào'}]}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: /People/}));
+ const menu = screen.getByRole('menu', {hidden: true});
+ fireEvent.keyDown(menu, {key: 'đ'});
+ expect(
+ screen.getByRole('menuitem', {name: 'Đào', hidden: true}),
+ ).toHaveFocus();
+ });
+
it('typeahead advances past an item that already starts with the letter', async () => {
const user = userEvent.setup();
render(
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index 46b9b97223..d34845d29d 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -760,6 +760,44 @@ describe('MultiSelector', () => {
expect(trigger).toHaveAttribute('aria-activedescendant', options[0].id);
});
+ it('typeahead reaches a stroked option with a plain letter (INV17)', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="City"
+ options={['Ankara', 'İzmir', 'Đà Nẵng']}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+
+ const trigger = screen.getByRole('combobox');
+ await user.click(trigger);
+ const options = screen.getAllByRole('option', h);
+
+ await user.keyboard('d');
+ expect(trigger).toHaveAttribute('aria-activedescendant', options[2].id);
+ });
+
+ it('typeahead puts the exact option first for a typed mark (INV17)', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Name"
+ options={['Anh', 'Dung', 'Đào']}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+
+ const trigger = screen.getByRole('combobox');
+ await user.click(trigger);
+ const options = screen.getAllByRole('option', h);
+
+ await user.keyboard('đ');
+ expect(trigger).toHaveAttribute('aria-activedescendant', options[2].id);
+ });
+
it('toggles item with Enter key', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
diff --git a/packages/core/src/MultiSelector/hooks.ts b/packages/core/src/MultiSelector/hooks.ts
index 0bd583ef43..c5954ec333 100644
--- a/packages/core/src/MultiSelector/hooks.ts
+++ b/packages/core/src/MultiSelector/hooks.ts
@@ -18,6 +18,7 @@ import {useCallback, useRef, useState} from 'react';
import {isRtlElement} from '../hooks/isRtlElement';
import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import type {MultiSelectorOptionData} from './types';
+import {findTypeaheadMatch} from '../utils/typeaheadMatch';
interface UseMultiComboboxOptions {
selectableItems: MultiSelectorOptionData[];
@@ -335,11 +336,12 @@ export function useMultiCombobox({
default:
// Typeahead only when search is not present
if (!hasSearch && e.key.length === 1 && !e.ctrlKey && !e.metaKey) {
- const newTypeahead = typeahead + e.key.toLowerCase();
- const matchIndex = selectableItems.findIndex(
- item =>
- !item.disabled &&
- item.label?.toLowerCase().startsWith(newTypeahead),
+ const newTypeahead = typeahead + e.key;
+ // INV17: the shared type-to-select fold, as Selector uses.
+ const matchIndex = findTypeaheadMatch(
+ selectableItems.flatMap((item, i) => (item.disabled ? [] : [i])),
+ i => selectableItems[i].label,
+ newTypeahead,
);
const didOpen = isOpen || matchIndex < 0 || onOpen() !== false;
if (didOpen) {
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index de765b39e2..a50e946c1b 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -2062,6 +2062,42 @@ describe('Selector', () => {
);
});
+ it('reaches accented and stroked options with a plain letter (INV17)', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <Selector
+ label="Name"
+ options={['Anh', 'Dung', 'Đào', 'Ánh']}
+ value="Dung"
+ onChange={onChange}
+ />,
+ );
+
+ await user.tab();
+ await user.keyboard('d');
+
+ expect(onChange).toHaveBeenLastCalledWith('Đào');
+ });
+
+ it('puts the exact option first for a typed mark (INV17)', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <Selector
+ label="Name"
+ options={['Anh', 'Dung', 'Đào']}
+ value="Anh"
+ onChange={onChange}
+ />,
+ );
+
+ await user.tab();
+ await user.keyboard('đ');
+
+ expect(onChange).toHaveBeenLastCalledWith('Đào');
+ });
+
it('cycles through options sharing a first letter on repeated presses', async () => {
const user = userEvent.setup();
function Harness() {
diff --git a/packages/core/src/TreeList/TreeList.test.tsx b/packages/core/src/TreeList/TreeList.test.tsx
index 740c528770..3c70724c52 100644
--- a/packages/core/src/TreeList/TreeList.test.tsx
+++ b/packages/core/src/TreeList/TreeList.test.tsx
@@ -1641,6 +1641,38 @@ describe('TreeList', () => {
);
});
+ it('typeahead reaches an accented label with a plain letter (INV17)', async () => {
+ const user = userEvent.setup();
+ render(
+ <TreeList
+ items={[
+ {id: 'dung', label: 'Dung', description: 'Đà Lạt'},
+ {id: 'dao', label: 'Đào', description: 'Hà Nội'},
+ {id: 'lodz', label: 'Łódź'},
+ ]}
+ />,
+ );
+ screen.getByText('Dung').closest('li')!.focus();
+ await user.keyboard('l');
+ expect(document.activeElement).toBe(screen.getByText('Łódź').closest('li'));
+ });
+
+ it('typeahead puts the exact match first for a typed mark (INV17)', async () => {
+ const user = userEvent.setup();
+ render(
+ <TreeList
+ items={[
+ {id: 'lodz', label: 'Łódź'},
+ {id: 'dung', label: 'Dung'},
+ {id: 'dao', label: 'Đào'},
+ ]}
+ />,
+ );
+ screen.getByText('Łódź').closest('li')!.focus();
+ await user.keyboard('đ');
+ expect(document.activeElement).toBe(screen.getByText('Đào').closest('li'));
+ });
+
it('lets a consumer prevent built-in TreeList keyboard navigation while receiving root div as event.currentTarget', () => {
let capturedCurrentTarget: Element | null = null;
const ref = {current: null as HTMLDivElement | null};
diff --git a/packages/core/src/hooks/useTreeFocus.doc.mjs b/packages/core/src/hooks/useTreeFocus.doc.mjs
index 2e162cc600..37158baf67 100644
--- a/packages/core/src/hooks/useTreeFocus.doc.mjs
+++ b/packages/core/src/hooks/useTreeFocus.doc.mjs
@@ -59,7 +59,7 @@ export const docs = {
{
name: 'options.typeahead',
type: 'boolean',
- description: 'Whether typeahead (jump to next item whose text starts with the typed characters) is enabled.',
+ description: 'Whether typeahead (jump to next item whose text starts with the typed characters, ignoring case, accents, the stroked letters đ ł ø ħ ŧ ƀ and Turkish ı/İ in every locale) is enabled.',
default: 'true',
required: false,
},
@@ -119,7 +119,7 @@ export const docsDense = {
'options.onActivate': 'called on Enter/Space activation. Return true when handled; else hook falls back to toggling expansion.',
'options.onActiveChange': 'notified when focus moves to a treeitem. Use to move a single roving tab stop.',
'options.hasRovingTabIndex': 'hook owns a single roving tab stop (stamps tabindex 0/-1, repairs on mount, moves w/ nav). Preserves an existing tabindex="0" seed. Attach handleFocus to sync after clicks.',
- 'options.typeahead': 'enable typeahead (jump to next item whose text starts with typed chars).',
+ 'options.typeahead': 'enable typeahead (jump to next item whose text starts with typed chars, ignoring case, accents, stroked letters + Turkish ı/İ).',
},
returnDescriptions: {
treeRef: 'ref to attach to tree container (role="tree").',
diff --git a/packages/core/src/hooks/useTreeFocus.test.tsx b/packages/core/src/hooks/useTreeFocus.test.tsx
index 92d366df58..ebd2941ebb 100644
--- a/packages/core/src/hooks/useTreeFocus.test.tsx
+++ b/packages/core/src/hooks/useTreeFocus.test.tsx
@@ -11,7 +11,7 @@
import {describe, it, expect, vi} from 'vitest';
import {useState} from 'react';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {cleanup, render, screen, fireEvent} from '@testing-library/react';
import {useTreeFocus} from './useTreeFocus';
interface Node {
@@ -317,6 +317,58 @@ describe('useTreeFocus activation + typeahead', () => {
expect(screen.getByTestId('avocado')).toHaveFocus();
});
+ it('typeahead ignores accents, stroked letters and Turkish i (INV17)', () => {
+ const nodes: Node[] = [
+ {id: 'dung', label: 'Dung', level: 1},
+ {id: 'dao', label: 'Đào', level: 1},
+ {id: 'izmir', label: 'İzmir', level: 1},
+ {id: 'isparta', label: 'Isparta', level: 1},
+ ];
+ render(<Tree collapsed={nodes} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('dung').focus();
+
+ fireEvent.keyDown(tree, {key: 'd'});
+ expect(screen.getByTestId('dao')).toHaveFocus();
+
+ // A fresh query (the typed buffer resets on its own after a pause).
+ cleanup();
+ render(<Tree collapsed={nodes} />);
+ screen.getByTestId('dung').focus();
+ fireEvent.keyDown(screen.getByRole('tree'), {key: 'i'});
+ expect(screen.getByTestId('izmir')).toHaveFocus();
+ });
+
+ it('typeahead ignores a combining mark typed first, as useTypeahead does (INV17)', () => {
+ const nodes: Node[] = [
+ {id: 'anna', label: 'Anna', level: 1},
+ {id: 'ava', label: 'Ava', level: 1},
+ {id: 'bo', label: 'Bo', level: 1},
+ ];
+ render(<Tree collapsed={nodes} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('bo').focus();
+ fireEvent.keyDown(tree, {key: '\u0301'});
+ fireEvent.keyDown(tree, {key: 'a'});
+ expect(screen.getByTestId('anna')).toHaveFocus();
+ // The mark never entered the buffer, so a repeat cycles to the next "a".
+ fireEvent.keyDown(tree, {key: 'a'});
+ expect(screen.getByTestId('ava')).toHaveFocus();
+ });
+
+ it('typeahead prefers the exact match for a typed mark (INV17)', () => {
+ const nodes: Node[] = [
+ {id: 'dung', label: 'Dung', level: 1},
+ {id: 'dao', label: 'Đào', level: 1},
+ {id: 'izmir', label: 'İzmir', level: 1},
+ {id: 'isparta', label: 'Isparta', level: 1},
+ ];
+ render(<Tree collapsed={nodes} />);
+ const tree = screen.getByRole('tree');
+ fireEvent.keyDown(tree, {key: 'đ'});
+ expect(screen.getByTestId('dao')).toHaveFocus();
+ });
+
it('typeahead searches from the top when no treeitem has focus', () => {
const nodes: Node[] = [
{id: 'apple', label: 'Apple', level: 1},
diff --git a/packages/core/src/hooks/useTreeFocus.ts b/packages/core/src/hooks/useTreeFocus.ts
index c9310b144a..42bcad699d 100644
--- a/packages/core/src/hooks/useTreeFocus.ts
+++ b/packages/core/src/hooks/useTreeFocus.ts
@@ -17,6 +17,7 @@
import {useCallback, useRef} from 'react';
import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
import {isRtlElement} from './isRtlElement';
+import {findTypeaheadMatch, nextTypeaheadBuffer} from '../utils/typeaheadMatch';
/** Keys handled by the tree keyboard model (used to gate typeahead). */
const NAVIGATION_KEYS = new Set([
@@ -427,15 +428,16 @@ export function useTreeFocusInternal<T extends HTMLElement = HTMLElement>(
currentIndex: number,
): void => {
const state = typeaheadRef.current;
+ // The same buffer step as useTypeahead: a repeat means "next match", and
+ // a lone combining mark typed first is not a letter to jump to.
+ const nextBuffer = nextTypeaheadBuffer(state.buffer, e.key);
+ if (nextBuffer == null) {
+ return;
+ }
if (state.timer != null) {
clearTimeout(state.timer);
}
- // "aa" would match nothing; a repeat means "next match" (useTypeahead).
- const char = e.key.toLowerCase();
- const isRepeatSameChar =
- state.buffer.length > 0 &&
- state.buffer.split('').every(c => c === char);
- state.buffer = isRepeatSameChar ? char : state.buffer + char;
+ state.buffer = nextBuffer;
state.timer = setTimeout(() => {
typeaheadRef.current.buffer = '';
}, typeaheadResetMs) as unknown as number;
@@ -449,11 +451,15 @@ export function useTreeFocusInternal<T extends HTMLElement = HTMLElement>(
...items.slice(start + offset),
...items.slice(0, start + offset),
];
- const match = ordered.find(
- item =>
- !itemDisabled(item) &&
- itemLabelText(item, matchLabelledBy).toLowerCase().startsWith(query),
+ const enabled = ordered.filter(item => !itemDisabled(item));
+ // INV17: case, accents, stroked letters and Turkish i fold away, and a
+ // typed mark prefers the exact match.
+ const matchIndex = findTypeaheadMatch(
+ enabled.map((_, i) => i),
+ i => itemLabelText(enabled[i], matchLabelledBy),
+ query,
);
+ const match = matchIndex >= 0 ? enabled[matchIndex] : undefined;
if (match != null) {
e.preventDefault();
focusItem(match);
diff --git a/packages/core/src/hooks/useTypeahead.doc.mjs b/packages/core/src/hooks/useTypeahead.doc.mjs
index 1d016b8c9b..ae3cae0030 100644
--- a/packages/core/src/hooks/useTypeahead.doc.mjs
+++ b/packages/core/src/hooks/useTypeahead.doc.mjs
@@ -75,7 +75,7 @@ export const docs = {
],
usage: {
description:
- "Adds APG type-to-focus search to a collection: printable keystrokes are buffered (resetting after a pause), and the first item whose label starts with the buffer is reported through onMatch. Pressing the same letter repeatedly cycles through the matches rather than filtering deeper. It moves nothing itself; pair it with the collection's own focus management, most often useListFocus or useGridFocus.",
+ "Adds APG type-to-focus search to a collection: printable keystrokes are buffered (resetting after a pause), and the first item whose label starts with the buffer (ignoring case, accents, the stroked letters đ ł ø ħ ŧ ƀ and Turkish ı/İ, the same in every locale; a typed accent prefers the exact match) is reported through onMatch. Pressing the same letter repeatedly cycles through the matches rather than filtering deeper. It moves nothing itself; pair it with the collection's own focus management, most often useListFocus or useGridFocus.",
bestPractices: [
{
guidance: true,
@@ -108,7 +108,7 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
description:
- 'APG type-to-focus search for a collection. Buffers printable keys (resets after pause), matches labels by prefix, reports index via onMatch. Same letter pressed repeatedly cycles matches. Moves nothing itself; pair w/ useListFocus / useGridFocus.',
+ 'APG type-to-focus search for a collection. Buffers printable keys (resets after pause), matches labels by prefix ignoring case, accents, stroked letters + Turkish ı/İ in every locale (typed accent prefers exact match), reports index via onMatch. Same letter pressed repeatedly cycles matches. Moves nothing itself; pair w/ useListFocus / useGridFocus.',
paramDescriptions: {
options: 'config.',
'options.getItemLabels':
diff --git a/packages/core/src/hooks/useTypeahead.test.tsx b/packages/core/src/hooks/useTypeahead.test.tsx
index 176ad60735..0161c178cd 100644
--- a/packages/core/src/hooks/useTypeahead.test.tsx
+++ b/packages/core/src/hooks/useTypeahead.test.tsx
@@ -12,6 +12,7 @@
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {Activity, type ReactNode} from 'react';
import {render, renderHook} from '@testing-library/react';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
import {useTypeahead} from './useTypeahead';
const LABELS = ['Apple', 'Apricot', 'Banana', 'Cherry'] as const;
@@ -348,4 +349,130 @@ describe('useTypeahead', () => {
expect(api.onKeyDown(synthetic)).toBe(false);
expect(onMatch).not.toHaveBeenCalled();
});
+
+ describe('accents and stroked letters', () => {
+ function setupLabels(
+ labels: ReadonlyArray<string>,
+ current = -1,
+ locale?: string,
+ ) {
+ const onMatch = vi.fn();
+ const {result} = renderHook(
+ () =>
+ useTypeahead({
+ getItemLabels: () => labels,
+ onMatch,
+ getCurrentIndex: () => current,
+ }),
+ locale == null
+ ? undefined
+ : {
+ wrapper: ({children}: {children: ReactNode}) => (
+ <InternationalizationProvider locale={locale}>
+ {children}
+ </InternationalizationProvider>
+ ),
+ },
+ );
+ return {onMatch, api: result.current};
+ }
+
+ it('matches a base letter against an accented first letter', () => {
+ const {onMatch, api} = setupLabels(['Anh', 'Dung', 'Đào', 'Ánh']);
+ api.onKeyDown(key('d'));
+ expect(onMatch).toHaveBeenLastCalledWith(1); // Dung
+ const second = setupLabels(['Dung', 'Đào'], 0);
+ second.api.onKeyDown(key('d'));
+ expect(second.onMatch).toHaveBeenLastCalledWith(1); // Đào
+ });
+
+ it('matches decomposed labels and a typed accent against the base letter', () => {
+ const decomposed = setupLabels(['Bob', 'Ánh']);
+ decomposed.api.onKeyDown(key('a'));
+ expect(decomposed.onMatch).toHaveBeenLastCalledWith(1);
+ const typed = setupLabels(['Bob', 'Ángel']);
+ typed.api.onKeyDown(key('á'));
+ expect(typed.onMatch).toHaveBeenLastCalledWith(1);
+ });
+
+ it('folds letters Unicode does not decompose (ł, ø)', () => {
+ const {onMatch, api} = setupLabels(['Anna', 'Łukasz']);
+ api.onKeyDown(key('l'));
+ expect(onMatch).toHaveBeenLastCalledWith(1);
+ const nordic = setupLabels(['Eva', 'Øystein']);
+ nordic.api.onKeyDown(key('o'));
+ expect(nordic.onMatch).toHaveBeenLastCalledWith(1);
+ });
+
+ it.each(['en-US', 'vi-VN', 'pl-PL', 'sv-SE', 'tr-TR'])(
+ 'folds the same way under the %s provider (INV17)',
+ locale => {
+ const reach = (
+ labels: ReadonlyArray<string>,
+ k: string,
+ ): number | undefined => {
+ const {onMatch, api} = setupLabels(labels, -1, locale);
+ api.onKeyDown(key(k));
+ return onMatch.mock.calls.at(-1)?.[0] as number | undefined;
+ };
+ expect(reach(['Bo', 'Åsa'], 'a')).toBe(1);
+ expect(reach(['Ana', 'Ñandú'], 'n')).toBe(1);
+ expect(reach(['Ana', 'Đào'], 'd')).toBe(1);
+ expect(reach(['Ana', 'Łódź'], 'l')).toBe(1);
+ expect(reach(['Ana', 'Ŧara'], 't')).toBe(1);
+ expect(reach(['Ana', 'Isparta'], 'ı')).toBe(1);
+ expect(reach(['Ana', 'İzmir'], 'i')).toBe(1);
+ expect(reach(['Dung', 'Đào'], 'đ')).toBe(1);
+ expect(reach(['İzmir', 'Isparta'], 'ı')).toBe(1);
+ expect(reach(['Isparta', 'İzmir'], 'İ')).toBe(1);
+ },
+ );
+
+ it('keeps a combining mark typed after a letter (Thai tone mark, Devanagari anusvara)', () => {
+ const typeAll = (
+ labels: ReadonlyArray<string>,
+ keys: ReadonlyArray<string>,
+ ): number | undefined => {
+ const {onMatch, api} = setupLabels(labels);
+ keys.forEach(k => api.onKeyDown(key(k)));
+ return onMatch.mock.calls.at(-1)?.[0];
+ };
+ // ตั้ง over ตัด and ตั้งค่า: the tone mark tells them apart.
+ expect(
+ typeAll(
+ ['วาง', 'ตัด', 'ตั้งค่า'],
+ ['ต', String.fromCharCode(0x0e31), String.fromCharCode(0xe49), 'ง'],
+ ),
+ ).toBe(2);
+ // हिंद over हिम and हिंदी: the anusvara tells them apart.
+ expect(
+ typeAll(
+ ['हिम', 'हिंदी'],
+ ['ह', String.fromCharCode(0x93f), String.fromCharCode(0x902), 'द'],
+ ),
+ ).toBe(1);
+ });
+
+ it('counts an accent typed as its own key as one letter, and matches decomposed labels', () => {
+ const typeAll = (
+ labels: ReadonlyArray<string>,
+ keys: ReadonlyArray<string>,
+ ): number | undefined => {
+ const {onMatch, api} = setupLabels(labels);
+ keys.forEach(k => api.onKeyDown(key(k)));
+ return onMatch.mock.calls.at(-1)?.[0];
+ };
+ const acute = String.fromCharCode(0x301);
+ // a, U+0301, n over a composed label.
+ expect(typeAll(['Ada', 'Ánh'], ['a', acute, 'n'])).toBe(1);
+ // The same over a label stored decomposed (A, U+0301, n, h).
+ expect(typeAll(['Ada', 'A' + acute + 'nh'], ['a', acute, 'n'])).toBe(1);
+ });
+
+ it('ignores a key that is only a combining mark', () => {
+ const {onMatch, api} = setupLabels(['Anna', 'Bob']);
+ expect(api.onKeyDown(key(String.fromCharCode(0x301)))).toBe(false);
+ expect(onMatch).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/packages/core/src/hooks/useTypeahead.ts b/packages/core/src/hooks/useTypeahead.ts
index 414fc686f2..3601de2641 100644
--- a/packages/core/src/hooks/useTypeahead.ts
+++ b/packages/core/src/hooks/useTypeahead.ts
@@ -4,7 +4,8 @@
/**
* @file useTypeahead.ts
- * @input Uses React useCallback/useEffect/useRef
+ * @input Uses React useCallback/useEffect/useRef, shared type-to-select
+ * matching (utils/typeaheadMatch)
* @output Exports useTypeahead hook for first-character (type-to-focus) search
* @position Core hook; adds APG typeahead to menus, listboxes, and other
* collections. Composes with useListFocus/useGridFocus (or any collection)
@@ -15,6 +16,7 @@
*/
import {useCallback, useEffect, useRef} from 'react';
+import {findTypeaheadMatch, nextTypeaheadBuffer} from '../utils/typeaheadMatch';
export interface UseTypeaheadOptions {
/**
@@ -94,7 +96,9 @@ function isComposingKey(e: React.KeyboardEvent | KeyboardEvent): boolean {
* First-character ("type-ahead") search for a collection.
*
* Buffers printable keystrokes (resetting after `resetMs` of inactivity),
- * matches items whose label starts with the buffer, and cycles from the
+ * matches items whose label starts with the buffer (ignoring case, accents,
+ * stroked letters and Turkish dotted/dotless i, the same in every locale:
+ * `architecture:internationalization` INV17), and cycles from the
* current index — so pressing "s" repeatedly walks through the "s" items
* instead of sticking on the first. Space is reserved for activation and is
* only treated as typeahead while a buffer is already active.
@@ -166,18 +170,19 @@ export function useTypeahead(options: UseTypeaheadOptions): UseTypeaheadReturn {
return false;
}
+ // A lone combining mark typed first is not a letter to jump to; after
+ // a letter it is part of that letter. A repeat of the same letter
+ // cycles rather than filtering deeper (APG behavior).
+ const nextBuffer = nextTypeaheadBuffer(bufferRef.current, e.key);
+ if (nextBuffer == null) {
+ return false;
+ }
+
const labels = getItemLabels();
if (labels.length === 0) {
return false;
}
- // Pressing the SAME single character repeatedly cycles to the next match
- // rather than filtering deeper (APG behavior).
- const char = e.key.toLowerCase();
- const isRepeatSameChar =
- bufferRef.current.length > 0 &&
- bufferRef.current.split('').every(c => c === char);
- const nextBuffer = isRepeatSameChar ? char : bufferRef.current + char;
bufferRef.current = nextBuffer;
scheduleReset();
@@ -191,21 +196,17 @@ export function useTypeahead(options: UseTypeaheadOptions): UseTypeaheadReturn {
// Once the buffer is longer it is refining a match, so the current item
// stays in range. With nothing current there is nothing to advance past.
const offset = hasCurrent && nextBuffer.length === 1 ? 1 : 0;
-
+ const order: number[] = [];
for (let i = 0; i < count; i++) {
const index = (start + offset + i + count) % count;
- if (isDisabled?.(index)) {
- continue;
- }
- const label = labels[index];
- if (
- label != null &&
- label.trim().toLowerCase().startsWith(nextBuffer)
- ) {
- onMatch(index);
- return true;
+ if (!isDisabled?.(index)) {
+ order.push(index);
}
}
+ const match = findTypeaheadMatch(order, i => labels[i], nextBuffer);
+ if (match >= 0) {
+ onMatch(match);
+ }
return true;
},
[getItemLabels, onMatch, getCurrentIndex, scheduleReset, isDisabled],
diff --git a/packages/core/src/utils/typeaheadMatch.test.ts b/packages/core/src/utils/typeaheadMatch.test.ts
new file mode 100644
index 0000000000..95814c9c4a
--- /dev/null
+++ b/packages/core/src/utils/typeaheadMatch.test.ts
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file typeaheadMatch.test.ts
+ * @input vitest, typeaheadMatch
+ * @output INV17 fold and exact-match preference cases
+ * @position Testing; `architecture:internationalization` INV17
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ findTypeaheadMatch,
+ foldForTypeahead,
+ nextTypeaheadBuffer,
+ typeaheadPrefixMatch,
+} from './typeaheadMatch';
+
+function first(labels: ReadonlyArray<string>, typed: string): string | null {
+ const index = findTypeaheadMatch(
+ labels.map((_, i) => i),
+ i => labels[i],
+ typed,
+ );
+ return index >= 0 ? labels[index] : null;
+}
+
+describe('typeaheadMatch (INV17)', () => {
+ it('ignores combining marks, composed or decomposed', () => {
+ expect(typeaheadPrefixMatch('Ánh', 'a')).toBe(true);
+ expect(typeaheadPrefixMatch('A\u0301nh', 'a')).toBe(true);
+ expect(typeaheadPrefixMatch('Åsa', 'a')).toBe(true);
+ expect(typeaheadPrefixMatch('Ñandú', 'n')).toBe(true);
+ });
+
+ it.each([
+ ['đ', 'Đào', 'd'],
+ ['ł', 'Łódź', 'l'],
+ ['ø', 'Øystein', 'o'],
+ ['ħ', 'Ħamrun', 'h'],
+ ['ŧ', 'Ŧara', 't'],
+ ['ƀ', 'Ƀorg', 'b'],
+ ])('folds the stroked letter %s to its plain letter', (_, label, typed) => {
+ expect(typeaheadPrefixMatch(label, typed)).toBe(true);
+ expect(typeaheadPrefixMatch(label.toLowerCase(), typed)).toBe(true);
+ });
+
+ it('folds Turkish ı and İ to i', () => {
+ expect(typeaheadPrefixMatch('Isparta', 'i')).toBe(true);
+ expect(typeaheadPrefixMatch('İzmir', 'i')).toBe(true);
+ expect(typeaheadPrefixMatch('Isparta', 'ı')).toBe(true);
+ expect(typeaheadPrefixMatch('İzmir', 'ı')).toBe(true);
+ });
+
+ it('prefers an exact match when the typed letters carry a mark', () => {
+ expect(first(['Dung', 'Đào'], 'đ')).toBe('Đào');
+ expect(first(['Ana', 'Ánh'], 'á')).toBe('Ánh');
+ expect(first(['Dung', 'Đào'], 'd')).toBe('Dung');
+ });
+
+ it('pairs case the Turkish way for the exact-match preference', () => {
+ expect(first(['İzmir', 'Isparta'], 'ı')).toBe('Isparta');
+ expect(first(['Isparta', 'İzmir'], 'İ')).toBe('İzmir');
+ });
+
+ it('falls back to the folded match when nothing matches exactly', () => {
+ expect(first(['Dung'], 'đ')).toBe('Dung');
+ });
+
+ it('never matches on a lone combining mark', () => {
+ expect(typeaheadPrefixMatch('Anna', '\u0301')).toBe(false);
+ expect(foldForTypeahead('\u0301')).toBe('');
+ });
+
+ it('keeps what canonical decomposition splits off outside U+0300–U+036F', () => {
+ // A Japanese voiced mark, an Arabic hamza, a Hangul final consonant.
+ expect(first(['がく', 'かさ'], 'か')).toBe('かさ');
+ expect(first(['أحمد', 'احلام'], 'ا')).toBe('احلام');
+ expect(first(['각도', '가방'], '가')).toBe('가방');
+ expect(typeaheadPrefixMatch('Йога', 'и')).toBe(true);
+ });
+
+ it('buffers keys the same way for every path', () => {
+ // A lone combining mark typed first is not a letter to jump to.
+ expect(nextTypeaheadBuffer('', '\u0301')).toBeNull();
+ // After a letter it is part of that letter.
+ expect(nextTypeaheadBuffer('a', '\u0301')).toBe('a\u0301');
+ // The same letter again cycles; a different letter refines.
+ expect(nextTypeaheadBuffer('a', 'a')).toBe('a');
+ expect(nextTypeaheadBuffer('a', 'á')).toBe('á');
+ expect(nextTypeaheadBuffer('a', 'n')).toBe('an');
+ });
+
+ it('keeps marks outside U+0300–U+036F (Thai tone marks)', () => {
+ expect(typeaheadPrefixMatch('ตั้งค่า', 'ตั้ง')).toBe(true);
+ expect(typeaheadPrefixMatch('ตัด', 'ตั้ง')).toBe(false);
+ });
+});
diff --git a/packages/core/src/utils/typeaheadMatch.ts b/packages/core/src/utils/typeaheadMatch.ts
new file mode 100644
index 0000000000..a025da3847
--- /dev/null
+++ b/packages/core/src/utils/typeaheadMatch.ts
@@ -0,0 +1,141 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file typeaheadMatch.ts
+ * @input Plain strings (an item label and the letters a person typed)
+ * @output foldForTypeahead, nextTypeaheadBuffer, typeaheadPrefixMatch,
+ * findTypeaheadMatch
+ * @position Shared type-to-select matching for useTypeahead, useTreeFocus and
+ * MultiSelector (`architecture:internationalization` INV17)
+ *
+ * Type-to-select is navigation, not sorting, so it folds the same way in every
+ * locale: case, the combining marks canonical decomposition leaves
+ * (U+0300–U+036F), six Latin letters with a stroke or bar, and Turkish ı and
+ * İ. Typed letters that carry one of those marks prefer an exact match, with
+ * case paired the Turkish way (ı with I, İ with i).
+ */
+
+const COMBINING_MARKS = /[\u0300-\u036f]/g;
+
+// The six stroked or barred Latin letters INV17 folds, in both cases. Turkish
+// dotless ı joins them; dotted İ decomposes to I + U+0307 and needs no entry.
+const STROKED: Readonly<Record<string, string>> = {
+ đ: 'd',
+ Đ: 'd',
+ ł: 'l',
+ Ł: 'l',
+ ø: 'o',
+ Ø: 'o',
+ ħ: 'h',
+ Ħ: 'h',
+ ŧ: 't',
+ Ŧ: 't',
+ ƀ: 'b',
+ Ƀ: 'b',
+ ı: 'i',
+};
+const STROKED_CHARS = /[đĐłŁøØħĦŧŦƀɃı]/g;
+const MARKED_CHARS = /[đĐłŁøØħĦŧŦƀɃıİ]/;
+
+/**
+ * Fold text for type-to-select: no case, no combining marks, the six stroked
+ * letters and ı as their base letter. Locale-independent by design.
+ */
+export function foldForTypeahead(text: string): string {
+ return (
+ text
+ .normalize('NFD')
+ .replace(COMBINING_MARKS, '')
+ .replace(STROKED_CHARS, c => STROKED[c] ?? c)
+ // Recompose what INV17 keeps (a Japanese voiced mark, an Arabic hamza, a
+ // Hangul final consonant), so a one-letter prefix does not skip it.
+ .normalize('NFC')
+ .toLowerCase()
+ );
+}
+
+/**
+ * The type-to-select buffer after one more key, shared by every path so they
+ * buffer the same way. Returns null when the key is not a letter to jump to: a
+ * lone combining mark typed first. Pressing the same letter again (as folded)
+ * cycles, so the buffer stays that one letter instead of growing.
+ */
+export function nextTypeaheadBuffer(
+ buffer: string,
+ key: string,
+): string | null {
+ if (
+ buffer.length === 0 &&
+ key !== ' ' &&
+ foldForTypeahead(key).length === 0
+ ) {
+ return null;
+ }
+ const isRepeatSameChar =
+ buffer.length > 0 &&
+ buffer.split('').every(c => foldForTypeahead(c) === foldForTypeahead(key));
+ return isRepeatSameChar ? key : buffer + key;
+}
+
+/**
+ * Case-fold for the exact-match preference, pairing the Turkish way: I with ı
+ * and İ with i. Composed, so an accent typed as its own key counts as one
+ * letter, as it does in a composed label.
+ */
+function exactFold(text: string): string {
+ return text
+ .normalize('NFC')
+ .replace(/I/g, 'ı')
+ .replace(/İ/g, 'i')
+ .toLowerCase();
+}
+
+/** Whether typed letters carry a mark that makes an exact match preferable. */
+function hasMark(typed: string): boolean {
+ return (
+ MARKED_CHARS.test(typed) || /[\u0300-\u036f]/.test(typed.normalize('NFD'))
+ );
+}
+
+/**
+ * Whether `label` starts with `typed` under INV17's fold. `exact` additionally
+ * requires the unfolded letters to match (Turkish case pairing).
+ */
+export function typeaheadPrefixMatch(
+ label: string,
+ typed: string,
+ exact = false,
+): boolean {
+ const trimmed = label.trim();
+ if (exact) {
+ return exactFold(trimmed).startsWith(exactFold(typed));
+ }
+ const foldedTyped = foldForTypeahead(typed);
+ // A lone combining mark folds to nothing; it is not a letter to jump to.
+ if (foldedTyped.length === 0) {
+ return false;
+ }
+ return foldForTypeahead(trimmed).startsWith(foldedTyped);
+}
+
+/**
+ * Find the next item whose label matches the typed letters, visiting indexes
+ * in `order`. When the typed letters carry a diacritic, a stroked letter, ı or
+ * İ, an exact match anywhere in the order wins over a folded one.
+ */
+export function findTypeaheadMatch(
+ order: ReadonlyArray<number>,
+ getLabel: (index: number) => string | null | undefined,
+ typed: string,
+): number {
+ const passes = hasMark(typed) ? [true, false] : [false];
+ for (const exact of passes) {
+ for (const index of order) {
+ const label = getLabel(index);
+ if (label != null && typeaheadPrefixMatch(label, typed, exact)) {
+ return index;
+ }
+ }
+ }
+ return -1;
+}