Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: improved time range filtering (#9252)

Leo Weigand9e3379f05fcd
diff --git a/.codespellrc b/.codespellrc
index 9ddfafafea..67e85ef00b 100644
--- a/.codespellrc
+++ b/.codespellrc
@@ -1,4 +1,4 @@
[codespell]
skip = .git,*.pdf,*.svg,package-lock.json,*.prisma,pnpm-lock.yaml
-ignore-words-list = afterall,vertx,notIn,alue
+ignore-words-list = afterall,vertx,notIn,alue,allTime
diff --git a/web/src/components/date-picker.tsx b/web/src/components/date-picker.tsx
index 131f6a5352..0680fefec6 100644
--- a/web/src/components/date-picker.tsx
+++ b/web/src/components/date-picker.tsx
@@ -1,7 +1,8 @@
"use client";
import * as React from "react";
-import { Calendar as CalendarIcon, X } from "lucide-react";
+import { Calendar as CalendarIcon, X, ChevronDown } from "lucide-react";
+import { addMinutes } from "date-fns";
import { Button } from "@/src/components/ui/button";
import { Calendar } from "@/src/components/ui/calendar";
import {
@@ -10,10 +11,9 @@ import {
PopoverTrigger,
} from "@/src/components/ui/popover";
import { cn } from "@/src/utils/tailwind";
-import { type DateRange } from "react-day-picker";
+import { type DateRange as RDPDateRange } from "react-day-picker";
import { format } from "date-fns";
-import { useEffect, useState } from "react";
-import { useMediaQuery } from "react-responsive";
+import { useEffect, useState, useCallback } from "react";
import { setBeginningOfDay, setEndOfDay } from "@/src/utils/dates";
import { TimePicker } from "@/src/components/ui/time-picker";
import { DashboardDateRangeDropdown } from "@/src/components/date-range-dropdowns";
@@ -21,6 +21,9 @@ import {
DASHBOARD_AGGREGATION_PLACEHOLDER,
type DashboardDateRangeOptions,
type DashboardDateRange,
+ TIME_RANGES,
+ formatDateRange,
+ type TimeRange,
} from "@/src/utils/date-range-utils";
import { combineDateAndTime } from "@/src/components/ui/time-picker-utils";
@@ -65,7 +68,7 @@ export function DatePicker({
mode="single"
selected={date}
onSelect={(d) => onChange(d)}
- initialFocus
+ autoFocus
/>
{includeTimePicker && (
<TimePicker date={date} setDate={(d) => onChange(d)} />
@@ -105,7 +108,7 @@ export function DatePickerWithRange({
disabled,
}: DatePickerWithRangeProps) {
const [internalDateRange, setInternalDateRange] = useState<
- DateRange | undefined
+ RDPDateRange | undefined
>(dateRange);
useEffect(() => {
@@ -113,10 +116,10 @@ export function DatePickerWithRange({
}, [dateRange]);
const setNewDateRange = (
- internalDateRange: DateRange | undefined,
+ internalDateRange: RDPDateRange | undefined,
newFromDate: Date | undefined,
newToDate: Date | undefined,
- ): DateRange | undefined => {
+ ): RDPDateRange | undefined => {
return internalDateRange
? {
from: newFromDate ?? internalDateRange.from,
@@ -126,7 +129,7 @@ export function DatePickerWithRange({
};
const updateDashboardDateRange = (
- newRange: DateRange | undefined,
+ newRange: RDPDateRange | undefined,
setDateRangeAndOption: (
option: DashboardDateRangeOptions,
date?: DashboardDateRange,
@@ -144,7 +147,7 @@ export function DatePickerWithRange({
}
};
- const onCalendarSelection = (range?: DateRange) => {
+ const onCalendarSelection = (range?: RDPDateRange) => {
const newRange = range
? {
from: range.from ? setBeginningOfDay(range.from) : undefined,
@@ -178,8 +181,6 @@ export function DatePickerWithRange({
updateDashboardDateRange(newRange, setDateRangeAndOption);
};
- const isSmallScreen = useMediaQuery({ query: "(max-width: 640px)" });
-
return (
<div
className={cn("my-3 flex flex-col-reverse gap-2 md:flex-row", className)}
@@ -216,49 +217,32 @@ export function DatePickerWithRange({
defaultMonth={internalDateRange?.from}
selected={internalDateRange}
onSelect={onCalendarSelection}
- numberOfMonths={isSmallScreen ? 1 : 2}
+ numberOfMonths={2}
+ className="[&>div:first-child]:block [&>div]:hidden [&>div]:sm:block"
disabled={disabled}
/>
- {!isSmallScreen && (
- <div className="flex flex-row border-t-2 py-1.5">
- <div className="px-3">
- <p className="px-1 text-sm font-medium">Start time</p>
- <TimePicker
- date={internalDateRange?.from}
- setDate={onStartTimeSelection}
- className="border-0 px-0 pt-1"
- />
- </div>
- <div className="px-3">
- <p className="px-1 text-sm font-medium">End time</p>
- <TimePicker
- date={internalDateRange?.to}
- setDate={onEndTimeSelection}
- className="border-0 px-0 pt-1"
- />
- </div>
+ <div className="flex flex-col gap-2 border-t-2 py-1.5 sm:flex-row sm:gap-0">
+ <div className="px-3">
+ <p className="px-1 text-sm font-medium">
+ Start<span className="hidden sm:inline"> time</span>
+ </p>
+ <TimePicker
+ date={internalDateRange?.from}
+ setDate={onStartTimeSelection}
+ className="border-0 px-0 pt-1"
+ />
</div>
- )}
- {isSmallScreen && (
- <div className="flex flex-col gap-2 border-t-2 py-1.5">
- <div className="px-3">
- <p className="px-1 text-sm font-medium">Start</p>
- <TimePicker
- date={internalDateRange?.from}
- setDate={onStartTimeSelection}
- className="border-0 px-0 pt-1"
- />
- </div>
- <div className="px-3">
- <p className="px-1 text-sm font-medium">End</p>
- <TimePicker
- date={internalDateRange?.to}
- setDate={onEndTimeSelection}
- className="border-0 px-0 pt-1"
- />
- </div>
+ <div className="px-3">
+ <p className="px-1 text-sm font-medium">
+ End<span className="hidden sm:inline"> time</span>
+ </p>
+ <TimePicker
+ date={internalDateRange?.to}
+ setDate={onEndTimeSelection}
+ className="border-0 px-0 pt-1"
+ />
</div>
- )}
+ </div>
</PopoverContent>
</Popover>
<DashboardDateRangeDropdown
@@ -268,3 +252,270 @@ export function DatePickerWithRange({
</div>
);
}
+
+export type TimeRangePickerProps = {
+ timeRange?: TimeRange;
+ onTimeRangeChange: (timeRange: TimeRange) => void;
+ timeRangePresets: readonly string[];
+ className?: string;
+ disabled?: boolean | { before?: Date; after?: Date } | Date | Date[];
+};
+
+export function TimeRangePicker({
+ className,
+ timeRange,
+ timeRangePresets,
+ onTimeRangeChange,
+ disabled,
+}: TimeRangePickerProps) {
+ // Determine the range type
+ const rangeType: "named" | "custom" | null = timeRange
+ ? "from" in timeRange
+ ? "custom"
+ : "named"
+ : null;
+
+ // Disable future dates by default, plus any additional disabled prop
+ const calendarDisabled = React.useMemo(() => {
+ const futureDisabled = { after: new Date() };
+
+ if (!disabled) return futureDisabled;
+ if (typeof disabled === "boolean") return disabled;
+
+ // Always return an array when combining with additional restrictions
+ const disabledArray = Array.isArray(disabled) ? disabled : [disabled];
+ return [...disabledArray, futureDisabled] as React.ComponentProps<
+ typeof Calendar
+ >["disabled"];
+ }, [disabled]);
+ const namedRangeValue =
+ rangeType === "named" && timeRange && "range" in timeRange
+ ? timeRange.range
+ : null;
+
+ // Convert TimeRange to DateRange for internal use
+ const dateRange = timeRange && "from" in timeRange ? timeRange : undefined;
+
+ const [internalDateRange, setInternalDateRange] = useState<
+ RDPDateRange | undefined
+ >(dateRange);
+
+ // Update internal date range when timeRange changes
+ useEffect(() => {
+ if (rangeType === "custom") {
+ // Custom range - use as is
+ setInternalDateRange(dateRange);
+ } else if (rangeType === "named" && timeRange && "range" in timeRange) {
+ // Preset range - look up in generic time ranges
+ const setting = TIME_RANGES[timeRange.range as keyof typeof TIME_RANGES];
+ if (setting && setting.minutes) {
+ const now = new Date();
+ setInternalDateRange({
+ from: addMinutes(now, -setting.minutes),
+ to: now,
+ });
+ } else {
+ setInternalDateRange(undefined);
+ }
+ } else {
+ setInternalDateRange(undefined);
+ }
+ }, [timeRange, dateRange, rangeType]);
+
+ const setNewDateRange = (
+ internalDateRange: RDPDateRange | undefined,
+ newFromDate: Date | undefined,
+ newToDate: Date | undefined,
+ ): RDPDateRange | undefined => {
+ return internalDateRange
+ ? {
+ from: newFromDate ?? internalDateRange.from,
+ to: newToDate ?? internalDateRange.to,
+ }
+ : undefined;
+ };
+
+ const updateDateRange = (newRange: RDPDateRange | undefined) => {
+ if (newRange && newRange.from && newRange.to) {
+ onTimeRangeChange({
+ from: newRange.from,
+ to: newRange.to,
+ });
+ }
+ };
+
+ const onCalendarSelection = (range?: RDPDateRange) => {
+ const newRange = range
+ ? {
+ from: range.from
+ ? setBeginningOfDay(new Date(range.from))
+ : undefined,
+ to: range.to ? setEndOfDay(new Date(range.to)) : undefined,
+ }
+ : undefined;
+
+ setInternalDateRange(newRange);
+ updateDateRange(newRange);
+ };
+
+ const onStartTimeSelection = (date: Date | undefined) => {
+ const newDateTime = combineDateAndTime(internalDateRange?.from, date);
+ const newRange = setNewDateRange(
+ internalDateRange,
+ newDateTime,
+ internalDateRange?.to,
+ );
+ setInternalDateRange(newRange);
+ updateDateRange(newRange);
+ };
+
+ const onEndTimeSelection = (date: Date | undefined) => {
+ const newDateTime = combineDateAndTime(internalDateRange?.to, date);
+ const newRange = setNewDateRange(
+ internalDateRange,
+ internalDateRange?.from,
+ newDateTime,
+ );
+ setInternalDateRange(newRange);
+ updateDateRange(newRange);
+ };
+
+ const onPresetSelection = (value: string) => {
+ if (timeRangePresets.includes(value as keyof typeof TIME_RANGES)) {
+ onTimeRangeChange({ range: value });
+ }
+ };
+
+ const [isOpen, setIsOpen] = useState(false);
+ const [tab, setTab] = useState<"presets" | "calendar">("presets");
+
+ const handleOpenChange = useCallback((open: boolean) => {
+ setIsOpen(open);
+ if (open) {
+ setTab("presets");
+ }
+ }, []);
+
+ const getDisplayContent = () => {
+ if (rangeType === "custom") {
+ // Custom range - show calendar icon and date range
+ return (
+ <div className="flex items-center gap-2">
+ <CalendarIcon className="h-4 w-4" />
+ <span>
+ {dateRange
+ ? formatDateRange(dateRange.from, dateRange.to)
+ : "Select from calendar"}
+ </span>
+ </div>
+ );
+ } else if (rangeType === "named") {
+ // Preset range - show badge with abbreviation and label
+ const setting = TIME_RANGES[namedRangeValue as keyof typeof TIME_RANGES];
+ return (
+ <div className="flex items-center gap-2">
+ <span className="h-5 w-10 rounded bg-muted px-1.5 text-center text-xs leading-5">
+ {setting?.abbreviation || namedRangeValue}
+ </span>
+ <span>{setting?.label || namedRangeValue}</span>
+ </div>
+ );
+ } else {
+ // No time range selected
+ return (
+ <div className="flex items-center gap-2">
+ <CalendarIcon className="h-4 w-4" />
+ <span>Select time range</span>
+ </div>
+ );
+ }
+ };
+
+ return (
+ <div className={cn("my-3", className)}>
+ <Popover open={isOpen} onOpenChange={handleOpenChange}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ className={cn(
+ "w-fit justify-start text-left font-normal hover:bg-accent hover:text-accent-foreground",
+ !timeRange && "text-muted-foreground",
+ )}
+ >
+ <div className="flex items-center gap-2">
+ {getDisplayContent()}
+ <ChevronDown className="h-4 w-4 opacity-50" />
+ </div>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0" align="start">
+ {tab === "calendar" ? (
+ /* Show calendar picker when in calendar mode */
+ <>
+ <Calendar
+ mode="range"
+ defaultMonth={internalDateRange?.from || new Date()}
+ selected={internalDateRange}
+ onSelect={onCalendarSelection}
+ numberOfMonths={1}
+ disabled={calendarDisabled}
+ />
+ <div className="flex flex-col gap-3 border-t p-3">
+ <div className="flex flex-col gap-1">
+ <p className="px-1 text-sm font-medium">Start time</p>
+ <TimePicker
+ date={internalDateRange?.from}
+ setDate={onStartTimeSelection}
+ className="border-0 px-0 py-0"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <p className="px-1 text-sm font-medium">End time</p>
+ <TimePicker
+ date={internalDateRange?.to}
+ setDate={onEndTimeSelection}
+ className="border-0 px-0 py-0"
+ />
+ </div>
+ </div>
+ </>
+ ) : (
+ /* Always show preset options dropdown */
+ <div className="p-1">
+ {timeRangePresets.map((presetKey) => {
+ const setting =
+ TIME_RANGES[presetKey as keyof typeof TIME_RANGES];
+ return (
+ <div
+ key={presetKey}
+ className="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground"
+ onClick={() => {
+ onPresetSelection(presetKey);
+ setIsOpen(false);
+ }}
+ >
+ <span className="h-5 w-10 rounded bg-muted px-1.5 text-center text-xs leading-5">
+ {setting.abbreviation}
+ </span>
+ <span>{setting.label}</span>
+ </div>
+ );
+ })}
+ <div
+ className="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground"
+ onClick={() => {
+ setTab("calendar");
+ }}
+ >
+ <span className="leading flex h-5 w-10 items-center justify-center rounded bg-muted px-1.5 text-center text-xs">
+ <CalendarIcon className="h-3 w-3" />
+ </span>
+ <span>Select from calendar</span>
+ </div>
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ </div>
+ );
+}
diff --git a/web/src/components/date-range-dropdowns.tsx b/web/src/components/date-range-dropdowns.tsx
index fea01be755..76abad393b 100644
--- a/web/src/components/date-range-dropdowns.tsx
+++ b/web/src/components/date-range-dropdowns.tsx
@@ -19,6 +19,8 @@ import {
getDateFromOption,
isTableDataRangeOptionAvailable,
isDashboardDateRangeOptionAvailable,
+ getAbbreviatedTimeRange,
+ getTimeRangeLabel,
} from "@/src/utils/date-range-utils";
import { useEntitlementLimit } from "@/src/features/entitlements/hooks";
import { useMemo } from "react";
@@ -45,24 +47,40 @@ const BaseDateRangeDropdown = <T extends string>({
return (
<Select value={selectedOption} onValueChange={onSelectionChange}>
<SelectTrigger className="w-fit font-medium hover:bg-accent hover:text-accent-foreground focus:ring-0 focus:ring-offset-0">
- {selectedOption !== "All time" && <span>Past</span>}
- <SelectValue placeholder="Select" />
+ <SelectValue placeholder="Select">
+ <div className="flex items-center gap-2">
+ <span className="w-10 rounded bg-muted px-1.5 py-0.5 text-center text-xs">
+ {getAbbreviatedTimeRange(selectedOption)}
+ </span>
+ <span>{getTimeRangeLabel(selectedOption)}</span>
+ </div>
+ </SelectValue>
</SelectTrigger>
- <SelectContent position="popper" defaultValue={60}>
+ <SelectContent
+ position="popper"
+ defaultValue={60}
+ className="[&_[data-checkmark]]:hidden"
+ >
{options.map((item) => {
const itemObj = (
<SelectItem
key={item}
value={item}
disabled={limitedOptions?.includes(item)}
+ className="pl-2"
>
- {item}
+ <div className="flex items-center gap-2">
+ <span className="w-10 rounded bg-muted px-1.5 py-0.5 text-center text-xs">
+ {getAbbreviatedTimeRange(item)}
+ </span>
+ <span>{getTimeRangeLabel(item)}</span>
+ </div>
</SelectItem>
);
const isLimited = limitedOptions?.includes(item);
return isLimited ? (
- <HoverCard openDelay={200}>
+ <HoverCard openDelay={200} key={item}>
<HoverCardTrigger asChild>
<span>{itemObj}</span>
</HoverCardTrigger>
@@ -113,7 +131,7 @@ export const DashboardDateRangeDropdown: React.FC<
value as keyof typeof dashboardDateRangeAggregationSettings
];
setDateRangeAndOption(value, {
- from: addMinutes(new Date(), -setting.minutes),
+ from: addMinutes(new Date(), -setting!.minutes!),
to: new Date(),
});
};
@@ -153,6 +171,12 @@ export const TableDateRangeDropdown: React.FC<TableDateRangeDropdownProps> = ({
}, [lookbackLimit]);
const onDropDownSelection = (value: TableDateRangeOptions) => {
+ // Handle "custom" placeholder case
+ if (value === "custom") {
+ setDateRangeAndOption(value, undefined);
+ return;
+ }
+
const dateFromOption = getDateFromOption({
filterSource: "TABLE",
option: value,
diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsx
index 61c41b57cc..435772a430 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -23,10 +23,10 @@ import {
} from "@/src/components/table/data-table-row-height-switch";
import { Search, ChevronDown } from "lucide-react";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { TableDateRangeDropdown } from "@/src/components/date-range-dropdowns";
+import { TimeRangePicker } from "@/src/components/date-picker";
import {
- type TableDateRange,
- type TableDateRangeOptions,
+ type TimeRange,
+ TABLE_AGGREGATION_OPTIONS,
} from "@/src/utils/date-range-utils";
import { DataTableSelectAllBanner } from "@/src/components/table/data-table-multi-select-actions/data-table-select-all-banner";
import { MultiSelect } from "@/src/features/filters/components/multi-select";
@@ -93,11 +93,8 @@ interface DataTableToolbarProps<TData, TValue> {
rowHeight?: RowHeight;
setRowHeight?: Dispatch<SetStateAction<RowHeight>>;
columnsWithCustomSelect?: string[];
- selectedOption?: TableDateRangeOptions;
- setDateRangeAndOption?: (
- option: TableDateRangeOptions,
- date?: TableDateRange,
- ) => void;
+ timeRange?: TimeRange;
+ setTimeRange?: (timeRange: TimeRange) => void;
multiSelect?: MultiSelect;
environmentFilter?: {
values: string[];
@@ -123,8 +120,8 @@ export function DataTableToolbar<TData, TValue>({
rowHeight,
setRowHeight,
columnsWithCustomSelect,
- selectedOption,
- setDateRangeAndOption,
+ timeRange,
+ setTimeRange,
multiSelect,
environmentFilter,
className,
@@ -257,10 +254,12 @@ export function DataTableToolbar<TData, TValue>({
)}
</div>
)}
- {selectedOption && setDateRangeAndOption && (
- <TableDateRangeDropdown
- selectedOption={selectedOption}
- setDateRangeAndOption={setDateRangeAndOption}
+ {timeRange && setTimeRange && (
+ <TimeRangePicker
+ timeRange={timeRange}
+ onTimeRangeChange={setTimeRange}
+ timeRangePresets={TABLE_AGGREGATION_OPTIONS}
+ className="my-0 max-w-full overflow-x-auto"
/>
)}
{environmentFilter && (
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index dba81ded91..49c74ca31b 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -26,6 +26,7 @@ import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { MemoizedIOTableCell } from "../../ui/IOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
+import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
import { useDebounce } from "@/src/hooks/useDebounce";
import { type ScoreAggregate } from "@langfuse/shared";
import TagList from "@/src/features/tag/components/TagList";
@@ -166,8 +167,12 @@ export default function ObservationsTable({
order: "DESC",
});
- const { selectedOption, dateRange, setDateRangeAndOption } =
- useTableDateRange(projectId);
+ const { timeRange, setTimeRange } = useTableDateRange(projectId);
+
+ // Convert timeRange to absolute date range for compatibility
+ const dateRange = useMemo(() => {
+ return toAbsoluteTimeRange(timeRange) ?? undefined;
+ }, [timeRange]);
const promptNameFilter: FilterState = promptName
? [
@@ -336,7 +341,10 @@ export default function ObservationsTable({
filterOptions: ObservationOptions | undefined,
) => {
return observationsTableColsWithOptions(filterOptions).filter(
- (col) => !omittedFilter?.includes(col.name),
+ (col) =>
+ col.id !== "startTime" &&
+ col.id !== "endTime" &&
+ !omittedFilter?.includes(col.name),
);
};
@@ -1065,8 +1073,8 @@ export default function ObservationsTable({
orderByState={orderByState}
rowHeight={rowHeight}
setRowHeight={setRowHeight}
- selectedOption={selectedOption}
- setDateRangeAndOption={setDateRangeAndOption}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
actionButtons={[
<BatchExportTableButton
{...{
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 65b546ce69..90ac965b69 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -11,6 +11,7 @@ import { isNumericDataType } from "@/src/features/scores/lib/helpers";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { useDebounce } from "@/src/hooks/useDebounce";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
+import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
import {
type ScoreOptions,
scoresTableColsWithOptions,
@@ -114,8 +115,12 @@ export default function ScoresTable({
const { selectAll, setSelectAll } = useSelectAll(projectId, "scores");
const [rowHeight, setRowHeight] = useRowHeightLocalStorage("scores", "s");
- const { selectedOption, dateRange, setDateRangeAndOption } =
- useTableDateRange(projectId);
+ const { timeRange, setTimeRange } = useTableDateRange(projectId);
+
+ // Convert timeRange to absolute date range for compatibility
+ const dateRange = React.useMemo(() => {
+ return toAbsoluteTimeRange(timeRange) ?? undefined;
+ }, [timeRange]);
const [userFilterState, setUserFilterState] = useQueryFilterState(
[],
@@ -608,7 +613,10 @@ export default function ScoresTable({
traceFilterOptions: ScoreOptions | undefined,
) => {
return scoresTableColsWithOptions(traceFilterOptions).filter(
- (c) => !omittedFilter?.includes(c.name) && !hiddenColumns.includes(c.id),
+ (c) =>
+ c.id !== "timestamp" &&
+ !omittedFilter?.includes(c.name) &&
+ !hiddenColumns.includes(c.id),
);
};
@@ -662,8 +670,8 @@ export default function ScoresTable({
]}
rowHeight={rowHeight}
setRowHeight={setRowHeight}
- selectedOption={selectedOption}
- setDateRangeAndOption={setDateRangeAndOption}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
multiSelect={{
selectAll,
setSelectAll,
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 80ea820075..2ef7cb2340 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -21,9 +21,10 @@ import { formatIntervalSeconds } from "@/src/utils/dates";
import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
import { type RouterOutput } from "@/src/utils/types";
import type Decimal from "decimal.js";
-import { useEffect, useState } from "react";
+import { useEffect, useState, useMemo } from "react";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
+import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
import { useDebounce } from "@/src/hooks/useDebounce";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { Skeleton } from "@/src/components/ui/skeleton";
@@ -78,8 +79,12 @@ export default function SessionsTable({
omittedFilter = [],
}: SessionTableProps) {
const { setDetailPageList } = useDetailPageLists();
- const { selectedOption, dateRange, setDateRangeAndOption } =
- useTableDateRange(projectId);
+ const { timeRange, setTimeRange } = useTableDateRange(projectId);
+
+ // Convert timeRange to absolute date range for compatibility
+ const dateRange = useMemo(() => {
+ return toAbsoluteTimeRange(timeRange) ?? undefined;
+ }, [timeRange]);
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const [userFilterState, setUserFilterState] = useQueryFilterState(
@@ -609,7 +614,7 @@ export default function SessionsTable({
const transformFilterOptions = () => {
return sessionsTableColsWithOptions(filterOptions.data).filter(
- (c) => !omittedFilter?.includes(c.name),
+ (c) => c.id !== "createdAt" && !omittedFilter?.includes(c.name),
);
};
@@ -664,8 +669,8 @@ export default function SessionsTable({
projectId,
controllers: viewControllers,
}}
- selectedOption={selectedOption}
- setDateRangeAndOption={setDateRangeAndOption}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
columnsWithCustomSelect={["userIds"]}
rowHeight={rowHeight}
setRowHeight={setRowHeight}
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 621a84149f..be1e2707bf 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -40,6 +40,7 @@ import {
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { MemoizedIOTableCell } from "../../ui/IOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
+import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
import { useDebounce } from "@/src/hooks/useDebounce";
import { type ScoreAggregate } from "@langfuse/shared";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
@@ -147,11 +148,13 @@ export default function TracesTable({
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const { setDetailPageList } = useDetailPageLists();
- const {
- selectedOption,
- dateRange: tableDateRange,
- setDateRangeAndOption,
- } = useTableDateRange(projectId);
+ const { timeRange, setTimeRange } = useTableDateRange(projectId);
+
+ // Convert timeRange to absolute date range for compatibility
+ const tableDateRange = useMemo(() => {
+ return toAbsoluteTimeRange(timeRange) ?? undefined;
+ }, [timeRange]);
+
const dateRange = externalDateRange ?? tableDateRange;
const [userFilterState, setUserFilterState] = useQueryFilterState(
@@ -173,6 +176,16 @@ export default function TracesTable({
operator: ">=",
value: dateRange.from,
},
+ ...(dateRange.to
+ ? [
+ {
+ column: "Timestamp",
+ type: "datetime",
+ operator: "<=",
+ value: dateRange.to,
+ } as const,
+ ]
+ : []),
]
: [];
const userIdFilter: FilterState = userId
@@ -316,6 +329,7 @@ export default function TracesTable({
return tracesTableColsWithOptions(traceFilterOptions).filter(
(c) =>
c.id !== "environment" &&
+ c.id !== "timestamp" &&
!omittedFilter?.includes(c.name) &&
!omittedFilter?.includes(c.id),
);
@@ -1169,8 +1183,8 @@ export default function TracesTable({
setColumnOrder={setColumnOrder}
rowHeight={rowHeight}
setRowHeight={setRowHeight}
- selectedOption={selectedOption}
- setDateRangeAndOption={setDateRangeAndOption}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
multiSelect={{
selectAll,
setSelectAll,
diff --git a/web/src/components/ui/calendar.tsx b/web/src/components/ui/calendar.tsx
index 0d3d11bcdd..1a928d451d 100644
--- a/web/src/components/ui/calendar.tsx
+++ b/web/src/components/ui/calendar.tsx
@@ -1,8 +1,13 @@
"use client";
import * as React from "react";
-import { ChevronLeft, ChevronRight } from "lucide-react";
-import { DayPicker } from "react-day-picker";
+import {
+ ChevronLeft,
+ ChevronRight,
+ ChevronUp,
+ ChevronDown,
+} from "lucide-react";
+import { DayPicker, UI, SelectionState, DayFlag } from "react-day-picker";
import { cn } from "@/src/utils/tailwind";
import { buttonVariants } from "@/src/components/ui/button";
@@ -22,46 +27,48 @@ function Calendar({
className={cn("p-3", className)}
disabled={disabled}
classNames={{
- months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
- month: "space-y-4",
- caption: "flex justify-center pt-1 relative items-center",
- caption_label: "text-sm font-medium",
- nav: "space-x-1 flex items-center",
- nav_button: cn(
+ [UI.Months]: "flex relative",
+ [UI.Month]: "space-y-4",
+ [UI.MonthCaption]: "flex justify-center items-center h-7",
+ [UI.CaptionLabel]: "text-sm font-medium",
+ [UI.PreviousMonthButton]: cn(
buttonVariants({ variant: "outline" }),
- "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",
+ "absolute left-1 top-0 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",
),
- nav_button_previous: "absolute left-1",
- nav_button_next: "absolute right-1",
- table: "w-full border-collapse space-y-1",
- head_row: "flex",
- head_cell:
+ [UI.NextMonthButton]: cn(
+ buttonVariants({ variant: "outline" }),
+ "absolute right-1 top-0 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",
+ ),
+ [UI.MonthGrid]: "w-full border-collapse space-y-1",
+ [UI.Weekdays]: "flex",
+ [UI.Weekday]:
"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
- row: "flex w-full mt-2",
- day: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
- day_button: cn(
+ [UI.Week]: "flex w-full mt-2",
+ [UI.Day]:
+ "h-9 w-9 text-center text-sm p-0 relative focus-within:relative focus-within:z-20",
+ [UI.DayButton]: cn(
buttonVariants({ variant: "ghost" }),
"h-9 w-9 p-0 font-normal aria-selected:opacity-100",
+ // can't use SelectionState.range_start here because Tailwind classes can't be constructed dynamically
+ "group-[.selection-edge]:bg-primary group-[.selection-edge]:text-primary-foreground group-[.today]:font-semibold",
),
- day_range_end: "day-range-end",
- day_selected:
- "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
- day_today: "bg-accent text-accent-foreground",
- day_outside:
- "day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
- disabled: "text-muted-foreground opacity-50",
- day_range_middle:
- "aria-selected:bg-accent aria-selected:text-accent-foreground",
- day_hidden: "invisible",
+ [SelectionState.range_start]:
+ "group selection-edge bg-accent text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground rounded-l-md rounded-r-none",
+ [SelectionState.range_middle]:
+ "bg-accent text-accent-foreground hover:bg-accent hover:text-accent-foreground rounded-none",
+ [SelectionState.range_end]:
+ "group selection-edge bg-accent text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground rounded-r-md rounded-l-none",
+ [SelectionState.selected]:
+ "bg-accent text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground rounded-md",
+ [DayFlag.today]: "group today",
+ [DayFlag.outside]:
+ "text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
+ [DayFlag.disabled]: "text-muted-foreground opacity-50",
+ [DayFlag.hidden]: "invisible",
...classNames,
}}
components={{
- Chevron: (props) => {
- if (props.orientation === "left") {
- return <ChevronLeft className="h-4 w-4" />;
- }
- return <ChevronRight className="h-4 w-4" />;
- },
+ Chevron: ({ ...props }) => <Chevron {...props} />,
}}
{...props}
/>
@@ -69,4 +76,19 @@ function Calendar({
}
Calendar.displayName = "Calendar";
+const Chevron = ({ orientation = "left" }) => {
+ switch (orientation) {
+ case "left":
+ return <ChevronLeft className="h-4 w-4" />;
+ case "right":
+ return <ChevronRight className="h-4 w-4" />;
+ case "up":
+ return <ChevronUp className="h-4 w-4" />;
+ case "down":
+ return <ChevronDown className="h-4 w-4" />;
+ default:
+ return null;
+ }
+};
+
export { Calendar };
diff --git a/web/src/components/ui/select.tsx b/web/src/components/ui/select.tsx
index 4d0a9b3fba..b12c887740 100644
--- a/web/src/components/ui/select.tsx
+++ b/web/src/components/ui/select.tsx
@@ -127,7 +127,10 @@ const SelectItem = React.forwardRef<
)}
{...props}
>
- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <span
+ data-checkmark
+ className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"
+ >
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
diff --git a/web/src/components/ui/time-picker.tsx b/web/src/components/ui/time-picker.tsx
index 7f690bdd6a..7e45904a95 100644
--- a/web/src/components/ui/time-picker.tsx
+++ b/web/src/components/ui/time-picker.tsx
@@ -7,6 +7,11 @@ import { type Period } from "./time-picker-utils";
import { getTimezoneDetails, getShortLocalTimezone } from "@/src/utils/dates";
import { TimeIcon } from "@/src/components/ui/time-icon";
import { cn } from "@/src/utils/tailwind";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
interface TimePickerProps {
date: Date | undefined;
@@ -82,11 +87,15 @@ export function TimePicker({ date, setDate, className }: TimePickerProps) {
onLeftFocus={() => secondRef.current?.focus()}
/>
</div>
- <div className="group relative ml-1">
- <span>{shortTimezone}</span>
- <div className="text-s absolute left-1/2 top-full mt-2 hidden -translate-x-1/2 transform whitespace-nowrap rounded bg-card px-2 py-1 text-card-foreground shadow-md ring-1 ring-border group-hover:block">
- {timezoneDetails}
- </div>
+ <div className="ml-1 flex items-center">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-s whitespace-nowrap">{shortTimezone}</span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" align="center">
+ {timezoneDetails}
+ </TooltipContent>
+ </Tooltip>
</div>
</div>
);
diff --git a/web/src/features/dashboard/components/BaseTimeSeriesChart.tsx b/web/src/features/dashboard/components/BaseTimeSeriesChart.tsx
index a9f0f555cf..d92270efa7 100644
--- a/web/src/features/dashboard/components/BaseTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/BaseTimeSeriesChart.tsx
@@ -50,7 +50,7 @@ export function BaseTimeSeriesChart(props: {
agg: DashboardDateRangeAggregationOption,
) => {
const showMinutes = ["minute", "hour"].includes(
- dashboardDateRangeAggregationSettings[agg].date_trunc,
+ dashboardDateRangeAggregationSettings[agg].dateTrunc ?? "",
);
if (showMinutes) {
diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsx
index 076da8bb73..6e071402ce 100644
--- a/web/src/features/dashboard/components/ChartScores.tsx
+++ b/web/src/features/dashboard/components/ChartScores.tsx
@@ -38,7 +38,8 @@ export function ChartScores(props: {
props.globalFilterState,
),
timeDimension: {
- granularity: dashboardDateRangeAggregationSettings[props.agg].date_trunc,
+ granularity:
+ dashboardDateRangeAggregationSettings[props.agg].dateTrunc ?? "day",
},
fromTimestamp: props.fromTimestamp.toISOString(),
toTimestamp: props.toTimestamp.toISOString(),
diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsx
index d8c0f36768..33ce3d7c72 100644
--- a/web/src/features/dashboard/components/LatencyChart.tsx
+++ b/web/src/features/dashboard/components/LatencyChart.tsx
@@ -81,7 +81,8 @@ export const GenerationLatencyChart = ({
},
],
timeDimension: {
- granularity: dashboardDateRangeAggregationSettings[agg].date_trunc,
+ granularity:
+ dashboardDateRangeAggregationSettings[agg].dateTrunc ?? "day",
},
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsx
index 28a50bcbae..fba1cbc776 100644
--- a/web/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx
@@ -82,7 +82,8 @@ export const ModelUsageChart = ({
},
],
timeDimension: {
- granularity: dashboardDateRangeAggregationSettings[agg].date_trunc,
+ granularity:
+ dashboardDateRangeAggregationSettings[agg].dateTrunc ?? "day",
},
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
@@ -132,7 +133,8 @@ export const ModelUsageChart = ({
{
type: "datetime",
column: "startTime",
- temporalUnit: dashboardDateRangeAggregationSettings[agg].date_trunc,
+ temporalUnit:
+ dashboardDateRangeAggregationSettings[agg].dateTrunc ?? "day",
},
{
type: "string",
@@ -182,7 +184,8 @@ export const ModelUsageChart = ({
{
type: "datetime",
column: "startTime",
- temporalUnit: dashboardDateRangeAggregationSettings[agg].date_trunc,
+ temporalUnit:
+ dashboardDateRangeAggregationSettings[agg].dateTrunc ?? "day",
},
{
type: "string",
diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
index 9a4b9b2ced..00738f27c9 100644
--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
@@ -39,7 +39,8 @@ export const TracesAndObservationsTimeSeriesChart = ({
metrics: [{ measure: "count", aggregation: "count" }],
filters: mapLegacyUiTableFilterToView("traces", globalFilterState),
timeDimension: {
- granularity: dashboardDateRangeAggregationSettings[agg].date_trunc,
+ granularity:
+ dashboardDateRangeAggregationSettings[agg].dateTrunc ?? "day",
},
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
@@ -85,7 +86,8 @@ export const TracesAndObservationsTimeSeriesChart = ({
metrics: [{ measure: "count", aggregation: "count" }],
filters: mapLegacyUiTableFilterToView("observations", globalFilterState),
timeDimension: {
- granularity: dashboardDateRangeAggregationSettings[agg].date_trunc,
+ granularity:
+ dashboardDateRangeAggregationSettings[agg].dateTrunc ?? "day",
},
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
diff --git a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
index 6742943476..2abf4616c0 100644
--- a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
@@ -54,7 +54,7 @@ export function CategoricalScoreChart(props: {
timeDimension: props.agg
? {
granularity:
- dashboardDateRangeAggregationSettings[props.agg].date_trunc,
+ dashboardDateRangeAggregationSettings[props.agg].dateTrunc ?? "day",
}
: null,
fromTimestamp: props.fromTimestamp.toISOString(),
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
index 7d86ade905..a98496222d 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
@@ -64,7 +64,8 @@ export function NumericScoreTimeSeriesChart(props: {
},
],
timeDimension: {
- granularity: dashboardDateRangeAggregationSettings[props.agg].date_trunc,
+ granularity:
+ dashboardDateRangeAggregationSettings[props.agg].dateTrunc ?? "day",
},
fromTimestamp: props.fromTimestamp.toISOString(),
toTimestamp: props.toTimestamp.toISOString(),
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index 6550b8d215..4658bb191b 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -101,7 +101,7 @@ const TracesPreview = memo(
return {
from: getDateFromOption({
filterSource: "TABLE",
- option: "24 hours",
+ option: "last1Day",
}),
} as TableDateRange;
}, []);
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index c300be40eb..2523999373 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -32,6 +32,10 @@ import { startCase } from "lodash";
import { DatePickerWithRange } from "@/src/components/date-picker";
import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";
import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";
+import {
+ toAbsoluteTimeRange,
+ type DashboardDateRangeOptions,
+} from "@/src/utils/date-range-utils";
import { type ColumnDefinition } from "@langfuse/shared";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
@@ -258,8 +262,38 @@ export function WidgetForm({
);
// Filter state
- const { selectedOption, dateRange, setDateRangeAndOption } =
- useDashboardDateRange({ defaultRelativeAggregation: "7 days" });
+ const { timeRange, setTimeRange } = useDashboardDateRange({
+ defaultRelativeAggregation: "last7Days",
+ });
+
+ // Convert timeRange to absolute date range for compatibility
+ const dateRange = useMemo(() => {
+ return toAbsoluteTimeRange(timeRange) ?? undefined;
+ }, [timeRange]);
+
+ // Convert timeRange to legacy format for DatePickerWithRange compatibility
+ const selectedOption = useMemo(() => {
+ if ("range" in timeRange) {
+ return timeRange.range;
+ }
+ return "custom" as const;
+ }, [timeRange]);
+
+ const setDateRangeAndOption = (
+ option: DashboardDateRangeOptions,
+ range?: { from: Date; to: Date },
+ ) => {
+ if (option === "custom") {
+ if (range) {
+ setTimeRange({
+ from: range.from,
+ to: range.to,
+ });
+ }
+ } else {
+ setTimeRange({ range: option });
+ }
+ };
const [userFilterState, setUserFilterState] = useState<FilterState>(
initialValues.filters?.map((filter) => {
if (filter.column === "name") {
@@ -1601,8 +1635,16 @@ export function WidgetForm({
<Label htmlFor="date-select">Date Range</Label>
<DatePickerWithRange
dateRange={dateRange}
- setDateRangeAndOption={setDateRangeAndOption}
- selectedOption={selectedOption}
+ setDateRangeAndOption={(option, range) => {
+ if (option === "custom") {
+ setDateRangeAndOption("custom", range);
+ } else {
+ setDateRangeAndOption(option, range);
+ }
+ }}
+ selectedOption={
+ (selectedOption ?? "custom") as DashboardDateRangeOptions
+ }
className="w-full"
/>
</div>
diff --git a/web/src/hooks/useDashboardDateRange.tsx b/web/src/hooks/useDashboardDateRange.tsx
index 9c20107842..74696f7e63 100644
--- a/web/src/hooks/useDashboardDateRange.tsx
+++ b/web/src/hooks/useDashboardDateRange.tsx
@@ -1,28 +1,18 @@
-import { useState } from "react";
import { useQueryParams, StringParam, withDefault } from "use-query-params";
import {
- dashboardDateRangeAggregationSettings,
type DashboardDateRangeAggregationOption,
- isValidDashboardDateRangeAggregationOption,
- type DashboardDateRangeOptions,
- DASHBOARD_AGGREGATION_PLACEHOLDER,
- type DashboardDateRange,
+ DEFAULT_DASHBOARD_AGGREGATION_SELECTION,
+ DASHBOARD_AGGREGATION_OPTIONS,
+ rangeToString,
+ rangeFromString,
+ getAbbreviatedTimeRange,
+ type TimeRange,
} from "@/src/utils/date-range-utils";
-import { addMinutes } from "date-fns";
+import { useMemo } from "react";
export interface UseDashboardDateRangeOutput {
- selectedOption: DashboardDateRangeOptions;
- dateRange: DashboardDateRange | undefined;
- setDateRangeAndOption: (
- option: DashboardDateRangeOptions,
- range?: DashboardDateRange,
- ) => void;
-}
-
-function isDashboardDateRangeAggregationOption(
- dateRange?: string | null,
-): dateRange is DashboardDateRangeAggregationOption {
- return !!dateRange && dateRange in dashboardDateRangeAggregationSettings;
+ timeRange: TimeRange;
+ setTimeRange: (timeRange: TimeRange) => void;
}
export function useDashboardDateRange(
@@ -30,64 +20,31 @@ export function useDashboardDateRange(
defaultRelativeAggregation?: DashboardDateRangeAggregationOption;
} = {},
): UseDashboardDateRangeOutput {
+ const fallbackAggregation =
+ options.defaultRelativeAggregation ??
+ DEFAULT_DASHBOARD_AGGREGATION_SELECTION;
+
const [queryParams, setQueryParams] = useQueryParams({
- dateRange: withDefault(StringParam, "Select a date range"),
- from: StringParam,
- to: StringParam,
+ dateRange: withDefault(
+ StringParam,
+ getAbbreviatedTimeRange(fallbackAggregation),
+ ),
});
- const fallbackAggregation = options.defaultRelativeAggregation ?? "24 hours";
- const initialRangeOption: DashboardDateRangeAggregationOption =
- isDashboardDateRangeAggregationOption(queryParams.dateRange)
- ? queryParams.dateRange
- : fallbackAggregation;
-
- const initialRange: DashboardDateRange | undefined =
- queryParams.dateRange !== "Select a date range" &&
- queryParams.from &&
- queryParams.to
- ? {
- from: new Date(queryParams.from),
- to: new Date(queryParams.to),
- }
- : {
- from: addMinutes(
- new Date(),
- -dashboardDateRangeAggregationSettings[initialRangeOption].minutes,
- ),
- to: new Date(),
- };
+ return useMemo(() => {
+ const timeRange = rangeFromString(
+ queryParams.dateRange,
+ DASHBOARD_AGGREGATION_OPTIONS,
+ fallbackAggregation,
+ );
- const validatedInitialRangeOption =
- isValidDashboardDateRangeAggregationOption(queryParams.dateRange) ||
- queryParams.dateRange === DASHBOARD_AGGREGATION_PLACEHOLDER
- ? (queryParams.dateRange as DashboardDateRangeAggregationOption)
- : initialRangeOption;
-
- const [selectedOption, setSelectedOption] =
- useState<DashboardDateRangeOptions>(validatedInitialRangeOption);
- const [dateRange, setDateRange] = useState<DashboardDateRange | undefined>(
- initialRange,
- );
-
- const setDateRangeAndOption = (
- option: DashboardDateRangeOptions,
- range?: DashboardDateRange,
- ) => {
- setSelectedOption(option);
- setDateRange(range);
-
- const newParams: typeof queryParams = {
- dateRange: option,
- from: undefined,
- to: undefined,
+ const setTimeRange = (timeRange: TimeRange) => {
+ setQueryParams({ dateRange: rangeToString(timeRange) });
};
- if (option === DASHBOARD_AGGREGATION_PLACEHOLDER && range) {
- newParams.from = range.from.toISOString();
- newParams.to = range.to.toISOString();
- }
- setQueryParams(newParams);
- };
- return { selectedOption, dateRange, setDateRangeAndOption };
+ return {
+ timeRange,
+ setTimeRange,
+ };
+ }, [queryParams.dateRange, fallbackAggregation, setQueryParams]);
}
diff --git a/web/src/hooks/useTableDateRange.tsx b/web/src/hooks/useTableDateRange.tsx
index 5e44588423..ff2a728d0c 100644
--- a/web/src/hooks/useTableDateRange.tsx
+++ b/web/src/hooks/useTableDateRange.tsx
@@ -1,61 +1,61 @@
-import { useState } from "react";
import { useQueryParams, StringParam, withDefault } from "use-query-params";
import {
- type TableDateRangeOptions,
- isValidTableDateRangeAggregationOption,
type TableDateRangeAggregationOption,
- type TableDateRange,
- getDateFromOption,
+ TABLE_AGGREGATION_OPTIONS,
+ rangeToString,
+ rangeFromString,
+ getAbbreviatedTimeRange,
+ type TimeRange,
} from "@/src/utils/date-range-utils";
+import { useMemo } from "react";
import useSessionStorage from "@/src/components/useSessionStorage";
export interface UseTableDateRangeOutput {
- selectedOption: TableDateRangeOptions;
- dateRange: TableDateRange | undefined;
- setDateRangeAndOption: (
- option: TableDateRangeOptions,
- range?: TableDateRange,
- ) => void;
+ timeRange: TimeRange;
+ setTimeRange: (timeRange: TimeRange) => void;
}
-export function useTableDateRange(projectId: string): UseTableDateRangeOutput {
+export function useTableDateRange(
+ projectId: string,
+ options: {
+ defaultRelativeAggregation?: TableDateRangeAggregationOption;
+ } = {},
+): UseTableDateRangeOutput {
+ const fallbackAggregation = options.defaultRelativeAggregation ?? "last1Day";
+
+ // Get stored preference from local storage
+ const [storedDateRange, setStoredDateRange] = useSessionStorage(
+ `tableDateRangeState-${projectId}`,
+ getAbbreviatedTimeRange(fallbackAggregation),
+ );
+
+ // Use stored preference as default if no URL param is set
const [queryParams, setQueryParams] = useQueryParams({
- dateRange: withDefault(StringParam, "Select a date range"),
+ dateRange: withDefault(StringParam, storedDateRange),
});
- const defaultDateRange: TableDateRangeOptions = "24 hours";
- const validatedInitialRangeOption = isValidTableDateRangeAggregationOption(
- queryParams.dateRange,
- )
- ? (queryParams.dateRange as TableDateRangeAggregationOption)
- : defaultDateRange;
-
- const [selectedOption, setSelectedOption] =
- useSessionStorage<TableDateRangeOptions>(
- `tableDateRangeState-${projectId}`,
- validatedInitialRangeOption,
+ return useMemo(() => {
+ const timeRange = rangeFromString(
+ queryParams.dateRange,
+ TABLE_AGGREGATION_OPTIONS,
+ fallbackAggregation,
);
- const dateFromOption = getDateFromOption({
- filterSource: "TABLE",
- option: selectedOption,
- });
-
- const initialDateRange = !!dateFromOption
- ? { from: dateFromOption }
- : undefined;
-
- const [dateRange, setDateRange] = useState<TableDateRange | undefined>(
- initialDateRange,
- );
- const setDateRangeAndOption = (
- option: TableDateRangeOptions,
- range?: TableDateRange,
- ) => {
- setSelectedOption(option);
- setDateRange(range);
- setQueryParams({ dateRange: option });
- };
-
- return { selectedOption, dateRange, setDateRangeAndOption };
+ const setTimeRange = (timeRange: TimeRange) => {
+ const newParam = rangeToString(timeRange);
+ setQueryParams({ dateRange: newParam });
+ // Also update local storage for future sessions
+ setStoredDateRange(newParam);
+ };
+
+ return {
+ timeRange,
+ setTimeRange,
+ };
+ }, [
+ queryParams.dateRange,
+ fallbackAggregation,
+ setQueryParams,
+ setStoredDateRange,
+ ]);
}
diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
index add21a8e18..46723c3ec4 100644
--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
@@ -2,7 +2,7 @@ import { useRouter } from "next/router";
import { api } from "@/src/utils/api";
import Page from "@/src/components/layouts/page";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
-import { DatePickerWithRange } from "@/src/components/date-picker";
+import { TimeRangePicker } from "@/src/components/date-picker";
import { PopoverFilterBuilder } from "@/src/features/filters/components/filter-builder";
import { useEffect, useState, useMemo, useCallback } from "react";
import type { ColumnDefinition, FilterState } from "@langfuse/shared";
@@ -20,6 +20,11 @@ import { useDebounce } from "@/src/hooks/useDebounce";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { DashboardGrid } from "@/src/features/widgets/components/DashboardGrid";
import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";
+import {
+ DASHBOARD_AGGREGATION_OPTIONS,
+ toAbsoluteTimeRange,
+} from "@/src/utils/date-range-utils";
+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";
interface WidgetPlacement {
id: string;
@@ -42,6 +47,8 @@ export default function DashboardDetail() {
addWidgetId?: string;
};
+ const lookbackLimit = useEntitlementLimit("data-access-days");
+
// Fetch dashboard data
const dashboard = api.dashboard.getDashboard.useQuery({
projectId,
@@ -66,8 +73,11 @@ export default function DashboardDetail() {
const [currentFilters, setCurrentFilters] = useState<FilterState>([]);
// Date range state - use the hook for all date range logic
- const { selectedOption, dateRange, setDateRangeAndOption } =
- useDashboardDateRange({ defaultRelativeAggregation: "7 days" });
+ const { timeRange, setTimeRange } = useDashboardDateRange();
+ const absoluteTimeRange = useMemo(
+ () => toAbsoluteTimeRange(timeRange) ?? undefined,
+ [timeRange],
+ );
// Check if current filters differ from saved filters
const hasUnsavedFilterChanges = useMemo(() => {
@@ -200,7 +210,7 @@ export default function DashboardDetail() {
api.projects.environmentFilterOptions.useQuery(
{
projectId,
- fromTimestamp: dateRange?.from,
+ fromTimestamp: absoluteTimeRange?.from,
},
{
trpc: {
@@ -382,6 +392,8 @@ export default function DashboardDetail() {
mutateCloneDashboard.mutate({ projectId, dashboardId });
};
+ const dashboardTimeRangePresets = DASHBOARD_AGGREGATION_OPTIONS;
+
return (
<Page
withPadding
@@ -447,11 +459,21 @@ export default function DashboardDetail() {
<div>
<div className="my-3 flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-col gap-2 lg:flex-row lg:gap-3">
- <DatePickerWithRange
- dateRange={dateRange}
- setDateRangeAndOption={setDateRangeAndOption}
- selectedOption={selectedOption}
+ <TimeRangePicker
+ timeRange={timeRange}
+ onTimeRangeChange={setTimeRange}
+ timeRangePresets={dashboardTimeRangePresets}
className="my-0 max-w-full overflow-x-auto"
+ disabled={
+ lookbackLimit
+ ? {
+ before: new Date(
+ new Date().getTime() -
+ lookbackLimit * 24 * 60 * 60 * 1000,
+ ),
+ }
+ : undefined
+ }
/>
<PopoverFilterBuilder
columns={filterColumns}
@@ -475,7 +497,7 @@ export default function DashboardDetail() {
canEdit={hasCUDAccess}
dashboardId={dashboardId}
projectId={projectId}
- dateRange={dateRange}
+ dateRange={absoluteTimeRange}
filterState={currentFilters}
onDeleteWidget={handleDeleteWidget}
dashboardOwner={dashboard.data?.owner}
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index 9af8ed6d32..c7157a00e7 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -7,7 +7,7 @@ import { ScoresTable } from "@/src/features/dashboard/components/ScoresTable";
import { ModelUsageChart } from "@/src/features/dashboard/components/ModelUsageChart";
import { TracesAndObservationsTimeSeriesChart } from "@/src/features/dashboard/components/TracesTimeSeriesChart";
import { UserChart } from "@/src/features/dashboard/components/UserChart";
-import { DatePickerWithRange } from "@/src/components/date-picker";
+import { TimeRangePicker } from "@/src/components/date-picker";
import { api } from "@/src/utils/api";
import { FeedbackButtonWrapper } from "@/src/features/feedback/component/FeedbackButton";
import { BarChart2 } from "lucide-react";
@@ -18,7 +18,12 @@ import { type ColumnDefinition } from "@langfuse/shared";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { LatencyTables } from "@/src/features/dashboard/components/LatencyTables";
import { useMemo } from "react";
-import { findClosestDashboardInterval } from "@/src/utils/date-range-utils";
+import {
+ findClosestDashboardInterval,
+ DASHBOARD_AGGREGATION_OPTIONS,
+ toAbsoluteTimeRange,
+ type DashboardDateRangeAggregationOption,
+} from "@/src/utils/date-range-utils";
import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";
import { useDebounce } from "@/src/hooks/useDebounce";
import { ScoreAnalytics } from "@/src/features/dashboard/components/score-analytics/ScoreAnalytics";
@@ -35,8 +40,11 @@ import {
export default function Dashboard() {
const router = useRouter();
const projectId = router.query.projectId as string;
- const { selectedOption, dateRange, setDateRangeAndOption } =
- useDashboardDateRange();
+ const { timeRange, setTimeRange } = useDashboardDateRange();
+ const absoluteTimeRange = useMemo(
+ () => toAbsoluteTimeRange(timeRange),
+ [timeRange],
+ );
const uiCustomization = useUiCustomization();
@@ -69,7 +77,7 @@ export default function Dashboard() {
api.projects.environmentFilterOptions.useQuery(
{
projectId,
- fromTimestamp: dateRange?.from,
+ fromTimestamp: absoluteTimeRange?.from,
},
{
trpc: {
@@ -128,18 +136,20 @@ export default function Dashboard() {
},
];
- const agg = useMemo(
- () =>
- dateRange
- ? (findClosestDashboardInterval(dateRange) ?? "7 days")
- : "7 days",
- [dateRange],
- );
+ const dashboardTimeRangePresets = DASHBOARD_AGGREGATION_OPTIONS;
+
+ const agg = useMemo(() => {
+ if ("range" in timeRange) {
+ return timeRange.range as DashboardDateRangeAggregationOption;
+ }
+
+ return findClosestDashboardInterval(timeRange) ?? "last7Days";
+ }, [timeRange]);
- const fromTimestamp = dateRange
- ? dateRange.from
+ const fromTimestamp = absoluteTimeRange?.from
+ ? absoluteTimeRange.from
: new Date(new Date().getTime() - 1000);
- const toTimestamp = dateRange ? dateRange.to : new Date();
+ const toTimestamp = absoluteTimeRange?.to ? absoluteTimeRange.to : new Date();
const timeFilter = [
{
type: "datetime" as const,
@@ -177,10 +187,10 @@ export default function Dashboard() {
>
<div className="my-3 flex flex-wrap items-center justify-between gap-2">
<div className="flex flex-col gap-2 lg:flex-row lg:gap-3">
- <DatePickerWithRange
- dateRange={dateRange}
- setDateRangeAndOption={useDebounce(setDateRangeAndOption)}
- selectedOption={selectedOption}
+ <TimeRangePicker
+ timeRange={timeRange}
+ onTimeRangeChange={setTimeRange}
+ timeRangePresets={dashboardTimeRangePresets}
className="my-0 max-w-full overflow-x-auto"
disabled={
lookbackLimit
diff --git a/web/src/pages/project/[projectId]/users.tsx b/web/src/pages/project/[projectId]/users.tsx
index 4351eec944..d415c3c5db 100644
--- a/web/src/pages/project/[projectId]/users.tsx
+++ b/web/src/pages/project/[projectId]/users.tsx
@@ -1,5 +1,5 @@
import { useRouter } from "next/router";
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import {
NumberParam,
StringParam,
@@ -21,6 +21,7 @@ import { type FilterState } from "@langfuse/shared";
import { usersTableCols } from "@/src/server/api/definitions/usersTable";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
+import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
import { useDebounce } from "@/src/hooks/useDebounce";
import Page from "@/src/components/layouts/page";
import { UsersOnboarding } from "@/src/components/onboarding/UsersOnboarding";
@@ -95,8 +96,12 @@ const UsersTable = () => {
pageSize: withDefault(NumberParam, 50),
});
- const { selectedOption, dateRange, setDateRangeAndOption } =
- useTableDateRange(projectId);
+ const { timeRange, setTimeRange } = useTableDateRange(projectId);
+
+ // Convert timeRange to absolute date range for compatibility
+ const dateRange = useMemo(() => {
+ return toAbsoluteTimeRange(timeRange) ?? undefined;
+ }, [timeRange]);
const dateRangeFilter: FilterState = dateRange
? [
@@ -342,8 +347,8 @@ const UsersTable = () => {
filterState={userFilterState}
setFilterState={useDebounce(setUserFilterState)}
columns={columns}
- selectedOption={selectedOption}
- setDateRangeAndOption={setDateRangeAndOption}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
searchConfig={{
metadataSearchFields: ["User ID"],
updateQuery: setSearchQuery,
diff --git a/web/src/utils/date-range-utils.ts b/web/src/utils/date-range-utils.ts
index 53b797a13d..a5f5d64d4a 100644
--- a/web/src/utils/date-range-utils.ts
+++ b/web/src/utils/date-range-utils.ts
@@ -1,34 +1,134 @@
-import { type DateRange } from "react-day-picker";
import { z } from "zod/v4";
-import { addMinutes } from "date-fns";
+import { addMinutes, format } from "date-fns";
import { type DateTrunc } from "@langfuse/shared/src/server";
-export const DEFAULT_DASHBOARD_AGGREGATION_SELECTION = "24 hours" as const;
-export const DASHBOARD_AGGREGATION_PLACEHOLDER = "Custom" as const;
+interface TimeRangeDefinition {
+ label: string;
+ abbreviation: string;
+ minutes: number | null;
+ dateTrunc: DateTrunc | null;
+}
+
+export const TIME_RANGES = {
+ last5Minutes: {
+ label: "Past 5 min",
+ abbreviation: "5m",
+ minutes: 5,
+ dateTrunc: "minute",
+ },
+ last30Minutes: {
+ label: "Past 30 min",
+ abbreviation: "30m",
+ minutes: 30,
+ dateTrunc: "minute",
+ },
+ last1Hour: {
+ label: "Past 1 hour",
+ abbreviation: "1h",
+ minutes: 60,
+ dateTrunc: "minute",
+ },
+ last3Hours: {
+ label: "Past 3 hours",
+ abbreviation: "3h",
+ minutes: 3 * 60,
+ dateTrunc: "minute",
+ },
+ last6Hours: {
+ label: "Past 6 hours",
+ abbreviation: "6h",
+ minutes: 6 * 60,
+ dateTrunc: "minute",
+ },
+ last1Day: {
+ label: "Past 1 day",
+ abbreviation: "1d",
+ minutes: 24 * 60,
+ dateTrunc: "hour",
+ },
+ last3Days: {
+ label: "Past 3 days",
+ abbreviation: "3d",
+ minutes: 3 * 24 * 60,
+ dateTrunc: "hour",
+ },
+ last7Days: {
+ label: "Past 7 days",
+ abbreviation: "7d",
+ minutes: 7 * 24 * 60,
+ dateTrunc: "hour",
+ },
+ last14Days: {
+ label: "Past 14 days",
+ abbreviation: "14d",
+ minutes: 14 * 24 * 60,
+ dateTrunc: "day",
+ },
+ last30Days: {
+ label: "Past 30 days",
+ abbreviation: "30d",
+ minutes: 30 * 24 * 60,
+ dateTrunc: "day",
+ },
+ last90Days: {
+ label: "Past 90 days",
+ abbreviation: "90d",
+ minutes: 90 * 24 * 60,
+ dateTrunc: "week",
+ },
+ last1Year: {
+ label: "Past 1 year",
+ abbreviation: "1y",
+ minutes: 365 * 24 * 60,
+ dateTrunc: "month",
+ },
+ allTime: {
+ label: "All time",
+ abbreviation: "All",
+ minutes: null,
+ dateTrunc: null,
+ },
+ custom: {
+ label: "Custom",
+ abbreviation: "Custom",
+ minutes: null,
+ dateTrunc: null,
+ },
+} satisfies Record<string, TimeRangeDefinition>;
+
+export type TimeRangePresets = Exclude<keyof typeof TIME_RANGES, "custom">;
+
+const ABBREVIATION_TO_KEY = new Map(
+ Object.entries(TIME_RANGES).map(([key, def]) => [def.abbreviation, key]),
+);
+
+export const DEFAULT_DASHBOARD_AGGREGATION_SELECTION = "last1Day" as const;
+export const DASHBOARD_AGGREGATION_PLACEHOLDER = "custom" as const;
+export const TABLE_AGGREGATION_PLACEHOLDER = "custom" as const;
export const DASHBOARD_AGGREGATION_OPTIONS = [
- "5 min",
- "30 min",
- "1 hour",
- "3 hours",
- "24 hours",
- "7 days",
- "1 month",
- "3 months",
- "1 year",
+ "last5Minutes",
+ "last30Minutes",
+ "last1Hour",
+ "last3Hours",
+ "last1Day",
+ "last7Days",
+ "last30Days",
+ "last90Days",
+ "last1Year",
] as const;
export const TABLE_AGGREGATION_OPTIONS = [
- "30 min",
- "1 hour",
- "6 hours",
- "24 hours",
- "3 days",
- "7 days",
- "14 days",
- "1 month",
- "3 months",
- "All time",
+ "last30Minutes",
+ "last1Hour",
+ "last6Hours",
+ "last1Day",
+ "last3Days",
+ "last7Days",
+ "last14Days",
+ "last30Days",
+ "last90Days",
+ "allTime",
] as const;
export type DashboardDateRangeAggregationOption =
@@ -36,6 +136,7 @@ export type DashboardDateRangeAggregationOption =
export type TableDateRange = {
from: Date;
+ to?: Date;
};
export type TableDateRangeAggregationOption =
@@ -54,13 +155,13 @@ export type DashboardDateRangeOptions =
| DashboardDateRangeAggregationOption
| typeof DASHBOARD_AGGREGATION_PLACEHOLDER;
-export type TableDateRangeOptions = TableDateRangeAggregationOption;
+export type TableDateRangeOptions =
+ | TableDateRangeAggregationOption
+ | typeof TABLE_AGGREGATION_PLACEHOLDER;
+
export type DashboardDateRangeAggregationSettings = Record<
DashboardDateRangeAggregationOption,
- {
- date_trunc: DateTrunc;
- minutes: number;
- }
+ TimeRangeDefinition
>;
export const dateTimeAggregationOptions = [
@@ -69,44 +170,12 @@ export const dateTimeAggregationOptions = [
] as const;
export const dashboardDateRangeAggregationSettings: DashboardDateRangeAggregationSettings =
- {
- "1 year": {
- date_trunc: "month",
- minutes: 365 * 24 * 60,
- },
- "3 months": {
- date_trunc: "week",
- minutes: 3 * 30 * 24 * 60,
- },
- "1 month": {
- date_trunc: "day",
- minutes: 30 * 24 * 60,
- },
- "7 days": {
- date_trunc: "hour",
- minutes: 7 * 24 * 60,
- },
- "24 hours": {
- date_trunc: "hour",
- minutes: 24 * 60,
- },
- "3 hours": {
- date_trunc: "minute",
- minutes: 3 * 60,
- },
- "1 hour": {
- date_trunc: "minute",
- minutes: 60,
- },
- "30 min": {
- date_trunc: "minute",
- minutes: 30,
- },
- "5 min": {
- date_trunc: "minute",
- minutes: 5,
- },
- };
+ Object.fromEntries(
+ DASHBOARD_AGGREGATION_OPTIONS.map((option) => [
+ option,
+ TIME_RANGES[option as keyof typeof TIME_RANGES],
+ ]),
+ ) as DashboardDateRangeAggregationSettings;
export const SelectedTimeOptionSchema = z
.discriminatedUnion("filterSource", [
@@ -131,6 +200,7 @@ export const isDashboardDateRangeOptionAvailable = ({
if (limitDays === false) return true;
const { minutes } = dashboardDateRangeAggregationSettings[option];
+ if (!minutes) return true; // Handle null minutes (like allTime)
return limitDays >= minutes / (24 * 60);
};
@@ -139,18 +209,12 @@ type SelectedTimeOption = z.infer<typeof SelectedTimeOptionSchema>;
const TABLE_DATE_RANGE_AGGREGATION_SETTINGS = new Map<
TableDateRangeAggregationOption,
number | null
->([
- ["3 months", 3 * 30 * 24 * 60],
- ["1 month", 30 * 24 * 60],
- ["14 days", 14 * 24 * 60],
- ["7 days", 7 * 24 * 60],
- ["3 days", 3 * 24 * 60],
- ["24 hours", 24 * 60],
- ["6 hours", 6 * 60],
- ["1 hour", 60],
- ["30 min", 30],
- ["All time", null],
-]);
+>(
+ TABLE_AGGREGATION_OPTIONS.map((option) => [
+ option,
+ TIME_RANGES[option].minutes,
+ ]),
+);
export const isTableDataRangeOptionAvailable = ({
option,
@@ -184,6 +248,7 @@ export const getDateFromOption = (
option as keyof typeof dashboardDateRangeAggregationSettings
];
+ if (!setting.minutes) return undefined; // Handle null minutes (like allTime)
return addMinutes(new Date(), -setting.minutes);
}
return undefined;
@@ -203,8 +268,26 @@ export function isValidTableDateRangeAggregationOption(
return (TABLE_AGGREGATION_OPTIONS as readonly string[]).includes(value);
}
+export function getAbbreviatedTimeRange(option: string): string {
+ return (
+ TIME_RANGES[option as keyof typeof TIME_RANGES]?.abbreviation || option
+ );
+}
+
+export function getFullTimeRangeFromAbbreviated(
+ abbreviated: string,
+): DateRangeAggregationOption | null {
+ return (
+ (ABBREVIATION_TO_KEY.get(abbreviated) as DateRangeAggregationOption) || null
+ );
+}
+
+export function getTimeRangeLabel(option: string): string {
+ return TIME_RANGES[option as keyof typeof TIME_RANGES]?.label || option;
+}
+
export const findClosestDashboardInterval = (
- dateRange: DateRange,
+ dateRange: AbsoluteTimeRange,
): DashboardDateRangeAggregationOption | undefined => {
if (!dateRange.from || !dateRange.to) return undefined;
const duration = dateRange.to.getTime() - dateRange.from.getTime();
@@ -213,7 +296,7 @@ export const findClosestDashboardInterval = (
const { minutes } = dashboardDateRangeAggregationSettings[interval];
return {
interval,
- diff: Math.abs(duration - minutes * 60 * 1000),
+ diff: Math.abs(duration - minutes! * 60 * 1000),
};
});
@@ -221,3 +304,126 @@ export const findClosestDashboardInterval = (
return diffs[0]?.interval;
};
+
+// Helper function to check if time represents full day
+export const isFullDay = (date: Date) => {
+ return (
+ date.getHours() === 0 && date.getMinutes() === 0 && date.getSeconds() === 0
+ );
+};
+
+// Helper function to check if date range represents full days
+export const isFullDayRange = (from: Date, to: Date) => {
+ return (
+ isFullDay(from) &&
+ to.getHours() === 23 &&
+ to.getMinutes() === 59 &&
+ to.getSeconds() === 59
+ );
+};
+
+// Format date range with smart year display and time inclusion
+export const formatDateRange = (from: Date, to: Date) => {
+ const currentYear = new Date().getFullYear();
+ const fromYear = from.getFullYear();
+ const toYear = to.getFullYear();
+
+ const showFromYear = fromYear !== currentYear;
+ const showToYear = toYear !== currentYear;
+
+ if (isFullDayRange(from, to)) {
+ // Show just dates for full day ranges
+ const fromPattern = showFromYear ? "LLL dd, yyyy" : "LLL dd";
+ const toPattern = showToYear ? "LLL dd, yyyy" : "LLL dd";
+ return `${format(from, fromPattern)} - ${format(to, toPattern)}`;
+ } else {
+ // Show dates with times for partial day ranges
+ const fromPattern = showFromYear ? "LLL dd yyyy, HH:mm" : "LLL dd, HH:mm";
+ const toPattern = showToYear ? "LLL dd yyyy, HH:mm" : "LLL dd, HH:mm";
+ return `${format(from, fromPattern)} - ${format(to, toPattern)}`;
+ }
+};
+
+export type RelativeTimeRange = {
+ range: string;
+};
+
+export type AbsoluteTimeRange = {
+ from: Date;
+ to: Date;
+};
+
+export type TimeRange = RelativeTimeRange | AbsoluteTimeRange;
+
+export const toAbsoluteTimeRange = (
+ timeRange: TimeRange,
+): AbsoluteTimeRange | null => {
+ if ("from" in timeRange) {
+ return timeRange;
+ }
+
+ const preset = TIME_RANGES[timeRange.range as keyof typeof TIME_RANGES];
+
+ if (!preset?.minutes) {
+ return null;
+ }
+
+ return {
+ from: addMinutes(new Date(), -preset.minutes),
+ to: new Date(),
+ };
+};
+
+/**
+ * Converts a range object to a string for URL serialization
+ * - Named ranges: "last7Days" -> "7d" (abbreviated)
+ * - Custom ranges: {from, to} -> "1693872000000-1694131199999"
+ */
+export function rangeToString(range: TimeRange): string {
+ if ("range" in range) {
+ return getAbbreviatedTimeRange(range.range);
+ } else {
+ return `${range.from.getTime()}-${range.to.getTime()}`;
+ }
+}
+
+/**
+ * Parses a string back to a range object with validation
+ * - Handles both abbreviated ("7d") and full ("last7Days") named ranges
+ * - Handles custom timestamp ranges ("1693872000000-1694131199999")
+ * - Returns fallback if parsing fails or range is not in allowedRanges
+ */
+export function rangeFromString<T extends string>(
+ abbreviatedRange: string,
+ allowedRanges: readonly T[],
+ fallback: T,
+): TimeRange {
+ // Named range
+ const fullRange = getFullTimeRangeFromAbbreviated(abbreviatedRange);
+ if (allowedRanges.includes(fullRange as T)) {
+ return { range: fullRange as T };
+ }
+
+ // Try parsing as custom range
+ try {
+ const parts = abbreviatedRange.split("-");
+ if (parts.length === 2) {
+ const fromTimestamp = parseInt(parts[0], 10);
+ const toTimestamp = parseInt(parts[1], 10);
+
+ if (!isNaN(fromTimestamp) && !isNaN(toTimestamp)) {
+ const from = new Date(fromTimestamp);
+ const to = new Date(toTimestamp);
+
+ // Validate dates
+ if (!isNaN(from.getTime()) && !isNaN(to.getTime()) && from <= to) {
+ return { from, to };
+ }
+ }
+ }
+ } catch (error) {
+ // Continue to fallback
+ }
+
+ return { range: fallback };
+}