Skip to content

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

Enhance analytics page title functionality and UI

Bill Yang830dbca9b083
diff --git a/client/src/api/analytics/useGetPageTitles.ts b/client/src/api/analytics/useGetPageTitles.ts
index 9be470526..62bfc558e 100644
--- a/client/src/api/analytics/useGetPageTitles.ts
+++ b/client/src/api/analytics/useGetPageTitles.ts
@@ -11,6 +11,7 @@ export type PageTitleItem = {
pathname: string; // A representative pathname
count: number;
percentage: number;
+ time_on_page_seconds?: number;
// Add other potential fields if your backend query for page_titles includes them
};
diff --git a/client/src/app/[site]/pages/components/PageListItem.tsx b/client/src/app/[site]/pages/components/PageListItem.tsx
index bdb58f7b6..6798984ae 100644
--- a/client/src/app/[site]/pages/components/PageListItem.tsx
+++ b/client/src/app/[site]/pages/components/PageListItem.tsx
@@ -10,6 +10,7 @@ import { usePageMetadata } from "@/api/usePageMetadata";
import { Card, CardContent } from "@/components/ui/card";
import { Filter, useStore } from "@/lib/store";
import { truncateString } from "@/lib/utils";
+import { formatShortDuration } from "@/lib/dateTimeUtils";
import { ExternalLink } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
@@ -156,12 +157,22 @@ export function PageListItem({
/>
</div>
- {/* Session count */}
- <div className="text-right min-w-[70px]">
- <div className="text-lg font-semibold">
- {pageData.count.toLocaleString()}
+ {/* Session count and duration */}
+ <div className="text-right min-w-[120px]">
+ <div>
+ <span className="text-base font-semibold">
+ {pageData.count.toLocaleString()}
+ </span>
+ <span className="text-xs text-foreground/70"> sessions</span>
</div>
- <div className="text-xs text-muted-foreground">sessions</div>
+ {pageData.time_on_page_seconds !== undefined && (
+ <div>
+ <span className="text-base font-semibold">
+ {formatShortDuration(pageData.time_on_page_seconds)}{" "}
+ </span>
+ <span className="text-xs text-foreground/70">avg time</span>
+ </div>
+ )}
</div>
</div>
</div>
diff --git a/client/src/app/[site]/pages/page.tsx b/client/src/app/[site]/pages/page.tsx
index 77cb603c2..e11cf52a1 100644
--- a/client/src/app/[site]/pages/page.tsx
+++ b/client/src/app/[site]/pages/page.tsx
@@ -27,10 +27,6 @@ export default function Pages() {
useSetPageTitle("Rybbit · Pages");
- if (!site) {
- return null;
- }
-
// Get page number (1-based) from pageIndex (0-based)
const pageNumber = pagination.pageIndex + 1;
@@ -110,6 +106,10 @@ export default function Pages() {
pagination.pageSize,
]);
+ if (!site) {
+ return null;
+ }
+
return (
<DisabledOverlay message="pages">
<div className="p-2 md:p-4 max-w-[1100px] mx-auto space-y-3">
@@ -132,6 +132,7 @@ export default function Pages() {
title: pageItem.value,
count: pageItem.count,
percentage: pageItem.percentage,
+ time_on_page_seconds: pageItem.time_on_page_seconds,
}}
/>
))}
diff --git a/client/src/lib/dateTimeUtils.ts b/client/src/lib/dateTimeUtils.ts
index 7347083ff..54265a804 100644
--- a/client/src/lib/dateTimeUtils.ts
+++ b/client/src/lib/dateTimeUtils.ts
@@ -1,10 +1,13 @@
import { Duration, DurationLikeObject, Settings } from "luxon";
// Detect user locale from the browser environment (fallback to 'en-US' on server)
-export const userLocale = typeof navigator !== "undefined" ? navigator.language : "en-US";
+export const userLocale =
+ typeof navigator !== "undefined" ? navigator.language : "en-US";
// Detect whether the user prefers 12-hour time format (true = 12h, false = 24h)
-const resolved = new Intl.DateTimeFormat(userLocale, { hour: "numeric" }).resolvedOptions();
+const resolved = new Intl.DateTimeFormat(userLocale, {
+ hour: "numeric",
+}).resolvedOptions();
export const hour12 = resolved.hourCycle === "h12";
// Detect user's timezone (not exported but used internally)
@@ -30,7 +33,15 @@ export function getLocalizedWeekdayNames(
const fallback: Record<"narrow" | "short" | "long", string[]> = {
narrow: ["M", "T", "W", "T", "F", "S", "S"],
short: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
- long: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
+ long: [
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday",
+ "Sunday",
+ ],
};
const today = new Date();
@@ -78,7 +89,7 @@ export function getLocalizedTimeLabels(
export function formatDuration(duration: number): string {
// Prepare duration parts in seconds and optionally minutes.
const units: Record<string, number> = {
- seconds: duration % 60,
+ seconds: Math.round(duration % 60),
};
if (duration > 59) {
@@ -86,7 +97,8 @@ export function formatDuration(duration: number): string {
}
// Choose which units to show: only "seconds" or both "minutes" and "seconds".
- const keys: (keyof DurationLikeObject)[] = duration > 59 ? ["minutes", "seconds"] : ["seconds"];
+ const keys: (keyof DurationLikeObject)[] =
+ duration > 59 ? ["minutes", "seconds"] : ["seconds"];
// Convert to Luxon duration object and format to human-readable string.
const luxonDuration = Duration.fromObject(units)
@@ -99,6 +111,22 @@ export function formatDuration(duration: number): string {
});
}
+/**
+ * Formats a duration in seconds to a compact string using short units.
+ *
+ * @param seconds - Duration in seconds.
+ * @returns Compact duration string (e.g., "1m 10s", "45s").
+ */
+export function formatShortDuration(seconds: number): string {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.round(seconds % 60);
+
+ if (mins > 0) {
+ return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
+ }
+ return `${secs}s`;
+}
+
/**
* Formats a given hour and minute into a localized time string
* (e.g., "11:00 AM" or "23:00"), using the detected `hour12` preference.
@@ -123,10 +151,16 @@ export const formatLocalTime = (hour: number, minute: number): string => {
// --- Precomputed localized data ---
// Full weekday names (e.g., "Monday", "Tuesday")
-export const longDayNames: string[] = getLocalizedWeekdayNames(userLocale, "long");
+export const longDayNames: string[] = getLocalizedWeekdayNames(
+ userLocale,
+ "long"
+);
// Short weekday names (e.g., "Mon", "Tue")
-export const shortDayNames: string[] = getLocalizedWeekdayNames(userLocale, "short");
+export const shortDayNames: string[] = getLocalizedWeekdayNames(
+ userLocale,
+ "short"
+);
// Hour-only labels (e.g., "00", "01", "02", "1 AM", "2 PM")
export const hourLabels: string[] = getLocalizedTimeLabels(userLocale, {
diff --git a/server/src/api/analytics/getPageTitles.ts b/server/src/api/analytics/getPageTitles.ts
index 77a11fd03..986f162d0 100644
--- a/server/src/api/analytics/getPageTitles.ts
+++ b/server/src/api/analytics/getPageTitles.ts
@@ -29,6 +29,7 @@ export type PageTitleItem = {
pathname: string;
count: number;
percentage: number;
+ time_on_page_seconds?: number;
};
// Structure for paginated response (if/when fully paginated)
@@ -95,38 +96,64 @@ const getPageTitlesQuery = (
!isCountQuery && validatedOffset ? `OFFSET ${validatedOffset}` : "";
// For page_title, we want to count distinct sessions that viewed this title.
- // We also need a representative pathname.
+ // We also need a representative pathname and calculate average time on page.
// Using argMax to get the pathname from the most recent event for that title in a session.
- const coreLogic = `
- SELECT
- page_title as value,
- argMax(pathname, timestamp) as pathname, // Get pathname of latest event for this title in session
- COUNT(DISTINCT session_id) as unique_sessions
- FROM events
- WHERE
- site_id = {siteId:Int32}
- AND page_title IS NOT NULL
- AND page_title <> ''
- AND type = 'pageview' // Ensure these are pageview events
- ${filterStatement}
- ${timeStatement}
- GROUP BY page_title
+ const baseCteQuery = `
+ EventTimes AS (
+ SELECT
+ session_id,
+ page_title,
+ pathname,
+ timestamp,
+ leadInFrame(timestamp) OVER (PARTITION BY session_id ORDER BY timestamp ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) as next_timestamp
+ FROM events
+ WHERE
+ site_id = {siteId:Int32}
+ AND page_title IS NOT NULL
+ AND page_title <> ''
+ AND type = 'pageview'
+ ${filterStatement}
+ ${timeStatement}
+ ),
+ PageDurations AS (
+ SELECT
+ session_id,
+ page_title,
+ pathname,
+ timestamp,
+ next_timestamp,
+ if(isNull(next_timestamp), 0, dateDiff('second', timestamp, next_timestamp)) as time_diff_seconds
+ FROM EventTimes
+ ),
+ PageTitleStats AS (
+ SELECT
+ page_title as value,
+ argMax(pathname, timestamp) as pathname,
+ count(DISTINCT session_id) as unique_sessions,
+ avg(if(time_diff_seconds < 0, 0, if(time_diff_seconds > 1800, 1800, time_diff_seconds))) as avg_time_on_page_seconds
+ FROM PageDurations
+ GROUP BY page_title
+ )
`;
if (isCountQuery) {
- return `SELECT COUNT(*) as totalCount FROM (${coreLogic})`;
+ return `
+ WITH ${baseCteQuery}
+ SELECT COUNT(*) as totalCount FROM PageTitleStats;
+ `;
}
return `
- WITH PageTitleStats AS (${coreLogic})
+ WITH ${baseCteQuery}
SELECT
value,
pathname,
unique_sessions as count,
ROUND(
- unique_sessions * 100.0 / SUM(unique_sessions) OVER (),
+ unique_sessions * 100.0 / SUM(unique_sessions) OVER (),
2
- ) as percentage
+ ) as percentage,
+ avg_time_on_page_seconds as time_on_page_seconds
FROM PageTitleStats
ORDER BY count DESC
${limitStatement}