Morphing Search
A search field or icon that morphs into a panel of results.
Preview
"use client";
import { Blocks, BookOpen, Bot, FolderOpen, Palette } from "lucide-react";
import {
MorphingSearch,
type MorphingSearchItem,
} from "@/components/motion/morphing-search";
const ITEMS: MorphingSearchItem[] = [
{
id: "project-folder",
title: "Project Folder",
description: "Block · Files and previews",
keywords: ["files", "overlay"],
icon: FolderOpen,
},
{
id: "motion-components",
title: "Motion components",
description: "Collection · Interaction primitives",
keywords: ["animation", "components"],
icon: Blocks,
},
{
id: "agent-interfaces",
title: "Agent interfaces",
description: "Collection · AI building blocks",
keywords: ["ai", "chat"],
icon: Bot,
},
{
id: "installation",
title: "Installation guide",
description: "Documentation · Add your first component",
keywords: ["setup", "shadcn"],
icon: BookOpen,
},
{
id: "design-tokens",
title: "Design tokens",
description: "Documentation · Color, type, and motion",
keywords: ["theme", "styles"],
icon: Palette,
},
];
export function MorphingSearchPreview() {
return (
<div className="flex w-full max-w-[22rem] items-center gap-3">
<MorphingSearch items={ITEMS} placeholder="Find components" />
<MorphingSearch
items={ITEMS}
placeholder="Find components"
shortcut=""
iconOnly
/>
</div>
);
}
"use client";
// beui.dev/components/blocks/morphing-search/overlay
import { type LucideIcon, Search } from "lucide-react";
import {
AnimatePresence,
LayoutGroup,
motion,
type Transition,
useReducedMotion,
} from "motion/react";
import {
type KeyboardEvent as ReactKeyboardEvent,
useCallback,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { EASE_OUT, SPRING_LAYOUT } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useOnOpen } from "@/lib/hooks/use-on-open";
import { useRowCursor } from "@/lib/hooks/use-row-cursor";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
// Keeps the Wallet Card feel with a little more time to read the morph.
const SEARCH_MORPH: Transition = {
type: "spring",
duration: 0.58,
bounce: 0.22,
};
// Keep the spring on the shell, but unfold complex clip-path values with the
// same progressive tween as Morph Popover so the content never snaps ahead.
const SEARCH_CLIP_TRANSITION: Transition = {
duration: 0.32,
ease: EASE_OUT,
};
export type MorphingSearchItem = {
/** Unique key for the result row. */
id: string;
/** Main text of the result row, matched by the search. */
title: string;
/** Smaller text under the title, also matched by the search. */
description?: string;
/** Extra words the search matches that are not shown. */
keywords?: string[];
/** Lucide icon component shown before the title. Omitted when not set. */
icon?: LucideIcon;
/** Called when this result is chosen, before the search's `onSelect`. */
onSelect?: () => void;
};
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const morphingSearchMessages = {
placeholder: "Search",
empty: "No results found.",
close: "Close search",
dialog: "Search",
results: "Search results",
};
export type MorphingSearchMessages = typeof morphingSearchMessages;
export interface MorphingSearchProps {
/** Searchable items, matched on title, description and keywords. */
items: MorphingSearchItem[];
/** Input placeholder and accessible name. Default: "Search" */
placeholder?: string;
/** Opens the search when this key is pressed outside a text field. Default: "f" */
shortcut?: string;
/** Render the closed trigger as a compact search icon. */
iconOnly?: boolean;
/** Text shown when no item matches the query. Default: "No results found." */
emptyMessage?: string;
/** Whether the search panel is open, for controlled use. */
open?: boolean;
/** Whether the panel starts open when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new open state when the panel opens or closes. */
onOpenChange?: (open: boolean) => void;
/** Called with the query text as the user types. */
onQueryChange?: (query: string) => void;
/** Called with the chosen item after its own `onSelect`, then the panel closes. */
onSelect?: (item: MorphingSearchItem) => void;
/** Override any built-in string. */
labels?: Partial<MorphingSearchMessages>;
/** Classes merged onto the closed trigger wrapper. */
className?: string;
}
type AnchorRect = {
top: number;
left: number;
width: number;
};
function isEditableTarget(target: EventTarget | null) {
if (!(target instanceof HTMLElement)) return false;
return (
target.isContentEditable ||
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement
);
}
export function MorphingSearch({
items,
placeholder: placeholderProp,
shortcut = "f",
iconOnly = false,
emptyMessage: emptyMessageProp,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
onQueryChange,
onSelect,
labels,
className,
}: MorphingSearchProps) {
const t = useMessages("morphingSearch", morphingSearchMessages, labels);
const placeholder = placeholderProp ?? t("placeholder");
const emptyMessage = emptyMessageProp ?? t("empty");
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [query, setQuery] = useState("");
const [mounted, setMounted] = useState(false);
const [backgroundScrollLocked, setBackgroundScrollLocked] =
useState(defaultOpen);
const [anchorRect, setAnchorRect] = useState<AnchorRect>({
top: 16,
left: 16,
width: 288,
});
const open = controlledOpen ?? internalOpen;
const controlled = controlledOpen !== undefined;
const reduce = useReducedMotion();
const uid = useId();
const anchorRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const dialogRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
const wasOpenRef = useRef(open);
const transition: Transition = reduce ? { duration: 0 } : SPRING_LAYOUT;
const morphTransition: Transition = reduce ? { duration: 0 } : SEARCH_MORPH;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const measureAnchor = useCallback(() => {
const rect = anchorRef.current?.getBoundingClientRect();
if (!rect || rect.width === 0) return;
setAnchorRect({ top: rect.top, left: rect.left, width: rect.width });
}, []);
const openSearch = useCallback(() => {
measureAnchor();
previousFocusRef.current =
document.activeElement instanceof HTMLElement
? document.activeElement
: null;
setOpen(true);
}, [measureAnchor, setOpen]);
const filteredItems = useMemo(() => {
const needle = query.trim().toLowerCase();
if (!needle) return items;
return items.filter((item) =>
[item.title, item.description ?? "", ...(item.keywords ?? [])]
.join(" ")
.toLowerCase()
.includes(needle),
);
}, [items, query]);
const { activeIndex, moveTo, moveActive } = useRowCursor(filteredItems, query);
// The cursor is stamped with the query, so changing it drops the highlight
// without this having to say so.
const updateQuery = useCallback(
(next: string) => {
setQuery(next);
onQueryChange?.(next);
},
[onQueryChange],
);
const closeSearch = useCallback(() => {
updateQuery("");
setOpen(false);
}, [setOpen, updateQuery]);
useEffect(() => setMounted(true), []);
useEffect(() => {
if (open) setBackgroundScrollLocked(true);
}, [open]);
useEffect(() => {
measureAnchor();
const anchor = anchorRef.current;
const observer =
anchor && typeof ResizeObserver !== "undefined"
? new ResizeObserver(measureAnchor)
: null;
if (anchor) observer?.observe(anchor);
window.addEventListener("resize", measureAnchor);
document.addEventListener("scroll", measureAnchor, true);
window.visualViewport?.addEventListener("resize", measureAnchor);
window.visualViewport?.addEventListener("scroll", measureAnchor);
return () => {
observer?.disconnect();
window.removeEventListener("resize", measureAnchor);
document.removeEventListener("scroll", measureAnchor, true);
window.visualViewport?.removeEventListener("resize", measureAnchor);
window.visualViewport?.removeEventListener("scroll", measureAnchor);
};
}, [measureAnchor]);
useEffect(() => {
if (!backgroundScrollLocked) return;
const preventBackgroundWheel = (event: WheelEvent) => {
const target = event.target;
if (target instanceof Node && listRef.current?.contains(target)) return;
event.preventDefault();
};
const preventBackgroundTouch = (event: TouchEvent) => {
const target = event.target;
if (target instanceof Node && listRef.current?.contains(target)) return;
event.preventDefault();
};
document.addEventListener("wheel", preventBackgroundWheel, {
passive: false,
});
document.addEventListener("touchmove", preventBackgroundTouch, {
passive: false,
});
return () => {
document.removeEventListener("wheel", preventBackgroundWheel);
document.removeEventListener("touchmove", preventBackgroundTouch);
};
}, [backgroundScrollLocked]);
// The backdrop handles presses; this is Escape, answered only while the
// search is the innermost open layer.
useDismiss(open, closeSearch, dialogRef, { outsidePress: false });
useEffect(() => {
const handleShortcut = (event: KeyboardEvent) => {
if (
!open &&
shortcut &&
event.key.toLowerCase() === shortcut.toLowerCase() &&
!event.repeat &&
!event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
!event.shiftKey &&
!isEditableTarget(event.target)
) {
event.preventDefault();
openSearch();
}
};
window.addEventListener("keydown", handleShortcut);
return () => window.removeEventListener("keydown", handleShortcut);
}, [open, openSearch, shortcut]);
// Only this component's own state. Telling the consumer the query changed is
// a side effect, so it waits for the effect below.
useOnOpen(open, () => {
setQuery("");
moveTo(null);
});
// Keyed to `open` alone. `onQueryChange` is read through a ref because an
// inline one changes identity on every keystroke, and this effect clearing
// the field on every keystroke is exactly what that costs. Written after
// commit for the reason `lib/hooks/use-row-cursor.ts` gives at length.
const notifyQuery = useRef(onQueryChange);
useLayoutEffect(() => {
notifyQuery.current = onQueryChange;
});
useEffect(() => {
if (open) {
notifyQuery.current?.("");
const frame = requestAnimationFrame(() => inputRef.current?.focus());
return () => cancelAnimationFrame(frame);
}
if (wasOpenRef.current) {
const frame = requestAnimationFrame(() => {
const previousFocus = previousFocusRef.current;
const focusTarget = previousFocus?.isConnected
? previousFocus
: triggerRef.current;
focusTarget?.focus();
});
return () => cancelAnimationFrame(frame);
}
}, [open]);
useEffect(() => {
wasOpenRef.current = open;
}, [open]);
useEffect(() => {
if (!open) return;
listRef.current
?.querySelector<HTMLElement>(`[data-index="${activeIndex}"]`)
?.scrollIntoView({ block: "nearest" });
}, [activeIndex, open]);
const selectItem = useCallback(
(item: MorphingSearchItem) => {
item.onSelect?.();
onSelect?.(item);
closeSearch();
},
[closeSearch, onSelect],
);
const handleDialogKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowDown") {
event.preventDefault();
moveActive(1);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
moveActive(-1);
return;
}
if (event.key === "Enter") {
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
event.preventDefault();
const item = filteredItems[activeIndex];
if (item) selectItem(item);
return;
}
if (event.key !== "Tab" || !dialogRef.current) return;
const focusable = Array.from(
dialogRef.current.querySelectorAll<HTMLElement>(
'input, button:not([disabled]), [tabindex]:not([tabindex="-1"])',
),
);
const first = focusable[0];
const last = focusable.at(-1);
if (!first || !last) return;
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
const shellLayoutId = `${uid}-shell`;
const listboxId = `${uid}-results`;
const panelWidth = mounted
? Math.max(
anchorRect.width,
Math.min(448, window.innerWidth - anchorRect.left - 16),
)
: anchorRect.width;
const resultsHeight = mounted
? Math.max(96, Math.min(288, window.innerHeight - anchorRect.top - 80))
: 288;
const collapsedContentClip = `inset(0px ${Math.max(
0,
panelWidth - anchorRect.width,
)}px ${resultsHeight}px 0px round 24px)`;
const expandedContentClip = "inset(0px 0px 0px 0px round 16px)";
// Neither grouping layer carries a box: they only hold `inert`/`aria-hidden`,
// the z-index and the presence key, and every child below is `fixed` and
// resolves against the viewport itself. The click catcher spans the viewport
// edges but has no children and filters nothing, so it is not a sampling
// layer either.
const overlay = mounted
? createPortal(
<div
aria-hidden={!open}
inert={!open}
className="pointer-events-none fixed left-0 top-0 z-50 size-0"
>
<AnimatePresence
initial={false}
mode="popLayout"
onExitComplete={() => setBackgroundScrollLocked(false)}
>
{open ? (
<motion.div
key="morphing-search-overlay"
className="fixed left-0 top-0 size-0"
>
<button
type="button"
aria-label={t("close")}
className="pointer-events-auto fixed inset-0 cursor-default bg-transparent"
onClick={closeSearch}
/>
<motion.div
layoutId={shellLayoutId}
aria-hidden="true"
className="fixed z-10 rounded-2xl bg-background/90 backdrop-blur-xl"
style={{
top: anchorRect.top,
left: anchorRect.left,
width: panelWidth,
height: 48 + resultsHeight,
boxShadow: "inset 0 0 0 1px var(--color-border)",
}}
transition={morphTransition}
/>
<motion.div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-label={t("dialog")}
onKeyDown={handleDialogKeyDown}
initial={
reduce
? false
: { opacity: 0, clipPath: collapsedContentClip }
}
animate={{ opacity: 1, clipPath: expandedContentClip }}
exit={{
opacity: 0,
clipPath: collapsedContentClip,
transition: reduce
? { duration: 0 }
: {
clipPath: SEARCH_CLIP_TRANSITION,
opacity: SEARCH_MORPH,
},
}}
transition={
reduce
? { duration: 0 }
: {
clipPath: SEARCH_CLIP_TRANSITION,
opacity: SEARCH_MORPH,
}
}
className="pointer-events-auto fixed z-20 overflow-hidden rounded-2xl"
style={{
top: anchorRect.top,
left: anchorRect.left,
width: panelWidth,
}}
>
<div
className={cn(
"flex h-12 items-center gap-2.5 border-b border-border",
iconOnly ? "px-4" : "px-3.5",
)}
>
<span className="shrink-0">
<Search className="size-4 text-muted-foreground" />
</span>
<div className="flex h-10 min-w-0 flex-1 items-center">
<input
ref={inputRef}
value={query}
onChange={(event) => updateQuery(event.target.value)}
role="combobox"
aria-label={placeholder}
aria-expanded="true"
aria-controls={listboxId}
aria-autocomplete="list"
aria-activedescendant={
filteredItems.length > 0
? `${uid}-option-${activeIndex}`
: undefined
}
placeholder={placeholder}
className="size-full bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground"
/>
</div>
<kbd className="flex h-7 shrink-0 items-center rounded-md border border-border px-2 text-xs text-muted-foreground">
Esc
</kbd>
</div>
<motion.div
ref={listRef}
id={listboxId}
role="listbox"
aria-label={t("results")}
transition={reduce ? { duration: 0 } : undefined}
variants={
reduce
? undefined
: {
closed: {
opacity: 0,
transform: "translateY(6px)",
transition: {
duration: 0.16,
delay: 0.18,
ease: EASE_OUT,
},
},
open: {
opacity: 1,
transform: "translateY(0px)",
transition: {
duration: 0.16,
ease: EASE_OUT,
},
},
}
}
initial={
reduce
? { opacity: 1, transform: "translateY(0px)" }
: "closed"
}
animate={
reduce
? { opacity: 1, transform: "translateY(0px)" }
: "open"
}
exit={reduce ? undefined : "closed"}
className="overscroll-contain overflow-y-auto p-2"
style={{
maxHeight: resultsHeight,
}}
>
{filteredItems.length > 0 ? (
filteredItems.map((item, index) => {
const Icon = item.icon;
const active = index === activeIndex;
return (
<button
key={item.id}
id={`${uid}-option-${index}`}
type="button"
role="option"
aria-selected={active}
data-index={index}
onMouseMove={() => {
if (!active) moveTo(item.id);
}}
onFocus={() => moveTo(item.id)}
onClick={() => selectItem(item)}
className="relative flex w-full items-center gap-2.5 rounded-full px-4 py-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
>
{active ? (
<motion.span
layoutId={`${uid}-active-result`}
className="absolute inset-0 rounded-full bg-foreground/5"
transition={transition}
/>
) : null}
{Icon ? (
<Icon className="relative size-4 shrink-0 text-muted-foreground" />
) : null}
<span className="relative min-w-0">
<span className="block truncate text-sm font-medium text-foreground">
{item.title}
</span>
{item.description ? (
<span className="block truncate text-xs text-muted-foreground">
{item.description}
</span>
) : null}
</span>
</button>
);
})
) : (
<p className="px-3 py-8 text-center text-sm text-muted-foreground">
{emptyMessage}
</p>
)}
</motion.div>
</motion.div>
</motion.div>
) : null}
</AnimatePresence>
</div>,
document.body,
)
: null;
return (
<LayoutGroup id={uid}>
<div
ref={anchorRef}
className={cn(
"relative",
iconOnly ? "size-12" : "h-12 w-72 max-w-full",
className,
)}
>
{!open ? (
<motion.button
ref={triggerRef}
layoutId={shellLayoutId}
type="button"
aria-haspopup="dialog"
aria-expanded="false"
aria-label={placeholder}
onClick={openSearch}
transition={morphTransition}
style={{
boxShadow: "inset 0 0 0 1px var(--search-trigger-stroke)",
}}
className={cn(
"flex size-full items-center rounded-full bg-background/60 text-left backdrop-blur-md outline-none [--search-trigger-stroke:var(--color-border)] hover:[--search-trigger-stroke:var(--color-border-strong)] focus-visible:ring-2 focus-visible:ring-ring",
iconOnly ? "cursor-pointer justify-center" : "cursor-text px-3.5",
)}
></motion.button>
) : null}
<motion.div
aria-hidden="true"
initial={false}
animate={{ opacity: open ? 0 : 1 }}
transition={
reduce
? { duration: 0 }
: {
duration: 0.1,
delay: open ? 0.1 : 0.12,
ease: EASE_OUT,
}
}
className={cn(
"pointer-events-none absolute inset-0 flex items-center",
backgroundScrollLocked && "z-[60]",
iconOnly ? "justify-center" : "gap-2.5 px-3.5",
)}
>
<Search className="size-4 shrink-0 text-muted-foreground" />
{iconOnly ? null : (
<>
<span className="min-w-0 flex-1 truncate text-sm text-muted-foreground">
{placeholder}
</span>
{shortcut ? (
<kbd className="flex h-7 min-w-7 shrink-0 items-center justify-center rounded-md border border-border px-2 text-xs text-muted-foreground">
{shortcut.toUpperCase()}
</kbd>
) : null}
</>
)}
</motion.div>
</div>
{overlay}
</LayoutGroup>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
"use client";
import { type RefObject, useEffect, useLayoutEffect, useRef } from "react";
import { inOtherLayer, type Layer, openLayer, ownsEscape } from "@/lib/layers";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */
export type DismissReason = "escape" | "pointer" | "focus";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */
focusOutside?: boolean;
/**
* Dismiss on a pointerdown outside. Default true. Turn it off for an overlay
* whose own backdrop handles presses and only needs Escape and layering.
*/
outsidePress?: boolean;
/** Return true for an outside target that should *not* dismiss. */
ignore?: (target: Element) => boolean;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over.
*
* Each open dismissal is a layer in `lib/layers.ts`, so only the innermost
* open overlay answers Escape (a menu inside a drawer closes, the drawer
* stays), and a drawer's focus trap leaves focus in a menu it portaled out.
*/
export function useDismiss(
open: boolean,
onDismiss: (reason: DismissReason) => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
focusOutside = false,
outsidePress = true,
ignore,
}: DismissOptions = {},
) {
// Read through refs, so a callback rebuilt each render neither re-binds the
// listeners nor moves this layer to the top of the stack.
const dismissRef = useRef(onDismiss);
const ignoreRef = useRef(ignore);
useLayoutEffect(() => {
dismissRef.current = onDismiss;
ignoreRef.current = ignore;
});
useEffect(() => {
if (!open) return;
const inside = (target: Node) =>
Boolean(ref?.current?.contains(target)) ||
(target instanceof Element && Boolean(ignoreRef.current?.(target)));
const layer: Layer = { contains: inside, escape: dismissOnEscape };
const closeLayer = openLayer(layer);
const onKey = (event: KeyboardEvent) => {
if (!dismissOnEscape || event.key !== "Escape" || !ownsEscape(layer, event)) return;
event.preventDefault();
dismissRef.current("escape");
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside another open one: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !inOtherLayer(layer, target, { traps: false })) {
consumeActivation(event);
}
dismissRef.current("pointer");
};
const onFocus = (event: FocusEvent) => {
const target = event.target;
if (target instanceof Node && !inside(target)) dismissRef.current("focus");
};
window.addEventListener("keydown", onKey);
if (outsidePress) window.addEventListener("pointerdown", onPointer, true);
if (focusOutside) window.addEventListener("focusin", onFocus);
return () => {
closeLayer();
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
window.removeEventListener("focusin", onFocus);
};
}, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);
}
"use client";
import { useState } from "react";
/**
* Runs `start` during the render in which `open` becomes true.
*
* Opening a list starts a fresh session — an empty query, the highlight back at
* the top — and that is a resolution, not a side effect: a passive effect runs
* after the commit, so the new session would carry the last one's state for a
* window in which a key press can land.
*
* `start` may only set state belonging to the calling component. Anything that
* reaches outside it — a consumer's callback, a DOM write, moving focus — is a
* side effect, and React rejects a callback that sets another component's state
* during this one's render. Put those in an effect keyed to `open`.
*/
export function useOnOpen(open: boolean, start: () => void) {
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
if (open) start();
}
}
"use client";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
/**
* Where the keyboard or the pointer last moved to: the row's id, stamped with
* the query it was placed under.
*/
type RowCursor = { id: string; query: string };
/** The cursor's row, or -1 once the query has moved on or the row has left. */
function indexOfCursor(
rows: readonly { id: string }[],
query: string,
cursor: RowCursor | null,
) {
if (cursor === null || cursor.query !== query) return -1;
return rows.findIndex((row) => row.id === cursor.id);
}
/**
* The highlighted row of a list whose rows can change under it.
*
* Which row is highlighted is resolved during render, never in a passive
* effect: a passive effect runs after the commit, so a list that had just
* changed would carry an `aria-activedescendant` naming a row that has left it,
* and a key pressed in that window would commit the wrong row or nothing at
* all.
*
* The cursor holds the row's id, not its position. A position alone cannot tell
* a list that shrank from one that swapped its rows for a different set of the
* same length, and the second case is the one that silently hands Enter to a
* row the user never chose. A cursor whose row has left the list returns the
* highlight to the first row rather than to the nearest surviving one: the row
* the user aimed at is gone, and the first row is where a new query already
* puts the highlight.
*
* Pass the query the list is filtered by. The cursor is stamped with it and
* dropped when it changes, so a caller cannot forget to clear it — including a
* caller whose query arrives as a prop and so never runs its own handler. Rows
* that come back under a query that has moved on cannot revive it either.
* `moveTo(null)` is for deliberate resets, such as reopening the list.
*
* Both callbacks keep one identity for the life of the component, and read the
* rows and the query through a ref to do it. A caller will put them in an
* effect's dependencies — the exhaustive-deps rule makes it — and a `moveTo`
* rebuilt on every keystroke would re-run that effect on every keystroke.
*/
export function useRowCursor(rows: readonly { id: string }[], query: string) {
const [cursor, setCursor] = useState<RowCursor | null>(null);
// Written after commit, not during render: a render React discards or has not
// finished still runs the component body, and an event handler that read this
// in that window would stamp the cursor with a query the committed tree does
// not have.
const latest = useRef({ rows, query });
useLayoutEffect(() => {
latest.current = { rows, query };
});
const cursorRow = indexOfCursor(rows, query, cursor);
// Cleared rather than ignored: React re-runs this render with the cursor
// already gone, so rows that come back cannot revive a highlight the user has
// stopped aiming at.
if (cursor !== null && cursorRow < 0) setCursor(null);
const moveTo = useCallback(
(id: string | null) =>
setCursor(id === null ? null : { id, query: latest.current.query }),
[],
);
const moveActive = useCallback((direction: 1 | -1) => {
const { rows: live, query: liveQuery } = latest.current;
const last = live.length - 1;
if (last < 0) return;
// Steps from the row the cursor is really on, inside the update, so that
// two keys landing in one batch move two rows rather than one.
setCursor((current) => {
const at = Math.max(indexOfCursor(live, liveQuery, current), 0);
const next = Math.min(Math.max(at + direction, 0), last);
return { id: live[next].id, query: liveQuery };
});
}, []);
return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };
}
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useMemo,
} from "react";
/**
* A component's messages. Plain strings with `{name}` placeholders, so a
* dictionary stays JSON-serializable and can be passed from a server layout.
* There are no plural forms: write messages that read correctly for any count.
*/
export type Messages = Record<string, string>;
/** A language file: component namespace → any subset of that component's messages. */
export type LocaleMessages = Record<string, Partial<Messages>>;
type LocaleContextValue = {
locale?: string;
messages: LocaleMessages;
};
const NO_MESSAGES: LocaleMessages = {};
const LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });
/** Without a locale, digits stay plain so server and client render the same text. */
export function formatNumber(value: number, locale?: string) {
return locale ? new Intl.NumberFormat(locale).format(value) : String(value);
}
export interface LocaleProviderProps {
/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */
locale: string;
/**
* Component namespace → translated strings. Missing keys fall back to English.
* Pass a stable object (a module constant, imported JSON or a memoized value):
* a new object each render gives every translated component a new `t`.
*/
messages?: LocaleMessages;
children: ReactNode;
}
export function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {
const value = useMemo(() => ({ locale, messages }), [locale, messages]);
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}
export function useLocale(): { locale?: string } {
return { locale: useContext(LocaleContext).locale };
}
/**
* Resolves a component's strings: `labels` prop, then the provider's
* messages for `namespace`, then the component's English `defaults`.
* Numbers passed as values are formatted for the provider's locale.
*/
export function useMessages<T extends Messages>(
namespace: string,
defaults: T,
labels?: Partial<T>,
) {
const { locale, messages } = useContext(LocaleContext);
const provided = messages[namespace];
// Inline `labels={{ … }}` is a new object every render. Keying it by content
// keeps `t` one identity until a label changes, so effects and memos that
// depend on `t` don't re-run per render, and render-time reads never lag.
const labelsKey = labels ? JSON.stringify(labels) : "";
const stableLabels = useMemo(
() => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),
[labelsKey],
);
return useCallback(
(key: keyof T & string, values?: Record<string, string | number>) => {
const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];
if (!values) return template;
return template.replace(/\{(\w+)\}/g, (match, name: string) => {
const value = values[name];
if (value === undefined) return match;
return typeof value === "number" ? formatNumber(value, locale) : value;
});
},
[defaults, stableLabels, locale, provided],
);
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Every open overlay on the page, innermost last: focus traps, modal scopes
* and dismissable menus all register here. Overlays have no shared z-order to
* consult, and a menu inside a drawer portals out of it, so this stack is how
* they agree on who answers Escape and where focus may go.
*/
export interface Layer {
/** Whether `target` belongs to this layer (its panel, portals, trigger). */
contains: (target: Node) => boolean;
/** True for focus traps and modal scopes, which pull stray focus back. */
traps?: boolean;
/** False for a layer that ignores Escape, so the key reaches the one below. */
escape?: boolean;
}
const stack: Layer[] = [];
// The innermost layer when each Escape began, read before any handler runs,
// so a layer that closes itself mid-event can't hand the key to the one below.
const escapeOwners = new WeakMap<Event, Layer | undefined>();
let listening = false;
function innermostEscapeLayer() {
for (let index = stack.length - 1; index >= 0; index--) {
if (stack[index].escape !== false) return stack[index];
}
return undefined;
}
function recordEscapeOwner(event: KeyboardEvent) {
if (event.key === "Escape") escapeOwners.set(event, innermostEscapeLayer());
}
/** Registers an open layer. Call the returned function when it closes. */
export function openLayer(layer: Layer) {
if (!listening) {
document.addEventListener("keydown", recordEscapeOwner, true);
listening = true;
}
stack.push(layer);
return () => {
const index = stack.indexOf(layer);
if (index !== -1) stack.splice(index, 1);
};
}
/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */
export function ownsEscape(layer: Layer, event: KeyboardEvent) {
if (event.defaultPrevented) return false;
const owner = escapeOwners.has(event)
? escapeOwners.get(event)
: innermostEscapeLayer();
return owner === layer;
}
/** Whether `target` sits in a layer opened on top of `layer`. */
export function inLayerAbove(layer: Layer, target: Node) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.contains(target));
}
/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */
export function trapAbove(layer: Layer) {
const index = stack.indexOf(layer);
return stack.slice(index + 1).some((above) => above.traps);
}
/**
* Whether `target` belongs to any open layer other than `layer`. Pass
* `traps: false` to count only dismissable overlays, not the traps under them.
*/
export function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {
return stack.some(
(other) => other !== layer && (traps || !other.traps) && other.contains(target),
);
}
Copy the source code
"use client";
// beui.dev/components/blocks/morphing-search/overlay
import { type LucideIcon, Search } from "lucide-react";
import {
AnimatePresence,
LayoutGroup,
motion,
type Transition,
useReducedMotion,
} from "motion/react";
import {
type KeyboardEvent as ReactKeyboardEvent,
useCallback,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { EASE_OUT, SPRING_LAYOUT } from "@/lib/ease";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useOnOpen } from "@/lib/hooks/use-on-open";
import { useRowCursor } from "@/lib/hooks/use-row-cursor";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
// Keeps the Wallet Card feel with a little more time to read the morph.
const SEARCH_MORPH: Transition = {
type: "spring",
duration: 0.58,
bounce: 0.22,
};
// Keep the spring on the shell, but unfold complex clip-path values with the
// same progressive tween as Morph Popover so the content never snaps ahead.
const SEARCH_CLIP_TRANSITION: Transition = {
duration: 0.32,
ease: EASE_OUT,
};
export type MorphingSearchItem = {
/** Unique key for the result row. */
id: string;
/** Main text of the result row, matched by the search. */
title: string;
/** Smaller text under the title, also matched by the search. */
description?: string;
/** Extra words the search matches that are not shown. */
keywords?: string[];
/** Lucide icon component shown before the title. Omitted when not set. */
icon?: LucideIcon;
/** Called when this result is chosen, before the search's `onSelect`. */
onSelect?: () => void;
};
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const morphingSearchMessages = {
placeholder: "Search",
empty: "No results found.",
close: "Close search",
dialog: "Search",
results: "Search results",
};
export type MorphingSearchMessages = typeof morphingSearchMessages;
export interface MorphingSearchProps {
/** Searchable items, matched on title, description and keywords. */
items: MorphingSearchItem[];
/** Input placeholder and accessible name. Default: "Search" */
placeholder?: string;
/** Opens the search when this key is pressed outside a text field. Default: "f" */
shortcut?: string;
/** Render the closed trigger as a compact search icon. */
iconOnly?: boolean;
/** Text shown when no item matches the query. Default: "No results found." */
emptyMessage?: string;
/** Whether the search panel is open, for controlled use. */
open?: boolean;
/** Whether the panel starts open when uncontrolled. Default: false */
defaultOpen?: boolean;
/** Called with the new open state when the panel opens or closes. */
onOpenChange?: (open: boolean) => void;
/** Called with the query text as the user types. */
onQueryChange?: (query: string) => void;
/** Called with the chosen item after its own `onSelect`, then the panel closes. */
onSelect?: (item: MorphingSearchItem) => void;
/** Override any built-in string. */
labels?: Partial<MorphingSearchMessages>;
/** Classes merged onto the closed trigger wrapper. */
className?: string;
}
type AnchorRect = {
top: number;
left: number;
width: number;
};
function isEditableTarget(target: EventTarget | null) {
if (!(target instanceof HTMLElement)) return false;
return (
target.isContentEditable ||
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement
);
}
export function MorphingSearch({
items,
placeholder: placeholderProp,
shortcut = "f",
iconOnly = false,
emptyMessage: emptyMessageProp,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
onQueryChange,
onSelect,
labels,
className,
}: MorphingSearchProps) {
const t = useMessages("morphingSearch", morphingSearchMessages, labels);
const placeholder = placeholderProp ?? t("placeholder");
const emptyMessage = emptyMessageProp ?? t("empty");
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [query, setQuery] = useState("");
const [mounted, setMounted] = useState(false);
const [backgroundScrollLocked, setBackgroundScrollLocked] =
useState(defaultOpen);
const [anchorRect, setAnchorRect] = useState<AnchorRect>({
top: 16,
left: 16,
width: 288,
});
const open = controlledOpen ?? internalOpen;
const controlled = controlledOpen !== undefined;
const reduce = useReducedMotion();
const uid = useId();
const anchorRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const dialogRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
const wasOpenRef = useRef(open);
const transition: Transition = reduce ? { duration: 0 } : SPRING_LAYOUT;
const morphTransition: Transition = reduce ? { duration: 0 } : SEARCH_MORPH;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setInternalOpen(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
const measureAnchor = useCallback(() => {
const rect = anchorRef.current?.getBoundingClientRect();
if (!rect || rect.width === 0) return;
setAnchorRect({ top: rect.top, left: rect.left, width: rect.width });
}, []);
const openSearch = useCallback(() => {
measureAnchor();
previousFocusRef.current =
document.activeElement instanceof HTMLElement
? document.activeElement
: null;
setOpen(true);
}, [measureAnchor, setOpen]);
const filteredItems = useMemo(() => {
const needle = query.trim().toLowerCase();
if (!needle) return items;
return items.filter((item) =>
[item.title, item.description ?? "", ...(item.keywords ?? [])]
.join(" ")
.toLowerCase()
.includes(needle),
);
}, [items, query]);
const { activeIndex, moveTo, moveActive } = useRowCursor(filteredItems, query);
// The cursor is stamped with the query, so changing it drops the highlight
// without this having to say so.
const updateQuery = useCallback(
(next: string) => {
setQuery(next);
onQueryChange?.(next);
},
[onQueryChange],
);
const closeSearch = useCallback(() => {
updateQuery("");
setOpen(false);
}, [setOpen, updateQuery]);
useEffect(() => setMounted(true), []);
useEffect(() => {
if (open) setBackgroundScrollLocked(true);
}, [open]);
useEffect(() => {
measureAnchor();
const anchor = anchorRef.current;
const observer =
anchor && typeof ResizeObserver !== "undefined"
? new ResizeObserver(measureAnchor)
: null;
if (anchor) observer?.observe(anchor);
window.addEventListener("resize", measureAnchor);
document.addEventListener("scroll", measureAnchor, true);
window.visualViewport?.addEventListener("resize", measureAnchor);
window.visualViewport?.addEventListener("scroll", measureAnchor);
return () => {
observer?.disconnect();
window.removeEventListener("resize", measureAnchor);
document.removeEventListener("scroll", measureAnchor, true);
window.visualViewport?.removeEventListener("resize", measureAnchor);
window.visualViewport?.removeEventListener("scroll", measureAnchor);
};
}, [measureAnchor]);
useEffect(() => {
if (!backgroundScrollLocked) return;
const preventBackgroundWheel = (event: WheelEvent) => {
const target = event.target;
if (target instanceof Node && listRef.current?.contains(target)) return;
event.preventDefault();
};
const preventBackgroundTouch = (event: TouchEvent) => {
const target = event.target;
if (target instanceof Node && listRef.current?.contains(target)) return;
event.preventDefault();
};
document.addEventListener("wheel", preventBackgroundWheel, {
passive: false,
});
document.addEventListener("touchmove", preventBackgroundTouch, {
passive: false,
});
return () => {
document.removeEventListener("wheel", preventBackgroundWheel);
document.removeEventListener("touchmove", preventBackgroundTouch);
};
}, [backgroundScrollLocked]);
// The backdrop handles presses; this is Escape, answered only while the
// search is the innermost open layer.
useDismiss(open, closeSearch, dialogRef, { outsidePress: false });
useEffect(() => {
const handleShortcut = (event: KeyboardEvent) => {
if (
!open &&
shortcut &&
event.key.toLowerCase() === shortcut.toLowerCase() &&
!event.repeat &&
!event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
!event.shiftKey &&
!isEditableTarget(event.target)
) {
event.preventDefault();
openSearch();
}
};
window.addEventListener("keydown", handleShortcut);
return () => window.removeEventListener("keydown", handleShortcut);
}, [open, openSearch, shortcut]);
// Only this component's own state. Telling the consumer the query changed is
// a side effect, so it waits for the effect below.
useOnOpen(open, () => {
setQuery("");
moveTo(null);
});
// Keyed to `open` alone. `onQueryChange` is read through a ref because an
// inline one changes identity on every keystroke, and this effect clearing
// the field on every keystroke is exactly what that costs. Written after
// commit for the reason `lib/hooks/use-row-cursor.ts` gives at length.
const notifyQuery = useRef(onQueryChange);
useLayoutEffect(() => {
notifyQuery.current = onQueryChange;
});
useEffect(() => {
if (open) {
notifyQuery.current?.("");
const frame = requestAnimationFrame(() => inputRef.current?.focus());
return () => cancelAnimationFrame(frame);
}
if (wasOpenRef.current) {
const frame = requestAnimationFrame(() => {
const previousFocus = previousFocusRef.current;
const focusTarget = previousFocus?.isConnected
? previousFocus
: triggerRef.current;
focusTarget?.focus();
});
return () => cancelAnimationFrame(frame);
}
}, [open]);
useEffect(() => {
wasOpenRef.current = open;
}, [open]);
useEffect(() => {
if (!open) return;
listRef.current
?.querySelector<HTMLElement>(`[data-index="${activeIndex}"]`)
?.scrollIntoView({ block: "nearest" });
}, [activeIndex, open]);
const selectItem = useCallback(
(item: MorphingSearchItem) => {
item.onSelect?.();
onSelect?.(item);
closeSearch();
},
[closeSearch, onSelect],
);
const handleDialogKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowDown") {
event.preventDefault();
moveActive(1);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
moveActive(-1);
return;
}
if (event.key === "Enter") {
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
event.preventDefault();
const item = filteredItems[activeIndex];
if (item) selectItem(item);
return;
}
if (event.key !== "Tab" || !dialogRef.current) return;
const focusable = Array.from(
dialogRef.current.querySelectorAll<HTMLElement>(
'input, button:not([disabled]), [tabindex]:not([tabindex="-1"])',
),
);
const first = focusable[0];
const last = focusable.at(-1);
if (!first || !last) return;
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
const shellLayoutId = `${uid}-shell`;
const listboxId = `${uid}-results`;
const panelWidth = mounted
? Math.max(
anchorRect.width,
Math.min(448, window.innerWidth - anchorRect.left - 16),
)
: anchorRect.width;
const resultsHeight = mounted
? Math.max(96, Math.min(288, window.innerHeight - anchorRect.top - 80))
: 288;
const collapsedContentClip = `inset(0px ${Math.max(
0,
panelWidth - anchorRect.width,
)}px ${resultsHeight}px 0px round 24px)`;
const expandedContentClip = "inset(0px 0px 0px 0px round 16px)";
// Neither grouping layer carries a box: they only hold `inert`/`aria-hidden`,
// the z-index and the presence key, and every child below is `fixed` and
// resolves against the viewport itself. The click catcher spans the viewport
// edges but has no children and filters nothing, so it is not a sampling
// layer either.
const overlay = mounted
? createPortal(
<div
aria-hidden={!open}
inert={!open}
className="pointer-events-none fixed left-0 top-0 z-50 size-0"
>
<AnimatePresence
initial={false}
mode="popLayout"
onExitComplete={() => setBackgroundScrollLocked(false)}
>
{open ? (
<motion.div
key="morphing-search-overlay"
className="fixed left-0 top-0 size-0"
>
<button
type="button"
aria-label={t("close")}
className="pointer-events-auto fixed inset-0 cursor-default bg-transparent"
onClick={closeSearch}
/>
<motion.div
layoutId={shellLayoutId}
aria-hidden="true"
className="fixed z-10 rounded-2xl bg-background/90 backdrop-blur-xl"
style={{
top: anchorRect.top,
left: anchorRect.left,
width: panelWidth,
height: 48 + resultsHeight,
boxShadow: "inset 0 0 0 1px var(--color-border)",
}}
transition={morphTransition}
/>
<motion.div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-label={t("dialog")}
onKeyDown={handleDialogKeyDown}
initial={
reduce
? false
: { opacity: 0, clipPath: collapsedContentClip }
}
animate={{ opacity: 1, clipPath: expandedContentClip }}
exit={{
opacity: 0,
clipPath: collapsedContentClip,
transition: reduce
? { duration: 0 }
: {
clipPath: SEARCH_CLIP_TRANSITION,
opacity: SEARCH_MORPH,
},
}}
transition={
reduce
? { duration: 0 }
: {
clipPath: SEARCH_CLIP_TRANSITION,
opacity: SEARCH_MORPH,
}
}
className="pointer-events-auto fixed z-20 overflow-hidden rounded-2xl"
style={{
top: anchorRect.top,
left: anchorRect.left,
width: panelWidth,
}}
>
<div
className={cn(
"flex h-12 items-center gap-2.5 border-b border-border",
iconOnly ? "px-4" : "px-3.5",
)}
>
<span className="shrink-0">
<Search className="size-4 text-muted-foreground" />
</span>
<div className="flex h-10 min-w-0 flex-1 items-center">
<input
ref={inputRef}
value={query}
onChange={(event) => updateQuery(event.target.value)}
role="combobox"
aria-label={placeholder}
aria-expanded="true"
aria-controls={listboxId}
aria-autocomplete="list"
aria-activedescendant={
filteredItems.length > 0
? `${uid}-option-${activeIndex}`
: undefined
}
placeholder={placeholder}
className="size-full bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground"
/>
</div>
<kbd className="flex h-7 shrink-0 items-center rounded-md border border-border px-2 text-xs text-muted-foreground">
Esc
</kbd>
</div>
<motion.div
ref={listRef}
id={listboxId}
role="listbox"
aria-label={t("results")}
transition={reduce ? { duration: 0 } : undefined}
variants={
reduce
? undefined
: {
closed: {
opacity: 0,
transform: "translateY(6px)",
transition: {
duration: 0.16,
delay: 0.18,
ease: EASE_OUT,
},
},
open: {
opacity: 1,
transform: "translateY(0px)",
transition: {
duration: 0.16,
ease: EASE_OUT,
},
},
}
}
initial={
reduce
? { opacity: 1, transform: "translateY(0px)" }
: "closed"
}
animate={
reduce
? { opacity: 1, transform: "translateY(0px)" }
: "open"
}
exit={reduce ? undefined : "closed"}
className="overscroll-contain overflow-y-auto p-2"
style={{
maxHeight: resultsHeight,
}}
>
{filteredItems.length > 0 ? (
filteredItems.map((item, index) => {
const Icon = item.icon;
const active = index === activeIndex;
return (
<button
key={item.id}
id={`${uid}-option-${index}`}
type="button"
role="option"
aria-selected={active}
data-index={index}
onMouseMove={() => {
if (!active) moveTo(item.id);
}}
onFocus={() => moveTo(item.id)}
onClick={() => selectItem(item)}
className="relative flex w-full items-center gap-2.5 rounded-full px-4 py-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
>
{active ? (
<motion.span
layoutId={`${uid}-active-result`}
className="absolute inset-0 rounded-full bg-foreground/5"
transition={transition}
/>
) : null}
{Icon ? (
<Icon className="relative size-4 shrink-0 text-muted-foreground" />
) : null}
<span className="relative min-w-0">
<span className="block truncate text-sm font-medium text-foreground">
{item.title}
</span>
{item.description ? (
<span className="block truncate text-xs text-muted-foreground">
{item.description}
</span>
) : null}
</span>
</button>
);
})
) : (
<p className="px-3 py-8 text-center text-sm text-muted-foreground">
{emptyMessage}
</p>
)}
</motion.div>
</motion.div>
</motion.div>
) : null}
</AnimatePresence>
</div>,
document.body,
)
: null;
return (
<LayoutGroup id={uid}>
<div
ref={anchorRef}
className={cn(
"relative",
iconOnly ? "size-12" : "h-12 w-72 max-w-full",
className,
)}
>
{!open ? (
<motion.button
ref={triggerRef}
layoutId={shellLayoutId}
type="button"
aria-haspopup="dialog"
aria-expanded="false"
aria-label={placeholder}
onClick={openSearch}
transition={morphTransition}
style={{
boxShadow: "inset 0 0 0 1px var(--search-trigger-stroke)",
}}
className={cn(
"flex size-full items-center rounded-full bg-background/60 text-left backdrop-blur-md outline-none [--search-trigger-stroke:var(--color-border)] hover:[--search-trigger-stroke:var(--color-border-strong)] focus-visible:ring-2 focus-visible:ring-ring",
iconOnly ? "cursor-pointer justify-center" : "cursor-text px-3.5",
)}
></motion.button>
) : null}
<motion.div
aria-hidden="true"
initial={false}
animate={{ opacity: open ? 0 : 1 }}
transition={
reduce
? { duration: 0 }
: {
duration: 0.1,
delay: open ? 0.1 : 0.12,
ease: EASE_OUT,
}
}
className={cn(
"pointer-events-none absolute inset-0 flex items-center",
backgroundScrollLocked && "z-[60]",
iconOnly ? "justify-center" : "gap-2.5 px-3.5",
)}
>
<Search className="size-4 shrink-0 text-muted-foreground" />
{iconOnly ? null : (
<>
<span className="min-w-0 flex-1 truncate text-sm text-muted-foreground">
{placeholder}
</span>
{shortcut ? (
<kbd className="flex h-7 min-w-7 shrink-0 items-center justify-center rounded-md border border-border px-2 text-xs text-muted-foreground">
{shortcut.toUpperCase()}
</kbd>
) : null}
</>
)}
</motion.div>
</div>
{overlay}
</LayoutGroup>
);
}
itemsMorphingSearchItem[]Searchable items, matched on title, description and keywords.
—placeholder?stringInput placeholder and accessible name. Default: "Search"
—shortcut?stringOpens the search when this key is pressed outside a text field. Default: "f"
ficonOnly?booleanRender the closed trigger as a compact search icon.
falseemptyMessage?stringText shown when no item matches the query. Default: "No results found."
—open?booleanWhether the search panel is open, for controlled use.
—defaultOpen?booleanWhether the panel starts open when uncontrolled. Default: false
falseonOpenChange?((open: boolean) => void)Called with the new open state when the panel opens or closes.
—onQueryChange?((query: string) => void)Called with the query text as the user types.
—onSelect?((item: MorphingSearchItem) => void)Called with the chosen item after its own `onSelect`, then the panel closes.
—labels?Partial<{ placeholder: string; empty: string; close: string; dialog: string; results: string; }>Override any built-in string.
—className?stringClasses merged onto the closed trigger wrapper.
—Expandable Action Bar
Compact icon actions that expand into labeled controls on hover or focus with shared layout motion.
Expandable Tabs
Icon tab bar where the active tab expands to a labelled pill, with a panel above that morphs height and slides content direction-aware on switch.
Morphing Tabs
Reorderable tabs whose selected item grows into a white content surface, with the active shape gliding as tabs move and a shared morph between rooms.
Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.
Updated