import { useCallback, useState } from "react"; /** The stretches of time every chart can show, the same everywhere: a day to a year. */ export const CHART_RANGES = [ { days: 1, label: "24 hours" }, { days: 7, label: "7 days" }, { days: 30, label: "30 days" }, { days: 90, label: "90 days" }, { days: 365, label: "1 year" }, ] as const; export type ChartDays = (typeof CHART_RANGES)[number]["days"]; const KEY = "chart.range"; const isRange = (n: number): n is ChartDays => CHART_RANGES.some((r) => r.days === n); function remembered(fallback: ChartDays): ChartDays { try { const n = Number(localStorage.getItem(KEY)); return isRange(n) ? n : fallback; } catch { return fallback; } } /** * The range a chart shows, remembered between charts and visits: choosing 30 days on one page means the next chart opens on 30 days as well. A convenience only — * without storage it is just the default each time. */ export function useChartRange(fallback: ChartDays = 7): [ChartDays, (days: number) => void] { const [days, setDays] = useState(() => remembered(fallback)); const choose = useCallback((n: number) => { if (!isRange(n)) return; setDays(n); try { localStorage.setItem(KEY, String(n)); } catch { // not remembered } }, []); return [days, choose]; }