🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Implement real-time session location map with zoom functionality
Bill Yangcf62c8ccc8de
diff --git a/client/src/api/analytics/useGetLiveSessionLocations.ts b/client/src/api/analytics/useGetLiveSessionLocations.tsnew file mode 100644index 000000000..6c8dd8d7b--- /dev/null+++ b/client/src/api/analytics/useGetLiveSessionLocations.ts@@ -0,0 +1,21 @@+import { useQuery } from "@tanstack/react-query";+import { useStore } from "../../lib/store";+import { BACKEND_URL } from "../../lib/const";+import { authedFetch } from "../utils";++export type LiveSessionLocation = {+ lat: number;+ lon: number;+ count: number;+};++export function useGetLiveSessionLocations() {+ const { site } = useStore();+ return useQuery<LiveSessionLocation[]>({+ queryKey: ["live-session-locations", site],+ queryFn: () =>+ authedFetch(`${BACKEND_URL}/live-session-locations/${site}`)+ .then((res) => res.json())+ .then((data) => data.data),+ });+}diff --git a/client/src/app/[site]/realtime/page.tsx b/client/src/app/[site]/realtime/page.tsxindex f84947841..3da984e0b 100644--- a/client/src/app/[site]/realtime/page.tsx+++ b/client/src/app/[site]/realtime/page.tsx@@ -1,12 +1,175 @@"use client";+import { useGetLiveSessionLocations } from "@/api/analytics/useGetLiveSessionLocations";+import { scaleSqrt } from "d3-scale";+import { Feature, GeoJsonObject } from "geojson";+import { Layer } from "leaflet";+import "leaflet/dist/leaflet.css";+import { useMemo, useState } from "react";+import { Circle, GeoJSON, MapContainer, useMapEvent } from "react-leaflet";+import { useCountries } from "../../../lib/geo";++// Component to handle zoom events and update circle sizes+function ZoomHandler({ setZoom }: { setZoom: (zoom: number) => void }) {+ const map = useMapEvent("zoom", () => {+ setZoom(map.getZoom());+ });+ return null;+}++interface TooltipContent {+ count: number;+}++interface TooltipPosition {+ x: number;+ y: number;+}+export default function RealtimePage() {+ const {+ data: liveSessionLocations,+ isLoading: isLiveSessionLocationsLoading,+ } = useGetLiveSessionLocations();+ const { data: countriesGeoData } = useCountries();+ const [currentZoom, setCurrentZoom] = useState(1.5); // Initial zoom level+ const [tooltipContent, setTooltipContent] = useState<TooltipContent | null>(+ null+ );+ const [tooltipPosition, setTooltipPosition] = useState<TooltipPosition>({+ x: 0,+ y: 0,+ });++ // Create a scale for circle radius based on count+ const radiusScale = useMemo(() => {+ if (!liveSessionLocations?.length) return () => 0;++ const maxCount = Math.max(...liveSessionLocations.map((loc) => loc.count));++ // Use sqrt scale to make small values more visible+ // This directly scales radius (not area) which makes small circles more noticeable+ const baseScale = scaleSqrt().domain([1, maxCount]).range([50000, 500000]); // Min/max radius in meters++ return (count: number) => {+ const baseRadius = baseScale(count);+ // Reduce radius gradually as zoom increases+ const zoomFactor = Math.pow(0.75, currentZoom - 1.5);+ return baseRadius * zoomFactor;+ };+ }, [liveSessionLocations, currentZoom]);++ const handleStyle = (feature: Feature | undefined) => {+ const count = feature?.properties?.["count"] || 0;+ return {+ color: "rgba(140, 140, 140, 0.5)",+ weight: 0.5,+ fill: true,+ fillColor: "rgba(140, 140, 140, 0.5)",+ fillOpacity: 0.2,+ };+ };++ const handleEachFeature = (feature: Feature, layer: Layer) => {+ layer.on({+ mouseover: () => {+ // @ts-ignore+ layer.setStyle({+ fillOpacity: 0.5,+ });+ },+ mouseout: () => {+ // @ts-ignore+ layer.setStyle({+ fillOpacity: 0.2,+ });+ },+ });+ };+return (- <div className="p-6">- <h1 className="text-2xl font-bold mb-4">Realtime</h1>- <p className="text-neutral-400">- Realtime analytics content will go here.- </p>+ <div className="py-6">+ <div+ className="w-full h-[600px] rounded-lg overflow-hidden border border-neutral-800"+ onMouseMove={(e) => {+ if (tooltipContent) {+ setTooltipPosition({+ x: e.clientX,+ y: e.clientY,+ });+ }+ }}+ >+ <MapContainer+ center={[30, 0]}+ zoom={1.5}+ minZoom={1}+ style={{ height: "100%", width: "100%", background: "none" }}+ attributionControl={false}+ zoomControl={false}+ >+ <ZoomHandler setZoom={setCurrentZoom} />+ {countriesGeoData && (+ <GeoJSON+ data={countriesGeoData as GeoJsonObject}+ style={handleStyle}+ // onEachFeature={handleEachFeature}+ />+ )}+ {liveSessionLocations?.map((location, index) => (+ <Circle+ key={`${location.lat}-${location.lon}-${index}`}+ center={[location.lat, location.lon]}+ radius={radiusScale(location.count)}+ pathOptions={{+ fillColor: "hsl(var(--accent-500))",+ fillOpacity: 0.4,+ color: "hsl(var(--accent-400))",+ weight: 0,+ }}+ eventHandlers={{+ mouseover: (e) => {+ setTooltipContent({ count: location.count });+ setTooltipPosition({+ x: e.originalEvent.clientX,+ y: e.originalEvent.clientY,+ });+ },+ mouseout: () => {+ setTooltipContent(null);+ },+ mousemove: (e) => {+ setTooltipPosition({+ x: e.originalEvent.clientX,+ y: e.originalEvent.clientY,+ });+ },+ }}+ />+ ))}+ </MapContainer>++ {tooltipContent && (+ <div+ className="fixed bg-neutral-1000 text-white rounded-md p-2 shadow-lg text-sm pointer-events-none"+ style={{+ left: tooltipPosition.x,+ top: tooltipPosition.y - 10,+ transform: "translate(-50%, -100%)",+ zIndex: 500,+ }}+ >+ <div className="font-sm">+ <span className="font-bold text-accent-400">+ {tooltipContent.count.toLocaleString()}+ </span>{" "}+ <span className="text-neutral-300">+ active {tooltipContent.count === 1 ? "session" : "sessions"}+ </span>+ </div>+ </div>+ )}+ </div></div>);}diff --git a/server/src/api/getLiveSessionLocations.ts b/server/src/api/getLiveSessionLocations.tsnew file mode 100644index 000000000..902dd1273--- /dev/null+++ b/server/src/api/getLiveSessionLocations.ts@@ -0,0 +1,52 @@+import { FastifyRequest, FastifyReply } from "fastify";+import clickhouse from "../db/clickhouse/clickhouse.js";+import { processResults } from "./utils.js";++export async function getLiveSessionLocations(+ req: FastifyRequest<{+ Params: {+ siteId: string;+ };+ }>,+ res: FastifyReply+) {+ const { siteId } = req.params;++ const result = await clickhouse.query({+ query: `+WITH stuff AS (+ SELECT+ session_id,+ any(lat) AS lat,+ any(lon) AS lon+ FROM+ pageviews+ WHERE+ site_id = {siteId:Int32}+ AND timestamp > now() - interval '30 minute'+ GROUP BY+ session_id+)+SELECT+ lat,+ lon,+ count() as count+from+ stuff+GROUP BY+ lat,+ lon`,+ query_params: {+ siteId: Number(siteId),+ },+ format: "JSONEachRow",+ });++ const data = await processResults<{+ lat: number;+ lon: number;+ count: number;+ }>(result);++ return res.status(200).send({ data });+}diff --git a/server/src/db/clickhouse/clickhouse.ts b/server/src/db/clickhouse/clickhouse.tsindex cc8cfac47..424ebaedf 100644--- a/server/src/db/clickhouse/clickhouse.ts+++ b/server/src/db/clickhouse/clickhouse.ts@@ -28,6 +28,7 @@ export const initializeClickhouse = async () => {language LowCardinality(String),country LowCardinality(FixedString(2)),iso_3166_2 LowCardinality(String),+ city String,latitude Float64,longitude Float64,screen_width UInt16,diff --git a/server/src/index.ts b/server/src/index.tsindex 1943c58ea..ff2ead02e 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -32,6 +32,7 @@ import { getUserOrganizations } from "./api/user/getUserOrganizations.js";import { initializeCronJobs } from "./cron/index.js";import { getUserSubscription } from "./api/user/getUserSubscription.js";import { getUserInfo } from "./api/getUserInfo.js";+import { getLiveSessionLocations } from "./api/getLiveSessionLocations.js";const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -131,6 +132,7 @@ server.get("/sessions", getSessions);server.get("/session/:sessionId", getSession);server.get("/user/:userId/sessions", getUserSessions);server.get("/user/info/:siteId/:userId", getUserInfo);+server.get("/live-session-locations/:siteId", getLiveSessionLocations);// Administrativeserver.post("/add-site", addSite);diff --git a/server/src/tracker/pageviewQueue.ts b/server/src/tracker/pageviewQueue.tsindex 2a5dc71c0..69434a881 100644--- a/server/src/tracker/pageviewQueue.ts+++ b/server/src/tracker/pageviewQueue.ts@@ -64,6 +64,7 @@ class PageviewQueue {const regionCode = dataForIp?.data?.subdivisions?.[0]?.isoCode || "";const latitude = dataForIp?.data?.latitude || 0;const longitude = dataForIp?.data?.longitude || 0;+ const city = dataForIp?.data?.city || "";return {site_id: pv.site_id,@@ -88,6 +89,7 @@ class PageviewQueue {country: countryCode,iso_3166_2:countryCode && regionCode ? countryCode + "-" + regionCode : "",+ city: city || "",lat: latitude || 0,lon: longitude || 0,type: pv.type || "pageview",