@veracity/vui
Version:
Veracity UI is a React component library crafted for use within Veracity applications and pages. Based on Styled Components and @xstyled.
72 lines (70 loc) • 2.62 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 { useEffect, useState } from "react";
import { jsx } from "react/jsx-runtime";
//#region src/datePicker/dateInput.tsx
const DateInput = ({ initialDate, onChange, onValidate, setValidateStatus, ...rest }) => {
const formattedInitialDate = initialDate ? formatDate(initialDate, "YYYY-MM-DD", { timeZone: "UTC" }) : "";
const [dateInput, setDateInput] = useState(formattedInitialDate);
const [dateInputValidated, setDateInputValidated] = useState(true);
const [errorMessage, setErrorMessage] = useState("");
const isValidDate = (dateString) => {
if (!validateDateFormat(dateString)) return false;
if (!parseIsoDate(dateString)) return false;
return true;
};
const handleOnBlur = () => {
setDateInputValidated(!dateInput);
const parsedDate = parseIsoDate(dateInput);
if (parsedDate) {
setDateInput(formatDate(parsedDate, "YYYY-MM-DD", { timeZone: "UTC" }));
const validateMessage = onValidate(parsedDate);
!validateMessage && onChange(parsedDate);
setDateInputValidated(!validateMessage);
setErrorMessage(validateMessage);
}
};
useEffect(() => {
setDateInput(formattedInitialDate);
const validation = onValidate(initialDate);
setDateInputValidated(!validation);
setValidateStatus(!validation);
setErrorMessage(validation);
}, [initialDate]);
useEffect(() => {
if (dateInput) {
setValidateStatus(isValidDate(dateInput));
if (!validateDateFormat(dateInput)) setErrorMessage("Supported format is YYYY-MM-DD");
else if (!parseIsoDate(dateInput)) setErrorMessage("Invalid date");
else {
const parsedDate = parseIsoDate(dateInput);
const validateMessage = onValidate(parsedDate);
!validateMessage && onChange(parsedDate);
setDateInputValidated(!validateMessage);
setErrorMessage(validateMessage);
}
}
}, [dateInput]);
return /* @__PURE__ */ jsx(Input, {
borderColor: dateInputValidated ? "sandstone.main" : "energyRed.main",
className: "dateInput",
"data-testid": "test-date-input",
errorText: !dateInputValidated && /* @__PURE__ */ jsx(T, {
size: "md",
children: errorMessage
}),
onBlur: handleOnBlur,
onChange: (e) => setDateInput(e.target.value),
placeholder: "YYYY-MM-DD",
size: "md",
state: !dateInputValidated && !errorMessage ? "error" : "default",
value: dateInput,
...rest
});
};
//#endregion
export { DateInput };
globalThis.__vuiVersion__ = "5.3.0-alpha.2"
//# sourceMappingURL=dateInput.js.map