import { endOfMonth, endOfYear, format, startOfMonth, startOfYear, subDays, subMonths, subYears, } from 'date-fns'; import { useEffect, useId, useState } from 'react'; import { Calendar, DateRange } from '@/components/originui/calendar'; import { Button } from '@/components/ui/button'; import { Popover, PopoverContent, PopoverTrigger, } from '@/components/ui/popover'; import { cn } from '@/lib/utils'; import { CalendarIcon } from 'lucide-react'; const CalendarComp = ({ selectDateRange, onSelect, ...props }: ITimeRangePickerProps) => { const today = new Date(); const yesterday = { from: subDays(today, 1), to: subDays(today, 1), }; const last7Days = { from: subDays(today, 6), to: today, }; const last30Days = { from: subDays(today, 29), to: today, }; const monthToDate = { from: startOfMonth(today), to: today, }; const lastMonth = { from: startOfMonth(subMonths(today, 1)), to: endOfMonth(subMonths(today, 1)), }; const yearToDate = { from: startOfYear(today), to: today, }; const lastYear = { from: startOfYear(subYears(today, 1)), to: endOfYear(subYears(today, 1)), }; const dateRangeList = [ { key: 'yestday', value: yesterday }, { key: 'last7Days', value: last7Days }, { key: 'last30Days', value: last30Days }, { key: 'monthToDate', value: monthToDate }, { key: 'lastMonth', value: lastMonth }, { key: 'yearToDate', value: yearToDate }, { key: 'lastYear', value: lastYear }, ]; const [month, setMonth] = useState(today); const [date, setDate] = useState(selectDateRange || last7Days); useEffect(() => { onSelect?.(date); }, [date, onSelect]); return (
{dateRangeList.map((dateRange) => ( ))}
{ if (newDate) { setDate(newDate as DateRange); } }} month={month} onMonthChange={setMonth} className="p-2" {...props} // disabled={[ // { after: today }, // Dates before today // ]} />
); }; export type ITimeRangePickerProps = { onSelect: (e: DateRange) => void; selectDateRange: DateRange; className?: string; }; const TimeRangePicker = ({ onSelect, selectDateRange, ...props }: ITimeRangePickerProps) => { const id = useId(); const today = new Date(); const [date, setDate] = useState( selectDateRange || { from: today, to: today }, ); useEffect(() => { setDate(selectDateRange); }, [selectDateRange]); const onChange = (e: DateRange | undefined) => { if (!e) return; setDate(e); onSelect?.(e); }; return ( ); }; export default TimeRangePicker;