Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for filtering by date AND time #1416

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useMemo, useState } from "react";
import React, { useMemo, useState, useRef, useCallback } from "react";
import { Calendar as CalendarIcon } from "lucide-react";
import debounce from "lodash/debounce";

import { cn } from "@/lib/utils";
import { formatDate } from "@/lib/date";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
Expand All @@ -10,12 +10,12 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Input } from "@/components/ui/input";
import { Filter } from "@/types/filters";
import OperatorSelector from "@/components/shared/FiltersButton/OperatorSelector";
import { DEFAULT_OPERATORS, OPERATORS_MAP } from "@/constants/filters";
import { COLUMN_TYPE } from "@/types/shared";
import dayjs from "dayjs";
import { SelectSingleEventHandler } from "react-day-picker";

type TimeRowProps = {
filter: Filter;
Expand All @@ -27,19 +27,156 @@ export const TimeRow: React.FunctionComponent<TimeRowProps> = ({
onChange,
}) => {
const [open, setOpen] = useState(false);
const date = useMemo(
() => (dayjs(filter.value).isValid() ? new Date(filter.value) : undefined),
[filter.value],
const [inputValue, setInputValue] = useState(() =>
filter.value ? formatDate(filter.value as string) : "",
);
const [pendingDate, setPendingDate] = useState<Date | undefined>(undefined);
const [pendingTime, setPendingTime] = useState<string>("00:00");
const lastFilterValue = useRef(filter.value);

const onSelectDate: SelectSingleEventHandler = (value) => {
onChange({
...filter,
value: value ? value.toISOString() : "",
});
setOpen(false);
const date = useMemo(() => {
if (!filter.value) return undefined;
const parsed = dayjs(filter.value);
return parsed.isValid() ? parsed.toDate() : undefined;
}, [filter.value]);

// Only update input value when filter value changes from external sources
React.useEffect(() => {
if (filter.value !== lastFilterValue.current) {
setInputValue(filter.value ? formatDate(filter.value as string) : "");
lastFilterValue.current = filter.value;
}
}, [filter.value]);

const debouncedUpdateFilter = useCallback(
(newValue: string | "") => {
if (newValue === filter.value) return;
if (newValue && !dayjs(newValue).isValid()) return;

lastFilterValue.current = newValue;
onChange({
...filter,
value: newValue,
});
},
[filter, onChange],
);

const debouncedFilterRef = useRef(debounce(debouncedUpdateFilter, 500));

// Use the debounced function through the ref
const handleFilterUpdate = useCallback((newValue: string | "") => {
debouncedFilterRef.current(newValue);
}, []);

const getTimeFromDate = (date: Date | undefined) => {
if (!date) return "00:00";
return `${String(date.getHours()).padStart(2, "0")}:${String(
date.getMinutes(),
).padStart(2, "0")}`;
};

const onSelectDate = (value: Date | undefined) => {
if (!value) {
setPendingDate(undefined);
return;
}

try {
// If there's a pending date, preserve its time
if (pendingDate) {
value.setHours(pendingDate.getHours());
value.setMinutes(pendingDate.getMinutes());
} else if (date) {
// If no pending date but we have a current date, use its time
value.setHours(date.getHours());
value.setMinutes(date.getMinutes());
} else {
// Default to start of day
value.setHours(0);
value.setMinutes(0);
value.setSeconds(0);
value.setMilliseconds(0);
}

setPendingDate(value);
} catch (error) {
console.error("Invalid date:", error);
}
};

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setInputValue(newValue);

if (!newValue) {
handleFilterUpdate("");
return;
}

const parsedDate = dayjs(
newValue,
["MM/DD/YY HH:mm A", "MM/DD/YYYY HH:mm A"],
true,
);

if (parsedDate.isValid()) {
try {
const isoString = parsedDate.toISOString();
handleFilterUpdate(isoString);
} catch (error) {
console.error("Invalid date:", error);
}
}
};

const handleTimeChange = (timeString: string) => {
setPendingTime(timeString);
if (!pendingDate) return;

try {
const [hours, minutes] = timeString.split(":").map(Number);
const newDate = new Date(pendingDate);
newDate.setHours(hours);
newDate.setMinutes(minutes);
setPendingDate(newDate);
} catch (error) {
console.error("Invalid time:", error);
}
};

// Handle popover close
const handleOpenChange = (isOpen: boolean) => {
setOpen(isOpen);

if (!isOpen && pendingDate) {
// When closing, apply the pending changes
const newValue = pendingDate.toISOString();
setInputValue(formatDate(newValue));
handleFilterUpdate(newValue);

// Reset pending states
setPendingDate(undefined);
setPendingTime("00:00");
}
};

// Initialize pending values when opening the popover
React.useEffect(() => {
if (open && date) {
setPendingDate(new Date(date));
setPendingTime(getTimeFromDate(date));
}
}, [open, date]);

// Update cleanup to use the ref
React.useEffect(() => {
const currentDebounced = debouncedFilterRef.current;
return () => {
currentDebounced.cancel();
};
}, []);

return (
<>
<td className="p-1">
Expand All @@ -52,32 +189,37 @@ export const TimeRow: React.FunctionComponent<TimeRowProps> = ({
/>
</td>
<td className="p-1">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"w-full min-w-40 justify-start text-left font-normal",
!filter.value && "text-muted-foreground",
)}
>
<CalendarIcon className="mr-2 size-4" />
{filter.value ? (
formatDate(filter.value as string)
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={date}
onSelect={onSelectDate}
initialFocus
<div className="relative flex items-center">
<div className="relative w-full">
<Input
value={inputValue}
onChange={handleInputChange}
placeholder="MM/DD/YY HH:mm A"
className="w-full pr-10"
/>
</PopoverContent>
</Popover>
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
>
<CalendarIcon className="size-4 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="end">
<Calendar
mode="single"
selected={pendingDate || date}
onSelect={onSelectDate}
initialFocus
selectedTime={pendingTime}
onTimeChange={handleTimeChange}
/>
</PopoverContent>
</Popover>
</div>
</div>
</td>
</>
);
Expand Down
Loading
Loading