53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import { useEffect, useState } from "react";
|
||
import DatePicker, { type DateObject } from "react-multi-date-picker";
|
||
import persian from "react-date-object/calendars/persian";
|
||
import persian_fa from "react-date-object/locales/persian_fa";
|
||
import { latinDigits } from "../lib/persianDate";
|
||
|
||
type Props = {
|
||
name?: string;
|
||
value?: string;
|
||
defaultValue?: string;
|
||
required?: boolean;
|
||
disabled?: boolean;
|
||
placeholder?: string;
|
||
onChange?: (value: string) => void;
|
||
};
|
||
|
||
export function PersianDateInput({ name, value, defaultValue, required, disabled, placeholder, onChange }: Props) {
|
||
const controlled = value !== undefined;
|
||
const [innerValue, setInnerValue] = useState(defaultValue ?? "");
|
||
const current = controlled ? value ?? "" : innerValue;
|
||
|
||
useEffect(() => {
|
||
if (!controlled) setInnerValue(defaultValue ?? "");
|
||
}, [controlled, defaultValue]);
|
||
|
||
function update(date: DateObject | null) {
|
||
const next = date ? latinDigits(date.format("YYYY/MM/DD")) : "";
|
||
if (!controlled) setInnerValue(next);
|
||
onChange?.(next);
|
||
}
|
||
|
||
return <>
|
||
<DatePicker
|
||
value={current || undefined}
|
||
onChange={update}
|
||
calendar={persian}
|
||
locale={persian_fa}
|
||
format="YYYY/MM/DD"
|
||
calendarPosition="bottom-right"
|
||
containerClassName="persian-date-container"
|
||
inputClass="input persian-date-input"
|
||
name={name}
|
||
required={required}
|
||
disabled={disabled}
|
||
placeholder={placeholder ?? "۱۴۰۴/۰۱/۰۱"}
|
||
inputMode="numeric"
|
||
editable
|
||
/>
|
||
</>;
|
||
}
|
||
|
||
|