Files
leaudit-platform-frontend/app/components/ui/SearchBox.tsx
T

104 lines
2.8 KiB
TypeScript

import React, { useState, useRef } from 'react';
interface SearchBoxProps {
placeholder?: string;
defaultValue?: string;
onSearch: (value: string) => void;
buttonText?: string;
className?: string;
name?: string;
}
export function SearchBox({
placeholder = '请输入搜索内容',
defaultValue = '',
onSearch,
buttonText = '搜索',
className = '',
name = 'keyword'
}: SearchBoxProps) {
const [inputValue, setInputValue] = useState(defaultValue);
const [isHovering, setIsHovering] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const value = formData.get(name) as string;
onSearch(value);
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setInputValue(value);
// 对于没有按钮的输入框,我们希望在输入时就触发搜索
if (className.includes('form-input-only')) {
onSearch(value);
}
};
const handleClear = () => {
setInputValue('');
if (inputRef.current) {
inputRef.current.value = '';
inputRef.current.focus();
}
onSearch('');
};
const handleMouseEnter = () => {
setIsHovering(true);
};
const handleMouseLeave = () => {
setIsHovering(false);
};
const isIconOnly = buttonText === '';
const isFilterControl = className.includes('filter-control');
const hasButton = !className.includes('form-input-only');
const searchBoxClass = `search-box ${className} ${isFilterControl ? 'search-box-row' : ''}`;
const showClearButton = inputValue && isHovering;
return (
<form onSubmit={handleSubmit} className={searchBoxClass}>
<div
className={`relative ${hasButton ? 'flex-1' : 'w-full'}`}
ref={containerRef}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<input
type="text"
id={name}
name={name}
className={`form-input w-full ${hasButton ? 'rounded-r-none' : ''}`}
placeholder={placeholder}
defaultValue={defaultValue}
onChange={handleChange}
ref={inputRef}
/>
{showClearButton && (
<button
type="button"
className="search-box-clear"
onClick={handleClear}
>
<i className="ri-close-circle-line"></i>
</button>
)}
</div>
{hasButton && (
<button
type="submit"
className={`search-button ${isIconOnly ? "icon-only-btn" : ""}`}
>
<i className="ri-search-line"></i>
{buttonText && <span>{buttonText}</span>}
</button>
)}
</form>
);
}