@veracity/vui
Version:
Veracity UI is a React component library crafted for use within Veracity applications and pages. Based on Styled Components and @xstyled.
87 lines (85 loc) • 2.83 kB
JavaScript
import { parseIsoDate, validateDateFormat } from "../utils/dates.js";
import { formatDate } from "../utils/formatDate.js";
import { T } from "../t/t.js";
import { Input } from "../input/input.js";
import { useCallback, useEffect, useRef, useState } from "react";
import { jsx } from "react/jsx-runtime";
//#region src/datePicker/dateInput.tsx
const isValidDate = (dateString) => !!validateDateFormat(dateString) && !!parseIsoDate(dateString);
const DateInput = ({ initialDate, onChange, onValidate, setValidateStatus, autoFocus, ...rest }) => {
const inputRef = useRef(null);
const [dateInput, setDateInput] = useState(initialDate ? formatDate(initialDate, "YYYY-MM-DD", { timeZone: "UTC" }) : "");
const [dateInputValidated, setDateInputValidated] = useState(true);
const [errorMessage, setErrorMessage] = useState("");
const handleOnBlur = useCallback(() => {
setDateInputValidated(!dateInput);
const parsedDate = parseIsoDate(dateInput);
if (parsedDate) {
setDateInput(formatDate(parsedDate, "YYYY-MM-DD", { timeZone: "UTC" }));
const validateMessage = onValidate(parsedDate);
if (!validateMessage) onChange(parsedDate);
setDateInputValidated(!validateMessage);
setErrorMessage(validateMessage);
}
}, [
dateInput,
onValidate,
onChange
]);
useEffect(() => {
const formatted = initialDate ? formatDate(initialDate, "YYYY-MM-DD", { timeZone: "UTC" }) : "";
setDateInput(formatted);
const validation = onValidate(initialDate);
setDateInputValidated(!validation);
setValidateStatus(!validation);
setErrorMessage(validation);
}, [
initialDate,
onValidate,
setValidateStatus
]);
useEffect(() => {
if (dateInput) {
setValidateStatus(isValidDate(dateInput));
if (!validateDateFormat(dateInput)) setErrorMessage("Supported format is YYYY-MM-DD");
else {
const parsedDate = parseIsoDate(dateInput);
if (!parsedDate) setErrorMessage("Invalid date");
else {
const validateMessage = onValidate(parsedDate);
if (!validateMessage) onChange(parsedDate);
setDateInputValidated(!validateMessage);
setErrorMessage(validateMessage);
}
}
}
}, [
dateInput,
onValidate,
onChange,
setValidateStatus
]);
useEffect(() => {
if (autoFocus) inputRef.current?.focus({ preventScroll: true });
}, []);
return /* @__PURE__ */ jsx(Input, {
className: "dateInput",
"data-testid": "test-date-input",
errorText: !dateInputValidated && /* @__PURE__ */ jsx(T, {
size: "md",
children: errorMessage
}),
inputRef,
onBlur: handleOnBlur,
onChange: (e) => setDateInput(e.target.value),
placeholder: "YYYY-MM-DD",
size: "md",
state: !dateInputValidated ? "error" : "default",
value: dateInput,
...rest
});
};
//#endregion
export { DateInput };
globalThis.__vuiVersion__ = "5.3.1"
//# sourceMappingURL=dateInput.js.map