parent
0805d70c07
commit
9d1e6df8f0
@ -0,0 +1,67 @@
|
||||
import { DatePickerProps } from 'antd';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
|
||||
interface RangePickerPreset {
|
||||
range: number;
|
||||
}
|
||||
|
||||
export default function useRangePickerPreset(options?: RangePickerPreset): {
|
||||
disabledRangeDaysDate: DatePickerProps['disabledDate'];
|
||||
rangePresets: {
|
||||
label: React.ReactNode;
|
||||
value: [Dayjs, Dayjs] | (() => [Dayjs, Dayjs]);
|
||||
}[];
|
||||
range: number;
|
||||
} {
|
||||
const { range = 60 } = options || {};
|
||||
|
||||
const getYearMonth = (date: Dayjs) => date.year() * 12 + date.month();
|
||||
|
||||
const disabledRangeDaysDate: DatePickerProps['disabledDate'] = (
|
||||
current,
|
||||
{ from, type }
|
||||
) => {
|
||||
// before 2025 is not allowed
|
||||
if (current.year() < 2025) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (from) {
|
||||
const minDate = from.add(1 - range, 'days');
|
||||
const maxDate = from.add(range - 1, 'days');
|
||||
|
||||
switch (type) {
|
||||
case 'year':
|
||||
return (
|
||||
current.year() < minDate.year() || current.year() > maxDate.year()
|
||||
);
|
||||
|
||||
case 'month':
|
||||
return (
|
||||
getYearMonth(current) < getYearMonth(minDate) ||
|
||||
getYearMonth(current) > getYearMonth(maxDate)
|
||||
);
|
||||
|
||||
default:
|
||||
return Math.abs(current.diff(from, 'days')) >= range;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const rangePresets: {
|
||||
label: React.ReactNode;
|
||||
value: [Dayjs, Dayjs] | (() => [Dayjs, Dayjs]);
|
||||
}[] = [
|
||||
{ label: 'Last 7 Days', value: [dayjs().add(-7, 'd'), dayjs()] },
|
||||
{ label: 'Last 30 Days', value: [dayjs().add(-30, 'd'), dayjs()] },
|
||||
{ label: 'Last 60 Days', value: [dayjs().add(-60, 'd'), dayjs()] }
|
||||
];
|
||||
|
||||
return {
|
||||
disabledRangeDaysDate,
|
||||
rangePresets,
|
||||
range
|
||||
};
|
||||
}
|
||||
Loading…
Reference in new issue