Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(traffic): open AI Traffic on the last 24 hours, remember the range and trend it by hour (#1163)

Cihan6f18fbeca7d3
diff --git a/web/messages/en.json b/web/messages/en.json
index 16bf999e3..508d0708d 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3098,6 +3098,7 @@
"value": "Value",
"note": "Note",
"day": "Day",
+ "hour": "Hour (UTC)",
"platform": "Platform",
"visits": "Visits",
"previousVisits": "Visits, previous period",
@@ -3186,7 +3187,9 @@
"kpiSubNoPrevious": "{pageviews, plural, one {# pageview} other {# pageviews}}",
"listTotal": "{visits, plural, one {# visit} other {# visits}} ({pageviews, plural, one {# pageview} other {# pageviews}})",
"rowPageviews": "{count, plural, one {# pageview} other {# pageviews}}",
- "listNote": "One row per visit (session). Repeated pageviews in the same visit are grouped."
+ "listNote": "One row per visit (session). Repeated pageviews in the same visit are grouped.",
+ "listRange": "{visits, plural, one {# visit} other {# visits}} ({pageviews, plural, one {# pageview} other {# pageviews}}) {preset, select, last {in the {range}} other {· {range}}}",
+ "showLast7Days": "Show last 7 days"
},
"sources": {
"label": "Data sources",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.test.ts
index 190af841d..fe87afbfb 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.test.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.test.ts
@@ -58,3 +58,12 @@ describe('formatTrafficBucketDate', () => {
}
});
});
+
+describe('formatTrafficBucketDate for the 24-hour range', () => {
+ it("names an hour on the axis, and its day too in the tooltip, in the member's time zone", () => {
+ const hour = '2026-10-17T13:00:00.000Z';
+ expect(formatTrafficBucketDate(hour, { timeZone: 'UTC' })).toBe('13:00');
+ expect(formatTrafficBucketDate(hour, { withDay: true, timeZone: 'UTC' })).toBe('Oct 17, 13:00');
+ expect(formatTrafficBucketDate(hour, { timeZone: 'Europe/Istanbul' })).toBe('16:00');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
index 889d5ef5b..8465ae93b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_charts.tsx
@@ -94,15 +94,27 @@ export function getPlatformFilterItems(
}
/**
- * A trend bucket's day ("Oct 12"). English like the rest of the UI, not the
- * browser's language (F7), and in UTC because the buckets are UTC days.
+ * A trend bucket's label. A day reads "Oct 12", in UTC because the day
+ * buckets are UTC days. An hour (the 24-hour range, AT-017) reads "13:00" on
+ * the axis and "Oct 17, 13:00" in the tooltip, in the member's own time zone.
+ * English like the rest of the UI, not the browser's language (F7).
*/
-export function formatTrafficBucketDate(value: string): string {
- return new Date(value).toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- timeZone: 'UTC',
+export function formatTrafficBucketDate(
+ value: string,
+ { withDay = false, timeZone }: { withDay?: boolean; timeZone?: string } = {},
+): string {
+ const date = new Date(value);
+ if (!value.includes('T')) {
+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
+ }
+ const hour = date.toLocaleTimeString('en-US', {
+ hour: '2-digit',
+ minute: '2-digit',
+ hourCycle: 'h23',
+ timeZone,
});
+ if (!withDay) return hour;
+ return `${date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone })}, ${hour}`;
}
// ─── Custom Tooltips ──────────────────────────────────────────────────────────
@@ -120,7 +132,7 @@ function AreaTooltip({
return (
<div className="rounded-lg border bg-background px-3 py-2 shadow-md text-xs">
<p className="font-medium text-foreground mb-1">
- {label ? formatTrafficBucketDate(label) : ''}
+ {label ? formatTrafficBucketDate(label, { withDay: true }) : ''}
</p>
{payload.map((entry) => (
<div key={entry.name} className="flex items-center gap-2">
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index fb5bae45e..39e76819d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -67,6 +67,7 @@ import { cn } from '@/lib/utils';
import { formatRelative } from '@/lib/format-relative';
import { formatNumber } from '@/lib/format';
import { visitChange } from '@/lib/traffic-change';
+import { browserStorage, readTrafficRange, writeTrafficRange } from '@/lib/traffic-range';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
@@ -317,7 +318,16 @@ function EmptyLogsState({ hasFilters }: { hasFilters: boolean }) {
}
}
-function NoTrafficForPeriod({ rangeLabel, onReset }: { rangeLabel: string; onReset: () => void }) {
+function NoTrafficForPeriod({
+ rangeLabel,
+ onReset,
+ onShowWeek,
+}: {
+ rangeLabel: string;
+ onReset: () => void;
+ /** The 24-hour range offers the last 7 days first (AT-017). */
+ onShowWeek?: () => void;
+}) {
const t = useTranslations('traffic');
return (
<Card>
@@ -327,9 +337,16 @@ function NoTrafficForPeriod({ rangeLabel, onReset }: { rangeLabel: string; onRes
<p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">
{t('noTrafficInPeriodDescription', { range: rangeLabel })}
</p>
- <Button variant="outline" size="sm" className="mt-4" onClick={onReset}>
- {t('showAllData')}
- </Button>
+ <div className="mt-4 flex justify-center gap-2">
+ {onShowWeek && (
+ <Button variant="outline" size="sm" onClick={onShowWeek}>
+ {t('visits.showLast7Days')}
+ </Button>
+ )}
+ <Button variant="outline" size="sm" onClick={onReset}>
+ {t('showAllData')}
+ </Button>
+ </div>
</CardContent>
</Card>
);
@@ -419,9 +436,16 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
const t = useTranslations('traffic');
const tCommon = useTranslations('common');
const tVisits = useTranslations('traffic.visits');
- const [datePreset, setDatePreset] = useState<DatePreset>('7d');
- const [customFrom, setCustomFrom] = useState('');
- const [customTo, setCustomTo] = useState('');
+ // The page opens on the member's last range, or the last 24 hours (AT-017,
+ // spec §3.01). This only renders in the browser, once the brand has loaded,
+ // so the stored choice is read before the first load rather than after it.
+ const [initialRange] = useState(() => readTrafficRange(browserStorage()));
+ const [datePreset, setDatePreset] = useState<DatePreset>(initialRange.preset);
+ const [customFrom, setCustomFrom] = useState(initialRange.from);
+ const [customTo, setCustomTo] = useState(initialRange.to);
+ useEffect(() => {
+ writeTrafficRange(browserStorage(), { preset: datePreset, from: customFrom, to: customTo });
+ }, [datePreset, customFrom, customTo]);
const dateWindow = useMemo(
() => getDateRange(datePreset, { from: customFrom, to: customTo }),
[datePreset, customFrom, customTo],
@@ -661,6 +685,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
<NoTrafficForPeriod
rangeLabel={rangeSubLabel}
onReset={() => handleDatePresetChange('all')}
+ onShowWeek={datePreset === '24h' ? () => handleDatePresetChange('7d') : undefined}
/>
) : null}
{isEmpty && opportunitiesCard}
@@ -924,6 +949,27 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
/>
);
})()}
+ {/* What the list covers, and a wider range when it is a short one
+ (AT-017, spec §3.01). */}
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 px-6 pb-1 text-xs text-muted-foreground">
+ <span>
+ {tVisits('listRange', {
+ visits: logsTotal,
+ pageviews: logsPageviews,
+ range: rangeSubLabel,
+ preset: datePreset === 'custom' || datePreset === 'all' ? 'other' : 'last',
+ })}
+ </span>
+ {datePreset === '24h' && (
+ <button
+ type="button"
+ onClick={() => handleDatePresetChange('7d')}
+ className="font-medium text-foreground underline-offset-4 hover:underline"
+ >
+ {tVisits('showLast7Days')}
+ </button>
+ )}
+ </div>
<p className="px-6 pb-4 text-xs text-muted-foreground">{tVisits('listNote')}</p>
</>
)}
diff --git a/web/src/lib/actions/traffic-trend.test.ts b/web/src/lib/actions/traffic-trend.test.ts
new file mode 100644
index 000000000..77d024041
--- /dev/null
+++ b/web/src/lib/actions/traffic-trend.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * AT-017 (spec §3.01): the trend reads the 24-hour range hour by hour, and
+ * longer ranges by day.
+ */
+
+const ROWS = [
+ { source_platform: 'gemini.google.com', created_at: '2026-10-18T09:05:00+00:00', id: '1' },
+ { source_platform: 'gemini.google.com', created_at: '2026-10-18T09:40:00+00:00', id: '2' },
+ { source_platform: 'chatgpt.com', created_at: '2026-10-18T11:10:00+00:00', id: '3' },
+];
+
+function query() {
+ const builder: Record<string, unknown> = {};
+ for (const method of ['select', 'eq', 'is', 'order', 'range', 'gte', 'lte', 'lt']) {
+ builder[method] = () => builder;
+ }
+ builder.then = (resolve: (v: unknown) => unknown) => resolve({ data: ROWS, error: null });
+ return builder;
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ from: () => query() }),
+}));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
+
+import { getTrafficTrend } from './traffic';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-18T12:30:00.000Z'));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('getTrafficTrend', () => {
+ it('reads the last 24 hours hour by hour', async () => {
+ const points = await getTrafficTrend('b1', { dateFrom: '2026-10-17T12:30:00.000Z' });
+
+ expect(points).toHaveLength(25);
+ expect(points[0].date).toBe('2026-10-17T12:00:00.000Z');
+ expect(points.at(-1)!.date).toBe('2026-10-18T12:00:00.000Z');
+ const hour = (h: string) => points.find((p) => p.date === h)!;
+ expect(hour('2026-10-18T09:00:00.000Z')).toEqual({
+ date: '2026-10-18T09:00:00.000Z',
+ 'gemini.google.com': 2,
+ 'chatgpt.com': 0,
+ });
+ expect(hour('2026-10-18T11:00:00.000Z')['chatgpt.com']).toBe(1);
+ });
+
+ it('reads 7 days day by day', async () => {
+ const points = await getTrafficTrend('b1', { dateFrom: '2026-10-11T12:30:00.000Z' });
+
+ expect(points.map((p) => p.date)).toEqual([
+ '2026-10-11',
+ '2026-10-12',
+ '2026-10-13',
+ '2026-10-14',
+ '2026-10-15',
+ '2026-10-16',
+ '2026-10-17',
+ '2026-10-18',
+ ]);
+ expect(points.at(-1)).toEqual({
+ date: '2026-10-18',
+ 'gemini.google.com': 2,
+ 'chatgpt.com': 1,
+ });
+ });
+});
diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.ts
index 87d7711fe..5f8f10b2e 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -3,6 +3,7 @@
import { createClient } from '@/lib/supabase/server';
import { API_BASE_URL } from '@/config/api';
import { expandDateToEndOfDay, utcDay } from '@/lib/dates';
+import { isHourlyWindow, listUtcHours, utcHourKey } from '@/lib/traffic-buckets';
import { getSuggestionSourceStates, type SourceState } from '@/lib/actions/integrations';
export interface TrafficDateWindow {
@@ -42,6 +43,7 @@ export interface TrafficSummary {
}
export interface TrafficTrendPoint {
+ /** The bucket: a UTC day ("2026-10-17"), or an hour ("2026-10-17T13:00:00.000Z") in a 24-hour window. */
date: string;
[platform: string]: string | number;
}
@@ -304,8 +306,10 @@ export async function getTrafficTrend(
): Promise<TrafficTrendPoint[]> {
const supabase = await createClient();
const { from, to } = resolveTrafficWindow(window);
+ // A day or less reads hour by hour (AT-017); longer windows by day.
+ const hourly = Boolean(from && to && isHourlyWindow(from, to));
- // Group by day + platform, aggregated per batch (#450).
+ // Group by day (or hour) + platform, aggregated per batch (#450).
const dayMap = new Map<string, Map<string, number>>();
const allPlatforms = new Set<string>();
@@ -314,7 +318,8 @@ export async function getTrafficTrend(
brandId,
{ columns: 'source_platform, created_at, id', from, to, toInclusive: true },
(r) => {
- const day = (r.created_at as string).slice(0, 10);
+ const created = r.created_at as string;
+ const day = hourly ? utcHourKey(created) : created.slice(0, 10);
const platform = (r.source_platform as string) || 'unknown';
allPlatforms.add(platform);
@@ -326,7 +331,7 @@ export async function getTrafficTrend(
let days: string[];
if (from && to) {
- days = listUtcDays(from, to);
+ days = hourly ? listUtcHours(from, to) : listUtcDays(from, to);
} else {
days = [...dayMap.keys()].sort();
if (days.length > TRAFFIC_TREND_MAX_DAYS) {
diff --git a/web/src/lib/traffic-buckets.ts b/web/src/lib/traffic-buckets.ts
new file mode 100644
index 000000000..75868fbf7
--- /dev/null
+++ b/web/src/lib/traffic-buckets.ts
@@ -0,0 +1,32 @@
+/**
+ * How the AI Traffic trend buckets a window (AT-017, spec §3.01): hour by
+ * hour for a day or less, as the 24-hour range is; by day otherwise. Plain
+ * functions, so the server's loaders and the client can share them.
+ */
+
+const HOUR_MS = 3_600_000;
+
+/**
+ * Whether a window reads hour by hour: a day or less, as the 24-hour range
+ * is. An hour of slack keeps a window measured a little after its start on
+ * hours. Longer windows read by day.
+ */
+export function isHourlyWindow(from: string | undefined, to: string): boolean {
+ if (!from) return false;
+ return Date.parse(to) - Date.parse(from) <= 25 * HOUR_MS;
+}
+
+/** The UTC hours a window touches, as "2026-10-17T13:00:00.000Z" keys. */
+export function listUtcHours(from: string, to: string): string[] {
+ const hours: string[] = [];
+ const end = Date.parse(to);
+ for (let t = Math.floor(Date.parse(from) / HOUR_MS) * HOUR_MS; t <= end; t += HOUR_MS) {
+ hours.push(new Date(t).toISOString());
+ }
+ return hours;
+}
+
+/** The hour a timestamp falls in, as listUtcHours names it. */
+export function utcHourKey(iso: string): string {
+ return new Date(Math.floor(Date.parse(iso) / HOUR_MS) * HOUR_MS).toISOString();
+}
diff --git a/web/src/lib/traffic-export.test.ts b/web/src/lib/traffic-export.test.ts
index bb6d88fef..034faf4f0 100644
--- a/web/src/lib/traffic-export.test.ts
+++ b/web/src/lib/traffic-export.test.ts
@@ -154,6 +154,20 @@ describe('trafficTable', () => {
});
});
+ it('names the hours of a 24-hour trend in UTC', () => {
+ const trend = [
+ { date: '2026-10-17T13:00:00.000Z', 'chatgpt.com': 1 },
+ { date: '2026-10-17T14:00:00.000Z', 'chatgpt.com': 0 },
+ ];
+ expect(trafficTable('trend', data({ trend }), label)).toEqual({
+ headers: ['Hour (UTC)', 'ChatGPT'],
+ rows: [
+ ['2026-10-17 13:00', 1],
+ ['2026-10-17 14:00', 0],
+ ],
+ });
+ });
+
it('gives each visit with its page, full URL and pageviews', () => {
expect(trafficTable('visits', data(), label)).toEqual({
headers: ['Time (UTC)', 'Platform', 'Page', 'URL', 'Referrer', 'Country', 'Pageviews'],
diff --git a/web/src/lib/traffic-export.ts b/web/src/lib/traffic-export.ts
index 692720aa0..01a68dafd 100644
--- a/web/src/lib/traffic-export.ts
+++ b/web/src/lib/traffic-export.ts
@@ -119,9 +119,17 @@ function kpis(data: TrafficExportData, label: ExportLabel): ExportTable {
function trend(data: TrafficExportData, label: ExportLabel): ExportTable {
const points = data.trend ?? [];
const platforms = [...new Set(points.flatMap((p) => Object.keys(p).filter((k) => k !== 'date')))];
+ // The 24-hour range trends by hour (AT-017): "2026-10-17 13:00", UTC.
+ const hourly = points.some((p) => p.date.includes('T'));
return {
- headers: [label('columns.day'), ...platforms.map(getPlatformName)],
- rows: points.map((p) => [p.date, ...platforms.map((k) => Number(p[k]) || 0)]),
+ headers: [
+ hourly ? label('columns.hour') : label('columns.day'),
+ ...platforms.map(getPlatformName),
+ ],
+ rows: points.map((p) => [
+ hourly ? utcMinute(p.date) : p.date,
+ ...platforms.map((k) => Number(p[k]) || 0),
+ ]),
};
}
diff --git a/web/src/lib/traffic-range.test.ts b/web/src/lib/traffic-range.test.ts
new file mode 100644
index 000000000..9f57cbb27
--- /dev/null
+++ b/web/src/lib/traffic-range.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DEFAULT_TRAFFIC_PRESET,
+ TRAFFIC_RANGE_KEY,
+ readTrafficRange,
+ writeTrafficRange,
+} from './traffic-range';
+import { isHourlyWindow, listUtcHours, utcHourKey } from './traffic-buckets';
+
+/** AT-017: the page opens on the last 24 hours, or the member's last range. */
+
+function memoryStorage(initial?: string) {
+ const values = new Map<string, string>(
+ initial === undefined ? [] : [[TRAFFIC_RANGE_KEY, initial]],
+ );
+ return {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => void values.set(key, value),
+ values,
+ };
+}
+
+describe('readTrafficRange', () => {
+ it('opens on the last 24 hours the first time', () => {
+ expect(DEFAULT_TRAFFIC_PRESET).toBe('24h');
+ expect(readTrafficRange(memoryStorage())).toEqual({ preset: '24h', from: '', to: '' });
+ expect(readTrafficRange(null)).toEqual({ preset: '24h', from: '', to: '' });
+ });
+
+ it('opens on the last range chosen', () => {
+ expect(readTrafficRange(memoryStorage('{"preset":"30d"}'))).toEqual({
+ preset: '30d',
+ from: '',
+ to: '',
+ });
+ expect(
+ readTrafficRange(memoryStorage('{"preset":"custom","from":"2026-10-01","to":"2026-10-10"}')),
+ ).toEqual({ preset: 'custom', from: '2026-10-01', to: '2026-10-10' });
+ });
+
+ it('falls back to 24 hours on anything it cannot read', () => {
+ const fallback = { preset: '24h', from: '', to: '' };
+ expect(readTrafficRange(memoryStorage('not json'))).toEqual(fallback);
+ expect(readTrafficRange(memoryStorage('{"preset":"1y"}'))).toEqual(fallback);
+ const blocked = {
+ getItem: () => {
+ throw new Error('SecurityError');
+ },
+ };
+ expect(readTrafficRange(blocked)).toEqual(fallback);
+ });
+
+ it("keeps a custom range's days only when they are days", () => {
+ expect(
+ readTrafficRange(memoryStorage('{"preset":"custom","from":"yesterday","to":"2026-10-10"}')),
+ ).toEqual({ preset: 'custom', from: '', to: '2026-10-10' });
+ });
+});
+
+describe('writeTrafficRange', () => {
+ it('stores a preset, and a custom range with its days', () => {
+ const storage = memoryStorage();
+ writeTrafficRange(storage, { preset: '7d', from: '2026-10-01', to: '' });
+ expect(JSON.parse(storage.values.get(TRAFFIC_RANGE_KEY)!)).toEqual({
+ preset: '7d',
+ from: '',
+ to: '',
+ });
+ writeTrafficRange(storage, { preset: 'custom', from: '2026-10-01', to: '2026-10-10' });
+ expect(readTrafficRange(storage)).toEqual({
+ preset: 'custom',
+ from: '2026-10-01',
+ to: '2026-10-10',
+ });
+ });
+
+ it('does nothing when storage refuses the write', () => {
+ const full = {
+ setItem: () => {
+ throw new Error('QuotaExceededError');
+ },
+ };
+ expect(() => writeTrafficRange(full, { preset: '24h', from: '', to: '' })).not.toThrow();
+ });
+});
+
+describe('trend buckets', () => {
+ it('reads a day or less hour by hour, and longer windows by day', () => {
+ const to = '2026-10-18T13:00:00.000Z';
+ expect(isHourlyWindow('2026-10-17T13:00:00.000Z', to)).toBe(true);
+ expect(isHourlyWindow('2026-10-11T13:00:00.000Z', to)).toBe(false);
+ // All time has no start.
+ expect(isHourlyWindow(undefined, to)).toBe(false);
+ });
+
+ it('lists every hour of the last 24, on the hour', () => {
+ const hours = listUtcHours('2026-10-17T13:25:00.000Z', '2026-10-18T13:25:00.000Z');
+ expect(hours).toHaveLength(25);
+ expect(hours[0]).toBe('2026-10-17T13:00:00.000Z');
+ expect(hours[24]).toBe('2026-10-18T13:00:00.000Z');
+ });
+
+ it('puts a visit in the hour it happened', () => {
+ expect(utcHourKey('2026-10-17T09:30:12.123+00:00')).toBe('2026-10-17T09:00:00.000Z');
+ });
+});
diff --git a/web/src/lib/traffic-range.ts b/web/src/lib/traffic-range.ts
new file mode 100644
index 000000000..1ab367183
--- /dev/null
+++ b/web/src/lib/traffic-range.ts
@@ -0,0 +1,70 @@
+/**
+ * The AI Traffic page's range (AT-017, spec §3.01): it opens on the last 24
+ * hours and remembers the member's last choice. Client-side: the presets
+ * come from the range control. How a window is bucketed is traffic-buckets.ts.
+ */
+
+import { ALL_DATE_PRESETS, type DateRangePreset } from '@/components/filters/date-range-filter';
+
+/** The range a first visit opens on. */
+export const DEFAULT_TRAFFIC_PRESET: DateRangePreset = '24h';
+
+/** localStorage: the last range chosen, kept per browser like the app's other view settings. */
+export const TRAFFIC_RANGE_KEY = 'aeo:traffic-range';
+
+export interface TrafficRangeChoice {
+ preset: DateRangePreset;
+ /** A custom range's days (YYYY-MM-DD); empty for a preset. */
+ from: string;
+ to: string;
+}
+
+const DAY = /^\d{4}-\d{2}-\d{2}$/;
+
+/** The browser's localStorage, or null where reading it throws (blocked storage). */
+export function browserStorage(): Storage | null {
+ try {
+ return typeof window === 'undefined' ? null : window.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The remembered range, or the default. Anything unreadable — no storage
+ * (private mode), a value from an older shape, a preset that no longer
+ * exists — falls back to the default rather than throwing.
+ */
+export function readTrafficRange(
+ storage: Pick<Storage, 'getItem'> | null | undefined,
+): TrafficRangeChoice {
+ const fallback = { preset: DEFAULT_TRAFFIC_PRESET, from: '', to: '' };
+ try {
+ const raw = storage?.getItem(TRAFFIC_RANGE_KEY);
+ if (!raw) return fallback;
+ const value = JSON.parse(raw) as Partial<TrafficRangeChoice>;
+ if (!ALL_DATE_PRESETS.includes(value.preset as DateRangePreset)) return fallback;
+ const day = (d: unknown) => (typeof d === 'string' && DAY.test(d) ? d : '');
+ return value.preset === 'custom'
+ ? { preset: 'custom', from: day(value.from), to: day(value.to) }
+ : { preset: value.preset as DateRangePreset, from: '', to: '' };
+ } catch {
+ return fallback;
+ }
+}
+
+export function writeTrafficRange(
+ storage: Pick<Storage, 'setItem'> | null | undefined,
+ choice: TrafficRangeChoice,
+): void {
+ try {
+ storage?.setItem(
+ TRAFFIC_RANGE_KEY,
+ JSON.stringify(
+ choice.preset === 'custom' ? choice : { preset: choice.preset, from: '', to: '' },
+ ),
+ );
+ } catch {
+ // Storage full or blocked: the page still works, it just won't remember.
+ }
+}