refactor: search

This commit is contained in:
codytseng
2025-08-31 22:43:47 +08:00
parent 88567c2c13
commit 0153465e29
24 changed files with 785 additions and 345 deletions

View File

@@ -1,33 +1,54 @@
import { cn } from '@/lib/utils'
import { SearchIcon, X } from 'lucide-react'
import { ComponentProps, useEffect, useState } from 'react'
import { ComponentProps, forwardRef, useEffect, useState } from 'react'
export default function SearchInput({ value, onChange, ...props }: ComponentProps<'input'>) {
const [displayClear, setDisplayClear] = useState(false)
const SearchInput = forwardRef<HTMLInputElement, ComponentProps<'input'>>(
({ value, onChange, className, ...props }, ref) => {
const [displayClear, setDisplayClear] = useState(false)
const [inputRef, setInputRef] = useState<HTMLInputElement | null>(null)
useEffect(() => {
setDisplayClear(!!value)
}, [value])
useEffect(() => {
setDisplayClear(!!value)
}, [value])
return (
<div
tabIndex={0}
className={cn(
'flex h-9 w-full items-center rounded-md border border-input bg-transparent px-2 py-1 text-base shadow-sm transition-colors md:text-sm [&:has(:focus-visible)]:ring-ring [&:has(:focus-visible)]:ring-1 [&:has(:focus-visible)]:outline-none'
)}
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<input
{...props}
value={value}
onChange={onChange}
className="size-full mx-2 border-none bg-transparent focus:outline-none placeholder:text-muted-foreground"
/>
{displayClear && (
<button type="button" onClick={() => onChange?.({ target: { value: '' } } as any)}>
<X className="size-4 shrink-0 opacity-50 hover:opacity-100" />
</button>
)}
</div>
)
}
function setRefs(el: HTMLInputElement) {
setInputRef(el)
if (typeof ref === 'function') {
ref(el)
} else if (ref) {
;(ref as React.MutableRefObject<HTMLInputElement | null>).current = el
}
}
return (
<div
tabIndex={0}
className={cn(
'flex h-9 w-full items-center rounded-md border border-input bg-transparent px-2 py-1 text-base shadow-sm transition-colors md:text-sm [&:has(:focus-visible)]:ring-ring [&:has(:focus-visible)]:ring-1 [&:has(:focus-visible)]:outline-none',
className
)}
>
<SearchIcon className="size-4 shrink-0 opacity-50" onClick={() => inputRef?.focus()} />
<input
{...props}
name="search-input"
ref={setRefs}
value={value}
onChange={onChange}
className="size-full mx-2 border-none bg-transparent focus:outline-none placeholder:text-muted-foreground"
/>
{displayClear && (
<button
type="button"
className="rounded-full bg-foreground/40 hover:bg-foreground transition-opacity size-5 shrink-0 flex flex-col items-center justify-center"
onClick={() => onChange?.({ target: { value: '' } } as any)}
>
<X className="!size-3 shrink-0 text-background" strokeWidth={4} />
</button>
)}
</div>
)
}
)
SearchInput.displayName = 'SearchInput'
export default SearchInput