72 lines
2.5 KiB
TypeScript
72 lines
2.5 KiB
TypeScript
import * as React from "react"
|
|
import { SearchIcon, XIcon } from "lucide-react"
|
|
|
|
import { cn } from "../lib/utils"
|
|
|
|
/** Поле поиска на мягкой подложке: иконка, крестик очистки. */
|
|
export const SearchInput = React.forwardRef<
|
|
HTMLInputElement,
|
|
Omit<React.ComponentProps<"input">, "value" | "onChange" | "size"> & {
|
|
value: string
|
|
onValueChange: (value: string) => void
|
|
size?: "sm" | "md" | "lg"
|
|
/** Что показать справа, пока поле пустое (подсказка клавиши). */
|
|
trailing?: React.ReactNode
|
|
}
|
|
>(function SearchInput({ value, onValueChange, size = "md", trailing, className, onKeyDown, ...props }, ref) {
|
|
const innerRef = React.useRef<HTMLInputElement>(null)
|
|
React.useImperativeHandle(ref, () => innerRef.current!)
|
|
|
|
return (
|
|
<div className={cn("relative", className)}>
|
|
<SearchIcon
|
|
className={cn(
|
|
"pointer-events-none absolute top-1/2 -translate-y-1/2 text-muted-foreground",
|
|
size === "lg" ? "left-4 size-5" : "left-3 size-4",
|
|
)}
|
|
/>
|
|
<input
|
|
ref={innerRef}
|
|
type="search"
|
|
value={value}
|
|
onChange={(e) => onValueChange(e.target.value)}
|
|
onKeyDown={(e) => {
|
|
if (e.key === "Escape" && value) {
|
|
e.stopPropagation()
|
|
onValueChange("")
|
|
}
|
|
onKeyDown?.(e)
|
|
}}
|
|
className={cn(
|
|
"w-full rounded-lg border border-transparent bg-muted/70 transition outline-none placeholder:text-muted-foreground/80 [&::-webkit-search-cancel-button]:hidden",
|
|
"focus:border-primary/40 focus:bg-card focus:ring-4 focus:ring-primary/10",
|
|
size === "sm" && "h-8 pr-8 pl-9 text-sm",
|
|
size === "md" && "h-9 pr-8 pl-9 text-sm",
|
|
size === "lg" && "h-12 rounded-xl pr-12 pl-12 text-base",
|
|
)}
|
|
{...props}
|
|
/>
|
|
<div className="absolute top-1/2 right-2 flex -translate-y-1/2 items-center">
|
|
{value ? (
|
|
<button
|
|
type="button"
|
|
aria-label="Очистить"
|
|
onClick={() => {
|
|
onValueChange("")
|
|
innerRef.current?.focus()
|
|
}}
|
|
className={cn(
|
|
"grid place-items-center rounded-md text-muted-foreground hover:bg-muted",
|
|
size === "lg" ? "size-7" : "size-5",
|
|
)}
|
|
>
|
|
<XIcon className={size === "lg" ? "size-4" : "size-3.5"} />
|
|
</button>
|
|
) : (
|
|
trailing
|
|
)}
|
|
</div>
|
|
</div>
|
|
)
|
|
})
|