Search dialog
Command-K dialog that searches a Pagefind index, with keyboard navigation.
<SearchDialog label="Search docs" />Installation
CLI
pnpm dlx shadcn@latest add @riff/search-dialogManual
Install UI SDK
pnpm add @ui-sdk/react @ui-sdk/coreCopy the component
Save this as
components/ui/search-dialog.tsx:'use client'; import { useEffect, useId, useRef, useState, type KeyboardEvent } from 'react'; import { Dialog, DialogBackdrop, DialogClose, DialogContent, DialogDescription, DialogShortcut, DialogTitle, DialogTrigger, } from '@ui-sdk/react/dialog'; import './search-dialog.css'; export type SearchResult = { id: string; url: string; title: string; /** A snippet as HTML whose matches are wrapped in `<mark>`, as Pagefind returns it. */ excerpt?: string; image?: string; /** Results group under this heading, in the order groups first appear. */ group?: string; }; /** Answers a query; an empty query warms the index and returns nothing. */ export type SearchSource = (query: string) => Promise<SearchResult[]>; type Pagefind = { init?: () => Promise<void>; search: (query: string) => Promise<{ results: { id: string; data: () => Promise<unknown> }[]; } | null>; }; type PagefindData = { url: string; excerpt?: string; meta?: Record<string, unknown>; }; const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null; /** Pagefind's data comes from a script loaded at runtime, so check it here. */ function parseData(value: unknown): PagefindData | null { if (!isRecord(value) || typeof value.url !== 'string') return null; return { url: value.url, ...(typeof value.excerpt === 'string' && { excerpt: value.excerpt }), ...(isRecord(value.meta) && { meta: value.meta }), }; } /** * Searches the Pagefind index your build wrote under `bundlePath`. Pages * group by a `data-pagefind-meta` key (`group` by default), else "Pages". */ export function pagefindSource({ bundlePath = '/pagefind/', limit = 12, groupMeta = 'group', }: { bundlePath?: string; limit?: number; groupMeta?: string; } = {}): SearchSource { let engine: Promise<Pagefind> | null = null; const load = () => { if (!engine) { // An absolute URL keeps bundlers from resolving the runtime script. const url = new URL(`${bundlePath}pagefind.js`, location.origin).href; engine = import(/* @vite-ignore */ /* webpackIgnore: true */ url).then( async (module: Pagefind) => { await module.init?.(); return module; }, ); // A failed load is forgotten, so Retry starts over. engine.catch(() => { engine = null; }); } return engine; }; return async (query) => { const pagefind = await load(); if (!query) return []; const search = await pagefind.search(query); const pages = await Promise.all( (search?.results ?? []).slice(0, limit).map(async (result) => { const data = parseData(await result.data()); if (!data) return null; const meta = data.meta ?? {}; const text = (key: string) => typeof meta[key] === 'string' ? meta[key] : undefined; const page: SearchResult = { id: result.id, url: data.url, title: text('title') ?? data.url, group: text(groupMeta) ?? 'Pages', }; if (data.excerpt) page.excerpt = data.excerpt; const image = text('image'); if (image) page.image = image; return page; }), ); return pages.filter((page) => page !== null); }; } type SearchState = | { status: 'idle' } | { status: 'loading' } | { status: 'error' } | { status: 'ready'; results: SearchResult[] }; type Answer = { term: string; attempt: number; results: SearchResult[] | null }; /** Debounced search that ignores answers a newer query has replaced. */ function useSearch(query: string, source: SearchSource, open: boolean) { const [answer, setAnswer] = useState<Answer>(); const [attempt, setAttempt] = useState(0); const term = query.trim(); useEffect(() => { if (!open) return; // An empty query warms the index as the dialog opens. if (!term) { source('').catch(() => {}); return; } let current = true; const timer = setTimeout(() => { source(term).then( (results) => { if (current) setAnswer({ term, attempt, results }); }, () => { if (current) setAnswer({ term, attempt, results: null }); }, ); }, 120); return () => { current = false; clearTimeout(timer); }; }, [term, source, open, attempt]); let state: SearchState = { status: 'idle' }; if (term) state = { status: 'loading' }; if (term && answer?.term === term && answer.attempt === attempt) state = answer.results ? { status: 'ready', results: answer.results } : { status: 'error' }; return { state, retry: () => setAttempt((value) => value + 1) }; } const NO_RESULTS: SearchResult[] = []; const KEY_SYMBOLS: Record<string, string> = { Shift: '⇧', Alt: '⌥' }; /** * One keycap per key of a formatted shortcut: `⌘⇧K` on Apple platforms, * `Ctrl+Shift+K` elsewhere, with Shift and Alt drawn as their symbols. */ function keysOf(text: string): string[] { if (!text) return []; if (text.includes('+') && text.length > 1) return text.split('+').map((key) => KEY_SYMBOLS[key] ?? key); const modifiers = /^[⌘⇧⌥⌃]*/.exec(text)?.[0] ?? ''; const key = text.slice(modifiers.length); return [...modifiers, ...(key ? [key] : [])]; } /** * A search button that opens a dialog, also with ⌘K or Ctrl+K. Results * group under headings; the arrow keys move through them and Enter opens * one. Searches your Pagefind index unless you pass another `source`. */ export function SearchDialog({ source, label = 'Search', placeholder = 'Search the site…', description = 'Search every page on this site.', shortcut = 'mod+k', open: controlledOpen, onOpenChange, }: { source?: SearchSource; /** The trigger's text and the dialog's title. */ label?: string; placeholder?: string; description?: string; /** Opens the dialog from anywhere on the page. */ shortcut?: string; open?: boolean; onOpenChange?: (open: boolean) => void; }) { const [defaultSource] = useState(() => pagefindSource()); const [ownOpen, setOwnOpen] = useState(false); const open = controlledOpen ?? ownOpen; const setOpen = (next: boolean) => { setOwnOpen(next); onOpenChange?.(next); }; const input = useRef<HTMLInputElement>(null); const scroller = useRef<HTMLDivElement>(null); const listId = useId(); const [query, setQuery] = useState(''); const [selected, setSelected] = useState(0); const { state, retry } = useSearch(query, source ?? defaultSource, open); const results = state.status === 'ready' ? state.results : NO_RESULTS; const groups = new Map<string, SearchResult[]>(); for (const result of results) { const group = result.group ?? 'Results'; groups.set(group, [...(groups.get(group) ?? []), result]); } const ordered = [...groups.values()].flat(); const active = ordered[Math.min(selected, ordered.length - 1)]; const updateQuery = (value: string) => { setQuery(value); setSelected(0); }; const optionId = (result: SearchResult) => `${listId}-${result.id}`; const keyDown = (event: KeyboardEvent<HTMLInputElement>) => { if (event.nativeEvent.isComposing) return; if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); const next = Math.max( 0, Math.min( ordered.length - 1, selected + (event.key === 'ArrowDown' ? 1 : -1), ), ); setSelected(next); const target = ordered[next]; if (target) document .getElementById(optionId(target)) ?.scrollIntoView({ block: 'nearest' }); } if (event.key === 'Enter' && active) { event.preventDefault(); document.getElementById(optionId(active))?.click(); } }; let status = ''; if (state.status === 'loading') status = 'Searching…'; if (state.status === 'ready') status = `${ordered.length} ${ordered.length === 1 ? 'result' : 'results'}`; return ( <Dialog open={open} onOpenChange={setOpen} onOpenChangeComplete={(isOpen) => { if (!isOpen) updateQuery(''); }} > <DialogTrigger className="riff-search-trigger" shortcut={shortcut}> <SearchIcon /> <span>{label}</span> <DialogShortcut className="riff-search-trigger-keys"> {(shortcut) => keysOf(shortcut.text).map((key) => <kbd key={key}>{key}</kbd>) } </DialogShortcut> </DialogTrigger> <DialogBackdrop className="riff-search-backdrop" /> <DialogContent className="riff-search-panel" initialFocus={() => input.current} > <header className="riff-search-header"> <DialogTitle className="riff-search-hidden">{label}</DialogTitle> <DialogDescription className="riff-search-hidden"> {description} </DialogDescription> <div className="riff-search-field"> <SearchIcon /> <input ref={input} type="search" className="riff-search-input" role="combobox" aria-expanded={ordered.length > 0} aria-controls={listId} aria-autocomplete="list" aria-activedescendant={active ? optionId(active) : undefined} aria-label={label} placeholder={placeholder} value={query} autoComplete="off" spellCheck={false} onChange={(event) => updateQuery(event.target.value)} onKeyDown={keyDown} /> <DialogClose className="riff-search-close" aria-label="Close"> <kbd>esc</kbd> </DialogClose> </div> </header> <p className="riff-search-hidden" role="status"> {status} </p> <div ref={scroller} className="riff-search-results" aria-busy={state.status === 'loading'} > {state.status === 'idle' && ( <p className="riff-search-message">Type to search.</p> )} {state.status === 'loading' && ( <p className="riff-search-message">Searching…</p> )} {state.status === 'error' && ( <div className="riff-search-message" role="alert"> <p>Search couldn’t load.</p> <button type="button" className="riff-search-retry" onClick={() => { retry(); input.current?.focus(); }} > Try again </button> </div> )} {state.status === 'ready' && !ordered.length && ( <p className="riff-search-message"> No results for “{query.trim()}”. </p> )} <div id={listId} role="listbox" aria-label="Results"> {[...groups].map(([group, entries]) => ( <div key={group} role="group" aria-label={group}> <p className="riff-search-group" aria-hidden="true"> {group} </p> {entries.map((result) => ( <a key={result.id} id={optionId(result)} href={result.url} role="option" tabIndex={-1} aria-selected={result === active} className="riff-search-result" onPointerMove={() => setSelected(ordered.indexOf(result))} onClick={() => setOpen(false)} > {result.image && ( <img className="riff-search-thumb" src={result.image} alt="" loading="lazy" /> )} <span className="riff-search-text"> <span className="riff-search-title">{result.title}</span> {result.excerpt && ( <span className="riff-search-excerpt" // Pagefind escapes page text and adds only <mark>. // oxlint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: result.excerpt }} /> )} </span> </a> ))} </div> ))} </div> </div> <footer className="riff-search-footer" aria-hidden="true"> <span> <kbd>↵</kbd> open </span> <span> <kbd>↑</kbd> <kbd>↓</kbd> move </span> <span> <kbd>esc</kbd> close </span> <span className="riff-search-count">{status}</span> </footer> </DialogContent> </Dialog> ); } function SearchIcon() { return ( <svg aria-hidden="true" className="riff-search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" > <circle cx="11" cy="11" r="7" /> <path d="m20 20-3.5-3.5" /> </svg> ); }Copy its styles
Save this beside it as
search-dialog.css:/* Host roles first, system colours after: the component reads your theme when it has these properties and stays legible when it does not. */ @layer components { .riff-search-trigger { display: inline-flex; min-width: 18rem; height: 2.75rem; align-items: center; gap: 0.625rem; border: 1px solid var(--color-border, ButtonBorder); border-radius: 999px; padding: 0 0.625rem 0 1rem; background-color: var(--color-background, Field); color: var(--color-muted-foreground, GrayText); font: inherit; font-size: 0.875rem; cursor: pointer; transition: background-color 150ms cubic-bezier(0, 0, 0.2, 1); &:focus-visible { outline: 2px solid var(--color-ring, Highlight); outline-offset: 2px; } } /* One keycap per key. */ .riff-search-trigger-keys { display: inline-flex; margin-inline-start: auto; gap: 0.25rem; & > kbd { display: inline-grid; min-width: 1.5rem; height: 1.5rem; place-items: center; border: 1px solid var(--color-border, ButtonBorder); border-radius: 0.375rem; padding-inline: 0.375rem; background-color: var(--color-muted, ButtonFace); color: var(--color-muted-foreground, GrayText); font-family: inherit; font-size: 0.75rem; font-weight: 500; line-height: 1; } } .riff-search-icon { width: 1rem; height: 1rem; flex: none; } .riff-search-backdrop { position: fixed; z-index: 50; inset: 0; background-color: rgb(0 0 0 / 50%); transition: opacity 200ms cubic-bezier(0.23, 1, 0.32, 1); &:is([data-starting-style], [data-ending-style]) { opacity: 0; } } .riff-search-panel { position: fixed; z-index: 50; top: min(12dvh, 6rem); left: 50%; display: flex; width: min(40rem, calc(100% - 2rem)); max-height: min(34rem, calc(100dvh - 2 * min(12dvh, 6rem))); flex-direction: column; overflow: hidden; border: 1px solid var(--color-border, CanvasText); border-radius: 1rem; background-color: var(--color-popover, Canvas); box-shadow: 0 24px 64px rgb(0 0 0 / 24%); color: var(--color-foreground, CanvasText); translate: -50% 0; transition: opacity 200ms cubic-bezier(0.23, 1, 0.32, 1), translate 200ms cubic-bezier(0.23, 1, 0.32, 1), scale 200ms cubic-bezier(0.23, 1, 0.32, 1); &:is([data-starting-style], [data-ending-style]) { opacity: 0; translate: -50% 0.5rem; scale: 0.98; } &:focus-visible { outline: none; } } .riff-search-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } .riff-search-header { border-bottom: 1px solid var(--color-border, GrayText); } .riff-search-field { display: flex; align-items: center; gap: 0.625rem; padding: 0 0.75rem 0 1rem; color: var(--color-muted-foreground, GrayText); } .riff-search-input { min-width: 0; height: 3.25rem; flex: 1; border: 0; background: none; color: var(--color-foreground, CanvasText); font: inherit; /* 16px keeps iOS from zooming the field. */ font-size: 1rem; outline: none; &::placeholder { color: var(--color-muted-foreground, GrayText); } &::-webkit-search-cancel-button { display: none; } } .riff-search-close { border: 0; padding: 0; background: none; cursor: pointer; &:focus-visible { border-radius: 0.25rem; outline: 2px solid var(--color-ring, Highlight); } } .riff-search-results { min-height: 6rem; flex: 1; overflow-y: auto; overscroll-behavior: contain; padding: 0.5rem; scroll-padding-block: 2rem 0.5rem; } .riff-search-message { display: flex; flex-direction: column; align-items: center; gap: 0.75rem; margin: 0; padding: 2rem 1rem; color: var(--color-muted-foreground, GrayText); font-size: 0.875rem; text-align: center; & > p { margin: 0; } } .riff-search-retry { border: 0; border-radius: 999px; padding: 0.5rem 1rem; background-color: var(--color-foreground, ButtonText); color: var(--color-background, ButtonFace); font: inherit; font-weight: 500; cursor: pointer; } .riff-search-group { margin: 0; padding: 0.5rem 0.5rem 0.25rem; color: var(--color-muted-foreground, GrayText); font-size: 0.75rem; font-weight: 500; } .riff-search-result { display: flex; align-items: center; gap: 0.75rem; border-radius: 0.5rem; padding: 0.5rem; color: inherit; text-decoration: none; &[aria-selected='true'] { background-color: var(--color-muted, Highlight); } } .riff-search-thumb { width: 4rem; height: 2.75rem; flex: none; border-radius: 0.375rem; background-color: var(--color-muted, ButtonFace); object-fit: cover; } .riff-search-text { display: flex; min-width: 0; flex-direction: column; gap: 0.125rem; } .riff-search-title { font-size: 0.875rem; font-weight: 500; } .riff-search-excerpt { display: -webkit-box; overflow: hidden; -webkit-box-orient: vertical; -webkit-line-clamp: 2; color: var(--color-muted-foreground, GrayText); font-size: 0.8125rem; line-height: 1.4; & mark { background: none; color: var(--color-foreground, CanvasText); font-weight: 600; } } .riff-search-footer { display: flex; align-items: center; gap: 1rem; border-top: 1px solid var(--color-border, GrayText); padding: 0.625rem 1rem; color: var(--color-muted-foreground, GrayText); font-size: 0.75rem; & > span { display: inline-flex; align-items: center; gap: 0.25rem; } } .riff-search-panel kbd { border-radius: 0.25rem; padding: 0.0625rem 0.375rem; background-color: var(--color-muted, ButtonFace); color: var(--color-muted-foreground, GrayText); font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.75rem; } .riff-search-count { margin-inline-start: auto; } @media (hover: hover) { .riff-search-trigger:hover { background-color: var(--color-muted, ButtonFace); } } @media (max-width: 39.999rem) { .riff-search-footer > span:not(.riff-search-count) { display: none; } } @media (prefers-reduced-motion: reduce) { .riff-search-trigger, .riff-search-backdrop, .riff-search-panel { transition: none; } } @media (forced-colors: active) { .riff-search-result[aria-selected='true'] { outline: 1px solid Highlight; } .riff-search-input:focus-visible { outline: 2px solid Highlight; } } }
Usage
import { SearchDialog } from '@/components/ui/search-dialog';
<SearchDialog />;It loads /pagefind/pagefind.js the first time it opens, so build your site with Pagefind first. Results group by a data-pagefind-meta key, group by default. Set pagefindSource({ bundlePath, groupMeta }) for another layout, or pass any source that returns results. The demo above answers ⌘/, since this site’s own search takes ⌘K.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
source | (query: string) => Promise<SearchResult[]> | Pagefind | Answers each query. |
label | string | 'Search' | The trigger’s text and the dialog’s title. |
placeholder | string | 'Search the site…' | The field’s placeholder. |
shortcut | string | 'mod+k' | Opens the dialog from anywhere. |
open | boolean | Controls the dialog. | |
onOpenChange | (open: boolean) => void | Called when it opens or closes. |