Rich comboboxes
Five comboboxes with a richer option row: an initials avatar, a two-line description, a trailing badge, a media tile and grouped sections. Every surface is a token, every mark is initials or inline SVG, so nothing loads from a remote URL. Each is self-contained (no radix, no cmdk), sized, filters as you type and supports arrow keys plus Enter.
Installation
The styled layer is free and installs like any other ai2 component.
Run the following command
npx shadcn@latest add @ai2/combobox-richDependencies, the @ai2/tokens theme and the component file are installed together.
Install dependencies
npm install motion lucide-reactCopy the source
components/ui/combobox-rich.tsx"use client"
import * as React from "react"
import { Check, ChevronsUpDown, Search } from "lucide-react"
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
import { cn } from "@/lib/utils"
/* Rich combobox family: 5 decorative SELF-CONTAINED searchable selects. NO radix,
NO portal, NO cmdk. This family enriches the ROW ANATOMY: an initial-based avatar,
a two-line description, a badge, a token-surfaced media square, and a grouped list.
NO REMOTE IMAGE URLs - everything is a token surface, an initial or an inline SVG.
Each export is a complete combobox: a real <input> carrying role="combobox"
filters, the arrow keys move the highlight, Enter selects, Escape closes. Color
comes ONLY from tokens, via alpha color-mix. */
export type StyledSize = "sm" | "md" | "lg" | "xl"
const triggerHeight: Record<StyledSize, string> = {
sm: "h-8",
md: "h-9",
lg: "h-10",
xl: "h-12",
}
const panelWidth: Record<StyledSize, string> = {
sm: "w-56",
md: "w-64",
lg: "w-72",
xl: "w-80",
}
export interface ComboboxOption {
value: string
label: React.ReactNode
}
interface ComboboxProps {
className?: string
size?: StyledSize
placeholder?: string
options?: ComboboxOption[]
value?: string
defaultValue?: string
onValueChange?: (v: string) => void
}
const defaultOptions: ComboboxOption[] = [
{ value: "next", label: "Next.js" },
{ value: "react", label: "React" },
{ value: "vue", label: "Vue" },
{ value: "svelte", label: "Svelte" },
{ value: "solid", label: "Solid" },
{ value: "astro", label: "Astro" },
]
/* Row enrichments: a sensible fallback is produced for an unknown value. */
interface OptionMeta {
description: string
badge: string
group: string
}
const optionMeta: Record<string, OptionMeta> = {
next: { description: "Full stack React framework", badge: "SSR", group: "Frameworks" },
react: { description: "The component library", badge: "Core", group: "Libraries" },
vue: { description: "Progressive framework", badge: "SFC", group: "Frameworks" },
svelte: { description: "Compiled components", badge: "Compiler", group: "Frameworks" },
solid: { description: "Fine grained reactivity", badge: "Signals", group: "Libraries" },
astro: { description: "Content first sites", badge: "Islands", group: "Frameworks" },
}
function metaFor(value: string): OptionMeta {
return optionMeta[value] ?? { description: "Available option", badge: "Item", group: "Other" }
}
function nodeText(node: React.ReactNode): string {
if (node === null || node === undefined || typeof node === "boolean") return ""
if (typeof node === "string" || typeof node === "number") return String(node)
if (Array.isArray(node)) return node.map(nodeText).join("")
if (React.isValidElement(node)) {
return nodeText((node.props as { children?: React.ReactNode }).children)
}
return ""
}
/* An initial from the label: deterministic avatar content instead of a remote image. */
function initials(label: React.ReactNode): string {
const text = nodeText(label).trim()
if (text.length === 0) return "?"
const words = text.split(/[\s.\-_]+/).filter(Boolean)
if (words.length === 1) return words[0].slice(0, 2).toUpperCase()
return (words[0][0] + words[1][0]).toUpperCase()
}
function filterOptions(options: ComboboxOption[], query: string): ComboboxOption[] {
const q = query.trim().toLowerCase()
if (q.length === 0) return options
return options.filter((o) => nodeText(o.label).toLowerCase().includes(q))
}
const rootBase = "relative"
const inputBase =
"w-full rounded-lg border border-field-border bg-transparent pl-9 pr-9 text-sm text-foreground shadow-xs outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-danger aria-invalid:ring-danger/20 dark:aria-invalid:ring-danger/40"
const panelBase =
"absolute left-0 right-0 top-full z-50 mt-2 min-w-64 origin-top overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-lg outline-none"
const listBase = "max-h-72 overflow-y-auto p-1.5"
const optionBase =
"flex cursor-pointer select-none items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm outline-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 [&_svg]:shrink-0 [&_i]:leading-none"
const emptyBase = "py-6 text-center text-sm text-muted-foreground"
const groupLabel =
"px-2.5 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground"
const panelMotion = {
initial: { opacity: 0, scale: 0.98, y: -6 },
animate: { opacity: 1, scale: 1, y: 0 },
exit: { opacity: 0, scale: 0.98, y: -6 },
}
function useCombobox(props: ComboboxProps) {
const { options = defaultOptions, value, defaultValue, onValueChange } = props
const isControlled = value !== undefined
const [internal, setInternal] = React.useState<string | undefined>(defaultValue)
const current = isControlled ? value : internal
const [open, setOpen] = React.useState(false)
const [editing, setEditing] = React.useState(false)
const [query, setQuery] = React.useState("")
const [active, setActive] = React.useState(0)
const wrapperRef = React.useRef<HTMLDivElement>(null)
const uid = React.useId()
const listId = `${uid}-list`
const optionId = React.useCallback((i: number) => `${uid}-option-${i}`, [uid])
const selected = React.useMemo(
() => (current === undefined ? undefined : options.find((o) => o.value === current)),
[options, current]
)
const filtered = React.useMemo(
() => (editing ? filterOptions(options, query) : options),
[editing, options, query]
)
React.useEffect(() => {
setActive((prev) => (prev >= filtered.length ? 0 : prev))
}, [filtered.length])
const close = React.useCallback(() => {
setOpen(false)
setEditing(false)
setQuery("")
setActive(0)
}, [])
React.useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") close()
}
const onPointer = (e: PointerEvent) => {
const node = wrapperRef.current
if (node && e.target instanceof Node && !node.contains(e.target)) close()
}
window.addEventListener("keydown", onKey)
window.addEventListener("pointerdown", onPointer)
return () => {
window.removeEventListener("keydown", onKey)
window.removeEventListener("pointerdown", onPointer)
}
}, [open, close])
const commit = React.useCallback(
(next: string) => {
if (!isControlled) setInternal(next)
onValueChange?.(next)
close()
},
[isControlled, onValueChange, close]
)
const onInputKeyDown = React.useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "ArrowDown") {
e.preventDefault()
setOpen(true)
setActive((prev) => (filtered.length === 0 ? 0 : (prev + 1) % filtered.length))
} else if (e.key === "ArrowUp") {
e.preventDefault()
setOpen(true)
setActive((prev) =>
filtered.length === 0 ? 0 : (prev - 1 + filtered.length) % filtered.length
)
} else if (e.key === "Enter") {
e.preventDefault()
const item = filtered[active]
if (item) commit(item.value)
} else if (e.key === "Escape") {
e.preventDefault()
close()
}
},
[filtered, active, commit, close]
)
const inputValue = editing ? query : selected ? nodeText(selected.label) : ""
return {
open,
setOpen,
setEditing,
setQuery,
active,
setActive,
filtered,
current,
commit,
onInputKeyDown,
wrapperRef,
inputValue,
listId,
optionId,
selected,
}
}
type RichState = ReturnType<typeof useCombobox>
/* Sunum kabugu: input + panel. Panel govdesi children ile gelir. */
function RichField({
state,
size,
className,
placeholder,
leading,
children,
}: {
state: RichState
size: StyledSize
className?: string
placeholder: string
leading?: React.ReactNode
children: React.ReactNode
}) {
const reduce = useReducedMotion() ?? false
const {
open,
setOpen,
setEditing,
setQuery,
active,
filtered,
onInputKeyDown,
wrapperRef,
inputValue,
listId,
optionId,
} = state
const activeId = open && filtered[active] ? optionId(active) : undefined
return (
<div
ref={wrapperRef}
data-slot="styled-combobox"
className={cn(rootBase, panelWidth[size], className)}
>
<div className="relative">
<span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground [&_svg]:size-4 [&_i]:text-base [&_i]:leading-none">
{leading ?? <Search />}
</span>
<input
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeId}
value={inputValue}
placeholder={placeholder}
onFocus={() => {
setOpen(true)
setEditing(false)
}}
onChange={(e) => {
setOpen(true)
setEditing(true)
setQuery(e.target.value)
}}
onKeyDown={onInputKeyDown}
className={cn(inputBase, triggerHeight[size])}
/>
<ChevronsUpDown className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground opacity-70" />
</div>
<AnimatePresence>
{open ? (
<motion.div
id={listId}
role="listbox"
className={panelBase}
initial={reduce ? { opacity: 0 } : panelMotion.initial}
animate={reduce ? { opacity: 1 } : panelMotion.animate}
exit={reduce ? { opacity: 0 } : panelMotion.exit}
transition={reduce ? { duration: 0 } : { duration: 0.16, ease: "easeOut" }}
>
{children}
</motion.div>
) : null}
</AnimatePresence>
</div>
)
}
/* A single rich row; its content arrives through a render prop. */
function RichRow({
state,
index,
option,
children,
}: {
state: RichState
index: number
option: ComboboxOption
children: React.ReactNode
}) {
const { active, setActive, current, commit, optionId } = state
const isActive = index === active
const isSelected = option.value === current
return (
<div
id={optionId(index)}
role="option"
tabIndex={-1}
aria-selected={isSelected}
onMouseEnter={() => setActive(index)}
onClick={() => commit(option.value)}
className={cn(optionBase, (isActive || isSelected) && "bg-accent text-accent-foreground")}
>
{children}
{isSelected ? <Check className="size-4 text-foreground" /> : null}
</div>
)
}
/* AvatarCombobox: a circle with a token surface and an initial on every row. No
remote images. */
export function AvatarCombobox(props: ComboboxProps) {
const { className, size = "md", placeholder = "Search framework..." } = props
const state = useCombobox(props)
const { filtered } = state
return (
<RichField state={state} size={size} className={className} placeholder={placeholder}>
<div className={listBase}>
{filtered.length === 0 ? (
<p className={emptyBase}>No results found.</p>
) : (
filtered.map((option, i) => (
<RichRow key={option.value} state={state} index={i} option={option}>
<span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_oklab,var(--color-primary)_16%,transparent)] text-[11px] font-semibold text-foreground">
{initials(option.label)}
</span>
<span className="flex-1 truncate">{option.label}</span>
</RichRow>
))
)}
</div>
</RichField>
)
}
/* DescriptionCombobox: a two-line row; title plus a secondary description. */
export function DescriptionCombobox(props: ComboboxProps) {
const { className, size = "md", placeholder = "Search framework..." } = props
const state = useCombobox(props)
const { filtered } = state
return (
<RichField state={state} size={size} className={className} placeholder={placeholder}>
<div className={listBase}>
{filtered.length === 0 ? (
<p className={emptyBase}>No results found.</p>
) : (
filtered.map((option, i) => (
<RichRow key={option.value} state={state} index={i} option={option}>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate font-medium">{option.label}</span>
<span className="truncate text-xs text-muted-foreground">
{metaFor(option.value).description}
</span>
</span>
</RichRow>
))
)}
</div>
</RichField>
)
}
/* BadgeCombobox: satirin sagina token bir rozet asilir. */
export function BadgeCombobox(props: ComboboxProps) {
const { className, size = "md", placeholder = "Search framework..." } = props
const state = useCombobox(props)
const { filtered } = state
return (
<RichField state={state} size={size} className={className} placeholder={placeholder}>
<div className={listBase}>
{filtered.length === 0 ? (
<p className={emptyBase}>No results found.</p>
) : (
filtered.map((option, i) => (
<RichRow key={option.value} state={state} index={i} option={option}>
<span className="flex-1 truncate">{option.label}</span>
<span className="shrink-0 rounded-md border border-border bg-secondary px-1.5 py-0.5 text-[11px] font-medium text-secondary-foreground">
{metaFor(option.value).badge}
</span>
</RichRow>
))
)}
</div>
</RichField>
)
}
/* MediaCombobox: a square media card on a token surface carrying an inline SVG. */
export function MediaCombobox(props: ComboboxProps) {
const { className, size = "md", placeholder = "Search framework..." } = props
const state = useCombobox(props)
const { filtered } = state
return (
<RichField state={state} size={size} className={className} placeholder={placeholder}>
<div className={listBase}>
{filtered.length === 0 ? (
<p className={emptyBase}>No results found.</p>
) : (
filtered.map((option, i) => (
<RichRow key={option.value} state={state} index={i} option={option}>
<span className="flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-md border border-border bg-[color-mix(in_oklab,var(--color-foreground)_6%,transparent)]">
<svg
viewBox="0 0 24 24"
aria-hidden="true"
className="size-5 text-muted-foreground"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<rect x="3" y="4" width="18" height="16" rx="2" />
<path d="m3 15 5-5 4 4 3-3 6 6" />
<circle cx="8.5" cy="8.5" r="1.25" />
</svg>
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate font-medium">{option.label}</span>
<span className="truncate text-xs text-muted-foreground">
{metaFor(option.value).description}
</span>
</span>
</RichRow>
))
)}
</div>
</RichField>
)
}
/* GroupCombobox: the rows are clustered under headings. The filter preserves the flat index, so the arrow keys move across groups without interruption. */
export function GroupCombobox(props: ComboboxProps) {
const { className, size = "md", placeholder = "Search framework..." } = props
const state = useCombobox(props)
const { filtered } = state
/* Group while preserving the flat index. */
const groups = React.useMemo(() => {
const out: { name: string; items: { option: ComboboxOption; index: number }[] }[] = []
filtered.forEach((option, index) => {
const name = metaFor(option.value).group
const bucket = out.find((g) => g.name === name)
if (bucket) bucket.items.push({ option, index })
else out.push({ name, items: [{ option, index }] })
})
return out
}, [filtered])
return (
<RichField state={state} size={size} className={className} placeholder={placeholder}>
<div className={listBase}>
{filtered.length === 0 ? (
<p className={emptyBase}>No results found.</p>
) : (
groups.map((group) => (
<div key={group.name} role="group" aria-label={group.name}>
<p className={groupLabel}>{group.name}</p>
{group.items.map(({ option, index }) => (
<RichRow key={option.value} state={state} index={index} option={option}>
<span className="flex-1 truncate">{option.label}</span>
</RichRow>
))}
</div>
))
)}
</div>
</RichField>
)
}Manual installs skip the @ai2/tokens theme, so add the token CSS from the theming guide or the tone colors will be missing.
Variations
5 takes on the same idea. Each is its own export, and every one accepts a size prop (sm, md, lg, xl) aligned to the base Button scale.
Avatar
Each row leads with an initials avatar on a token surface.
import { AvatarCombobox } from "@/components/ui/combobox-rich"
<AvatarCombobox />Description
Two-line rows: a title over a secondary line.
import { DescriptionCombobox } from "@/components/ui/combobox-rich"
<DescriptionCombobox />Badge
A token badge sits at the end of every row.
import { BadgeCombobox } from "@/components/ui/combobox-rich"
<BadgeCombobox />Media
A square media tile drawn with inline SVG.
import { MediaCombobox } from "@/components/ui/combobox-rich"
<MediaCombobox />Group
Rows cluster under section headings.
import { GroupCombobox } from "@/components/ui/combobox-rich"
<GroupCombobox />ai2 Rich comboboxes: 5 styled variations on the token system
The ai2 Rich comboboxes are a set of 5 decorative button variations from the styled layer of the @ai2 design system, built around searchable selects with richer option rows. They are free and MIT licensed, and every color comes from a semantic token, so they theme with the rest of ai2 in light and dark.
Motion runs on framer-motion: framer-motion fades and scales the option panel in from the input. The styled layer is opt-in, so the dependency only lands if you use it; the base components stay lean. Under reduced motion, the scale is skipped and the panel appears instantly.
What is in the ai2 Rich comboboxes?
5 exports in one file: Avatar, Description, Badge, Media and Group. Each renders a native button and takes a size prop (sm, md, lg, xl) aligned to the base Button. They are separate from the base Button on purpose: the base keeps its clean variant, tone and size axes, while the styled layer carries the effects.
You own the file. Copy the one category file and you have all 5 variations, with no runtime dependency on ai2 itself.
Why use it
- On-system by construction: Every color resolves to an ai2 semantic token, so the buttons follow your theme in light and dark with no extra work.
- Effect without the sprawl: The decorations live in a dedicated styled file, so the base Button keeps its clean, predictable API.
- Accessible and honest: Each renders a real button element, keeps a visible focus ring, and respects prefers-reduced-motion.
Features
- Token-driven color: No hardcoded hex or oklch; the look recolors with your theme tokens.
- framer-motion: framer-motion fades and scales the option panel in from the input.
- Reduced-motion aware: Under prefers-reduced-motion, the scale is skipped and the panel appears instantly.
- Size aligned to the base: Every variation takes sm, md, lg and xl matching the base Button height scale, so styled and base buttons line up in a row.
Production tips
- Use it for emphasis, not everywhere: Styled buttons draw the eye. Reserve them for the one action you want people to take on a screen, and use the base Button for the rest.
- Keep labels as verbs: The decoration adds weight, so a clear action label keeps the button scannable.
- Pick one variation per surface: The variations share a family; using two different ones in the same view competes for attention.
Works with the rest of ai2
The Rich comboboxes sit alongside the base Button and the rest of the @ai2 registry. They share the same token file, so a styled action next to a base button or a badge stays visually consistent in both modes.