Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat(dashboard): date picker shows presets and a calendar together, with arrows to step periods (#589)

Carl-Gerhard Lindesvärdd3dee2953b55
diff --git a/apps/start/e2e/overview-chart.spec.ts b/apps/start/e2e/overview-chart.spec.ts
index 03231df7d..19da38115 100644
--- a/apps/start/e2e/overview-chart.spec.ts
+++ b/apps/start/e2e/overview-chart.spec.ts
@@ -127,11 +127,10 @@ test('custom range through the date picker and the "last days" input', async ({
await dismissFeedbackPrompt(page);
await page.getByRole('button', { name: 'Last 7 days', exact: true }).click();
- await page.getByRole('menuitem', { name: /^Custom range/ }).click();
const picker = page.getByRole('dialog');
await expect(picker.getByRole('button', { name: 'Cancel' })).toBeVisible();
- // Nothing is selected yet, so there is nothing to confirm.
- await expect(picker.getByRole('button', { name: /^Select / })).toHaveCount(0);
+ // Nothing is picked yet, so there is nothing to apply.
+ await expect(picker.getByRole('button', { name: 'Apply' })).toBeDisabled();
await shot(page, 'chart-datepicker-empty', false);
// The October grid repeats the last September days, hence `first()`.
@@ -144,14 +143,14 @@ test('custom range through the date picker and the "last days" input', async ({
.first()
.click();
await shot(page, 'chart-datepicker-selected', false);
- await picker.getByRole('button', { name: /^Select / }).click();
+ await picker.getByRole('button', { name: 'Apply' }).click();
await expect(page).toHaveURL(/range=custom/);
const search = new URL(page.url()).searchParams;
expect(search.get('start')).toBe('2026-09-22 00:00:00');
expect(search.get('end')).toBe('2026-09-28 23:59:59');
await expect(
- page.getByRole('button', { name: 'Custom range', exact: true })
+ page.getByRole('button', { name: '22 sep – 28 sep', exact: true })
).toBeVisible();
await expect(
page.getByRole('button', { name: 'Day', exact: true })
@@ -172,17 +171,17 @@ test('custom range through the date picker and the "last days" input', async ({
await page.reload();
await overviewReady(page);
await expect(
- page.getByRole('button', { name: 'Custom range', exact: true })
+ page.getByRole('button', { name: '22 sep – 28 sep', exact: true })
).toBeVisible();
await expect(metricCard(page, 'Sessions')).toContainText(
compactNumber(Number(custom.metrics.total_sessions))
);
// "Last days" input
- await page.getByRole('button', { name: 'Custom range', exact: true }).click();
- const days = page.getByRole('spinbutton', {
- name: 'Number of days for custom date filter',
- });
+ await page
+ .getByRole('button', { name: '22 sep – 28 sep', exact: true })
+ .click();
+ const days = page.getByRole('spinbutton', { name: 'Number of days' });
await days.fill('3');
await days.press('Enter');
await expect(page).toHaveURL(/start=/);
@@ -202,7 +201,7 @@ test('custom range through the date picker and the "last days" input', async ({
// Out-of-range values are ignored.
const urlBefore = page.url();
- await page.getByRole('button', { name: 'Custom range', exact: true }).click();
+ await page.getByRole('button', { name: /^\d+ \w+ – \d+ \w+$/ }).click();
await days.fill('0');
await days.press('Enter');
await days.fill('366');
diff --git a/apps/start/e2e/overview-metrics.spec.ts b/apps/start/e2e/overview-metrics.spec.ts
index f5d6e3e62..23e1355f4 100644
--- a/apps/start/e2e/overview-metrics.spec.ts
+++ b/apps/start/e2e/overview-metrics.spec.ts
@@ -213,9 +213,13 @@ test('every range can be picked, sets its default interval and enables the right
})
.first()
.click();
+ // Exact, since the calendar also names today's cell "Today, …".
await page
- .getByRole('menuitem', { name: new RegExp(`^${range.label}`) })
+ .getByRole('dialog')
+ .getByRole('button', { name: range.label, exact: true })
.click();
+ // The picker animates out; its preset would otherwise match the trigger's name.
+ await expect(page.getByRole('dialog')).toBeHidden();
await expect(page).toHaveURL(new RegExp(`range=${range.key}(&|$)`));
await overviewReady(page);
await expect(
diff --git a/apps/start/e2e/overview-range-stepper.spec.ts b/apps/start/e2e/overview-range-stepper.spec.ts
new file mode 100644
index 000000000..ecc3d468c
--- /dev/null
+++ b/apps/start/e2e/overview-range-stepper.spec.ts
@@ -0,0 +1,137 @@
+import { expect as baseExpect, test } from './fixtures';
+import {
+ attachProblems,
+ dismissFeedbackPrompt,
+ expectNoRealProblems,
+ gotoOverview,
+ overviewReady,
+ shot,
+ watchPage,
+} from './overview-helpers';
+
+const expect = baseExpect.configure({ timeout: 30_000 });
+test.use({ actionTimeout: 20_000 });
+
+const PROJECT = 'acme-shop';
+
+function searchParams(page: { url: () => string }) {
+ return new URL(page.url()).searchParams;
+}
+
+test('the date picker opens as one popover with presets and a calendar', async ({
+ page,
+}, testInfo) => {
+ const problems = watchPage(page);
+ await gotoOverview(page, PROJECT, '?range=7d');
+ await dismissFeedbackPrompt(page);
+
+ await page.getByRole('button', { name: 'Last 7 days', exact: true }).click();
+ const picker = page.getByRole('dialog');
+ await expect(
+ picker.getByRole('button', { name: 'Last 30 min' })
+ ).toBeVisible();
+ await expect(picker.getByRole('button', { name: 'Last year' })).toBeVisible();
+ await expect(picker.getByRole('grid')).toHaveCount(2);
+ await expect(picker.getByRole('button', { name: 'Apply' })).toBeDisabled();
+ await shot(page, 'range-picker-open', false);
+
+ // A preset applies at once and closes the picker.
+ await picker.getByRole('button', { name: 'Yesterday' }).click();
+ await expect(picker).toBeHidden();
+ await expect(page).toHaveURL(/range=yesterday/);
+ await expect(
+ page.getByRole('button', { name: 'Yesterday', exact: true })
+ ).toBeVisible();
+
+ await attachProblems(testInfo, problems);
+ expect(expectNoRealProblems(problems)).toEqual({
+ pageErrors: [],
+ responses: [],
+ });
+});
+
+test('on a phone the presets sit above a single-month calendar', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 390, height: 844 });
+ await gotoOverview(page, PROJECT, '?range=7d');
+ await dismissFeedbackPrompt(page);
+ await page.getByRole('button', { name: 'Last 7 days', exact: true }).click();
+ const picker = page.getByRole('dialog');
+ await expect(picker.getByRole('grid')).toHaveCount(1);
+ await expect(picker.getByRole('button', { name: 'Apply' })).toBeVisible();
+ // The popover fades in; a screenshot mid-animation looks transparent.
+ await expect(picker).toHaveCSS('opacity', '1');
+ await shot(page, 'range-picker-mobile', false);
+});
+
+// The stepper reads the browser clock, so the dated expectations below pin it.
+const PINNED_NOW = new Date(2026, 9, 23, 14, 30, 0);
+
+test('the arrows step the window by its own length and stop at today', async ({
+ page,
+}) => {
+ await page.clock.setFixedTime(PINNED_NOW);
+ await gotoOverview(page, PROJECT, '?range=7d');
+ await dismissFeedbackPrompt(page);
+
+ // "Last 7 days" on the pinned 2026-10-23 is Oct 16 – Oct 23, the same eight days the API uses.
+ await expect(
+ page.getByRole('button', { name: 'Next period' })
+ ).toBeDisabled();
+ await page.getByRole('button', { name: 'Previous period' }).click();
+ await expect(page).toHaveURL(/range=custom/);
+ expect(searchParams(page).get('start')).toBe('2026-10-08 00:00:00');
+ expect(searchParams(page).get('end')).toBe('2026-10-15 23:59:59');
+ await overviewReady(page);
+ await expect(
+ page.getByRole('button', { name: '8 oct – 15 oct', exact: true })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', { name: 'Day', exact: true })
+ ).toBeVisible();
+ await shot(page, 'range-stepper-previous', false);
+
+ await page.getByRole('button', { name: 'Next period' }).click();
+ await expect(
+ page.getByRole('button', { name: '16 oct – 23 oct', exact: true })
+ ).toBeVisible();
+ expect(searchParams(page).get('start')).toBe('2026-10-16 00:00:00');
+ expect(searchParams(page).get('end')).toBe('2026-10-23 23:59:59');
+ await expect(
+ page.getByRole('button', { name: 'Next period' })
+ ).toBeDisabled();
+});
+
+test('stepping a calendar month keeps whole months', async ({ page }) => {
+ await page.clock.setFixedTime(PINNED_NOW);
+ await gotoOverview(page, PROJECT, '?range=lastMonth');
+ await dismissFeedbackPrompt(page);
+
+ await page.getByRole('button', { name: 'Previous period' }).click();
+ await expect(
+ page.getByRole('button', { name: '1 aug – 31 aug', exact: true })
+ ).toBeVisible();
+ expect(searchParams(page).get('start')).toBe('2026-08-01 00:00:00');
+ expect(searchParams(page).get('end')).toBe('2026-08-31 23:59:59');
+
+ await page.getByRole('button', { name: 'Next period' }).click();
+ await expect(
+ page.getByRole('button', { name: '1 sep – 30 sep', exact: true })
+ ).toBeVisible();
+});
+
+test('stepping a minute window keeps the minute interval', async ({ page }) => {
+ await gotoOverview(page, PROJECT, '?range=30min');
+ await dismissFeedbackPrompt(page);
+ await expect(
+ page.getByRole('button', { name: 'Minute', exact: true })
+ ).toBeVisible();
+
+ await page.getByRole('button', { name: 'Previous period' }).click();
+ await expect(page).toHaveURL(/range=custom/);
+ await expect(page).toHaveURL(/overrideInterval=minute/);
+ await expect(
+ page.getByRole('button', { name: 'Minute', exact: true })
+ ).toBeVisible();
+});
diff --git a/apps/start/e2e/overview-share.spec.ts b/apps/start/e2e/overview-share.spec.ts
index f0594c11d..4a00ef696 100644
--- a/apps/start/e2e/overview-share.spec.ts
+++ b/apps/start/e2e/overview-share.spec.ts
@@ -146,7 +146,10 @@ test('public share: create from the modal, open logged out, then make private',
await visitor.page
.getByRole('button', { name: 'Last 7 days', exact: true })
.click();
- await visitor.page.getByRole('menuitem', { name: /^Last 30 days/ }).click();
+ await visitor.page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^Last 30 days/ })
+ .click();
const month = await fetchStats(page, PROJECT, { range: '30d' });
await expect(metricCard(visitor.page, 'Sessions')).toContainText(
compactNumber(Number(month.metrics.total_sessions))
diff --git a/apps/start/e2e/overview-siblings.spec.ts b/apps/start/e2e/overview-siblings.spec.ts
index c4a6e95dd..0291c211b 100644
--- a/apps/start/e2e/overview-siblings.spec.ts
+++ b/apps/start/e2e/overview-siblings.spec.ts
@@ -189,7 +189,10 @@ test.describe('390px mobile viewport', () => {
await page
.getByRole('button', { name: 'Last 7 days', exact: true })
.click();
- await page.getByRole('menuitem', { name: /^Last 30 days/ }).click();
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^Last 30 days/ })
+ .click();
await expect(page).toHaveURL(/range=30d/);
await shot(page, 'mobile-overview-30d', false);
diff --git a/apps/start/e2e/reports-dashboards.spec.ts b/apps/start/e2e/reports-dashboards.spec.ts
index f4ba9a751..4cccfc3df 100644
--- a/apps/start/e2e/reports-dashboards.spec.ts
+++ b/apps/start/e2e/reports-dashboards.spec.ts
@@ -128,11 +128,14 @@ test('dashboard page: search, range, duplicate, move, delete, reload', async ({
.getByRole('button', { name: /Last 7 days|Last 30 days|Today/ })
.first()
.click();
- await page.getByRole('menuitem', { name: 'Last 30 days' }).click();
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: 'Last 30 days' })
+ .click();
await expect(page).toHaveURL(/range=30d/);
await page.reload();
await expect(
- page.getByRole('button', { name: 'Last 30 days' })
+ page.getByRole('button', { name: 'Last 30 days', exact: true })
).toBeVisible({ timeout: 30_000 });
await expect(page.getByText('E2E reports opens')).toBeVisible({
timeout: 30_000,
diff --git a/apps/start/e2e/verify-b-dashboard-range.spec.ts b/apps/start/e2e/verify-b-dashboard-range.spec.ts
index 47be9a66a..170cebf88 100644
--- a/apps/start/e2e/verify-b-dashboard-range.spec.ts
+++ b/apps/start/e2e/verify-b-dashboard-range.spec.ts
@@ -79,7 +79,10 @@ test('a dashboard card uses the range and interval saved on its report', async (
await page
.getByRole('button', { name: 'Last 7 days', exact: true })
.click();
- await page.getByRole('menuitem', { name: /^Last 6 months/ }).click();
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^Last 6 months/ })
+ .click();
await expect.poll(() => rangeCookie(page)).toContain('6m');
calls.length = 0;
await page.goto(`/acme/${SHOP}/dashboards/${dashboard.id}`);
diff --git a/apps/start/e2e/verify-b-range-edges.spec.ts b/apps/start/e2e/verify-b-range-edges.spec.ts
index 6265ff15e..2bb128f93 100644
--- a/apps/start/e2e/verify-b-range-edges.spec.ts
+++ b/apps/start/e2e/verify-b-range-edges.spec.ts
@@ -42,7 +42,7 @@ test('report builder ranges: bucket counts at the edges', async ({ page }) => {
await closeSidebar(page);
const pickRange = (current: string, next: RegExp) => async () => {
await page.getByRole('button', { name: current, exact: true }).click();
- await page.getByRole('menuitem', { name: next }).click();
+ await page.getByRole('dialog').getByRole('button', { name: next }).click();
};
const month = await bucketsAfter(page, async () => {
await addEvent(page, 'screen_view');
diff --git a/apps/start/e2e/verify-b-share.spec.ts b/apps/start/e2e/verify-b-share.spec.ts
index 0cc97c72d..0f78b61ca 100644
--- a/apps/start/e2e/verify-b-share.spec.ts
+++ b/apps/start/e2e/verify-b-share.spec.ts
@@ -271,7 +271,10 @@ test('range and interval controls on a shared dashboard drive the chart queries'
await visitor.page
.getByRole('button', { name: 'Last 7 days', exact: true })
.click();
- await visitor.page.getByRole('menuitem', { name: /^Last 30 days/ }).click();
+ await visitor.page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^Last 30 days/ })
+ .click();
await expect
.poll(() =>
chartRequests.some((r) => r.range === '30d' && r.status === 200)
diff --git a/apps/start/src/components/overview/overview-range.tsx b/apps/start/src/components/overview/overview-range.tsx
index ee1c64537..4a1dc8980 100644
--- a/apps/start/src/components/overview/overview-range.tsx
+++ b/apps/start/src/components/overview/overview-range.tsx
@@ -9,12 +9,14 @@ export function OverviewRange() {
setEndDate,
endDate,
startDate,
+ interval,
setInterval,
} = useOverviewOptions();
return (
<TimeWindowPicker
endDate={endDate}
+ interval={interval}
onChange={setRange}
onEndDateChange={setEndDate}
onIntervalChange={setInterval}
diff --git a/apps/start/src/components/report-chart/report-editor.tsx b/apps/start/src/components/report-chart/report-editor.tsx
index f82a4ec68..de3e21deb 100644
--- a/apps/start/src/components/report-chart/report-editor.tsx
+++ b/apps/start/src/components/report-chart/report-editor.tsx
@@ -93,6 +93,7 @@ export default function ReportEditor({
<TimeWindowPicker
className={TOOLBAR_TRIGGER_CLASS}
endDate={report.endDate}
+ interval={report.interval}
onChange={(value) => {
dispatch(changeDateRanges(value));
}}
diff --git a/apps/start/src/components/time-window-picker.tsx b/apps/start/src/components/time-window-picker.tsx
index 306fda859..9765fcb0b 100644
--- a/apps/start/src/components/time-window-picker.tsx
+++ b/apps/start/src/components/time-window-picker.tsx
@@ -7,24 +7,42 @@ import {
timeWindows,
} from '@openpanel/core/modules/report/report.constants';
import { bind } from 'bind-event-listener';
-import { addDays, endOfDay, format, startOfDay, subDays } from 'date-fns';
-import { CalendarIcon } from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { endOfDay, isSameDay, startOfDay, subDays, subMonths } from 'date-fns';
+import { CalendarIcon, ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import type { DateRange } from 'react-day-picker';
import { Button, type ButtonProps } from '@/components/ui/button';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuShortcut,
- DropdownMenuTrigger,
-} from '@/components/ui/dropdown-menu';
+import { Calendar } from '@/components/ui/calendar';
import { InputEnter } from '@/components/ui/input-enter';
-import { pushModal, useOnPushModal } from '@/modals';
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@/components/ui/popover';
+import { useBreakpoint } from '@/hooks/use-breakpoint';
import { cn } from '@/utils/cn';
+import { formatDate, formatDateTime } from '@/utils/date';
import { shouldIgnoreKeypress } from '@/utils/should-ignore-keypress';
+import {
+ canStepTimeWindow,
+ formatTimeWindowBoundary,
+ resolveTimeWindow,
+ type StepDirection,
+ stepTimeWindow,
+ type TimeWindowBounds,
+} from '@/utils/time-window';
+
+const MAX_CUSTOM_DAYS = 365;
+const DESKTOP_MONTHS = 2;
+const MOBILE_MONTHS = 1;
+const COLLISION_PADDING = 16;
+
+const PRESET_GROUPS: IChartRange[][] = [
+ ['30min', 'lastHour', 'last24h'],
+ ['today', 'yesterday', '7d', '30d'],
+ ['3m', '6m', '12m'],
+ ['monthToDate', 'lastMonth', 'yearToDate', 'lastYear'],
+];
interface Props {
value: IChartRange;
@@ -32,12 +50,25 @@ interface Props {
onStartDateChange: (date: string) => void;
onEndDateChange: (date: string) => void;
onIntervalChange: (interval: IInterval) => void;
+ /** The interval in effect; stepping keeps it since the window length does not change. */
+ interval?: IInterval | null;
endDate: string | null;
startDate: string | null;
className?: string;
variant?: ButtonProps['variant'];
size?: ButtonProps['size'];
}
+
+function formatWindowLabel(bounds: TimeWindowBounds): string {
+ if (bounds.unit === 'minute') {
+ return `${formatDateTime(bounds.start)} – ${formatDateTime(bounds.end)}`;
+ }
+ if (isSameDay(bounds.start, bounds.end)) {
+ return formatDate(bounds.start);
+ }
+ return `${formatDate(bounds.start)} – ${formatDate(bounds.end)}`;
+}
+
export function TimeWindowPicker({
value,
onChange,
@@ -46,55 +77,101 @@ export function TimeWindowPicker({
endDate,
onEndDateChange,
onIntervalChange,
+ interval,
className,
variant = 'outline',
size,
}: Props) {
- const isDateRangerPickerOpen = useRef(false);
- useOnPushModal('DateRangerPicker', (open) => {
- isDateRangerPickerOpen.current = open;
- });
- const timeWindow = timeWindows[value ?? '30d'];
+ const { isBelowSm } = useBreakpoint('sm');
const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState<DateRange | undefined>();
const [customDaysKey, setCustomDaysKey] = useState(0);
- const handleCustomDays = useCallback(
+ const isCustom = value === 'custom';
+ const bounds = useMemo(
+ () => resolveTimeWindow(value, startDate, endDate),
+ [value, startDate, endDate]
+ );
+ const triggerLabel = isCustom
+ ? formatWindowLabel(bounds)
+ : timeWindows[value]?.label;
+
+ const applyBounds = useCallback(
+ (next: TimeWindowBounds, nextInterval: IInterval | null | undefined) => {
+ onStartDateChange(formatTimeWindowBoundary(next.start));
+ onEndDateChange(formatTimeWindowBoundary(next.end));
+ onChange('custom');
+ const resolvedInterval =
+ nextInterval ??
+ getDefaultIntervalByDates(
+ next.start.toISOString(),
+ next.end.toISOString()
+ );
+ if (resolvedInterval) {
+ onIntervalChange(resolvedInterval);
+ }
+ },
+ [onChange, onStartDateChange, onEndDateChange, onIntervalChange]
+ );
+
+ // Radix only reports its own dismissals, so every close path drops the draft here.
+ const close = useCallback(() => {
+ setDraft(undefined);
+ setOpen(false);
+ }, []);
+
+ const selectPreset = useCallback(
+ (range: IChartRange) => {
+ onChange(range);
+ close();
+ },
+ [onChange, close]
+ );
+
+ const applyDraft = useCallback(() => {
+ if (!(draft?.from && draft.to)) {
+ return;
+ }
+ applyBounds(
+ {
+ start: startOfDay(draft.from),
+ end: endOfDay(draft.to),
+ unit: 'day',
+ size: 0,
+ },
+ null
+ );
+ close();
+ }, [draft, applyBounds, close]);
+
+ const applyCustomDays = useCallback(
(raw: string) => {
const days = Number(raw);
- if (!Number.isInteger(days) || days < 1 || days > 365) {
+ if (!Number.isInteger(days) || days < 1 || days > MAX_CUSTOM_DAYS) {
return;
}
const now = new Date();
- const start = startOfDay(subDays(now, days - 1));
- const end = startOfDay(addDays(now, 1));
- onStartDateChange(format(start, 'yyyy-MM-dd HH:mm:ss'));
- onEndDateChange(format(end, 'yyyy-MM-dd HH:mm:ss'));
- onChange('custom');
- const interval = getDefaultIntervalByDates(
- start.toISOString(),
- end.toISOString()
+ applyBounds(
+ {
+ start: startOfDay(subDays(now, days - 1)),
+ end: endOfDay(now),
+ unit: 'day',
+ size: days,
+ },
+ null
);
- if (interval) {
- onIntervalChange(interval);
- }
- setCustomDaysKey((k) => k + 1);
- setOpen(false);
+ setCustomDaysKey((key) => key + 1);
+ close();
},
- [onChange, onStartDateChange, onEndDateChange, onIntervalChange]
+ [applyBounds, close]
);
- const handleCustom = useCallback(() => {
- pushModal('DateRangerPicker', {
- onChange: ({ startDate, endDate, interval }) => {
- onStartDateChange(format(startOfDay(startDate), 'yyyy-MM-dd HH:mm:ss'));
- onEndDateChange(format(endOfDay(endDate), 'yyyy-MM-dd HH:mm:ss'));
- onChange('custom');
- onIntervalChange(interval);
- },
- startDate: startDate ? new Date(startDate) : undefined,
- endDate: endDate ? new Date(endDate) : undefined,
- });
- }, [startDate, endDate]);
+ const step = useCallback(
+ (direction: StepDirection) => {
+ applyBounds(stepTimeWindow(bounds, direction), interval);
+ },
+ [bounds, interval, applyBounds]
+ );
useEffect(() => {
return bind(document, {
@@ -103,181 +180,175 @@ export function TimeWindowPicker({
if (shouldIgnoreKeypress(event)) {
return;
}
-
- if (isDateRangerPickerOpen.current) {
- return;
- }
-
const match = Object.values(timeWindows).find(
- (tw) => event.key === tw.shortcut.toLowerCase()
+ (window) => event.key === window.shortcut.toLowerCase()
);
- if (match?.key === 'custom') {
- handleCustom();
- } else if (match) {
- onChange(match.key);
+ if (!match) {
+ return;
+ }
+ if (match.key === 'custom') {
+ setOpen(true);
+ return;
}
+ selectPreset(match.key);
},
});
- }, [handleCustom]);
+ }, [selectPreset]);
+
+ const selectedRange: DateRange | undefined = draft ?? {
+ from: bounds.start,
+ to: bounds.end,
+ };
+ const canApply = Boolean(draft?.from && draft?.to);
+ const canStepNext = canStepTimeWindow(bounds, 'next');
+ const stepperSize = size === 'sm' ? 'sm' : 'default';
return (
- <DropdownMenu onOpenChange={setOpen} open={open}>
- <DropdownMenuTrigger asChild>
+ <div className="flex items-center gap-1">
+ <Popover
+ onOpenChange={(nextOpen) => (nextOpen ? setOpen(true) : close())}
+ open={open}
+ >
+ <PopoverTrigger asChild>
+ <Button
+ className={cn('justify-start', className)}
+ icon={CalendarIcon}
+ size={size}
+ variant={variant}
+ >
+ {triggerLabel}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ className="max-h-(--radix-popover-content-available-height) w-auto max-w-[calc(100vw-2rem)] overflow-y-auto p-0"
+ collisionPadding={COLLISION_PADDING}
+ portal
+ >
+ <div className="flex flex-col sm:flex-row">
+ <div className="col gap-2 border-b p-2 sm:w-44 sm:border-r sm:border-b-0">
+ <div className="flex items-center gap-2 px-2 pt-1">
+ <span className="text-muted-foreground text-sm">Last</span>
+ <InputEnter
+ aria-label="Number of days"
+ className="h-7 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
+ inputMode="numeric"
+ key={customDaysKey}
+ max={MAX_CUSTOM_DAYS}
+ min={1}
+ onChangeValue={applyCustomDays}
+ placeholder="N"
+ step={1}
+ type="number"
+ value=""
+ />
+ <span className="text-muted-foreground text-sm">days</span>
+ </div>
+ <div className="grid grid-cols-2 gap-x-2 gap-y-1.5 sm:flex sm:flex-col">
+ {PRESET_GROUPS.map((group) => (
+ <div className="col" key={group[0]}>
+ {group.map((range) => {
+ const preset = timeWindows[range];
+ const isActive = value === range;
+ return (
+ <button
+ className={cn(
+ 'flex h-7 items-center justify-between rounded-md px-2 text-left text-sm hover:bg-accent hover:text-accent-foreground',
+ isActive && 'bg-accent font-medium'
+ )}
+ key={range}
+ onClick={() => selectPreset(range)}
+ type="button"
+ >
+ <span>{preset.label}</span>
+ <kbd
+ aria-hidden
+ className="hidden rounded border border-border bg-def-200 px-1 font-mono text-2xs text-muted-foreground sm:inline"
+ >
+ {preset.shortcut}
+ </kbd>
+ </button>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="col justify-between gap-3 p-3">
+ <Calendar
+ captionLayout="dropdown"
+ className="p-0"
+ defaultMonth={subMonths(
+ bounds.start,
+ isBelowSm ? 0 : DESKTOP_MONTHS - 1
+ )}
+ disabled={{ after: endOfDay(new Date()) }}
+ mode="range"
+ numberOfMonths={isBelowSm ? MOBILE_MONTHS : DESKTOP_MONTHS}
+ onSelect={(range, day) => {
+ // The current window is shown for orientation; the first
+ // click starts a new pick instead of stretching it.
+ setDraft(draft ? range : { from: day, to: undefined });
+ }}
+ selected={selectedRange}
+ />
+ <div className="flex items-center justify-between gap-4 border-t pt-3">
+ <span className="text-muted-foreground text-sm">
+ {draft?.from
+ ? formatWindowLabel({
+ start: draft.from,
+ end: draft.to ?? draft.from,
+ unit: 'day',
+ size: 0,
+ })
+ : formatWindowLabel(bounds)}
+ </span>
+ <div className="flex gap-2">
+ <Button
+ onClick={close}
+ size="sm"
+ type="button"
+ variant="outline"
+ >
+ Cancel
+ </Button>
+ <Button
+ disabled={!canApply}
+ onClick={applyDraft}
+ size="sm"
+ type="button"
+ >
+ Apply
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ <div className="flex items-center">
<Button
- className={cn('justify-start', className)}
- icon={CalendarIcon}
- size={size}
+ aria-label="Previous period"
+ className={cn(className, 'rounded-r-none px-2')}
+ onClick={() => step('previous')}
+ size={stepperSize}
+ type="button"
variant={variant}
>
- {timeWindow?.label}
+ <ChevronLeftIcon className="size-4" />
</Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent className="w-56">
- <DropdownMenuLabel>Time window</DropdownMenuLabel>
- <DropdownMenuSeparator />
-
- <DropdownMenuGroup>
- <DropdownMenuItem onClick={() => onChange(timeWindows['30min'].key)}>
- {timeWindows['30min'].label}
- <DropdownMenuShortcut>
- {timeWindows['30min'].shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows.lastHour.key)}>
- {timeWindows.lastHour.label}
- <DropdownMenuShortcut>
- {timeWindows.lastHour.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows.last24h.key)}>
- {timeWindows.last24h.label}
- <DropdownMenuShortcut>
- {timeWindows.last24h.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows.today.key)}>
- {timeWindows.today.label}
- <DropdownMenuShortcut>
- {timeWindows.today.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows.yesterday.key)}>
- {timeWindows.yesterday.label}
- <DropdownMenuShortcut>
- {timeWindows.yesterday.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- </DropdownMenuGroup>
-
- <DropdownMenuSeparator />
-
- <DropdownMenuGroup>
- <DropdownMenuItem onClick={() => onChange(timeWindows['7d'].key)}>
- {timeWindows['7d'].label}
- <DropdownMenuShortcut>
- {timeWindows['7d'].shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows['30d'].key)}>
- {timeWindows['30d'].label}
- <DropdownMenuShortcut>
- {timeWindows['30d'].shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows['3m'].key)}>
- {timeWindows['3m'].label}
- <DropdownMenuShortcut>
- {timeWindows['3m'].shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows['6m'].key)}>
- {timeWindows['6m'].label}
- <DropdownMenuShortcut>
- {timeWindows['6m'].shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows['12m'].key)}>
- {timeWindows['12m'].label}
- <DropdownMenuShortcut>
- {timeWindows['12m'].shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- </DropdownMenuGroup>
-
- <DropdownMenuSeparator />
-
- <DropdownMenuGroup>
- <DropdownMenuItem
- onClick={() => onChange(timeWindows.monthToDate.key)}
- >
- {timeWindows.monthToDate.label}
- <DropdownMenuShortcut>
- {timeWindows.monthToDate.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows.lastMonth.key)}>
- {timeWindows.lastMonth.label}
- <DropdownMenuShortcut>
- {timeWindows.lastMonth.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- </DropdownMenuGroup>
-
- <DropdownMenuSeparator />
-
- <DropdownMenuGroup>
- <DropdownMenuItem
- onClick={() => onChange(timeWindows.yearToDate.key)}
- >
- {timeWindows.yearToDate.label}
- <DropdownMenuShortcut>
- {timeWindows.yearToDate.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => onChange(timeWindows.lastYear.key)}>
- {timeWindows.lastYear.label}
- <DropdownMenuShortcut>
- {timeWindows.lastYear.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- </DropdownMenuGroup>
-
- <DropdownMenuSeparator />
-
- <DropdownMenuGroup>
- {/** biome-ignore lint/a11y/noNoninteractiveElementInteractions: none */}
- {/** biome-ignore lint/a11y/noStaticElementInteractions: none */}
- <div
- className="flex items-center gap-4 rounded-sm px-2 py-1.5"
- onClick={(e) => e.stopPropagation()}
- onKeyDown={(e) => e.stopPropagation()}
- >
- <span className="whitespace-nowrap">Last days</span>
- <InputEnter
- aria-label="Number of days for custom date filter"
- className="h-7 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
- inputMode="numeric"
- key={customDaysKey}
- max={365}
- min={1}
- onChangeValue={handleCustomDays}
- placeholder="X days"
- step={1}
- type="number"
- value=""
- />
- </div>
- </DropdownMenuGroup>
- <DropdownMenuSeparator />
- <DropdownMenuGroup>
- <DropdownMenuItem onClick={() => handleCustom()}>
- {timeWindows.custom.label}
- <DropdownMenuShortcut>
- {timeWindows.custom.shortcut}
- </DropdownMenuShortcut>
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
+ <Button
+ aria-label="Next period"
+ className={cn(className, '-ml-px rounded-l-none px-2')}
+ disabled={!canStepNext}
+ onClick={() => step('next')}
+ size={stepperSize}
+ type="button"
+ variant={variant}
+ >
+ <ChevronRightIcon className="size-4" />
+ </Button>
+ </div>
+ </div>
);
}
diff --git a/apps/start/src/utils/time-window.test.ts b/apps/start/src/utils/time-window.test.ts
new file mode 100644
index 000000000..82a676eb3
--- /dev/null
+++ b/apps/start/src/utils/time-window.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from 'vitest';
+import {
+ canStepTimeWindow,
+ formatTimeWindowBoundary,
+ resolveTimeWindow,
+ stepTimeWindow,
+} from './time-window';
+
+const now = new Date(2026, 9, 23, 14, 30, 0);
+const boundary = (date: Date) => formatTimeWindowBoundary(date);
+
+describe('resolveTimeWindow', () => {
+ it('resolves "today" to the whole current day', () => {
+ const bounds = resolveTimeWindow('today', null, null, now);
+ expect(boundary(bounds.start)).toBe('2026-10-23 00:00:00');
+ expect(boundary(bounds.end)).toBe('2026-10-23 23:59:59');
+ expect(bounds).toMatchObject({ unit: 'day', size: 1 });
+ });
+
+ it('resolves "7d" the way the API does: eight calendar days', () => {
+ const bounds = resolveTimeWindow('7d', null, null, now);
+ expect(boundary(bounds.start)).toBe('2026-10-16 00:00:00');
+ expect(bounds).toMatchObject({ unit: 'day', size: 8 });
+ });
+
+ it('resolves "lastMonth" to a month-aligned window', () => {
+ const bounds = resolveTimeWindow('lastMonth', null, null, now);
+ expect(boundary(bounds.start)).toBe('2026-09-01 00:00:00');
+ expect(boundary(bounds.end)).toBe('2026-09-30 23:59:59');
+ expect(bounds).toMatchObject({ unit: 'month', size: 1 });
+ });
+
+ it('prefers explicit dates over the range key', () => {
+ const bounds = resolveTimeWindow(
+ '30d',
+ '2026-10-10 00:00:00',
+ '2026-10-16 23:59:59',
+ now
+ );
+ expect(bounds).toMatchObject({ unit: 'day', size: 7 });
+ });
+
+ it('treats an exclusive midnight end as the previous whole day', () => {
+ const bounds = resolveTimeWindow(
+ 'custom',
+ '2026-10-10 00:00:00',
+ '2026-10-24 00:00:00',
+ now
+ );
+ expect(boundary(bounds.end)).toBe('2026-10-23 23:59:59');
+ expect(bounds).toMatchObject({ unit: 'day', size: 14 });
+ });
+
+ it('recognises whole months in custom dates', () => {
+ const bounds = resolveTimeWindow(
+ 'custom',
+ '2026-08-01 00:00:00',
+ '2026-09-30 23:59:59',
+ now
+ );
+ expect(bounds).toMatchObject({ unit: 'month', size: 2 });
+ });
+
+ it('keeps sub-day custom dates as a minute window', () => {
+ const bounds = resolveTimeWindow(
+ 'custom',
+ '2026-10-23 14:00:00',
+ '2026-10-23 14:30:00',
+ now
+ );
+ expect(bounds).toMatchObject({ unit: 'minute', size: 30 });
+ });
+});
+
+describe('stepTimeWindow', () => {
+ it('moves a day window back by its own length without overlap', () => {
+ const bounds = resolveTimeWindow(
+ 'custom',
+ '2026-10-17 00:00:00',
+ '2026-10-23 23:59:59',
+ now
+ );
+ const previous = stepTimeWindow(bounds, 'previous');
+ expect(boundary(previous.start)).toBe('2026-10-10 00:00:00');
+ expect(boundary(previous.end)).toBe('2026-10-16 23:59:59');
+ const next = stepTimeWindow(previous, 'next');
+ expect(boundary(next.start)).toBe('2026-10-17 00:00:00');
+ expect(boundary(next.end)).toBe('2026-10-23 23:59:59');
+ });
+
+ it('steps "last month" to the full month before it', () => {
+ const bounds = resolveTimeWindow('lastMonth', null, null, now);
+ const previous = stepTimeWindow(bounds, 'previous');
+ expect(boundary(previous.start)).toBe('2026-08-01 00:00:00');
+ expect(boundary(previous.end)).toBe('2026-08-31 23:59:59');
+ });
+
+ it('steps "last year" to the full year before it', () => {
+ const bounds = resolveTimeWindow('lastYear', null, null, now);
+ const previous = stepTimeWindow(bounds, 'previous');
+ expect(boundary(previous.start)).toBe('2024-01-01 00:00:00');
+ expect(boundary(previous.end)).toBe('2024-12-31 23:59:59');
+ });
+
+ it('steps a minute window by its duration', () => {
+ const bounds = resolveTimeWindow('30min', null, null, now);
+ const previous = stepTimeWindow(bounds, 'previous');
+ expect(boundary(previous.start)).toBe('2026-10-23 13:30:00');
+ expect(boundary(previous.end)).toBe('2026-10-23 14:00:00');
+ });
+});
+
+describe('canStepTimeWindow', () => {
+ it('always allows stepping back', () => {
+ const bounds = resolveTimeWindow('today', null, null, now);
+ expect(canStepTimeWindow(bounds, 'previous', now)).toBe(true);
+ });
+
+ it('refuses to step into a window that starts in the future', () => {
+ const bounds = resolveTimeWindow('today', null, null, now);
+ expect(canStepTimeWindow(bounds, 'next', now)).toBe(false);
+ const yesterday = resolveTimeWindow('yesterday', null, null, now);
+ expect(canStepTimeWindow(yesterday, 'next', now)).toBe(true);
+ });
+});
diff --git a/apps/start/src/utils/time-window.ts b/apps/start/src/utils/time-window.ts
new file mode 100644
index 000000000..7df21816f
--- /dev/null
+++ b/apps/start/src/utils/time-window.ts
@@ -0,0 +1,239 @@
+import type { IChartRange } from '@openpanel/core/modules/report/report.constants';
+import {
+ addDays,
+ addMonths,
+ addYears,
+ differenceInCalendarDays,
+ differenceInCalendarMonths,
+ endOfDay,
+ endOfMonth,
+ endOfYear,
+ format,
+ isSameDay,
+ parseISO,
+ startOfDay,
+ startOfMonth,
+ startOfYear,
+ subDays,
+ subMonths,
+ subYears,
+} from 'date-fns';
+
+export const DATE_TIME_FORMAT = 'yyyy-MM-dd HH:mm:ss';
+
+const MINUTES_30 = 30;
+const MINUTES_60 = 60;
+const MINUTES_24H = 24 * 60;
+
+/**
+ * The concrete window a range stands for, in the browser's timezone, and the
+ * calendar unit it is counted in. `size` is how many units the window spans,
+ * which is how far a step moves it.
+ */
+export interface TimeWindowBounds {
+ start: Date;
+ end: Date;
+ unit: 'minute' | 'day' | 'month' | 'year';
+ size: number;
+}
+
+export type StepDirection = 'previous' | 'next';
+
+function minuteWindow(now: Date, minutes: number): TimeWindowBounds {
+ return {
+ start: new Date(now.getTime() - minutes * 60_000),
+ end: now,
+ unit: 'minute',
+ size: minutes,
+ };
+}
+
+function dayWindow(start: Date, end: Date): TimeWindowBounds {
+ return {
+ start: startOfDay(start),
+ end: endOfDay(end),
+ unit: 'day',
+ size: differenceInCalendarDays(end, start) + 1,
+ };
+}
+
+function isStartOfDay(date: Date): boolean {
+ return date.getTime() === startOfDay(date).getTime();
+}
+
+// Stored boundaries carry whole seconds, so compare without milliseconds.
+function isEndOfDay(date: Date): boolean {
+ return format(date, 'HH:mm:ss') === '23:59:59';
+}
+
+function boundsFromCustomDates(start: Date, rawEnd: Date): TimeWindowBounds {
+ // An exclusive midnight end ("2026-10-24 00:00:00") means the whole previous day.
+ const endsAtMidnight = isStartOfDay(rawEnd) && !isSameDay(start, rawEnd);
+ const end = endsAtMidnight ? endOfDay(subDays(rawEnd, 1)) : rawEnd;
+
+ const isWholeDays = isStartOfDay(start) && isEndOfDay(end);
+ if (!isWholeDays) {
+ const minutes = Math.round((end.getTime() - start.getTime()) / 60_000);
+ return { start, end, unit: 'minute', size: Math.max(minutes, 1) };
+ }
+
+ const isWholeMonths =
+ isSameDay(start, startOfMonth(start)) && isSameDay(end, endOfMonth(end));
+ if (isWholeMonths) {
+ return {
+ start,
+ end,
+ unit: 'month',
+ size: differenceInCalendarMonths(end, start) + 1,
+ };
+ }
+
+ return dayWindow(start, end);
+}
+
+/**
+ * Mirrors `getDatesFromRange` in `packages/core` for the browser, so the
+ * trigger can show real dates and the stepper can move from what is on screen.
+ */
+export function resolveTimeWindow(
+ range: IChartRange,
+ startDate: string | null | undefined,
+ endDate: string | null | undefined,
+ now = new Date()
+): TimeWindowBounds {
+ if (startDate && endDate) {
+ return boundsFromCustomDates(parseISO(startDate), parseISO(endDate));
+ }
+
+ switch (range) {
+ case '30min':
+ return minuteWindow(now, MINUTES_30);
+ case 'lastHour':
+ return minuteWindow(now, MINUTES_60);
+ case 'last24h':
+ return minuteWindow(now, MINUTES_24H);
+ case 'today':
+ return dayWindow(now, now);
+ case 'yesterday': {
+ const yesterday = subDays(now, 1);
+ return dayWindow(yesterday, yesterday);
+ }
+ case '7d':
+ return dayWindow(subDays(now, 7), now);
+ case '3m':
+ return {
+ start: startOfDay(subMonths(now, 3)),
+ end: endOfDay(now),
+ unit: 'month',
+ size: 3,
+ };
+ case '6m':
+ return {
+ start: startOfDay(subMonths(now, 6)),
+ end: endOfDay(now),
+ unit: 'month',
+ size: 6,
+ };
+ case '12m': {
+ const start = startOfMonth(subMonths(now, 12));
+ const end = endOfMonth(now);
+ return {
+ start,
+ end,
+ unit: 'month',
+ size: differenceInCalendarMonths(end, start) + 1,
+ };
+ }
+ case 'monthToDate':
+ return {
+ start: startOfMonth(now),
+ end: endOfDay(now),
+ unit: 'month',
+ size: 1,
+ };
+ case 'lastMonth': {
+ const month = subMonths(now, 1);
+ return {
+ start: startOfMonth(month),
+ end: endOfMonth(month),
+ unit: 'month',
+ size: 1,
+ };
+ }
+ case 'yearToDate':
+ return {
+ start: startOfYear(now),
+ end: endOfDay(now),
+ unit: 'year',
+ size: 1,
+ };
+ case 'lastYear': {
+ const year = subYears(now, 1);
+ return {
+ start: startOfYear(year),
+ end: endOfYear(year),
+ unit: 'year',
+ size: 1,
+ };
+ }
+ default:
+ return dayWindow(subDays(now, 30), now);
+ }
+}
+
+function shiftDate(
+ date: Date,
+ unit: TimeWindowBounds['unit'],
+ amount: number
+): Date {
+ switch (unit) {
+ case 'minute':
+ return new Date(date.getTime() + amount * 60_000);
+ case 'day':
+ return addDays(date, amount);
+ case 'month':
+ return addMonths(date, amount);
+ default:
+ return addYears(date, amount);
+ }
+}
+
+/**
+ * Moves the window one whole length back or forward. A month- or year-aligned
+ * end stays pinned to the end of its month/year so "last month" steps to a
+ * full month, not to a month minus a day.
+ */
+export function stepTimeWindow(
+ bounds: TimeWindowBounds,
+ direction: StepDirection
+): TimeWindowBounds {
+ const amount = direction === 'next' ? bounds.size : -bounds.size;
+ const start = shiftDate(bounds.start, bounds.unit, amount);
+ let end = shiftDate(bounds.end, bounds.unit, amount);
+ if (
+ bounds.unit === 'month' &&
+ isSameDay(bounds.end, endOfMonth(bounds.end))
+ ) {
+ end = endOfMonth(end);
+ }
+ if (bounds.unit === 'year' && isSameDay(bounds.end, endOfYear(bounds.end))) {
+ end = endOfYear(end);
+ }
+ return { ...bounds, start, end };
+}
+
+/** A window that starts after now has no data yet, so there is nothing to step to. */
+export function canStepTimeWindow(
+ bounds: TimeWindowBounds,
+ direction: StepDirection,
+ now = new Date()
+): boolean {
+ if (direction === 'previous') {
+ return true;
+ }
+ return stepTimeWindow(bounds, direction).start.getTime() <= now.getTime();
+}
+
+export function formatTimeWindowBoundary(date: Date): string {
+ return format(date, DATE_TIME_FORMAT);
+}