♻️(react) extract duplicated utility functions and types

DateRangePicker and DatePicker would share quite a lot of
common logics. Make sure the code elements are factorised
easily reusable in each components.
This commit is contained in:
Lebaud Antoine
2023-06-16 13:49:47 +02:00
committed by aleb_the_flash
parent d16ada2825
commit 0dae71aa92
3 changed files with 213 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
import {
CalendarDate,
parseAbsoluteToLocal,
toCalendarDate,
} from "@internationalized/date";
import { DateRange } from "react-aria";
import {
StringOrDate,
StringsOrDateRange,
} from ":/components/Forms/DatePicker/types";
import { DatePickerAuxSubProps } from ":/components/Forms/DatePicker/DatePickerAux";
export const parseCalendarDate = (
rawDate: StringOrDate | undefined
): undefined | CalendarDate => {
if (!rawDate) {
return undefined;
}
try {
const ISODateString = new Date(rawDate).toISOString();
return toCalendarDate(parseAbsoluteToLocal(ISODateString));
} catch (e) {
throw new Error(
"Invalid date format when initializing props on DatePicker component"
);
}
};
export const parseRangeCalendarDate = (
rawRange: StringsOrDateRange | undefined
): DateRange | undefined => {
if (!rawRange || !rawRange[0] || !rawRange[1]) {
return undefined;
}
return {
start: parseCalendarDate(rawRange[0])!,
end: parseCalendarDate(rawRange[1])!,
};
};
export const getDefaultPickerOptions = (props: DatePickerAuxSubProps): any => ({
minValue: parseCalendarDate(props.minValue),
maxValue: parseCalendarDate(props.maxValue),
shouldCloseOnSelect: true,
granularity: "day",
isDisabled: props.disabled,
label: props.label,
});