-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat(react-search): add SearchBox typeahead/autocomplete Storybook story and design spec #35875
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ValentinaKozlova
merged 6 commits into
master
from
copilot/add-searchbox-typeahead-feature
Mar 27, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d4ef7e5
Initial plan
Copilot 21ac6e0
feat(react-search): add SearchBox typeahead story and TYPEAHEAD-SEARC…
Copilot 9a9ef56
fix build
ValentinaKozlova 454faf5
PR fix
ValentinaKozlova 039258d
PR fix
ValentinaKozlova 851a280
removed role combobox
ValentinaKozlova File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
77 changes: 77 additions & 0 deletions
77
packages/react-components/react-search/library/docs/TYPEAHEAD-SEARCHBOX-SPEC.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| # Typeahead SearchBox — Design Spec | ||
|
|
||
| ## Background | ||
|
|
||
| The [FluentUI design docs for SearchBox](https://fluent2.microsoft.design/components/web/react/core/searchbox/usage#content) describe a pattern for displaying search results beneath the input as the user types. The current `SearchBox` component has no built-in typeahead; this spec documents the recommended composable approach. | ||
|
|
||
| ## Prior Art | ||
|
|
||
| - [OpenUI ComboBox research](https://open-ui.org/components/combobox.research/) — combobox suits a known finite option set, but is less practical for dynamically fetched results of unknown size. | ||
| - [FluentUI design docs for SearchBox](https://fluent2.microsoft.design/components/web/react/core/searchbox/usage#content) — guidance on sorting results; rendering is left to the developer. | ||
| - [Azure AI Search — Autocomplete](https://learn.microsoft.com/en-us/azure/search/search-add-autocomplete-suggestions) | ||
| - [FluentUI Blazor Search — Autocomplete](https://www.fluentui-blazor.net/Search#documentation) | ||
| - [Typeahead.js](https://typeahead.js.org/examples/) — mostly pre-fetched options rather than dynamic fetching. | ||
|
|
||
| ## Approach | ||
|
|
||
| Rather than a sealed `TypeaheadSearchbox` component, this feature is delivered as a **composable pattern**: a Storybook story (and best-practices guidance) showing how to pair `SearchBox` with a results dropdown. This lets consumers plug in their own data-fetching layer (TanStack Query, SWR, custom hooks, etc.) and fully control result rendering. | ||
|
|
||
| ### Sample Code | ||
|
|
||
| ```tsx | ||
| <div style={{ position: 'relative' }}> | ||
| <SearchBox | ||
| aria-autocomplete="list" | ||
| aria-controls={listboxId} | ||
| aria-expanded={isOpen} | ||
| aria-activedescendant={activeOptionId} | ||
| value={query} | ||
| onChange={handleChange} | ||
| onKeyDown={handleKeyDown} | ||
| /> | ||
| <ul id={listboxId} role="listbox"> | ||
| {results.map(item => ( | ||
| <li key={item.id} role="option" aria-selected={item.id === selectedId}> | ||
| {item.label} | ||
| </li> | ||
| ))} | ||
| </ul> | ||
| </div> | ||
| ``` | ||
|
|
||
| See the **Typeahead** story for a complete, runnable example with debouncing, loading state, keyboard navigation, and ARIA live announcements. | ||
|
|
||
| ## Behavior | ||
|
|
||
| ### Component States | ||
|
|
||
| | State | Description | | ||
| | ------------------ | ----------------------------------------------------------------------------------------------------- | | ||
| | **Rest** | No text entered; dropdown hidden. | | ||
| | **Typing** | User is typing; after debounce, a search request fires and the dropdown opens with a loading spinner. | | ||
| | **Results loaded** | Results are displayed in the dropdown as a listbox. | | ||
| | **No results** | Dropdown shows a "No results found" message. | | ||
| | **Item selected** | Selected label fills the input; dropdown closes. | | ||
|
|
||
| ### Interaction | ||
|
|
||
| - **Keyboard** | ||
| - `ArrowDown` / `ArrowUp` — traverse the result list. | ||
| - `Enter` — select the focused result (equivalent to click). | ||
| - `Escape` — close the dropdown without selecting. | ||
| - **Pointer / Touch** — click or tap a result to select it. | ||
| - **Blur** — dropdown closes when focus leaves both the input and the listbox. | ||
|
|
||
| ## Accessibility | ||
|
|
||
| The pattern follows the [ARIA combobox pattern](https://www.w3.org/WAI/ARIA/apd/patterns/combobox/): | ||
|
|
||
| | Element | Attributes | | ||
| | ------------------------ | ------------------------------------------------------------------------------------- | | ||
| | Input (`SearchBox`) | `aria-autocomplete="list"`, `aria-controls`, `aria-expanded`, `aria-activedescendant` | | ||
| | Results container (`ul`) | `role="listbox"`, `aria-label="Search results"` | | ||
| | Each result (`li`) | `role="option"`, `aria-selected` | | ||
|
|
||
| - A **live region** (`aria-live="polite"`) announces loading state, result count, and "no results" to screen readers. | ||
| - Focus remains on the input at all times; `aria-activedescendant` communicates the visually focused option. | ||
| - The dismiss button and `Escape` key close the dropdown predictably. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
301 changes: 301 additions & 0 deletions
301
packages/react-components/react-search/stories/src/SearchBox/SearchBoxTypeahead.stories.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,301 @@ | ||
| import * as React from 'react'; | ||
| import type { JSXElement } from '@fluentui/react-components'; | ||
| import { | ||
| AriaLiveAnnouncer, | ||
| makeStyles, | ||
| mergeClasses, | ||
| SearchBox, | ||
| Spinner, | ||
| tokens, | ||
| useId, | ||
| useTypingAnnounce, | ||
| } from '@fluentui/react-components'; | ||
| import type { SearchBoxChangeEvent } from '@fluentui/react-components'; | ||
| import type { InputOnChangeData } from '@fluentui/react-components'; | ||
|
|
||
| const DEBOUNCE_MS = 300; | ||
|
|
||
| const useStyles = makeStyles({ | ||
| root: { | ||
| position: 'relative', | ||
| maxWidth: '400px', | ||
| }, | ||
| listbox: { | ||
| backgroundColor: tokens.colorNeutralBackground1, | ||
| border: `1px solid ${tokens.colorNeutralStroke1}`, | ||
| borderRadius: tokens.borderRadiusMedium, | ||
| boxShadow: tokens.shadow16, | ||
| boxSizing: 'border-box', | ||
| listStyleType: 'none', | ||
| margin: 0, | ||
| padding: `${tokens.spacingVerticalXS} 0`, | ||
| position: 'absolute', | ||
| width: '100%', | ||
| zIndex: 1000, | ||
| }, | ||
| listboxHidden: { | ||
| display: 'none', | ||
| }, | ||
| option: { | ||
| alignItems: 'center', | ||
| cursor: 'pointer', | ||
| display: 'flex', | ||
| gap: tokens.spacingHorizontalS, | ||
| padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`, | ||
| ':hover': { | ||
| backgroundColor: tokens.colorNeutralBackground1Hover, | ||
| }, | ||
| }, | ||
| optionFocused: { | ||
| backgroundColor: tokens.colorNeutralBackground1Selected, | ||
| outline: 'none', | ||
| }, | ||
| spinnerWrapper: { | ||
| alignItems: 'center', | ||
| display: 'flex', | ||
| gap: tokens.spacingHorizontalS, | ||
| padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`, | ||
| color: tokens.colorNeutralForeground3, | ||
| }, | ||
| noResults: { | ||
| color: tokens.colorNeutralForeground3, | ||
| padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`, | ||
| }, | ||
| }); | ||
|
|
||
| type SearchResult = { | ||
| id: string; | ||
| label: string; | ||
| }; | ||
|
|
||
| // Simulated async search function | ||
| const fetchResults = (query: string): Promise<SearchResult[]> => { | ||
| const allResults: SearchResult[] = [ | ||
| { id: '1', label: 'Accessibility in Fluent UI' }, | ||
| { id: '2', label: 'Button component' }, | ||
| { id: '3', label: 'Combobox with filtering' }, | ||
| { id: '4', label: 'Dark mode theming' }, | ||
| { id: '5', label: 'Fluent UI v9 migration guide' }, | ||
| { id: '6', label: 'Form validation patterns' }, | ||
| { id: '7', label: 'Grid layout examples' }, | ||
| { id: '8', label: 'High contrast support' }, | ||
| { id: '9', label: 'Icon library overview' }, | ||
| { id: '10', label: 'Jest testing utilities' }, | ||
| ]; | ||
|
|
||
| return new Promise(resolve => { | ||
| setTimeout(() => { | ||
| resolve(allResults.filter(r => r.label.toLowerCase().includes(query.toLowerCase()))); | ||
| }, 500); | ||
| }); | ||
| }; | ||
|
|
||
| export const Typeahead = (): JSXElement => { | ||
| const styles = useStyles(); | ||
|
|
||
| const [query, setQuery] = React.useState(''); | ||
| const [results, setResults] = React.useState<SearchResult[]>([]); | ||
| const [isLoading, setIsLoading] = React.useState(false); | ||
| const [isOpen, setIsOpen] = React.useState(false); | ||
| const [focusedIndex, setFocusedIndex] = React.useState(-1); | ||
| const [hideActiveDescendant, setHideActiveDescendant] = React.useState(false); | ||
| const [selectedId, setSelectedId] = React.useState<string | null>(null); | ||
|
|
||
| const listboxId = useId(); | ||
| const announceId = useId('typeahead'); | ||
| const { typingAnnounce, inputRef } = useTypingAnnounce<HTMLInputElement>(); | ||
| const optionRefs = React.useRef<(HTMLLIElement | null)[]>([]); | ||
| const cancelRef = React.useRef<(() => void) | null>(null); | ||
|
|
||
| // Debounced search when query changes | ||
| React.useEffect(() => { | ||
| if (!query) { | ||
| setResults([]); | ||
| setIsOpen(false); | ||
| setIsLoading(false); | ||
| return; | ||
| } | ||
|
|
||
| setIsLoading(true); | ||
| setIsOpen(true); | ||
| setFocusedIndex(-1); | ||
|
|
||
| const debounceTimer = setTimeout(() => { | ||
| let cancelled = false; | ||
| fetchResults(query).then(data => { | ||
| if (!cancelled) { | ||
| setResults(data); | ||
| optionRefs.current = new Array(data.length).fill(null); | ||
| setIsLoading(false); | ||
| } | ||
| }); | ||
|
|
||
| // Store cancel in the ref so the cleanup can access it | ||
| cancelRef.current = () => { | ||
| cancelled = true; | ||
| }; | ||
| }, DEBOUNCE_MS); | ||
|
|
||
| return () => { | ||
| clearTimeout(debounceTimer); | ||
| cancelRef.current?.(); | ||
| cancelRef.current = null; | ||
| }; | ||
| }, [query]); | ||
|
|
||
| React.useEffect(() => { | ||
| if (!isOpen || isLoading) { | ||
| return; | ||
| } | ||
|
|
||
| if (results.length > 0) { | ||
| typingAnnounce(`${results.length} result${results.length !== 1 ? 's' : ''} available`, { | ||
| batchId: announceId, | ||
| }); | ||
| } else if (query.length > 0) { | ||
| typingAnnounce('No results found', { batchId: announceId }); | ||
| } | ||
| }, [isLoading, isOpen, results.length, query.length, typingAnnounce, announceId]); | ||
|
|
||
| // Keep focused option scrolled into view | ||
| React.useEffect(() => { | ||
| if (focusedIndex >= 0) { | ||
| optionRefs.current[focusedIndex]?.scrollIntoView({ block: 'nearest' }); | ||
| } | ||
| }, [focusedIndex]); | ||
|
|
||
| const handleChange = (_: SearchBoxChangeEvent, data: InputOnChangeData) => { | ||
| setQuery(data.value); | ||
| setSelectedId(null); | ||
|
|
||
| if (!data.value) { | ||
| return; | ||
| } | ||
|
|
||
| // useTypingAnnounce waits until the user pauses typing before announcing, | ||
| // preventing interference with screen reader keyboard echo. | ||
| typingAnnounce('Searching…', { batchId: announceId }); | ||
| }; | ||
|
|
||
| const handleSelect = (result: SearchResult) => { | ||
| setSelectedId(result.id); | ||
| setQuery(result.label); | ||
| setIsOpen(false); | ||
| setFocusedIndex(-1); | ||
| inputRef.current?.focus(); | ||
| }; | ||
|
|
||
| const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { | ||
| if (!isOpen) { | ||
| return; | ||
| } | ||
|
|
||
| if (e.key === 'ArrowDown') { | ||
| e.preventDefault(); | ||
| setHideActiveDescendant(false); | ||
| setFocusedIndex(prev => Math.min(prev + 1, results.length - 1)); | ||
| } else if (e.key === 'ArrowUp') { | ||
| e.preventDefault(); | ||
| setHideActiveDescendant(false); | ||
| setFocusedIndex(prev => Math.max(prev - 1, -1)); | ||
| } else if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { | ||
| setHideActiveDescendant(true); | ||
| } else if (e.key === 'Enter' && focusedIndex >= 0) { | ||
| e.preventDefault(); | ||
| handleSelect(results[focusedIndex]); | ||
| } else if (e.key === 'Escape') { | ||
| setIsOpen(false); | ||
| setFocusedIndex(-1); | ||
| setHideActiveDescendant(false); | ||
| } | ||
ValentinaKozlova marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }; | ||
|
|
||
| const handleBlur = (e: React.FocusEvent<HTMLSpanElement>) => { | ||
| // Close if focus leaves both the input and the listbox | ||
| const relatedTarget = e.relatedTarget as Node | null; | ||
| const listboxEl = document.getElementById(listboxId); | ||
| if (!e.currentTarget.contains(relatedTarget) && !listboxEl?.contains(relatedTarget)) { | ||
| setIsOpen(false); | ||
| setFocusedIndex(-1); | ||
| } | ||
| }; | ||
|
|
||
| const showDropdown = isOpen && (isLoading || results.length > 0); | ||
| const noResults = isOpen && !isLoading && query.length > 0 && results.length === 0; | ||
| const activedescendant = | ||
| focusedIndex >= 0 && !hideActiveDescendant ? `${listboxId}-option-${focusedIndex}` : undefined; | ||
|
|
||
| return ( | ||
| <AriaLiveAnnouncer> | ||
| <div className={styles.root}> | ||
| <SearchBox | ||
| ref={inputRef} | ||
| aria-autocomplete="list" | ||
| aria-controls={listboxId} | ||
| aria-expanded={showDropdown || noResults} | ||
| aria-activedescendant={activedescendant} | ||
| placeholder="Search..." | ||
| value={query} | ||
| onChange={handleChange} | ||
| onKeyDown={handleKeyDown} | ||
| root={{ onBlur: handleBlur }} | ||
| /> | ||
|
|
||
| <ul | ||
| id={listboxId} | ||
| role="listbox" | ||
| aria-label="Search results" | ||
| className={mergeClasses(styles.listbox, !showDropdown && !noResults && styles.listboxHidden)} | ||
| > | ||
| {isLoading ? ( | ||
| <li className={styles.spinnerWrapper}> | ||
| <Spinner size="tiny" label="Loading results…" labelPosition="after" /> | ||
| </li> | ||
| ) : results.length > 0 ? ( | ||
| results.map((result, index) => ( | ||
| <li | ||
| key={result.id} | ||
| id={`${listboxId}-option-${index}`} | ||
| ref={el => { | ||
| optionRefs.current[index] = el; | ||
| }} | ||
| role="option" | ||
| aria-selected={selectedId === result.id} | ||
| className={mergeClasses(styles.option, focusedIndex === index && styles.optionFocused)} | ||
| onMouseDown={e => { | ||
| // Prevent input blur before click registers | ||
| e.preventDefault(); | ||
| }} | ||
| onClick={() => handleSelect(result)} | ||
| > | ||
| {result.label} | ||
| </li> | ||
| )) | ||
| ) : ( | ||
| <li className={styles.noResults}>No results found</li> | ||
| )} | ||
| </ul> | ||
| </div> | ||
| </AriaLiveAnnouncer> | ||
| ); | ||
| }; | ||
|
|
||
| Typeahead.parameters = { | ||
| docs: { | ||
| description: { | ||
| story: ` | ||
| A \`SearchBox\` can be combined with a results dropdown to create a typeahead (autocomplete) pattern. | ||
| This example demonstrates: | ||
|
|
||
| - **Debounced async search**: results are fetched asynchronously after a ${DEBOUNCE_MS}ms debounce to avoid firing on every keystroke. In-flight requests are cancelled when the query changes. | ||
| - **Loading state**: a \`Spinner\` is shown inside the dropdown while results are loading. | ||
| - **Keyboard navigation**: use \`ArrowDown\`/\`ArrowUp\` to move through results, \`Enter\` to select, and \`Escape\` to close the dropdown. | ||
| - **Accessibility**: the input uses \`role="combobox"\`, \`aria-autocomplete="list"\`, \`aria-expanded\`, \`aria-controls\`, and \`aria-activedescendant\` to communicate state to assistive technologies. The \`useTypingAnnounce\` hook announces loading state, result count, and "no results" to screen readers — waiting until the user pauses typing so announcements don't interfere with keyboard echo. | ||
|
|
||
| > **Note**: This pattern is intentionally left as a composable building block rather than a single sealed component, | ||
| > allowing you to integrate your own data-fetching solution (e.g. TanStack Query, SWR, or a custom hook) and | ||
| > to customise the appearance of each result item. | ||
| `.trim(), | ||
| }, | ||
| }, | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.