Skip to content

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

Intl time (#904)

Goldflag98698c1dcb5a
diff --git a/client/CLAUDE.md b/client/CLAUDE.md
new file mode 100644
index 000000000..9314195ad
--- /dev/null
+++ b/client/CLAUDE.md
@@ -0,0 +1,138 @@
+# CLAUDE.md – Rybbit Client
+
+This file provides guidance to Claude Code when working in the `/client` directory.
+
+## Commands
+
+- `npm run dev` – Start dev server (Next.js + Turbopack, port 3002)
+- `npm run build` – Production build
+- `npm run lint` – ESLint
+- `npm run format` – Prettier format
+- `tsc --noEmit` – Type-check without emitting
+
+## Stack
+
+- **Framework**: Next.js 16 (App Router), React 19
+- **Styling**: Tailwind CSS v4, Shadcn UI (New York style), Lucide icons
+- **State**: Zustand 5 (app/user stores), Jotai (atomic state)
+- **Server state**: TanStack React Query 5
+- **Auth**: Better-auth (admin, organization, emailOTP, apiKey plugins)
+- **Forms**: React Hook Form + Zod
+- **i18n**: next-intl (10 locales: en, de, fr, zh, es, pl, it, ko, pt, ja)
+- **Charts**: Nivo (bar, calendar, line), D3, Mapbox GL
+- **Date/time**: Luxon, date-fns
+- **URL state**: nuqs (query string), vaul (drawer)
+- **HTTP**: Axios via `authedFetch<T>()` wrapper
+
+## Project Structure
+
+```
+src/
+├── api/ # API layer
+│ ├── analytics/ # Analytics endpoints + React Query hooks
+│ ├── admin/ # Admin endpoints + hooks
+│ ├── gsc/ # Google Search Console
+│ ├── uptime/ # Uptime monitoring
+│ ├── types.ts # Shared types (CommonApiParams, Filter, etc.)
+│ └── utils.ts # authedFetch, buildApiParams
+├── app/ # Next.js App Router pages
+│ ├── [site]/ # Per-site analytics dashboard
+│ ├── admin/ # Admin panel
+│ ├── auth/ # Auth flows
+│ ├── settings/ # User settings
+│ ├── uptime/ # Uptime dashboard
+│ ├── layout.tsx # Root layout
+│ └── Providers.tsx # Provider stack
+├── components/
+│ ├── ui/ # Shadcn UI primitives (41 files)
+│ ├── charts/ # Chart components
+│ ├── DateSelector/ # Date/time picker
+│ ├── Sessions/ # Session replay
+│ ├── sidebar/ # Navigation sidebar
+│ └── [feature components]
+├── hooks/ # Custom hooks
+├── lib/
+│ ├── store.ts # Main Zustand store
+│ ├── userStore.ts # User/auth Zustand store
+│ ├── auth.ts # Better-auth client
+│ ├── utils.ts # cn(), formatters, helpers
+│ ├── dateTimeUtils.ts # Luxon-based date helpers
+│ └── urlParams.ts # URL param management
+├── types/ # TypeScript definitions
+├── i18n/request.ts # next-intl config
+└── proxy.ts # Next.js middleware (routing)
+
+messages/ # Translation files (en.json, de.json, etc.)
+```
+
+## API Layer Pattern
+
+Every data domain has two layers:
+
+**1. Endpoints** (`api/[domain]/endpoints/*.ts`) – pure async functions, no React:
+```ts
+export async function fetchSomething(siteId: string): Promise<SomeType> {
+ return authedFetch<SomeType>(`/api/something?siteId=${siteId}`);
+}
+```
+
+**2. Hooks** (`api/[domain]/hooks/*.ts`) – React Query wrappers:
+```ts
+export function useGetSomething(siteId?: string) {
+ return useQuery({
+ queryKey: ["get-something", siteId],
+ queryFn: () => fetchSomething(siteId!),
+ enabled: !!siteId,
+ });
+}
+```
+
+**`authedFetch<T>(url, options?)`** (`api/utils.ts`):
+- Prepends `BACKEND_URL`
+- Sends `credentials: "include"`
+- Adds `x-private-key` header if present
+- Converts array params to JSON strings
+- Extracts and throws backend errors from `response.data.error`
+
+**`buildApiParams(time, timezone, filters?)`** returns `CommonApiParams` with `.toQueryParams()` / `.toBucketedQueryParams()` helpers for converting the time store state into API-ready parameters.
+
+## State Management
+
+**Main store** (`lib/store.ts`) via Zustand:
+- `site` – current site ID
+- `time` – selected time range (modes: `day`, `range`, `week`, `month`, `year`, `past-minutes`, `all-time`)
+- `previousTime` – comparison period
+- `bucket` – time bucketing (`hour`, `day`, `week`, `month`)
+- `selectedStat` – active metric (`pageviews`, `sessions`, `users`, `bounce_rate`, etc.)
+- `filters` – active analytics filters
+- `timezone` – IANA timezone (persisted to localStorage)
+- Helpers: `resetStore()`, `goBack()`, `goForward()`, `addFilter()`, `removeFilter()`
+
+**User store** (`lib/userStore.ts`) via Zustand:
+- User session data and `isPending` flag
+
+Only `timezone` is persisted; everything else is session-only.
+
+## Routing
+
+- `/[site]/main` – analytics dashboard (middleware redirects `/{siteId}` → `/{siteId}/main`)
+- `/[site]/[privateKey]/main` – public/shared analytics
+- `/admin` – admin panel
+- `/login`, `/signup` – auth pages
+- `/settings` – user settings
+- `/uptime` – uptime monitoring
+
+Middleware in `proxy.ts` handles redirects and OAuth callbacks (`/auth/callback/github`, `/auth/callback/google`).
+
+## Code Conventions
+
+- **TypeScript** strict mode throughout; use Zod for runtime validation
+- **Components**: functional, `"use client"` where needed, minimal `useEffect`
+- **Naming**: `camelCase` variables/functions, `PascalCase` components/types, `UPPER_SNAKE_CASE` constants
+- **API hooks**: prefix with `use`, e.g. `useGetSites`; endpoint functions prefix with `fetch`/`create`/`update`/`delete`
+- **Query keys**: descriptive arrays, e.g. `["get-site", siteId]`
+- **Imports**: external first, then internal; alphabetical within groups
+- **Dark mode**: default theme; class-based, CSS HSL variables
+- **i18n**: use `useTranslations()` from next-intl; translation files in `messages/`
+- **Error handling**: try/catch with specific error types; let React Query surface API errors
+- **Do not** add unnecessary abstractions, extra error handling for impossible cases, or docstrings to unchanged code
diff --git a/client/messages/de.json b/client/messages/de.json
index c11ff22c4..ff546a3aa 100644
--- a/client/messages/de.json
+++ b/client/messages/de.json
@@ -194,8 +194,8 @@
"Zx7WPP": "Alle Event-Reihen ausgeblendet",
"AKRVhS": "Klicken Sie auf ein Legendenelement, um es anzuzeigen",
"NuhCPH": "Erfahren Sie, wie Sie Events verfolgen",
- "ES6IYH": "Versuchen Sie einen anderen Zeitraum oder Filter",
"/aq5/F": "Keine benutzerdefinierten Events gefunden",
+ "ES6IYH": "Versuchen Sie einen anderen Zeitraum oder Filter",
"j7BiRg": "Kein Event ausgewählt.",
"kF9XUo": "Zeitstempel",
"EwRIOm": "Benutzer",
@@ -965,10 +965,11 @@
"jssBN0": "monatlich abgerechnet",
"qyJtWy": "Weniger anzeigen",
"P3H0J/": "Mehr anzeigen ({count} weitere)",
+ "XkmpXm": "Benutzer anzeigen",
+ "lBlz7y": "",
"74Tffy": "Session Replay ansehen",
"XNeN37": "Fehler beim Laden der Sitzungsdetails. Bitte versuchen Sie es erneut.",
"1gYD1y": "Sitzungsinformationen",
- "XkmpXm": "Benutzer anzeigen",
"wOFJFO": "Keine Daten verfügbar",
"op7jCp": "Benutzerinformationen",
"1bqKv/": "Benutzer-ID:",
diff --git a/client/messages/en.json b/client/messages/en.json
index a8a0de114..bc3f3ba76 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -194,8 +194,8 @@
"Zx7WPP": "All event series hidden",
"AKRVhS": "Click a legend item to show it",
"NuhCPH": "Learn how to track events",
- "ES6IYH": "Try a different date range or filter",
"/aq5/F": "No custom events found",
+ "ES6IYH": "Try a different date range or filter",
"j7BiRg": "No event selected.",
"kF9XUo": "Timestamp",
"EwRIOm": "User",
@@ -965,10 +965,11 @@
"jssBN0": "billed monthly",
"qyJtWy": "Show less",
"P3H0J/": "Show more ({count} more)",
+ "XkmpXm": "View User",
+ "lBlz7y": "{count} events captured ({groupCount} groups)",
"74Tffy": "Watch Session Replay",
"XNeN37": "Error loading session details. Please try again.",
"1gYD1y": "Session Info",
- "XkmpXm": "View User",
"wOFJFO": "No data available",
"op7jCp": "User Information",
"1bqKv/": "User ID:",
diff --git a/client/messages/es.json b/client/messages/es.json
index 26c130033..f7e3f2488 100644
--- a/client/messages/es.json
+++ b/client/messages/es.json
@@ -194,8 +194,8 @@
"Zx7WPP": "Todas las series de eventos ocultas",
"AKRVhS": "Haz clic en un elemento de la leyenda para mostrarlo",
"NuhCPH": "Aprende cómo rastrear eventos",
- "ES6IYH": "Prueba un rango de fechas o filtro diferente",
"/aq5/F": "No se encontraron eventos personalizados",
+ "ES6IYH": "Prueba un rango de fechas o filtro diferente",
"j7BiRg": "Ningún evento seleccionado.",
"kF9XUo": "Marca de tiempo",
"EwRIOm": "Usuario",
@@ -965,10 +965,11 @@
"jssBN0": "facturado mensualmente",
"qyJtWy": "Mostrar menos",
"P3H0J/": "Mostrar más ({count} más)",
+ "XkmpXm": "Ver usuario",
+ "lBlz7y": "",
"74Tffy": "Ver repetición de sesión",
"XNeN37": "Error al cargar detalles de la sesión. Inténtalo de nuevo.",
"1gYD1y": "Información de la sesión",
- "XkmpXm": "Ver usuario",
"wOFJFO": "No hay datos disponibles",
"op7jCp": "Información del usuario",
"1bqKv/": "ID de usuario:",
diff --git a/client/messages/fr.json b/client/messages/fr.json
index 57ab97b93..3d41c45e5 100644
--- a/client/messages/fr.json
+++ b/client/messages/fr.json
@@ -194,8 +194,8 @@
"Zx7WPP": "Toutes les séries d'événements masquées",
"AKRVhS": "Cliquez sur un élément de la légende pour l'afficher",
"NuhCPH": "Apprenez à suivre les événements",
- "ES6IYH": "Essayez une autre période ou un autre filtre",
"/aq5/F": "Aucun événement personnalisé trouvé",
+ "ES6IYH": "Essayez une autre période ou un autre filtre",
"j7BiRg": "Aucun événement sélectionné.",
"kF9XUo": "Horodatage",
"EwRIOm": "Utilisateur",
@@ -965,10 +965,11 @@
"jssBN0": "facturé mensuellement",
"qyJtWy": "Voir moins",
"P3H0J/": "Voir plus ({count} de plus)",
+ "XkmpXm": "Voir l'utilisateur",
+ "lBlz7y": "",
"74Tffy": "Regarder le Session Replay",
"XNeN37": "Erreur lors du chargement des détails de la session. Veuillez réessayer.",
"1gYD1y": "Info session",
- "XkmpXm": "Voir l'utilisateur",
"wOFJFO": "Aucune donnée disponible",
"op7jCp": "Informations utilisateur",
"1bqKv/": "ID utilisateur :",
diff --git a/client/messages/it.json b/client/messages/it.json
index e413fef8b..22020fc65 100644
--- a/client/messages/it.json
+++ b/client/messages/it.json
@@ -194,8 +194,8 @@
"Zx7WPP": "Tutte le serie di eventi nascoste",
"AKRVhS": "Clicca un elemento della legenda per mostrarlo",
"NuhCPH": "Scopri come tracciare gli eventi",
- "ES6IYH": "Prova un intervallo di date diverso o un filtro",
"/aq5/F": "Nessun evento personalizzato trovato",
+ "ES6IYH": "Prova un intervallo di date diverso o un filtro",
"j7BiRg": "Nessun evento selezionato.",
"kF9XUo": "Timestamp",
"EwRIOm": "Utente",
@@ -965,10 +965,11 @@
"jssBN0": "fatturato mensilmente",
"qyJtWy": "Mostra meno",
"P3H0J/": "Mostra di più ({count} in più)",
+ "XkmpXm": "Visualizza Utente",
+ "lBlz7y": "",
"74Tffy": "Guarda Riproduzione Sessione",
"XNeN37": "Errore nel caricamento dei dettagli della sessione. Riprova.",
"1gYD1y": "Info Sessione",
- "XkmpXm": "Visualizza Utente",
"wOFJFO": "Nessun dato disponibile",
"op7jCp": "Informazioni Utente",
"1bqKv/": "ID Utente:",
diff --git a/client/messages/ja.json b/client/messages/ja.json
index 866573888..25c04ac99 100644
--- a/client/messages/ja.json
+++ b/client/messages/ja.json
@@ -194,8 +194,8 @@
"Zx7WPP": "すべてのイベント系列が非表示です",
"AKRVhS": "凡例の項目をクリックして表示します",
"NuhCPH": "イベントのトラッキング方法を学ぶ",
- "ES6IYH": "別の日付範囲またはフィルターをお試しください",
"/aq5/F": "カスタムイベントが見つかりません",
+ "ES6IYH": "別の日付範囲またはフィルターをお試しください",
"j7BiRg": "イベントが選択されていません。",
"kF9XUo": "タイムスタンプ",
"EwRIOm": "ユーザー",
@@ -965,10 +965,11 @@
"jssBN0": "月額請求",
"qyJtWy": "折りたたむ",
"P3H0J/": "もっと表示(他{count}件)",
+ "XkmpXm": "ユーザーを表示",
+ "lBlz7y": "",
"74Tffy": "セッションリプレイを視聴",
"XNeN37": "セッション詳細の読み込みエラー。もう一度お試しください。",
"1gYD1y": "セッション情報",
- "XkmpXm": "ユーザーを表示",
"wOFJFO": "データがありません",
"op7jCp": "ユーザー情報",
"1bqKv/": "ユーザーID:",
diff --git a/client/messages/ko.json b/client/messages/ko.json
index 5cf7d5dfd..864a5697f 100644
--- a/client/messages/ko.json
+++ b/client/messages/ko.json
@@ -194,8 +194,8 @@
"Zx7WPP": "모든 이벤트 시리즈 숨김",
"AKRVhS": "범례 항목을 클릭하여 표시",
"NuhCPH": "이벤트 추적 방법 알아보기",
- "ES6IYH": "다른 날짜 범위 또는 필터를 시도하세요",
"/aq5/F": "사용자 정의 이벤트를 찾을 수 없음",
+ "ES6IYH": "다른 날짜 범위 또는 필터를 시도하세요",
"j7BiRg": "이벤트가 선택되지 않았습니다.",
"kF9XUo": "타임스탬프",
"EwRIOm": "사용자",
@@ -965,10 +965,11 @@
"jssBN0": "월별 청구",
"qyJtWy": "간략히 보기",
"P3H0J/": "더 보기 ({count}개 더)",
+ "XkmpXm": "사용자 보기",
+ "lBlz7y": "",
"74Tffy": "세션 리플레이 보기",
"XNeN37": "세션 상세 로딩 오류. 다시 시도해 주세요.",
"1gYD1y": "세션 정보",
- "XkmpXm": "사용자 보기",
"wOFJFO": "사용 가능한 데이터 없음",
"op7jCp": "사용자 정보",
"1bqKv/": "사용자 ID:",
diff --git a/client/messages/pl.json b/client/messages/pl.json
index e59c2d5b3..330d5f5b6 100644
--- a/client/messages/pl.json
+++ b/client/messages/pl.json
@@ -194,8 +194,8 @@
"Zx7WPP": "Wszystkie serie zdarzeń ukryte",
"AKRVhS": "Kliknij element legendy, aby go wyświetlić",
"NuhCPH": "Dowiedz się, jak śledzić zdarzenia",
- "ES6IYH": "Spróbuj innego zakresu dat lub filtra",
"/aq5/F": "Nie znaleziono niestandardowych zdarzeń",
+ "ES6IYH": "Spróbuj innego zakresu dat lub filtra",
"j7BiRg": "Nie wybrano zdarzenia.",
"kF9XUo": "Znacznik czasu",
"EwRIOm": "Użytkownik",
@@ -965,10 +965,11 @@
"jssBN0": "rozliczane miesięcznie",
"qyJtWy": "Pokaż mniej",
"P3H0J/": "Pokaż więcej (jeszcze {count})",
+ "XkmpXm": "Zobacz użytkownika",
+ "lBlz7y": "",
"74Tffy": "Obejrzyj odtwarzanie sesji",
"XNeN37": "Błąd ładowania szczegółów sesji. Spróbuj ponownie.",
"1gYD1y": "Informacje o sesji",
- "XkmpXm": "Zobacz użytkownika",
"wOFJFO": "Brak dostępnych danych",
"op7jCp": "Informacje o użytkowniku",
"1bqKv/": "ID użytkownika:",
diff --git a/client/messages/pt.json b/client/messages/pt.json
index 4e96c3cde..8582b1a65 100644
--- a/client/messages/pt.json
+++ b/client/messages/pt.json
@@ -194,8 +194,8 @@
"Zx7WPP": "Todas as séries de eventos ocultas",
"AKRVhS": "Clique em um item da legenda para exibi-lo",
"NuhCPH": "Saiba como rastrear eventos",
- "ES6IYH": "Tente um intervalo de datas diferente ou filtro",
"/aq5/F": "Nenhum evento personalizado encontrado",
+ "ES6IYH": "Tente um intervalo de datas diferente ou filtro",
"j7BiRg": "Nenhum evento selecionado.",
"kF9XUo": "Data/Hora",
"EwRIOm": "Usuário",
@@ -965,10 +965,11 @@
"jssBN0": "cobrado mensalmente",
"qyJtWy": "Mostrar menos",
"P3H0J/": "Mostrar mais ({count} mais)",
+ "XkmpXm": "Ver Usuário",
+ "lBlz7y": "",
"74Tffy": "Assistir Replay de Sessão",
"XNeN37": "Erro ao carregar detalhes da sessão. Por favor, tente novamente.",
"1gYD1y": "Info da Sessão",
- "XkmpXm": "Ver Usuário",
"wOFJFO": "Nenhum dado disponível",
"op7jCp": "Informações do Usuário",
"1bqKv/": "ID do Usuário:",
diff --git a/client/messages/zh.json b/client/messages/zh.json
index 0cc826506..bb92bdb33 100644
--- a/client/messages/zh.json
+++ b/client/messages/zh.json
@@ -194,8 +194,8 @@
"Zx7WPP": "所有事件系列已隐藏",
"AKRVhS": "点击图例项以显示它",
"NuhCPH": "了解如何追踪事件",
- "ES6IYH": "尝试不同的日期范围或过滤器",
"/aq5/F": "未找到自定义事件",
+ "ES6IYH": "尝试不同的日期范围或过滤器",
"j7BiRg": "未选择事件。",
"kF9XUo": "时间戳",
"EwRIOm": "用户",
@@ -965,10 +965,11 @@
"jssBN0": "按月计费",
"qyJtWy": "显示较少",
"P3H0J/": "显示更多(还有 {count} 个)",
+ "XkmpXm": "查看用户",
+ "lBlz7y": "",
"74Tffy": "观看会话回放",
"XNeN37": "加载会话详情时出错。请重试。",
"1gYD1y": "会话信息",
- "XkmpXm": "查看用户",
"wOFJFO": "没有可用的数据",
"op7jCp": "用户信息",
"1bqKv/": "用户 ID:",
diff --git a/client/src/app/[site]/errors/components/ErrorDetails.tsx b/client/src/app/[site]/errors/components/ErrorDetails.tsx
index a1f2b8e27..1fc95af5a 100644
--- a/client/src/app/[site]/errors/components/ErrorDetails.tsx
+++ b/client/src/app/[site]/errors/components/ErrorDetails.tsx
@@ -6,6 +6,7 @@ import { useGetErrorEventsInfinite } from "@/api/analytics/hooks/errors/useGetEr
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
import { useGetRegionName } from "@/lib/geo";
import { getTimezone } from "@/lib/store";
import { getCountryName, truncateString } from "@/lib/utils";
@@ -28,6 +29,7 @@ interface ErrorDetailsProps {
// Component to display individual error event
function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {
const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
const { getRegionName } = useGetRegionName();
const { site } = useParams();
@@ -51,7 +53,7 @@ function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-4">
<span className="text-sm text-neutral-700 dark:text-neutral-200">
- {DateTime.fromSQL(errorEvent.timestamp, { zone: "utc" }).setZone(getTimezone()).toRelative()}
+ {formatRelative(DateTime.fromSQL(errorEvent.timestamp, { zone: "utc" }).setZone(getTimezone()))}
</span>
<div className="flex items-center gap-2">
{errorEvent.country && (
diff --git a/client/src/app/[site]/events/components/EventLog/EventRow.tsx b/client/src/app/[site]/events/components/EventLog/EventRow.tsx
index fa3471872..26246e321 100644
--- a/client/src/app/[site]/events/components/EventLog/EventRow.tsx
+++ b/client/src/app/[site]/events/components/EventLog/EventRow.tsx
@@ -7,7 +7,7 @@ import { Event } from "../../../../../api/analytics/endpoints";
import { Avatar } from "../../../../../components/Avatar";
import { EventTypeIcon } from "../../../../../components/EventIcons";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
-import { hour12, userLocale } from "../../../../../lib/dateTimeUtils";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
import { getTimezone } from "../../../../../lib/store";
import { getCountryName, getUserDisplayName, truncateString } from "../../../../../lib/utils";
import { Browser } from "../../../components/shared/icons/Browser";
@@ -24,9 +24,10 @@ interface EventRowProps {
export function EventRow({ event, site, onClick }: EventRowProps) {
const t = useExtracted();
+ const { locale, hour12, formatRelative } = useDateTimeFormat();
const eventProperties = parseEventProperties(event);
const eventTime = DateTime.fromSQL(event.timestamp, { zone: "utc" })
- .setLocale(userLocale)
+ .setLocale(locale)
.setZone(getTimezone());
const pagePath = buildEventPath(event);
const pageUrl = `https://${event.hostname}${pagePath}`;
@@ -62,7 +63,7 @@ export function EventRow({ event, site, onClick }: EventRowProps) {
<span>{eventTime.toFormat(hour12 ? "MMM d, h:mm:ss a" : "dd MMM, HH:mm:ss")}</span>
</TooltipTrigger>
<TooltipContent>
- <span>{eventTime.toRelative()}</span>
+ <span>{formatRelative(eventTime)}</span>
</TooltipContent>
</Tooltip>
</div>
diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsx
index abc69a683..286a944e4 100644
--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx
+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx
@@ -21,7 +21,8 @@ import { Badge } from "../../../../components/ui/badge";
import { Button } from "../../../../components/ui/button";
import { Dialog, DialogContent, DialogTitle } from "../../../../components/ui/dialog";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
-import { formatShortDuration, hour12, userLocale } from "../../../../lib/dateTimeUtils";
+import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
+import { formatShortDuration } from "../../../../lib/dateTimeUtils";
import { cn, formatter, truncateString } from "../../../../lib/utils";
function SessionCardSkeleton() {
@@ -58,6 +59,7 @@ function SessionCardSkeleton() {
function SessionCard({ session, onClick }: { session: GetSessionsResponse[number]; onClick?: () => void }) {
const t = useExtracted();
+ const { hour12, formatDateTime } = useDateTimeFormat();
// Calculate session duration in minutes
const start = DateTime.fromSQL(session.session_start, { zone: "utc" });
const end = DateTime.fromSQL(session.session_end, { zone: "utc" });
@@ -80,12 +82,14 @@ function SessionCard({ session, onClick }: { session: GetSessionsResponse[number
<div className="flex space-x-2 items-center pr-2">
<div className="flex items-center gap-1.5 text-xs text-neutral-300">
<span className="text-neutral-400">
- {DateTime.fromSQL(session.session_start, {
- zone: "utc",
- })
- .setLocale(userLocale)
- .setZone(getTimezone())
- .toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm")}
+ {formatDateTime(DateTime.fromSQL(session.session_start, { zone: "utc" }), {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ hour12,
+ timeZone: getTimezone(),
+ })}
</span>
<span className="text-neutral-400">•</span>
<span className="hidden md:block">{duration}</span>
diff --git a/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx b/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
index c9dafa326..018358379 100644
--- a/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
+++ b/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
@@ -13,6 +13,7 @@ import { DateTime } from "luxon";
import { ChevronDown, ChevronUp, Loader2, Search, SquareArrowOutUpRight } from "lucide-react";
import { useExtracted } from "next-intl";
import { useEffect, useMemo, useState } from "react";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
import { OutboundLink } from "../../../../../api/analytics/endpoints";
import { cn } from "../../../../../lib/utils";
@@ -29,6 +30,7 @@ type SortKey = "url" | "count" | "percentage" | "lastClicked";
export function OutboundLinksDialog({ outboundLinks, expanded, close }: OutboundLinksDialogProps) {
const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearchTerm = useDebounce(searchTerm, 200);
const [sortKey, setSortKey] = useState<SortKey>("count");
@@ -189,7 +191,7 @@ export function OutboundLinksDialog({ outboundLinks, expanded, close }: Outbound
{(() => {
try {
const dt = DateTime.fromSQL(row.lastClicked, { zone: "utc" }).setZone(getTimezone());
- return dt.toRelative();
+ return formatRelative(dt);
} catch {
return "-";
}
diff --git a/client/src/app/[site]/replay/components/ReplayCard.tsx b/client/src/app/[site]/replay/components/ReplayCard.tsx
index ee00c62d3..c09d98342 100644
--- a/client/src/app/[site]/replay/components/ReplayCard.tsx
+++ b/client/src/app/[site]/replay/components/ReplayCard.tsx
@@ -3,6 +3,7 @@ import { Clock, MousePointerClick, Trash2 } from "lucide-react";
import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
import { useState } from "react";
+import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
import { useDeleteSessionReplay } from "../../../../api/analytics/hooks/sessionReplay/useDeleteSessionReplay";
import { Avatar } from "../../../../components/Avatar";
import { IdentifiedBadge } from "../../../../components/IdentifiedBadge";
@@ -53,6 +54,7 @@ interface SessionReplayListItem {
export function ReplayCard({ replay }: { replay: SessionReplayListItem }) {
const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
const { sessionId, setSessionId, resetPlayerState } = useReplayStore();
const [isDialogOpen, setIsDialogOpen] = useState(false);
const deleteSessionReplay = useDeleteSessionReplay();
@@ -106,7 +108,7 @@ export function ReplayCard({ replay }: { replay: SessionReplayListItem }) {
</div>
<div className="flex items-center gap-2 mb-1">
- <div className="text-xs text-neutral-600 dark:text-neutral-400">{startTime.toRelative()}</div>
+ <div className="text-xs text-neutral-600 dark:text-neutral-400">{formatRelative(startTime)}</div>
{duration && (
<div className="flex items-center gap-1 text-neutral-600 dark:text-neutral-400 text-xs">
<Clock className="w-3 h-3" />
diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
index 051fd519a..a072c336b 100644
--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
@@ -8,6 +8,7 @@ import { Avatar, generateName } from "../../../../../components/Avatar";
import { Badge } from "../../../../../components/ui/badge";
import { Skeleton } from "../../../../../components/ui/skeleton";
import { IdentifiedBadge } from "../../../../../components/IdentifiedBadge";
+import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";
import { formatDuration } from "../../../../../lib/dateTimeUtils";
import { getCountryName, getLanguageName } from "../../../../../lib/utils";
import { Browser } from "../../../components/shared/icons/Browser";
@@ -85,6 +86,7 @@ function StatCard({
export function UserSidebar({ data, isLoading, sessionCount, getRegionName }: UserSidebarProps) {
const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
const isIdentified = !!data?.identified_user_id;
// Filter custom traits (exclude username, name, email)
@@ -292,7 +294,7 @@ export function UserSidebar({ data, isLoading, sessionCount, getRegionName }: Us
{device.anonymous_id}
</span>
<span className="text-neutral-400 dark:text-neutral-500 text-xs">
- {DateTime.fromISO(device.created_at).toRelative()}
+ {formatRelative(DateTime.fromISO(device.created_at))}
</span>
</div>
))}
diff --git a/client/src/app/[site]/users/components/UsersTable.tsx b/client/src/app/[site]/users/components/UsersTable.tsx
index c9bf2409b..139d171e3 100644
--- a/client/src/app/[site]/users/components/UsersTable.tsx
+++ b/client/src/app/[site]/users/components/UsersTable.tsx
@@ -16,6 +16,7 @@ import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useExtracted } from "next-intl";
+import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
import { useDebounce } from "@uidotdev/usehooks";
import { UsersResponse } from "../../../../api/analytics/endpoints";
import { useGetUsers } from "../../../../api/analytics/hooks/useGetUsers";
@@ -73,19 +74,20 @@ const SortHeader = ({ column, children }: any) => {
);
};
-const formatRelativeTime = (dateStr: string) => {
- const date = DateTime.fromSQL(dateStr, { zone: "utc" }).setZone(getTimezone());
- const diff = Math.abs(date.diffNow(["minutes"]).minutes);
+export function UsersTable() {
+ const t = useExtracted();
+ const { formatRelative, formatDateTime } = useDateTimeFormat();
- if (diff < 1) {
- return "<1 min ago";
- }
+ const formatRelativeTime = (dateStr: string) => {
+ const date = DateTime.fromSQL(dateStr, { zone: "utc" }).setZone(getTimezone());
+ const diff = Math.abs(date.diffNow(["minutes"]).minutes);
- return date.toRelative();
-};
+ if (diff < 1) {
+ return "<1 min ago";
+ }
-export function UsersTable() {
- const t = useExtracted();
+ return formatRelative(date);
+ };
const { site } = useParams();
const [pagination, setPagination] = useState({
@@ -256,7 +258,7 @@ export function UsersTable() {
const date = DateTime.fromSQL(info.getValue(), {
zone: "utc",
}).setZone(getTimezone());
- const formattedDate = date.toLocaleString(DateTime.DATETIME_SHORT);
+ const formattedDate = formatDateTime(date, { year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "2-digit" });
const relativeTime = formatRelativeTime(info.getValue());
return (
@@ -279,7 +281,7 @@ export function UsersTable() {
const date = DateTime.fromSQL(info.getValue(), {
zone: "utc",
}).setZone(getTimezone());
- const formattedDate = date.toLocaleString(DateTime.DATETIME_SHORT);
+ const formattedDate = formatDateTime(date, { year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "2-digit" });
const relativeTime = formatRelativeTime(info.getValue());
return (
diff --git a/client/src/app/admin/components/organizations/OrganizationsTable.tsx b/client/src/app/admin/components/organizations/OrganizationsTable.tsx
index 5b638ae08..7a101337d 100644
--- a/client/src/app/admin/components/organizations/OrganizationsTable.tsx
+++ b/client/src/app/admin/components/organizations/OrganizationsTable.tsx
@@ -5,6 +5,7 @@ import { AdminOrganizationData } from "@/api/admin/endpoints";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
+import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
import { parseUtcTimestamp } from "@/lib/dateTimeUtils";
import { formatter } from "@/lib/utils";
import { ChevronDown, ChevronRight } from "lucide-react";
@@ -30,6 +31,7 @@ interface OrganizationsTableProps {
export function OrganizationsTable({ organizations, isLoading, searchQuery }: OrganizationsTableProps) {
const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
const [expandedOrgs, setExpandedOrgs] = useState<Set<string>>(new Set());
const [sorting, setSorting] = useState<SortingState>([]);
const [pagination, setPagination] = useState({
@@ -80,7 +82,7 @@ export function OrganizationsTable({ organizations, isLoading, searchQuery }: Or
{
accessorKey: "createdAt",
header: ({ column }) => <SortableHeader column={column}>{t("Created")}</SortableHeader>,
- cell: ({ row }) => <div>{parseUtcTimestamp(row.getValue("createdAt")).toRelative()}</div>,
+ cell: ({ row }) => <div>{formatRelative(parseUtcTimestamp(row.getValue("createdAt")))}</div>,
},
{
accessorKey: "monthlyEventCount",
diff --git a/client/src/app/admin/components/sites/Sites.tsx b/client/src/app/admin/components/sites/Sites.tsx
index 3b378a74c..b76631b11 100644
--- a/client/src/app/admin/components/sites/Sites.tsx
+++ b/client/src/app/admin/components/sites/Sites.tsx
@@ -24,6 +24,7 @@ import { AdminLayout } from "../shared/AdminLayout";
import { GrowthChart } from "../shared/GrowthChart";
import Link from "next/link";
import { Favicon } from "../../../../components/Favicon";
+import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
import { parseUtcTimestamp } from "../../../../lib/dateTimeUtils";
import { formatter } from "../../../../lib/utils";
import { useExtracted } from "next-intl";
@@ -31,6 +32,7 @@ import { useExtracted } from "next-intl";
export function Sites() {
const { data: sites, isLoading, isError } = useAdminSites();
const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
const [searchQuery, setSearchQuery] = useState("");
const [sorting, setSorting] = useState<SortingState>([{ id: "eventsLast24Hours", desc: true }]);
const [pagination, setPagination] = useState({
@@ -80,7 +82,7 @@ export function Sites() {
{
accessorKey: "createdAt",
header: ({ column }) => <SortableHeader column={column}>{t("Created")}</SortableHeader>,
- cell: ({ row }) => <div>{parseUtcTimestamp(row.getValue("createdAt")).toRelative()}</div>,
+ cell: ({ row }) => <div>{formatRelative(parseUtcTimestamp(row.getValue("createdAt")))}</div>,
},
{
accessorKey: "public",
diff --git a/client/src/app/admin/components/users/UsersTable.tsx b/client/src/app/admin/components/users/UsersTable.tsx
index 3c0c94a58..963c6547d 100644
--- a/client/src/app/admin/components/users/UsersTable.tsx
+++ b/client/src/app/admin/components/users/UsersTable.tsx
@@ -36,6 +36,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
import { UserTableSkeleton } from "./UserTableSkeleton";
import { userStore } from "@/lib/userStore";
import { SortableHeader } from "../shared/SortableHeader";
+import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
import { parseUtcTimestamp } from "../../../../lib/dateTimeUtils";
import { AddToOrganizationDialog } from "./AddToOrganizationDialog";
import { useRemoveUserFromOrganization } from "@/api/admin/hooks/useOrganizations";
@@ -83,6 +84,7 @@ export function UsersTable({
const { data: organizations } = useAdminOrganizations();
const removeUserFromOrganization = useRemoveUserFromOrganization();
const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
const handleRemoveFromOrganization = async () => {
if (!selectedUser || !selectedOrganizationId) return;
@@ -127,7 +129,7 @@ export function UsersTable({
{
accessorKey: "createdAt",
header: ({ column }) => <SortableHeader column={column}>{t("Created At")}</SortableHeader>,
- cell: ({ row }) => <div>{parseUtcTimestamp(row.getValue("createdAt")).toRelative()}</div>,
+ cell: ({ row }) => <div>{formatRelative(parseUtcTimestamp(row.getValue("createdAt")))}</div>,
},
{
id: "actions",
diff --git a/client/src/app/uptime/incidents/page.tsx b/client/src/app/uptime/incidents/page.tsx
index 8ba81665c..f7285cb75 100644
--- a/client/src/app/uptime/incidents/page.tsx
+++ b/client/src/app/uptime/incidents/page.tsx
@@ -10,6 +10,7 @@ import {
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
import { getTimezone } from "@/lib/store";
import { cn } from "@/lib/utils";
import { AlertCircle, CheckCircle, MoreHorizontal } from "lucide-react";
@@ -23,11 +24,6 @@ import {
useResolveIncident,
} from "../../../api/uptime/incidents";
-const formatStartTime = (timestamp: string) => {
- const dt = DateTime.fromSQL(timestamp, { zone: "UTC" }).setZone(getTimezone());
- return dt.toRelative() || dt.toFormat("MMM dd, HH:mm");
-};
-
const getStatusIcon = (status: UptimeIncident["status"]) => {
switch (status) {
case "active":
@@ -76,6 +72,13 @@ const formatDuration = (startTime: string, endTime: string | null): string => {
};
export default function IncidentsPage() {
+ const { formatRelative } = useDateTimeFormat();
+
+ const formatStartTime = (timestamp: string) => {
+ const dt = DateTime.fromSQL(timestamp, { zone: "UTC" }).setZone(getTimezone());
+ return formatRelative(dt);
+ };
+
const [statusFilter, setStatusFilter] = useState<"active" | "acknowledged" | "resolved" | "all">("active");
const { data, isLoading } = useIncidents({ status: statusFilter });
diff --git a/client/src/components/Avatar.tsx b/client/src/components/Avatar.tsx
index ad59d2fa1..6186a9cc1 100644
--- a/client/src/components/Avatar.tsx
+++ b/client/src/components/Avatar.tsx
@@ -2,6 +2,7 @@ import BoringAvatar from "boring-avatars";
import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
import { animals, colors, uniqueNamesGenerator } from "unique-names-generator";
+import { useDateTimeFormat } from "../hooks/useDateTimeFormat";
import { getTimezone } from "../lib/store";
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
@@ -30,6 +31,7 @@ export const AVATAR_COLORS = [
export function Avatar({ id, size = 20, lastActiveTime }: { id: string; size?: number; lastActiveTime?: DateTime }) {
const t = useExtracted();
+ const { formatRelative } = useDateTimeFormat();
const timeSinceEnd = lastActiveTime ? -lastActiveTime.setZone(getTimezone()).diffNow().toMillis() / 1000 : 0;
const online = lastActiveTime ? timeSinceEnd < 300 : false;
return (
@@ -44,7 +46,7 @@ export function Avatar({ id, size = 20, lastActiveTime }: { id: string; size?: n
/>
</TooltipTrigger>
<TooltipContent>
- <p>{t("Active {time}", { time: lastActiveTime?.toRelative() ?? "" })}</p>
+ <p>{t("Active {time}", { time: lastActiveTime ? formatRelative(lastActiveTime) : "" })}</p>
</TooltipContent>
</Tooltip>
)}
diff --git a/client/src/components/EventUsageChart.tsx b/client/src/components/EventUsageChart.tsx
index 2b7bce395..b45bcda9f 100644
--- a/client/src/components/EventUsageChart.tsx
+++ b/client/src/components/EventUsageChart.tsx
@@ -2,7 +2,7 @@
import { EventCountRow } from "@/api/admin/endpoints/adminServiceEventCount";
import { ChartTooltip } from "@/components/charts/ChartTooltip";
-import { userLocale } from "@/lib/dateTimeUtils";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
import { useNivoTheme } from "@/lib/nivo";
import { formatter } from "@/lib/utils";
import { ResponsiveLine } from "@nivo/line";
@@ -41,6 +41,7 @@ export function EventUsageChart({
const { width } = useWindowSize();
const t = useExtracted();
const nivoTheme = useNivoTheme();
+ const { locale, formatDateTime } = useDateTimeFormat();
const [hiddenSeries, setHiddenSeries] = useState<Set<string>>(new Set());
const maxTicks = Math.round((width ?? Infinity) / 200);
@@ -160,8 +161,7 @@ export function EventUsageChart({
truncateTickAt: 0,
tickValues: Math.min(maxTicks, maxTickCount),
format: (value) => {
- const dt = DateTime.fromJSDate(value).setLocale(userLocale);
- return dt.toFormat("MMM d");
+ return new Intl.DateTimeFormat(locale, { month: "short", day: "numeric" }).format(value);
},
}}
axisLeft={{
@@ -192,7 +192,7 @@ export function EventUsageChart({
<ChartTooltip>
<div className="p-3 min-w-[100px]">
<div className="font-medium mb-1">
- {currentTime.toLocaleString(DateTime.DATE_MED)}
+ {formatDateTime(currentTime, { month: "short", day: "numeric", year: "numeric" })}
</div>
{slice.points
.sort(
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index 4108aa957..8d6ebd1f4 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -9,7 +9,8 @@ import Link from "next/link";
import { useParams } from "next/navigation";
import { memo, useCallback, useState } from "react";
import { GetSessionsResponse } from "../../api/analytics/endpoints";
-import { formatShortDuration, hour12, userLocale } from "../../lib/dateTimeUtils";
+import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
+import { formatShortDuration } from "../../lib/dateTimeUtils";
import { cn, formatter, getUserDisplayName, truncateString } from "../../lib/utils";
import { Avatar } from "../Avatar";
import { Channel } from "../Channel";
@@ -36,6 +37,7 @@ interface SessionCardProps {
export function SessionCard({ session, onClick, userId, expandedByDefault, highlightedEventTimestamp }: SessionCardProps) {
const { site } = useParams();
const t = useExtracted();
+ const { hour12, formatDateTime } = useDateTimeFormat();
const [expanded, setExpanded] = useState(expandedByDefault || false);
const [replayDrawerOpen, setReplayDrawerOpen] = useState(false);
// Calculate session duration in minutes
@@ -85,12 +87,14 @@ export function SessionCard({ session, onClick, userId, expandedByDefault, highl
{!!session.identified_user_id && <IdentifiedBadge traits={session.traits} />}
</div>
<span className="text-xs text-neutral-500 dark:text-neutral-400">
- {DateTime.fromSQL(session.session_start, {
- zone: "utc",
- })
- .setLocale(userLocale)
- .setZone(getTimezone())
- .toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm")}
+ {formatDateTime(DateTime.fromSQL(session.session_start, { zone: "utc" }), {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ hour12,
+ timeZone: getTimezone(),
+ })}
</span>
</div>
@@ -287,12 +291,14 @@ export function SessionCard({ session, onClick, userId, expandedByDefault, highl
{/* Time information */}
<div className="flex items-center gap-1.5 text-xs text-neutral-600 dark:text-neutral-300">
<span className="text-neutral-500 dark:text-neutral-400">
- {DateTime.fromSQL(session.session_start, {
- zone: "utc",
- })
- .setLocale(userLocale)
- .setZone(getTimezone())
- .toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm")}
+ {formatDateTime(DateTime.fromSQL(session.session_start, { zone: "utc" }), {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ hour12,
+ timeZone: getTimezone(),
+ })}
</span>
<span className="text-neutral-500 dark:text-neutral-400">•</span>
<span>{duration}</span>
diff --git a/client/src/components/Sessions/SessionDetails/PageviewItem.tsx b/client/src/components/Sessions/SessionDetails/PageviewItem.tsx
index 9cfc02896..dcc0637f3 100644
--- a/client/src/components/Sessions/SessionDetails/PageviewItem.tsx
+++ b/client/src/components/Sessions/SessionDetails/PageviewItem.tsx
@@ -8,7 +8,8 @@ import Link from "next/link";
import { useExtracted } from "next-intl";
import { SessionEvent } from "../../../api/analytics/endpoints";
import { getEventDisplayName, PROPS_TO_HIDE } from "../../../lib/events";
-import { formatDuration, hour12 } from "../../../lib/dateTimeUtils";
+import { useDateTimeFormat } from "../../../hooks/useDateTimeFormat";
+import { formatDuration } from "../../../lib/dateTimeUtils";
import { cn } from "../../../lib/utils";
import { EventTypeIcon } from "../../EventIcons";
@@ -169,6 +170,7 @@ export function PageviewItem({
highlightedEventTimestamp,
}: PageviewItemProps) {
const t = useExtracted();
+ const { hour12 } = useDateTimeFormat();
const isPageview = item.type === "pageview";
const isOutbound = item.type === "outbound";
const isEvent = item.type === "custom_event";
diff --git a/client/src/components/replay/ReplayBreadcrumbs.tsx b/client/src/components/replay/ReplayBreadcrumbs.tsx
index 5ade42542..c1ec84f0d 100644
--- a/client/src/components/replay/ReplayBreadcrumbs.tsx
+++ b/client/src/components/replay/ReplayBreadcrumbs.tsx
@@ -36,6 +36,7 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { getTimezone } from "@/lib/store";
import { cn, getUserDisplayName } from "@/lib/utils";
import { useReplayStore } from "./replayStore";
+import { useExtracted } from "next-intl";
// Event type mapping based on rrweb event types
const EVENT_TYPE_INFO = {
@@ -150,6 +151,7 @@ const getEventColor = (event: any) => {
};
export function ReplayBreadcrumbs() {
+ const t = useExtracted();
const params = useParams();
const siteId = Number(params.site);
const { sessionId, player, setCurrentTime } = useReplayStore();
@@ -278,12 +280,12 @@ export function ReplayBreadcrumbs() {
{isIdentified && <IdentifiedBadge traits={data.metadata.traits} />}
</div>
<Link href={userLink} className="flex items-center gap-2">
- <Button size="sm">View User</Button>
+ <Button size="sm">{t("View User")}</Button>
</Link>
</div>
<div className="rounded-lg border border-neutral-100 dark:border-neutral-800 flex flex-col h-full bg-white dark:bg-neutral-900">
<div className="p-2 border-b border-neutral-100 dark:border-neutral-800 text-xs text-neutral-600 dark:text-neutral-400 shrink-0">
- {data.events.length} events captured ({groupedEvents.length} groups)
+ {t("{count} events captured ({groupCount} groups)", { count: String(data.events.length), groupCount: String(groupedEvents.length) })}
</div>
<ScrollArea className="flex-1 rounded-lg">
<div className="overflow-x-hidden">
diff --git a/client/src/hooks/useDateTimeFormat.ts b/client/src/hooks/useDateTimeFormat.ts
new file mode 100644
index 000000000..db4a36026
--- /dev/null
+++ b/client/src/hooks/useDateTimeFormat.ts
@@ -0,0 +1,69 @@
+import { TimeBucket } from "@rybbit/shared";
+import { DateTime } from "luxon";
+import { useLocale } from "next-intl";
+import { useMemo } from "react";
+import { getTimezone } from "@/lib/store";
+
+function getHour12ForLocale(locale: string): boolean {
+ const resolved = new Intl.DateTimeFormat(locale, { hour: "numeric" }).resolvedOptions();
+ return resolved.hourCycle === "h12";
+}
+
+export function useDateTimeFormat() {
+ const locale = useLocale();
+ const hour12 = useMemo(() => getHour12ForLocale(locale), [locale]);
+
+ const formatDateTime = useMemo(
+ () =>
+ (dt: DateTime, options: Intl.DateTimeFormatOptions): string =>
+ new Intl.DateTimeFormat(locale, options).format(dt.toJSDate()),
+ [locale]
+ );
+
+ const formatRelative = useMemo(
+ () =>
+ (dt: DateTime): string =>
+ dt.setLocale(locale).toRelative() ??
+ new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(dt.toJSDate()),
+ [locale]
+ );
+
+ const formatChartDateTime = useMemo(() => {
+ return (dt: DateTime, bucket: TimeBucket): string => {
+ const showMinutes = [
+ "minute",
+ "five_minutes",
+ "ten_minutes",
+ "fifteen_minutes",
+ "hour",
+ ].includes(bucket);
+ const options: Intl.DateTimeFormatOptions = {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ hour12,
+ timeZone: getTimezone(),
+ };
+ if (showMinutes && !hour12) {
+ options.minute = "numeric";
+ }
+ if (bucket === "day") {
+ options.minute = undefined;
+ options.hour = undefined;
+ options.weekday = "short";
+ }
+ if (
+ bucket === "fifteen_minutes" ||
+ bucket === "ten_minutes" ||
+ bucket === "five_minutes" ||
+ bucket === "minute"
+ ) {
+ options.minute = "numeric";
+ options.hour = "numeric";
+ }
+ return new Intl.DateTimeFormat(locale, options).format(dt.toJSDate());
+ };
+ }, [locale, hour12]);
+
+ return { locale, hour12, formatDateTime, formatRelative, formatChartDateTime };
+}
diff --git a/client/src/lib/dateTimeUtils.ts b/client/src/lib/dateTimeUtils.ts
index 3610dc22d..36908b5a5 100644
--- a/client/src/lib/dateTimeUtils.ts
+++ b/client/src/lib/dateTimeUtils.ts
@@ -155,7 +155,7 @@ export const hourMinuteLabels: string[] = getLocalizedTimeLabels(userLocale, {
hour12: hour12,
});
-export const formatChartDateTime = (dt: DateTime, bucket: TimeBucket) => {
+export const formatChartDateTime = (dt: DateTime, bucket: TimeBucket, locale = userLocale) => {
const showMinutes = ["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour"].includes(bucket);
const options: Intl.DateTimeFormatOptions = {
month: "short",
@@ -176,7 +176,7 @@ export const formatChartDateTime = (dt: DateTime, bucket: TimeBucket) => {
options.minute = "numeric";
options.hour = "numeric";
}
- return new Intl.DateTimeFormat(userLocale, options).format(dt.toJSDate());
+ return new Intl.DateTimeFormat(locale, options).format(dt.toJSDate());
};
/**