Skip to content

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

TypeScript

feat(Typeahead): show local matches at once and append server results (spec:AST-092) (#7962)

Cindy Zhanga03bffd8e7d1
diff --git a/.changeset/typeahead-incremental-results.md b/.changeset/typeahead-incremental-results.md
new file mode 100644
index 0000000000..f21508c007
--- /dev/null
+++ b/.changeset/typeahead-incremental-results.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] A `SearchSource` can show results before its search settles. `search(query, context)` may call `context.update(items)` (new exported type `SearchContext`) to show matches it already has, such as people the page loaded earlier, and then return the server's answer. `BaseTypeahead`, `Typeahead` and `Tokenizer` show each list for the current query, change the list at most once per keystroke, and add later rows only after the ones already shown, so the highlighted row never moves; the field stays busy and the result count is announced once, when the search settles. A later list that moves or removes shown rows is shown as given with a development warning. Sources that never call `update` show one list per query as before, with two changes every field sees: option element ids now follow the item's `id` instead of its row index (tests that select options by an index-based id need updating), and a grouped `Tokenizer` with `hasCreate` shows its Create row after the groups instead of first. To show local matches at once, pass `debounceMs={0}` and delay the server request inside the source (`spec:AST-092`).
+
+@cixzhang
diff --git a/.github/scripts/story-play-guard.js b/.github/scripts/story-play-guard.js
index db34b39b9c..17883bc7c3 100644
--- a/.github/scripts/story-play-guard.js
+++ b/.github/scripts/story-play-guard.js
@@ -354,6 +354,36 @@ const TARGETS = [
'isFullBleed strip/label geometry incl. clamp far side, and the real ' +
'LayoutHeader paddingBlockEnd -> TabList isFullBleed dock (#2622)',
},
+ {
+ component: 'Typeahead',
+ story: 'core-typeahead--incremental-results',
+ guards:
+ 'local matches show at once while busy; server rows only append; the highlighted option and its id stay; Enter selects it (spec:AST-092)',
+ },
+ {
+ component: 'Typeahead',
+ story: 'core-typeahead--incremental-results-above-field',
+ guards:
+ 'a popup above the field keeps its shown rows in place on screen while server rows append (spec:AST-092 FR6)',
+ },
+ {
+ component: 'Typeahead',
+ story: 'core-typeahead--incremental-results-scrolled',
+ guards:
+ 'a scrolled partial list keeps its scroll offset and shown rows in place while server rows append (spec:AST-092 FR6)',
+ },
+ {
+ component: 'Typeahead',
+ story: 'core-typeahead--incremental-results-below-field-overflow',
+ guards:
+ 'a popup below the field stays below and grows only within the room there when the server list outgrows it (spec:AST-092 FR6)',
+ },
+ {
+ component: 'Typeahead',
+ story: 'core-typeahead--incremental-results-resting-pointer',
+ guards:
+ 'rows appended under a resting pointer do not take the highlight; Enter selects the highlighted row (spec:AST-092 FR6)',
+ },
];
const CONTENT_TYPES = {
diff --git a/apps/storybook/stories/Typeahead.stories.tsx b/apps/storybook/stories/Typeahead.stories.tsx
index 01f21a7b4c..b007b4d116 100644
--- a/apps/storybook/stories/Typeahead.stories.tsx
+++ b/apps/storybook/stories/Typeahead.stories.tsx
@@ -2,6 +2,7 @@
import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
+import {expect, userEvent, waitFor, within} from 'storybook/test';
import {Typeahead} from '@astryxdesign/core/Typeahead';
import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';
import {MagnifyingGlassIcon} from '@heroicons/react/24/outline';
@@ -325,6 +326,368 @@ export const Loading: Story = {
name: 'Loading (async source)',
};
+/**
+ * People the page already has, and a directory server that answers later.
+ * The source shows its local matches through `context.update` at once and
+ * returns the server answer with the shown rows first and new rows after
+ * them, so the list changes once per keystroke and never moves under the
+ * pointer or the highlight (spec:AST-092).
+ */
+const localPeople: SearchableItem[] = [
+ {id: 'u1', label: 'Bea Lin'},
+ {id: 'u2', label: 'Ben Ortiz'},
+ {id: 'u3', label: 'Benita Ruiz'},
+ {id: 'u4', label: 'Bo Park'},
+];
+const directoryPeople: SearchableItem[] = [
+ ...localPeople,
+ {id: 'u7', label: 'Ben Shah'},
+ {id: 'u8', label: 'Bennett Cole'},
+ {id: 'u9', label: 'Bea Novak'},
+];
+
+function matchPeople(people: SearchableItem[], query: string) {
+ const lower = query.toLowerCase();
+ return people.filter(person =>
+ person.label
+ .toLowerCase()
+ .split(' ')
+ .some(word => word.startsWith(lower)),
+ );
+}
+
+let pendingDirectoryRequest: {
+ timer: ReturnType<typeof setTimeout>;
+ reject: (reason: Error) => void;
+} | null = null;
+const incrementalPeopleSource: SearchSource = {
+ bootstrap: () => localPeople,
+ cancel() {
+ // Settle the cancelled search so the field stops being busy.
+ if (pendingDirectoryRequest != null) {
+ clearTimeout(pendingDirectoryRequest.timer);
+ pendingDirectoryRequest.reject(new Error('cancelled'));
+ pendingDirectoryRequest = null;
+ }
+ },
+ async search(query, context) {
+ const local = matchPeople(localPeople, query);
+ context?.update(local);
+ return await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ pendingDirectoryRequest = null;
+ const shown = new Set(local.map(person => person.id));
+ const added = matchPeople(directoryPeople, query).filter(
+ person => !shown.has(person.id),
+ );
+ resolve([...local, ...added]);
+ }, 800);
+ pendingDirectoryRequest = {timer, reject};
+ });
+ },
+};
+
+export const IncrementalResults: Story = {
+ render: () => {
+ const [value, setValue] = useState<SearchableItem | null>(null);
+ return (
+ <Typeahead
+ label="Assign to"
+ placeholder="Search people"
+ searchSource={incrementalPeopleSource}
+ value={value}
+ onChange={setValue}
+ debounceMs={0}
+ />
+ );
+ },
+ name: 'Incremental results (local first, server appended)',
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByRole('combobox', {name: 'Assign to'});
+ const page = within(document.body);
+ const labels = () =>
+ page.queryAllByRole('option').map(option => option.textContent);
+
+ await userEvent.type(input, 'ben');
+ // One change for the keystroke: the local matches, while still busy.
+ await waitFor(() => expect(labels()).toEqual(['Ben Ortiz', 'Benita Ruiz']));
+ await expect(input).toHaveAttribute('aria-busy', 'true');
+
+ await userEvent.keyboard('{ArrowDown}');
+ const activeId = input.getAttribute('aria-activedescendant');
+ await expect(activeId).not.toBeNull();
+
+ // The server answer only appends; the shown rows and highlight stay put.
+ await waitFor(() => expect(input).not.toHaveAttribute('aria-busy'), {
+ timeout: 3000,
+ });
+ await expect(labels()).toEqual([
+ 'Ben Ortiz',
+ 'Benita Ruiz',
+ 'Ben Shah',
+ 'Bennett Cole',
+ ]);
+ await expect(input).toHaveAttribute(
+ 'aria-activedescendant',
+ activeId ?? '',
+ );
+
+ await userEvent.keyboard('{Enter}');
+ // The selected person shows as the field's value.
+ // The field shows the selected person (its value text renders more than
+ // once: shown, and measured for sizing).
+ await expect(
+ (await canvas.findAllByText('Benita Ruiz'))[0],
+ ).toBeInTheDocument();
+ },
+};
+
+/**
+ * The same source with the field near the bottom of the viewport, so the
+ * popup opens above it. Appended server rows scroll inside the popup; the
+ * rows already shown keep their place on screen (spec:AST-092 FR6).
+ */
+export const IncrementalResultsAboveField: Story = {
+ render: () => {
+ const [value, setValue] = useState<SearchableItem | null>(null);
+ return (
+ <div style={{paddingBlockStart: 'calc(100vh - 140px)'}}>
+ <Typeahead
+ label="Assign to"
+ placeholder="Search people"
+ searchSource={incrementalPeopleSource}
+ value={value}
+ onChange={setValue}
+ debounceMs={0}
+ />
+ </div>
+ );
+ },
+ name: 'Incremental results above the field',
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByRole('combobox', {name: 'Assign to'});
+ const page = within(document.body);
+
+ await userEvent.type(input, 'ben');
+ await waitFor(() => expect(page.queryAllByRole('option')).toHaveLength(2));
+ const [first] = page.getAllByRole('option');
+ const firstTop = first.getBoundingClientRect().top;
+ await expect(first.getBoundingClientRect().bottom).toBeLessThanOrEqual(
+ input.getBoundingClientRect().top,
+ );
+
+ await waitFor(() => expect(input).not.toHaveAttribute('aria-busy'), {
+ timeout: 3000,
+ });
+ await expect(page.getAllByRole('option')).toHaveLength(4);
+ // The shown rows did not move; the appended ones are reached by scrolling.
+ await expect(
+ Math.abs(
+ page.getAllByRole('option')[0].getBoundingClientRect().top - firstTop,
+ ),
+ ).toBeLessThan(1);
+ },
+};
+
+/**
+ * A source with many local matches and more from the server, for the cases
+ * where the list outgrows its popup (spec:AST-092 FR6).
+ */
+const manyLocal: SearchableItem[] = Array.from({length: 12}, (_, index) => ({
+ id: `local-${index}`,
+ label: `Alex ${String.fromCharCode(65 + index)}. Local`,
+}));
+const manyServer: SearchableItem[] = Array.from({length: 8}, (_, index) => ({
+ id: `server-${index}`,
+ label: `Alex ${String.fromCharCode(77 + index)}. Server`,
+}));
+function delayedAppendSource(local: SearchableItem[]): SearchSource {
+ let pending: {
+ timer: ReturnType<typeof setTimeout>;
+ reject: (reason: Error) => void;
+ } | null = null;
+ return {
+ bootstrap: () => [],
+ cancel() {
+ if (pending != null) {
+ clearTimeout(pending.timer);
+ pending.reject(new Error('cancelled'));
+ pending = null;
+ }
+ },
+ async search(query, context) {
+ const shown = matchPeople(local, query);
+ context?.update(shown);
+ return await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ pending = null;
+ resolve([...shown, ...matchPeople(manyServer, query)]);
+ }, 800);
+ pending = {timer, reject};
+ });
+ },
+ };
+}
+const scrolledSource = delayedAppendSource(manyLocal);
+const shortListSource = delayedAppendSource(manyLocal.slice(0, 2));
+
+/**
+ * The user scrolls a partial list before the server answers: appended rows
+ * land below, and the scroll position and the rows shown stay put.
+ */
+export const IncrementalResultsScrolled: Story = {
+ render: () => {
+ const [value, setValue] = useState<SearchableItem | null>(null);
+ return (
+ <Typeahead
+ label="Assign to"
+ placeholder="Search people"
+ searchSource={scrolledSource}
+ value={value}
+ onChange={setValue}
+ debounceMs={0}
+ maxMenuItems={30}
+ />
+ );
+ },
+ name: 'Incremental results in a scrolled list',
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByRole('combobox', {name: 'Assign to'});
+ const page = within(document.body);
+
+ await userEvent.type(input, 'alex');
+ await waitFor(() => expect(page.queryAllByRole('option')).toHaveLength(12));
+ const listbox = page.getByRole('listbox');
+ const scroller =
+ listbox.scrollHeight > listbox.clientHeight
+ ? listbox
+ : (listbox.parentElement as HTMLElement);
+ scroller.scrollTop = scroller.scrollHeight;
+ const scrolledTo = scroller.scrollTop;
+ await expect(scrolledTo).toBeGreaterThan(0);
+ const lastShown = page.getByRole('option', {name: 'Alex L. Local'});
+ const lastShownTop = lastShown.getBoundingClientRect().top;
+
+ await waitFor(() => expect(input).not.toHaveAttribute('aria-busy'), {
+ timeout: 3000,
+ });
+ await expect(page.getAllByRole('option')).toHaveLength(20);
+ // The scroll offset and the shown rows' place on screen did not move.
+ await expect(Math.abs(scroller.scrollTop - scrolledTo)).toBeLessThan(1);
+ await expect(
+ Math.abs(lastShown.getBoundingClientRect().top - lastShownTop),
+ ).toBeLessThan(1);
+ },
+};
+
+/**
+ * The field sits low enough that the first, short list fits below it but the
+ * server's answer would not: the popup stays below and grows only within the
+ * room there, scrolling the rest (spec:AST-092 FR6).
+ */
+export const IncrementalResultsBelowFieldOverflow: Story = {
+ render: () => {
+ const [value, setValue] = useState<SearchableItem | null>(null);
+ return (
+ <div style={{paddingBlockStart: 'calc(100vh - 280px)'}}>
+ <Typeahead
+ label="Assign to"
+ placeholder="Search people"
+ searchSource={shortListSource}
+ value={value}
+ onChange={setValue}
+ debounceMs={0}
+ />
+ </div>
+ );
+ },
+ name: 'Incremental results below the field, outgrowing the room',
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByRole('combobox', {name: 'Assign to'});
+ const page = within(document.body);
+
+ await userEvent.type(input, 'alex');
+ await waitFor(() => expect(page.queryAllByRole('option')).toHaveLength(2));
+ const [first] = page.getAllByRole('option');
+ const firstTop = first.getBoundingClientRect().top;
+ // The first list opens below the field.
+ await expect(firstTop).toBeGreaterThanOrEqual(
+ input.getBoundingClientRect().bottom,
+ );
+
+ await waitFor(() => expect(input).not.toHaveAttribute('aria-busy'), {
+ timeout: 3000,
+ });
+ await expect(page.getAllByRole('option')).toHaveLength(10);
+ const popup = page.getByRole('listbox');
+ // Still below the field, inside the viewport, with the first row in place.
+ await expect(popup.getBoundingClientRect().top).toBeGreaterThanOrEqual(
+ input.getBoundingClientRect().bottom - 1,
+ );
+ await expect(popup.getBoundingClientRect().bottom).toBeLessThanOrEqual(
+ window.innerHeight,
+ );
+ await expect(
+ Math.abs(
+ page.getAllByRole('option')[0].getBoundingClientRect().top - firstTop,
+ ),
+ ).toBeLessThan(1);
+ },
+};
+
+/**
+ * A pointer resting where the server's rows land does not take the
+ * highlight: the rows arrive under it without the pointer moving, so Enter
+ * still picks the row the keyboard highlighted (spec:AST-092 FR6).
+ */
+export const IncrementalResultsRestingPointer: Story = {
+ render: () => {
+ const [value, setValue] = useState<SearchableItem | null>(null);
+ return (
+ <Typeahead
+ label="Assign to"
+ placeholder="Search people"
+ searchSource={incrementalPeopleSource}
+ value={value}
+ onChange={setValue}
+ debounceMs={0}
+ />
+ );
+ },
+ name: 'Incremental results under a resting pointer',
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByRole('combobox', {name: 'Assign to'});
+ const page = within(document.body);
+
+ await userEvent.type(input, 'ben');
+ await waitFor(() => expect(page.queryAllByRole('option')).toHaveLength(2));
+ await userEvent.keyboard('{ArrowDown}');
+ const activeId = input.getAttribute('aria-activedescendant');
+ await waitFor(() => expect(input).not.toHaveAttribute('aria-busy'), {
+ timeout: 3000,
+ });
+ // A row appearing under a still pointer gets boundary events, not a move.
+ const appended = page.getByRole('option', {name: 'Ben Shah'});
+ appended.dispatchEvent(new MouseEvent('mouseover', {bubbles: true}));
+ appended.dispatchEvent(new MouseEvent('mouseenter'));
+ await expect(input).toHaveAttribute(
+ 'aria-activedescendant',
+ activeId ?? '',
+ );
+ await userEvent.keyboard('{Enter}');
+ // The field shows the selected person (its value text renders more than
+ // once: shown, and measured for sizing).
+ await expect(
+ (await canvas.findAllByText('Benita Ruiz'))[0],
+ ).toBeInTheDocument();
+ },
+};
+
/**
* The two cases no Typeahead story covered, which is why a bug this visible
* survived: a value selected, and a parent that is sized by its content.
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 0fab0e43de..93d91fcded 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -466,7 +466,10 @@ layers use Layer rendering without joining Escape/platform dismissal.
app-declared inset have one definition in the runtime; every anchor-mode layer
inherits them, the layer box never exceeds the caps, the toast viewport reads
the same inset, no consumer defines its own, no size is capped to the span
- beside the trigger, and a consumer minimum is clamped by the runtime's cap.
+ beside the trigger, except that a later list for the same query keeps an open
+ Typeahead popup on its side and grows it only within the room there
+ (`spec:AST-092` FR6); the first list for a query places it normally, and a
+ consumer minimum is clamped by the runtime's cap.
- **INV12 — The first frame is the settled frame.** No input to a layer's
viewport geometry is measured after paint and then applied, with one
exception. The runtime observes anchor visibility for every layer, and,
@@ -632,17 +635,17 @@ this current architecture record.
## Verification
-| Invariant | Evidence | Failure signal |
-| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| INV1, INV2 | `useLayer.test.tsx` and `layerHost.test.ts` | Invalid DOM, stale host, lost theme/writing context, or portal mistaken for top-layer promotion |
-| INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost |
-| INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor |
-| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |
-| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |
-| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |
-| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests | A current local channel silently changes ownership or policy |
-| INV10 | `LayerProvider.tsx`, `LayerProvider.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, and `ToastViewport.modalHost.test.tsx` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, or a default provider renders differently from no provider |
-| INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow |
+| Invariant | Evidence | Failure signal |
+| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| INV1, INV2 | `useLayer.test.tsx` and `layerHost.test.ts` | Invalid DOM, stale host, lost theme/writing context, or portal mistaken for top-layer promotion |
+| INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost |
+| INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport; `BaseTypeahead.incremental.test.tsx` and the Typeahead incremental-results stories for the `spec:AST-092` FR6 exception | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor; for an open Typeahead popup, a later list for the same query that flips it to the other side or grows it past the room on its side, or a first list for a query that is capped to the span beside the trigger |
+| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |
+| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |
+| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |
+| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests | A current local channel silently changes ownership or policy |
+| INV10 | `LayerProvider.tsx`, `LayerProvider.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, and `ToastViewport.modalHost.test.tsx` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, or a default provider renders differently from no provider |
+| INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow |
Current unit coverage proves emitted styles, reducers, state transitions, and DOM
placement. Native Popover, `<dialog>`, focus, top-layer ordering, and rendered
diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
index b393882d80..94d6bbd23f 100644
--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs
+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
@@ -42,7 +42,7 @@ export const docs = {
name: 'searchSource',
type: 'SearchSource<T>',
description:
- 'Data source providing search and bootstrap methods for populating the dropdown.',
+ 'Data source providing search and bootstrap methods. `search(query, context)` may call `context.update(items)` to show matches it already has before it returns; the value it returns is the final list, and every list after the first for a query keeps the shown rows first and adds new rows after them.',
required: true,
},
{
@@ -196,7 +196,7 @@ export const docs = {
name: 'debounceMs',
type: 'number',
description:
- 'Debounce delay in ms before triggering search. Set to 0 for synchronous sources.',
+ 'Debounce delay in ms before triggering search. Set to 0 for synchronous sources, and for a source that shows local matches through `context.update` and delays its own server request.',
default: '150',
},
{
@@ -266,12 +266,14 @@ export const docs = {
{
name: 'containerClassName',
type: 'string',
- description: 'Class name for the field container. Same targeting as `containerXstyle`.',
+ description:
+ 'Class name for the field container. Same targeting as `containerXstyle`.',
},
{
name: 'containerStyle',
type: 'CSSProperties',
- description: 'Inline styles for the field container. Same targeting as `containerXstyle`.',
+ description:
+ 'Inline styles for the field container. Same targeting as `containerXstyle`.',
},
{
name: 'controlXstyle',
@@ -407,7 +409,7 @@ export const docsZh = {
name: 'searchSource',
type: 'SearchSource<T>',
description:
- '\u63d0\u4f9b\u641c\u7d22\u548c\u5f15\u5bfc\u65b9\u6cd5\u7684\u6570\u636e\u6e90\uff0c\u7528\u4e8e\u586b\u5145\u4e0b\u62c9\u5217\u8868\u3002',
+ '提供搜索和引导方法的数据源。`search(query, context)` 可调用 `context.update(items)` 先显示已有的匹配项;返回值是最终列表,同一查询在第一个列表之后的每个列表都保留已显示的行,并只在其后追加新行。',
required: true,
},
{
@@ -570,7 +572,7 @@ export const docsZh = {
name: 'debounceMs',
type: 'number',
description:
- '\u89e6\u53d1\u641c\u7d22\u524d\u7684\u9632\u6296\u5ef6\u8fdf\uff08\u6beb\u79d2\uff09\u3002\u540c\u6b65\u6570\u636e\u6e90\u8bbe\u7f6e\u4e3a 0\u3002',
+ '触发搜索前的防抖延迟(毫秒)。同步数据源,以及通过 `context.update` 显示本地匹配项并自行延迟服务器请求的数据源,设置为 0。',
default: '150',
},
{
@@ -780,10 +782,12 @@ export const docsDense = {
],
},
propDescriptions: {
- containerXstyle: 'StyleX styles for the field container; no effect in InputGroup or horizontal-labels FormLayout. No root xstyle/className/style.',
+ containerXstyle:
+ 'StyleX styles for the field container; no effect in InputGroup or horizontal-labels FormLayout. No root xstyle/className/style.',
containerClassName: 'Class name for the field container.',
containerStyle: 'Inline styles for the field container.',
- controlXstyle: 'StyleX styles for the visual control box (border, background, icons); not the native input.',
+ controlXstyle:
+ 'StyleX styles for the visual control box (border, background, icons); not the native input.',
controlClassName: 'Class name for the visual control box.',
controlStyle: 'Inline styles for the visual control box.',
label: 'Accessible label for input.',
diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsx
index 304940d546..2cb81e9189 100644
--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx
@@ -2295,3 +2295,110 @@ describe('Tokenizer caller aria-labelledby', () => {
).toBeInTheDocument();
});
});
+
+describe('Tokenizer incremental results (spec:AST-092)', () => {
+ const ben = {id: 'u2', label: 'Ben'};
+ const benita = {id: 'u3', label: 'Benita'};
+ const benShah = {id: 'u7', label: 'Ben Shah'};
+
+ function pendingSource() {
+ let settle: (items: SearchableItem[]) => void = () => {};
+ const source: SearchSource = {
+ bootstrap: () => [],
+ async search(_query, context) {
+ context?.update([ben, benita]);
+ return new Promise<SearchableItem[]>(resolve => {
+ settle = resolve;
+ });
+ },
+ };
+ return {source, settle: (items: SearchableItem[]) => settle(items)};
+ }
+
+ function optionLabels() {
+ return screen
+ .queryAllByRole('option', {hidden: true})
+ .map(option => option.textContent);
+ }
+
+ it('removes committed values from partial lists too (FR1, component:Tokenizer FR13)', async () => {
+ const {source, settle} = pendingSource();
+ render(
+ <Tokenizer
+ label="People"
+ searchSource={source}
+ value={[benita]}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'ben'}});
+ });
+ expect(optionLabels()).toEqual(['Ben']);
+
+ await act(async () => {
+ settle([ben, benita, benShah]);
+ });
+ expect(optionLabels()).toEqual(['Ben', 'Ben Shah']);
+ });
+
+ it('offers the create row only once a searched query settles (FR1)', async () => {
+ const {source, settle} = pendingSource();
+ render(
+ <Tokenizer
+ label="People"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ hasCreate
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'ben s'}});
+ });
+ expect(optionLabels()).toEqual(['Ben', 'Benita']);
+
+ await act(async () => {
+ settle([ben, benita]);
+ });
+ expect(optionLabels()).toEqual(['Ben', 'Benita', 'Create "ben s"']);
+ });
+
+ it('keeps grouped rows in place and shows the create row after them when the query settles (FR1, FR2)', async () => {
+ const people = {id: 'p1', label: 'Ben', auxiliaryData: {group: 'People'}};
+ const teams = {id: 't1', label: 'Bento', auxiliaryData: {group: 'Teams'}};
+ let settle: (items: SearchableItem[]) => void = () => {};
+ const source: SearchSource = {
+ bootstrap: () => [],
+ async search(_query, context) {
+ context?.update([people]);
+ return new Promise<SearchableItem[]>(resolve => {
+ settle = resolve;
+ });
+ },
+ };
+ render(
+ <Tokenizer
+ label="People"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ hasCreate
+ debounceMs={0}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'ben x'}});
+ });
+ expect(optionLabels()).toEqual(['Ben']);
+ await act(async () => {
+ settle([people, teams]);
+ });
+ expect(optionLabels()).toEqual(['Ben', 'Bento', 'Create "ben x"']);
+ });
+});
diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx
index a14058602f..93f90ba3db 100644
--- a/packages/core/src/Tokenizer/Tokenizer.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.tsx
@@ -85,7 +85,11 @@ import {
sizeVars,
typeScaleVars,
} from '../theme/tokens.stylex';
-import type {SearchableItem, SearchSource} from '../Typeahead/types';
+import type {
+ SearchContext,
+ SearchableItem,
+ SearchSource,
+} from '../Typeahead/types';
import {composeEventHandlers, mergeProps} from '../utils';
import {joinAriaIDs} from '../utils/inputAria';
import {isFocusDetached} from '../utils/focusReturn';
@@ -1098,8 +1102,16 @@ export function Tokenizer<T extends SearchableItem>({
const filteredSource: SearchSource<T> = useMemo(
() => ({
- search: async (query: string) => {
- const results = await searchSource.search(query);
+ // Committed values leave every list, partial or final
+ // (component:Tokenizer FR13, spec:AST-092 FR1).
+ search: async (query: string, context?: SearchContext<T>) => {
+ const results = await searchSource.search(
+ query,
+ context && {
+ update: items =>
+ context.update(items.filter(item => !selectedIds.has(item.id))),
+ },
+ );
return results.filter(item => !selectedIds.has(item.id));
},
bootstrap: async () => {
diff --git a/packages/core/src/Typeahead/BaseTypeahead.doc.mjs b/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
index 4986f71431..4649faba91 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
+++ b/packages/core/src/Typeahead/BaseTypeahead.doc.mjs
@@ -107,7 +107,8 @@ export const docs = {
{
name: 'searchSource',
type: 'SearchSource<T>',
- description: 'Data source providing search and bootstrap methods.',
+ description:
+ 'Data source providing search and bootstrap methods. `search(query, context)` may call `context.update(items)` to show matches it already has before it returns; the value it returns is the final list, and every list after the first for a query keeps the shown rows first and adds new rows after them.',
required: true,
},
{
@@ -188,7 +189,7 @@ export const docs = {
name: 'debounceMs',
type: 'number',
description:
- 'Debounce delay in ms before triggering search. Set to 0 for synchronous sources.',
+ 'Debounce delay in ms before triggering search. Set to 0 for synchronous sources, and for a source that shows local matches through `context.update` and delays its own server request.',
default: '150',
},
{
@@ -267,7 +268,8 @@ export const docsZh = {
{
name: 'searchSource',
type: 'SearchSource<T>',
- description: '提供搜索和引导方法的数据源。',
+ description:
+ '提供搜索和引导方法的数据源。`search(query, context)` 可调用 `context.update(items)` 先显示已有的匹配项;返回值是最终列表,同一查询在第一个列表之后的每个列表都保留已显示的行,并只在其后追加新行。',
required: true,
},
{
@@ -346,7 +348,8 @@ export const docsZh = {
{
name: 'debounceMs',
type: 'number',
- description: '触发搜索前的防抖延迟(毫秒)。同步数据源设置为 0。',
+ description:
+ '触发搜索前的防抖延迟(毫秒)。同步数据源,以及通过 `context.update` 显示本地匹配项并自行延迟服务器请求的数据源,设置为 0。',
default: '150',
},
{
diff --git a/packages/core/src/Typeahead/BaseTypeahead.incremental.test.tsx b/packages/core/src/Typeahead/BaseTypeahead.incremental.test.tsx
new file mode 100644
index 0000000000..f88b357621
--- /dev/null
+++ b/packages/core/src/Typeahead/BaseTypeahead.incremental.test.tsx
@@ -0,0 +1,612 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file BaseTypeahead.incremental.test.tsx
+ * @input BaseTypeahead with a source that calls `context.update` before it settles
+ * @output Verification of incremental search results (spec:AST-092)
+ * @position Colocated verification for BaseTypeahead partial and final lists
+ */
+
+import {afterAll, afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {StrictMode} from 'react';
+import {BaseTypeahead} from './BaseTypeahead';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {__resetDevWarnings} from '../utils/devWarning';
+import type {SearchContext, SearchSource, SearchableItem} from './types';
+
+const popoverOpenState = new WeakMap<HTMLElement, boolean>();
+const originalMatchesDescriptor = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ 'matches',
+);
+const originalMatches = HTMLElement.prototype.matches;
+
+beforeAll(() => {
+ HTMLElement.prototype.showPopover = function () {
+ popoverOpenState.set(this, true);
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ };
+ HTMLElement.prototype.hidePopover = function () {
+ popoverOpenState.set(this, false);
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ };
+ Object.defineProperty(HTMLElement.prototype, 'matches', {
+ ...originalMatchesDescriptor,
+ value(this: HTMLElement, selector: string) {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ return originalMatches.call(this, selector);
+ },
+ });
+});
+
+afterAll(() => {
+ if (originalMatchesDescriptor) {
+ Object.defineProperty(
+ HTMLElement.prototype,
+ 'matches',
+ originalMatchesDescriptor,
+ );
+ }
+});
+
+afterEach(() => {
+ __resetLiveRegionsForTest();
+ __resetDevWarnings();
+ vi.restoreAllMocks();
+});
+
+const benOrtiz = {id: 'u2', label: 'Ben Ortiz'};
+const benitaRuiz = {id: 'u3', label: 'Benita Ruiz'};
+const benShah = {id: 'u7', label: 'Ben Shah'};
+const bennettCole = {id: 'u8', label: 'Bennett Cole'};
+const beaLin = {id: 'u1', label: 'Bea Lin'};
+
+interface PendingSearch {
+ query: string;
+ context: SearchContext<SearchableItem> | undefined;
+ resolve: (items: SearchableItem[]) => void;
+ reject: (error: unknown) => void;
+}
+
+/**
+ * A source whose every search stays pending until the test settles it. Local
+ * matches, when given for a query, are shown through `update` before
+ * `search()` returns, the way a source with cached results behaves.
+ */
+function createPendingSource(local: Record<string, SearchableItem[]> = {}) {
+ const searches: PendingSearch[] = [];
+ const source: SearchSource<SearchableItem> = {
+ bootstrap: () => [],
+ async search(query, context) {
+ const localMatches = local[query];
+ if (localMatches) {
+ context?.update(localMatches);
+ }
+ return new Promise<SearchableItem[]>((resolve, reject) => {
+ searches.push({query, context, resolve, reject});
+ });
+ },
+ };
+ const latest = () => searches[searches.length - 1];
+ return {source, searches, latest};
+}
+
+function renderTypeahead(
+ source: SearchSource<SearchableItem>,
+ onChange: (item: SearchableItem | null) => void = () => {},
+) {
+ render(
+ <BaseTypeahead
+ aria-label="Assign to"
+ searchSource={source}
+ value={null}
+ onChange={onChange}
+ debounceMs={0}
+ />,
+ );
+ return screen.getByRole('combobox', {name: 'Assign to'});
+}
+
+function optionLabels() {
+ return screen
+ .queryAllByRole('option', {hidden: true})
+ .map(option => option.textContent);
+}
+
+function liveRegion() {
+ return document.querySelector('[data-astryx-live-region="polite"]');
+}
+
+async function type(input: HTMLElement, value: string) {
+ await act(async () => {
+ fireEvent.change(input, {target: {value}});
+ });
+}
+
+async function settle(search: PendingSearch, items: SearchableItem[]) {
+ await act(async () => {
+ search.resolve(items);
+ });
+}
+
+describe('BaseTypeahead incremental results (spec:AST-092)', () => {
+ it('shows a partial list at once and stays busy until the final list (FR1, FR5)', async () => {
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+
+ await type(input, 'ben');
+ expect(optionLabels()).toEqual(['Ben Ortiz', 'Benita Ruiz']);
+ expect(input).toHaveAttribute('aria-busy', 'true');
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah, bennettCole]);
+ expect(optionLabels()).toEqual([
+ 'Ben Ortiz',
+ 'Benita Ruiz',
+ 'Ben Shah',
+ 'Bennett Cole',
+ ]);
+ expect(input).not.toHaveAttribute('aria-busy');
+ });
+
+ it('keeps the highlighted item, its option id, and Enter on it when rows are appended (FR6, FR7)', async () => {
+ const onChange = vi.fn();
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source, onChange);
+
+ await type(input, 'ben');
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ const activeId = input.getAttribute('aria-activedescendant');
+ expect(activeId).not.toBeNull();
+ expect(document.getElementById(activeId!)).toHaveTextContent('Benita Ruiz');
+
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah, bennettCole]);
+ expect(input).toHaveAttribute('aria-activedescendant', activeId!);
+ expect(document.getElementById(activeId!)).toHaveTextContent('Benita Ruiz');
+
+ fireEvent.keyDown(input, {key: 'Enter'});
+ expect(onChange).toHaveBeenCalledWith(benitaRuiz);
+ });
+
+ it('announces the result count once per query, when it settles (FR8)', async () => {
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+ const announced: string[] = [];
+ let lastText = '';
+ const observer = new MutationObserver(() => {
+ const text = liveRegion()?.textContent ?? '';
+ if (text !== lastText) {
+ if (text !== '') {
+ announced.push(text);
+ }
+ lastText = text;
+ }
+ });
+
+ observer.observe(document.body, {
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+ await type(input, 'ben');
+ // The channel writes on the next frame; give a partial list the chance.
+ await act(async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ });
+ expect(announced).toEqual([]);
+
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah, bennettCole]);
+ await waitFor(() => {
+ expect(announced).toContain('4 results');
+ });
+ await act(async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ });
+ observer.disconnect();
+ expect(announced).toEqual(['4 results']);
+ });
+
+ it('drops lists for a query that is no longer current (FR4)', async () => {
+ const {source, searches} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+
+ await type(input, 'be');
+ const stale = searches[0];
+ await type(input, 'ben');
+ await act(async () => {
+ stale.context?.update([beaLin]);
+ });
+ await settle(stale, [beaLin, benOrtiz]);
+ expect(optionLabels()).toEqual(['Ben Ortiz', 'Benita Ruiz']);
+ });
+
+ it('ignores an update after the query settles (FR3)', async () => {
+ const {source, latest} = createPendingSource();
+ const input = renderTypeahead(source);
+
+ await type(input, 'ben');
+ const search = latest();
+ await settle(search, [benOrtiz]);
+ await act(async () => {
+ search.context?.update([benOrtiz, benShah]);
+ });
+ expect(optionLabels()).toEqual(['Ben Ortiz']);
+ });
+
+ it('leaves rows in place on an empty update and shows the empty row only at settle (FR5)', async () => {
+ const {source, latest} = createPendingSource({b: [beaLin], bz: []});
+ const input = renderTypeahead(source);
+
+ await type(input, 'b');
+ await settle(latest(), [beaLin]);
+ await type(input, 'bz');
+ expect(optionLabels()).toEqual(['Bea Lin']);
+ expect(input).toHaveAttribute('aria-busy', 'true');
+
+ await settle(latest(), []);
+ expect(optionLabels()).toEqual(['No results found']);
+ });
+
+ it('keeps the last non-empty list when the answer fails (FR9)', async () => {
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+
+ await type(input, 'ben');
+ await act(async () => {
+ latest().reject(new Error('offline'));
+ });
+ expect(optionLabels()).toEqual(['Ben Ortiz', 'Benita Ruiz']);
+ expect(input).not.toHaveAttribute('aria-busy');
+ await waitFor(() => {
+ expect(liveRegion()?.textContent).toBe('2 results');
+ });
+ });
+
+ it('announces only the count when the answer fails before the busy start is written (FR9, AST-086 FR8)', async () => {
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+ const announced: string[] = [];
+ const observer = new MutationObserver(() => {
+ const text = liveRegion()?.textContent ?? '';
+ if (text !== '' && announced.at(-1) !== text) {
+ announced.push(text);
+ }
+ });
+ observer.observe(document.body, {
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+
+ await type(input, 'ben');
+ // The busy start is queued on the polite channel a frame after the
+ // partial list; the failure lands before the channel writes it.
+ await act(async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ latest().reject(new Error('offline'));
+ });
+ await waitFor(() => {
+ expect(announced).toContain('2 results');
+ });
+ for (let frame = 0; frame < 3; frame++) {
+ await act(async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ });
+ }
+ observer.disconnect();
+ expect(announced.join(' | ')).not.toMatch(/Loading|Searching/);
+ expect(liveRegion()?.textContent).toBe('2 results');
+ });
+
+ it('settles empty, not on the previous query rows, when only empty updates preceded a failure (FR9)', async () => {
+ const {source, latest} = createPendingSource({b: [beaLin], bz: []});
+ const input = renderTypeahead(source);
+
+ await type(input, 'b');
+ await settle(latest(), [beaLin]);
+ await type(input, 'bz');
+ await act(async () => {
+ latest().reject(new Error('offline'));
+ });
+ expect(optionLabels()).toEqual(['No results found']);
+ });
+
+ it('warns in development when a later list moves shown rows, and shows it as given (FR2)', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+
+ await type(input, 'ben');
+ await settle(latest(), [benShah, benOrtiz, benitaRuiz]);
+ expect(optionLabels()).toEqual(['Ben Shah', 'Ben Ortiz', 'Benita Ruiz']);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('BaseTypeahead:'),
+ );
+ });
+
+ it('lets the first list of a new query replace the rows without a warning (FR2)', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {source, latest} = createPendingSource({be: [benitaRuiz]});
+ const input = renderTypeahead(source);
+
+ await type(input, 'b');
+ await settle(latest(), [beaLin, benOrtiz, benitaRuiz]);
+ await type(input, 'be');
+ expect(optionLabels()).toEqual(['Benita Ruiz']);
+ await settle(latest(), [benitaRuiz, beaLin]);
+ expect(optionLabels()).toEqual(['Benita Ruiz', 'Bea Lin']);
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('keeps a row in place when its id returns with fresher data (FR2)', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+
+ await type(input, 'ben');
+ await settle(latest(), [
+ {...benOrtiz, label: 'Ben Ortiz (Payments)'},
+ benitaRuiz,
+ benShah,
+ ]);
+ expect(optionLabels()).toEqual([
+ 'Ben Ortiz (Payments)',
+ 'Benita Ruiz',
+ 'Ben Shah',
+ ]);
+ expect(warn).not.toHaveBeenCalled();
+ });
+ it('applies append-only to displayed order, groups included (FR2)', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const people = {
+ id: 'g1',
+ label: 'Ben Ortiz',
+ auxiliaryData: {group: 'People'},
+ };
+ const teams = {
+ id: 'g2',
+ label: 'Bento team',
+ auxiliaryData: {group: 'Teams'},
+ };
+ const lateUngrouped = {id: 'g3', label: 'Ben (alias)'};
+ const {source, latest} = createPendingSource({ben: [people]});
+ const input = renderTypeahead(source);
+
+ await type(input, 'ben');
+ // A new group after the shown rows is an append.
+ await act(async () => {
+ latest().context?.update([people, teams]);
+ });
+ expect(warn).not.toHaveBeenCalled();
+
+ // An ungrouped row displays above every group, so it breaks the rule.
+ await settle(latest(), [people, teams, lateUngrouped]);
+ expect(optionLabels()).toEqual(['Ben (alias)', 'Ben Ortiz', 'Bento team']);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('BaseTypeahead:'),
+ );
+ });
+
+ it('holds the height of a popup above the field when rows are appended (FR6)', async () => {
+ const {source, latest} = createPendingSource({ben: [benOrtiz, benitaRuiz]});
+ const input = renderTypeahead(source);
+ await type(input, 'ben');
+
+ const listbox = screen.getByRole('listbox', {hidden: true});
+ vi.spyOn(listbox, 'getBoundingClientRect').mockReturnValue(
+ DOMRect.fromRect({x: 0, y: 20, width: 240, height: 80}),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(
+ DOMRect.fromRect({x: 0, y: 104, width: 240, height: 32}),
+ );
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah, bennettCole]);
+ expect(listbox.getAttribute('style') ?? '').toContain('80px');
+ });
+
+ it('grows a popup below the field only within the room below it (FR6)', async () => {
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+ await type(input, 'ben');
+
+ const listbox = screen.getByRole('listbox', {hidden: true});
+ vi.spyOn(listbox, 'getBoundingClientRect').mockReturnValue(
+ DOMRect.fromRect({x: 0, y: 140, width: 240, height: 80}),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(
+ DOMRect.fromRect({x: 0, y: 104, width: 240, height: 32}),
+ );
+ vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(360);
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah, bennettCole]);
+ // 360 px of viewport, the list starting 140 px down: 220 px of room.
+ expect(listbox.getAttribute('style') ?? '').toContain('220px');
+ });
+
+ it('announces nothing for a rejection after the popup closed and cancelled (FR9)', async () => {
+ const {source, latest} = createPendingSource({ben: [benOrtiz, benitaRuiz]});
+ const input = renderTypeahead(source);
+ await type(input, 'ben');
+ fireEvent.keyDown(input, {key: 'Escape'});
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+
+ await act(async () => {
+ latest().reject(new Error('aborted'));
+ });
+ await act(async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ });
+ expect(input).not.toHaveAttribute('aria-busy');
+ expect(liveRegion()?.textContent ?? '').not.toContain('results');
+ });
+
+ it('keeps no rows from the previous query when a cancelled search rejects before its first list (FR9)', async () => {
+ const {source, latest} = createPendingSource({b: [beaLin], bz: []});
+ const input = renderTypeahead(source);
+ await type(input, 'b');
+ await settle(latest(), [beaLin]);
+ await type(input, 'bz');
+ fireEvent.keyDown(input, {key: 'Escape'});
+ await act(async () => {
+ latest().reject(new Error('aborted'));
+ });
+ expect(optionLabels()).toEqual([]);
+ expect(input).not.toHaveAttribute('aria-busy');
+ });
+
+ it('releases the held popup height when the query ends (FR6)', async () => {
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+ await type(input, 'ben');
+ const listbox = screen.getByRole('listbox', {hidden: true});
+ vi.spyOn(listbox, 'getBoundingClientRect').mockReturnValue(
+ DOMRect.fromRect({x: 0, y: 20, width: 240, height: 80}),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockReturnValue(
+ DOMRect.fromRect({x: 0, y: 104, width: 240, height: 32}),
+ );
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah, bennettCole]);
+ expect(listbox.getAttribute('style') ?? '').toContain('80px');
+
+ await type(input, '');
+ expect(listbox.getAttribute('style') ?? '').not.toContain('80px');
+ });
+
+ it('does not scroll the list when a later list appends rows (FR6)', async () => {
+ const scrollIntoView = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: scrollIntoView,
+ });
+ try {
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const input = renderTypeahead(source);
+ await type(input, 'ben');
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ expect(scrollIntoView).toHaveBeenCalled();
+
+ scrollIntoView.mockClear();
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah, bennettCole]);
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ } finally {
+ delete (HTMLElement.prototype as unknown as {scrollIntoView?: unknown})
+ .scrollIntoView;
+ }
+ });
+
+ it('drops lists and rejections that arrive after unmount (FR4)', async () => {
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ const {unmount} = render(
+ <BaseTypeahead
+ aria-label="Assign to"
+ searchSource={source}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+ await type(screen.getByRole('combobox'), 'ben');
+ const search = latest();
+ unmount();
+ await act(async () => {
+ search.context?.update([benOrtiz]);
+ search.reject(new Error('aborted'));
+ });
+ await act(async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ });
+ expect(liveRegion()?.textContent ?? '').not.toContain('results');
+ });
+
+ it('drops a slow bootstrap once the person types, and stays busy for the query (slow bootstrap)', async () => {
+ let finishBootstrap: (items: SearchableItem[]) => void = () => {};
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ source.bootstrap = async () =>
+ new Promise<SearchableItem[]>(resolve => {
+ finishBootstrap = resolve;
+ });
+ render(
+ <BaseTypeahead
+ aria-label="Assign to"
+ searchSource={source}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ hasEntriesOnFocus
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ fireEvent.focus(input);
+ expect(input).toHaveAttribute('aria-busy', 'true');
+
+ await type(input, 'ben');
+ expect(optionLabels()).toEqual(['Ben Ortiz', 'Benita Ruiz']);
+
+ // The bootstrap lands late: it neither replaces nor reorders the rows.
+ await act(async () => {
+ finishBootstrap([beaLin, bennettCole]);
+ });
+ expect(optionLabels()).toEqual(['Ben Ortiz', 'Benita Ruiz']);
+ expect(input).toHaveAttribute('aria-busy', 'true');
+
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah]);
+ expect(optionLabels()).toEqual(['Ben Ortiz', 'Benita Ruiz', 'Ben Shah']);
+ expect(input).not.toHaveAttribute('aria-busy');
+ });
+
+ it('behaves the same under StrictMode (pure updaters, no effect-driven state)', async () => {
+ const onChange = vi.fn();
+ const {source, latest} = createPendingSource({
+ ben: [benOrtiz, benitaRuiz],
+ });
+ render(
+ <StrictMode>
+ <BaseTypeahead
+ aria-label="Assign to"
+ searchSource={source}
+ value={null}
+ onChange={onChange}
+ debounceMs={0}
+ />
+ </StrictMode>,
+ );
+ const input = screen.getByRole('combobox');
+ await type(input, 'ben');
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ await settle(latest(), [benOrtiz, benitaRuiz, benShah]);
+ expect(optionLabels()).toEqual(['Ben Ortiz', 'Benita Ruiz', 'Ben Shah']);
+ fireEvent.keyDown(input, {key: 'Enter'});
+ expect(onChange).toHaveBeenCalledWith(benitaRuiz);
+ });
+});
diff --git a/packages/core/src/Typeahead/BaseTypeahead.test.tsx b/packages/core/src/Typeahead/BaseTypeahead.test.tsx
index cfca32d6bf..a1179af5e7 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.test.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.test.tsx
@@ -376,7 +376,7 @@ describe('BaseTypeahead', () => {
screen.getByRole('option', {name: 'Updated result', hidden: true}),
).toBeInTheDocument();
});
- expect(updatedSearch).toHaveBeenCalledWith('re');
+ expect(updatedSearch).toHaveBeenCalledWith('re', expect.anything());
expect(
screen.queryByRole('option', {name: 'Result', hidden: true}),
).not.toBeInTheDocument();
@@ -435,7 +435,9 @@ describe('BaseTypeahead', () => {
expect(input).toHaveAttribute('aria-expanded', 'false');
fireEvent.change(input, {target: {value: '😀a'}});
- await waitFor(() => expect(search).toHaveBeenCalledExactlyOnceWith('😀a'));
+ await waitFor(() =>
+ expect(search).toHaveBeenCalledExactlyOnceWith('😀a', expect.anything()),
+ );
});
it('exposes a completed empty search as a disabled listbox option', async () => {
@@ -587,7 +589,7 @@ describe('BaseTypeahead', () => {
expect(input).not.toHaveAttribute('aria-busy');
await act(async () => vi.advanceTimersByTimeAsync(1));
}
- expect(search).toHaveBeenLastCalledWith('next');
+ expect(search).toHaveBeenLastCalledWith('next', expect.anything());
expect(input).toHaveAttribute('aria-busy', 'true');
expect(options.queryByText('No matching frameworks')).toBeNull();
expect(options.queryAllByRole('option', {hidden: true})).toHaveLength(
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index e7b2a77e7f..a3549449c4 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -5,7 +5,10 @@
/**
* @file BaseTypeahead.tsx
* @input Uses React, StyleX, usePopover, TypeaheadItem
- * @output Exports BaseTypeahead; empty feedback belongs to the current settled query
+ * @output Exports BaseTypeahead; empty feedback belongs to the current settled query;
+ * focus bootstraps a replaced search source; a source shows partial lists
+ * for a query through context.update, and later lists only append
+ * (spec:AST-092)
* @position Core implementation; used by Typeahead and Tokenizer
*
* Pure combobox engine: input, search, keyboard navigation, dropdown.
@@ -21,6 +24,7 @@ import React, {
useCallback,
useEffect,
useId,
+ useMemo,
useRef,
useState,
type ReactNode,
@@ -57,7 +61,7 @@ import {
} from '../utils';
import {warnOnce} from '../utils/devWarning';
import type {BaseProps} from '../BaseProps';
-import type {SearchableItem, SearchSource} from './types';
+import type {SearchContext, SearchableItem, SearchSource} from './types';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
@@ -296,10 +300,16 @@ const styles = stylex.create({
},
dropdown: {
boxSizing: 'border-box',
+ // Matches DROPDOWN_MAX_HEIGHT, which the room-below cap uses.
maxHeight: '300px',
overflowY: 'auto',
padding: spacingVars['--spacing-1'],
},
+ // Once a later list for the same query arrives, the popup holds its height
+ // above the field, or the room below it (spec:AST-092 FR6).
+ dropdownHeld: (height: number) => ({
+ maxHeight: `${height}px`,
+ }),
// The menu prefers the input's width and renders an explicit menuWidth at
// its size, both clamped to the layer runtime's viewport cap rather than to
// the room beside the input (spec:AST-059 FR2, FR7).
@@ -409,6 +419,42 @@ const itemSizeStyles = stylex.create({
// Helpers
// =============================================================================
+/** The result popup's maximum height in CSS pixels (`styles.dropdown`). */
+const DROPDOWN_MAX_HEIGHT = 300;
+
+/**
+ * Rows in the order the popup displays them: ungrouped source rows, then each
+ * group, then the trailing entries derived from the typed text (Tokenizer's
+ * create row), which always follow the rows (spec:AST-092 FR1).
+ */
+function displayOrder<T extends SearchableItem>(
+ list: T[],
+ queryEntryCount = 0,
+): T[] {
+ const end = list.length - queryEntryCount;
+ return [
+ ...groupItems(list.slice(0, end), {ungroupedFirst: true}).flatMap(
+ group => group.items,
+ ),
+ ...list.slice(end),
+ ];
+}
+
+/**
+ * Whether `next` starts with `shown`, item by item and in order, by `id`: the
+ * append-only rule a later list for the same query follows, applied to
+ * displayed order (spec:AST-092 FR2).
+ */
+function startsWithRows<T extends SearchableItem>(
+ next: ReadonlyArray<T>,
+ shown: ReadonlyArray<T>,
+): boolean {
+ return (
+ next.length >= shown.length &&
+ shown.every((item, index) => next[index].id === item.id)
+ );
+}
+
/**
* A query that has been typed but is still shorter than the caller's
* threshold. An empty query is not "below the minimum" — it is the
@@ -529,6 +575,65 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
}
}, [results]);
const [highlightedIndex, setHighlightedIndex] = useState(-1);
+ // Bumped whenever the rows are replaced rather than appended to, so the
+ // highlighted-row scroll runs for a new list but not when a later list for
+ // the same query appends rows below (spec:AST-092 FR6).
+ const [listKey, setListKey] = useState(0);
+ // How many trailing rows are entries derived from the typed text rather
+ // than source results; they display after every group.
+ const [queryEntryCount, setQueryEntryCount] = useState(0);
+ const replaceResults = useCallback((next: T[], entryCount = 0) => {
+ setResults(next);
+ setQueryEntryCount(entryCount);
+ setListKey(key => key + 1);
+ }, []);
+ // Highlight indexes count rows in displayed order (ungrouped first, then
+ // groups), which is how the popup renders them.
+ const displayedResults = useMemo(
+ () => displayOrder(results, queryEntryCount),
+ [results, queryEntryCount],
+ );
+ // The popup's listbox, measured when a later list arrives so the appended
+ // rows scroll instead of moving the shown rows or flipping the popup to
+ // the other side of the field (spec:AST-092 FR6).
+ const dropdownRef = useRef<HTMLDivElement>(null);
+ const [heldHeight, setHeldHeight] = useState<number | null>(null);
+ // The search generation the popup's close cancelled, so that search's
+ // rejection settles silently (spec:AST-092 FR9).
+ const closedGenRef = useRef(-1);
+ const isMountedRef = useRef(false);
+ const holdPopupInPlace = useCallback(() => {
+ const dropdown = dropdownRef.current;
+ const anchor = anchorRef?.current ?? fallbackAnchorRef.current;
+ if (dropdown == null || anchor == null) {
+ return;
+ }
+ const box = dropdown.getBoundingClientRect();
+ if (box.height <= 0) {
+ return;
+ }
+ if (box.bottom <= anchor.getBoundingClientRect().top + 1) {
+ // Above the field the popup grows upward, so any growth moves the
+ // shown rows: keep the height it has.
+ setHeldHeight(current => current ?? box.height);
+ return;
+ }
+ // Below the field, grow only within the room below, so the layer runtime
+ // never flips the popup above the field.
+ const layer = dropdown.closest<HTMLElement>('[popover]') ?? dropdown;
+ const layerBox = layer.getBoundingClientRect();
+ const gutter = parseFloat(getComputedStyle(layer).marginBlockEnd) || 0;
+ const viewportHeight = window.visualViewport?.height ?? window.innerHeight;
+ const room =
+ viewportHeight -
+ box.top -
+ Math.max(0, layerBox.bottom - box.bottom) -
+ gutter;
+ setHeldHeight(
+ current =>
+ current ?? Math.min(DROPDOWN_MAX_HEIGHT, Math.max(box.height, room)),
+ );
+ }, [anchorRef]);
const [isLoading, setIsLoading] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
// `isLoading` starts with the request, after debouncing. Until then the
@@ -670,6 +775,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
const handleLayerHide = useCallback(() => {
onOpenChange?.(false);
setHighlightedIndex(-1);
+ closedGenRef.current = searchGenRef.current;
+ setHeldHeight(null);
searchSource.cancel?.();
}, [onOpenChange, searchSource]);
@@ -724,7 +831,12 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
};
}, [popover, anchorRef]);
- // Perform search
+ // Perform search. A source may show lists for the query before it settles
+ // through `context.update`, and the value it returns is the final list
+ // (spec:AST-092). The first list shown for a query may replace the rows;
+ // every later one keeps the shown rows first, so nothing moves under the
+ // pointer or the highlight. Merging is the source's work: a later list that
+ // breaks that rule is shown as given, with a development warning.
const performSearch = useCallback(
async (searchQuery: string) => {
searchSource.cancel?.();
@@ -735,41 +847,142 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
setLastSearchedQuery(searchQuery);
setLoading(true);
setHasSearched(true);
+ let isSettled = false;
+ // The capped source rows last shown for this query, and the array handed
+ // to React for them. Null until the query's first non-empty list.
+ let shownRows: T[] | null = null;
+ let shownState: T[] | null = null;
+ let shownEntryCount = 0;
+
+ const showList = (list: T[], isFinal: boolean): T[] => {
+ const fetched = list.slice(0, maxMenuItems);
+ if (
+ shownRows != null &&
+ !startsWithRows(displayOrder(fetched), displayOrder(shownRows))
+ ) {
+ warnOnce(
+ 'base-typeahead:append-only',
+ 'BaseTypeahead',
+ 'A later list for the same query moved, removed, or inserted ' +
+ 'above rows already shown. After the first list for a query, ' +
+ 'a search source keeps the shown rows first and in order and ' +
+ 'adds new rows after them (spec:AST-092 FR2).',
+ );
+ }
+ // Entries derived from the typed text (Tokenizer's create row) wait
+ // for the query to settle: before then a pending server result may
+ // still show the value they would offer to create.
+ const entries = isFinal
+ ? (__queryEntries?.(searchQuery, fetched) ?? [])
+ : [];
+ const shown = [...fetched, ...entries];
+ resultsGenRef.current = gen;
+ const firstRow = shown.length > 0 ? 0 : -1;
+ const previous = shownState;
+ const previousEntryCount = shownEntryCount;
+ if (previous == null) {
+ setHeldHeight(null);
+ replaceResults(shown, entries.length);
+ setHighlightedIndex(firstRow);
+ } else {
+ holdPopupInPlace();
+ const previousOrder = displayOrder(previous, previousEntryCount);
+ const nextOrder = displayOrder(shown, entries.length);
+ if (startsWithRows(nextOrder, previousOrder)) {
+ setResults(shown);
+ setQueryEntryCount(entries.length);
+ } else {
+ replaceResults(shown, entries.length);
+ }
+ // Within one query only this function sets the rows, so the index
+ // the updater receives points into `previous`: the highlighted item
+ // keeps its highlight wherever it now sits (spec:AST-092 FR6).
+ setHighlightedIndex(index => {
+ const id = previousOrder[index]?.id;
+ const kept =
+ id == null ? -1 : nextOrder.findIndex(item => item.id === id);
+ return kept >= 0 ? kept : firstRow;
+ });
+ }
+ if (fetched.length > 0) {
+ shownRows = fetched;
+ shownState = shown;
+ shownEntryCount = entries.length;
+ }
+ return shown;
+ };
+
+ const announceCount = (count: number) => {
+ // Announce the outcome only for an active query (not the initial
+ // focus-open), so screen-reader users hear result counts / no-results.
+ // An empty result is announced from the rendered row instead, so the
+ // region speaks whatever the caller put there.
+ if (isMountedRef.current && searchQuery.length > 0 && count > 0) {
+ announce(t('@astryx.typeahead.resultCount', {count}));
+ }
+ };
+
+ const context: SearchContext<T> = {
+ update(items) {
+ // An empty list leaves the shown rows in place; a list for a query
+ // that is no longer current, or after it settled, is dropped.
+ if (isSettled || searchGenRef.current !== gen || items.length === 0) {
+ return;
+ }
+ showList(items, false);
+ showLayer();
+ },
+ };
+
try {
- const searchResults = await searchSource.search(searchQuery);
+ const searchResults = await searchSource.search(searchQuery, context);
if (searchGenRef.current !== gen) {
return;
}
- resultsGenRef.current = gen;
- const fetched = searchResults.slice(0, maxMenuItems);
- const shown = [
- ...fetched,
- ...(__queryEntries?.(searchQuery, fetched) ?? []),
- ];
- setResults(shown);
- setHighlightedIndex(shown.length > 0 ? 0 : -1);
+ isSettled = true;
+ const shown = showList(searchResults, true);
if (searchResults.length > 0 || searchQuery.length > 0) {
showLayer();
}
- // Announce the outcome only for an active query (not the initial
- // focus-open), so screen-reader users hear result counts / no-results.
if (searchQuery.length > 0) {
// This query's outcome is announced now (a count) or from the
// rendered row (an empty result); a busy start not yet announced
// would follow it, so it is dropped (spec:AST-086 FR8).
settleBusyAnnouncement();
}
- if (searchQuery.length > 0 && shown.length > 0) {
- announce(t('@astryx.typeahead.resultCount', {count: shown.length}));
- }
- // An empty result is announced from the rendered row instead, so the
- // region speaks whatever the caller put there.
+ announceCount(shown.length);
} catch {
if (searchGenRef.current !== gen) {
return;
}
- setResults([]);
- setHighlightedIndex(-1);
+ isSettled = true;
+ if (closedGenRef.current === gen) {
+ // The popup closed and cancelled this search, so its rejection is
+ // not a failed answer: announce nothing, and keep only this query's
+ // own rows (spec:AST-092 FR9).
+ if (shownRows != null) {
+ showList(shownRows, true);
+ } else {
+ replaceResults([]);
+ setHighlightedIndex(-1);
+ setHasSearched(false);
+ }
+ } else {
+ // A failure settles this query: its outcome is announced now (the
+ // kept rows' count) or from the rendered empty row, so a busy start
+ // not yet announced is dropped, as on success (spec:AST-086 FR8).
+ if (searchQuery.length > 0) {
+ settleBusyAnnouncement();
+ }
+ if (shownRows != null) {
+ // A failed server answer keeps the last non-empty list the source
+ // showed for this query, which settles it.
+ announceCount(showList(shownRows, true).length);
+ } else {
+ replaceResults([]);
+ setHighlightedIndex(-1);
+ }
+ }
} finally {
if (searchGenRef.current === gen) {
setLoading(false);
@@ -785,6 +998,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
setLoading,
settleBusyAnnouncement,
t,
+ holdPopupInPlace,
+ replaceResults,
],
);
@@ -803,13 +1018,14 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
) {
return;
}
- setResults(shown);
+ setHeldHeight(null);
+ replaceResults(shown);
setHighlightedIndex(nextHighlightedIndex);
if (bootstrapResults.length > 0) {
showLayer();
}
},
- [highlightedIndex, maxMenuItems, results.length, showLayer],
+ [highlightedIndex, maxMenuItems, results.length, showLayer, replaceResults],
);
// Perform bootstrap
@@ -820,7 +1036,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
bootstrapResult = searchSource.bootstrap();
} catch {
if (searchGenRef.current === gen) {
- setResults([]);
+ replaceResults([]);
setLoading(false);
}
return;
@@ -837,14 +1053,14 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
applyBootstrapResults(await bootstrapResult, gen);
} catch {
if (searchGenRef.current === gen) {
- setResults([]);
+ replaceResults([]);
}
} finally {
if (searchGenRef.current === gen) {
setLoading(false);
}
}
- }, [searchSource, applyBootstrapResults, setLoading]);
+ }, [searchSource, applyBootstrapResults, setLoading, replaceResults]);
// Handle query change
const handleQueryChange = useCallback(
@@ -870,7 +1086,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// the text itself. `hasSearched` stays false either way, so the menu
// never reports "no results" for a query nobody looked for.
const derived = __queryEntries?.(newQuery, []) ?? [];
- setResults(derived);
+ replaceResults(derived, derived.length);
+ setHeldHeight(null);
setHighlightedIndex(derived.length > 0 ? 0 : -1);
setHasSearched(false);
// Bumping the generation abandons any in-flight search, which means
@@ -903,6 +1120,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
}
},
[
+ replaceResults,
onChangeQuery,
hasEntriesOnFocus,
minQueryLength,
@@ -943,7 +1161,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
searchSource.cancel?.();
onChange(item);
setQuery('');
- setResults([]);
+ replaceResults([]);
+ setHeldHeight(null);
setHasSearched(false);
// Same reason as in handleQueryChange: the invalidated search will not
// clear this itself. Selecting a stale result while the next search is
@@ -952,7 +1171,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
popover.hide();
inputRef.current?.focus();
},
- [isDisabled, onChange, popover, searchSource, setLoading],
+ [isDisabled, onChange, popover, searchSource, setLoading, replaceResults],
);
// Shared by handleFocus and handleClick: bootstrap entries if none are
@@ -1142,7 +1361,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
case 'Enter':
e.preventDefault();
if (highlightedIndex >= 0 && highlightedIndex < results.length) {
- handleSelect(results[highlightedIndex]);
+ handleSelect(displayedResults[highlightedIndex]);
}
break;
case 'Escape':
@@ -1179,6 +1398,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
isDisabled,
popover,
results,
+ displayedResults,
highlightedIndex,
handleSelect,
hasEntriesOnFocus,
@@ -1190,28 +1410,53 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
],
);
- // Generate item ID for accessibility
+ // Option ids follow the item, not the row, so the active descendant keeps
+ // naming the same option while rows are added after it and a screen reader
+ // does not re-read it (spec:AST-092 FR7). A repeated id in one list falls
+ // back to its row so DOM ids stay unique.
+ const optionIds = useMemo(() => {
+ const seen = new Set<string>();
+ return displayedResults.map((item, index) => {
+ const byItem = `${listboxId}-option-${encodeURIComponent(item.id)}`;
+ const id = seen.has(byItem) ? `${byItem}-${index}` : byItem;
+ seen.add(byItem);
+ return id;
+ });
+ }, [displayedResults, listboxId]);
const getItemId = useCallback(
- (index: number) => `${listboxId}-option-${index}`,
- [listboxId],
+ (index: number) => optionIds[index] ?? `${listboxId}-option-${index}`,
+ [optionIds, listboxId],
);
// Keep the highlighted option visible during keyboard navigation; hover
// highlights never scroll (#6077). Both sides live in useHighlightedOptionScroll.
+ // The scroll follows the highlighted option's id and the list it belongs
+ // to, so rows a later list appends below do not scroll a list the person
+ // has scrolled (spec:AST-092 FR6, FR7).
+ const highlightedOptionId = optionIds[highlightedIndex];
+ const getHighlightedOptionId = useCallback(
+ (index: number) => highlightedOptionId ?? `${listboxId}-option-${index}`,
+ [highlightedOptionId, listboxId],
+ );
const highlightOnHover = useHighlightedOptionScroll({
isOpen: popover.isOpen,
highlightedIndex,
setHighlightedIndex,
- getOptionId: getItemId,
- itemCount: results.length,
+ getOptionId: getHighlightedOptionId,
+ itemCount: listKey,
});
const selectedKey =
value == null ? null : getKey(value.id, () => results.indexOf(value));
- // Unmount: clear the pending debounce and cancel in-flight work.
+ // Unmount: clear the pending debounce and cancel in-flight work, and stop
+ // announcing for a field that is gone (spec:AST-092 FR4). A flag rather than
+ // a generation bump, so StrictMode's simulated unmount keeps a search or
+ // bootstrap started during mount.
useEffect(() => {
+ isMountedRef.current = true;
return () => {
+ isMountedRef.current = false;
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
@@ -1302,12 +1547,16 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
)}
{popover.render(
<div
+ ref={dropdownRef}
id={listboxId}
role="listbox"
aria-label={t('@astryx.typeahead.searchResults')}
{...mergeProps(
themeProps('typeahead-dropdown'),
- stylex.props(styles.dropdown),
+ stylex.props(
+ styles.dropdown,
+ heldHeight != null && styles.dropdownHeld(heldHeight),
+ ),
)}>
{results.length === 0 && hasSearched && !isSearchPending ? (
<div
@@ -1364,7 +1613,10 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
);
};
- return groupItems(results, {ungroupedFirst: true}).map(group => {
+ const sourceEnd = results.length - queryEntryCount;
+ const grouped = groupItems(results.slice(0, sourceEnd), {
+ ungroupedFirst: true,
+ }).map(group => {
const options = group.items.map(renderOption);
if (group.heading == null) {
return options;
@@ -1383,6 +1635,12 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
</div>
);
});
+ // Entries derived from the typed text follow every group
+ // (spec:AST-092 FR1).
+ return [
+ ...grouped,
+ ...results.slice(sourceEnd).map(renderOption),
+ ];
})()
)}
</div>,
diff --git a/packages/core/src/Typeahead/Typeahead.doc.mjs b/packages/core/src/Typeahead/Typeahead.doc.mjs
index db3eba41d4..7931bcb2ab 100644
--- a/packages/core/src/Typeahead/Typeahead.doc.mjs
+++ b/packages/core/src/Typeahead/Typeahead.doc.mjs
@@ -119,7 +119,7 @@ export const docs = {
name: 'searchSource',
type: 'SearchSource<T>',
description:
- 'Data source providing search and bootstrap methods for populating the dropdown.',
+ 'Data source providing search and bootstrap methods. `search(query, context)` may call `context.update(items)` to show matches it already has before it returns; the value it returns is the final list, and every list after the first for a query keeps the shown rows first and adds new rows after them.',
required: true,
},
{
@@ -246,7 +246,7 @@ export const docs = {
name: 'debounceMs',
type: 'number',
description:
- 'Debounce delay in ms before triggering search. Set to 0 for synchronous sources.',
+ 'Debounce delay in ms before triggering search. Set to 0 for synchronous sources, and for a source that shows local matches through `context.update` and delays its own server request.',
default: '150',
},
{
@@ -279,12 +279,14 @@ export const docs = {
{
name: 'containerClassName',
type: 'string',
- description: 'Class name for the field container. Same targeting as `containerXstyle`.',
+ description:
+ 'Class name for the field container. Same targeting as `containerXstyle`.',
},
{
name: 'containerStyle',
type: 'CSSProperties',
- description: 'Inline styles for the field container. Same targeting as `containerXstyle`.',
+ description:
+ 'Inline styles for the field container. Same targeting as `containerXstyle`.',
},
{
name: 'controlXstyle',
@@ -332,6 +334,11 @@ export const docs = {
description:
'Add a search delay for remote data sources to avoid excessive network requests.',
},
+ {
+ guidance: true,
+ description:
+ 'For a remote source, show the matches the page already has at once: call `context.update(local)` in `search`, pass `debounceMs={0}`, delay the server request in the source, and return the server answer with the shown rows first.',
+ },
{
guidance: true,
description:
@@ -381,6 +388,11 @@ export const docsZh = {
description:
'Add a search delay for remote data sources to avoid excessive network requests.',
},
+ {
+ guidance: true,
+ description:
+ 'For a remote source, show the matches the page already has at once: call `context.update(local)` in `search`, pass `debounceMs={0}`, delay the server request in the source, and return the server answer with the shown rows first.',
+ },
{
guidance: false,
description:
@@ -427,6 +439,11 @@ export const docsDense = {
description:
'Add a search delay for remote data sources to avoid excessive network requests.',
},
+ {
+ guidance: true,
+ description:
+ 'For a remote source, show the matches the page already has at once: call `context.update(local)` in `search`, pass `debounceMs={0}`, delay the server request in the source, and return the server answer with the shown rows first.',
+ },
{
guidance: true,
description:
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index 918bdebc55..fb31fcbf5c 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -1453,7 +1453,7 @@ describe('BaseTypeahead minQueryLength', () => {
await waitFor(() => {
expect(input).toHaveAttribute('aria-expanded', 'true');
});
- expect(search).toHaveBeenCalledExactlyOnceWith('App');
+ expect(search).toHaveBeenCalledExactlyOnceWith('App', expect.anything());
});
it('closes the menu again when the query falls back below the threshold', async () => {
@@ -1531,7 +1531,7 @@ describe('BaseTypeahead minQueryLength', () => {
await waitFor(() => {
expect(input).toHaveAttribute('aria-expanded', 'true');
});
- expect(search).toHaveBeenCalledExactlyOnceWith('A');
+ expect(search).toHaveBeenCalledExactlyOnceWith('A', expect.anything());
});
it('stops reporting "Loading" when the query falls below the threshold mid-search', async () => {
@@ -1669,7 +1669,7 @@ describe('BaseTypeahead hasSearched reset', () => {
// Type a query that starts an asynchronous search
fireEvent.change(input, {target: {value: 'abc'}});
- expect(initialSource.search).toHaveBeenCalledWith('abc');
+ expect(initialSource.search).toHaveBeenCalledWith('abc', expect.anything());
// Replace the search source while the search is still pending
rerender(
diff --git a/packages/core/src/Typeahead/TypeaheadItem.doc.mjs b/packages/core/src/Typeahead/TypeaheadItem.doc.mjs
index a1be47e706..c773f4d23e 100644
--- a/packages/core/src/Typeahead/TypeaheadItem.doc.mjs
+++ b/packages/core/src/Typeahead/TypeaheadItem.doc.mjs
@@ -6,7 +6,8 @@ export const docs = {
name: 'TypeaheadItem',
subComponentOf: 'Typeahead',
displayName: 'Typeahead Item',
- description: 'Default dropdown item renderer for typeahead results. Shows label with optional icon, description, and avatar. Exported for use in custom renderItem implementations.',
+ description:
+ 'Default dropdown item renderer for typeahead results. Shows label with optional icon, description, and avatar. Exported for use in custom renderItem implementations.',
props: [
{
name: 'item',
@@ -50,7 +51,8 @@ export const docs = {
export const docsZh = {
name: 'TypeaheadItem',
displayName: 'Typeahead Item',
- description: '预输入结果的默认下拉项渲染器。显示标签以及可选的图标、描述和头像。导出供自定义 renderItem 实现使用。',
+ description:
+ '预输入结果的默认下拉项渲染器。显示标签以及可选的图标、描述和头像。导出供自定义 renderItem 实现使用。',
props: [
{
name: 'item',
@@ -85,7 +87,8 @@ export const docsZh = {
export const docsDense = {
name: 'TypeaheadItem',
displayName: 'Typeahead Item',
- description: 'Default dropdown item renderer. Label w/ optional icon, description, avatar. Exported for custom renderItem.',
+ description:
+ 'Default dropdown item renderer. Label w/ optional icon, description, avatar. Exported for custom renderItem.',
propDescriptions: {
item: 'Search result item to render.',
icon: 'Icon/avatar before label.',
diff --git a/packages/core/src/Typeahead/index.ts b/packages/core/src/Typeahead/index.ts
index 95ad3eadc5..4301384733 100644
--- a/packages/core/src/Typeahead/index.ts
+++ b/packages/core/src/Typeahead/index.ts
@@ -12,7 +12,7 @@
*/
// Shared types
-export type {SearchableItem, SearchSource} from './types';
+export type {SearchableItem, SearchContext, SearchSource} from './types';
// Search source utilities
export {createStaticSource} from './createStaticSource';
diff --git a/packages/core/src/Typeahead/types.ts b/packages/core/src/Typeahead/types.ts
index e629062db3..ff68284fe2 100644
--- a/packages/core/src/Typeahead/types.ts
+++ b/packages/core/src/Typeahead/types.ts
@@ -60,6 +60,25 @@ export interface SearchableItem<TAuxData = unknown> {
auxiliaryData?: TAuxData;
}
+/**
+ * Per-call context a typeahead passes as the second argument of
+ * `SearchSource.search` (`spec:AST-092`).
+ */
+export interface SearchContext<T extends SearchableItem = SearchableItem> {
+ /**
+ * Show a list for this query before `search()` settles, such as matches the
+ * page already holds while the server is still answering.
+ *
+ * Every list is the source's complete answer at that moment. The first list
+ * shown for a query may replace the rows; every later list for the same
+ * query, including the value `search()` returns, keeps the rows already
+ * shown first and in order and adds new rows only after them. An empty list
+ * leaves the shown rows in place. Calls for a query that is no longer
+ * current, or after `search()` settles, are ignored.
+ */
+ update(items: T[]): void;
+}
+
/**
* Search source interface for providing items to typeahead components.
* Supports both synchronous and asynchronous search.
@@ -93,13 +112,18 @@ export interface SearchableItem<TAuxData = unknown> {
*/
export interface SearchSource<T extends SearchableItem = SearchableItem> {
/**
- * Called on query change. Returns matching items.
- * Can be synchronous or asynchronous.
+ * Called on query change. Returns matching items: the final, complete list
+ * for the query. Can be synchronous or asynchronous.
+ *
+ * A typeahead that can show partial lists passes `context`; call
+ * `context.update(items)` to show a list before returning, for example local
+ * matches first and the server's answer appended after them. Callers that
+ * cannot show partial lists omit `context` and show only the return value.
*
* For expensive operations (API calls, large datasets), consider caching
* results internally to avoid redundant work on repeated queries.
*/
- search(query: string): Promise<T[]> | T[];
+ search(query: string, context?: SearchContext<T>): Promise<T[]> | T[];
/**
* Called on init/focus. Returns initial/default items.