Skip to content

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

Refactor: centralize locale date/time utils and add localeFormat helper

Andrii Andrushchyshyn3af5b0cc2f88
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 16f04c2af..3e3d8ac41 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -8,11 +8,7 @@ import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGet
import { APIResponse } from "../../../../../api/types";
import { Time } from "../../../../../components/DateSelector/types";
import { formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";
-
-// Detect user locale and 12h/24h preference
-const userLocale = typeof navigator !== "undefined" ? navigator.language : "en";
-const resolved = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }).resolvedOptions();
-const is24Hour = resolved.hourCycle === 'h23' || resolved.hourCycle === 'h24';
+import { userLocale, is24Hour } from "../../../../../lib/dateTimeUtils";
export const formatter = Intl.NumberFormat(userLocale, { notation: "compact" });
diff --git a/client/src/app/[site]/retention/RetentionChart.tsx b/client/src/app/[site]/retention/RetentionChart.tsx
index 306cb718b..c3ae74e51 100644
--- a/client/src/app/[site]/retention/RetentionChart.tsx
+++ b/client/src/app/[site]/retention/RetentionChart.tsx
@@ -9,6 +9,7 @@ import {
RetentionMode,
} from "../../../api/analytics/useGetRetention";
import { Skeleton } from "../../../components/ui/skeleton";
+import { localeFormat } from "../../../lib/dateTimeUtils";
interface RetentionChartProps {
data: ProcessedRetentionData | undefined;
@@ -16,9 +17,6 @@ interface RetentionChartProps {
mode: RetentionMode;
}
-// Detect user locale and 12h/24h preference
-const userLocale = typeof navigator !== "undefined" ? navigator.language : "en";
-
// Vibrant color palette for different cohorts using Tailwind CSS HSL variables
const cohortColors = [
"hsl(var(--accent-500))", // Primary accent color
@@ -80,7 +78,7 @@ export function RetentionChart({ data, isLoading, mode }: RetentionChartProps) {
// Format the date label based on mode
let formattedDate: string;
if (mode === "day") {
- formattedDate = DateTime.fromISO(cohortKey).setLocale(userLocale).toFormat("MMM dd");
+ formattedDate = localeFormat(DateTime.fromISO(cohortKey), "MMM dd");
} else {
// For weekly mode
const startDate = DateTime.fromISO(cohortKey);
@@ -88,13 +86,9 @@ export function RetentionChart({ data, isLoading, mode }: RetentionChartProps) {
// If same month, don't repeat month
if (startDate.month === endDate.month) {
- formattedDate = `${startDate.setLocale(userLocale).toFormat("MMM dd")}-${endDate.setLocale(userLocale).toFormat(
- "dd"
- )}`;
+ formattedDate = `${localeFormat(startDate, "MMM dd")}-${localeFormat(endDate, "dd")}`;
} else {
- formattedDate = `${startDate.setLocale(userLocale).toFormat("MMM dd")}-${endDate.setLocale(userLocale).toFormat(
- "MMM dd"
- )}`;
+ formattedDate = `${localeFormat(startDate, "MMM dd")}-${localeFormat(endDate, "MMM dd")}`;
}
}
@@ -214,25 +208,21 @@ export function RetentionChart({ data, isLoading, mode }: RetentionChartProps) {
// Format full date for tooltip
let cohortDateDisplay = point.seriesId;
if (originalCohortKey) {
+ const startDate = DateTime.fromISO(originalCohortKey);
if (mode === "day") {
- cohortDateDisplay =
- DateTime.fromISO(originalCohortKey).setLocale(userLocale).toFormat("MMM dd, yyyy");
+ cohortDateDisplay = localeFormat(startDate, "MMM dd, yyyy");
} else {
- const startDate = DateTime.fromISO(originalCohortKey);
const endDate = startDate.plus({ days: 6 });
if (startDate.month === endDate.month) {
- cohortDateDisplay = `${startDate.setLocale(userLocale).toFormat(
- "MMM dd"
- )} - ${endDate.setLocale(userLocale).toFormat("dd, yyyy")}`;
+ cohortDateDisplay = `${localeFormat(startDate, "MMM dd"
+ )} - ${localeFormat(endDate, "dd, yyyy")}`;
} else if (startDate.year === endDate.year) {
- cohortDateDisplay = `${startDate.setLocale(userLocale).toFormat(
- "MMM dd"
- )} - ${endDate.setLocale(userLocale).toFormat("MMM dd, yyyy")}`;
+ cohortDateDisplay = `${localeFormat(startDate, "MMM dd"
+ )} - ${localeFormat(endDate, "MMM dd, yyyy")}`;
} else {
- cohortDateDisplay = `${startDate.setLocale(userLocale).toFormat(
- "MMM dd, yyyy"
- )} - ${endDate.setLocale(userLocale).toFormat("MMM dd, yyyy")}`;
+ cohortDateDisplay = `${localeFormat(startDate, "MMM dd, yyyy"
+ )} - ${localeFormat(endDate, "MMM dd, yyyy")}`;
}
}
}
diff --git a/client/src/app/[site]/retention/page.tsx b/client/src/app/[site]/retention/page.tsx
index b40dc87cb..77ff5fb02 100644
--- a/client/src/app/[site]/retention/page.tsx
+++ b/client/src/app/[site]/retention/page.tsx
@@ -25,9 +25,7 @@ import { Tabs, TabsList, TabsTrigger } from "../../../components/ui/tabs";
import { RetentionChart } from "./RetentionChart";
import { NothingFound } from "../../../components/NothingFound";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-
-// Detect user locale and 12h/24h preference
-const userLocale = typeof navigator !== "undefined" ? navigator.language : "en";
+import { localeFormat } from "../../../lib/dateTimeUtils";
// Available time range options (in days)
const RANGE_OPTIONS = [
@@ -102,7 +100,8 @@ export default function RetentionPage() {
// Function to format date based on mode
const formatDate = (dateStr: string) => {
if (mode === "day") {
- return DateTime.fromISO(dateStr).setLocale(userLocale).toFormat("MMM dd, yyyy");
+ const date = DateTime.fromISO(dateStr);
+ return localeFormat(date, "MMM dd, yyyy");
} else {
// For weekly mode, show start and end dates of the week
const startDate = DateTime.fromISO(dateStr);
@@ -110,19 +109,13 @@ export default function RetentionPage() {
// If same month, don't repeat month name
if (startDate.month === endDate.month) {
- return `${startDate.setLocale(userLocale).toFormat("MMM dd")} - ${endDate.setLocale(userLocale).toFormat(
- "dd, yyyy"
- )}`;
+ return `${localeFormat(startDate, "MMM dd")} - ${localeFormat(endDate, "dd, yyyy")}`;
} else if (startDate.year === endDate.year) {
// Different months, same year
- return `${startDate.setLocale(userLocale).toFormat("MMM dd")} - ${endDate.setLocale(userLocale).toFormat(
- "MMM dd, yyyy"
- )}`;
+ return `${localeFormat(startDate, "MMM dd")} - ${localeFormat(endDate, "MMM dd, yyyy")}`;
} else {
// Different years
- return `${startDate.setLocale(userLocale).toFormat("MMM dd, yyyy")} - ${endDate.setLocale(userLocale).toFormat(
- "MMM dd, yyyy"
- )}`;
+ return `${localeFormat(startDate, "MMM dd, yyyy")} - ${localeFormat(endDate, "MMM dd, yyyy")}`;
}
}
};
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index dd9c77d73..a3dee8202 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -19,9 +19,11 @@ import { GetSessionsResponse } from "../../api/analytics/userSessions";
import { Browser } from "../../app/[site]/components/shared/icons/Browser";
import { CountryFlag } from "../../app/[site]/components/shared/icons/CountryFlag";
import { OperatingSystem } from "../../app/[site]/components/shared/icons/OperatingSystem";
-import { cn, formatter, getCountryName, formatDurationHuman } from "../../lib/utils";
+import { cn, formatter, getCountryName } from "../../lib/utils";
+import { formatDuration } from "../../lib/dateTimeUtils";
import { Badge } from "../ui/badge";
import { SessionDetails } from "./SessionDetails";
+import { userLocale, is24Hour } from "../../lib/dateTimeUtils";
interface SessionCardProps {
session: GetSessionsResponse[number];
@@ -49,11 +51,6 @@ function truncatePath(path: string, maxLength: number = 32) {
return `${path.substring(0, maxLength)}...`;
}
-// Detect user locale and 12h/24h preference
-const userLocale = typeof navigator !== "undefined" ? navigator.language : "en";
-const resolved = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }).resolvedOptions();
-const is24Hour = resolved.hourCycle === 'h23' || resolved.hourCycle === 'h24';
-
export function SessionCard({ session, onClick, userId }: SessionCardProps) {
const [expanded, setExpanded] = useState(false);
@@ -61,7 +58,7 @@ export function SessionCard({ session, onClick, userId }: SessionCardProps) {
const start = DateTime.fromSQL(session.session_start);
const end = DateTime.fromSQL(session.session_end);
const duration = end.diff(start, ["minutes", "seconds"]);
- const durationFormatted = formatDurationHuman(duration.minutes, duration.seconds);
+ const durationFormatted = formatDuration(duration.minutes, duration.seconds);
// Truncate user ID to first 8 characters
const truncatedUserId = session.user_id.substring(0, 8);
diff --git a/client/src/components/Sessions/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails.tsx
index 38838318b..687ea967d 100644
--- a/client/src/components/Sessions/SessionDetails.tsx
+++ b/client/src/components/Sessions/SessionDetails.tsx
@@ -26,13 +26,10 @@ import {
import { Browser } from "../../app/[site]/components/shared/icons/Browser";
import { CountryFlag } from "../../app/[site]/components/shared/icons/CountryFlag";
import { OperatingSystem } from "../../app/[site]/components/shared/icons/OperatingSystem";
-import { cn, getCountryName, getLanguageName, formatDurationHuman } from "../../lib/utils";
+import { cn, getCountryName, getLanguageName } from "../../lib/utils";
+import { formatDuration } from "../../lib/dateTimeUtils";
import { Button } from "../ui/button";
-
-// Detect user locale and 12h/24h preference
-const userLocale = typeof navigator !== "undefined" ? navigator.language : "en";
-const resolved = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }).resolvedOptions();
-const is24Hour = resolved.hourCycle === 'h23' || resolved.hourCycle === 'h24';
+import { localeFormat, is24Hour } from "../../lib/dateTimeUtils";
// Component to display a single pageview or event
function PageviewItem({
@@ -48,10 +45,7 @@ function PageviewItem({
}) {
const isEvent = item.type !== "pageview";
const timestamp = DateTime.fromSQL(item.timestamp, { zone: "utc" }).toLocal();
- const formattedTime = timestamp.setLocale(userLocale)
- .toFormat(is24Hour? "HH:mm:ss" : "h:mm:ss a");
-
- console.info(item);
+ const formattedTime = localeFormat(timestamp, is24Hour ? "HH:mm:ss" : "h:mm:ss a");
// Calculate duration if this is a pageview and we have the next timestamp
let duration = null;
@@ -62,7 +56,7 @@ function PageviewItem({
const seconds = Math.floor(diff.seconds);
if (minutes > 0 || seconds > 0) {
- duration = formatDurationHuman(minutes, seconds);
+ duration = formatDuration(minutes, seconds);
}
}
diff --git a/client/src/components/SiteSessionChart.tsx b/client/src/components/SiteSessionChart.tsx
index 7105befe4..00317aa6f 100644
--- a/client/src/components/SiteSessionChart.tsx
+++ b/client/src/components/SiteSessionChart.tsx
@@ -4,17 +4,13 @@ import { DateTime } from "luxon";
import { useMemo } from "react";
import { GetOverviewBucketedResponse } from "../api/analytics/useGetOverviewBucketed";
import { formatter } from "../lib/utils";
+import { localeFormat, is24Hour } from "../lib/dateTimeUtils";
interface SiteSessionChartProps {
data: GetOverviewBucketedResponse;
height?: number | string;
}
-// Detect user locale and 12h/24h preference
-const userLocale = typeof navigator !== "undefined" ? navigator.language : "en";
-const resolved = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }).resolvedOptions();
-const is24Hour = resolved.hourCycle === 'h23' || resolved.hourCycle === 'h24';
-
export function SiteSessionChart({
data,
height = 100,
@@ -64,9 +60,8 @@ export function SiteSessionChart({
tickRotation: 0,
tickValues: 3,
format: (value) => {
- return DateTime.fromJSDate(value)
- .setLocale(userLocale)
- .toFormat(is24Hour ? 'HH:mm' : 'ha');
+ const time = DateTime.fromJSDate(value);
+ return localeFormat(time, is24Hour ? "HH:mm" : "ha");
},
}}
axisLeft={{
@@ -103,10 +98,7 @@ export function SiteSessionChart({
<div className="text-xs mb-1">Sessions</div>
<div className="flex justify-between text-xs w-20">
<div className="text-muted-foreground">
- {currentTime
- .setLocale(userLocale)
- .toFormat(is24Hour ? 'HH:mm' : 'ha')
- }
+ { localeFormat(currentTime, is24Hour ? "HH:mm" : "ha") }
</div>
<div className="font-medium">{currentY.toLocaleString()}</div>
</div>
diff --git a/client/src/lib/dateTimeUtils.ts b/client/src/lib/dateTimeUtils.ts
new file mode 100644
index 000000000..e1ae745b0
--- /dev/null
+++ b/client/src/lib/dateTimeUtils.ts
@@ -0,0 +1,58 @@
+
+import { Duration, DateTime } from "luxon";
+
+/**
+ * Formats a duration given in minutes and seconds into a human-readable string.
+ *
+ * Uses `luxon.Duration` to normalize and format the result, omitting zero units
+ * and showing the output in a compact style (e.g., "1 min 30 sec").
+ *
+ * @param minutes - Number of minutes.
+ * @param seconds - Number of seconds.
+ * @returns A human-readable duration string.
+ */
+export function formatDuration(minutes: number, seconds: number): string {
+ const units: Record<string, number> = {};
+
+ if (minutes > 0) {
+ units.minutes = minutes;
+ }
+
+ // Always show seconds if minutes is zero or seconds > 0
+ if (seconds > 0 || minutes === 0) {
+ units.seconds = seconds;
+ }
+
+ const duration = Duration.fromObject(units)
+ .shiftTo("minutes", "seconds")
+ .normalize();
+
+ return duration.toHuman({
+ listStyle: "narrow",
+ unitDisplay: "short",
+ });
+}
+
+/**
+ * Formats a Luxon DateTime object using a locale-aware format string.
+ *
+ * Internally sets the locale of the DateTime object to the detected user locale
+ * before formatting, ensuring the output reflects local conventions (e.g., month names, weekdays).
+ *
+ * @param dateTime - A Luxon DateTime instance to format.
+ * @param format - A Luxon-compatible format string (e.g., "yyyy-MM-dd", "HH:mm", "ccc").
+ * @returns The formatted date/time string according to the user's locale.
+ */
+export function localeFormat(dateTime: DateTime, format: string): string {
+ return dateTime.setLocale(userLocale).toFormat(format);
+}
+
+
+
+
+// Detect user locale
+export const userLocale = typeof navigator !== "undefined" ? navigator.language : "en";
+
+// Detect user 12h/24h preference
+const resolved = new Intl.DateTimeFormat(undefined, { hour: "numeric" }).resolvedOptions();
+export const is24Hour = resolved.hourCycle === "h23" || resolved.hourCycle === "h24";
diff --git a/client/src/lib/utils.ts b/client/src/lib/utils.ts
index 17ef3091e..a00dea859 100644
--- a/client/src/lib/utils.ts
+++ b/client/src/lib/utils.ts
@@ -47,25 +47,6 @@ export function formatDuration(seconds: number): string {
}
}
-export function formatDurationHuman(minutes: number, seconds: number) {
- const units: Record<string, number> = {};
- if (minutes > 0) {
- units.minutes = minutes;
- }
- if (seconds > 0 || minutes === 0) {
- units.seconds = seconds;
- }
-
- const duration = Duration.fromObject(units)
- .shiftTo('minutes', 'seconds')
- .normalize();
-
- return duration.toHuman({
- listStyle: 'narrow',
- unitDisplay: 'short'
- });
-}
-
export function truncateString(str: string, n = 50) {
return str.length > n ? str.substring(0, n) + "..." : str;
}