Selection and input · Material 3: Search
Search
A search field whose suggestions grow out of it. Matching letters turn bold; the highlight slides; Clear appears once you type.
Examples and variants
Suggestions
Type “ca”; pick with arrows and Enter.
Try “ca”.
function SearchSuggestions() {
const [picked, setPicked] = useState("")
return (
<div className="flex w-full max-w-sm flex-col gap-2">
<Search items={components} placeholder="Search components" onSelect={setPicked} />
<p className="text-sm text-muted-foreground">{picked ? `Opened ${picked}` : "Try “ca”."}</p>
</div>
)
}Spec drawing
Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.
Install
With the CLI
The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/search.json
npx shadcn@latest add https://isotopi.com/r/combobox.jsonBy hand
No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.
Install the packages it uses.
Terminalnpm install @base-ui/react class-variance-authority cn lucide-reactCopy these 3 files to the same paths in your project. Imports use the
@/alias for your project root.components/ui/chip.tsxchip
components/ui/chip.tsx"use client" import * as React from "react" import { XIcon } from "lucide-react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "cn" /* One Chip for every compact, interactive token (component-model.md §3): - kind="input": a value someone entered or picked (Combobox multiple, tag fields). Removable. - kind="filter": a toggle that narrows a list. Pressed state. - kind="suggestion": a one-tap suggestion that runs an action. Badge stays static (status and counts) and is not a Chip. */ const chipVariants = cva( "chip-land inline-flex h-(--chip-height) shrink-0 items-center gap-1 rounded-(--chip-corner) px-(--chip-padding-x) text-xs whitespace-nowrap outline-none select-none focus-visible:shadow-(--focus-ring)", { variants: { kind: { input: "bg-(--chip-container) text-(--chip-label)", filter: "liquid-press bg-(--chip-filter-container) text-(--chip-label) hover:bg-(--chip-filter-container-hover) active:bg-(--chip-filter-container-pressed) data-[pressed]:bg-(--chip-container-selected) data-[pressed]:text-(--chip-label-selected) data-[pressed]:hover:bg-(--chip-container-selected-hover) disabled:bg-(--chip-container-disabled) disabled:text-(--chip-label-disabled)", suggestion: "liquid-press bg-(--chip-suggestion-container) text-(--chip-label) shadow-1 hover:bg-(--chip-suggestion-container-hover) disabled:bg-(--chip-container-disabled) disabled:text-(--chip-label-disabled) disabled:shadow-none", }, tone: { neutral: "", danger: "bg-(--color-danger-subtle) text-(--color-danger-fg)", success: "bg-(--color-success-subtle) text-(--color-success-fg)", }, }, defaultVariants: { kind: "input", tone: "neutral" }, } ) type ChipProps = React.ComponentProps<"span"> & VariantProps<typeof chipVariants> & { /** Plays the melt-away animation (set by the parent while the chip is being removed). */ melting?: boolean } function Chip({ className, kind, tone, melting, ...props }: ChipProps) { return ( <span data-slot="chip" data-kind={kind ?? "input"} className={cn(chipVariants({ kind, tone }), melting && "chip-melt", className)} {...props} /> ) } function ChipRemove({ className, children, ...props }: React.ComponentProps<"button">) { return ( <button type="button" data-slot="chip-remove" aria-label="Remove" className={cn( "hit-target liquid-press -mr-1 inline-flex size-4 items-center justify-center rounded-(--radius-pill) text-muted-foreground outline-none hover:bg-(--chip-remove-container-hover) hover:text-foreground active:bg-(--chip-remove-container-pressed) focus-visible:shadow-(--focus-ring) [&_svg]:size-3", className )} {...props} > {children ?? <XIcon aria-hidden />} </button> ) } export { Chip, ChipRemove, chipVariants }components/ui/combobox.tsxcombobox
components/ui/combobox.tsx"use client" import * as React from "react" import { createPortal } from "react-dom" import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox" import { cn } from "cn" import { tokenMs } from "@/lib/motion/token-ms" import { motionLevel } from "@/lib/overlay" import { Chip, ChipRemove } from "@/components/ui/chip" function ComboboxValue(props: ComboboxPrimitive.Value.Props) { return <ComboboxPrimitive.Value {...props} /> } type Bud = { id: number; x: number; y: number; dx: number; dy: number } /* Per-instance state (no window events or document lookups), so two comboboxes on one page never animate each other: - anchor: the visible field shape (ComboboxChips). The list anchors to it, not to the bare text input, so it never overlaps the field's focus halo. - bud: the droplet that flies from a picked row into the field, or from a removed chip back into the input. - melting: the chip being removed; it melts before the value updates. */ type ComboboxState = { anchor: HTMLElement | null setAnchor: (node: HTMLElement | null) => void input: React.RefObject<HTMLInputElement | null> bud: Bud | null sendBud: (from: { x: number; y: number }, to?: { x: number; y: number }) => void clearBud: () => void melting: unknown } const ComboboxContext = React.createContext<ComboboxState | null>(null) function useComboboxState() { const state = React.useContext(ComboboxContext) if (!state) throw new Error("Combobox parts must be inside <Combobox>") return state } function Combobox<Value, Multiple extends boolean | undefined = false>({ onValueChange, value, ...props }: ComboboxPrimitive.Root.Props<Value, Multiple>) { const [anchor, setAnchor] = React.useState<HTMLElement | null>(null) const [bud, setBud] = React.useState<Bud | null>(null) const [melting, setMelting] = React.useState<unknown>(null) const input = React.useRef<HTMLInputElement | null>(null) const current = React.useRef<unknown>(value) React.useEffect(() => { if (value !== undefined) current.current = value }, [value]) const sendBud = React.useCallback( (from: { x: number; y: number }, to?: { x: number; y: number }) => { if (!anchor || motionLevel(anchor) !== "liquid") return const box = anchor.getBoundingClientRect() const target = to ?? { x: box.left + box.width / 2, y: box.top + box.height / 2 } setBud({ id: Date.now(), x: from.x, y: from.y, dx: target.x - from.x, dy: target.y - from.y }) }, [anchor] ) // Multiple: a removed value melts first, then the change is reported. const handleChange = React.useCallback( (next: unknown, details: unknown) => { const report = () => { current.current = next ;(onValueChange as ((v: unknown, d: unknown) => void) | undefined)?.(next, details) } const before = Array.isArray(current.current) ? current.current : [] const after = Array.isArray(next) ? next : [] const removed = before.find((item) => !after.includes(item)) if (removed === undefined || !anchor || motionLevel(anchor) !== "liquid") { setMelting(null) report() return } setMelting(removed) window.setTimeout(() => { setMelting(null) report() }, tokenMs("--duration-fast", anchor)) }, [anchor, onValueChange] ) const state = React.useMemo( () => ({ anchor, setAnchor, input, bud, sendBud, clearBud: () => setBud(null), melting }), [anchor, bud, sendBud, melting] ) return ( <ComboboxContext.Provider value={state}> <ComboboxPrimitive.Root<Value, Multiple> {...props} value={value} onValueChange={handleChange as ComboboxPrimitive.Root.Props<Value, Multiple>["onValueChange"]} /> </ComboboxContext.Provider> ) } function ComboboxInput({ className, ...props }: ComboboxPrimitive.Input.Props) { const { input } = useComboboxState() return ( <ComboboxPrimitive.Input ref={input} data-slot="combobox-input" className={cn( "h-(--field-height-md) w-full min-w-48 rounded-(--field-corner) border-solid border-(length:--field-stroke-width) border-(--field-stroke-color) bg-(--field-container) px-(--field-padding-x) text-sm text-(--field-label) shadow-(--field-elevation) outline-none transition-[background-color,box-shadow] duration-(--duration-fast) ease-(--ease-out) placeholder:text-(--field-placeholder) focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)", className )} {...props} /> ) } function ComboboxContent({ className, children, ...props }: ComboboxPrimitive.Popup.Props) { const { anchor } = useComboboxState() return ( <ComboboxPrimitive.Portal> <ComboboxPrimitive.Positioner anchor={anchor ?? undefined} sideOffset={8} className="z-(--z-dropdown)" > <ComboboxPrimitive.Popup data-slot="combobox-content" className={cn( "grow-from-origin min-w-(--anchor-width) overflow-hidden rounded-(--menu-corner) bg-(--menu-container) p-1 text-foreground shadow-(--menu-elevation) outline-none", className )} {...props} > {children} </ComboboxPrimitive.Popup> </ComboboxPrimitive.Positioner> </ComboboxPrimitive.Portal> ) } function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) { const ref = React.useRef<HTMLDivElement>(null) const places = React.useRef(new Map<string, number>()) React.useLayoutEffect(() => { const root = ref.current if (!root) return const rows = [...root.querySelectorAll<HTMLElement>(".combo-row:not(.combo-row-out)")] const next = new Map<string, number>() const duration = tokenMs("--duration-fast", root) const easing = getComputedStyle(root).getPropertyValue("--ease-sheet").trim() || "ease" for (const row of rows) { const key = row.textContent ?? "" const top = row.getBoundingClientRect().top const before = places.current.get(key) next.set(key, top) if (before === undefined || duration === 0) continue const dy = before - top if (Math.abs(dy) < 1) continue row.animate([{ transform: `translateY(${dy}px)` }, { transform: "none" }], { duration, easing }) } places.current = next }) return ( <ComboboxPrimitive.List ref={ref} data-slot="combobox-list" className={cn("max-h-60 overflow-y-auto", className)} {...props} /> ) } function ComboboxItem({ className, onClick, ...props }: ComboboxPrimitive.Item.Props) { const { sendBud } = useComboboxState() return ( <ComboboxPrimitive.Item data-slot="combobox-item" className={cn( "flex cursor-default items-center rounded-(--menu-item-corner) text-sm outline-none data-highlighted:bg-(--menu-item-highlight)", className )} {...props} onClick={(event) => { onClick?.(event) const rect = event.currentTarget.getBoundingClientRect() sendBud({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }) }} /> ) } function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) { return ( <ComboboxPrimitive.Empty data-slot="combobox-empty" className={cn( "isotope-rise px-2 py-3 text-center text-sm text-muted-foreground", className )} {...props} /> ) } /** A plain field wrapper that anchors the list (single-value comboboxes with icons). */ function ComboboxField({ className, ...props }: React.ComponentProps<"div">) { const ref = React.useRef<HTMLDivElement>(null) const { setAnchor } = useComboboxState() React.useLayoutEffect(() => { setAnchor(ref.current) return () => setAnchor(null) }, [setAnchor]) return <div ref={ref} data-slot="combobox-field" className={cn("relative flex w-full items-center", className)} {...props} /> } function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) { return ( <ComboboxPrimitive.Clear data-slot="combobox-clear" aria-label="Clear" className={cn( "liquid-press inline-flex size-6 items-center justify-center rounded-(--shape-full) text-(--field-action-label) outline-none hover:bg-(--field-action-container-hover) hover:text-(--field-action-label-hover) active:bg-(--field-action-container-pressed) focus-visible:shadow-(--focus-ring)", className )} {...props} /> ) } function ComboboxChips({ className, children, ...props }: ComboboxPrimitive.Chips.Props) { const chipsRef = React.useRef<HTMLDivElement>(null) const { setAnchor, bud, clearBud } = useComboboxState() const places = React.useRef(new Map<string, number>()) React.useLayoutEffect(() => { setAnchor(chipsRef.current) return () => setAnchor(null) }, [setAnchor]) // Neighbours slide over when a chip arrives or leaves (FLIP). React.useLayoutEffect(() => { const root = chipsRef.current if (!root) return const chips = [...root.querySelectorAll<HTMLElement>("[data-slot=chip]")] const next = new Map<string, number>() const easing = getComputedStyle(root).getPropertyValue("--ease-sheet").trim() || "ease" const duration = tokenMs("--duration-fast", root) for (const chip of chips) { const key = chip.textContent ?? "" const left = chip.getBoundingClientRect().left const before = places.current.get(key) next.set(key, left) if (before === undefined || duration === 0) continue const dx = before - left if (Math.abs(dx) < 1) continue chip.animate([{ transform: `translateX(${dx}px)` }, { transform: "none" }], { duration, easing }) } places.current = next }) return ( <ComboboxPrimitive.Chips ref={chipsRef} data-slot="combobox-chips" className={cn( "flex min-h-(--field-height-md) w-full min-w-48 flex-wrap items-center gap-(--space-gap-inline-xs) rounded-(--combobox-chips-corner) bg-(--field-container) px-2 py-1 shadow-(--field-elevation) transition-[background-color,box-shadow] duration-(--duration-fast) ease-(--ease-out) focus-within:bg-(--field-container-focus) focus-within:shadow-(--field-focus-shadow)", "**:data-[slot=combobox-input]:h-auto **:data-[slot=combobox-input]:min-w-0 **:data-[slot=combobox-input]:flex-1 **:data-[slot=combobox-input]:rounded-none **:data-[slot=combobox-input]:bg-transparent **:data-[slot=combobox-input]:px-1 **:data-[slot=combobox-input]:shadow-none **:data-[slot=combobox-input]:focus-visible:bg-transparent **:data-[slot=combobox-input]:focus-visible:shadow-none", className )} {...props} > {children} {/* Portalled: a fixed element inside a blurred surface (Glass) would be positioned against that surface. */} {bud ? createPortal( <span key={bud.id} aria-hidden className="chip-bud pointer-events-none fixed z-(--z-tooltip) size-(--size-icon-sm) -translate-1/2 rounded-full bg-muted" style={{ left: bud.x, top: bud.y, "--bud-x": `${bud.dx}px`, "--bud-y": `${bud.dy}px`, } as React.CSSProperties} onAnimationEnd={clearBud} />, document.body ) : null} </ComboboxPrimitive.Chips> ) } /** A chosen value in a multiple Combobox. Pass `value` so it knows when it's being removed. */ function ComboboxChip({ className, value, children, ...props }: ComboboxPrimitive.Chip.Props & { value?: unknown }) { const ref = React.useRef<HTMLDivElement>(null) const { melting, input, sendBud } = useComboboxState() const isMelting = melting !== null && melting === value React.useEffect(() => { if (!isMelting || !ref.current || !input.current) return const chip = ref.current.getBoundingClientRect() const field = input.current.getBoundingClientRect() sendBud( { x: chip.left + chip.width / 2, y: chip.top + chip.height / 2 }, { x: field.left + field.width / 2, y: field.top + field.height / 2 } ) }, [isMelting, input, sendBud]) return ( <ComboboxPrimitive.Chip ref={ref} render={<Chip kind="input" melting={isMelting} />} className={className} {...props} > {children} </ComboboxPrimitive.Chip> ) } function ComboboxChipRemove(props: ComboboxPrimitive.ChipRemove.Props) { return <ComboboxPrimitive.ChipRemove render={<ChipRemove />} {...props} /> } export { Combobox, ComboboxField, ComboboxClear, ComboboxChip, ComboboxChipRemove, ComboboxChips, ComboboxValue, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList, }components/ui/search.tsxsearch
components/ui/search.tsx"use client" import * as React from "react" import { SearchIcon, XIcon } from "lucide-react" import { cn } from "cn" import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxField, ComboboxInput, ComboboxItem, ComboboxList, } from "@/components/ui/combobox" /* Search (Material 3 "Search"): a search field whose suggestions grow out of it. Matching characters turn bold as they match; the highlight slides between suggestions. Picking one calls onSelect. For free text, listen to onQueryChange and run your own search. */ function SearchHighlight({ text, query }: { text: string; query: string }) { const needle = query.trim().toLowerCase() const at = needle ? text.toLowerCase().indexOf(needle) : -1 if (at === -1) return <>{text}</> return ( <> {text.slice(0, at)} <mark className="search-match bg-transparent font-semibold text-foreground">{text.slice(at, at + needle.length)}</mark> {text.slice(at + needle.length)} </> ) } function Search({ items, placeholder = "Search", label = "Search", onSelect, onQueryChange, empty = "No results", className, }: { items: string[] placeholder?: string label?: string onSelect?: (item: string) => void onQueryChange?: (query: string) => void empty?: React.ReactNode className?: string }) { const [query, setQuery] = React.useState("") return ( <div data-slot="search" className={cn("w-full", className)}> <Combobox items={items} inputValue={query} onInputValueChange={(next) => { setQuery(next) onQueryChange?.(next) }} onValueChange={(next) => { if (typeof next === "string") onSelect?.(next) }} > <ComboboxField> <SearchIcon aria-hidden className="pointer-events-none absolute start-(--field-padding-x) size-(--size-icon-md) text-(--field-placeholder)" /> <ComboboxInput aria-label={label} placeholder={placeholder} className="ps-(--search-padding-start) pe-(--search-padding-end)" /> {query ? ( <button type="button" aria-label="Clear search" onClick={() => { setQuery("") onQueryChange?.("") }} className="search-clear liquid-press absolute end-2 inline-flex size-6 items-center justify-center rounded-(--shape-full) text-(--field-action-label) outline-none hover:bg-(--field-action-container-hover) hover:text-(--field-action-label-hover) active:bg-(--field-action-container-pressed) focus-visible:shadow-(--focus-ring)" > <XIcon className="size-(--size-icon-sm)" /> </button> ) : null} </ComboboxField> <ComboboxContent> <ComboboxEmpty>{empty}</ComboboxEmpty> <ComboboxList> {(item: string) => ( <ComboboxItem key={item} value={item} className="search-suggestion"> <SearchIcon aria-hidden className="me-2 size-(--size-icon-sm) shrink-0 text-ink-subtle" /> <span className="truncate text-muted-foreground"> <SearchHighlight text={item} query={query} /> </span> </ComboboxItem> )} </ComboboxList> </ComboboxContent> </Combobox> </div> ) } export { Search, SearchHighlight }
Imports
What the examples on this page import:
import { CopyIcon, FileIcon, MoonIcon, PlusIcon, SettingsIcon, TrashIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Calendar, type CalendarRange } from "@/components/ui/calendar"
import { Carousel } from "@/components/ui/carousel"
import { CommandDialog, type CommandItem } from "@/components/ui/command"
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from "@/components/ui/context-menu"
import { DatePicker } from "@/components/ui/date-picker"
import { DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut } from "@/components/ui/dropdown-menu"
import { Kbd, KbdGroup } from "@/components/ui/kbd"
import { Menubar, MenubarMenu, MenubarTrigger } from "@/components/ui/menubar"
import { Search } from "@/components/ui/search"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { TimePicker } from "@/components/ui/time-picker"Anatomy
- 1Field · Text field tokens with --search-padding-start/-end for the icons.
- 2Search icon and Clear · Leading icon; Clear shows once there's a query.
- 3Suggestions · Menu tokens; the match is <mark>.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
items | string[] | — | Suggestions. |
onSelect | (item: string) => void | — | Called when a suggestion is picked. |
onQueryChange | (query: string) => void | — | For your own search as people type. |
placeholder, label, empty | string, string, ReactNode | — | Text. |
Tokens
Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.
| Token | Points to | Light | Dark |
|---|---|---|---|
--field-height-sm | var(--size-control-sm) | 32px | same |
--field-height-md | var(--size-control-md) | 40px | same |
--field-height-lg | var(--size-control-lg) | 48px | same |
--field-padding-x | var(--space-inset-control-x) | 12px | same |
--field-padding-x-text | var(--space-inset-control-x-lg) | 16px | same |
--field-padding-y | var(--space-inset-control-y) | 8px | same |
--field-corner | var(--shape-full) | 999px | same |
--field-corner-multiline | var(--shape-md) | 14px | same |
--field-container | var(--surface-container) | oklch(0.965 0.005 95) | oklch(0.12 0 0) |
--field-container-focus | var(--surface-container-lowest) | oklch(1 0 0) | oklch(0.14 0 0) |
--field-label | var(--on-surface) | oklch(0.22 0.01 260) | oklch(1 0 0) |
--field-container-hover | color-mix(in oklch, var(--field-container), var(--field-label) var(--state-hover-mix)) | color-mix(in oklch, var(--field-container), var(--field-label) var(--state-hover-mix)) | same |
--field-container-disabled | var(--color-bg-disabled) | color-mix(in oklch, var(--color-fg-default) var(--state-disabled-container-mix), transparent) | same |
--field-label-disabled | var(--color-fg-disabled) | oklch(0.62 0.01 95) | oklch(0.53 0 0) |
--field-placeholder | var(--on-surface-variant) | oklch(0.45 0.01 95) | oklch(0.68 0 0) |
--field-stroke-width | var(--stroke-width-control) | 0px | same |
--field-stroke-color | var(--stroke-color-default) | oklch(0.22 0.01 260 / 18%) | oklch(1 0 0 / 12%) |
--field-elevation | var(--elevation-1) | 0 1px 1px -0.5px oklch(0.22 0.01 260 / 7%), 0 2px 3px -1px oklch(0.22 0.01 260 / 10%), 0 4px 8px -4px oklch(0.22 0.01 260 / 6%) | 0 1px 2px oklch(0 0 0 / 35%), 0 2px 10px oklch(0 0 0 / 25%) |
--field-focus-halo-width | var(--state-field-stroke) | 3px | same |
--field-focus-shadow | var(--focus-field) | 0 0 0 var(--state-field-stroke) color-mix(in oklch, var(--color-fg-default) var(--state-field-stroke-mix), transparent), var(--elevation-3) | same |
--field-error-shadow | var(--focus-ring-invalid) | 0 0 0 var(--state-focus-ring-offset) var(--focus-ring-gap, var(--color-bg-canvas)), 0 0 0 calc(var(--state-focus-ring-offset) + var(--state-focus-ring-width)) var(--color-danger) | same |
--field-label-gap | var(--space-1) | 4px | same |
--field-action-label | var(--field-placeholder) | oklch(0.45 0.01 95) | oklch(0.68 0 0) |
--field-action-label-hover | var(--field-label) | oklch(0.22 0.01 260) | oklch(1 0 0) |
--field-action-container-hover | var(--color-bg-hover) | oklch(0.965 0.005 95) | oklch(0.22 0 0) |
--field-action-container-pressed | var(--color-bg-pressed) | oklch(0.94 0.007 95) | oklch(0.27 0 0) |
--field-choice-container-hover | color-mix(in oklch, var(--field-container), var(--field-label) var(--state-hover-mix)) | color-mix(in oklch, var(--field-container), var(--field-label) var(--state-hover-mix)) | same |
--search-padding-start | calc(var(--field-padding-x) + var(--size-icon-md) + var(--space-2)) | calc(var(--field-padding-x) + var(--size-icon-md) + var(--space-2)) | same |
--search-padding-end | var(--space-10) | 40px | same |
--menu-container | var(--surface-container-raised) | oklch(1 0 0) | oklch(0.22 0 0) |
--menu-corner | var(--shape-md) | 14px | same |
--menu-padding | var(--space-inset-overlay) | 8px | same |
--menu-elevation | var(--elevation-2) | 0 1px 1px -0.5px oklch(0.22 0.01 260 / 6%), 0 3px 3px -1.5px oklch(0.22 0.01 260 / 6%), 0 6px 6px -3px oklch(0.22 0.01 260 / 6%), 0 12px 12px -6px oklch(0.22 0.01 260 / 6%), 0 24px 24px -12px oklch(0.22 0.01 260 / 6%) | 0 4px 12px oklch(0 0 0 / 40%), 0 12px 28px oklch(0 0 0 / 35%) |
--menu-item-height | var(--size-row-sm) | 32px | same |
--menu-item-padding-x | var(--space-inset-control-x-sm) | 8px | same |
--menu-item-corner | var(--shape-sm) | 8px | same |
--menu-item-highlight | var(--color-bg-hover) | oklch(0.965 0.005 95) | oklch(0.22 0 0) |
--menu-item-label-disabled | var(--color-fg-disabled) | oklch(0.62 0.01 95) | oklch(0.53 0 0) |
--menu-item-danger | var(--color-danger-fg) | oklch(0.48 0.18 25) | oklch(0.78 0.14 22) |
--menu-min-width | var(--layout-menu-min) | 180px | same |
Motion
| Trigger | What happens | Tokens |
|---|---|---|
| Type | The list grows from the field; matches light up; the highlight slides. | --duration-fast |
Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.
Accessibility
- Combobox role with a label; arrows move, Enter picks, Escape clears the list.
Usage
Do
- Show recent or popular suggestions.
Don’t
- Don't use for picking from a short fixed list (use Select).
Code
"use client"
import * as React from "react"
import { SearchIcon, XIcon } from "lucide-react"
import { cn } from "cn"
import {
Combobox,
ComboboxContent,
ComboboxEmpty,
ComboboxField,
ComboboxInput,
ComboboxItem,
ComboboxList,
} from "@/components/ui/combobox"
/*
Search (Material 3 "Search"): a search field whose suggestions grow out of
it. Matching characters turn bold as they match; the highlight slides
between suggestions. Picking one calls onSelect. For free text, listen to
onQueryChange and run your own search.
*/
function SearchHighlight({ text, query }: { text: string; query: string }) {
const needle = query.trim().toLowerCase()
const at = needle ? text.toLowerCase().indexOf(needle) : -1
if (at === -1) return <>{text}</>
return (
<>
{text.slice(0, at)}
<mark className="search-match bg-transparent font-semibold text-foreground">{text.slice(at, at + needle.length)}</mark>
{text.slice(at + needle.length)}
</>
)
}
function Search({
items,
placeholder = "Search",
label = "Search",
onSelect,
onQueryChange,
empty = "No results",
className,
}: {
items: string[]
placeholder?: string
label?: string
onSelect?: (item: string) => void
onQueryChange?: (query: string) => void
empty?: React.ReactNode
className?: string
}) {
const [query, setQuery] = React.useState("")
return (
<div data-slot="search" className={cn("w-full", className)}>
<Combobox
items={items}
inputValue={query}
onInputValueChange={(next) => {
setQuery(next)
onQueryChange?.(next)
}}
onValueChange={(next) => {
if (typeof next === "string") onSelect?.(next)
}}
>
<ComboboxField>
<SearchIcon aria-hidden className="pointer-events-none absolute start-(--field-padding-x) size-(--size-icon-md) text-(--field-placeholder)" />
<ComboboxInput aria-label={label} placeholder={placeholder} className="ps-(--search-padding-start) pe-(--search-padding-end)" />
{query ? (
<button
type="button"
aria-label="Clear search"
onClick={() => {
setQuery("")
onQueryChange?.("")
}}
className="search-clear liquid-press absolute end-2 inline-flex size-6 items-center justify-center rounded-(--shape-full) text-(--field-action-label) outline-none hover:bg-(--field-action-container-hover) hover:text-(--field-action-label-hover) active:bg-(--field-action-container-pressed) focus-visible:shadow-(--focus-ring)"
>
<XIcon className="size-(--size-icon-sm)" />
</button>
) : null}
</ComboboxField>
<ComboboxContent>
<ComboboxEmpty>{empty}</ComboboxEmpty>
<ComboboxList>
{(item: string) => (
<ComboboxItem key={item} value={item} className="search-suggestion">
<SearchIcon aria-hidden className="me-2 size-(--size-icon-sm) shrink-0 text-ink-subtle" />
<span className="truncate text-muted-foreground">
<SearchHighlight text={item} query={query} />
</span>
</ComboboxItem>
)}
</ComboboxList>
</ComboboxContent>
</Combobox>
</div>
)
}
export { Search, SearchHighlight }