Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat(date-selector): choose what the dashboard compares against (#1152)

Goldflag6c3a980fe40d
diff --git a/client/messages/cs.json b/client/messages/cs.json
index 58afacd29..018b7a40c 100644
--- a/client/messages/cs.json
+++ b/client/messages/cs.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Založ novou organizaci pro přidání webů a uživatelů",
"RgoiQm": "Předplatné se nepřenese",
"bo543i": "Můžeš vytvořit další organizaci, ale tvé aktuální předplatné platí pouze pro tvou současnou organizaci.",
+ "hCCWuZ": "Předchozí období",
+ "5xQQz7": "Stejné dny v týdnu",
+ "VB5EJL": "Stejné období loni",
+ "jWq9Z8": "Vlastní rozsah",
+ "Xh42fm": "Bez porovnání",
+ "YelS6o": "Porovnává se s {range}",
+ "mYMHgc": "Žádné srovnávací období",
+ "J32ri5": "Počáteční datum porovnání",
+ "oAzdD6": "Koncové datum porovnání",
"XnjTRS": "Posledních {hours} hodin",
"T+D/1o": "Posledních {minutes} minut",
"zWgbGg": "Dnes",
@@ -1405,8 +1414,6 @@
"Humfno": "Koncové datum",
"yc/tuy": "Koncový čas",
"H359cw": "Zadejte rozsah, který končí po svém začátku a nejpozději dnes",
- "YelS6o": "Porovnává se s {range}",
- "mYMHgc": "Žádné srovnávací období",
"ucusZJ": "Hledat časová pásma",
"kR140n": "Žádné odpovídající časové pásmo",
"EWw/tK": "Použít",
diff --git a/client/messages/de.json b/client/messages/de.json
index 111f0288c..d66f0a419 100644
--- a/client/messages/de.json
+++ b/client/messages/de.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Richten Sie eine neue Organisation ein, um Websites und Benutzer hinzuzufügen",
"RgoiQm": "Abonnement wird nicht übertragen",
"bo543i": "Sie können eine weitere Organisation erstellen, aber Ihr aktuelles Abonnement gilt nur für Ihre aktuelle Organisation.",
+ "hCCWuZ": "Vorheriger Zeitraum",
+ "5xQQz7": "Gleiche Wochentage",
+ "VB5EJL": "Gleicher Zeitraum im Vorjahr",
+ "jWq9Z8": "Benutzerdefinierter Zeitraum",
+ "Xh42fm": "Kein Vergleich",
+ "YelS6o": "Vergleich mit {range}",
+ "mYMHgc": "Kein Vergleichszeitraum",
+ "J32ri5": "Startdatum des Vergleichs",
+ "oAzdD6": "Enddatum des Vergleichs",
"XnjTRS": "Letzte {hours} Stunden",
"T+D/1o": "Letzte {minutes} Minuten",
"zWgbGg": "Heute",
@@ -1405,8 +1414,6 @@
"Humfno": "Enddatum",
"yc/tuy": "Endzeit",
"H359cw": "Geben Sie einen Zeitraum ein, der nach seinem Beginn endet und heute oder früher liegt",
- "YelS6o": "Vergleich mit {range}",
- "mYMHgc": "Kein Vergleichszeitraum",
"ucusZJ": "Zeitzonen suchen",
"kR140n": "Keine passende Zeitzone",
"EWw/tK": "Übernehmen",
diff --git a/client/messages/en.json b/client/messages/en.json
index bb042f87b..8e3a3ffcf 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Set up a new organization to add websites and users",
"RgoiQm": "Subscription Will Not Carry Over",
"bo543i": "You can create another organization, but your current subscription only applies to your current organization.",
+ "hCCWuZ": "Previous period",
+ "5xQQz7": "Matching weekdays",
+ "VB5EJL": "Same period last year",
+ "jWq9Z8": "Custom range",
+ "Xh42fm": "No comparison",
+ "YelS6o": "Compares against {range}",
+ "mYMHgc": "No comparison period",
+ "J32ri5": "Comparison start date",
+ "oAzdD6": "Comparison end date",
"XnjTRS": "Last {hours} hours",
"T+D/1o": "Last {minutes} minutes",
"zWgbGg": "Today",
@@ -1405,8 +1414,6 @@
"Humfno": "End date",
"yc/tuy": "End time",
"H359cw": "Enter a date range that ends after it starts, on or before today",
- "YelS6o": "Compares against {range}",
- "mYMHgc": "No comparison period",
"ucusZJ": "Search timezones",
"kR140n": "No matching timezone",
"EWw/tK": "Apply",
diff --git a/client/messages/es.json b/client/messages/es.json
index 057d4221e..f2a40b0f7 100644
--- a/client/messages/es.json
+++ b/client/messages/es.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Configura una nueva organización para añadir sitios web y usuarios",
"RgoiQm": "La suscripción no se transferirá",
"bo543i": "Puedes crear otra organización, pero tu suscripción actual solo se aplica a tu organización actual.",
+ "hCCWuZ": "Período anterior",
+ "5xQQz7": "Mismos días de la semana",
+ "VB5EJL": "Mismo período del año pasado",
+ "jWq9Z8": "Rango personalizado",
+ "Xh42fm": "Sin comparación",
+ "YelS6o": "Se compara con {range}",
+ "mYMHgc": "Sin periodo de comparación",
+ "J32ri5": "Fecha de inicio de la comparación",
+ "oAzdD6": "Fecha de fin de la comparación",
"XnjTRS": "Últimas {hours} horas",
"T+D/1o": "Últimos {minutes} minutos",
"zWgbGg": "Hoy",
@@ -1405,8 +1414,6 @@
"Humfno": "Fecha de fin",
"yc/tuy": "Hora de fin",
"H359cw": "Introduce un periodo que termine después de comenzar y no sea posterior a hoy",
- "YelS6o": "Se compara con {range}",
- "mYMHgc": "Sin periodo de comparación",
"ucusZJ": "Buscar zonas horarias",
"kR140n": "Ninguna zona horaria coincide",
"EWw/tK": "Aplicar",
diff --git a/client/messages/fr.json b/client/messages/fr.json
index d8f50c6bf..0ad2649c1 100644
--- a/client/messages/fr.json
+++ b/client/messages/fr.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Configurez une nouvelle organisation pour ajouter des sites web et des utilisateurs",
"RgoiQm": "L'abonnement ne sera pas transféré",
"bo543i": "Vous pouvez créer une autre organisation, mais votre abonnement actuel ne s'applique qu'à votre organisation actuelle.",
+ "hCCWuZ": "Période précédente",
+ "5xQQz7": "Mêmes jours de la semaine",
+ "VB5EJL": "Même période l’an dernier",
+ "jWq9Z8": "Plage personnalisée",
+ "Xh42fm": "Aucune comparaison",
+ "YelS6o": "Comparé à {range}",
+ "mYMHgc": "Aucune période de comparaison",
+ "J32ri5": "Date de début de la comparaison",
+ "oAzdD6": "Date de fin de la comparaison",
"XnjTRS": "{hours} dernières heures",
"T+D/1o": "{minutes} dernières minutes",
"zWgbGg": "Aujourd'hui",
@@ -1405,8 +1414,6 @@
"Humfno": "Date de fin",
"yc/tuy": "Heure de fin",
"H359cw": "Saisissez une période qui se termine après son début, aujourd’hui ou avant",
- "YelS6o": "Comparé à {range}",
- "mYMHgc": "Aucune période de comparaison",
"ucusZJ": "Rechercher un fuseau horaire",
"kR140n": "Aucun fuseau horaire correspondant",
"EWw/tK": "Appliquer",
diff --git a/client/messages/it.json b/client/messages/it.json
index 613757fd1..b130ed4a0 100644
--- a/client/messages/it.json
+++ b/client/messages/it.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Imposta una nuova organizzazione per aggiungere siti web e utenti",
"RgoiQm": "L'Abbonamento Non Verrà Trasferito",
"bo543i": "Puoi creare un'altra organizzazione, ma il tuo attuale abbonamento si applica solo all'organizzazione corrente.",
+ "hCCWuZ": "Periodo precedente",
+ "5xQQz7": "Stessi giorni della settimana",
+ "VB5EJL": "Stesso periodo dello scorso anno",
+ "jWq9Z8": "Intervallo personalizzato",
+ "Xh42fm": "Nessun confronto",
+ "YelS6o": "Confronto con {range}",
+ "mYMHgc": "Nessun periodo di confronto",
+ "J32ri5": "Data di inizio del confronto",
+ "oAzdD6": "Data di fine del confronto",
"XnjTRS": "Ultime {hours} ore",
"T+D/1o": "Ultimi {minutes} minuti",
"zWgbGg": "Oggi",
@@ -1405,8 +1414,6 @@
"Humfno": "Data di fine",
"yc/tuy": "Ora di fine",
"H359cw": "Inserisci un intervallo che termini dopo il suo inizio e non oltre oggi",
- "YelS6o": "Confronto con {range}",
- "mYMHgc": "Nessun periodo di confronto",
"ucusZJ": "Cerca fusi orari",
"kR140n": "Nessun fuso orario corrispondente",
"EWw/tK": "Applica",
diff --git a/client/messages/ja.json b/client/messages/ja.json
index 9c0dd4040..737946340 100644
--- a/client/messages/ja.json
+++ b/client/messages/ja.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "新しい組織を作成してウェブサイトとユーザーを追加",
"RgoiQm": "サブスクリプションは引き継がれません",
"bo543i": "別の組織を作成できますが、現在のサブスクリプションは現在の組織にのみ適用されます。",
+ "hCCWuZ": "前の期間",
+ "5xQQz7": "同じ曜日",
+ "VB5EJL": "前年の同期間",
+ "jWq9Z8": "カスタム範囲",
+ "Xh42fm": "比較なし",
+ "YelS6o": "{range} と比較",
+ "mYMHgc": "比較期間なし",
+ "J32ri5": "比較の開始日",
+ "oAzdD6": "比較の終了日",
"XnjTRS": "過去{hours}時間",
"T+D/1o": "過去{minutes}分",
"zWgbGg": "今日",
@@ -1405,8 +1414,6 @@
"Humfno": "終了日",
"yc/tuy": "終了時刻",
"H359cw": "開始より後に終わり、本日以前で終わる期間を入力してください",
- "YelS6o": "{range} と比較",
- "mYMHgc": "比較期間なし",
"ucusZJ": "タイムゾーンを検索",
"kR140n": "一致するタイムゾーンがありません",
"EWw/tK": "適用",
diff --git a/client/messages/ko.json b/client/messages/ko.json
index 7b5043e57..aba030522 100644
--- a/client/messages/ko.json
+++ b/client/messages/ko.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "웹사이트와 사용자를 추가할 새 조직을 설정하세요",
"RgoiQm": "구독이 이전되지 않습니다",
"bo543i": "다른 조직을 만들 수 있지만 현재 구독은 현재 조직에만 적용됩니다.",
+ "hCCWuZ": "이전 기간",
+ "5xQQz7": "같은 요일",
+ "VB5EJL": "작년 같은 기간",
+ "jWq9Z8": "사용자 지정 범위",
+ "Xh42fm": "비교 없음",
+ "YelS6o": "{range}과(와) 비교",
+ "mYMHgc": "비교 기간 없음",
+ "J32ri5": "비교 시작일",
+ "oAzdD6": "비교 종료일",
"XnjTRS": "최근 {hours}시간",
"T+D/1o": "최근 {minutes}분",
"zWgbGg": "오늘",
@@ -1405,8 +1414,6 @@
"Humfno": "종료 날짜",
"yc/tuy": "종료 시간",
"H359cw": "시작 이후에 끝나고 오늘 이전인 기간을 입력하세요",
- "YelS6o": "{range}과(와) 비교",
- "mYMHgc": "비교 기간 없음",
"ucusZJ": "시간대 검색",
"kR140n": "일치하는 시간대 없음",
"EWw/tK": "적용",
diff --git a/client/messages/pl.json b/client/messages/pl.json
index 7b68d881a..ee5e000d8 100644
--- a/client/messages/pl.json
+++ b/client/messages/pl.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Skonfiguruj nową organizację, aby dodać strony i użytkowników",
"RgoiQm": "Subskrypcja nie zostanie przeniesiona",
"bo543i": "Możesz utworzyć kolejną organizację, ale Twoja obecna subskrypcja dotyczy tylko bieżącej organizacji.",
+ "hCCWuZ": "Poprzedni okres",
+ "5xQQz7": "Te same dni tygodnia",
+ "VB5EJL": "Ten sam okres w zeszłym roku",
+ "jWq9Z8": "Zakres niestandardowy",
+ "Xh42fm": "Brak porównania",
+ "YelS6o": "Porównanie z {range}",
+ "mYMHgc": "Brak okresu porównawczego",
+ "J32ri5": "Data początkowa porównania",
+ "oAzdD6": "Data końcowa porównania",
"XnjTRS": "Ostatnie {hours} godzin",
"T+D/1o": "Ostatnie {minutes} minut",
"zWgbGg": "Dzisiaj",
@@ -1405,8 +1414,6 @@
"Humfno": "Data końcowa",
"yc/tuy": "Godzina końcowa",
"H359cw": "Podaj zakres, który kończy się po rozpoczęciu i nie wykracza poza dzisiaj",
- "YelS6o": "Porównanie z {range}",
- "mYMHgc": "Brak okresu porównawczego",
"ucusZJ": "Szukaj stref czasowych",
"kR140n": "Brak pasującej strefy czasowej",
"EWw/tK": "Zastosuj",
diff --git a/client/messages/pt.json b/client/messages/pt.json
index bfeca3685..52172a7bf 100644
--- a/client/messages/pt.json
+++ b/client/messages/pt.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Configure uma nova organização para adicionar sites e usuários",
"RgoiQm": "A Assinatura Não Será Transferida",
"bo543i": "Você pode criar outra organização, mas sua assinatura atual se aplica apenas à sua organização atual.",
+ "hCCWuZ": "Período anterior",
+ "5xQQz7": "Mesmos dias da semana",
+ "VB5EJL": "Mesmo período do ano passado",
+ "jWq9Z8": "Intervalo personalizado",
+ "Xh42fm": "Sem comparação",
+ "YelS6o": "Compara com {range}",
+ "mYMHgc": "Sem período de comparação",
+ "J32ri5": "Data de início da comparação",
+ "oAzdD6": "Data de fim da comparação",
"XnjTRS": "Últimas {hours} horas",
"T+D/1o": "Últimos {minutes} minutos",
"zWgbGg": "Hoje",
@@ -1405,8 +1414,6 @@
"Humfno": "Data de término",
"yc/tuy": "Hora de término",
"H359cw": "Informe um período que termine após o início e não ultrapasse hoje",
- "YelS6o": "Compara com {range}",
- "mYMHgc": "Sem período de comparação",
"ucusZJ": "Pesquisar fusos horários",
"kR140n": "Nenhum fuso horário correspondente",
"EWw/tK": "Aplicar",
diff --git a/client/messages/uk.json b/client/messages/uk.json
index c23eadb7d..e2aa039a9 100644
--- a/client/messages/uk.json
+++ b/client/messages/uk.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "Створіть нову організацію для додавання вебсайтів і користувачів",
"RgoiQm": "Підписка не переноситься",
"bo543i": "Ви можете створити іншу організацію, але ваша поточна підписка діє лише для вашої поточної організації.",
+ "hCCWuZ": "Попередній період",
+ "5xQQz7": "Ті самі дні тижня",
+ "VB5EJL": "Той самий період торік",
+ "jWq9Z8": "Власний діапазон",
+ "Xh42fm": "Без порівняння",
+ "YelS6o": "Порівняння з {range}",
+ "mYMHgc": "Немає періоду порівняння",
+ "J32ri5": "Початкова дата порівняння",
+ "oAzdD6": "Кінцева дата порівняння",
"XnjTRS": "Останні {hours} годин",
"T+D/1o": "Останні {minutes} хвилин",
"zWgbGg": "Сьогодні",
@@ -1405,8 +1414,6 @@
"Humfno": "Дата завершення",
"yc/tuy": "Час завершення",
"H359cw": "Введіть період, який завершується після початку й не пізніше сьогодні",
- "YelS6o": "Порівняння з {range}",
- "mYMHgc": "Немає періоду порівняння",
"ucusZJ": "Пошук часових поясів",
"kR140n": "Немає відповідного часового поясу",
"EWw/tK": "Застосувати",
diff --git a/client/messages/zh.json b/client/messages/zh.json
index eaa9128e9..178f7f24b 100644
--- a/client/messages/zh.json
+++ b/client/messages/zh.json
@@ -1377,6 +1377,15 @@
"qFQkeR": "设置一个新组织以添加网站和用户",
"RgoiQm": "订阅不会结转",
"bo543i": "您可以创建另一个组织,但您当前的订阅仅适用于您当前的组织。",
+ "hCCWuZ": "上一时段",
+ "5xQQz7": "相同星期",
+ "VB5EJL": "去年同期",
+ "jWq9Z8": "自定义范围",
+ "Xh42fm": "不对比",
+ "YelS6o": "对比 {range}",
+ "mYMHgc": "无对比时间段",
+ "J32ri5": "对比开始日期",
+ "oAzdD6": "对比结束日期",
"XnjTRS": "过去 {hours} 小时",
"T+D/1o": "过去 {minutes} 分钟",
"zWgbGg": "今天",
@@ -1405,8 +1414,6 @@
"Humfno": "结束日期",
"yc/tuy": "结束时间",
"H359cw": "请输入结束时间晚于开始时间、且不晚于今天的时间范围",
- "YelS6o": "对比 {range}",
- "mYMHgc": "无对比时间段",
"ucusZJ": "搜索时区",
"kR140n": "没有匹配的时区",
"EWw/tK": "应用",
diff --git a/client/src/api/analytics/useAnalyticsQuery.ts b/client/src/api/analytics/useAnalyticsQuery.ts
index 7398ac359..29f01b163 100644
--- a/client/src/api/analytics/useAnalyticsQuery.ts
+++ b/client/src/api/analytics/useAnalyticsQuery.ts
@@ -51,6 +51,8 @@ export interface AnalyticsContextOptions {
export function useAnalyticsContext(options: AnalyticsContextOptions = {}): {
site: number | string;
context: AnalyticsContext;
+ /** False when the request has no window to ask for — comparison turned off. */
+ hasPeriod: boolean;
} {
const storeSite = useStore(state => state.site);
const time = useStore(state => state.time);
@@ -61,9 +63,11 @@ export function useAnalyticsContext(options: AnalyticsContextOptions = {}): {
const site = options.site ?? storeSite;
const baseTime = options.overrideTime ?? time;
+ // A comparison of "none" leaves previousTime null: there is no window to ask
+ // about, so the query is disabled rather than falling through to all-time.
let timeToUse = options.periodTime === "previous" ? previousTime : baseTime;
- if (options.doublePastMinutesForPrevious && options.periodTime === "previous" && timeToUse.mode === "past-minutes") {
+ if (options.doublePastMinutesForPrevious && options.periodTime === "previous" && timeToUse?.mode === "past-minutes") {
timeToUse = {
...timeToUse,
pastMinutesStart: timeToUse.pastMinutesStart * 2,
@@ -82,8 +86,9 @@ export function useAnalyticsContext(options: AnalyticsContextOptions = {}): {
return {
site,
+ hasPeriod: timeToUse !== null,
context: {
- time: (options.useTime ?? true) ? timeToUse : null,
+ time: (options.useTime ?? true) && timeToUse ? timeToUse : null,
timeZone,
filters: combinedFilters,
},
@@ -91,8 +96,8 @@ export function useAnalyticsContext(options: AnalyticsContextOptions = {}): {
}
function useAnalyticsRequest(options: AnalyticsContextOptions & AnalyticsDescriptor) {
- const { site, context } = useAnalyticsContext(options);
- return { site, request: buildAnalyticsRequest(options, context) };
+ const { site, context, hasPeriod } = useAnalyticsContext(options);
+ return { site, hasPeriod, request: buildAnalyticsRequest(options, context) };
}
export interface AnalyticsQueryOptions<TData> extends AnalyticsContextOptions, AnalyticsDescriptor {
@@ -115,7 +120,7 @@ const buildQueryKey = (
) => [...(Array.isArray(key) ? key : [key]), site, request.path, request.params, request.body];
export function useAnalyticsQuery<TData>(options: AnalyticsQueryOptions<TData>): UseQueryResult<TData> {
- const { site, request } = useAnalyticsRequest(options);
+ const { site, request, hasPeriod } = useAnalyticsRequest(options);
return useQuery<TData, Error>({
queryKey: buildQueryKey(options.key, site, request),
@@ -127,7 +132,7 @@ export function useAnalyticsQuery<TData>(options: AnalyticsQueryOptions<TData>):
? (previousData, previousQuery) =>
site !== undefined && previousQuery?.queryKey?.includes(site) ? previousData : undefined
: undefined,
- enabled: (options.enabled ?? true) && !!site,
+ enabled: (options.enabled ?? true) && !!site && hasPeriod,
...options.props,
});
}
@@ -148,7 +153,7 @@ export interface AnalyticsInfiniteQueryOptions<TPage, TCursor> extends Analytics
export function useAnalyticsInfiniteQuery<TPage, TCursor = number>(
options: AnalyticsInfiniteQueryOptions<TPage, TCursor>
): UseInfiniteQueryResult<InfiniteData<TPage>> {
- const { site, request } = useAnalyticsRequest(options);
+ const { site, request, hasPeriod } = useAnalyticsRequest(options);
return useInfiniteQuery<TPage, Error, InfiniteData<TPage>, readonly unknown[], TCursor>({
queryKey: [...buildQueryKey(options.key, site, request), "infinite"],
@@ -162,7 +167,7 @@ export function useAnalyticsInfiniteQuery<TPage, TCursor = number>(
staleTime: options.staleTime ?? 60_000,
refetchInterval: options.refetchInterval,
refetchOnWindowFocus: options.refetchOnWindowFocus,
- enabled: (options.enabled ?? true) && !!site,
+ enabled: (options.enabled ?? true) && !!site && hasPeriod,
});
}
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 0d6d99984..8d57db255 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -82,7 +82,7 @@ export function Chart({
// Previous points are time-shifted onto the current period's x-axis, but
// keep originalTime so the tooltip can show the real previous date.
- const { min: prevMin } = getChartTimeBounds(previousTime, bucket, timezone);
+ const prevMin = previousTime ? getChartTimeBounds(previousTime, bucket, timezone).min : undefined;
const offsetMs = cMin && prevMin ? cMin.getTime() - prevMin.getTime() : 0;
const previousPoints: PrevPoint[] = [];
previousData?.forEach(e => {
diff --git a/client/src/app/[site]/main/components/MainSection/Overview.tsx b/client/src/app/[site]/main/components/MainSection/Overview.tsx
index 107fdbbab..c0ef8e4e2 100644
--- a/client/src/app/[site]/main/components/MainSection/Overview.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Overview.tsx
@@ -9,7 +9,7 @@ import { useExtracted } from "next-intl";
import { useState } from "react";
import { useGetOverview } from "../../../../../api/analytics/hooks/useGetOverview";
import { useGetOverviewBucketed } from "../../../../../api/analytics/hooks/useGetOverviewBucketed";
-import { StatType, useStore } from "../../../../../lib/store";
+import { StatType, useComparisonEnabled, useStore } from "../../../../../lib/store";
import { SparklinesChart } from "./SparklinesChart";
export const ChangePercentage = ({
@@ -21,8 +21,13 @@ export const ChangePercentage = ({
previous: number;
reverseColor?: boolean;
}) => {
+ const comparisonEnabled = useComparisonEnabled();
const change = ((current - previous) / previous) * 100;
+ // Nothing to compare against: a delta here would be a percentage of a period
+ // the user has explicitly stopped asking for.
+ if (!comparisonEnabled) return null;
+
if (previous === 0) {
if (current === 0) {
return <div className="text-sm">0%</div>;
diff --git a/client/src/app/[site]/pages/components/PagesTable.tsx b/client/src/app/[site]/pages/components/PagesTable.tsx
index 9190c1d3d..4bf970e9e 100644
--- a/client/src/app/[site]/pages/components/PagesTable.tsx
+++ b/client/src/app/[site]/pages/components/PagesTable.tsx
@@ -17,7 +17,7 @@ import { useGetPageTitlesPaginated } from "@/api/analytics/hooks/useGetPageTitle
import { PageTitleItem } from "@/api/analytics/endpoints";
import { ErrorState } from "@/components/ErrorState";
import { Pagination } from "@/components/pagination";
-import { useStore } from "@/lib/store";
+import { useComparisonEnabled, useStore } from "@/lib/store";
import { formatShortDuration } from "@/lib/dateTimeUtils";
import { cn, truncateString } from "@/lib/utils";
import { PageSparklineChart } from "./PageSparklineChart";
@@ -29,6 +29,9 @@ const MAX_TITLE_LENGTH = 80;
const columnHelper = createColumnHelper<PageTitleItem>();
function ChangePercentage({ current, previous }: { current: number; previous: number }) {
+ const comparisonEnabled = useComparisonEnabled();
+ if (!comparisonEnabled) return null;
+
if (previous === 0) {
if (current === 0) return null;
return <span className="text-xs text-green-400">+999%</span>;
diff --git a/client/src/app/[site]/performance/components/PerformanceOverview.tsx b/client/src/app/[site]/performance/components/PerformanceOverview.tsx
index bfedf7111..995e575a0 100644
--- a/client/src/app/[site]/performance/components/PerformanceOverview.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceOverview.tsx
@@ -7,13 +7,16 @@ import NumberFlow from "@number-flow/react";
import { TrendingDown, TrendingUp } from "lucide-react";
import { useGetPerformanceOverview } from "../../../../api/analytics/hooks/performance/useGetPerformanceOverview";
import { Card, CardContent, CardLoader } from "../../../../components/ui/card";
-import { useStore } from "../../../../lib/store";
+import { useComparisonEnabled, useStore } from "../../../../lib/store";
import { PerformanceMetric, usePerformanceStore } from "../performanceStore";
import { formatMetricValue, getMetricColor, getMetricUnit } from "../utils/performanceUtils";
import { PercentileSelector } from "./PercentileSelector";
import { MetricTooltip } from "./shared/MetricTooltip";
const ChangePercentage = ({ current, previous }: { current: number; previous: number }) => {
+ const comparisonEnabled = useComparisonEnabled();
+ if (!comparisonEnabled) return null;
+
const change = ((current - previous) / previous) * 100;
if (previous === 0) {
diff --git a/client/src/components/DateSelector/ComparisonSelect.tsx b/client/src/components/DateSelector/ComparisonSelect.tsx
new file mode 100644
index 000000000..bddb26e8e
--- /dev/null
+++ b/client/src/components/DateSelector/ComparisonSelect.tsx
@@ -0,0 +1,158 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { availableComparisonModes, getAbsoluteBounds, resolveComparison } from "@/lib/time";
+import { cn } from "@/lib/utils";
+import { Check, ChevronDown } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useState } from "react";
+import { describeBounds, rangeFieldsForTime, timeFromRangeFields } from "./rangeFields";
+import { Comparison, ComparisonMode, Time } from "./types";
+
+type CustomFields = { startDate: string; endDate: string };
+
+const customFieldsFor = (time: Time, zone: string): CustomFields => {
+ const { startDate, endDate } = rangeFieldsForTime(time, zone);
+ return { startDate, endDate };
+};
+
+const timeFromCustomFields = (fields: CustomFields, zone: string, maxDate: string): Time | null =>
+ timeFromRangeFields({ ...fields, startTime: "", endTime: "" }, zone, maxDate);
+
+/**
+ * The panel's footer already said what the dashboard compares against; this
+ * turns that sentence into the control that changes it. Nothing new appears in
+ * the toolbar, and the choice sits next to the range it modifies.
+ */
+export function ComparisonSelect({
+ time,
+ comparison,
+ zone,
+ maxDate,
+ onChange,
+}: {
+ /** The drafted period the comparison is resolved against. */
+ time: Time;
+ comparison: Comparison;
+ zone: string;
+ /** The dashboard's today — a comparison window cannot end after it. */
+ maxDate: string;
+ onChange: (comparison: Comparison) => void;
+}) {
+ const t = useExtracted();
+ const [open, setOpen] = useState(false);
+
+ const resolved = resolveComparison(time, comparison, zone);
+
+ // The custom window is held as fields rather than read back off the draft, so
+ // a cleared date input does not snap back to the last value under the cursor.
+ const [customFields, setCustomFields] = useState<CustomFields>(() =>
+ customFieldsFor(comparison.customTime ?? resolved ?? time, zone)
+ );
+
+ const labels: Record<ComparisonMode, string> = {
+ previous: t("Previous period"),
+ weekday: t("Matching weekdays"),
+ year: t("Same period last year"),
+ custom: t("Custom range"),
+ none: t("No comparison"),
+ };
+
+ // "Mar 8 – Mar 14" says nothing useful when the window is a year back, so the
+ // year is named whenever it differs from the period being compared.
+ const describe = (target: Time | null) => {
+ const bounds = target && getAbsoluteBounds(target, zone);
+ const label = describeBounds(bounds ?? null);
+ const current = getAbsoluteBounds(time, zone);
+ if (!bounds || !label || !current) return label;
+
+ const year = bounds.end.minus({ minutes: 1 }).year;
+ return year === current.end.minus({ minutes: 1 }).year ? label : `${label}, ${year}`;
+ };
+
+ const resolvedRange = describe(resolved);
+
+ const selectMode = (mode: ComparisonMode) => {
+ if (mode === "custom") {
+ const seeded = comparison.customTime ? customFields : customFieldsFor(resolved ?? time, zone);
+ setCustomFields(seeded);
+ onChange({ mode, customTime: timeFromCustomFields(seeded, zone, maxDate) ?? undefined });
+ return;
+ }
+
+ onChange({ mode });
+ setOpen(false);
+ };
+
+ const editCustom = (key: keyof CustomFields, value: string) => {
+ const next = { ...customFields, [key]: value };
+ setCustomFields(next);
+
+ // A half-edited window keeps the last usable one applied — the dashboard
+ // should not blank its comparison line between two keystrokes.
+ const parsed = timeFromCustomFields(next, zone, maxDate);
+ if (parsed) onChange({ mode: "custom", customTime: parsed });
+ };
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" size="xs" className="text-neutral-500 dark:text-neutral-400">
+ {resolvedRange ? t("Compares against {range}", { range: resolvedRange }) : t("No comparison period")}
+ <ChevronDown className="h-3 w-3" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[312px] p-1">
+ {availableComparisonModes(time).map(mode => {
+ const selected = comparison.mode === mode;
+ const range = mode === "none" ? null : describe(resolveComparison(time, { ...comparison, mode }, zone));
+
+ return (
+ <div key={mode}>
+ <button
+ type="button"
+ onClick={() => selectMode(mode)}
+ aria-pressed={selected}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-200 dark:hover:bg-neutral-800",
+ selected && "font-medium"
+ )}
+ >
+ <span className="whitespace-nowrap">{labels[mode]}</span>
+ <span className="ml-auto whitespace-nowrap text-[11px] tabular-nums text-neutral-500 dark:text-neutral-400">
+ {range}
+ </span>
+ <Check className={cn("h-3.5 w-3.5 shrink-0", !selected && "invisible")} />
+ </button>
+
+ {mode === "custom" && selected && (
+ <div className="flex gap-1.5 px-2 pb-2 pt-1">
+ <Input
+ type="date"
+ inputSize="sm"
+ aria-label={t("Comparison start date")}
+ value={customFields.startDate}
+ max={maxDate}
+ onChange={event => editCustom("startDate", event.target.value)}
+ className="min-w-0 flex-1"
+ />
+ <Input
+ type="date"
+ inputSize="sm"
+ aria-label={t("Comparison end date")}
+ value={customFields.endDate}
+ max={maxDate}
+ onChange={event => editCustom("endDate", event.target.value)}
+ className="min-w-0 flex-1"
+ />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/client/src/components/DateSelector/DateSelector.test.tsx b/client/src/components/DateSelector/DateSelector.test.tsx
index 835fbd318..edab6b30d 100644
--- a/client/src/components/DateSelector/DateSelector.test.tsx
+++ b/client/src/components/DateSelector/DateSelector.test.tsx
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DateSelector } from "./DateSelector";
import { Time } from "./types";
-const mocks = vi.hoisted(() => ({ timezone: "America/New_York", setTimezone: vi.fn() }));
+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>) =>
@@ -12,7 +12,13 @@ vi.mock("next-intl", () => ({
}));
vi.mock("@/lib/store", () => ({
- useStore: () => ({ timezone: mocks.timezone, setTimezone: mocks.setTimezone, bucket: "day" }),
+ useStore: () => ({
+ timezone: mocks.timezone,
+ setTimezone: mocks.setTimezone,
+ bucket: "day",
+ comparison: { mode: "previous" },
+ setComparison: mocks.setComparison,
+ }),
useTimezone: () => (mocks.timezone === "system" ? "America/New_York" : mocks.timezone),
}));
diff --git a/client/src/components/DateSelector/DateSelector.tsx b/client/src/components/DateSelector/DateSelector.tsx
index b67b38eb9..1d3f0b606 100644
--- a/client/src/components/DateSelector/DateSelector.tsx
+++ b/client/src/components/DateSelector/DateSelector.tsx
@@ -47,7 +47,7 @@ export function DateSelector({
setTime: (time: Time) => void;
pastMinutesEnabled?: boolean;
}) {
- const { timezone, setTimezone, bucket } = useStore();
+ const { timezone, setTimezone, bucket, comparison, setComparison } = useStore();
const zone = useTimezone();
const t = useExtracted();
const presetLabels = usePresetLabels();
@@ -154,8 +154,10 @@ export function DateSelector({
zone={zone}
timezone={timezone}
setTimezone={setTimezone}
+ comparison={comparison}
pastMinutesEnabled={pastMinutesEnabled}
- onApply={nextTime => {
+ onApply={(nextTime, nextComparison) => {
+ setComparison(nextComparison);
setTime(nextTime);
setOpen(false);
}}
diff --git a/client/src/components/DateSelector/RangePanel.test.tsx b/client/src/components/DateSelector/RangePanel.test.tsx
index 48454409f..ae833b5d1 100644
--- a/client/src/components/DateSelector/RangePanel.test.tsx
+++ b/client/src/components/DateSelector/RangePanel.test.tsx
@@ -3,7 +3,7 @@ import { DateTime } from "luxon";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RangePanel } from "./RangePanel";
-import { Time } from "./types";
+import { Comparison, DEFAULT_COMPARISON, Time } from "./types";
vi.mock("next-intl", () => ({
useExtracted: () => (message: string, values?: Record<string, string>) =>
@@ -16,10 +16,11 @@ const onApply = vi.fn();
const onCancel = vi.fn();
const setTimezone = vi.fn();
-const renderPanel = (time: Time, props: { pastMinutesEnabled?: boolean } = {}) =>
+const renderPanel = (time: Time, props: { pastMinutesEnabled?: boolean; comparison?: Comparison } = {}) =>
render(
<RangePanel
time={time}
+ comparison={props.comparison ?? DEFAULT_COMPARISON}
zone={ZONE}
timezone="America/New_York"
setTimezone={setTimezone}
@@ -127,7 +128,10 @@ describe("RangePanel draft", () => {
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
- expect(onApply).toHaveBeenCalledWith({ mode: "range", startDate: "2024-03-20", endDate: "2024-03-25" });
+ expect(onApply).toHaveBeenCalledWith(
+ { mode: "range", startDate: "2024-03-20", endDate: "2024-03-25" },
+ DEFAULT_COMPARISON
+ );
});
it("a fresh click starts a new range rather than extending the old one", () => {
@@ -146,7 +150,7 @@ describe("RangePanel draft", () => {
fireEvent.click(day("3/20/2024"));
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
- expect(onApply).toHaveBeenCalledWith({ mode: "day", day: "2024-03-20" });
+ expect(onApply).toHaveBeenCalledWith({ mode: "day", day: "2024-03-20" }, DEFAULT_COMPARISON);
});
it("typing a clock promotes the window to an exact datetime range", () => {
@@ -156,13 +160,16 @@ describe("RangePanel draft", () => {
fireEvent.change(screen.getByLabelText("End time"), { target: { value: "17:00" } });
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
- expect(onApply).toHaveBeenCalledWith({
- mode: "range",
- startDate: "2024-03-08",
- startTime: "09:30:00",
- endDate: "2024-03-14",
- endTime: "17:00:00",
- });
+ expect(onApply).toHaveBeenCalledWith(
+ {
+ mode: "range",
+ startDate: "2024-03-08",
+ startTime: "09:30:00",
+ endDate: "2024-03-14",
+ endTime: "17:00:00",
+ },
+ DEFAULT_COMPARISON
+ );
});
it("typing a date is not clobbered mid-edit by an unparseable intermediate value", () => {
@@ -176,7 +183,10 @@ describe("RangePanel draft", () => {
expect(endDate.value).toBe("2024-03-11");
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
- expect(onApply).toHaveBeenCalledWith({ mode: "range", startDate: "2024-03-08", endDate: "2024-03-11" });
+ expect(onApply).toHaveBeenCalledWith(
+ { mode: "range", startDate: "2024-03-08", endDate: "2024-03-11" },
+ DEFAULT_COMPARISON
+ );
});
it("keeps the clocks when the days move under them", () => {
@@ -192,13 +202,16 @@ describe("RangePanel draft", () => {
fireEvent.click(day("3/25/2024"));
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
- expect(onApply).toHaveBeenCalledWith({
- mode: "range",
- startDate: "2024-03-20",
- startTime: "09:30:00",
- endDate: "2024-03-25",
- endTime: "17:00:00",
- });
+ expect(onApply).toHaveBeenCalledWith(
+ {
+ mode: "range",
+ startDate: "2024-03-20",
+ startTime: "09:30:00",
+ endDate: "2024-03-25",
+ endTime: "17:00:00",
+ },
+ DEFAULT_COMPARISON
+ );
});
it("keeps an overnight clock through the first of the two clicks", () => {
@@ -216,13 +229,16 @@ describe("RangePanel draft", () => {
fireEvent.click(day("3/25/2024"));
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
- expect(onApply).toHaveBeenCalledWith({
- mode: "range",
- startDate: "2024-03-20",
- startTime: "17:00:00",
- endDate: "2024-03-25",
- endTime: "09:00:00",
- });
+ expect(onApply).toHaveBeenCalledWith(
+ {
+ mode: "range",
+ startDate: "2024-03-20",
+ startTime: "17:00:00",
+ endDate: "2024-03-25",
+ endTime: "09:00:00",
+ },
+ DEFAULT_COMPARISON
+ );
});
it("refuses to apply while the fields do not describe a window", () => {
@@ -240,7 +256,10 @@ describe("RangePanel draft", () => {
fireEvent.change(screen.getByLabelText("End date"), { target: { value: "2024-03-12" } });
expect((screen.getByRole("button", { name: "Apply" }) as HTMLButtonElement).disabled).toBe(false);
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
- expect(onApply).toHaveBeenCalledWith({ mode: "range", startDate: "2024-03-08", endDate: "2024-03-12" });
+ expect(onApply).toHaveBeenCalledWith(
+ { mode: "range", startDate: "2024-03-08", endDate: "2024-03-12" },
+ DEFAULT_COMPARISON
+ );
});
it("refuses a typed date past today, which the calendar already disables", () => {
@@ -284,6 +303,57 @@ describe("RangePanel footer", () => {
expect(screen.getByText("No comparison period")).toBeTruthy();
});
+ it("changes what the dashboard compares against, and applies it with the period", () => {
+ renderPanel(DATE_RANGE);
+
+ fireEvent.click(screen.getByRole("button", { name: /Compares against/ }));
+ fireEvent.click(screen.getByRole("button", { name: /Same period last year/ }));
+
+ // drafted, not applied: the dashboard does not move until Apply
+ expect(onApply).not.toHaveBeenCalled();
+ expect(screen.getByText("Compares against Mar 8 – Mar 14, 2023")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Apply" }));
+ expect(onApply).toHaveBeenCalledWith(DATE_RANGE, { mode: "year" });
+ });
+
+ it("turns the comparison off entirely", () => {
+ renderPanel(DATE_RANGE);
+
+ fireEvent.click(screen.getByRole("button", { name: /Compares against/ }));
+ fireEvent.click(screen.getByRole("button", { name: /No comparison/ }));
+
+ expect(screen.getByText("No comparison period")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Apply" }));
+ expect(onApply).toHaveBeenCalledWith(DATE_RANGE, { mode: "none" });
+ });
+
+ it("offers only the comparisons a realtime window can answer", () => {
+ renderPanel({ mode: "past-minutes", pastMinutesStart: 30, pastMinutesEnd: 0 });
+
+ fireEvent.click(screen.getByRole("button", { name: /Compares against/ }));
+
+ expect(screen.getByRole("button", { name: /Previous period/ })).toBeTruthy();
+ expect(screen.queryByRole("button", { name: /Same period last year/ })).toBeNull();
+ expect(screen.queryByRole("button", { name: /Matching weekdays/ })).toBeNull();
+ });
+
+ it("compares against a window typed by hand", () => {
+ renderPanel(DATE_RANGE);
+
+ fireEvent.click(screen.getByRole("button", { name: /Compares against/ }));
+ fireEvent.click(screen.getByRole("button", { name: /Custom range/ }));
+
+ fireEvent.change(screen.getByLabelText("Comparison start date"), { target: { value: "2023-12-01" } });
+ fireEvent.change(screen.getByLabelText("Comparison end date"), { target: { value: "2023-12-07" } });
+
+ fireEvent.click(screen.getByRole("button", { name: "Apply" }));
+ expect(onApply).toHaveBeenCalledWith(DATE_RANGE, {
+ mode: "custom",
+ customTime: { mode: "range", startDate: "2023-12-01", endDate: "2023-12-07" },
+ });
+ });
+
it("surfaces the timezone and lets it be searched", async () => {
renderPanel(DATE_RANGE);
diff --git a/client/src/components/DateSelector/RangePanel.tsx b/client/src/components/DateSelector/RangePanel.tsx
index 9aa49ce4b..cf106fa81 100644
--- a/client/src/components/DateSelector/RangePanel.tsx
+++ b/client/src/components/DateSelector/RangePanel.tsx
@@ -16,22 +16,17 @@ import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { timezones } from "@/lib/dateTimeUtils";
import { getDashboardTimeForRange, type DashboardDefaultTimeRange } from "@/lib/defaultTimeRange";
-import { deriveTimeState, getAbsoluteBounds } from "@/lib/time";
+import { getAbsoluteBounds } from "@/lib/time";
import { cn } from "@/lib/utils";
import { DateTime } from "luxon";
import { Check, Globe } from "lucide-react";
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 {
- describeBounds,
- rangeFieldsForTime,
- timeFromRangeFields,
- timeFromSelectedDays,
- type RangeFields,
-} from "./rangeFields";
-import { Time } from "./types";
+import { rangeFieldsForTime, timeFromRangeFields, timeFromSelectedDays, type RangeFields } from "./rangeFields";
+import { Comparison, Time } from "./types";
/**
* react-day-picker works in whole calendar days in the browser's zone, so days
@@ -44,6 +39,7 @@ const fromCalendarDate = (date: Date) => DateTime.fromJSDate(date).toISODate() ?
export function RangePanel({
time,
+ comparison,
zone,
timezone,
setTimezone,
@@ -52,13 +48,14 @@ export function RangePanel({
onCancel,
}: {
time: Time;
+ comparison: Comparison;
/** The resolved IANA zone — never the "system" sentinel. */
zone: string;
/** The stored preference, which may be "system". */
timezone: string;
setTimezone: (timezone: string) => void;
pastMinutesEnabled: boolean;
- onApply: (time: Time) => void;
+ onApply: (time: Time, comparison: Comparison) => void;
onCancel: () => void;
}) {
const t = useExtracted();
@@ -93,6 +90,10 @@ export function RangePanel({
invalid?: boolean;
}>(() => ({ time, fields: rangeFieldsForTime(time, zone) }));
+ // The comparison is drafted alongside the period: picking one should no more
+ // refire every query than dragging a range does.
+ const [draftComparison, setDraftComparison] = useState<Comparison>(comparison);
+
const setDraftTime = (next: Time) => setDraft({ time: next, fields: rangeFieldsForTime(next, zone) });
const editField = (key: keyof RangeFields, value: string) =>
@@ -132,10 +133,8 @@ export function RangePanel({
const months = isWide === false ? 1 : 2;
const lastMonth = DateTime.fromISO(todayHere).startOf("month");
- const { previousTime } = deriveTimeState(draft.time, zone);
- const comparison = describeBounds(getAbsoluteBounds(previousTime, zone));
-
- const applyPreset = (preset: DashboardDefaultTimeRange) => onApply(getDashboardTimeForRange(preset, zone));
+ const applyPreset = (preset: DashboardDefaultTimeRange) =>
+ onApply(getDashboardTimeForRange(preset, zone), draftComparison);
return (
<div className="flex flex-col">
@@ -227,18 +226,21 @@ export function RangePanel({
</div>
<div className="flex flex-wrap items-center gap-2 border-t border-neutral-150 px-3 py-2 dark:border-neutral-800">
- <span
- className={cn(
- "mr-auto text-xs text-neutral-500 dark:text-neutral-400",
- draft.invalid && "text-red-500 dark:text-red-400"
- )}
- >
- {draft.invalid
- ? t("Enter a date range that ends after it starts, on or before today")
- : comparison
- ? t("Compares against {range}", { range: comparison })
- : t("No comparison period")}
- </span>
+ {draft.invalid ? (
+ <span className="mr-auto text-xs text-red-500 dark:text-red-400">
+ {t("Enter a date range that ends after it starts, on or before today")}
+ </span>
+ ) : (
+ <span className="mr-auto">
+ <ComparisonSelect
+ time={draft.time}
+ comparison={draftComparison}
+ zone={zone}
+ maxDate={todayHere}
+ onChange={setDraftComparison}
+ />
+ </span>
+ )}
<Popover open={timezoneOpen} onOpenChange={setTimezoneOpen}>
<PopoverTrigger asChild>
@@ -276,7 +278,12 @@ export function RangePanel({
<Button variant="ghost" size="sm" onClick={onCancel}>
{t("Cancel")}
</Button>
- <Button variant="accent" size="sm" disabled={draft.invalid} onClick={() => onApply(draft.time)}>
+ <Button
+ variant="accent"
+ size="sm"
+ disabled={draft.invalid}
+ onClick={() => onApply(draft.time, draftComparison)}
+ >
{t("Apply")}
</Button>
</div>
diff --git a/client/src/components/DateSelector/types.ts b/client/src/components/DateSelector/types.ts
index e56a1d08a..a0bb9813c 100644
--- a/client/src/components/DateSelector/types.ts
+++ b/client/src/components/DateSelector/types.ts
@@ -62,3 +62,18 @@ export type Time =
| YearMode
| AllTimeMode
| PastMinutesMode;
+
+/**
+ * What the dashboard's comparison line is drawn against. Everything but
+ * `custom` is derived from the selected period; `none` turns the comparison
+ * off entirely.
+ */
+export type ComparisonMode = "previous" | "weekday" | "year" | "custom" | "none";
+
+export type Comparison = {
+ mode: ComparisonMode;
+ /** Only read when `mode` is `"custom"`. */
+ customTime?: Time;
+};
+
+export const DEFAULT_COMPARISON: Comparison = { mode: "previous" };
diff --git a/client/src/lib/parsers.ts b/client/src/lib/parsers.ts
index 8a5eead8f..a82a7d264 100644
--- a/client/src/lib/parsers.ts
+++ b/client/src/lib/parsers.ts
@@ -2,7 +2,7 @@ import { Filter, FilterParameter, FilterType, TimeBucket } from "@rybbit/shared"
import { createParser, parseAsBoolean, parseAsInteger, parseAsJson, parseAsString, parseAsStringEnum } from "nuqs";
import { DASHBOARD_DEFAULT_TIME_RANGES } from "./defaultTimeRange";
import { StatType } from "./store";
-import { Time } from "@/components/DateSelector/types";
+import { ComparisonMode, Time } from "@/components/DateSelector/types";
// Basic parsers
export const parseAsOptionalString = parseAsString;
@@ -41,6 +41,11 @@ const timeModeValues: string[] = ["day", "range", "week", "month", "year", "all-
export const parseAsTimeMode = parseAsStringEnum(timeModeValues);
+// Comparison mode parser — what the dashboard's comparison line is drawn from.
+const comparisonModeValues: ComparisonMode[] = ["previous", "weekday", "year", "custom", "none"];
+
+export const parseAsComparisonMode = parseAsStringEnum<ComparisonMode>(comparisonModeValues);
+
// Well-known preset parser — the preset list lives in defaultTimeRange.ts.
export const parseAsWellKnown = parseAsStringEnum<string>([...DASHBOARD_DEFAULT_TIME_RANGES]);
@@ -151,6 +156,11 @@ export const analyticsParsers = {
past_minutes_start: parseAsInteger,
past_minutes_end: parseAsInteger,
+ // Comparison parameters
+ compare: parseAsComparisonMode,
+ compareStart: parseAsIsoDate,
+ compareEnd: parseAsIsoDate,
+
// Display parameters
bucket: parseAsTimeBucket,
stat: parseAsStatType,
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index 5f4db2ab6..e40b4897a 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -2,14 +2,15 @@ import { Filter, FilterParameter, TimeBucket } from "@rybbit/shared";
import { DateTime } from "luxon";
import { create } from "zustand";
import { persist } from "zustand/middleware";
-import { Time } from "../components/DateSelector/types";
+import { Comparison, DEFAULT_COMPARISON, Time } from "../components/DateSelector/types";
import { LITE_DASHBOARD } from "./const";
import { getDashboardTimeForRange, getStoredDashboardDefaultTime } from "./defaultTimeRange";
import {
canGoForward as canGoForwardFrom,
- deriveTimeState,
+ getBucketForTime,
hasRangeTimes,
recalculateTimeForTimezone,
+ resolveComparison,
shiftTimeBackward,
shiftTimeForward,
} from "./time";
@@ -26,12 +27,19 @@ const getSystemTimezone = () =>
export type StatType = "pageviews" | "sessions" | "users" | "pages_per_session" | "bounce_rate" | "session_duration";
-const getTimeState = (time: Time): Pick<Store, "time" | "previousTime" | "bucket"> => {
+const getTimeState = (
+ time: Time,
+ comparison: Comparison = DEFAULT_COMPARISON
+): Pick<Store, "time" | "previousTime" | "bucket" | "comparison"> => {
// Resolve the zone lazily: this runs during store creation (before useStore
// exists), and only range-with-times values actually need the zone.
const zone = hasRangeTimes(time) ? getTimezone() : "UTC";
- const { previousTime, bucket } = deriveTimeState(time, zone);
- return { time, previousTime, bucket: clampBucketForLite(bucket) };
+ return {
+ time,
+ comparison,
+ previousTime: resolveComparison(time, comparison, zone),
+ bucket: clampBucketForLite(getBucketForTime(time, zone)),
+ };
};
type Store = {
@@ -41,8 +49,11 @@ type Store = {
setPrivateKey: (privateKey: string | null) => void;
setSiteContext: (site: string, privateKey: string | null) => void;
time: Time;
- previousTime: Time;
+ /** The window the comparison line is drawn from; null when comparison is off. */
+ previousTime: Time | null;
setTime: (time: Time, changeBucket?: boolean) => void;
+ comparison: Comparison;
+ setComparison: (comparison: Comparison) => void;
bucket: TimeBucket;
setBucket: (bucket: TimeBucket) => void;
selectedStat: StatType;
@@ -79,6 +90,7 @@ const getSiteStateForUrl = (state: Store, site: string, privateKey?: string | nu
...(privateKey !== undefined ? { privateKey } : {}),
time: hasTimeInUrl ? state.time : defaultTimeState.time,
previousTime: hasTimeInUrl ? state.previousTime : defaultTimeState.previousTime,
+ comparison: hasTimeInUrl ? state.comparison : defaultTimeState.comparison,
bucket: hasBucketInUrl ? state.bucket : defaultTimeState.bucket,
selectedStat: hasStatInUrl ? state.selectedStat : "users",
filters: hasFiltersInUrl ? state.filters : [],
@@ -99,7 +111,7 @@ export const useStore = create<Store, [["zustand/persist", PersistedStore]]>(
},
...getInitialTimeState(),
setTime: (time, changeBucket = true) => {
- const nextTimeState = getTimeState(time);
+ const nextTimeState = getTimeState(time, get().comparison);
if (changeBucket) {
set(nextTimeState);
@@ -107,6 +119,10 @@ export const useStore = create<Store, [["zustand/persist", PersistedStore]]>(
set({ time, previousTime: nextTimeState.previousTime });
}
},
+ // A comparison is stored as the choice, not as the window it resolves to,
+ // so stepping the date selector carries it along instead of stranding the
+ // dashboard on the period it was picked in.
+ setComparison: comparison => set(getTimeState(get().time, comparison)),
setBucket: bucket => set({ bucket }),
selectedStat: "users",
setSelectedStat: stat => set({ selectedStat: stat }),
@@ -147,15 +163,20 @@ export const useTimezone = () => {
return timezone === "system" ? getSystemTimezone() : timezone;
};
+// Whether a comparison window exists at all — false only when the user has
+// turned the comparison off, which is what hides every delta and dotted line.
+export const useComparisonEnabled = () => useStore(state => state.previousTime !== null);
+
// Helper to convert a DateTime to the user's selected timezone
export const toUserTimezone = (dt: DateTime): DateTime => {
return dt.setZone(getTimezone());
};
export const resetStore = () => {
- const { setSite, setPrivateKey, setTime, setSelectedStat, setFilters } = useStore.getState();
+ const { setSite, setPrivateKey, setTime, setSelectedStat, setFilters, setComparison } = useStore.getState();
setSite("");
setPrivateKey(null);
+ setComparison(DEFAULT_COMPARISON);
setTime(getDefaultTime());
setSelectedStat("users");
setFilters([]);
diff --git a/client/src/lib/time.test.ts b/client/src/lib/time.test.ts
index 29c2f1627..60f32f776 100644
--- a/client/src/lib/time.test.ts
+++ b/client/src/lib/time.test.ts
@@ -3,14 +3,18 @@ import { describe, expect, it } from "vitest";
import { Time } from "../components/DateSelector/types";
import { getDashboardTimeForRange } from "./defaultTimeRange";
import {
+ availableComparisonModes,
canGoForward,
+ comparisonToUrlParams,
deriveTimeState,
getAbsoluteBounds,
getBucketForDateTimeRange,
recalculateTimeForTimezone,
+ resolveComparison,
shiftTimeBackward,
shiftTimeForward,
timeToUrlParams,
+ urlParamsToComparison,
urlParamsToTime,
} from "./time";
@@ -395,3 +399,127 @@ describe("getAbsoluteBounds", () => {
expect(ny.start.toMillis()).not.toBe(tokyo.start.toMillis());
});
});
+
+describe("resolveComparison", () => {
+ const LAST_30: Time = { mode: "range", startDate: "2026-07-31", endDate: "2026-08-29" };
+
+ it("previous: the period immediately before, matching deriveTimeState", () => {
+ expect(resolveComparison(LAST_30, { mode: "previous" }, ZONE)).toEqual(deriveTimeState(LAST_30, ZONE).previousTime);
+ });
+
+ it("none: no window at all", () => {
+ expect(resolveComparison(LAST_30, { mode: "none" }, ZONE)).toBeNull();
+ });
+
+ it("custom: the named window, untouched by the selected period", () => {
+ const customTime: Time = { mode: "range", startDate: "2026-03-02", endDate: "2026-03-31" };
+
+ expect(resolveComparison(LAST_30, { mode: "custom", customTime }, ZONE)).toEqual(customTime);
+ expect(resolveComparison({ mode: "day", day: "2026-08-29" }, { mode: "custom", customTime }, ZONE)).toEqual(
+ customTime
+ );
+ });
+
+ it("custom: falls back to the previous period when no window has been named yet", () => {
+ expect(resolveComparison(LAST_30, { mode: "custom" }, ZONE)).toEqual(deriveTimeState(LAST_30, ZONE).previousTime);
+ });
+
+ it("weekday: steps back whole weeks so the days of the week line up", () => {
+ // 30 days rounds to 4 weeks back — Jul 31 (a Friday) is read against Jul 3,
+ // also a Friday.
+ const previous = resolveComparison(LAST_30, { mode: "weekday" }, ZONE);
+
+ expect(previous).toEqual({
+ mode: "range",
+ startDate: "2026-07-03",
+ startTime: "00:00:00",
+ endDate: "2026-08-02",
+ endTime: "00:00:00",
+ });
+ expect(dt("2026-07-03").weekday).toBe(dt("2026-07-31").weekday);
+ });
+
+ it("weekday: a single day is read against the same weekday a week earlier", () => {
+ expect(resolveComparison({ mode: "day", day: "2026-08-29" }, { mode: "weekday" }, ZONE)).toEqual({
+ mode: "day",
+ day: "2026-08-22",
+ });
+ });
+
+ it("year: the same dates a year earlier, keeping calendar modes calendar-shaped", () => {
+ expect(resolveComparison({ mode: "month", month: "2026-08-01" }, { mode: "year" }, ZONE)).toEqual({
+ mode: "month",
+ month: "2025-08-01",
+ });
+ expect(resolveComparison(LAST_30, { mode: "year" }, ZONE)).toEqual({
+ mode: "range",
+ startDate: "2025-07-31",
+ startTime: "00:00:00",
+ endDate: "2025-08-30",
+ endTime: "00:00:00",
+ });
+ });
+
+ it("falls back to the previous period where a mode cannot be expressed", () => {
+ const realtime: Time = { mode: "past-minutes", pastMinutesStart: 30, pastMinutesEnd: 0 };
+ const previous = deriveTimeState(realtime, ZONE).previousTime;
+
+ expect(resolveComparison(realtime, { mode: "year" }, ZONE)).toEqual(previous);
+ expect(resolveComparison(realtime, { mode: "weekday" }, ZONE)).toEqual(previous);
+ // Weekday alignment across whole months is meaningless.
+ expect(resolveComparison({ mode: "month", month: "2026-08-01" }, { mode: "weekday" }, ZONE)).toEqual({
+ mode: "month",
+ month: "2026-07-01",
+ });
+ });
+
+ it("all-time keeps its historical self-comparison for the default mode", () => {
+ expect(resolveComparison({ mode: "all-time" }, { mode: "previous" }, ZONE)).toEqual({ mode: "all-time" });
+ expect(resolveComparison({ mode: "all-time" }, { mode: "none" }, ZONE)).toBeNull();
+ });
+});
+
+describe("availableComparisonModes", () => {
+ it("offers only what a realtime window can answer", () => {
+ expect(availableComparisonModes({ mode: "past-minutes", pastMinutesStart: 30, pastMinutesEnd: 0 })).toEqual([
+ "previous",
+ "none",
+ ]);
+ });
+
+ it("drops weekday alignment for whole months and years", () => {
+ expect(availableComparisonModes({ mode: "month", month: "2026-08-01" })).not.toContain("weekday");
+ expect(availableComparisonModes({ mode: "range", startDate: "2026-07-31", endDate: "2026-08-29" })).toContain(
+ "weekday"
+ );
+ });
+});
+
+describe("comparison URL serialization", () => {
+ it("writes nothing for the default, so existing links are untouched", () => {
+ expect(comparisonToUrlParams({ mode: "previous" })).toEqual({
+ compare: null,
+ compareStart: null,
+ compareEnd: null,
+ });
+ });
+
+ it("round-trips a named mode", () => {
+ expect(urlParamsToComparison(comparisonToUrlParams({ mode: "year" }))).toEqual({ mode: "year" });
+ });
+
+ it("round-trips a custom window", () => {
+ const comparison = {
+ mode: "custom" as const,
+ customTime: { mode: "range" as const, startDate: "2026-03-02", endDate: "2026-03-31" },
+ };
+
+ expect(urlParamsToComparison(comparisonToUrlParams(comparison))).toEqual(comparison);
+ });
+
+ it("ignores a custom mode with no window and an unknown mode", () => {
+ expect(urlParamsToComparison({ compare: "custom" })).toBeNull();
+ expect(urlParamsToComparison({ compare: "sideways" })).toBeNull();
+ expect(urlParamsToComparison({})).toBeNull();
+ });
+});
diff --git a/client/src/lib/time.ts b/client/src/lib/time.ts
index 917a30852..9beedc74e 100644
--- a/client/src/lib/time.ts
+++ b/client/src/lib/time.ts
@@ -1,6 +1,6 @@
import { TimeBucket } from "@rybbit/shared";
-import { DateTime } from "luxon";
-import { Time } from "../components/DateSelector/types";
+import { DateTime, type DurationLike } from "luxon";
+import { Comparison, ComparisonMode, Time } from "../components/DateSelector/types";
import { getDashboardTimeForRange } from "./defaultTimeRange";
// The Time module: every derivation over a `Time` value lives here — previous
@@ -75,82 +75,156 @@ export const getBucketForDateTimeRange = (start: DateTime, end: DateTime): TimeB
};
/**
- * The comparison period and default bucket for a Time. This is the single
- * implementation of "previous period" math (day-1, shifted ranges, doubled
- * past-minutes windows, week/month/year steps).
+ * The default bucket for a Time: fine enough to show shape, coarse enough that
+ * a year does not arrive as 365 points.
*/
-export const deriveTimeState = (time: Time, zone: string): { previousTime: Time; bucket: TimeBucket } => {
- let bucket: TimeBucket = "hour";
- let previousTime: Time;
-
- if (time.mode === "day") {
- bucket = "hour";
- previousTime = {
- mode: "day",
- day: DateTime.fromISO(time.day).minus({ days: 1 }).toISODate() ?? "",
- };
- } else if (time.mode === "past-minutes") {
- const timeDiff = time.pastMinutesStart - time.pastMinutesEnd;
-
- if (timeDiff <= 120) {
- bucket = "minute";
- }
-
- previousTime = {
- mode: "past-minutes",
- pastMinutesStart: time.pastMinutesStart + timeDiff,
- pastMinutesEnd: time.pastMinutesEnd + timeDiff,
- };
- } else if (time.mode === "range") {
- if (hasRangeTimes(time)) {
- const { start, end } = getRangeDateTimeBounds(time, zone);
- const duration = end.diff(start);
- bucket = getBucketForDateTimeRange(start, end);
+export const getBucketForTime = (time: Time, zone: string): TimeBucket => {
+ switch (time.mode) {
+ case "day":
+ return "hour";
+ case "past-minutes":
+ return time.pastMinutesStart - time.pastMinutesEnd <= 120 ? "minute" : "hour";
+ case "week":
+ case "month":
+ case "all-time":
+ return "day";
+ case "year":
+ return "month";
+ case "range": {
+ if (hasRangeTimes(time)) {
+ const { start, end } = getRangeDateTimeBounds(time, zone);
+ return getBucketForDateTimeRange(start, end);
+ }
- previousTime = toRangeWithTimes(start.minus(duration), end.minus(duration));
- } else {
const timeRangeLength = DateTime.fromISO(time.endDate).diff(DateTime.fromISO(time.startDate), "days").days + 1;
+ if (timeRangeLength > 180) return "month";
+ if (timeRangeLength > 31) return "week";
+ return "day";
+ }
+ }
+};
- if (timeRangeLength > 180) {
- bucket = "month";
- } else if (timeRangeLength > 31) {
- bucket = "week";
- } else {
- bucket = "day";
+/**
+ * The period immediately before this one — the single implementation of
+ * "previous period" math (day-1, shifted ranges, doubled past-minutes windows,
+ * week/month/year steps).
+ */
+export const getPreviousPeriod = (time: Time, zone: string): Time => {
+ switch (time.mode) {
+ case "day":
+ return { mode: "day", day: DateTime.fromISO(time.day).minus({ days: 1 }).toISODate() ?? "" };
+ case "past-minutes": {
+ const timeDiff = time.pastMinutesStart - time.pastMinutesEnd;
+ return {
+ mode: "past-minutes",
+ pastMinutesStart: time.pastMinutesStart + timeDiff,
+ pastMinutesEnd: time.pastMinutesEnd + timeDiff,
+ };
+ }
+ case "week":
+ return { mode: "week", week: DateTime.fromISO(time.week).minus({ weeks: 1 }).toISODate() ?? "" };
+ case "month":
+ return { mode: "month", month: DateTime.fromISO(time.month).minus({ months: 1 }).toISODate() ?? "" };
+ case "year":
+ return { mode: "year", year: DateTime.fromISO(time.year).minus({ years: 1 }).toISODate() ?? "" };
+ case "all-time":
+ return { mode: "all-time" };
+ case "range": {
+ if (hasRangeTimes(time)) {
+ const { start, end } = getRangeDateTimeBounds(time, zone);
+ const duration = end.diff(start);
+ return toRangeWithTimes(start.minus(duration), end.minus(duration));
}
- previousTime = {
+ const timeRangeLength = DateTime.fromISO(time.endDate).diff(DateTime.fromISO(time.startDate), "days").days + 1;
+ return {
mode: "range",
startDate: DateTime.fromISO(time.startDate).minus({ days: timeRangeLength }).toISODate() ?? "",
endDate: DateTime.fromISO(time.startDate).minus({ days: 1 }).toISODate() ?? "",
};
}
- } else if (time.mode === "week") {
- bucket = "day";
- previousTime = {
- mode: "week",
- week: DateTime.fromISO(time.week).minus({ weeks: 1 }).toISODate() ?? "",
- };
- } else if (time.mode === "month") {
- bucket = "day";
- previousTime = {
- mode: "month",
- month: DateTime.fromISO(time.month).minus({ months: 1 }).toISODate() ?? "",
- };
- } else if (time.mode === "year") {
- bucket = "month";
- previousTime = {
- mode: "year",
- year: DateTime.fromISO(time.year).minus({ years: 1 }).toISODate() ?? "",
- };
- } else if (time.mode === "all-time") {
- bucket = "day";
- previousTime = { mode: "all-time" };
- } else {
- previousTime = time;
}
+};
+
+/** The comparison period and default bucket for a Time. */
+export const deriveTimeState = (time: Time, zone: string): { previousTime: Time; bucket: TimeBucket } => ({
+ previousTime: getPreviousPeriod(time, zone),
+ bucket: getBucketForTime(time, zone),
+});
+
+/**
+ * How far back "matching weekdays" steps: the whole number of weeks closest to
+ * the period's own length, so a Saturday is read against a Saturday. A 30-day
+ * window lands 4 weeks back and overlaps its own first two days — the price of
+ * keeping the weekly shape aligned, and the reason this is not the default.
+ */
+const weekdayShiftWeeks = (start: DateTime, end: DateTime): number =>
+ Math.max(1, Math.round(end.diff(start, "days").days / 7));
+
+/**
+ * Steps a period back by `duration`, keeping the calendar-native modes native
+ * so the comparison keeps the label and the bucketing of the period it mirrors.
+ * Anything else becomes an explicit range. Null for all-time, which has no
+ * bounds to step.
+ */
+const shiftPeriod = (time: Time, zone: string, duration: DurationLike): Time | null => {
+ const bounds = getAbsoluteBounds(time, zone);
+ if (!bounds) return null;
+
+ if (time.mode === "day") {
+ return { mode: "day", day: DateTime.fromISO(time.day).minus(duration).toISODate() ?? "" };
+ }
+ if (time.mode === "month") {
+ return { mode: "month", month: DateTime.fromISO(time.month).minus(duration).toISODate() ?? "" };
+ }
+ if (time.mode === "year") {
+ return { mode: "year", year: DateTime.fromISO(time.year).minus(duration).toISODate() ?? "" };
+ }
+
+ return toRangeWithTimes(bounds.start.minus(duration), bounds.end.minus(duration));
+};
+
+/**
+ * What the dashboard compares against. Everything but `custom` is derived from
+ * the selected period, so stepping the date selector carries the comparison
+ * with it; `none` resolves to null and no comparison is fetched at all.
+ *
+ * A mode that cannot be expressed for the selected period — weekday alignment
+ * across whole months, last year against a rolling past-minutes window — falls
+ * back to the previous period rather than to nothing, so the dashboard never
+ * silently loses its second line.
+ */
+export const resolveComparison = (time: Time, comparison: Comparison, zone: string): Time | null => {
+ switch (comparison.mode) {
+ case "none":
+ return null;
+ case "custom":
+ return comparison.customTime ?? getPreviousPeriod(time, zone);
+ case "weekday": {
+ if (time.mode !== "day" && time.mode !== "week" && time.mode !== "range") break;
+ const bounds = getAbsoluteBounds(time, zone);
+ if (!bounds) break;
+ return (
+ shiftPeriod(time, zone, { weeks: weekdayShiftWeeks(bounds.start, bounds.end) }) ?? getPreviousPeriod(time, zone)
+ );
+ }
+ case "year": {
+ if (time.mode === "past-minutes" || time.mode === "all-time") break;
+ return shiftPeriod(time, zone, { years: 1 }) ?? getPreviousPeriod(time, zone);
+ }
+ case "previous":
+ break;
+ }
+
+ return getPreviousPeriod(time, zone);
+};
- return { previousTime, bucket };
+/** The comparison modes that mean something for the selected period. */
+export const availableComparisonModes = (time: Time): ComparisonMode[] => {
+ if (time.mode === "all-time") return ["previous", "custom", "none"];
+ if (time.mode === "past-minutes") return ["previous", "none"];
+ if (time.mode === "month" || time.mode === "year") return ["previous", "year", "custom", "none"];
+ return ["previous", "weekday", "year", "custom", "none"];
};
/**
@@ -475,3 +549,51 @@ export const urlParamsToTime = (params: Partial<TimeUrlParams>, zone: string): T
return null;
};
+
+export interface ComparisonUrlParams {
+ compare: string | null;
+ compareStart: string | null;
+ compareEnd: string | null;
+}
+
+const COMPARISON_MODES: ComparisonMode[] = ["previous", "weekday", "year", "custom", "none"];
+
+/**
+ * The comparison travels in the URL alongside the period. Without it a link to
+ * "vs last year" opens for the next person as "vs last month" — the same
+ * numbers under a different question.
+ *
+ * The default needs no param, so existing links keep working and the common
+ * case leaves the query string as short as it is today.
+ */
+export const comparisonToUrlParams = (comparison: Comparison): ComparisonUrlParams => {
+ if (comparison.mode === "previous") {
+ return { compare: null, compareStart: null, compareEnd: null };
+ }
+
+ if (comparison.mode === "custom" && comparison.customTime?.mode === "range") {
+ return {
+ compare: "custom",
+ compareStart: comparison.customTime.startDate,
+ compareEnd: comparison.customTime.endDate,
+ };
+ }
+
+ return { compare: comparison.mode, compareStart: null, compareEnd: null };
+};
+
+/** Null when the params don't name a comparison (caller keeps the default). */
+export const urlParamsToComparison = (params: Partial<ComparisonUrlParams>): Comparison | null => {
+ const mode = COMPARISON_MODES.find(candidate => candidate === params.compare);
+ if (!mode) return null;
+
+ if (mode === "custom") {
+ if (!params.compareStart || !params.compareEnd) return null;
+ return {
+ mode: "custom",
+ customTime: { mode: "range", startDate: params.compareStart, endDate: params.compareEnd },
+ };
+ }
+
+ return { mode };
+};
diff --git a/client/src/lib/urlParams.ts b/client/src/lib/urlParams.ts
index 89ec31cdb..8cb2b115d 100644
--- a/client/src/lib/urlParams.ts
+++ b/client/src/lib/urlParams.ts
@@ -1,5 +1,6 @@
"use client";
+import { DEFAULT_COMPARISON } from "@/components/DateSelector/types";
import { usePathname, useSearchParams } from "next/navigation";
import { useQueryStates } from "nuqs";
import React, { useEffect } from "react";
@@ -7,13 +8,25 @@ import { getStoredDashboardDefaultTime } from "./defaultTimeRange";
import { analyticsParsers } from "./parsers";
import { getSiteRouteContext, isSyncedAnalyticsRoute } from "./siteRoute";
import { getTimezone, useStore } from "./store";
-import { timeToUrlParams, urlParamsToTime } from "./time";
+import { comparisonToUrlParams, timeToUrlParams, urlParamsToComparison, urlParamsToTime } from "./time";
// Hook to sync store state with URL
export const useSyncStateWithUrl = () => {
const pathname = usePathname();
const searchParams = useSearchParams();
- const { time, bucket, selectedStat, filters, setTime, setBucket, setSelectedStat, setFilters, site } = useStore();
+ const {
+ time,
+ bucket,
+ selectedStat,
+ filters,
+ comparison,
+ setTime,
+ setBucket,
+ setSelectedStat,
+ setFilters,
+ setComparison,
+ site,
+ } = useStore();
const routeContext = React.useMemo(() => getSiteRouteContext(pathname), [pathname]);
const shouldSyncUrl = isSyncedAnalyticsRoute(routeContext.route);
@@ -38,6 +51,10 @@ export const useSyncStateWithUrl = () => {
useEffect(() => {
if (!hydrationKey || site !== routeContext.siteId || hydratedUrlKey === hydrationKey) return;
+ // The comparison is restored before the period so the window it resolves
+ // to is the shared link's, not the default period's.
+ setComparison(urlParamsToComparison(urlParams) ?? DEFAULT_COMPARISON);
+
// Deserialize time from URL
const timeFromUrl = urlParamsToTime(urlParams, getTimezone());
@@ -70,6 +87,7 @@ export const useSyncStateWithUrl = () => {
setBucket,
setSelectedStat,
setFilters,
+ setComparison,
urlParams,
]);
@@ -80,6 +98,7 @@ export const useSyncStateWithUrl = () => {
// Build params object to update - values, not parsers
const newParams: Record<string, any> = {
...timeToUrlParams(time),
+ ...comparisonToUrlParams(comparison),
// startDateTime/endDateTime are legacy params no mode writes anymore.
startDateTime: null,
endDateTime: null,
@@ -90,5 +109,16 @@ export const useSyncStateWithUrl = () => {
// Note: embed params are automatically preserved by nuqs
setUrlParams(newParams);
- }, [time, bucket, selectedStat, filters, site, setUrlParams, hydrationKey, hydratedUrlKey, routeContext.siteId]);
+ }, [
+ time,
+ bucket,
+ selectedStat,
+ filters,
+ comparison,
+ site,
+ setUrlParams,
+ hydrationKey,
+ hydratedUrlKey,
+ routeContext.siteId,
+ ]);
};