92 lines
3.1 KiB
TypeScript
92 lines
3.1 KiB
TypeScript
import { useState, useRef, useEffect, type FC } from 'react';
|
|
import { clx, formatTimeToHHmm } from '../helpers/utils';
|
|
import { Clock } from 'iconsax-react';
|
|
import Error from './Error';
|
|
|
|
type Props = {
|
|
onChange: (time: string) => void;
|
|
defaultValue?: string;
|
|
error_text?: string;
|
|
placeholder?: string;
|
|
className?: string;
|
|
label?: string;
|
|
};
|
|
|
|
const TimePickerComponent: FC<Props> = (props: Props) => {
|
|
const [inputValue, setInputValue] = useState<string>('');
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
|
|
useEffect(() => {
|
|
if (props.defaultValue) {
|
|
const timeValue = formatTimeToHHmm(props.defaultValue.replace('.', ':'));
|
|
setInputValue(timeValue);
|
|
}
|
|
}, [props.defaultValue]);
|
|
|
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const timeValue = e.target.value; // فرمت: HH:mm
|
|
setInputValue(timeValue);
|
|
|
|
if (timeValue) {
|
|
// فرمت HH:mm را مستقیماً ارسال میکنیم
|
|
props.onChange(timeValue);
|
|
} else {
|
|
props.onChange('');
|
|
}
|
|
};
|
|
|
|
const handleWrapperClick = () => {
|
|
inputRef.current?.showPicker?.();
|
|
inputRef.current?.focus();
|
|
inputRef.current?.click();
|
|
};
|
|
|
|
return (
|
|
<div className="w-full">
|
|
{props.label && (
|
|
<div className='text-sm'>
|
|
{props.label}
|
|
</div>
|
|
)}
|
|
<div className={clx(
|
|
'relative',
|
|
props.label && 'mt-1.5'
|
|
)}>
|
|
<div
|
|
onClick={handleWrapperClick}
|
|
className={clx(
|
|
'w-full bg-white h-10 text-black flex items-center px-4 pl-10 pr-4 text-xs rounded-xl border border-border cursor-pointer relative',
|
|
'hover:border-primary transition-colors',
|
|
props.className
|
|
)}
|
|
>
|
|
<input
|
|
ref={inputRef}
|
|
type="time"
|
|
value={inputValue}
|
|
onChange={handleChange}
|
|
className="absolute opacity-0 w-full h-full cursor-pointer"
|
|
/>
|
|
{!inputValue && (
|
|
<span className="absolute right-4 text-description pointer-events-none">
|
|
{props.placeholder || 'انتخاب زمان'}
|
|
</span>
|
|
)}
|
|
{inputValue && (
|
|
<span className="absolute right-4 pointer-events-none text-black">
|
|
{inputValue}
|
|
</span>
|
|
)}
|
|
<Clock size={20} color="#8C90A3" className='absolute left-2 top-1/2 -translate-y-1/2 pointer-events-none z-10' />
|
|
</div>
|
|
{props.error_text && props.error_text !== '' && (
|
|
<Error errorText={props.error_text} />
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default TimePickerComponent;
|
|
|