Skip to content

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

Integrate RealtimeEvents component and enhance visual elements in RealtimePage

Bill Yang8d02dcea190c
diff --git a/client/src/api/analytics/useGetEvents.ts b/client/src/api/analytics/useGetEvents.ts
new file mode 100644
index 000000000..9e7e7a50c
--- /dev/null
+++ b/client/src/api/analytics/useGetEvents.ts
@@ -0,0 +1,33 @@
+import { useQuery } from "@tanstack/react-query";
+import { useStore } from "../../lib/store";
+import { BACKEND_URL } from "../../lib/const";
+import { authedFetch } from "../utils";
+
+export type Event = {
+ timestamp: string;
+ event_name: string;
+ properties: string;
+ user_id: string;
+ hostname: string;
+ pathname: string;
+ querystring: string;
+ page_title: string;
+ referrer: string;
+ browser: string;
+ operating_system: string;
+ country: string;
+ device_type: string;
+ type: string;
+};
+
+export function useGetEvents(count = 10) {
+ const { site } = useStore();
+ return useQuery({
+ queryKey: ["events", site, count],
+ refetchInterval: 5000,
+ queryFn: () =>
+ authedFetch(`${BACKEND_URL}/events/${site}?count=${count}`).then((res) =>
+ res.json()
+ ),
+ });
+}
diff --git a/client/src/app/[site]/realtime/RealtimeEvents/RealtimeEvents.tsx b/client/src/app/[site]/realtime/RealtimeEvents/RealtimeEvents.tsx
new file mode 100644
index 000000000..649cd7f40
--- /dev/null
+++ b/client/src/app/[site]/realtime/RealtimeEvents/RealtimeEvents.tsx
@@ -0,0 +1,235 @@
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { FileText, Laptop, MousePointerClick, Smartphone } from "lucide-react";
+import { DateTime } from "luxon";
+import { Event, useGetEvents } from "../../../../api/analytics/useGetEvents";
+import { Skeleton } from "../../../../components/ui/skeleton";
+import { getCountryName } from "../../../../lib/utils";
+import { Browser } from "../../components/shared/icons/Browser";
+import { CountryFlag } from "../../components/shared/icons/CountryFlag";
+import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";
+import Link from "next/link";
+
+// DeviceIcon component for displaying mobile/desktop icons
+function DeviceIcon({ deviceType }: { deviceType: string }) {
+ const type = deviceType.toLowerCase();
+
+ if (type.includes("mobile") || type.includes("tablet")) {
+ return <Smartphone className="w-4 h-4" />;
+ }
+
+ return <Laptop className="w-4 h-4" />;
+}
+
+// Function to truncate path for display
+function truncatePath(path: string, maxLength: number = 31) {
+ if (!path) return "-";
+ if (path.length <= maxLength) return path;
+
+ // Keep the beginning of the path with ellipsis
+ return `${path.substring(0, maxLength)}...`;
+}
+
+function EventCard({ event }: { event: Event }) {
+ // Parse event timestamp
+ const eventTime = DateTime.fromSQL(event.timestamp, {
+ zone: "utc",
+ }).toLocal();
+
+ // Determine if it's a pageview or custom event
+ const isPageview = event.type === "pageview";
+
+ const fullPath = `https://${event.hostname}${event.pathname}${
+ event.querystring ? `${event.querystring}` : ""
+ }`;
+
+ return (
+ <div className="mb-3 rounded-lg bg-neutral-850/50 border border-neutral-800 overflow-hidden p-3 flex flex-col filter backdrop-blur-sm">
+ <div className="flex items-center gap-2 text-sm text-neutral-100 mb-2">
+ <div className="flex items-center gap-2">
+ {isPageview ? (
+ <FileText className="w-4 h-4 text-blue-500" />
+ ) : (
+ <MousePointerClick className="w-4 h-4 text-amber-500" />
+ )}
+ </div>
+
+ {event.type === "pageview" ? (
+ <div>
+ <Link href={fullPath} target="_blank" rel="noopener noreferrer">
+ <div
+ className="text-sm truncate hover:underline "
+ title={event.pathname}
+ style={{
+ maxWidth: "calc(min(100vw, 1150px) - 250px)",
+ }}
+ >
+ {truncatePath(
+ `${event.pathname}${
+ event.querystring ? `${event.querystring}` : ""
+ }`
+ )}
+ </div>
+ </Link>
+ </div>
+ ) : (
+ <div>{event.event_name}</div>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="flex space-x-2 items-center ml-6">
+ {event.country && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex items-center">
+ <CountryFlag country={event.country} />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{getCountryName(event.country)}</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Browser browser={event.browser || "Unknown"} />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{event.browser || "Unknown browser"}</p>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <OperatingSystem os={event.operating_system || ""} />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{event.operating_system || "Unknown OS"}</p>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <DeviceIcon deviceType={event.device_type || ""} />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{event.device_type || "Unknown device"}</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+
+ {/* Path with tooltip for long paths */}
+ {/* <div className="flex items-center ml-3 flex-1 min-w-0">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-xs text-gray-400 truncate max-w-[200px] inline-block">
+ {truncatePath(
+ isPageview && event.page_title
+ ? event.page_title
+ : event.pathname
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>
+ {isPageview && event.page_title
+ ? `${event.page_title} (${event.pathname})`
+ : event.pathname || "-"}
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </div> */}
+
+ {/* Time information */}
+ <div className="flex items-center text-xs text-gray-300">
+ <span className="text-gray-400">{eventTime.toRelative()}</span>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function RealtimeEvents() {
+ const { data, isLoading } = useGetEvents(100);
+
+ if (isLoading) {
+ return <EventCardSkeleton />;
+ }
+
+ if (!data?.data || data.data.length === 0) {
+ return (
+ <div className="text-sm text-gray-400 p-4 text-center">
+ No events recorded yet
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className="overflow-y-auto p-2"
+ style={{ height: "calc(100vh - 50px)" }}
+ >
+ {data.data.map((event: Event, index: number) => (
+ <EventCard key={`${event.timestamp}-${index}`} event={event} />
+ ))}
+ </div>
+ );
+}
+
+function EventCardSkeleton() {
+ // Function to get a random width class for skeletons
+ const getRandomWidth = () => {
+ const widths = ["w-16", "w-20", "w-24", "w-28", "w-32"];
+ return widths[Math.floor(Math.random() * widths.length)];
+ };
+
+ // Create multiple skeletons for a realistic loading state
+ const skeletons = Array.from({ length: 5 }).map((_, index) => (
+ <div
+ className="mb-3 rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden"
+ key={index}
+ >
+ <div className="p-3">
+ <div className="flex items-center gap-2">
+ {/* Event badge and User ID */}
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-6 w-20 rounded-md" />
+ <Skeleton className="h-3 w-14" />
+ </div>
+
+ {/* Icons */}
+ <div className="flex space-x-2 items-center ml-3">
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ <Skeleton className="h-4 w-4 rounded-sm" />
+ </div>
+
+ {/* Path with randomized width */}
+ <div className="flex items-center ml-3 flex-1 min-w-0">
+ <Skeleton className={`h-3 max-w-[200px] ${getRandomWidth()}`} />
+ </div>
+
+ {/* Time */}
+ <div className="flex items-center ml-3">
+ <Skeleton className="h-3 w-24" />
+ </div>
+ </div>
+ </div>
+ </div>
+ ));
+
+ return (
+ <div className="max-h-[400px] overflow-y-auto p-2">
+ <div className="mb-2 text-sm font-medium">Recent Events</div>
+ {skeletons}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/realtime/RealtimeGlobe/RealtimeGlobe.tsx b/client/src/app/[site]/realtime/RealtimeGlobe/RealtimeGlobe.tsx
index ea9c947a4..f9dfa3428 100644
--- a/client/src/app/[site]/realtime/RealtimeGlobe/RealtimeGlobe.tsx
+++ b/client/src/app/[site]/realtime/RealtimeGlobe/RealtimeGlobe.tsx
@@ -89,13 +89,12 @@ export const World = ({ width }: { width: number }) => {
ref={globeEl as any}
width={width ?? 0}
height={(size.height ?? 0) - 50}
- globeOffset={[0, -36]}
+ globeOffset={[-100, 0]}
atmosphereColor="rgba(170, 170, 200, 1)"
globeMaterial={oceanBlueMaterial}
hexPolygonsData={countries.features}
hexPolygonResolution={3}
hexPolygonMargin={0.2}
- // hexBinMargin={0.2}
hexBinResolution={3}
hexBinPointsData={liveSessionLocationsData}
hexBinMerge={true}
@@ -104,9 +103,6 @@ export const World = ({ width }: { width: number }) => {
hexPolygonColor={(e: any) => {
return randomShader(e.properties.ISO_A2);
}}
- // hexPolygonColor={(e) => {
- // return `rgba(100, 100, 100, ${Math.random() / 3 + 0.5})`;
- // }}
hexTopColor={(d) => weightColor(d.sumWeight)}
hexSideColor={(d) => weightColor(d.sumWeight)}
// @ts-ignore
diff --git a/client/src/app/[site]/realtime/page.tsx b/client/src/app/[site]/realtime/page.tsx
index b9fb3a589..b0e47c5d8 100644
--- a/client/src/app/[site]/realtime/page.tsx
+++ b/client/src/app/[site]/realtime/page.tsx
@@ -7,8 +7,8 @@ import { Pages } from "../main/components/sections/Pages";
import { Referrers } from "../main/components/sections/Referrers";
import { RealtimeChart } from "./RealtimeChart/RealtimeChart";
import { World } from "./RealtimeGlobe/RealtimeGlobe";
+import { RealtimeEvents } from "./RealtimeEvents/RealtimeEvents";
import { useGetLiveUsercount } from "../../../api/analytics/useLiveUserCount";
-import { Tabs, TabsList, TabsTrigger } from "../../../components/ui/tabs";
import {
Select,
SelectTrigger,
@@ -32,42 +32,53 @@ export default function RealtimePage() {
<div style={{ position: "relative", overflow: "hidden" }} ref={ref}>
<World width={width ?? 0} />
- <div className="absolute top-4 left-4 flex justify-center items-center w-full">
- <div style={{ width: size.height ?? 0 }}>
- <div className="flex flex-col p-4 pt-3 bg-neutral-900 rounded-lg shadow-lg border border-neutral-750 w-fit">
- <div className="text-sm text-gray-400 flex gap-2 text-nowrap items-center">
- Visitors in the last{" "}
- <Select
- value={minutes}
- onValueChange={(value) => setMinutes(value as MinutesType)}
- >
- <SelectTrigger>
- <SelectValue placeholder="Select a time period" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="5">5 minutes</SelectItem>
- <SelectItem value="15">15 minutes</SelectItem>
- <SelectItem value="30">30 minutes</SelectItem>
- <SelectItem value="60">1 hour</SelectItem>
- <SelectItem value="120">2 hours</SelectItem>
- <SelectItem value="240">4 hours</SelectItem>
- <SelectItem value="480">8 hours</SelectItem>
- <SelectItem value="720">12 hours</SelectItem>
- <SelectItem value="1440">24 hours</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div className="text-4xl font-bold">
- {
- <NumberFlow
- respectMotionPreference={false}
- value={data?.count ?? 0}
- />
- }
+ <div className="absolute top-4 left-4 flex items-center w-full">
+ {/* <div style={{ width: (size.height ?? 0) + 100 }}> */}
+ <div className="flex flex-col p-4 pt-3 bg-neutral-900 rounded-lg shadow-lg border border-neutral-750 w-fit">
+ <div className="text-sm text-gray-400 flex gap-2 text-nowrap items-center">
+ <div className="flex justify-center">
+ <span className="relative flex h-4 w-4">
+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"></span>
+ <span className="relative inline-flex h-4 w-4 rounded-full bg-green-500"></span>
+ </span>
</div>
+ Visitors in the last{" "}
+ <Select
+ value={minutes}
+ onValueChange={(value) => setMinutes(value as MinutesType)}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select a time period" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="5">5 minutes</SelectItem>
+ <SelectItem value="15">15 minutes</SelectItem>
+ <SelectItem value="30">30 minutes</SelectItem>
+ <SelectItem value="60">1 hour</SelectItem>
+ <SelectItem value="120">2 hours</SelectItem>
+ <SelectItem value="240">4 hours</SelectItem>
+ <SelectItem value="480">8 hours</SelectItem>
+ <SelectItem value="720">12 hours</SelectItem>
+ <SelectItem value="1440">24 hours</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="text-5xl font-bold flex items-center gap-2">
+ {
+ <NumberFlow
+ respectMotionPreference={false}
+ value={data?.count ?? 0}
+ />
+ }
</div>
+ {/* </div> */}
</div>
</div>
+
+ <div className="absolute top-4 right-4 w-[320px]">
+ <RealtimeEvents />
+ </div>
+
{/* <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Pages isRealtime />
<Events isRealtime />
diff --git a/client/src/components/Sessions/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails.tsx
index ebdd05720..7a27e3c62 100644
--- a/client/src/components/Sessions/SessionDetails.tsx
+++ b/client/src/components/Sessions/SessionDetails.tsx
@@ -255,19 +255,6 @@ export function SessionDetails({ session, userId }: SessionDetailsProps) {
.length;
}, [allPageviews]);
- // Calculate session duration for the details section
- const getDurationFormatted = () => {
- if (!sessionDetails) return "";
- const start = DateTime.fromSQL(sessionDetails.session_start, {
- zone: "utc",
- }).toLocal();
- const end = DateTime.fromSQL(sessionDetails.session_end, {
- zone: "utc",
- }).toLocal();
- const duration = end.diff(start, ["minutes", "seconds"]);
- return `${Math.floor(duration.minutes)}m ${Math.floor(duration.seconds)}s`;
- };
-
return (
<div className="px-4 bg-neutral-900 border-t border-neutral-800">
{isLoading ? (
diff --git a/server/src/api/analytics/getEvents.ts b/server/src/api/analytics/getEvents.ts
new file mode 100644
index 000000000..aafe3f644
--- /dev/null
+++ b/server/src/api/analytics/getEvents.ts
@@ -0,0 +1,85 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import clickhouse from "../../db/clickhouse/clickhouse.js";
+import { processResults } from "./utils.js";
+import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";
+
+export type GetEventsResponse = {
+ timestamp: string;
+ event_name: string;
+ properties: string;
+ user_id: string;
+ pathname: string;
+ querystring: string;
+ hostname: string;
+ referrer: string;
+ browser: string;
+ operating_system: string;
+ country: string;
+ device_type: string;
+ type: string;
+ page_title: string;
+}[];
+
+interface GetEventsRequest {
+ Params: {
+ site: string;
+ };
+ Querystring: {
+ count?: string;
+ };
+}
+
+export async function getEvents(
+ req: FastifyRequest<GetEventsRequest>,
+ res: FastifyReply
+) {
+ const { site } = req.params;
+ const { count = "10" } = req.query;
+
+ const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);
+ if (!userHasAccessToSite) {
+ return res.status(403).send({ error: "Forbidden" });
+ }
+
+ const limitCount = parseInt(count, 10);
+
+ try {
+ const query = await clickhouse.query({
+ query: `
+ SELECT
+ timestamp,
+ event_name,
+ properties,
+ user_id,
+ pathname,
+ querystring,
+ hostname,
+ page_title,
+ referrer,
+ browser,
+ operating_system,
+ country,
+ device_type,
+ type
+ FROM pageviews
+ WHERE
+ site_id = {siteId:Int32}
+ AND (type = 'custom_event' OR type = 'pageview')
+ ORDER BY timestamp DESC
+ LIMIT {limit:Int32}
+ `,
+ format: "JSONEachRow",
+ query_params: {
+ siteId: Number(site),
+ limit: limitCount,
+ },
+ });
+
+ const events = await processResults<GetEventsResponse[number]>(query);
+
+ return res.send({ data: events });
+ } catch (error) {
+ console.error("Error fetching events:", error);
+ return res.status(500).send({ error: "Failed to fetch events" });
+ }
+}
diff --git a/server/src/api/analytics/getLiveSessionLocations.ts b/server/src/api/analytics/getLiveSessionLocations.ts
index fca8a9342..4350ce3d3 100644
--- a/server/src/api/analytics/getLiveSessionLocations.ts
+++ b/server/src/api/analytics/getLiveSessionLocations.ts
@@ -14,6 +14,9 @@ export async function getLiveSessionLocations(
res: FastifyReply
) {
const { site } = req.params;
+ if (isNaN(Number(req.query.time))) {
+ return res.status(400).send({ error: "Invalid time" });
+ }
const result = await clickhouse.query({
query: `
@@ -27,7 +30,7 @@ WITH stuff AS (
pageviews
WHERE
site_id = {site:Int32}
- AND timestamp > now() - interval '{time:Int32} minute'
+ AND timestamp > now() - interval '${req.query.time} minute'
GROUP BY
session_id
)
@@ -44,7 +47,6 @@ GROUP BY
city`,
query_params: {
site,
- time: req.query.time,
},
format: "JSONEachRow",
});
diff --git a/server/src/index.ts b/server/src/index.ts
index bb87fe32b..5d6623d3c 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -8,6 +8,7 @@ import { Headers, HeadersInit } from "undici";
import { fileURLToPath } from "url";
import { createFunnel } from "./api/analytics/createFunnel.js";
import { deleteReport } from "./api/analytics/deleteReport.js";
+import { getEvents } from "./api/analytics/getEvents.js";
import { getFunnel } from "./api/analytics/getFunnel.js";
import { getFunnels } from "./api/analytics/getFunnels.js";
import { getLiveSessionLocations } from "./api/analytics/getLiveSessionLocations.js";
@@ -113,6 +114,7 @@ const ANALYTICS_ROUTES = [
"/site-is-public/",
"/sessions/",
"/session/",
+ "/events/",
"/users/",
"/user/info/",
"/live-session-locations/",
@@ -181,6 +183,7 @@ server.get("/user/:userId/sessions/:site", getUserSessions);
server.get("/user/info/:userId/:site", getUserInfo);
server.get("/live-session-locations/:site", getLiveSessionLocations);
server.get("/funnels/:site", getFunnels);
+server.get("/events/:site", getEvents);
server.post("/funnel/:site", getFunnel);
server.post("/funnel/create/:site", createFunnel);
server.delete("/report/:reportId", deleteReport);