61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
import jalaali from "jalaali-js";
|
|
import { useEffect, useState } from "react";
|
|
import type { CalendarDate } from "~/types/util.type";
|
|
|
|
const { jy } = jalaali.toJalaali(new Date());
|
|
|
|
const DATE_PATTERN = /^\d{4}\/\d{2}\/\d{2}$/;
|
|
|
|
export function defaultCalendarDate(): CalendarDate {
|
|
return {
|
|
start: `${jy}/01/01`,
|
|
end: `${jy}/12/30`,
|
|
sinceMonth: "بهار",
|
|
untilMonth: "زمستان",
|
|
};
|
|
}
|
|
|
|
export function readStoredDate(): CalendarDate {
|
|
const fallback = defaultCalendarDate();
|
|
try {
|
|
const raw = localStorage.getItem("dateSelected");
|
|
const parsed = raw ? JSON.parse(raw) : {};
|
|
// Accept and normalize the naming used by older builds.
|
|
const start = parsed?.start ?? parsed?.startDate;
|
|
const end = parsed?.end ?? parsed?.endDate;
|
|
if (
|
|
typeof start === "string" &&
|
|
typeof end === "string" &&
|
|
DATE_PATTERN.test(start) &&
|
|
DATE_PATTERN.test(end) &&
|
|
start <= end
|
|
) {
|
|
const normalized: CalendarDate = {
|
|
start,
|
|
end,
|
|
sinceMonth: parsed.sinceMonth,
|
|
untilMonth: parsed.untilMonth ?? parsed.fromMonth,
|
|
};
|
|
localStorage.setItem("dateSelected", JSON.stringify(normalized));
|
|
return normalized;
|
|
}
|
|
} catch {
|
|
// Invalid/stale browser state is replaced below.
|
|
}
|
|
localStorage.setItem("dateSelected", JSON.stringify(fallback));
|
|
return fallback;
|
|
}
|
|
|
|
export function useStoredDate(): [
|
|
CalendarDate,
|
|
React.Dispatch<React.SetStateAction<CalendarDate>>,
|
|
] {
|
|
const [date, setDate] = useState<CalendarDate>({});
|
|
|
|
useEffect(() => {
|
|
setDate(readStoredDate());
|
|
}, [jy]);
|
|
|
|
return [date, setDate];
|
|
}
|