Search field
A search input with scope picker, clear button, ⌘K focus and hint, loading spinner, debounced search and a recent-searches dropdown with removal.
Preview
- Seat-based pricing toggleissues
- Pricing page copy reviewdocs
Empty, with the ⌘K hint
Plain, loading
Install
Add the editable source with the shadcn CLI. Your project also needs the shared theme tokens this component uses. Setup and requirements. The Pebble installer is not published yet.
npx shadcn@latest add https://pebbleui.com/r/search-field.jsonProps
| Prop | Type | Default | Description |
|---|---|---|---|
| value / defaultValue | string | "" | Query text. |
| onValueChange | (value: string) => void | — | Called on every edit. |
| onSearch | (query, scope) => void | — | Debounced while typing; immediate on Enter, clear or picking a recent. |
| debounce | number | 250 | Delay in ms before onSearch while typing. |
| loading | boolean | false | Spinner in place of the search glyph; sets aria-busy. |
| scopes | { value, label }[] | — | Scope menu before the input. |
| scope / defaultScope / onScopeChange | string | first scope | Selected scope; changing it re-runs the query. |
| recent / defaultRecent / onRecentChange | string[] | [] | Recent searches shown when focused and empty. |
| maxRecent | number | 5 | Recent searches kept. |
| hotkey | boolean | true | ⌘K / Ctrl+K focuses the field; shows the key hint. |
| placeholder | string | "Search…" | Placeholder text. |
Build notes
- Debounce: each keystroke bumps a counter; an effect keyed on it sets a timeout and cleans up the previous one, so only the last keystroke fires. - The ⌘K listener is added in an effect on `window` (SSR-safe). - The Recent list is positioned inside the wrapper (not portalled) so focus never leaves the input; rows prevent mousedown default to keep focus. <!-- PEBBLE-LICENSE -->
View source
registry/input/search-field/search-field.tsx
"use client";
/* PEBBLE-LICENSE
Built by Pebble. Component: search-field.
First-party license: MIT
The following first-party terms apply only to original Pebble material.
MIT License
Copyright (c) 2026 Praxys Solutions LLC (Pebble)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
END PEBBLE-LICENSE */
import * as React from "react";
import { AnimatePresence, MotionConfig, motion } from "motion/react";
import { cn } from "@/lib/utils";
import {
Menu,
MenuContent,
MenuLabel,
MenuRadioGroup,
MenuRadioItem,
MenuTrigger,
} from "@/registry/overlay/menu/menu";
import { Kbd, KbdGroup } from "@/registry/text/kbd/kbd";
export type SearchScope = { value: string; label: string };
export type SearchFieldProps = {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/** Debounced while typing; immediate on Enter or when a recent is picked. */
onSearch?: (query: string, scope: string | undefined) => void;
/** Debounce for onSearch while typing, in ms. */
debounce?: number;
/** Shows a spinner in place of the search glyph and sets aria-busy. */
loading?: boolean;
placeholder?: string;
/** Scope picker shown before the input ("All", "Issues", "People"…). */
scopes?: SearchScope[];
scope?: string;
defaultScope?: string;
onScopeChange?: (scope: string) => void;
/** Recent searches (newest first) shown when the field is focused and empty. */
recent?: string[];
defaultRecent?: string[];
onRecentChange?: (recent: string[]) => void;
maxRecent?: number;
/** Focus the field with ⌘K / Ctrl+K anywhere on the page. */
hotkey?: boolean;
disabled?: boolean;
id?: string;
className?: string;
"aria-label"?: string;
};
function Glyph({ d, className }: { d: React.ReactNode; className?: string }) {
return (
<svg
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth={1.5}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
className={cn("size-4 shrink-0", className)}
>
{d}
</svg>
);
}
const searchPath = (
<>
<circle cx="7.25" cy="7.25" r="4.25" />
<path d="m10.5 10.5 3 3" />
</>
);
export function SearchField({
value: valueProp,
defaultValue = "",
onValueChange,
onSearch,
debounce = 250,
loading = false,
placeholder = "Search…",
scopes,
scope: scopeProp,
defaultScope,
onScopeChange,
recent: recentProp,
defaultRecent = [],
onRecentChange,
maxRecent = 5,
hotkey = true,
disabled = false,
id,
className,
"aria-label": ariaLabel = "Search",
}: SearchFieldProps) {
const uid = React.useId();
const listId = `${uid}-recent`;
const inputRef = React.useRef<HTMLInputElement>(null);
const [internal, setInternal] = React.useState(defaultValue);
const value = valueProp ?? internal;
const [scopeState, setScopeState] = React.useState(defaultScope ?? scopes?.[0]?.value);
const scope = scopeProp ?? scopeState;
const [recentState, setRecentState] = React.useState(defaultRecent);
const recent = recentProp ?? recentState;
const [focused, setFocused] = React.useState(false);
const [active, setActive] = React.useState(-1);
const [dismissed, setDismissed] = React.useState(false);
// Bumped on each keystroke; the effect below debounces onSearch from it.
const [typed, setTyped] = React.useState(0);
const setValue = (v: string) => {
setInternal(v);
onValueChange?.(v);
};
const setRecent = (r: string[]) => {
setRecentState(r);
onRecentChange?.(r);
};
React.useEffect(() => {
if (!typed) return;
const t = setTimeout(() => onSearch?.(value, scope), debounce);
return () => clearTimeout(t);
// Debounce only on typing; value/scope are read at fire time.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [typed]);
React.useEffect(() => {
if (!hotkey) return;
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
inputRef.current?.focus();
inputRef.current?.select();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [hotkey]);
const submit = (q: string) => {
const query = q.trim();
setTyped(0);
onSearch?.(query, scope);
if (query) setRecent([query, ...recent.filter((r) => r !== query)].slice(0, maxRecent));
};
const open = focused && !dismissed && !value && recent.length > 0;
const activeIndex = active < recent.length ? active : -1;
const removeRecent = (r: string) => {
setRecent(recent.filter((x) => x !== r));
inputRef.current?.focus();
};
return (
<MotionConfig reducedMotion="user">
<div data-slot="search-field" className={cn("relative w-full", className)}>
<div
aria-busy={loading || undefined}
className={cn(
"group/search flex h-9 items-center rounded-md border border-border-control bg-card inset-shadow-xs",
"transition-[border-color,box-shadow] duration-(--motion-fast) hover:border-muted-foreground",
"has-[input:focus-visible]:border-muted-foreground has-[input:focus-visible]:ring-2 has-[input:focus-visible]:ring-ring has-[input:focus-visible]:ring-offset-2 has-[input:focus-visible]:ring-offset-background",
disabled && "pointer-events-none bg-muted opacity-50",
)}
>
{scopes && scopes.length > 0 && (
<>
<Menu>
<MenuTrigger asChild>
<button
type="button"
disabled={disabled}
aria-label={`Search in: ${scopes.find((s) => s.value === scope)?.label ?? ""}`}
data-slot="search-scope"
className="ms-1 inline-flex h-7 shrink-0 cursor-pointer items-center gap-1 rounded-[5px] px-2 text-[13px] font-medium text-foreground transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none data-[state=open]:bg-muted"
>
{scopes.find((s) => s.value === scope)?.label}
<Glyph
d={<path d="M5 6.5 8 9.5l3-3" />}
className="size-3.5 text-muted-foreground"
/>
</button>
</MenuTrigger>
<MenuContent align="start" className="w-40">
<MenuLabel>Search in</MenuLabel>
<MenuRadioGroup
value={scope}
onValueChange={(v) => {
setScopeState(v);
onScopeChange?.(v);
if (value) onSearch?.(value, v);
}}
>
{scopes.map((s) => (
<MenuRadioItem key={s.value} value={s.value}>
{s.label}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuContent>
</Menu>
<span aria-hidden className="mx-0.5 h-5 w-px bg-border" />
</>
)}
<span className="grid w-8 shrink-0 place-items-center text-muted-foreground transition-colors group-focus-within/search:text-foreground">
{loading ? (
<span
aria-hidden
data-slot="search-spinner"
className="size-3.5 animate-spin rounded-full border-[1.5px] border-current border-r-transparent motion-reduce:animate-none"
/>
) : (
<Glyph d={searchPath} />
)}
</span>
<input
ref={inputRef}
id={id}
type="search"
role="combobox"
aria-label={ariaLabel}
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={
open && activeIndex >= 0 ? `${listId}-${activeIndex}` : undefined
}
enterKeyHint="search"
autoComplete="off"
spellCheck={false}
disabled={disabled}
placeholder={placeholder}
value={value}
onChange={(e) => {
setValue(e.target.value);
setActive(-1);
setTyped((n) => n + 1);
}}
onFocus={() => {
setFocused(true);
setDismissed(false);
}}
onBlur={() => setFocused(false)}
onKeyDown={(e) => {
if (open && (e.key === "ArrowDown" || e.key === "ArrowUp")) {
e.preventDefault();
// Cycle through the items and back to the input (-1).
const step = e.key === "ArrowDown" ? 1 : -1;
const n = recent.length + 1;
setActive(((activeIndex + 1 + step + n) % n) - 1);
} else if (e.key === "Enter") {
e.preventDefault();
if (open && activeIndex >= 0) {
const q = recent[activeIndex];
setValue(q);
submit(q);
} else submit(value);
} else if (e.key === "Delete" && e.shiftKey && open && activeIndex >= 0) {
e.preventDefault();
removeRecent(recent[activeIndex]);
} else if (e.key === "Escape") {
if (value) {
e.preventDefault();
setValue("");
submit("");
} else if (open) {
e.preventDefault();
setDismissed(true);
}
}
}}
className="h-full w-0 min-w-0 flex-1 bg-transparent pe-2 text-base text-foreground outline-none placeholder:text-muted-foreground md:text-sm [&::-webkit-search-cancel-button]:hidden"
/>
<AnimatePresence initial={false} mode="popLayout">
{value ? (
<motion.button
key="clear"
type="button"
aria-label="Clear search"
initial={{ opacity: 0, scale: 0.7 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.7 }}
transition={{ duration: 0.12 }}
onClick={() => {
setValue("");
submit("");
inputRef.current?.focus();
}}
className="me-1 grid size-7 shrink-0 cursor-pointer place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
>
<Glyph d={<path d="m4.5 4.5 7 7m0-7-7 7" />} className="size-3.5" />
</motion.button>
) : hotkey ? (
<motion.span
key="hint"
initial={{ opacity: 0 }}
animate={{ opacity: focused ? 0 : 1 }}
exit={{ opacity: 0 }}
aria-hidden
className="me-2 shrink-0"
>
<KbdGroup>
<Kbd>⌘</Kbd>
<Kbd>K</Kbd>
</KbdGroup>
</motion.span>
) : null}
</AnimatePresence>
</div>
<AnimatePresence>
{open && (
<motion.div
key="recent"
initial={{ opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.14, ease: [0.22, 1, 0.36, 1] }}
className="absolute inset-x-0 top-full z-50 mt-1.5 rounded-lg bg-card p-1 shadow-raised-lg ring-1 inset-shadow-highlight ring-hairline"
>
<div className="flex items-center justify-between px-2 pt-1 pb-1.5">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">
Recent
</span>
<button
type="button"
tabIndex={-1}
onMouseDown={(e) => e.preventDefault()}
onClick={() => setRecent([])}
className="cursor-pointer rounded px-1 text-[11px] text-muted-foreground hover:text-foreground"
>
Clear all
</button>
</div>
<ul id={listId} role="listbox" aria-label="Recent searches">
{recent.map((r, i) => (
<li
key={r}
id={`${listId}-${i}`}
role="option"
aria-selected={i === activeIndex}
onMouseDown={(e) => e.preventDefault()}
onMouseMove={() => setActive(i)}
onClick={() => {
setValue(r);
submit(r);
}}
className={cn(
"group/item flex h-8 cursor-pointer items-center gap-2 rounded-md ps-2 pe-1 text-[13px]",
i === activeIndex && "bg-muted",
)}
>
<Glyph
d={
<>
<path d="M2.75 8a5.25 5.25 0 1 0 1.5-3.7" />
<path d="M2.5 2.75v2.5H5M8 5.25V8l1.75 1.25" />
</>
}
className="size-3.5 text-muted-foreground"
/>
<span className="flex-1 truncate">{r}</span>
<button
type="button"
tabIndex={-1}
aria-label={`Remove “${r}” from recent searches`}
onMouseDown={(e) => e.preventDefault()}
onClick={(e) => {
e.stopPropagation();
removeRecent(r);
}}
className="grid size-6 cursor-pointer place-items-center rounded-md text-muted-foreground opacity-0 transition-opacity group-hover/item:opacity-100 group-aria-selected/item:opacity-100 hover:bg-card hover:text-foreground"
>
<Glyph d={<path d="m4.5 4.5 7 7m0-7-7 7" />} className="size-3" />
</button>
</li>
))}
</ul>
<p className="px-2 pt-1.5 pb-1 text-[11px] text-muted-foreground">
Shift + Delete removes the highlighted search.
</p>
</motion.div>
)}
</AnimatePresence>
</div>
</MotionConfig>
);
}
