73 lines
2.7 KiB
TypeScript
73 lines
2.7 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(
|
||
// как Input: рамка на белом, та же подсветка фокуса — в строке фильтров стоит рядом с Select
|
||
"w-full min-w-0 rounded-md border border-input bg-transparent shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground dark:bg-input/30 [&::-webkit-search-cancel-button]:hidden",
|
||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||
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>
|
||
)
|
||
})
|