Skip to content

Commit cfacdbe

Browse files
authored
feat: relative date ranges can be saved for dashboards (#3073)
1 parent c8cc8e5 commit cfacdbe

10 files changed

Lines changed: 185 additions & 27 deletions

File tree

‎.changeset/orange-pens-accept.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@hyperdx/common-utils": patch
3+
"@hyperdx/api": patch
4+
"@hyperdx/app": patch
5+
---
6+
7+
feat: relative date ranges for dashboards can now be saved

‎packages/api/src/models/dashboard.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ export default mongoose.model<IDashboard>(
3434
savedQuery: { type: String, required: false },
3535
savedQueryLanguage: { type: String, required: false },
3636
savedFilterValues: { type: mongoose.Schema.Types.Array, required: false },
37+
savedDateRange: {
38+
type: mongoose.Schema.Types.Mixed,
39+
required: false,
40+
},
3741
containers: { type: mongoose.Schema.Types.Array, required: false },
3842
createdBy: {
3943
type: mongoose.Schema.Types.ObjectId,

‎packages/app/src/DBDashboardPage.tsx‎

Lines changed: 85 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ import {
7878
Group,
7979
Indicator,
8080
List,
81+
Loader,
8182
Menu,
8283
Modal,
8384
Paper,
@@ -147,7 +148,10 @@ import { PageHeader } from '@/components/PageHeader';
147148
import { PageLayout } from '@/components/PageLayout';
148149
import { SqlVariablesProvider } from '@/components/SQLEditor/variableCompletions';
149150
import { TimePicker } from '@/components/TimePicker';
150-
import { parseTimeRangeInput } from '@/components/TimePicker/utils';
151+
import {
152+
parseTimeRangeInput,
153+
timeRangeInputToSeconds,
154+
} from '@/components/TimePicker/utils';
151155
import {
152156
Dashboard,
153157
type Tile,
@@ -211,6 +215,7 @@ import {
211215
} from './source';
212216
import {
213217
dateRangeToString,
218+
parseRelativeTimeQuery,
214219
useDefaultTimeRange,
215220
useNewTimeQuery,
216221
} from './timeQuery';
@@ -1855,15 +1860,14 @@ function DashboardContainerRow({
18551860

18561861
const DEFAULT_INTERVAL = 'Past 1h';
18571862

1858-
function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
1859-
const defaultTimeRange = useDefaultTimeRange(DEFAULT_INTERVAL);
1860-
const brandName = useBrandDisplayName();
1861-
const confirm = useConfirm();
1862-
1863-
const router = useRouter();
1864-
const dashboardId = router.query.dashboardId as string | undefined;
1865-
const { enterKioskMode, exitKioskMode, isKioskMode } =
1866-
useDashboardKioskMode();
1863+
function DBDashboardPage({
1864+
dashboardProps,
1865+
defaultTimeInput = DEFAULT_INTERVAL,
1866+
}: {
1867+
dashboardProps: ReturnType<typeof useDashboard>;
1868+
defaultTimeInput?: string;
1869+
}) {
1870+
const defaultTimeRange = useDefaultTimeRange(defaultTimeInput);
18671871

18681872
const {
18691873
dashboard,
@@ -1872,10 +1876,17 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
18721876
isLocalDashboard,
18731877
isFetching: isFetchingDashboard,
18741878
isSetting: isSavingDashboard,
1875-
} = useDashboard({
1876-
dashboardId: dashboardId as string | undefined,
1877-
presetConfig,
1878-
});
1879+
} = dashboardProps;
1880+
const brandName = useBrandDisplayName();
1881+
const confirm = useConfirm();
1882+
const {
1883+
userPreferences: { isUTC },
1884+
} = useUserPreferences();
1885+
1886+
const router = useRouter();
1887+
const dashboardId = router.query.dashboardId as string | undefined;
1888+
const { enterKioskMode, exitKioskMode, isKioskMode } =
1889+
useDashboardKioskMode();
18791890

18801891
const { data: sources } = useSources();
18811892
const { data: connections } = useConnections();
@@ -2033,10 +2044,10 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
20332044
}, [router.isReady, watchedGranularity, granularity, setGranularity]);
20342045

20352046
const [displayedTimeInputValue, setDisplayedTimeInputValue] =
2036-
useState(DEFAULT_INTERVAL);
2047+
useState(defaultTimeInput);
20372048

20382049
const { searchedTimeRange, onSearch, onTimeRangeSelect } = useNewTimeQuery({
2039-
initialDisplayValue: DEFAULT_INTERVAL,
2050+
initialDisplayValue: defaultTimeInput,
20402051
initialTimeRange: defaultTimeRange,
20412052
setDisplayedTimeInputValue,
20422053
});
@@ -2113,6 +2124,7 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
21132124
dashboard?.savedQuery,
21142125
dashboard?.savedQueryLanguage,
21152126
dashboard?.savedFilterValues,
2127+
dashboard?.savedDateRange,
21162128
isLocalDashboard,
21172129
isFetchingDashboard,
21182130
router.isReady,
@@ -2121,6 +2133,7 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
21212133
setWhere,
21222134
setWhereLanguage,
21232135
setFilterValueEntries,
2136+
onTimeRangeSelect,
21242137
]);
21252138

21262139
// Sync changes to the URL params into the form
@@ -2150,18 +2163,30 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
21502163
? filterValueEntries
21512164
: [];
21522165

2166+
const currentRelativeDateRange = timeRangeInputToSeconds(
2167+
displayedTimeInputValue,
2168+
isUTC,
2169+
);
2170+
21532171
setDashboard(
21542172
produce(dashboard, draft => {
21552173
draft.savedQuery = currentWhere;
21562174
draft.savedQueryLanguage = currentWhereLanguage;
21572175
draft.savedFilterValues = currentFilterValues;
2176+
// Only supporting relative date range saving ATM
2177+
if (currentRelativeDateRange) {
2178+
draft.savedDateRange = {
2179+
type: 'relative',
2180+
value: currentRelativeDateRange,
2181+
};
2182+
}
21582183
}),
21592184
() => {
21602185
notifications.show({
21612186
color: 'green',
21622187
title: 'Query saved and executed',
21632188
message:
2164-
'Filter query and dropdown values have been saved with the dashboard',
2189+
'Filter query, dropdown values, and relative time range have been saved with the dashboard',
21652190
autoClose: 3000,
21662191
});
21672192
},
@@ -2173,6 +2198,8 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
21732198
getValues,
21742199
filterValueEntries,
21752200
onSubmit,
2201+
isUTC,
2202+
displayedTimeInputValue,
21762203
]);
21772204
const handleRemoveSavedQuery = useCallback(() => {
21782205
if (!dashboard || isLocalDashboard) return;
@@ -2182,6 +2209,7 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
21822209
draft.savedQuery = null;
21832210
draft.savedQueryLanguage = null;
21842211
draft.savedFilterValues = [];
2212+
draft.savedDateRange = null;
21852213
}),
21862214
() => {
21872215
notifications.show({
@@ -3484,7 +3512,46 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) {
34843512
);
34853513
}
34863514

3487-
const DBDashboardPageDynamic = dynamic(async () => DBDashboardPage, {
3515+
function DBDashboardPageGuarded({
3516+
presetConfig,
3517+
}: {
3518+
presetConfig?: Dashboard;
3519+
}) {
3520+
const router = useRouter();
3521+
const dashboardId = router.query.dashboardId as string | undefined;
3522+
const dashboardProps = useDashboard({
3523+
dashboardId: dashboardId as string | undefined,
3524+
presetConfig,
3525+
});
3526+
const {
3527+
userPreferences: { isUTC },
3528+
} = useUserPreferences();
3529+
3530+
const savedDateRange = dashboardProps.dashboard?.savedDateRange;
3531+
// Keyed on the saved range, not the render: a relative range re-stringifies
3532+
// to a new value every render, and useNewTimeQuery resets the input on change.
3533+
// Valid URL from/to still win: useNewTimeQuery overwrites the input from them.
3534+
const defaultTimeInput = useMemo(() => {
3535+
if (!savedDateRange) return undefined;
3536+
const [start, end] =
3537+
savedDateRange.type === 'relative'
3538+
? parseRelativeTimeQuery(savedDateRange.value * 1000)
3539+
: savedDateRange.value.map(v => new Date(v));
3540+
// TODO: show relative ranges as "Past Xh" via getRelativeInterval
3541+
return dateRangeToString([start, end], isUTC);
3542+
}, [savedDateRange, isUTC]);
3543+
3544+
if (!dashboardProps || !router.isReady) return <Loader size="lg" />;
3545+
3546+
return (
3547+
<DBDashboardPage
3548+
dashboardProps={dashboardProps}
3549+
defaultTimeInput={defaultTimeInput}
3550+
/>
3551+
);
3552+
}
3553+
3554+
const DBDashboardPageDynamic = dynamic(async () => DBDashboardPageGuarded, {
34883555
ssr: false,
34893556
});
34903557

‎packages/app/src/components/TimePicker/__tests__/utils.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { dateParser, parseTimeRangeInput } from '@/components/TimePicker/utils';
1+
import {
2+
dateParser,
3+
parseTimeRangeInput,
4+
timeRangeInputToSeconds,
5+
} from '@/components/TimePicker/utils';
26

37
describe('dateParser', () => {
48
let mockDate: Date;
@@ -154,3 +158,30 @@ describe('parseTimeRangeInput', () => {
154158
]);
155159
});
156160
});
161+
162+
describe('timeRangeInputToSeconds', () => {
163+
beforeEach(() => {
164+
jest.useFakeTimers();
165+
jest.setSystemTime(new Date('2025-01-15T22:00:00'));
166+
});
167+
168+
afterEach(() => {
169+
jest.useRealTimers();
170+
});
171+
172+
it('returns the relative range length in seconds', () => {
173+
expect(timeRangeInputToSeconds('Past 1h', false)).toBe(3600);
174+
expect(timeRangeInputToSeconds('Past 15m', false)).toBe(900);
175+
});
176+
177+
it('returns the span of an absolute range', () => {
178+
expect(timeRangeInputToSeconds('2024-01-15 to 2024-01-16', false)).toBe(
179+
86400,
180+
);
181+
});
182+
183+
it('returns null for unparseable input', () => {
184+
expect(timeRangeInputToSeconds('', false)).toBeNull();
185+
expect(timeRangeInputToSeconds('not a date', false)).toBeNull();
186+
});
187+
});

‎packages/app/src/components/TimePicker/utils.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,16 @@ export function parseTimeRangeInput(
7272
}
7373
}
7474

75+
// Duration of a time range input in seconds, or null if it doesn't parse.
76+
export function timeRangeInputToSeconds(
77+
str: string,
78+
isUTC: boolean,
79+
): number | null {
80+
const [start, end] = parseTimeRangeInput(str, isUTC);
81+
if (start == null || end == null) return null;
82+
return (end.getTime() - start.getTime()) / 1000;
83+
}
84+
7585
export const LIVE_TAIL_TIME_QUERY = 'Live Tail' as const;
7686
export const LIVE_TAIL_DURATION_MS = ms('15m');
7787

‎packages/app/src/dashboard.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
DashboardContainer,
55
DashboardFilter,
66
DashboardFilterValue,
7+
DashboardWithoutId,
78
resolveChartPaletteToken,
89
SavedChartConfig,
910
SearchConditionLanguage,
@@ -39,6 +40,7 @@ export type Dashboard = {
3940
savedQuery?: string | null;
4041
savedQueryLanguage?: SearchConditionLanguage | null;
4142
savedFilterValues?: DashboardFilterValue[];
43+
savedDateRange?: DashboardWithoutId['savedDateRange'];
4244
containers?: DashboardContainer[];
4345
createdAt?: string;
4446
updatedAt?: string;

‎packages/app/src/timeQuery.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -522,27 +522,30 @@ export function useNewTimeQuery({
522522
};
523523
}
524524

525-
function getRangeOrFallback(query: string): [Date, Date] {
525+
function getRangeOrFallback(query: string, isUTC: boolean): [Date, Date] {
526526
return (
527-
parseValidTimeRange(query, false) ??
527+
parseValidTimeRange(query, isUTC) ??
528528
// This fallback catches arbitrary inputs but shouldn't be reachable
529529
// for standard literal labels (e.g., 'Past 1h') since they are always valid.
530530
parseRelativeTimeQuery(60 * 60 * 1000)
531531
);
532532
}
533533

534534
export function useDefaultTimeRange(query: string): [Date, Date] {
535+
const {
536+
userPreferences: { isUTC },
537+
} = useUserPreferences();
535538
const [state, setState] = useState<{ query: string; range: [Date, Date] }>(
536539
() => ({
537540
query,
538-
range: getRangeOrFallback(query),
541+
range: getRangeOrFallback(query, isUTC),
539542
}),
540543
);
541544

542545
if (state.query !== query) {
543546
const newState = {
544547
query,
545-
range: getRangeOrFallback(query),
548+
range: getRangeOrFallback(query, isUTC),
546549
};
547550
setState(newState);
548551
return newState.range;

‎packages/app/tests/e2e/features/dashboard.spec.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1201,7 +1201,7 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => {
12011201

12021202
// Wait for success notification
12031203
const notification = dashboardPage.page.locator(
1204-
'text=/Filter query and dropdown values/i',
1204+
'text=/Filter query, dropdown values, and relative time range/i',
12051205
);
12061206
await expect(notification).toBeVisible({ timeout: 5000 });
12071207
});
@@ -1266,7 +1266,7 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => {
12661266
// Wait for the save success notification rather than a blind sleep, so
12671267
// we only read the URL once the save has actually landed.
12681268
const notification = dashboardPage.page.locator(
1269-
'text=/Filter query and dropdown values/i',
1269+
'text=/Filter query, dropdown values, and relative time range/i',
12701270
);
12711271
await expect(notification).toBeVisible({ timeout: 5000 });
12721272

@@ -2649,7 +2649,7 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => {
26492649

26502650
// Wait for success notification
26512651
const notification = dashboardPage.page.locator(
2652-
'text=/Filter query and dropdown values/i',
2652+
'text=/Filter query, dropdown values, and relative time range/i',
26532653
);
26542654
await expect(notification).toBeVisible({ timeout: 5000 });
26552655
});
@@ -2670,7 +2670,7 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => {
26702670

26712671
// Wait for success notification
26722672
const notification = dashboardPage.page.locator(
2673-
'text=/Filter query and dropdown values/i',
2673+
'text=/Filter query, dropdown values, and relative time range/i',
26742674
);
26752675
await expect(notification).toBeVisible({ timeout: 5000 });
26762676
});

‎packages/common-utils/src/__tests__/types.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,28 @@ describe('DashboardFilterValueSchema', () => {
829829
});
830830
});
831831

832+
describe('DashboardSchema.savedDateRange', () => {
833+
const base = { id: 'd1', name: 'Dashboard', tiles: [], tags: [] };
834+
const parse = (savedDateRange: unknown) =>
835+
DashboardSchema.safeParse({ ...base, savedDateRange }).success;
836+
837+
it('accepts relative, historical, null, or absent', () => {
838+
expect(parse({ type: 'relative', value: 3600 })).toBe(true);
839+
expect(parse({ type: 'historical', value: [1700000000, 1700003600] })).toBe(
840+
true,
841+
);
842+
expect(parse(null)).toBe(true);
843+
expect(parse(undefined)).toBe(true);
844+
});
845+
846+
it('rejects malformed values', () => {
847+
expect(parse({ type: 'relative', value: '1h' })).toBe(false);
848+
expect(parse({ type: 'historical', value: [1700000000] })).toBe(false);
849+
expect(parse({ type: 'other', value: 1 })).toBe(false);
850+
expect(parse(3600)).toBe(false);
851+
});
852+
});
853+
832854
describe('MetricFormulaSchema', () => {
833855
it('parses an expression-only formula', () => {
834856
const result = MetricFormulaSchema.safeParse({

0 commit comments

Comments
 (0)