πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feat(date-selector): preset hotkeys, ten-preset rail, typed windows (#1167)
Goldflag7c14af47bf45
diff --git a/client/messages/en.json b/client/messages/en.jsonindex 3c08b174e..b1bca379c 100644--- a/client/messages/en.json+++ b/client/messages/en.json@@ -1826,5 +1826,11 @@"zwhI6a": "No conversion event code is needed for this goal. Rybbit tracks it automatically based on user behavior.","zxvhnE": "Daily","zyQ3nw": "Add Another Property",- "zz0om1": "IP Exclusions"+ "zz0om1": "IP Exclusions",+ "DDyIYi": "Search, or type 14d, 6h",+ "q5g+LV": "Last {count} β¦",+ "UG2tSi": "Last {count, plural, one {# minute} other {# minutes}}",+ "hq3XcK": "Last {count, plural, one {# hour} other {# hours}}",+ "lYB+ft": "Last {count, plural, one {# day} other {# days}}",+ "QyVOhk": "Last {count, plural, one {# week} other {# weeks}}"}diff --git a/client/src/components/DateSelector/DateSelector.test.tsx b/client/src/components/DateSelector/DateSelector.test.tsxindex edab6b30d..020c213aa 100644--- a/client/src/components/DateSelector/DateSelector.test.tsx+++ b/client/src/components/DateSelector/DateSelector.test.tsx@@ -1,4 +1,5 @@import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { DateTime } from "luxon";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { DateSelector } from "./DateSelector";@@ -7,8 +8,14 @@ import { Time } from "./types";const mocks = vi.hoisted(() => ({ timezone: "America/New_York", setTimezone: vi.fn(), setComparison: vi.fn() }));vi.mock("next-intl", () => ({- useExtracted: () => (message: string, values?: Record<string, string>) =>- values ? message.replace(/\{(\w+)\}/g, (_, key) => values[key] ?? `{${key}}`) : message,+ useExtracted: () => (message: string, values?: Record<string, string | number>) =>+ values+ ? message+ .replace(/\{(\w+), plural, one \{([^}]*)\} other \{([^}]*)\}\}/g, (_, key, one, other) =>+ String(values[key] === 1 ? one : other).replace("#", String(values[key]))+ )+ .replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? `{${key}}`))+ : message,}));vi.mock("@/lib/store", () => ({@@ -109,10 +116,10 @@ describe("DateSelector", () => {render(<DateSelector time={{ mode: "range", startDate: "2024-03-08", endDate: "2024-03-14" }} setTime={setTime} />);fireEvent.click(screen.getByRole("button", { name: /Mar 8/ }));- expect(screen.getByPlaceholderText("Search ranges")).toBeTruthy();+ expect(screen.getByPlaceholderText(/Search/)).toBeTruthy();fireEvent.click(screen.getByRole("button", { name: "Cancel" }));- expect(screen.queryByPlaceholderText("Search ranges")).toBeNull();+ expect(screen.queryByPlaceholderText(/Search/)).toBeNull();});it("hides the realtime presets when a caller disables them", () => {@@ -129,3 +136,107 @@ describe("DateSelector", () => {expect(screen.getByText("Today")).toBeTruthy();});});++describe("DateSelector realtime label", () => {+ it("keeps the minutes of a window that is not a whole number of hours", () => {+ render(<DateSelector time={{ mode: "past-minutes", pastMinutesStart: 90, pastMinutesEnd: 0 }} setTime={setTime} />);+ expect(screen.getByRole("button", { name: /Last 90 minutes/ })).toBeTruthy();+ });++ it("names whole hours as hours", () => {+ render(+ <DateSelector time={{ mode: "past-minutes", pastMinutesStart: 120, pastMinutesEnd: 0 }} setTime={setTime} />+ );+ expect(screen.getByRole("button", { name: /Last 2 hours/ })).toBeTruthy();+ });+});++describe("DateSelector hotkeys", () => {+ const range: Time = { mode: "range", startDate: "2024-03-08", endDate: "2024-03-14" };++ it("applies a preset from a single key", () => {+ render(<DateSelector time={range} setTime={setTime} />);++ fireEvent.keyDown(document.body, { key: "w" });++ expect(setTime).toHaveBeenCalledTimes(1);+ expect(setTime.mock.calls[0][0]).toMatchObject({ wellKnown: "last-7-days" });+ expect(localStorage.getItem("rybbit-default-time-range")).toBe("last-7-days");+ });++ it("opens the panel on c", () => {+ render(<DateSelector time={range} setTime={setTime} />);++ fireEvent.keyDown(document.body, { key: "c" });++ expect(screen.getByPlaceholderText(/Search/)).toBeTruthy();+ expect(setTime).not.toHaveBeenCalled();+ });++ it("stays out of the way while typing or chording", () => {+ render(+ <>+ <input aria-label="Other field" />+ <DateSelector time={range} setTime={setTime} />+ </>+ );++ fireEvent.keyDown(screen.getByLabelText("Other field"), { key: "w" });+ fireEvent.keyDown(document.body, { key: "w", metaKey: true });+ fireEvent.keyDown(document.body, { key: "w", ctrlKey: true });++ expect(setTime).not.toHaveBeenCalled();+ });++ it("ignores realtime keys when a caller hides those presets", () => {+ render(<DateSelector time={range} setTime={setTime} pastMinutesEnabled={false} />);++ fireEvent.keyDown(document.body, { key: "r" });+ expect(setTime).not.toHaveBeenCalled();++ fireEvent.keyDown(document.body, { key: "d" });+ expect(setTime.mock.calls[0][0]).toMatchObject({ wellKnown: "today" });+ });++ it("lets the newest mounted selector keep the keys even after an older one re-renders", () => {+ const older = vi.fn();+ const newer = vi.fn();+ const { rerender } = render(+ <>+ <DateSelector time={range} setTime={older} />+ <DateSelector time={range} setTime={newer} />+ </>+ );++ // A fresh callback re-memoises the older selector's handlers; its stack+ // slot must not move above the newer selector's.+ const olderAgain = vi.fn();+ rerender(+ <>+ <DateSelector time={range} setTime={olderAgain} />+ <DateSelector time={range} setTime={newer} />+ </>+ );++ fireEvent.keyDown(document.body, { key: "w" });++ expect(newer).toHaveBeenCalledTimes(1);+ expect(older).not.toHaveBeenCalled();+ expect(olderAgain).not.toHaveBeenCalled();+ });++ it("can be switched off", () => {+ render(<DateSelector time={range} setTime={setTime} hotkeys={false} />);++ fireEvent.keyDown(document.body, { key: "w" });+ expect(setTime).not.toHaveBeenCalled();+ });++ it("shows the key beside each preset in the rail", () => {+ render(<DateSelector time={range} setTime={setTime} />);++ fireEvent.click(screen.getByRole("button", { name: /Mar 8/ }));++ expect(screen.getByText("Last 7 Days").parentElement?.textContent).toContain("w");+ });+});diff --git a/client/src/components/DateSelector/DateSelector.tsx b/client/src/components/DateSelector/DateSelector.tsxindex 1d3f0b606..247fac890 100644--- a/client/src/components/DateSelector/DateSelector.tsx+++ b/client/src/components/DateSelector/DateSelector.tsx@@ -3,15 +3,16 @@import { Button } from "@/components/ui/button";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { hour12 } from "@/lib/dateTimeUtils";-import { setStoredDashboardDefaultTimeRange } from "@/lib/defaultTimeRange";+import { getDashboardTimeForRange, setStoredDashboardDefaultTimeRange } from "@/lib/defaultTimeRange";import { useStore, useTimezone } from "@/lib/store";import { Calendar } from "lucide-react";import { DateTime } from "luxon";import { useExtracted } from "next-intl";-import { useState } from "react";+import { useMemo, useState } from "react";import { RangePanel } from "./RangePanel";-import { usePresetLabels } from "./presets";+import { PRESET_GROUPS, usePresetLabels } from "./presets";import { Time } from "./types";+import { useDatePresetHotkeys } from "./useDatePresetHotkeys";import { TimeBucket } from "@rybbit/shared";const stepDateTimeBucket = (dt: DateTime, bucket: TimeBucket, direction: 1 | -1): DateTime => {@@ -42,10 +43,13 @@ export function DateSelector({time,setTime: setSelectedTime,pastMinutesEnabled = true,+ hotkeys = true,}: {time: Time;setTime: (time: Time) => void;pastMinutesEnabled?: boolean;+ /** Single-key preset shortcuts (see `PRESET_HOTKEYS`). Off for selectors that live inside another form. */+ hotkeys?: boolean;}) {const { timezone, setTimezone, bucket, comparison, setComparison } = useStore();const zone = useTimezone();@@ -61,6 +65,25 @@ export function DateSelector({setSelectedTime(nextTime);};+ useDatePresetHotkeys(+ useMemo(+ () =>+ hotkeys+ ? {+ onPreset: preset => {+ setTime(getDashboardTimeForRange(preset, zone));+ setOpen(false);+ },+ onCustom: () => setOpen(true),+ enabled: preset =>+ pastMinutesEnabled || !PRESET_GROUPS.some(g => g.id === "realtime" && g.presets.includes(preset)),+ }+ : null,+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [hotkeys, zone, pastMinutesEnabled, setSelectedTime]+ )+ );+const getLabel = (time: Time) => {if (time.wellKnown) {return presetLabels[time.wellKnown];@@ -103,9 +126,10 @@ export function DateSelector({return `${startFormatted} - ${endFormatted}`;}- if (time.pastMinutesStart >= 60) {- const hours = Math.floor(time.pastMinutesStart / 60);- return t("Last {hours} hours", { hours: String(hours) });+ // Whole hours read as hours; a typed 90m keeps its minutes rather than+ // rounding down to "Last 1 hours".+ if (time.pastMinutesStart >= 60 && time.pastMinutesStart % 60 === 0) {+ return t("Last {hours} hours", { hours: String(time.pastMinutesStart / 60) });}return t("Last {minutes} minutes", { minutes: String(time.pastMinutesStart) });}diff --git a/client/src/components/DateSelector/RangePanel.test.tsx b/client/src/components/DateSelector/RangePanel.test.tsxindex ae833b5d1..f760ec507 100644--- a/client/src/components/DateSelector/RangePanel.test.tsx+++ b/client/src/components/DateSelector/RangePanel.test.tsx@@ -6,8 +6,14 @@ import { RangePanel } from "./RangePanel";import { Comparison, DEFAULT_COMPARISON, Time } from "./types";vi.mock("next-intl", () => ({- useExtracted: () => (message: string, values?: Record<string, string>) =>- values ? message.replace(/\{(\w+)\}/g, (_, key) => values[key] ?? `{${key}}`) : message,+ useExtracted: () => (message: string, values?: Record<string, string | number>) =>+ values+ ? message+ .replace(/\{(\w+), plural, one \{([^}]*)\} other \{([^}]*)\}\}/g, (_, key, one, other) =>+ String(values[key] === 1 ? one : other).replace("#", String(values[key]))+ )+ .replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? `{${key}}`))+ : message,}));const ZONE = "America/New_York";@@ -71,11 +77,13 @@ describe("RangePanel presets", () => {expect(container.querySelectorAll('[data-slot="command-separator"]').length).toBe(2);});- it("offers Last Week and Last Month, which had labels but no menu item before", () => {+ it("keeps the list to the ten presets people learn, not the seventeen they scanned", () => {renderPanel(DATE_RANGE);- expect(screen.getByText("Last Week")).toBeTruthy();- expect(screen.getByText("Last Month")).toBeTruthy();+ expect(within(screen.getAllByRole("listbox")[0]).getAllByRole("option").length).toBe(10);+ expect(screen.getByText("This Week")).toBeTruthy();+ expect(screen.queryByText("Last 14 Days")).toBeNull();+ expect(screen.queryByText("Last Week")).toBeNull();});it("applies a preset immediately β the fast path does not wait for Apply", () => {@@ -90,11 +98,18 @@ describe("RangePanel presets", () => {it("filters the list as you search", async () => {renderPanel(DATE_RANGE);- fireEvent.change(screen.getByPlaceholderText("Search ranges"), { target: { value: "week" } });+ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: "week" } });await waitFor(() => expect(screen.queryByText("Last 30 Days")).toBeNull());expect(screen.getByText("This Week")).toBeTruthy();- expect(screen.getByText("Last Week")).toBeTruthy();+ });++ it("says so when nothing matches", () => {+ renderPanel(DATE_RANGE);++ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: "quarter" } });++ expect(screen.getByText("No matching range")).toBeTruthy();});it("hides the realtime group when a caller disables past-minutes windows", () => {@@ -106,6 +121,95 @@ describe("RangePanel presets", () => {});});+describe("RangePanel typed windows", () => {+ it("turns 14d into a window instead of a search, and applies it on select", () => {+ renderPanel(DATE_RANGE);++ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: "14d" } });++ // The presets step aside: "3d" must not surface Last 30 Days beside the typed row.+ expect(screen.queryByText("Last 30 Days")).toBeNull();+ fireEvent.click(screen.getByText("Last 14 days"));++ expect(onApply).toHaveBeenCalledTimes(1);+ const applied = onApply.mock.calls[0][0];+ // 14 days is a dropped preset, so the typed window keeps its identity.+ expect(applied).toMatchObject({ mode: "range", wellKnown: "last-14-days" });+ expect(DateTime.fromISO(applied.endDate).diff(DateTime.fromISO(applied.startDate), "days").days).toBe(13);+ });++ it("applies a count no preset covers as a plain range", () => {+ renderPanel(DATE_RANGE);++ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: "20d" } });+ fireEvent.click(screen.getByText("Last 20 days"));++ const applied = onApply.mock.calls[0][0];+ expect(applied.mode).toBe("range");+ expect(applied.wellKnown).toBeUndefined();+ expect(DateTime.fromISO(applied.endDate).diff(DateTime.fromISO(applied.startDate), "days").days).toBe(19);+ });++ it("serves hours from the realtime path", () => {+ renderPanel(DATE_RANGE);++ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: "5h" } });+ fireEvent.click(screen.getByText("Last 5 hours"));++ expect(onApply.mock.calls[0][0]).toEqual({ mode: "past-minutes", pastMinutesStart: 300, pastMinutesEnd: 0 });+ });++ it("applies the typed row on Enter", () => {+ renderPanel(DATE_RANGE);++ const input = screen.getByPlaceholderText(/Search/);+ fireEvent.change(input, { target: { value: "20d" } });+ fireEvent.keyDown(input, { key: "Enter" });++ expect(onApply).toHaveBeenCalledTimes(1);+ expect(onApply.mock.calls[0][0].wellKnown).toBeUndefined();+ });++ it("still lets Enter pick the first row when the current preset is no longer in the rail", () => {+ // A stored default of a dropped preset used to become cmdk's defaultValue+ // with nothing to match, leaving no row selected and Enter dead.+ const zone = "America/New_York";+ const today = DateTime.now().setZone(zone);+ renderPanel({+ mode: "range",+ startDate: today.minus({ days: 13 }).toISODate()!,+ endDate: today.toISODate()!,+ wellKnown: "last-14-days",+ });++ fireEvent.keyDown(screen.getByPlaceholderText(/Search/), { key: "Enter" });++ expect(onApply).toHaveBeenCalledTimes(1);+ expect(onApply.mock.calls[0][0]).toMatchObject({ wellKnown: "last-30-minutes" });+ });++ it("names the unit letters while only the digits are typed", () => {+ renderPanel(DATE_RANGE);++ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: "14" } });++ expect(screen.getByText("Last 14 β¦")).toBeTruthy();+ expect(within(screen.getAllByRole("listbox")[0]).queryAllByRole("option").length).toBe(0);+ });++ it("does not offer minutes or hours where realtime windows are disabled", () => {+ renderPanel(DATE_RANGE, { pastMinutesEnabled: false });++ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: "6h" } });+ expect(screen.queryByText("Last 6 hours")).toBeNull();+ expect(screen.getByText("No matching range")).toBeTruthy();++ fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: "14" } });+ expect(screen.queryByText("m")).toBeNull();+ expect(screen.getByText("d")).toBeTruthy();+ });+});+describe("RangePanel draft", () => {it("seeds the bound fields from the current window", () => {renderPanel(DATE_RANGE);diff --git a/client/src/components/DateSelector/RangePanel.tsx b/client/src/components/DateSelector/RangePanel.tsxindex cf106fa81..8ec4e5263 100644--- a/client/src/components/DateSelector/RangePanel.tsx+++ b/client/src/components/DateSelector/RangePanel.tsx@@ -10,6 +10,7 @@ import {CommandItem,CommandList,CommandSeparator,+ CommandShortcut,} from "@/components/ui/command";import useMediaQuery from "@/components/ui/hooks/useMediaQuery";import { Input } from "@/components/ui/input";@@ -24,8 +25,9 @@ import { useExtracted } from "next-intl";import { Fragment, useState } from "react";import { DateRange } from "react-day-picker";import { ComparisonSelect } from "./ComparisonSelect";-import { PRESET_GROUPS, usePresetLabels } from "./presets";+import { HOTKEY_FOR_PRESET, PRESET_GROUPS, usePresetLabels } from "./presets";import { rangeFieldsForTime, timeFromRangeFields, timeFromSelectedDays, type RangeFields } from "./rangeFields";+import { parseTypedWindow, timeForTypedWindow, type TypedUnit } from "./typedWindow";import { Comparison, Time } from "./types";/**@@ -62,6 +64,7 @@ export function RangePanel({const presetLabels = usePresetLabels();const isWide = useMediaQuery("(min-width: 768px)");const [timezoneOpen, setTimezoneOpen] = useState(false);+ const [query, setQuery] = useState("");// "Today" is the dashboard's today, not the browser's β the picker used to// disable future days against the machine clock, which is off by one for@@ -119,7 +122,38 @@ export function RangePanel({return { time: next, fields: rangeFieldsForTime(next, zone) };});- const groups = PRESET_GROUPS.filter(group => pastMinutesEnabled || group.id !== "realtime");+ /**+ * The search box doubles as a window parser: "14d" or "6h" is a window, not+ * a search, and it becomes the first row of the rail. Filtering is done here+ * rather than by cmdk so the typed row is never fuzzy-matched against, and+ * so "3d" does not surface Last 30 Days beside it.+ */+ const typed = parseTypedWindow(query);+ const typedAllowed = typed && (pastMinutesEnabled || (typed.unit !== "minute" && typed.unit !== "hour"));+ const needle = query.trim().toLowerCase();+ const groups = PRESET_GROUPS.filter(group => pastMinutesEnabled || group.id !== "realtime")+ .map(group => ({+ ...group,+ presets: typedAllowed+ ? []+ : group.presets.filter(preset => !needle || presetLabels[preset].toLowerCase().includes(needle)),+ }))+ .filter(group => group.presets.length > 0);+ const typedUnits: TypedUnit[] = pastMinutesEnabled ? ["minute", "hour", "day", "week"] : ["day", "week"];+ const typedLabels: Record<TypedUnit, (count: number) => string> = {+ minute: count => t("Last {count, plural, one {# minute} other {# minutes}}", { count }),+ hour: count => t("Last {count, plural, one {# hour} other {# hours}}", { count }),+ day: count => t("Last {count, plural, one {# day} other {# days}}", { count }),+ week: count => t("Last {count, plural, one {# week} other {# weeks}}", { count }),+ };+ // cmdk only selects the first row on its own when it has no default; a stored+ // default that is no longer in the rail must not leave it with nothing to+ // Enter on.+ const currentPreset = draft.time.wellKnown;+ const defaultValue =+ currentPreset && groups.some(group => group.presets.includes(currentPreset))+ ? presetLabels[currentPreset]+ : undefined;const bounds = getAbsoluteBounds(draft.time, zone);const selected: DateRange | undefined = bounds@@ -140,15 +174,43 @@ export function RangePanel({<div className="flex flex-col"><div className="flex flex-col md:flex-row"><div className="w-full border-b border-neutral-150 md:w-[190px] md:shrink-0 md:border-b-0 md:border-r dark:border-neutral-800">- <Command defaultValue={draft.time.wellKnown ? presetLabels[draft.time.wellKnown] : undefined}>- <CommandInput placeholder={t("Search ranges")} />+ <Command shouldFilter={false} defaultValue={defaultValue}>+ <CommandInput placeholder={t("Search, or type 14d, 6h")} value={query} onValueChange={setQuery} />{/* Capped so the rail ends level with the calendar column beside it(two months + the bound rows + the pane's padding, less thislist's own 36px search row). Left to its natural height theseventeen presets stretched the panel and left a block of deadspace under the calendar. */}<CommandList className="max-h-[180px] md:max-h-[384px]">- <CommandEmpty>{t("No matching range")}</CommandEmpty>+ {typedAllowed &&+ (typed.unit ? (+ <CommandGroup>+ <CommandItem+ value={`typed:${typed.count}${typed.unit}`}+ onSelect={() =>+ onApply(timeForTypedWindow({ count: typed.count, unit: typed.unit! }, zone), draftComparison)+ }+ >+ {typedLabels[typed.unit](typed.count)}+ <CommandShortcut className="tracking-normal">β΅</CommandShortcut>+ </CommandItem>+ </CommandGroup>+ ) : (+ // Digits alone: name the letters that would finish the phrase.+ <div className="flex items-center px-2 py-1.5 text-sm text-neutral-500 dark:text-neutral-400">+ {t("Last {count} β¦", { count: String(typed.count) })}+ <span className="ml-auto flex gap-1">+ {typedUnits.map(unit => (+ <KeyCap key={unit}>{unit[0]}</KeyCap>+ ))}+ </span>+ </div>+ ))}+ {!typedAllowed && groups.length === 0 && (+ <div className="py-6 text-center text-sm text-neutral-500 dark:text-neutral-400">+ {t("No matching range")}+ </div>+ )}{/* Separators rather than headings: the groups are obvious fromtheir contents, and cmdk drops the rules automatically while asearch is filtering across them. */}@@ -165,6 +227,16 @@ export function RangePanel({>{presetLabels[preset]}{draft.time.wellKnown === preset && <Check className="ml-auto h-3.5 w-3.5" />}+ {HOTKEY_FOR_PRESET[preset] && (+ <KeyCap+ className={cn(+ "hidden md:inline-flex",+ draft.time.wellKnown === preset ? "ml-1.5" : "ml-auto"+ )}+ >+ {HOTKEY_FOR_PRESET[preset]}+ </KeyCap>+ )}</CommandItem>))}</CommandGroup>@@ -291,6 +363,19 @@ export function RangePanel({);}+function KeyCap({ className, children }: { className?: string; children: string }) {+ return (+ <kbd+ className={cn(+ "inline-flex h-4 min-w-4 items-center justify-center rounded-[2.8px] border border-neutral-200 px-1 font-mono text-[10px] uppercase text-neutral-500 dark:border-neutral-750 dark:text-neutral-400",+ className+ )}+ >+ {children}+ </kbd>+ );+}+function BoundRow({label,date,diff --git a/client/src/components/DateSelector/presets.ts b/client/src/components/DateSelector/presets.tsindex 5c4d937b8..f2a7cf76f 100644--- a/client/src/components/DateSelector/presets.ts+++ b/client/src/components/DateSelector/presets.ts@@ -6,21 +6,21 @@ import type { DashboardDefaultTimeRange } from "@/lib/defaultTimeRange";* named headings β their contents say what they are, and it keeps the rail as* quiet as the dropdown it replaces.*- * Two of the seventeen presets were previously unreachable: `last-week` and- * `last-month` had labels but no menu item, so they could only be arrived at- * from a stored default or a URL param.+ * Ten presets rather than the seventeen there used to be: a list this short is+ * one people learn rather than scan, and every window it dropped (1h, 6h, 3d,+ * 14d, 60d) is a count back from now that the search box now takes typed β+ * see `parseTypedWindow`. Last week and last month are not counts, so they+ * stay a click away in the calendar. Every dropped preset keeps its label and+ * resolver so a stored default or URL param still names itself.** `realtime` is dropped when a caller passes `pastMinutesEnabled={false}`.*/export type PresetGroupId = "realtime" | "relative" | "calendar";export const PRESET_GROUPS: { id: PresetGroupId; presets: DashboardDefaultTimeRange[] }[] = [- { id: "realtime", presets: ["last-30-minutes", "last-1-hour", "last-6-hours", "last-24-hours"] },- {- id: "relative",- presets: ["today", "yesterday", "last-3-days", "last-7-days", "last-14-days", "last-30-days", "last-60-days"],- },- { id: "calendar", presets: ["this-week", "last-week", "this-month", "last-month", "this-year", "all-time"] },+ { id: "realtime", presets: ["last-30-minutes", "last-24-hours"] },+ { id: "relative", presets: ["today", "yesterday", "last-7-days", "last-30-days"] },+ { id: "calendar", presets: ["this-week", "this-month", "this-year", "all-time"] },];/**@@ -50,3 +50,29 @@ export function usePresetLabels(): Record<DashboardDefaultTimeRange, string> {"all-time": t("All Time"),};}++/**+ * Single-key shortcuts. The letters follow Plausible's scheme (D/E/W/T/M/Y/A)+ * so anyone arriving from there keeps their muscle memory; the two realtime+ * windows and the custom picker fill the gaps. Only This Week has no key.+ */+export const PRESET_HOTKEYS = {+ d: "today",+ e: "yesterday",+ h: "last-24-hours",+ w: "last-7-days",+ t: "last-30-days",+ m: "this-month",+ y: "this-year",+ a: "all-time",+ r: "last-30-minutes",+} as const satisfies Record<string, DashboardDefaultTimeRange>;++export type PresetHotkey = keyof typeof PRESET_HOTKEYS;++/** Opens the panel for a custom range. */+export const CUSTOM_RANGE_HOTKEY = "c";++export const HOTKEY_FOR_PRESET: Partial<Record<DashboardDefaultTimeRange, PresetHotkey>> = Object.fromEntries(+ (Object.entries(PRESET_HOTKEYS) as [PresetHotkey, DashboardDefaultTimeRange][]).map(([key, preset]) => [preset, key])+);diff --git a/client/src/components/DateSelector/typedWindow.test.ts b/client/src/components/DateSelector/typedWindow.test.tsnew file mode 100644index 000000000..4ae8a907a--- /dev/null+++ b/client/src/components/DateSelector/typedWindow.test.ts@@ -0,0 +1,87 @@+import { DateTime } from "luxon";+import { describe, expect, it } from "vitest";++import { parseTypedWindow, timeForTypedWindow } from "./typedWindow";++describe("parseTypedWindow", () => {+ it("reads a count and a unit in the metrics-tool shorthand", () => {+ expect(parseTypedWindow("14d")).toEqual({ count: 14, unit: "day" });+ expect(parseTypedWindow("6h")).toEqual({ count: 6, unit: "hour" });+ expect(parseTypedWindow("90m")).toEqual({ count: 90, unit: "minute" });+ expect(parseTypedWindow("2w")).toEqual({ count: 2, unit: "week" });+ });++ it("tolerates spaces, case and longer unit names", () => {+ expect(parseTypedWindow(" 3 days ")).toEqual({ count: 3, unit: "day" });+ expect(parseTypedWindow("12 HRS")).toEqual({ count: 12, unit: "hour" });+ expect(parseTypedWindow("45 min")).toEqual({ count: 45, unit: "minute" });+ });++ it("keeps bare digits so the rail can show which unit letters finish it", () => {+ expect(parseTypedWindow("14")).toEqual({ count: 14 });+ });++ it("treats anything else as an ordinary search", () => {+ expect(parseTypedWindow("week")).toBeNull();+ expect(parseTypedWindow("14x")).toBeNull();+ expect(parseTypedWindow("0d")).toBeNull();+ expect(parseTypedWindow("")).toBeNull();+ expect(parseTypedWindow("14 d ago")).toBeNull();+ });++ it("refuses windows the dashboard cannot serve", () => {+ expect(parseTypedWindow("400d")).toBeNull();+ expect(parseTypedWindow("53w")).toBeNull();+ expect(parseTypedWindow("200h")).toBeNull();+ expect(parseTypedWindow("999h")).toBeNull();+ expect(parseTypedWindow("168h")).toEqual({ count: 168, unit: "hour" });+ });+});++describe("timeForTypedWindow", () => {+ const zone = "America/New_York";+ const today = DateTime.now().setZone(zone).toISODate();++ it("serves minutes and hours from the realtime path", () => {+ expect(timeForTypedWindow({ count: 90, unit: "minute" }, zone)).toEqual({+ mode: "past-minutes",+ pastMinutesStart: 90,+ pastMinutesEnd: 0,+ });+ expect(timeForTypedWindow({ count: 5, unit: "hour" }, zone)).toEqual({+ mode: "past-minutes",+ pastMinutesStart: 300,+ pastMinutesEnd: 0,+ });+ });++ it("counts days back from today inclusive, the same shape as the day presets", () => {+ expect(timeForTypedWindow({ count: 20, unit: "day" }, zone)).toEqual({+ mode: "range",+ startDate: DateTime.now().setZone(zone).minus({ days: 19 }).toISODate(),+ endDate: today,+ });+ expect(timeForTypedWindow({ count: 3, unit: "week" }, zone)).toEqual({+ mode: "range",+ startDate: DateTime.now().setZone(zone).minus({ days: 20 }).toISODate(),+ endDate: today,+ });+ });++ it("keeps a preset's identity when the typed window lands on one, so it re-resolves tomorrow", () => {+ expect(timeForTypedWindow({ count: 14, unit: "day" }, zone)).toMatchObject({+ mode: "range",+ wellKnown: "last-14-days",+ });+ expect(timeForTypedWindow({ count: 2, unit: "week" }, zone)).toMatchObject({ wellKnown: "last-14-days" });+ expect(timeForTypedWindow({ count: 1, unit: "week" }, zone)).toMatchObject({ wellKnown: "last-7-days" });+ expect(timeForTypedWindow({ count: 1, unit: "day" }, zone)).toEqual({+ mode: "day",+ day: today,+ wellKnown: "today",+ });+ expect(timeForTypedWindow({ count: 6, unit: "hour" }, zone)).toMatchObject({ wellKnown: "last-6-hours" });+ expect(timeForTypedWindow({ count: 60, unit: "minute" }, zone)).toMatchObject({ wellKnown: "last-1-hour" });+ expect(timeForTypedWindow({ count: 24, unit: "hour" }, zone)).toMatchObject({ wellKnown: "last-24-hours" });+ });+});diff --git a/client/src/components/DateSelector/typedWindow.ts b/client/src/components/DateSelector/typedWindow.tsnew file mode 100644index 000000000..c79a2c558--- /dev/null+++ b/client/src/components/DateSelector/typedWindow.ts@@ -0,0 +1,106 @@+import { DateTime } from "luxon";+import { getDashboardTimeForRange, type DashboardDefaultTimeRange } from "@/lib/defaultTimeRange";+import { Time } from "./types";++export type TypedUnit = "minute" | "hour" | "day" | "week";++export type TypedWindow = {+ count: number;+ /** Absent while only the digits have been typed. */+ unit?: TypedUnit;+};++const UNITS: Record<string, TypedUnit> = {+ m: "minute",+ min: "minute",+ mins: "minute",+ minute: "minute",+ minutes: "minute",+ h: "hour",+ hr: "hour",+ hrs: "hour",+ hour: "hour",+ hours: "hour",+ d: "day",+ day: "day",+ days: "day",+ w: "week",+ wk: "week",+ wks: "week",+ week: "week",+ weeks: "week",+};++/**+ * The ceiling on a typed window, in minutes: a year. Minutes and hours are+ * served from the past-minutes path, which the API only sizes for realtime+ * use, so they stop well short of that at a week.+ */+const MAX_DAYS = 366;+const MAX_REALTIME_MINUTES = 7 * 24 * 60;++/**+ * "14d", "3 days", "90 min" β a window counted back from now. Grafana and+ * Datadog take the same shorthand, so anyone who has used a metrics tool+ * already knows it. Bare digits ("14") parse with no unit so the rail can show+ * which letters would finish the phrase; anything else is an ordinary search.+ */+export function parseTypedWindow(text: string): TypedWindow | null {+ const match = /^\s*(\d{1,4})\s*([a-z]*)\s*$/i.exec(text);+ if (!match) return null;++ const count = Number(match[1]);+ if (count < 1) return null;++ if (!match[2]) return { count };++ const unit = UNITS[match[2].toLowerCase()];+ if (!unit) return null;++ const minutes = unit === "minute" ? count : unit === "hour" ? count * 60 : 0;+ if (minutes > MAX_REALTIME_MINUTES) return null;++ const days = unit === "day" ? count : unit === "week" ? count * 7 : 0;+ if (days > MAX_DAYS) return null;++ return { count, unit };+}++/**+ * A typed window that lands exactly on a preset keeps that preset's identity:+ * the store re-resolves a `wellKnown` window from the URL and the stored+ * default, so "14d" still means the last 14 days tomorrow, where an anonymous+ * range would be frozen to the dates it was typed on.+ */+const PRESET_BY_MINUTES: Record<number, DashboardDefaultTimeRange> = {+ 30: "last-30-minutes",+ 60: "last-1-hour",+ 360: "last-6-hours",+ 1440: "last-24-hours",+};+const PRESET_BY_DAYS: Record<number, DashboardDefaultTimeRange> = {+ 1: "today",+ 3: "last-3-days",+ 7: "last-7-days",+ 14: "last-14-days",+ 30: "last-30-days",+ 60: "last-60-days",+};++export function timeForTypedWindow(window: TypedWindow & { unit: TypedUnit }, zone: string): Time {+ const { count, unit } = window;++ if (unit === "minute" || unit === "hour") {+ const minutes = unit === "hour" ? count * 60 : count;+ const preset = PRESET_BY_MINUTES[minutes];+ if (preset) return getDashboardTimeForRange(preset, zone);+ return { mode: "past-minutes", pastMinutesStart: unit === "hour" ? count * 60 : count, pastMinutesEnd: 0 };+ }++ const days = unit === "week" ? count * 7 : count;+ const preset = PRESET_BY_DAYS[days];+ if (preset) return getDashboardTimeForRange(preset, zone);++ const now = DateTime.now().setZone(zone);+ return { mode: "range", startDate: now.minus({ days: days - 1 }).toISODate() ?? "", endDate: now.toISODate() ?? "" };+}diff --git a/client/src/components/DateSelector/types.ts b/client/src/components/DateSelector/types.tsindex a0bb9813c..008662389 100644--- a/client/src/components/DateSelector/types.ts+++ b/client/src/components/DateSelector/types.ts@@ -54,14 +54,7 @@ export type PastMinutesMode = {wellKnown?: "last-30-minutes" | "last-1-hour" | "last-6-hours" | "last-24-hours";};-export type Time =- | DateMode- | DateRangeMode- | WeekMode- | MonthMode- | YearMode- | AllTimeMode- | PastMinutesMode;+export type Time = DateMode | DateRangeMode | WeekMode | MonthMode | YearMode | AllTimeMode | PastMinutesMode;/*** What the dashboard's comparison line is drawn against. Everything butdiff --git a/client/src/components/DateSelector/useDatePresetHotkeys.ts b/client/src/components/DateSelector/useDatePresetHotkeys.tsnew file mode 100644index 000000000..73921344c--- /dev/null+++ b/client/src/components/DateSelector/useDatePresetHotkeys.ts@@ -0,0 +1,71 @@+import { useEffect, useRef } from "react";+import type { DashboardDefaultTimeRange } from "@/lib/defaultTimeRange";+import { CUSTOM_RANGE_HOTKEY, PRESET_HOTKEYS, type PresetHotkey } from "./presets";++type Handlers = {+ onPreset: (preset: DashboardDefaultTimeRange) => void;+ onCustom: () => void;+ /** Presets the caller has hidden, so their keys fall through untouched. */+ enabled: (preset: DashboardDefaultTimeRange) => boolean;+};++type Entry = { current: Handlers };++/**+ * Only the most recently mounted selector answers a key. Pages mount exactly+ * one, but a dialog that stacks its own on top of the page's must not apply+ * the same preset twice β the newest one wins, and the older resumes when it+ * unmounts. Each selector holds one stack slot for its whole life and swaps+ * handlers through a ref, so a re-render of the page's selector cannot push+ * it back above the dialog's.+ */+const stack: Entry[] = [];++const isTyping = (target: EventTarget | null) => {+ if (!(target instanceof HTMLElement)) return false;+ if (target.isContentEditable) return true;+ const tag = target.tagName;+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";+};++const onKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented || event.repeat) return;+ if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;+ if (isTyping(event.target)) return;++ const handlers = stack[stack.length - 1]?.current;+ if (!handlers) return;++ const key = event.key.toLowerCase();+ if (key === CUSTOM_RANGE_HOTKEY) {+ event.preventDefault();+ handlers.onCustom();+ return;+ }++ const preset = key in PRESET_HOTKEYS ? PRESET_HOTKEYS[key as PresetHotkey] : undefined;+ if (!preset || !handlers.enabled(preset)) return;++ event.preventDefault();+ handlers.onPreset(preset);+};++export function useDatePresetHotkeys(handlers: Handlers | null) {+ const entry = useRef<Entry | null>(null);+ if (handlers)+ entry.current = entry.current ? Object.assign(entry.current, { current: handlers }) : { current: handlers };++ const enabled = handlers !== null;+ useEffect(() => {+ if (!enabled) return;+ const slot = entry.current!;++ stack.push(slot);+ if (stack.length === 1) document.addEventListener("keydown", onKeyDown);++ return () => {+ stack.splice(stack.indexOf(slot), 1);+ if (stack.length === 0) document.removeEventListener("keydown", onKeyDown);+ };+ }, [enabled]);+}