Primitives
Animated Number Avatar Badge Button Button Group Toggle Toggle Group Checkbox Chip Countdown Divider Fab Grid Icon Image Input Search Input Textarea Label Loader Marquee Masked Input Message Bubble Notification Banner Offline Banner Progress Progress Ring Radio Group Range Slider Rating Separator Skeleton Slider Stack Stepper Switch Text Theme Toggle Ticker Typing IndicatorComposed
Accordion Achievement Badge Action Bar Action Sheet Action Swap Activity Rings Add to Cart Button Address Card Agenda List Alert Amount Keypad Animated Icons App Bar Audio Message Audio Recorder Autocomplete Avatar Group Balance Display Bar List Barcode Before After Biometric Gate Bloom Menu Bottom Sheet Paywall Sheet Side Sheet Breadcrumb Calendar Calendar Strip Card Carousel Cart Item Character Charts Chat Composer Chat List Item Choice Card Circle Reveal Coach Marks Collapsible Collapsible Header Color Picker Combobox Command Palette Comment Thread Confetti Consent Sheet Context Menu Copy Field Country Picker Coupon Input Currency Input Data Table Date Range Picker Day Schedule Dialog Dock Donut Chart Drawer Driver Card Dropdown Menu Drum Picker Emoji Picker Empty State Error State Event Card Expandable Control Fader Feature Gate File Picker Filter Bar Follow Button Form Gauge Glass Glass Cluster Glass Dock Morph Glass Fab Morph Glass Lab Glass Orb Glass Search Morph Glass Sheet Edge Gradient Button Headline New Heatmap Image Cropper Image Viewer Kanban Card Keyboard Avoiding Keyboard Toolbar Leaderboard Level Progress Lightbox Like Button Line Chart List Reorderable List Swipeable Row Location Card Location Search Map Sheet Map View Markdown View Media Controls Media Picker Media Tile Mention Input Meter Bar Mini Player Mood Slider Morphing Modal Multi Select Navigation Rail Notification Item Number Input Onboarding Pager Order Card Order Summary OTP Input Pagination Paper Clip New Parallax Header Pass Card Password Strength Payment Button Payment Card Payment Method Permission Primer Phone Input PIN Pad Polaroid New Poll Popover Post Card Postage Stamp New Price Tag Pricing Table Product Card Product Gallery Profile Header Promo Banner Prompt Input Property Card Pull To Refresh QR Code Quick Actions Quick Replies Rating Summary Reaction Picker Resend Timer Review Card Review Prompt Ride Option Save Button Scan Frame Scroll Spy Tabs Seat Map Section Header Section Index Segmented Control Select Share Button Share Sheet Shutter Button Signature Pad Slide to Confirm Slot Picker Smart Banner Social Login Button Sparkline Splash Screen Split Button Stat Card Stateful Button Status Dot Step Flow Steps Sticker New Stopwatch Stories Progress Stories Viewer Story Ring Streak Counter Streaming Text Success Seal Swipe Deck Tabs Tag Input Tape New Text Reveal Thinking Indicator Time Picker Timeline Timer Ring Tip Selector Toast Toolbar Tooltip Track Row Transaction Row Trip Progress Variant Picker Video Controls Waveform Weather Card Weekday Picker Zoom TransitionScreens
Account Switcher Biometric Setup Delete Account Forgot Password Grow Auth Login Login — Dark Stage Login — Dense Work Login — Editorial Login — Illustrated Login — Minimal Ink Login — Social Login — Video Loop Food Onboarding Onboarding Onboarding Dark Objects Onboarding Editorial Onboarding Illustrated Onboarding Personalize Onboarding Photo Carousel OTP Verification Passkey — Create Password Reset Permission — Notifications Phone Verification Onboarding Quiz Session Devices Signup Sign-up Chat Sign-up Photo Sheet Social Auth Split Auth Verify Identity Welcome AI Chat AI Assistant Channels List Chat Info Chat List Chat Media Chat Thread Create Group Group Info Message Requests New Message Kept Messages Accessibility Activity Log Appearance Authenticator Blocked Accounts Export Your Data Downloads Edit Profile Edit Profile — Rows Emergency Call Empty States Set Error State Send Feedback Device Locator Help Center Home — Bento Home — Dark Home — Editorial Home Feed Invite Friends Language & Region Linked Accounts Not Found (404) Notification Settings Notifications Password Vault Paywall Paywall — Comparison Paywall — Dark Stage Paywall — Editorial Paywall — Photo Paywall — Trial Timeline Privacy Profile Profile — Gamified Profile — Minimal Profile — Photo Hero QR Scanner Report Issue Saved Items Phone Time Search Search — Command Palette Search — Visual Account Health Settings Settings — Dark Device Settings — Search Storage & Data Terms & Privacy Dating Chat Dating Filters Profile Discover Its A Match Into You Matches Profile Detail Profile Editor Courier Matching Delivery History Delivery Support Package Schedule Parcel Tracking Proof Of Delivery Quick Aisle Quick Home Send Package Substitutions Add Payment Address Book Cart Categories Checkout Checkout — Steps Checkout Success Delivery Filters & Sort Flash Sale Gift Cards Loyalty Points Order Cancel Order Detail Orders Pay Later Checkout Payment Methods Product Detail Product Detail — Hero Product Grid Product Reviews Promo Codes Recently Viewed Return Items Search Results Shop Assistant Store Home Tip & Rate Courier Order Tracking Wishlist Write a Review Event Checkin Event Hero Events Discover My Tickets Seat Selection Ticket Checkout Add Card Bank Accounts Dashboard — Bento Bill Pay Budgets Card Details Crypto Portfolio Finance Dashboard Dashboard — Dark Exchange Currency Expense List Invoice Detail Manage Cards Plan Management Savings Goals Send Money Spending Analytics Split Bill Subscriptions Token Detail Token Swap Transactions Wallet Home Wallet Movers Courier Tracking Food Cart Food Home Food Orders Grocery List Recipe Detail Restaurant — Dark Restaurant Detail Activity Rings Fitness Home Habit Quest Habit Tracker Meal Planner Med Store Meditation Player Mood Check-in Nutrition Home Period Tracker Prior Auth Prior Auth Cases Quest Complete Run Tracking Rx Scan Sleep Tracker Telehealth Booking Walk Map Water Tracker Workout Complete Workout Detail Workout Session Applications Apply Company Interview Schedule Job Detail Job Feed Resume Saved Jobs Create Listing Item Chat Listing Detail Make Offer Market Checkout Market Home Market Search My Listings Offers Inbox Seller Profile Audiobook Player Camera Gallery Albums Game Store Mini Player Music Player Photo Editor Photo Gallery Playlist Detail Podcast Player Clips Feed Serene Home Sound Mixer Stories Video Call Video Player Article Reader Course Detail Event Detail Memory Onboarding Icon Lab Leaderboard Lesson Player Match Detail News Editorial News Home Plant Care Prediction Live Prediction Welcome Smart Home Standings Ticket Wallet Topics Follow Weather Detail Add Task Sheet Alarm Clock Calendar Day Calendar Month Doc Scanner File Manager Focus Timer Journal Kanban Board Mail Inbox Mail Thread Note Editor Notes List Reminders Task List Time Blocks Agent Profile Compare Homes Mortgage Calculator Property Detail Rental Application Saved Homes Schedule Tour Search List Search Map Complete Destination Driver Arriving Ev Charging History Home In Trip Matching Options Parking Receipt Safety Schedule Scooter Unlock Booking Confirmed Booking Review Booking Slots My Bookings Pro On The Way Provider Detail Provider List Rate Service Services Home Arc Create Arc Detail Arc Onboarding Avatar Creator Comments Sheet Create Post Explore Grid Followers List Hashtag Feed Mentions Post Detail Post Hero Social Profile Boarding Pass Booking Confirm Car Rental Trip Discover Flight Live Flight Preferences Flight Results Flight Search Hotel Detail Live Transit Trip — Map Day Trip — Rideshare Request Seat Select Travel Home Trip Itinerary Trip OnboardingNothing matches — try another word.
Search Input
Search field with a clear button and a busy indicator while results load. Focus brightens the field, matching text in results can be highlighted, and a frosted glass style is included.
Preview
import * as React from "react";
import { forwardRef, useEffect, useRef, useState } from "react";
import { TextInput, View, Text, Pressable, type TextInputProps } from "react-native";
import Animated, {
Easing,
cancelAnimation,
useSharedValue,
useAnimatedStyle,
withRepeat,
withSpring,
withTiming,
interpolateColor,
type SharedValue,
} from "react-native-reanimated";
import {
cn,
ease,
tempo,
useHaptic,
useTheme,
usePressAnimation,
useReducedMotion,
spring,
timing,
AnimatedTextInput,
LitEdge,
} from "@lumioui/core";
import { Icon } from "../icon";
import { Glass } from "../glass";
/** Refusal flicker — one 4px kick released into spring.shake. */
const ERROR_KICK = 4;
/** Searching — the leading glyph swaps for three dots that brighten in turn;
* one cycle, the same beat as Button's busy dots. */
const BUSY_CYCLE_MS = tempo.roll * 2;
/** Busy dots sized to the glyph slot, and their resting brightness. */
const BUSY_DOT = 4;
const BUSY_DOT_REST = 0.3;
/** One busy dot: brightens as the cycle passes its turn, then rests. Opacity
* only — reduced motion holds it half lit. */
function BusyDot({ index, lap, color, still }: { index: number; lap: SharedValue<number>; color: string; still: boolean }) {
const style = useAnimatedStyle(() => {
if (still) return { opacity: 0.6 };
const t = (((lap.value - index / 3) % 1) + 1) % 1;
const peak = t < 0.5 ? Math.sin(t * 2 * Math.PI) : 0;
return { opacity: BUSY_DOT_REST + (1 - BUSY_DOT_REST) * Math.max(0, peak) };
});
return <Animated.View style={[{ width: BUSY_DOT, height: BUSY_DOT, borderRadius: BUSY_DOT / 2, backgroundColor: color }, style]} />;
}
/** Disabled rests at half strength. */
const DISABLED_OPACITY = 0.5;
const IGNITE = { duration: timing.fast.duration, easing: Easing.bezier(...ease.out) };
const DIM = { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) };
/** Clear button — ignites in place when text appears, dims away when it
* goes; it stays mounted so the exit is seen. */
function ClearButton({ visible, onPress }: { visible: boolean; onPress: () => void }) {
const reduceMotion = useReducedMotion();
const on = useSharedValue(visible ? 1 : 0);
const scale = useSharedValue(1);
const press = usePressAnimation({ pressedScale: 0.85, pressedOpacity: 0.5 });
React.useEffect(() => {
if (visible) {
on.value = withTiming(1, IGNITE);
if (!reduceMotion) {
scale.value = 0.9;
scale.value = withSpring(1, spring.swap);
}
} else {
on.value = withTiming(0, DIM);
}
}, [visible, on, scale, reduceMotion]);
const appearStyle = useAnimatedStyle(() => ({
opacity: on.value,
transform: [{ scale: scale.value }],
}));
return (
<Pressable
onPress={onPress}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
disabled={!visible}
pointerEvents={visible ? "auto" : "none"}
className="h-8 w-8 items-center justify-center"
accessibilityRole="button"
accessibilityLabel="Clear search"
accessibilityElementsHidden={!visible}
importantForAccessibility={visible ? "auto" : "no-hide-descendants"}
// 32px visual + 8px/side hitSlop = 48pt ≥ 44pt touch target.
hitSlop={{ top: 8, left: 8, right: 8, bottom: 8 }}
>
<Animated.View style={appearStyle}>
<Animated.View style={press.animatedStyle}>
<Icon name="x" size="sm" color="mutedForeground" />
</Animated.View>
</Animated.View>
</Pressable>
);
}
export interface SearchInputProps extends Omit<TextInputProps, "className"> {
/** Visible label above the field. */
label?: string;
/** Helper text below the field. */
helper?: string;
/** Error message. */
error?: string;
/** Debounce duration in ms for onChangeText. While a debounced query is
* pending, the leading glyph shows busy dots. */
debounceMs?: number;
/** A search is running (e.g. awaiting results) — the leading glyph shows
* busy dots until it turns false, then swaps back. */
searching?: boolean;
/** Called when the clear button is pressed. */
onClear?: () => void;
/** Leading icon slot. */
icon?: React.ReactNode;
/** Classes for the input element. */
className?: string;
/** Classes for the outer wrapper. */
containerClassName?: string;
/** Capsule mode — the field becomes a floating glass pill
* (search rides over content instead of sitting on the surface). */
glass?: boolean;
/** Glass mode only: tint the capsule (e.g. a dark wash over a bright photo). */
glassTint?: string;
/** Field height — "sm" 36pt (search inside a navigation bar), "md" 44pt
* (default, standalone search on a screen). */
size?: "sm" | "md";
}
/** Field height per size — bar search is 36pt, standalone fields 44. */
const FIELD_HEIGHT = { sm: 36, md: 44 } as const;
/**
* SearchInput — search is a light. Focus brightens the field (muted → card
* over timing.fast) and lights its top edge; there is no outer halo. While a
* debounced query is pending (or `searching` is set) the leading glyph swaps
* in place for three dots that brighten in turn, and swaps back when results
* land. Nothing sweeps across the field.
* The clear button ignites and dims in place. An error flickers the field
* once (4px into spring.shake). Pair with `SearchMatch` so each result
* lights the part the query matched.
*/
export const SearchInput = forwardRef<React.ElementRef<typeof TextInput>, SearchInputProps>(
function SearchInput(
{
label,
helper,
error,
debounceMs,
searching = false,
onClear,
icon,
className,
containerClassName,
value,
defaultValue,
onChangeText,
editable = true,
returnKeyType = "search",
onFocus,
onBlur,
glass = false,
glassTint,
size = "md",
...props
},
ref
) {
const height = FIELD_HEIGHT[size];
const haptics = useHaptic();
const { colors } = useTheme();
const reduceMotion = useReducedMotion();
// Built-in label gets a stable nativeID so the field can point back at
// it via accessibilityLabelledBy / aria-labelledby (Input parity).
const autoId = React.useId();
const labelId = `${autoId}-label`;
/** Focus progression — the field brightens and its top edge lights. */
const focusT = useSharedValue(0);
/** Error flicker offset. */
const shakeX = useSharedValue(0);
/** Error/helper text entrance: 0 hidden → 1 visible. */
const msgT = useSharedValue(error || helper ? 1 : 0);
/** Disabled ↔ enabled crossfade. */
const live = useSharedValue(editable ? 1 : DISABLED_OPACITY);
const hadError = useRef(!!error);
const [display, setDisplay] = useState<string>(() => {
const v = value ?? defaultValue;
return typeof v === "string" ? v : "";
});
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const [pending, setPending] = useState(false);
useEffect(() => {
if (value !== undefined) setDisplay(value);
}, [value]);
useEffect(() => {
live.value = withTiming(editable ? 1 : DISABLED_OPACITY, timing.normal);
}, [editable, live]);
// Error → one flicker; message switches on under the field (Input parity).
useEffect(() => {
if (error && !hadError.current) {
haptics.warning();
if (!reduceMotion) {
shakeX.value = ERROR_KICK;
shakeX.value = withSpring(0, spring.shake);
}
hadError.current = true;
} else if (!error) {
hadError.current = false;
}
const target = error || helper ? 1 : 0;
msgT.value = reduceMotion ? target : withTiming(target, timing.fast);
}, [error, helper, msgT, shakeX, reduceMotion, haptics]);
// Searching — the leading glyph swaps in place for three dots that
// brighten in turn while a query is pending or a search runs.
const working = (pending || searching) && editable;
const busyOn = useSharedValue(0);
const lap = useSharedValue(0);
useEffect(() => {
busyOn.value = working ? withTiming(1, IGNITE) : withTiming(0, { ...timing.recede, easing: Easing.bezier(...ease.in) });
if (!working || reduceMotion) {
cancelAnimation(lap);
return;
}
lap.value = 0;
lap.value = withRepeat(withTiming(1, { duration: BUSY_CYCLE_MS, easing: Easing.linear }), -1, false);
return () => cancelAnimation(lap);
}, [working, reduceMotion, busyOn, lap]);
const glyphStyle = useAnimatedStyle(() => ({ opacity: 1 - busyOn.value }));
const dotsStyle = useAnimatedStyle(() => ({ opacity: busyOn.value }));
const fieldStyle = useAnimatedStyle(() => ({
transform: [{ translateX: shakeX.value }],
opacity: live.value,
// Muted fill at rest; focus brightens it to the card surface.
backgroundColor: interpolateColor(focusT.value, [0, 1], [colors.muted, colors.card]),
borderColor: error ? colors.destructive : interpolateColor(focusT.value, [0, 1], [colors.muted, colors.border]),
}));
// Glass capsule keeps its material — only the flicker and the dim.
const glassShakeStyle = useAnimatedStyle(() => ({
transform: [{ translateX: shakeX.value }],
opacity: live.value,
}));
const litStyle = useAnimatedStyle(() => ({ opacity: focusT.value }));
const msgStyle = useAnimatedStyle(() => ({
opacity: msgT.value,
transform: [{ translateY: reduceMotion ? 0 : (1 - msgT.value) * -4 }],
}));
useEffect(() => {
return () => {
if (timer.current) clearTimeout(timer.current);
};
}, []);
const emit = (text: string) => {
if (timer.current) clearTimeout(timer.current);
if (debounceMs && debounceMs > 0) {
setPending(text.length > 0);
timer.current = setTimeout(() => {
setPending(false);
onChangeText?.(text);
}, debounceMs);
} else {
onChangeText?.(text);
}
};
const handleChangeText = (text: string) => {
setDisplay(text);
emit(text);
};
const handleClear = () => {
haptics.selection();
if (timer.current) clearTimeout(timer.current);
setPending(false);
setDisplay("");
onChangeText?.("");
onClear?.();
};
const radius = glass ? height / 2 : size === "sm" ? 10 : 12;
return (
<View className={cn("w-full gap-1.5", containerClassName)}>
{label ? (
<Text
nativeID={labelId}
className="text-sm font-medium text-foreground"
accessibilityRole="text"
>
{label}
</Text>
) : null}
<FieldSurface glass={glass} height={height} tint={glassTint}>
<Animated.View
style={glass ? glassShakeStyle : fieldStyle}
className={cn(
// Constant border-[1.5px] — width never flickers; the colour is
// animated in fieldStyle, not swapped via classes.
"w-full flex-row items-center overflow-hidden border-[1.5px] border-transparent",
size === "sm" ? "h-9 px-2" : "h-11 px-3",
glass ? "rounded-full border-0" : size === "sm" ? "rounded-[10px]" : "rounded-xl"
)}
>
{/* Leading glyph — while searching it swaps in place for busy dots. */}
<View className="items-center justify-center">
<Animated.View style={glyphStyle}>
{icon ?? <Icon name="search" size="sm" color="mutedForeground" />}
</Animated.View>
<Animated.View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={[{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, flexDirection: "row", alignItems: "center", justifyContent: "center", gap: BUSY_DOT / 2 }, dotsStyle]}
>
{[0, 1, 2].map((i) => (
<BusyDot key={i} index={i} lap={lap} color={colors.mutedForeground} still={!!reduceMotion} />
))}
</Animated.View>
</View>
{/* AnimatedTextInput is the shared className-registered primitive —
a drop-in TextInput accepting the same props + className. */}
<AnimatedTextInput
ref={ref}
value={display}
editable={editable}
returnKeyType={returnKeyType}
placeholderTextColor={colors.mutedForeground}
onFocus={(e) => {
focusT.value = withTiming(1, IGNITE);
onFocus?.(e);
}}
onBlur={(e) => {
focusT.value = withTiming(0, DIM);
onBlur?.(e);
}}
onChangeText={handleChangeText}
className={cn(
"h-full flex-1 px-2 text-foreground",
size === "sm" ? "text-[15px]" : "text-base",
"placeholder:text-muted-foreground",
className
)}
accessibilityRole="search"
accessibilityLabel={label ?? props.accessibilityLabel}
accessibilityLabelledBy={label ? labelId : undefined}
aria-labelledby={label ? labelId : undefined}
// Hint is helper only — errors are announced by the live
// region below, so repeating them here double-announces.
accessibilityHint={helper}
accessibilityState={{ disabled: !editable, busy: working }}
// accessibilityState isn't forwarded to the DOM on web — mirror
// the error with an explicit aria-invalid like Checkbox does.
aria-invalid={!!error}
aria-busy={working}
{...props}
/>
{editable ? <ClearButton visible={display.length > 0} onPress={handleClear} /> : null}
{/* Focus lights the top edge of the field. */}
<Animated.View pointerEvents="none" style={[{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0 }, litStyle]}>
<LitEdge tone={glass ? "fill" : "surface"} radius={radius} />
</Animated.View>
</Animated.View>
</FieldSurface>
{error || helper ? (
<Animated.View style={msgStyle}>
{error ? (
<Text
className="text-sm text-destructive"
accessibilityLiveRegion="polite"
accessibilityRole="alert"
>
{error}
</Text>
) : (
<Text className="text-sm text-muted-foreground">{helper}</Text>
)}
</Animated.View>
) : null}
</View>
);
}
);
SearchInput.displayName = "SearchInput";
export interface SearchMatchProps {
/** The result text. */
text: string;
/** The query — its first case-insensitive match is lit. */
query: string;
/** Classes for the whole line (size, weight). */
className?: string;
numberOfLines?: number;
}
/** SearchMatch — a result line where the query lights its match: the matched
* part is full ink, the rest muted. With no query the whole line is ink. */
export const SearchMatch = forwardRef<React.ElementRef<typeof Text>, SearchMatchProps>(function SearchMatch(
{ text, query, className, numberOfLines },
ref
) {
const q = query.trim().toLowerCase();
const at = q ? text.toLowerCase().indexOf(q) : -1;
if (at < 0) {
return (
<Text ref={ref} className={cn(q ? "text-muted-foreground" : "text-foreground", className)} numberOfLines={numberOfLines}>
{text}
</Text>
);
}
return (
<Text ref={ref} className={cn("text-muted-foreground", className)} numberOfLines={numberOfLines} accessibilityLabel={text}>
{text.slice(0, at)}
<Text className="text-foreground">{text.slice(at, at + q.length)}</Text>
{text.slice(at + q.length)}
</Text>
);
});
SearchMatch.displayName = "SearchMatch";
/** Field surface — glass capsule or plain field, keeping the field row
* identical underneath so focus/flicker behavior is shared. */
function FieldSurface({
glass,
height,
tint,
children,
}: {
glass?: boolean;
height: number;
tint?: string;
children: React.ReactNode;
}) {
if (!glass) return <>{children}</>;
return (
<Glass effect="regular" tintColor={tint} className="w-full rounded-full" style={{ height }}>
{children}
</Glass>
);
} import { SearchInput } from "@/components/ui/search-input/search-input";
export function Example() {
return (
<SearchInput />
);
} Installation
Install the dependencies
npx expo install react-native-reanimatedAdd the components it builds on
Copy the source from the Code tab into your project
components/ui/search-input/search-input.tsxcomponents/ui/search-input/index.tsIcons it renders
Update the import paths to match your project setup.
Usage
import { SearchInput, SearchMatch } from "@/components/ui/search-input/search-input"; <SearchInput /> Also exported: SearchMatch.
Examples
The people directory in a team workspace.
import * as React from "react";
import { View } from "react-native";
import { SwitchOn, rowDelay } from "@lumioui/core";
import { SearchInput, SearchMatch } from "../search-input";
import { Avatar } from "../../avatar/avatar";
import { Text } from "../../text/text";
interface Person {
id: string;
name: string;
detail: string;
img: number;
}
const PEOPLE: Person[] = [
{ id: "1", name: "Aiko Tanabe", detail: "Design · Tokyo", img: 5 },
{ id: "2", name: "Bram de Vries", detail: "Engineering · Amsterdam", img: 12 },
{ id: "3", name: "Camila Reyes", detail: "Sales · Bogotá", img: 32 },
{ id: "4", name: "Dev Malhotra", detail: "Engineering · Pune", img: 14 },
{ id: "5", name: "Elif Kaya", detail: "Support · Istanbul", img: 44 },
{ id: "6", name: "Felix Brandt", detail: "Finance · Hamburg", img: 59 },
{ id: "7", name: "Grace Okafor", detail: "Engineering · Lagos", img: 47 },
];
/** Debounce before the directory looks — busy dots hold the glyph meanwhile. */
const DEBOUNCE = 260;
/** The directory lookup itself. */
const LOOKUP = 380;
/** SearchDirectory — the people directory in a team workspace. Type and the
* search glyph swaps for busy dots while the lookup runs; when results
* land it swaps back, the rows switch on top to bottom 40ms apart, the
* count swaps in place and every row lights the part your query matched. */
export function SearchDirectory() {
const [text, setText] = React.useState("eng");
const [query, setQuery] = React.useState("eng");
const [searching, setSearching] = React.useState(false);
const [round, setRound] = React.useState(0);
const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
React.useEffect(() => () => {
if (timer.current) clearTimeout(timer.current);
}, []);
const run = (q: string) => {
if (timer.current) clearTimeout(timer.current);
if (!q.trim()) {
setSearching(false);
setQuery("");
setRound((n) => n + 1);
return;
}
setSearching(true);
timer.current = setTimeout(() => {
setSearching(false);
setQuery(q);
setRound((n) => n + 1);
}, LOOKUP);
};
const q = query.trim().toLowerCase();
const results = q ? PEOPLE.filter((p) => `${p.name} ${p.detail}`.toLowerCase().includes(q)) : PEOPLE;
const count = q ? `${results.length} ${results.length === 1 ? "match" : "matches"}` : "Everyone";
return (
<View className="w-full gap-4">
<Text className="px-1 text-3xl font-bold tracking-tight">People</Text>
<SearchInput
placeholder="Name, team or city"
value={text}
onChangeText={(t) => {
setText(t);
run(t);
}}
debounceMs={DEBOUNCE}
searching={searching}
accessibilityLabel="Search people"
/>
{results.length > 0 ? (
<View className="gap-2">
{/* The count swaps in place when results land. */}
<SwitchOn key={`count-${round}`} className="px-4">
<Text className="text-[13px] text-muted-foreground" accessibilityLiveRegion="polite">
{count}
</Text>
</SwitchOn>
<View className="overflow-hidden rounded-2xl bg-card">
{results.map((p, i) => (
<SwitchOn key={`${round}-${p.id}`} delay={rowDelay(i)}>
{i > 0 ? <View className="ml-[68px] h-px bg-border" /> : null}
<View className="min-h-14 flex-row items-center gap-3 px-4 py-2">
<Avatar size="md" source={{ uri: `https://i.pravatar.cc/150?img=${p.img}` }} fallback={p.name[0]} />
<View className="min-w-0 flex-1">
<SearchMatch text={p.name} query={query} className="text-base font-medium" numberOfLines={1} />
<SearchMatch text={p.detail} query={query} className="text-sm" numberOfLines={1} />
</View>
</View>
</SwitchOn>
))}
</View>
</View>
) : (
<SwitchOn key={`empty-${round}`} className="items-center gap-1 rounded-2xl bg-card px-6 py-10">
<Text className="text-[17px] font-semibold">No one called “{query.trim()}”</Text>
<Text variant="muted" className="text-center">Try a first name, a team like Design, or a city.</Text>
</SwitchOn>
)}
</View>
);
} A maps-style capsule floating over the map/photo layer at the bottom edge, where the thumb lives.
import * as React from "react";
import { Image, StyleSheet, View } from "react-native";
import { SearchInput } from "../search-input";
const PHOTO =
"https://images.unsplash.com/photo-1558370781-d6196949e317?w=800&h=1000&fit=crop&q=70&auto=format";
/** SearchInputGlass — a maps-style capsule floating over the map/photo
* layer at the bottom edge, where the thumb lives. Glass is earned: it
* rides over photographic content. Focus lights the capsule's rim; type and
* the clear button ignites in place. */
export function SearchInputGlass() {
const [q, setQ] = React.useState("");
return (
<View className="relative h-[460px] w-full overflow-hidden rounded-3xl bg-muted">
<Image source={{ uri: PHOTO }} style={StyleSheet.absoluteFill} resizeMode="cover" accessibilityIgnoresInvertColors />
<View className="absolute inset-x-4 bottom-5">
<SearchInput
glass
value={q}
onChangeText={setQ}
placeholder="Search for a place or address"
accessibilityLabel="Search places"
/>
</View>
</View>
);
} API reference
SearchInput
label string Visible label above the field.
—helper string Helper text below the field.
—error string Error message.
—debounceMs number Debounce duration in ms for onChangeText. While a debounced query is pending, the leading glyph shows busy dots.
—searching boolean A search is running (e.g. awaiting results) — the leading glyph shows busy dots until it turns false, then swaps back.
false onClear () => void Called when the clear button is pressed.
—icon React.ReactNode Leading icon slot.
—className string Classes for the input element.
—containerClassName string Classes for the outer wrapper.
—glass boolean Capsule mode — the field becomes a floating glass pill (search rides over content instead of sitting on the surface).
false glassTint string Glass mode only: tint the capsule (e.g. a dark wash over a bright photo).
—size "sm" | "md" Field height — "sm" 36pt (search inside a navigation bar), "md" 44pt (default, standalone search on a screen).
"md" SearchMatch
text* string The result text.
—query* string The query — its first case-insensitive match is lit.
—className string Classes for the whole line (size, weight).
—numberOfLines number —