feature(dashboard): remember last selected range

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-10-23 21:47:59 +02:00
parent 2329982cd1
commit 8c4d157633
3 changed files with 43 additions and 3 deletions

View File

@@ -89,7 +89,8 @@ export function ListReports({ reports, dashboard }: ListReportsProps) {
<div className="mt-2 flex gap-2 ">
<span
className={
range !== null || (startDate && endDate)
(chartRange !== range && range !== null) ||
(startDate && endDate)
? 'line-through'
: ''
}
@@ -99,7 +100,10 @@ export function ListReports({ reports, dashboard }: ListReportsProps) {
{startDate && endDate ? (
<span>Custom dates</span>
) : (
range !== null && <span>{range}</span>
range !== null &&
chartRange !== range && (
<span>{timeWindows[range].label}</span>
)
)}
</div>
)}

View File

@@ -6,6 +6,7 @@ import {
useQueryState,
} from 'nuqs';
import { getStorageItem, setStorageItem } from '@/utils/storage';
import {
getDefaultIntervalByDates,
getDefaultIntervalByRange,
@@ -13,6 +14,7 @@ import {
} from '@openpanel/constants';
import type { IChartRange } from '@openpanel/validation';
import { mapKeys } from '@openpanel/validation';
import { useEffect } from 'react';
const nuqsOptions = { history: 'push' } as const;
@@ -29,9 +31,19 @@ export function useOverviewOptions() {
'range',
parseAsStringEnum(mapKeys(timeWindows))
.withDefault('7d')
.withOptions(nuqsOptions),
.withOptions({
...nuqsOptions,
clearOnDefault: false,
}),
);
useEffect(() => {
const range = getStorageItem('range', '7d');
if (range !== '7d') {
setRange(range);
}
}, []);
const interval =
getDefaultIntervalByDates(startDate, endDate) ||
getDefaultIntervalByRange(range);
@@ -56,6 +68,7 @@ export function useOverviewOptions() {
if (value !== 'custom') {
setStartDate(null);
setEndDate(null);
setStorageItem('range', value);
}
setRange(value);
},

View File

@@ -0,0 +1,23 @@
const prefix = '@op';
export function getStorageItem<T>(key: string): T | null;
export function getStorageItem<T>(key: string, defaultValue: T): T;
export function getStorageItem<T>(key: string, defaultValue?: T): T | null {
if (typeof window === 'undefined') return defaultValue ?? null;
const item = localStorage.getItem(`${prefix}:${key}`);
if (item === null) {
return defaultValue ?? null;
}
return item as T;
}
export function setStorageItem(key: string, value: unknown) {
if (typeof window === 'undefined') return;
localStorage.setItem(`${prefix}:${key}`, value as string);
}
export function removeStorageItem(key: string) {
if (typeof window === 'undefined') return;
localStorage.removeItem(`${prefix}:${key}`);
}