refactor: simplify calendar and form state
This commit is contained in:
@@ -1,47 +1,22 @@
|
||||
const ISO_DATE_LENGTH = 10;
|
||||
import { calendarDate } from "@/shared/lib";
|
||||
|
||||
const DATE_PART_COUNT = 3;
|
||||
|
||||
type IncomePeriod = { from: string; to: string };
|
||||
|
||||
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
function formatDraftDate(value: string): string {
|
||||
const [year, month, day] = value.split("-", DATE_PART_COUNT);
|
||||
|
||||
return `${day}.${month}.${year}`;
|
||||
}
|
||||
|
||||
function isDate(value: string): boolean {
|
||||
if (!datePattern.test(value)) return false;
|
||||
const parsed = new Date(`${value}T00:00:00Z`);
|
||||
|
||||
return (
|
||||
Number.isFinite(parsed.valueOf())
|
||||
&& parsed.toISOString().slice(0, ISO_DATE_LENGTH) === value
|
||||
);
|
||||
}
|
||||
|
||||
function moscowDate(value: Date): string {
|
||||
const parts = new Intl.DateTimeFormat("en-CA", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
timeZone: "Europe/Moscow",
|
||||
year: "numeric",
|
||||
}).formatToParts(value);
|
||||
|
||||
const part = (type: string) =>
|
||||
parts.find(item => item.type === type)?.value;
|
||||
|
||||
return `${part("year")}-${part("month")}-${part("day")}`;
|
||||
}
|
||||
|
||||
function parseDraftDate(value: string): null | string {
|
||||
if (!/^\d{2}\.\d{2}\.\d{4}$/.test(value))
|
||||
return null;
|
||||
const [day, month, year] = value.split(".", DATE_PART_COUNT);
|
||||
const date = `${year}-${month}-${day}`;
|
||||
|
||||
return isDate(date)
|
||||
return calendarDate.safeParse(date).success
|
||||
? date
|
||||
: null;
|
||||
}
|
||||
@@ -50,8 +25,5 @@ export {
|
||||
formatDraftDate,
|
||||
type IncomePeriod as IncomeForm,
|
||||
type IncomePeriod,
|
||||
isDate,
|
||||
ISO_DATE_LENGTH,
|
||||
moscowDate,
|
||||
parseDraftDate,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user