import React, { useState } from "react"; import { CalendarIcon } from "lucide-react"; import dayjs from "dayjs"; import timezone from "dayjs/plugin/timezone"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Calendar, DateRange } from "@/components/ui/calendar_v9"; import { Input } from "@/components/ui/input"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { DoneButton, EARLIEST_DATE, LATEST_DATE, PickerInput, PREVENT_DEFAULT, QuickOption, } from "./SelectDate"; dayjs.extend(timezone); export type PickDateTimeRangeProps = { range?: DateRange; quickOptions?: Array<{ label: string; range: DateRange }>; showTimezone?: boolean; onSelect: (range: DateRange | undefined) => void; }; export const PickDateTimeRange: React.FC = ({ range, quickOptions, showTimezone, onSelect, }) => { const [month, setMonth] = useState(range?.from); function initializeRange(e) { e.preventDefault(); if (!range) { const to = dayjs().toDate(); const from = dayjs(to).subtract(7, "days").toDate(); onSelect({ from, to }); } } return ( <> {quickOptions?.length ? (
Quick Options
{quickOptions.map((option, idx) => ( { onSelect(option.range); setMonth(option.range.from); }} /> ))}
) : null}
{ onSelect(range); setMonth( range?.to === triggerDate && dayjs(range.to).diff(dayjs(range.from), "months") > 1 ? dayjs(range.to).subtract(1, "month").toDate() : range?.from, ); }} numberOfMonths={2} captionLayout="dropdown" startMonth={EARLIEST_DATE} endMonth={LATEST_DATE} hidden={{ before: EARLIEST_DATE, after: LATEST_DATE }} required={false} />
{ const value = dayjs(e.target.value).toDate(); if (dayjs(value).isValid()) { setMonth(value); onSelect({ from: value, to: range?.to && value > range.to ? value : range?.to, }); } }} onMouseDown={initializeRange} onFocus={PREVENT_DEFAULT} onClick={PREVENT_DEFAULT} />
{ const value = dayjs(e.target.value).toDate(); if (dayjs(value).isValid()) { setMonth(value); onSelect({ to: value, from: range?.from && value < range.from ? value : range?.from, }); } }} onMouseDown={initializeRange} onFocus={PREVENT_DEFAULT} onClick={PREVENT_DEFAULT} />
{showTimezone && (
Time Zone: {(dayjs as any)?.["tz"]?.guess()}
)} ); }; // Popover containing a PickDateTimeRange const SelectDateTimeRange: React.FC< Omit & { initialRange?: DateRange; align: "center" | "start" | "end"; } > = ({ initialRange, align = "start", quickOptions, showTimezone, onSelect, }) => { const [isOpen, setIsOpen] = useState(false); const toggle = (value?: boolean) => { if (!isOpen) { setTimestampRange(initialRange); } setIsOpen(value === undefined ? !isOpen : value); }; const [timestampRange, setTimestampRange] = useState( initialRange, ); return (
{ onSelect(timestampRange); toggle(false); }} />
); }; export default SelectDateTimeRange;