Files
cunningham/packages/react/src/components/Forms/DatePicker/utils.ts
Lebaud Antoine 0dae71aa92 ♻️(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.
2023-07-10 22:05:33 +02:00

49 lines
1.3 KiB
TypeScript

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,
});