Autocomplete
An input that suggests options as you type.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\Autocomplete;
use function Phem\Ui\{ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxLabel, ComboboxList, ComboboxPopup};
const TAGS = [
't1' => 'feature',
't2' => 'fix',
't3' => 'bug',
't4' => 'docs',
't5' => 'internal',
't6' => 'mobile',
'c-accordion' => 'component: accordion',
'c-alert-dialog' => 'component: alert dialog',
'c-autocomplete' => 'component: autocomplete',
'c-avatar' => 'component: avatar',
'c-checkbox' => 'component: checkbox',
'c-checkbox-group' => 'component: checkbox group',
'c-collapsible' => 'component: collapsible',
'c-combobox' => 'component: combobox',
'c-context-menu' => 'component: context menu',
'c-dialog' => 'component: dialog',
'c-field' => 'component: field',
'c-fieldset' => 'component: fieldset',
'c-filterable-menu' => 'component: filterable menu',
'c-form' => 'component: form',
'c-input' => 'component: input',
'c-menu' => 'component: menu',
'c-menubar' => 'component: menubar',
'c-meter' => 'component: meter',
'c-navigation-menu' => 'component: navigation menu',
'c-number-field' => 'component: number field',
'c-popover' => 'component: popover',
'c-preview-card' => 'component: preview card',
'c-progress' => 'component: progress',
'c-radio' => 'component: radio',
'c-scroll-area' => 'component: scroll area',
'c-select' => 'component: select',
'c-separator' => 'component: separator',
'c-slider' => 'component: slider',
'c-switch' => 'component: switch',
'c-tabs' => 'component: tabs',
'c-toast' => 'component: toast',
'c-toggle' => 'component: toggle',
'c-toggle-group' => 'component: toggle group',
'c-toolbar' => 'component: toolbar',
'c-tooltip' => 'component: tooltip',
];
#[Component]
function AutocompleteHeroDemo(): Node
{
$tags = TAGS;
return (
<Autocomplete id="tags" filter="contains">
<ComboboxLabel>Search tags</ComboboxLabel>
<ComboboxInput placeholder="e.g. feature" className="placeholder:opacity-100 placeholder:[-webkit-text-fill-color:var(--color-muted-foreground)]" />
<ComboboxPopup>
<ComboboxEmpty>No tags found.</ComboboxEmpty>
<ComboboxList>
{% for id, tag in tags %}
<ComboboxItem key={{ id }} value={{ id }} className="flex">{{ tag }}</ComboboxItem>
{% endfor %}
</ComboboxList>
</ComboboxPopup>
</Autocomplete>
);
}
Examples#
Async search#
Load items asynchronously while typing and render custom status content. The onChange handler of ComboboxInput calls a repository service, and the state keeps the results. ComboboxStatus shows the texts of the states of the search: pending with a spinner while it runs, error when the handler throws, empty when nothing matches, and results when items show. The label of an item is the text that a choice writes in the input. Type "will_error" to see a failure.
<?phem
use Phem\Attribute\{Component, State};
use Phem\{Event, Node};
use Phem\Ui\Autocomplete;
use function Phem\Ui\{ComboboxInput, ComboboxItem, ComboboxLabel, ComboboxList, ComboboxPopup, ComboboxStatus};
#[Component]
final class AutocompleteAsyncDemo
{
#[State] public string $query = '';
/** @var list<array{id: string, title: string, year: int}> */
#[State] public array $movies = [];
public function __construct(private readonly MovieRepository $repository)
{
}
public function search(Event $e): void
{
$this->query = trim((string) $e->value);
$this->movies = $this->repository->search($this->query);
}
public function render(): Node
{
$count = \count($this->movies);
$found = $count.' result'.(1 === $count ? '' : 's').' found';
return (
<Autocomplete id="movies">
<ComboboxLabel>Search movies by name or year</ComboboxLabel>
<ComboboxInput onChange={{ search }} placeholder="e.g. Pulp Fiction or 1994" />
<ComboboxPopup className="py-1">
<ComboboxStatus
pending="Searching…"
empty={{ 'Movie or year "' ~ query ~ '" does not exist in the Top 100 IMDb movies' }}
error="Failed to fetch movies. Please try again."
results={{ found }}
className="pr-8"
/>
<ComboboxList className="py-0">
{% for movie in movies %}
<ComboboxItem key={{ movie.id }} value={{ movie.id }} label={{ movie.title }} className="flex">
<span className="flex w-full flex-col gap-1">
<span className="leading-5 font-bold">{{ movie.title }}</span>
<span className="text-sm leading-4 text-neutral-500 group-data-highlighted:text-neutral-300 dark:text-neutral-400 dark:group-data-highlighted:text-neutral-500">{{ movie.year }}</span>
</span>
</ComboboxItem>
{% endfor %}
</ComboboxList>
</ComboboxPopup>
</Autocomplete>
);
}
}
Inline autocomplete#
Autofill the input with the highlighted item while navigating with arrow keys using the mode prop. Accepts aria-autocomplete values list, both, inline, or none.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\Autocomplete;
use function Phem\Ui\{ComboboxInput, ComboboxItem, ComboboxLabel, ComboboxList, ComboboxPopup};
const TAGS = [
't1' => 'feature',
't2' => 'fix',
't3' => 'bug',
't4' => 'docs',
't5' => 'internal',
't6' => 'mobile',
'c-accordion' => 'component: accordion',
'c-alert-dialog' => 'component: alert dialog',
'c-autocomplete' => 'component: autocomplete',
'c-avatar' => 'component: avatar',
'c-checkbox' => 'component: checkbox',
'c-checkbox-group' => 'component: checkbox group',
'c-collapsible' => 'component: collapsible',
'c-combobox' => 'component: combobox',
'c-context-menu' => 'component: context menu',
'c-dialog' => 'component: dialog',
'c-field' => 'component: field',
'c-fieldset' => 'component: fieldset',
'c-filterable-menu' => 'component: filterable menu',
'c-form' => 'component: form',
'c-input' => 'component: input',
'c-menu' => 'component: menu',
'c-menubar' => 'component: menubar',
'c-meter' => 'component: meter',
'c-navigation-menu' => 'component: navigation menu',
'c-number-field' => 'component: number field',
'c-popover' => 'component: popover',
'c-preview-card' => 'component: preview card',
'c-progress' => 'component: progress',
'c-radio' => 'component: radio',
'c-scroll-area' => 'component: scroll area',
'c-select' => 'component: select',
'c-separator' => 'component: separator',
'c-slider' => 'component: slider',
'c-switch' => 'component: switch',
'c-tabs' => 'component: tabs',
'c-toast' => 'component: toast',
'c-toggle' => 'component: toggle',
'c-toggle-group' => 'component: toggle group',
'c-toolbar' => 'component: toolbar',
'c-tooltip' => 'component: tooltip',
];
#[Component]
function AutocompleteInlineDemo(): Node
{
$tags = TAGS;
return (
<Autocomplete id="inline-tags" filter="contains" mode="both">
<ComboboxLabel>Search tags</ComboboxLabel>
<ComboboxInput placeholder="e.g. feature" />
<ComboboxPopup className="data-empty:hidden">
<ComboboxList>
{% for id, tag in tags %}
<ComboboxItem key={{ id }} value={{ id }} className="flex">{{ tag }}</ComboboxItem>
{% endfor %}
</ComboboxList>
</ComboboxPopup>
</Autocomplete>
);
}
Grouped#
Organize related options with ComboboxGroup and ComboboxGroupLabel to add section headings inside the popup.
Render one group for each section of your data, with the heading text in its label and its items in it. A group with no matching item is hidden.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\Autocomplete;
use function Phem\Ui\{ComboboxEmpty, ComboboxGroup, ComboboxGroupLabel, ComboboxInput, ComboboxItem, ComboboxLabel, ComboboxList, ComboboxPopup};
const TAGS = [
't1' => 'feature',
't2' => 'fix',
't3' => 'bug',
't4' => 'docs',
't5' => 'internal',
't6' => 'mobile',
'c-accordion' => 'component: accordion',
'c-alert-dialog' => 'component: alert dialog',
'c-autocomplete' => 'component: autocomplete',
'c-avatar' => 'component: avatar',
'c-checkbox' => 'component: checkbox',
'c-checkbox-group' => 'component: checkbox group',
'c-collapsible' => 'component: collapsible',
'c-combobox' => 'component: combobox',
'c-context-menu' => 'component: context menu',
'c-dialog' => 'component: dialog',
'c-field' => 'component: field',
'c-fieldset' => 'component: fieldset',
'c-filterable-menu' => 'component: filterable menu',
'c-form' => 'component: form',
'c-input' => 'component: input',
'c-menu' => 'component: menu',
'c-menubar' => 'component: menubar',
'c-meter' => 'component: meter',
'c-navigation-menu' => 'component: navigation menu',
'c-number-field' => 'component: number field',
'c-popover' => 'component: popover',
'c-preview-card' => 'component: preview card',
'c-progress' => 'component: progress',
'c-radio' => 'component: radio',
'c-scroll-area' => 'component: scroll area',
'c-select' => 'component: select',
'c-separator' => 'component: separator',
'c-slider' => 'component: slider',
'c-switch' => 'component: switch',
'c-tabs' => 'component: tabs',
'c-toast' => 'component: toast',
'c-toggle' => 'component: toggle',
'c-toggle-group' => 'component: toggle group',
'c-toolbar' => 'component: toolbar',
'c-tooltip' => 'component: tooltip',
];
#[Component]
function AutocompleteGroupedDemo(): Node
{
$groups = [
'Type' => array_filter(
TAGS,
static fn (string $id): bool => !str_starts_with($id, 'c-'),
\ARRAY_FILTER_USE_KEY
),
'Component' => array_filter(
TAGS,
static fn (string $id): bool => str_starts_with($id, 'c-'),
\ARRAY_FILTER_USE_KEY
),
];
return (
<Autocomplete id="grouped-tags" filter="contains">
<ComboboxLabel>Select a tag</ComboboxLabel>
<ComboboxInput placeholder="e.g. feature" />
<ComboboxPopup>
<ComboboxEmpty>No tags found.</ComboboxEmpty>
<ComboboxList>
{% for name, tags in groups %}
<ComboboxGroup key={{ name }} className="block pb-2 last:pb-0">
<ComboboxGroupLabel>{{ name }}</ComboboxGroupLabel>
{% for id, tag in tags %}
<ComboboxItem key={{ id }} value={{ id }} className="flex">{{ tag }}</ComboboxItem>
{% endfor %}
</ComboboxGroup>
{% endfor %}
</ComboboxList>
</ComboboxPopup>
</Autocomplete>
);
}
Fuzzy matching#
Use fuzzy matching to find relevant results even when the query doesn’t exactly match the item text. Here filter="fuzzy" matches the characters of the query in order, in the label and in each of the keywords of an item, and ComboboxHighlight marks the text that has the query.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\Autocomplete;
use function Phem\Ui\{ComboboxEmpty, ComboboxHighlight, ComboboxInput, ComboboxItem, ComboboxLabel, ComboboxList, ComboboxPopup};
const DOCS = [
[
'title' => 'React Hooks Guide',
'description' => 'Learn how to use React Hooks like useState, useEffect, and custom hooks',
'category' => 'React',
],
[
'title' => 'JavaScript Array Methods',
'description' => 'Master array methods like map, filter, reduce, and forEach in JavaScript',
'category' => 'JavaScript',
],
[
'title' => 'CSS Flexbox Layout',
'description' => 'Complete guide to CSS Flexbox for responsive web design',
'category' => 'CSS',
],
[
'title' => 'TypeScript Interfaces',
'description' => 'Understanding TypeScript interfaces and type definitions',
'category' => 'TypeScript',
],
[
'title' => 'React Performance Optimization',
'description' => 'Tips and techniques for optimizing React application performance',
'category' => 'React',
],
[
'title' => 'HTML Semantic Elements',
'description' => 'Using semantic HTML elements for better accessibility and SEO',
'category' => 'HTML',
],
[
'title' => 'Node.js Express Server',
'description' => 'Building RESTful APIs with Node.js and Express framework',
'category' => 'Node.js',
],
[
'title' => 'Vue Composition API',
'description' => 'Modern Vue.js development using the Composition API',
'category' => 'Vue.js',
],
[
'title' => 'Angular Components',
'description' => 'Creating reusable Angular components with TypeScript',
'category' => 'Angular',
],
[
'title' => 'Python Django Framework',
'description' => 'Web development with Python Django framework',
'category' => 'Python',
],
[
'title' => 'CSS Grid Layout',
'description' => 'Advanced CSS Grid techniques for complex layouts',
'category' => 'CSS',
],
[
'title' => 'React Testing Library',
'description' => 'Testing React components with React Testing Library',
'category' => 'React',
],
[
'title' => 'MongoDB Queries',
'description' => 'Advanced MongoDB queries and aggregation pipelines',
'category' => 'Database',
],
[
'title' => 'Webpack Configuration',
'description' => 'Optimizing webpack configuration for production builds',
'category' => 'Build Tools',
],
[
'title' => 'SASS/SCSS Guide',
'description' => 'Writing maintainable CSS with SASS and SCSS',
'category' => 'CSS',
],
];
#[Component]
function AutocompleteFuzzyDemo(): Node
{
$docs = DOCS;
return (
<Autocomplete id="docs" filter="fuzzy">
<ComboboxLabel>Fuzzy search documentation</ComboboxLabel>
<ComboboxInput placeholder="e.g. React" />
<ComboboxPopup>
<ComboboxEmpty text='No results found for "{query}"' className="py-3" />
<ComboboxList className="flex max-h-[min(var(--available-height),28rem)] flex-col">
{% for doc in docs %}
<ComboboxItem key={{ doc.title }} value={{ doc.title }} label={{ doc.title }} keywords={{ [doc.description, doc.category] }} className="flex py-3 leading-6 data-highlighted:text-neutral-950 data-highlighted:before:bg-neutral-100 dark:data-highlighted:text-white dark:data-highlighted:before:bg-neutral-800">
<span className="flex w-full flex-col gap-1">
<ComboboxHighlight className="leading-5 font-bold">{{ doc.title }}</ComboboxHighlight>
<ComboboxHighlight className="text-sm text-neutral-500 dark:text-neutral-400">{{ doc.description }}</ComboboxHighlight>
</span>
</ComboboxItem>
{% endfor %}
</ComboboxList>
</ComboboxPopup>
</Autocomplete>
);
}
Limit results#
Limit the number of visible items using the limit prop and guide users to refine their query using ComboboxStatus.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\Autocomplete;
use function Phem\Ui\{ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxLabel, ComboboxList, ComboboxPopup, ComboboxStatus};
const TAGS = [
't1' => 'feature',
't2' => 'fix',
't3' => 'bug',
't4' => 'docs',
't5' => 'internal',
't6' => 'mobile',
'c-accordion' => 'component: accordion',
'c-alert-dialog' => 'component: alert dialog',
'c-autocomplete' => 'component: autocomplete',
'c-avatar' => 'component: avatar',
'c-checkbox' => 'component: checkbox',
'c-checkbox-group' => 'component: checkbox group',
'c-collapsible' => 'component: collapsible',
'c-combobox' => 'component: combobox',
'c-context-menu' => 'component: context menu',
'c-dialog' => 'component: dialog',
'c-field' => 'component: field',
'c-fieldset' => 'component: fieldset',
'c-filterable-menu' => 'component: filterable menu',
'c-form' => 'component: form',
'c-input' => 'component: input',
'c-menu' => 'component: menu',
'c-menubar' => 'component: menubar',
'c-meter' => 'component: meter',
'c-navigation-menu' => 'component: navigation menu',
'c-number-field' => 'component: number field',
'c-popover' => 'component: popover',
'c-preview-card' => 'component: preview card',
'c-progress' => 'component: progress',
'c-radio' => 'component: radio',
'c-scroll-area' => 'component: scroll area',
'c-select' => 'component: select',
'c-separator' => 'component: separator',
'c-slider' => 'component: slider',
'c-switch' => 'component: switch',
'c-tabs' => 'component: tabs',
'c-toast' => 'component: toast',
'c-toggle' => 'component: toggle',
'c-toggle-group' => 'component: toggle group',
'c-toolbar' => 'component: toolbar',
'c-tooltip' => 'component: tooltip',
];
const MORE_TAGS = [
't7' => 'frontend',
't8' => 'backend',
't9' => 'performance',
't10' => 'accessibility',
't11' => 'design',
't12' => 'research',
't13' => 'testing',
't14' => 'infrastructure',
't15' => 'documentation',
];
#[Component]
function AutocompleteLimitDemo(): Node
{
$tags = [...\array_slice(TAGS, 0, 6), ...MORE_TAGS, ...\array_slice(TAGS, 6)];
return (
<Autocomplete id="limited-tags" filter="contains" limit={{ 8 }}>
<ComboboxLabel>Limit results to 8</ComboboxLabel>
<ComboboxInput placeholder="e.g. component" />
<ComboboxPopup>
<ComboboxEmpty className="py-2" text='No results found for "{query}"' />
<ComboboxList>
{% for id, tag in tags %}
<ComboboxItem key={{ id }} value={{ id }} className="flex">{{ tag }}</ComboboxItem>
{% endfor %}
</ComboboxList>
<ComboboxStatus className="py-2 pr-4 pl-2" more="Hiding {count} results (type a more specific query to narrow results)" />
</ComboboxPopup>
</Autocomplete>
);
}
Auto highlight#
The first matching item can be automatically highlighted as the user types by specifying the autoHighlight prop on Autocomplete. Set the prop’s value to "always" if the highlight should always be present, such as when the list is rendered inline within a dialog.
The prop can be combined with the keepHighlight and highlightItemOnHover props to configure how the highlight behaves during mouse interactions.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\Autocomplete;
use function Phem\Ui\{ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxLabel, ComboboxList, ComboboxPopup};
const TAGS = [
't1' => 'feature',
't2' => 'fix',
't3' => 'bug',
't4' => 'docs',
't5' => 'internal',
't6' => 'mobile',
'c-accordion' => 'component: accordion',
'c-alert-dialog' => 'component: alert dialog',
'c-autocomplete' => 'component: autocomplete',
'c-avatar' => 'component: avatar',
'c-checkbox' => 'component: checkbox',
'c-checkbox-group' => 'component: checkbox group',
'c-collapsible' => 'component: collapsible',
'c-combobox' => 'component: combobox',
'c-context-menu' => 'component: context menu',
'c-dialog' => 'component: dialog',
'c-field' => 'component: field',
'c-fieldset' => 'component: fieldset',
'c-filterable-menu' => 'component: filterable menu',
'c-form' => 'component: form',
'c-input' => 'component: input',
'c-menu' => 'component: menu',
'c-menubar' => 'component: menubar',
'c-meter' => 'component: meter',
'c-navigation-menu' => 'component: navigation menu',
'c-number-field' => 'component: number field',
'c-popover' => 'component: popover',
'c-preview-card' => 'component: preview card',
'c-progress' => 'component: progress',
'c-radio' => 'component: radio',
'c-scroll-area' => 'component: scroll area',
'c-select' => 'component: select',
'c-separator' => 'component: separator',
'c-slider' => 'component: slider',
'c-switch' => 'component: switch',
'c-tabs' => 'component: tabs',
'c-toast' => 'component: toast',
'c-toggle' => 'component: toggle',
'c-toggle-group' => 'component: toggle group',
'c-toolbar' => 'component: toolbar',
'c-tooltip' => 'component: tooltip',
];
#[Component]
function AutocompleteAutoHighlightDemo(): Node
{
$tags = TAGS;
return (
<Autocomplete id="highlighted-tags" filter="contains" autoHighlight>
<ComboboxLabel>Auto highlight on type</ComboboxLabel>
<ComboboxInput placeholder="e.g. feature" />
<ComboboxPopup>
<ComboboxEmpty>No tags found.</ComboboxEmpty>
<ComboboxList>
{% for id, tag in tags %}
<ComboboxItem key={{ id }} value={{ id }} className="flex">{{ tag }}</ComboboxItem>
{% endfor %}
</ComboboxList>
</ComboboxPopup>
</Autocomplete>
);
}
Command palette#
Use the autocomplete input to filter a list of command items that perform an action when clicked. With no ComboboxPopup, the list is inline and always open. Give the items data-phem-dialog-target="close" to close the dialog on a choice. Each open starts with an empty search.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\{Autocomplete, Dialog};
use function Phem\Ui\{ComboboxEmpty, ComboboxGroup, ComboboxGroupLabel, ComboboxInput, ComboboxItem, ComboboxList, DialogClose, DialogPopup, DialogTrigger, ScrollArea, ScrollAreaContent, ScrollAreaScrollbar, ScrollAreaThumb, ScrollAreaViewport};
const PALETTE = [
'Suggestions' => [
'linear' => 'Linear',
'figma' => 'Figma',
'slack' => 'Slack',
'youtube' => 'YouTube',
'raycast' => 'Raycast',
'notion' => 'Notion',
'github' => 'GitHub',
'jira' => 'Jira',
'calendar' => 'Google Calendar',
'chrome' => 'Google Chrome',
'mail' => 'Apple Mail',
'terminal' => 'Terminal',
],
'Commands' => [
'clipboard-history' => 'Clipboard History',
'import-extension' => 'Import Extension',
'create-snippet' => 'Create Snippet',
'system-preferences' => 'System Preferences',
'window-management' => 'Window Management',
'toggle-dark-mode' => 'Toggle Dark Mode',
'new-window' => 'New Window',
'new-tab' => 'New Tab',
'search-docs' => 'Search Documentation',
'capture-screen' => 'Capture Screenshot',
'close-sidebar' => 'Toggle Sidebar',
'toggle-terminal' => 'Toggle Integrated Terminal',
'run-script' => 'Run Script',
],
];
#[Component]
function AutocompleteCommandPaletteDemo(): Node
{
$groups = PALETTE;
return (
<Dialog>
<DialogTrigger>Open command palette</DialogTrigger>
<DialogPopup aria-label="Command palette" className="top-18 mt-0 max-h-[min(36rem,calc(100dvh-5rem))] w-[calc(100vw-1rem)] max-w-md translate-y-0 gap-0 p-0 data-ending-style:-translate-y-4 data-ending-style:scale-95 data-starting-style:-translate-y-4 data-starting-style:scale-95 transition-[translate,scale,opacity] duration-150">
<Autocomplete id="palette" filter="contains" autoHighlight="always" keepHighlight className="min-h-0 gap-0">
<div className="relative z-1 flex cursor-text items-center gap-2 bg-white pl-3 focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-neutral-950 dark:bg-neutral-950 dark:focus-within:outline-white">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round" aria-hidden="true" className="block h-4 w-4 shrink-0 text-neutral-500 dark:text-neutral-400">
<path d="m11 11 3.5 3.5" />
<circle cx="7" cy="7" r="5.5" />
</svg>
<ComboboxInput aria-label="Search commands" aria-describedby="palette-shortcuts" placeholder="Search for apps and commands…" autofocus className="h-10 w-full border-0 bg-transparent pr-3 pl-0 focus:outline-none dark:bg-transparent" />
</div>
<DialogClose className="sr-only">Close command palette</DialogClose>
<ScrollArea className="relative flex h-auto max-h-[min(60dvh,24rem)] min-h-0 w-auto max-w-none flex-[0_1_auto] overflow-hidden border-t border-neutral-950 bg-transparent dark:border-t-white dark:bg-transparent">
<ScrollAreaViewport className="h-auto min-h-0 flex-1 overscroll-contain border-0 [scroll-padding-block:0.25rem]">
<ScrollAreaContent className="block min-w-full p-0">
<ComboboxEmpty className="flex min-h-32 items-center justify-start empty:min-h-0">No results found.</ComboboxEmpty>
<ComboboxList className="max-h-none overflow-visible">
{% for name, items in groups %}
<ComboboxGroup key={{ name }} className="not-last:mb-1">
<ComboboxGroupLabel className="flex min-h-8 items-center py-0 pr-6 pl-3 leading-none">{{ name }}</ComboboxGroupLabel>
{% for value, label in items %}
<ComboboxItem key={{ value }} value={{ value }} label={{ label }} data-phem-dialog-target="close" className="min-h-8 grid-cols-[minmax(0,1fr)_auto] px-6 py-0 leading-[1.25] [scroll-margin-block:0.25rem] data-highlighted:text-neutral-950 data-highlighted:before:bg-neutral-200 dark:data-highlighted:text-white dark:data-highlighted:before:bg-neutral-700">
<span className="min-w-0 truncate">{{ label }}</span>
<span className="shrink-0 text-sm whitespace-nowrap text-neutral-500 group-data-highlighted:text-neutral-700 dark:text-neutral-400 dark:group-data-highlighted:text-neutral-300">{{ name == 'Suggestions' ? 'Application' : 'Command' }}</span>
</ComboboxItem>
{% endfor %}
</ComboboxGroup>
{% endfor %}
</ComboboxList>
</ScrollAreaContent>
</ScrollAreaViewport>
<ScrollAreaScrollbar className="pointer-events-auto m-0 w-4 justify-center bg-black/12 opacity-100 dark:bg-white/12">
<ScrollAreaThumb className="bg-neutral-950 dark:bg-white" />
</ScrollAreaScrollbar>
</ScrollArea>
<div className="flex items-center justify-between border-t border-neutral-950 bg-white px-3 py-2.5 text-xs font-normal text-neutral-600 dark:border-white dark:bg-neutral-950 dark:text-neutral-400">
<span id="palette-shortcuts" className="sr-only">Use Enter to activate the highlighted item.</span>
<div className="flex items-center gap-1">
<span>Activate</span>
<kbd className="inline-flex h-5 min-w-5 items-center justify-center border border-neutral-400 bg-neutral-100 px-1 font-mono text-[0.625rem] leading-none text-neutral-600 dark:border-neutral-600 dark:bg-neutral-900 dark:text-neutral-400">Enter</kbd>
</div>
</div>
</Autocomplete>
</DialogPopup>
</Dialog>
);
}
Grid layout#
Display items in a grid layout, wrapping each row in ComboboxRow components, and add the grid prop to Autocomplete. The arrow keys move in the rows and in the columns.
The browser filters the emojis, and the matches of each category fill its rows again. A choice inserts the emoji at the caret of the message (insertInto), and the focus goes back to the message.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\{Align, Autocomplete};
use function Phem\Ui\{ComboboxEmpty, ComboboxGroup, ComboboxGroupLabel, ComboboxInput, ComboboxItem, ComboboxList, ComboboxPopup, ComboboxRow, ComboboxTrigger};
const EMOJIS = [
'Smileys & Emotion' => [
'😀' => 'grinning face',
'😃' => 'grinning face with big eyes',
'😄' => 'grinning face with smiling eyes',
'😁' => 'beaming face with smiling eyes',
'😆' => 'grinning squinting face',
'😅' => 'grinning face with sweat',
'🤣' => 'rolling on the floor laughing',
'😂' => 'face with tears of joy',
'🙂' => 'slightly smiling face',
'🙃' => 'upside-down face',
'😉' => 'winking face',
'😊' => 'smiling face with smiling eyes',
'😇' => 'smiling face with halo',
'🥰' => 'smiling face with hearts',
'😍' => 'smiling face with heart-eyes',
'🤩' => 'star-struck',
'😘' => 'face blowing a kiss',
'😗' => 'kissing face',
'☺️' => 'smiling face',
'😚' => 'kissing face with closed eyes',
'😙' => 'kissing face with smiling eyes',
'🥲' => 'smiling face with tear',
'😋' => 'face savoring food',
'😛' => 'face with tongue',
'😜' => 'winking face with tongue',
'🤪' => 'zany face',
'😝' => 'squinting face with tongue',
'🤑' => 'money-mouth face',
'🤗' => 'hugging face',
'🤭' => 'face with hand over mouth',
],
'Animals & Nature' => [
'🐶' => 'dog face',
'🐱' => 'cat face',
'🐭' => 'mouse face',
'🐹' => 'hamster',
'🐰' => 'rabbit face',
'🦊' => 'fox',
'🐻' => 'bear',
'🐼' => 'panda',
'🐨' => 'koala',
'🐯' => 'tiger face',
'🦁' => 'lion',
'🐮' => 'cow face',
'🐷' => 'pig face',
'🐽' => 'pig nose',
'🐸' => 'frog',
'🐵' => 'monkey face',
'🙈' => 'see-no-evil monkey',
'🙉' => 'hear-no-evil monkey',
'🙊' => 'speak-no-evil monkey',
'🐒' => 'monkey',
'🐔' => 'chicken',
'🐧' => 'penguin',
'🐦' => 'bird',
'🐤' => 'baby chick',
'🐣' => 'hatching chick',
'🐥' => 'front-facing baby chick',
'🦆' => 'duck',
'🦅' => 'eagle',
'🦉' => 'owl',
'🦇' => 'bat',
],
'Food & Drink' => [
'🍎' => 'red apple',
'🍏' => 'green apple',
'🍊' => 'tangerine',
'🍋' => 'lemon',
'🍌' => 'banana',
'🍉' => 'watermelon',
'🍇' => 'grapes',
'🍓' => 'strawberry',
'🫐' => 'blueberries',
'🍈' => 'melon',
'🍒' => 'cherries',
'🍑' => 'peach',
'🥭' => 'mango',
'🍍' => 'pineapple',
'🥥' => 'coconut',
'🥝' => 'kiwi fruit',
'🍅' => 'tomato',
'🍆' => 'eggplant',
'🥑' => 'avocado',
'🥦' => 'broccoli',
'🥬' => 'leafy greens',
'🥒' => 'cucumber',
'🌶️' => 'hot pepper',
'🫑' => 'bell pepper',
'🌽' => 'ear of corn',
'🥕' => 'carrot',
'🫒' => 'olive',
'🧄' => 'garlic',
'🧅' => 'onion',
'🥔' => 'potato',
],
];
#[Component]
function AutocompleteGridDemo(): Node
{
$groups = [];
foreach (EMOJIS as $category => $emojis) {
$groups[$category] = array_chunk($emojis, 5, true);
}
return (
<div className="mx-auto w-[16rem]">
<div className="relative flex w-full">
<input id="emoji-message" type="text" aria-label="Message" placeholder="iMessage" className="-mr-px h-control flex-1 border border-r-0 border-neutral-950 bg-white px-2 text-sm font-normal text-neutral-950 placeholder:text-neutral-500 focus:relative focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 any-pointer-coarse:text-base dark:border-white dark:bg-neutral-950 dark:text-white dark:placeholder:text-neutral-400 dark:focus:outline-white" />
<Autocomplete id="emoji" grid filter="contains" insertInto="emoji-message" align={{ Align.End }}>
<ComboboxTrigger tabindex="0" aria-label="Choose emoji" className="size-control w-control border border-neutral-950 text-xl leading-none hover:bg-neutral-100 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 active:bg-neutral-200 data-popup-open:bg-neutral-100 dark:border-white dark:hover:bg-neutral-800 dark:focus-visible:outline-white dark:active:bg-neutral-700 dark:data-popup-open:bg-neutral-800">😀</ComboboxTrigger>
<ComboboxPopup aria-label="Select emoji" className="w-auto border-0 [--input-container-height:2rem]">
<ComboboxInput aria-label="Search emojis" placeholder="Search emojis…" className="max-w-full focus:-outline-offset-2" />
<div className="border border-t-0 border-neutral-950 dark:border-white">
<ComboboxEmpty className="px-2 py-3">No emojis found</ComboboxEmpty>
<ComboboxList aria-label="Emoji results" className="max-h-[min(calc(20.5rem-var(--input-container-height)-2px),calc(var(--available-height)-var(--input-container-height)-2px))] overflow-auto py-2 scroll-pt-1 scroll-pb-[0.35rem]">
{% for category, rows in groups %}
<ComboboxGroup key={{ category }} className="block">
<ComboboxGroupLabel>{{ category }}</ComboboxGroupLabel>
<div className="px-2 pt-0 pb-1" role="presentation">
{% for index, row in rows %}
<ComboboxRow key={{ index }} className="grid grid-cols-5">
{% for emoji, name in row %}
<ComboboxItem key={{ emoji }} value={{ emoji }} label={{ name }} className="flex h-10 min-w-[var(--anchor-width)] flex-col items-center justify-center px-0.5 py-2 data-highlighted:before:bg-neutral-100 dark:data-highlighted:before:bg-neutral-800">
<span className="text-2xl leading-none">{{ emoji }}</span>
</ComboboxItem>
{% endfor %}
</ComboboxRow>
{% endfor %}
</div>
</ComboboxGroup>
{% endfor %}
</ComboboxList>
</div>
</ComboboxPopup>
</Autocomplete>
</div>
</div>
);
}
Virtualized#
Efficiently handle large datasets by rendering only the first matches. The onChange handler of ComboboxInput searches the dataset on the server, and the state keeps the first 50 matches. ComboboxStatus shows the number of matches, and a choice writes the label of the item in the input.
<?phem
use Phem\Attribute\{Component, State};
use Phem\{Event, Node};
use Phem\Ui\{Autocomplete, Combobox};
use function Phem\Ui\{ComboboxActions, ComboboxClear, ComboboxEmpty, ComboboxInput, ComboboxInputGroup, ComboboxItem, ComboboxItemIndicator, ComboboxItemLabel, ComboboxLabel, ComboboxList, ComboboxPopup, ComboboxStatus, ComboboxTrigger};
#[Component]
final class AutocompleteVirtualizedDemo
{
/** @var array<string, string> */
#[State] public array $items = [];
#[State] public int $total = 0;
public function mount(): void
{
[$this->items, $this->total] = ComboboxLargeDatasetDemo::search('');
}
public function search(Event $e): void
{
[$this->items, $this->total] = ComboboxLargeDatasetDemo::search((string) $e->value);
}
public function render(): Node
{
$status = $this->total > 50
? 'Showing 50 of '.number_format($this->total).' items. Type to refine.'
: null;
return (
<Autocomplete id="many" openOnInputClick>
<ComboboxLabel>Search 10,000 items</ComboboxLabel>
<ComboboxInput onChange={{ search }} />
<ComboboxPopup>
<ComboboxEmpty className="px-2 py-3">No items found.</ComboboxEmpty>
<ComboboxList>
{% for id, name in items %}
<ComboboxItem key={{ id }} value={{ '' ~ id }} label={{ name }} className="flex">{{ name }}</ComboboxItem>
{% endfor %}
</ComboboxList>
<ComboboxStatus className="py-1 pr-5 pl-2 empty:hidden">{{ status }}</ComboboxStatus>
</ComboboxPopup>
</Autocomplete>
);
}
}
#[Component]
final class ComboboxLargeDatasetDemo
{
#[State] public string $query = '';
/**
* @return array{array<string, string>, int} the first 50 matches, and the
* number of matches
*/
public static function search(string $query): array
{
$needle = mb_strtolower(trim($query));
$matches = [];
$total = 0;
for ($i = 1; $i <= 10000; ++$i) {
$name = 'Item '.str_pad((string) $i, 4, '0', \STR_PAD_LEFT);
if ('' !== $needle && !str_contains(mb_strtolower($name), $needle)) {
continue;
}
++$total;
if (\count($matches) < 50) {
$matches[(string) $i] = $name;
}
}
return [$matches, $total];
}
public function render(): Node
{
[$matches, $total] = self::search($this->query);
$status = $total > 50
? 'Showing 50 of '.number_format($total).' items. Type to refine.'
: null;
return (
<Combobox id="items">
<ComboboxLabel>Search 10,000 items</ComboboxLabel>
<ComboboxInputGroup>
<ComboboxInput phem:bind={{ query }} placeholder="e.g. Item 0042" />
<ComboboxActions>
<ComboboxClear aria-label="Clear selection" />
<ComboboxTrigger aria-label="Open popup" />
</ComboboxActions>
</ComboboxInputGroup>
<ComboboxPopup>
<ComboboxEmpty>No items found.</ComboboxEmpty>
<ComboboxList>
{% for id, name in matches %}
<ComboboxItem key={{ id }} value={{ '' ~ id }}>
<ComboboxItemIndicator />
<ComboboxItemLabel>{{ name }}</ComboboxItemLabel>
</ComboboxItem>
{% endfor %}
</ComboboxList>
<ComboboxStatus className="py-1 pr-5 pl-2 text-sm leading-5 text-neutral-500 empty:hidden dark:text-neutral-400">{{ status }}</ComboboxStatus>
</ComboboxPopup>
</Combobox>
);
}
}
API reference#
Import the components of the family:
use Phem\Ui\Autocomplete;Autocomplete#
A text field that suggests values while the user types: Base UI Autocomplete.Root, on the phem-combobox controller. The input keeps the free text that the user types: an item fills the input, and does not become a chosen value.
Use the parts of Combobox in it: ComboboxLabel, ComboboxInput, ComboboxPopup, ComboboxList, ComboboxItem, ComboboxHighlight, ComboboxEmpty, ComboboxStatus, ComboboxGroup…
| Prop | Type | Default |
|---|---|---|
id (required) | string | — |
multiple | bool | false |
filter | ?string | null |
mode | ?string | null |
limit | ?int | null |
locale | ?string | null |
autoHighlight | bool|string | false |
keepHighlight | bool | false |
highlightItemOnHover | bool | true |
grid | bool | false |
insertInto | ?string | null |
loopFocus | bool | true |
side | 'top' | 'bottom' | 'left' | 'right' | 'inline-start' | 'inline-end' | Side::Bottom |
align | 'start' | 'center' | 'end' | Align::Start |
sideOffset | int | 4 |
alignOffset | int | 0 |
collisionPadding | int | 5 |
name | ?string | null |
value | ?Bound | null |
defaultValue | string|array|null | null |
defaultInputValue | ?string | null |
selectionMode | ?string | null |
openOnInputClick | ?bool | null |
children | ?Html | null |
...attrs | array | [] |
The source of the examples: examples/ui/Autocomplete.phem.