Skip to content

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

clustering (#627)

Bill Yangb7d84bf4fe8f
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index e6388cbcc..1321a4496 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -43,7 +43,8 @@
"WebFetch(domain:rybbit.io)",
"WebFetch(domain:docs.mapbox.com)",
"WebFetch(domain:www.onyx.app)",
- "WebFetch(domain:docs.onyx.app)"
+ "WebFetch(domain:docs.onyx.app)",
+ "Bash(awk:*)"
]
},
"enableAllProjectMcpServers": false
diff --git a/client/src/app/[site]/globe/components/TimelineScrubber.tsx b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
index 7cbcba274..3644363f1 100644
--- a/client/src/app/[site]/globe/components/TimelineScrubber.tsx
+++ b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
@@ -1,29 +1,26 @@
import { debounce } from "lodash";
import { AlertTriangle, Pause, Play } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../../components/ui/select";
import { TimelineSlider } from "../../../../components/ui/timeline-slider";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "../../../../components/ui/tooltip";
-import { useTimelineSessions } from "../hooks/useTimelineSessions";
-import { useTimelineStore } from "../timelineStore";
-import { formatTimelineTime, generateTimeWindows, getActiveSessions, WINDOW_SIZE_OPTIONS } from "../timelineUtils";
+import { useTimelineStore, useActiveSessions } from "../timelineStore";
+import { formatTimelineTime, generateTimeWindows, getSessionCountsPerWindow } from "../timelineUtils";
+import { MAX_PAGES, PAGE_SIZE } from "../hooks/timelineLayer/timelineLayerConstants";
export function TimelineScrubber() {
- const { currentTime, timeRange, windowSize, setCurrentTime, setManualWindowSize } = useTimelineStore();
- const { activeSessions, allSessions, isLoading, hasMoreData } = useTimelineSessions();
+ const { currentTime, timeRange, windowSize, setCurrentTime, allSessions, isLoading, hasMoreData } =
+ useTimelineStore();
+ const activeSessions = useActiveSessions();
const [isPlaying, setIsPlaying] = useState(false);
const [localSliderIndex, setLocalSliderIndex] = useState(0);
-
- // Handle window size change
- const handleWindowSizeChange = (value: string) => {
- const newSize = parseInt(value, 10);
- setManualWindowSize(newSize);
- };
+ const [displayedCounts, setDisplayedCounts] = useState<number[]>([]);
+ const [isCalculating, setIsCalculating] = useState(false);
// Generate time windows for the slider
const timeWindows = useMemo(() => {
if (!timeRange) return [];
- return generateTimeWindows(timeRange.start, timeRange.end, windowSize);
+ const timeWindows = generateTimeWindows(timeRange.start, timeRange.end, windowSize);
+ return timeWindows;
}, [timeRange, windowSize]);
// Get current window index from store
@@ -93,20 +90,52 @@ export function TimelineScrubber() {
return timeWindows[localSliderIndex] || currentTime;
}, [timeWindows, localSliderIndex, currentTime]);
- // Calculate session counts per time window for histogram
- const sessionCounts = useMemo(() => {
- if (timeWindows.length === 0 || allSessions.length === 0) return [];
+ // Debounced function to calculate session counts
+ const debouncedCalculateCounts = useRef(
+ debounce((windows: ReturnType<typeof generateTimeWindows>, sessions: typeof allSessions, size: number) => {
+ if (windows.length === 0 || sessions.length === 0) {
+ setDisplayedCounts([]);
+ setIsCalculating(false);
+ return;
+ }
+ const counts = getSessionCountsPerWindow(sessions, windows, size);
+ setDisplayedCounts(counts);
+ setIsCalculating(false);
+ }, 200)
+ ).current;
+
+ // Cleanup debounce on unmount
+ useEffect(() => {
+ return () => {
+ debouncedCalculateCounts.cancel();
+ };
+ }, [debouncedCalculateCounts]);
+
+ // Reset to start time when window size changes
+ const prevWindowSizeRef = useRef(windowSize);
+ useEffect(() => {
+ if (prevWindowSizeRef.current !== windowSize && timeWindows.length > 0) {
+ setCurrentTime(timeWindows[0]);
+ setLocalSliderIndex(0);
+ }
+ prevWindowSizeRef.current = windowSize;
+ }, [windowSize, timeWindows, setCurrentTime]);
- return timeWindows.map(windowStart => {
- const sessionsInWindow = getActiveSessions(allSessions, windowStart, windowSize);
- return sessionsInWindow.length;
- });
- }, [timeWindows, allSessions, windowSize]);
+ // Trigger calculation when dependencies change
+ useEffect(() => {
+ if (timeWindows.length > 0 && allSessions.length > 0) {
+ setIsCalculating(true);
+ debouncedCalculateCounts(timeWindows, allSessions, windowSize);
+ } else {
+ setDisplayedCounts([]);
+ setIsCalculating(false);
+ }
+ }, [timeWindows, allSessions, windowSize, debouncedCalculateCounts]);
// Get max count for scaling the histogram
const maxCount = useMemo(() => {
- return sessionCounts.length > 0 ? Math.max(...sessionCounts, 1) : 1;
- }, [sessionCounts]);
+ return displayedCounts.length > 0 ? Math.max(...displayedCounts, 1) : 1;
+ }, [displayedCounts]);
if (isLoading) {
return (
@@ -124,8 +153,13 @@ export function TimelineScrubber() {
return (
<div className="w-full flex flex-col">
{/* Session histogram */}
- <div className="w-full h-8 flex items-end gap-[1px]">
- {sessionCounts.map((count, index) => {
+ <div className="w-full h-8 flex items-end gap-[1px] relative">
+ {isCalculating && displayedCounts.length === 0 && (
+ <div className="absolute inset-0 flex items-center justify-center">
+ <div className="w-3 h-3 border-2 border-neutral-600 border-t-accent-500 rounded-full animate-spin" />
+ </div>
+ )}
+ {displayedCounts.map((count, index) => {
const heightPercentage = (count / maxCount) * 100;
const isActive = index === localSliderIndex;
@@ -137,6 +171,7 @@ export function TimelineScrubber() {
height: `${heightPercentage}%`,
backgroundColor: isActive ? "hsl(var(--accent-600))" : "rgba(115, 115, 115, 0.4)",
minHeight: count > 0 ? "2px" : "0px",
+ opacity: isCalculating ? 0.5 : 1,
}}
title={`${count} session${count !== 1 ? "s" : ""}`}
onClick={() => {
@@ -151,7 +186,7 @@ export function TimelineScrubber() {
</div>
<TimelineSlider value={[localSliderIndex]} max={timeWindows.length - 1} onValueChange={handleSliderChange} />
- <div className="flex items-center justify-between">
+ <div className="flex items-center justify-between mt-1">
<div className="flex items-center gap-1 w-full">
<button
onClick={() => setIsPlaying(!isPlaying)}
@@ -165,21 +200,9 @@ export function TimelineScrubber() {
</span>
</div>
<div className="flex items-center gap-3">
- <Select value={windowSize.toString()} onValueChange={handleWindowSizeChange}>
- <SelectTrigger className="w-[100px] h-8 text-xs" size="sm">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {WINDOW_SIZE_OPTIONS.map(option => (
- <SelectItem key={option.value} value={option.value.toString()}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
<div className="text-xs text-neutral-400 flex items-center gap-1 whitespace-nowrap">
<span className="font-bold text-accent-400">
- {activeSessions.length} / {allSessions.length}
+ {activeSessions.length.toLocaleString()} / {allSessions.length.toLocaleString()}
</span>{" "}
sessions
{hasMoreData && (
@@ -189,7 +212,10 @@ export function TimelineScrubber() {
<AlertTriangle className="w-3.5 h-3.5 text-yellow-500 ml-1" />
</TooltipTrigger>
<TooltipContent>
- <p>Showing only the first 50,000 sessions. More data may be available.</p>
+ <p>
+ Showing only the first {(MAX_PAGES * PAGE_SIZE).toLocaleString()} sessions. More data may be
+ available.
+ </p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineClusterUtils.ts b/client/src/app/[site]/globe/hooks/timelineLayer/timelineClusterUtils.ts
new file mode 100644
index 000000000..996d48099
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/timelineClusterUtils.ts
@@ -0,0 +1,119 @@
+import mapboxgl from "mapbox-gl";
+import { isNil, round } from "lodash";
+import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import { SOURCE_ID, MIN_CLUSTER_SIZE } from "./timelineLayerConstants";
+import { spreadOverlappingPoints } from "./timelineLayerManager";
+
+/**
+ * Query and expand features from the map, including expanding small clusters
+ * to their individual constituent points.
+ */
+export async function getUnclusteredFeatures(
+ mapInstance: mapboxgl.Map,
+ shouldShowClusters: boolean,
+ activeSessions: GetSessionsResponse,
+ spreadStartZoom: number
+): Promise<any[]> {
+ const zoom = mapInstance.getZoom();
+ const spreadCoordinates = spreadOverlappingPoints(activeSessions, zoom, spreadStartZoom);
+
+ if (!shouldShowClusters) {
+ // When clustering is disabled, show all sessions as individual markers with spreading
+ return activeSessions
+ .filter(s => !isNil(s.lat) && !isNil(s.lon))
+ .map(session => {
+ const coords = spreadCoordinates.get(session.session_id) || [round(session.lon, 4), round(session.lat, 4)];
+ return {
+ properties: session,
+ geometry: {
+ type: "Point" as const,
+ coordinates: coords,
+ },
+ };
+ });
+ }
+
+ // When clustering is enabled, show unclustered points and expand small clusters
+ const features = mapInstance.querySourceFeatures(SOURCE_ID, {
+ sourceLayer: undefined,
+ });
+
+ const source = mapInstance.getSource(SOURCE_ID) as mapboxgl.GeoJSONSource;
+ const unclusteredFeatures: any[] = [];
+ const promises: Promise<void>[] = [];
+
+ features.forEach(f => {
+ if (!f.properties) return;
+
+ if (!f.properties.cluster) {
+ // Regular unclustered point
+ unclusteredFeatures.push(f);
+ } else if (f.properties.point_count && f.properties.point_count < MIN_CLUSTER_SIZE) {
+ // Small cluster - expand it to get individual points
+ const promise = new Promise<void>(resolve => {
+ source.getClusterLeaves(f.properties!.cluster_id, f.properties!.point_count, 0, (err, leaves) => {
+ if (!err && leaves) {
+ unclusteredFeatures.push(...leaves);
+ }
+ resolve();
+ });
+ });
+ promises.push(promise);
+ }
+ // Clusters with >= MIN_CLUSTER_SIZE points are shown as cluster circles, ignore them here
+ });
+
+ // Wait for all cluster expansions to complete
+ await Promise.all(promises);
+
+ return unclusteredFeatures;
+}
+
+/**
+ * Initialize Mapbox source with clustering configuration
+ */
+export function initializeClusterSource(mapInstance: mapboxgl.Map, clusterMaxZoom: number, clusterRadius: number) {
+ mapInstance.addSource(SOURCE_ID, {
+ type: "geojson",
+ data: {
+ type: "FeatureCollection",
+ features: [],
+ },
+ cluster: true,
+ clusterMaxZoom,
+ clusterRadius,
+ });
+}
+
+/**
+ * Setup cluster expansion zoom behavior on click
+ */
+export function setupClusterClickHandler(mapInstance: mapboxgl.Map, layerId: string): () => void {
+ const handleClusterClick = (e: mapboxgl.MapMouseEvent) => {
+ const features = mapInstance.queryRenderedFeatures(e.point, {
+ layers: [layerId],
+ });
+
+ if (!features.length) return;
+
+ const clusterId = features[0].properties?.cluster_id;
+ const source = mapInstance.getSource(SOURCE_ID) as mapboxgl.GeoJSONSource;
+
+ source.getClusterExpansionZoom(clusterId, (err, zoom) => {
+ if (err || !zoom) return;
+
+ const coordinates = (features[0].geometry as any).coordinates;
+ mapInstance.easeTo({
+ center: coordinates,
+ zoom: zoom,
+ duration: 500,
+ });
+ });
+ };
+
+ mapInstance.on("click", layerId, handleClusterClick);
+
+ return () => {
+ mapInstance.off("click", layerId, handleClusterClick);
+ };
+}
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerConstants.ts b/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerConstants.ts
new file mode 100644
index 000000000..a77cd9f9b
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerConstants.ts
@@ -0,0 +1,24 @@
+// Mapbox layer and source IDs
+export const SOURCE_ID = "timeline-sessions";
+export const CLUSTER_LAYER_ID = "timeline-clusters";
+export const CLUSTER_COUNT_LAYER_ID = "timeline-cluster-count";
+export const UNCLUSTERED_LAYER_ID = "timeline-unclustered-point";
+
+// Clustering configuration
+// Maximum zoom level where clustering is applied. Beyond this zoom, all points are shown individually
+export const CLUSTER_MAX_ZOOM = 11;
+// Radius in pixels within which points are grouped into clusters
+export const CLUSTER_RADIUS = 25;
+// Minimum number of points required to form a visible cluster
+export const MIN_CLUSTER_SIZE = 10;
+// Only enable clustering when total session count exceeds this threshold (performance optimization)
+export const CLUSTERING_THRESHOLD = 500;
+
+export const PAGE_SIZE = 10000;
+export const MAX_PAGES = 10;
+
+// Point spreading configuration (for overlapping coordinates)
+// Zoom level at which points at the same location start spreading apart
+export const SPREAD_START_ZOOM = 8;
+// Maximum offset in degrees to apply when spreading points (roughly 11 meters at equator)
+export const SPREAD_RADIUS_DEGREES = 0.006;
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerManager.ts b/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerManager.ts
new file mode 100644
index 000000000..86aa09861
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerManager.ts
@@ -0,0 +1,152 @@
+import mapboxgl from "mapbox-gl";
+import { isNil, round } from "lodash";
+import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import { CLUSTER_LAYER_ID, CLUSTER_COUNT_LAYER_ID, SOURCE_ID, SPREAD_RADIUS_DEGREES } from "./timelineLayerConstants";
+
+/**
+ * Simple hash function to generate pseudo-random numbers from a string
+ */
+function hashStringToNumber(str: string): number {
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ const char = str.charCodeAt(i);
+ hash = ((hash << 5) - hash) + char;
+ hash = hash & hash; // Convert to 32bit integer
+ }
+ return Math.abs(hash);
+}
+
+/**
+ * Generate a seeded pseudo-random number between 0 and 1
+ */
+function seededRandom(seed: number): number {
+ const x = Math.sin(seed) * 10000;
+ return x - Math.floor(x);
+}
+
+/**
+ * Spreads points that share the same coordinates in a scattered pattern
+ * Returns a map of session IDs to their spread coordinates
+ */
+export function spreadOverlappingPoints(
+ sessions: GetSessionsResponse,
+ zoom: number,
+ spreadStartZoom: number
+): Map<string, [number, number]> {
+ const coordinateMap = new Map<string, [number, number]>();
+
+ // Don't spread if zoom is below threshold
+ if (zoom < spreadStartZoom) {
+ return coordinateMap;
+ }
+
+ // Calculate spread intensity based on zoom level (more spread at higher zoom)
+ const spreadIntensity = Math.min((zoom - spreadStartZoom) / 6, 1); // 0 to 1 over 6 zoom levels
+ const spreadRadius = SPREAD_RADIUS_DEGREES * spreadIntensity;
+
+ // Group sessions by rounded coordinates
+ const locationGroups = new Map<string, GetSessionsResponse>();
+
+ sessions.forEach(session => {
+ if (isNil(session.lat) || isNil(session.lon)) return;
+
+ const roundedLon = round(session.lon, 4);
+ const roundedLat = round(session.lat, 4);
+ const key = `${roundedLat},${roundedLon}`;
+
+ if (!locationGroups.has(key)) {
+ locationGroups.set(key, []);
+ }
+ locationGroups.get(key)!.push(session);
+ });
+
+ // Spread points in each group in a scattered pattern
+ locationGroups.forEach((group, key) => {
+ if (group.length === 1) {
+ // Single point, no spreading needed
+ const session = group[0];
+ coordinateMap.set(session.session_id, [round(session.lon, 4), round(session.lat, 4)]);
+ } else {
+ // Multiple points at same location - scatter them randomly but deterministically
+ const [latStr, lonStr] = key.split(",");
+ const baseLat = parseFloat(latStr);
+ const baseLon = parseFloat(lonStr);
+
+ group.forEach(session => {
+ // Use session_id as seed for deterministic but random-looking positions
+ const seed = hashStringToNumber(session.session_id);
+
+ // Generate two random values for x and y offsets
+ const random1 = seededRandom(seed);
+ const random2 = seededRandom(seed + 1);
+
+ // Convert to angle and radius for more natural scatter
+ const angle = random1 * 2 * Math.PI;
+ const radius = Math.sqrt(random2) * spreadRadius; // sqrt for uniform distribution
+
+ // Adjust longitude offset to account for latitude compression (makes it circular instead of oval)
+ // At higher latitudes, degrees of longitude represent less distance than degrees of latitude
+ const latRad = baseLat * (Math.PI / 180);
+ const lonAdjustment = Math.cos(latRad);
+
+ const offsetLat = Math.sin(angle) * radius;
+ const offsetLon = (Math.cos(angle) * radius) / lonAdjustment;
+
+ coordinateMap.set(session.session_id, [
+ baseLon + offsetLon,
+ baseLat + offsetLat,
+ ]);
+ });
+ }
+ });
+
+ return coordinateMap;
+}
+
+/**
+ * Toggle visibility of cluster layers
+ */
+export function setClusterLayersVisibility(mapInstance: mapboxgl.Map, visible: boolean): void {
+ const visibility = visible ? "visible" : "none";
+
+ if (mapInstance.getLayer(CLUSTER_LAYER_ID)) {
+ mapInstance.setLayoutProperty(CLUSTER_LAYER_ID, "visibility", visibility);
+ }
+ if (mapInstance.getLayer(CLUSTER_COUNT_LAYER_ID)) {
+ mapInstance.setLayoutProperty(CLUSTER_COUNT_LAYER_ID, "visibility", visibility);
+ }
+}
+
+/**
+ * Update the GeoJSON data source with active sessions
+ */
+export function updateGeoJSONData(
+ mapInstance: mapboxgl.Map,
+ activeSessions: GetSessionsResponse,
+ spreadStartZoom: number
+): void {
+ const source = mapInstance.getSource(SOURCE_ID) as mapboxgl.GeoJSONSource;
+ if (!source) return;
+
+ const zoom = mapInstance.getZoom();
+ const spreadCoordinates = spreadOverlappingPoints(activeSessions, zoom, spreadStartZoom);
+
+ const geojson: GeoJSON.FeatureCollection = {
+ type: "FeatureCollection",
+ features: activeSessions
+ .filter(s => !isNil(s.lat) && !isNil(s.lon))
+ .map(session => {
+ const coords = spreadCoordinates.get(session.session_id) || [round(session.lon, 4), round(session.lat, 4)];
+ return {
+ type: "Feature",
+ properties: session,
+ geometry: {
+ type: "Point",
+ coordinates: coords,
+ },
+ };
+ }),
+ };
+
+ source.setData(geojson);
+}
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerSetup.ts b/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerSetup.ts
new file mode 100644
index 000000000..cdb3faa41
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerSetup.ts
@@ -0,0 +1,99 @@
+import mapboxgl from "mapbox-gl";
+import {
+ SOURCE_ID,
+ CLUSTER_LAYER_ID,
+ CLUSTER_COUNT_LAYER_ID,
+ UNCLUSTERED_LAYER_ID,
+ MIN_CLUSTER_SIZE,
+} from "./timelineLayerConstants";
+
+/**
+ * Create and configure the popup for session tooltips
+ */
+export function createTooltipPopup(): mapboxgl.Popup {
+ return new mapboxgl.Popup({
+ closeButton: false,
+ closeOnClick: false,
+ className: "globe-tooltip",
+ anchor: "top-left",
+ offset: [-30, -30],
+ });
+}
+
+/**
+ * Add all cluster layers to the map (circles, labels, unclustered points)
+ */
+export function addClusterLayers(mapInstance: mapboxgl.Map): void {
+ // Add cluster circle layer
+ mapInstance.addLayer({
+ id: CLUSTER_LAYER_ID,
+ type: "circle",
+ source: SOURCE_ID,
+ filter: ["all", ["has", "point_count"], [">=", ["get", "point_count"], MIN_CLUSTER_SIZE]],
+ paint: {
+ "circle-color": ["step", ["get", "point_count"], "#059669", 10, "#059669", 30, "#10b981", 100, "#34d399"],
+ "circle-radius": ["step", ["get", "point_count"], 15, 10, 20, 30, 25],
+ },
+ });
+
+ // Add cluster count layer
+ mapInstance.addLayer({
+ id: CLUSTER_COUNT_LAYER_ID,
+ type: "symbol",
+ source: SOURCE_ID,
+ filter: ["all", ["has", "point_count"], [">=", ["get", "point_count"], MIN_CLUSTER_SIZE]],
+ layout: {
+ "text-field": ["get", "point_count_abbreviated"],
+ "text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
+ "text-size": 14,
+ "text-allow-overlap": true,
+ "text-ignore-placement": true,
+ },
+ paint: {
+ "text-color": "#ffffff",
+ },
+ });
+
+ // Add unclustered point layer (hidden, used for querying)
+ mapInstance.addLayer({
+ id: UNCLUSTERED_LAYER_ID,
+ type: "circle",
+ source: SOURCE_ID,
+ filter: ["!", ["has", "point_count"]],
+ paint: {
+ "circle-radius": 0,
+ "circle-opacity": 0,
+ },
+ });
+}
+
+/**
+ * Disable all transitions on cluster layers for instant appearance/disappearance
+ */
+export function disableClusterTransitions(mapInstance: mapboxgl.Map): void {
+ mapInstance.setPaintProperty(CLUSTER_LAYER_ID, "circle-opacity-transition", { duration: 0 });
+ mapInstance.setPaintProperty(CLUSTER_LAYER_ID, "circle-radius-transition", { duration: 0 });
+ mapInstance.setPaintProperty(CLUSTER_LAYER_ID, "circle-color-transition", { duration: 0 });
+ mapInstance.setPaintProperty(CLUSTER_COUNT_LAYER_ID, "text-opacity-transition", { duration: 0 });
+}
+
+/**
+ * Setup cursor change on cluster hover
+ */
+export function setupClusterHoverHandlers(mapInstance: mapboxgl.Map, layerId: string): () => void {
+ const handleClusterMouseEnter = () => {
+ mapInstance.getCanvas().style.cursor = "pointer";
+ };
+
+ const handleClusterMouseLeave = () => {
+ mapInstance.getCanvas().style.cursor = "";
+ };
+
+ mapInstance.on("mouseenter", layerId, handleClusterMouseEnter);
+ mapInstance.on("mouseleave", layerId, handleClusterMouseLeave);
+
+ return () => {
+ mapInstance.off("mouseenter", layerId, handleClusterMouseEnter);
+ mapInstance.off("mouseleave", layerId, handleClusterMouseLeave);
+ };
+}
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerHelpers.ts b/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerHelpers.ts
new file mode 100644
index 000000000..8ae160df8
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerHelpers.ts
@@ -0,0 +1,129 @@
+import BoringAvatar from "boring-avatars";
+import { createElement } from "react";
+// @ts-ignore - React 19 has built-in types
+import { renderToStaticMarkup } from "react-dom/server";
+import * as CountryFlags from "country-flag-icons/react/3x2";
+import {
+ Monitor,
+ Smartphone,
+ Link,
+ Search,
+ ExternalLink,
+ Users,
+ Mail,
+ HelpCircle,
+ DollarSign,
+ Video,
+ Handshake,
+ FileText,
+ ShoppingCart,
+ Calendar,
+ Headphones,
+} from "lucide-react";
+import { AVATAR_COLORS } from "../../../../../components/Avatar";
+
+// Generate avatar SVG using boring-avatars
+export function generateAvatarSVG(userId: string, size: number): string {
+ const avatarElement = createElement(BoringAvatar, {
+ size,
+ name: userId,
+ variant: "beam",
+ colors: AVATAR_COLORS,
+ });
+ return renderToStaticMarkup(avatarElement);
+}
+
+// Render country flag to static SVG
+export function renderCountryFlag(countryCode: string): string {
+ if (!countryCode || countryCode.length !== 2) return "";
+ const FlagComponent = CountryFlags[countryCode.toUpperCase() as keyof typeof CountryFlags];
+ if (!FlagComponent) return "";
+ const flagElement = createElement(FlagComponent, { className: "w-4 h-3 inline-block" });
+ return renderToStaticMarkup(flagElement);
+}
+
+// Render device icon based on device type
+export function renderDeviceIcon(deviceType: string): string {
+ const type = deviceType?.toLowerCase() || "";
+ const Icon = type.includes("mobile") || type.includes("tablet") ? Smartphone : Monitor;
+ const iconElement = createElement(Icon, { size: 14, className: "inline-block" });
+ return renderToStaticMarkup(iconElement);
+}
+
+// Get channel icon component
+function getChannelIconComponent(channel: string) {
+ switch (channel) {
+ case "Direct":
+ return Link;
+ case "Organic Search":
+ return Search;
+ case "Referral":
+ return ExternalLink;
+ case "Organic Social":
+ return Users;
+ case "Email":
+ return Mail;
+ case "Unknown":
+ return HelpCircle;
+ case "Paid Search":
+ return Search;
+ case "Paid Unknown":
+ return DollarSign;
+ case "Paid Social":
+ return Users;
+ case "Display":
+ return Monitor;
+ case "Organic Video":
+ return Video;
+ case "Affiliate":
+ return Handshake;
+ case "Content":
+ return FileText;
+ case "Organic Shopping":
+ return ShoppingCart;
+ case "Event":
+ return Calendar;
+ case "Audio":
+ return Headphones;
+ default:
+ return null;
+ }
+}
+
+// Render channel icon
+export function renderChannelIcon(channel: string): string {
+ const IconComponent = getChannelIconComponent(channel);
+ if (!IconComponent) return "";
+ const iconElement = createElement(IconComponent, { size: 14, className: "inline-block" });
+ return renderToStaticMarkup(iconElement);
+}
+
+// Get browser icon path
+export function getBrowserIconPath(browser: string): string {
+ const BROWSER_TO_LOGO: Record<string, string> = {
+ Chrome: "Chrome.svg",
+ "Mobile Chrome": "Chrome.svg",
+ Firefox: "Firefox.svg",
+ "Mobile Firefox": "Firefox.svg",
+ Safari: "Safari.svg",
+ "Mobile Safari": "Safari.svg",
+ Edge: "Edge.svg",
+ Opera: "Opera.svg",
+ Brave: "Brave.svg",
+ };
+ return BROWSER_TO_LOGO[browser] ? `/browsers/${BROWSER_TO_LOGO[browser]}` : "";
+}
+
+// Get OS icon path
+export function getOSIconPath(os: string): string {
+ const OS_TO_LOGO: Record<string, string> = {
+ Windows: "Windows.svg",
+ Android: "Android.svg",
+ android: "Android.svg",
+ Linux: "Tux.svg",
+ macOS: "macOS.svg",
+ iOS: "Apple.svg",
+ "Chrome OS": "Chrome.svg",
+ };
+ return OS_TO_LOGO[os] ? `/operating-systems/${OS_TO_LOGO[os]}` : "";
+}
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerManager.ts b/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerManager.ts
new file mode 100644
index 000000000..070989fb2
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerManager.ts
@@ -0,0 +1,166 @@
+import mapboxgl from "mapbox-gl";
+import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import { generateAvatarSVG } from "./timelineMarkerHelpers";
+import { buildTooltipHTML } from "./timelineTooltipBuilder";
+import { getUnclusteredFeatures } from "./timelineClusterUtils";
+
+export type MarkerData = {
+ marker: mapboxgl.Marker;
+ element: HTMLDivElement;
+ cleanup: () => void;
+};
+
+/**
+ * Create an avatar marker for a session
+ */
+export function createAvatarMarker(
+ session: GetSessionsResponse[number],
+ lng: number,
+ lat: number,
+ mapInstance: mapboxgl.Map,
+ popupRef: React.RefObject<mapboxgl.Popup | null>,
+ openTooltipSessionIdRef: React.MutableRefObject<string | null>,
+ map: React.RefObject<mapboxgl.Map | null>,
+ setSelectedSession: (session: GetSessionsResponse[number]) => void
+): { marker: mapboxgl.Marker; element: HTMLDivElement; cleanup: () => void } {
+ const avatarContainer = document.createElement("div");
+ avatarContainer.className = "timeline-avatar-marker";
+ avatarContainer.style.cursor = "pointer";
+ avatarContainer.style.borderRadius = "50%";
+ avatarContainer.style.overflow = "hidden";
+ avatarContainer.style.width = "32px";
+ avatarContainer.style.height = "32px";
+ avatarContainer.style.boxShadow = "0 2px 8px rgba(0,0,0,0.3)";
+
+ const avatarSVG = generateAvatarSVG(session.user_id, 32);
+ avatarContainer.innerHTML = avatarSVG;
+
+ const marker = new mapboxgl.Marker({
+ element: avatarContainer,
+ anchor: "center",
+ })
+ .setLngLat([lng, lat])
+ .addTo(mapInstance);
+
+ // Add click event for tooltip
+ const toggleTooltip = (e: MouseEvent) => {
+ e.stopPropagation();
+ if (!map.current || !popupRef.current) return;
+
+ // If clicking the same marker that has the tooltip open, close it
+ if (popupRef.current.isOpen() && openTooltipSessionIdRef.current === session.session_id) {
+ popupRef.current.remove();
+ openTooltipSessionIdRef.current = null;
+ return;
+ }
+
+ // If clicking a different marker (or no tooltip is open), show this one
+ if (popupRef.current.isOpen()) {
+ popupRef.current.remove();
+ }
+
+ const html = buildTooltipHTML(session, lng, lat);
+
+ popupRef.current.setLngLat([lng, lat]).setHTML(html).addTo(map.current);
+ openTooltipSessionIdRef.current = session.session_id;
+
+ // Add click handler to the button
+ const button = document.querySelector(`[data-session-id="${session.session_id}"]`);
+ if (button) {
+ button.addEventListener("click", e => {
+ e.stopPropagation();
+ setSelectedSession(session);
+ popupRef.current?.remove();
+ openTooltipSessionIdRef.current = null;
+ });
+ }
+ };
+
+ avatarContainer.addEventListener("click", toggleTooltip);
+
+ const cleanup = () => {
+ avatarContainer.removeEventListener("click", toggleTooltip);
+ };
+
+ return { marker, element: avatarContainer, cleanup };
+}
+
+/**
+ * Update all markers on the map based on current unclustered features
+ */
+export async function updateMarkers(
+ mapInstance: mapboxgl.Map,
+ markersMap: Map<string, MarkerData>,
+ shouldShowClusters: boolean,
+ activeSessions: GetSessionsResponse,
+ popupRef: React.RefObject<mapboxgl.Popup | null>,
+ openTooltipSessionIdRef: React.MutableRefObject<string | null>,
+ map: React.RefObject<mapboxgl.Map | null>,
+ setSelectedSession: (session: GetSessionsResponse[number]) => void,
+ spreadStartZoom: number
+): Promise<void> {
+ // Get unclustered features (including expanded small clusters)
+ const unclusteredFeatures = await getUnclusteredFeatures(
+ mapInstance,
+ shouldShowClusters,
+ activeSessions,
+ spreadStartZoom
+ );
+
+ // Build set of current session IDs
+ const currentSessionIds = new Set(
+ unclusteredFeatures.map(f => f.properties?.session_id).filter(Boolean)
+ );
+
+ // Remove markers that are no longer unclustered
+ const toRemove: string[] = [];
+ markersMap.forEach(({ marker, cleanup }, sessionId) => {
+ if (!currentSessionIds.has(sessionId)) {
+ cleanup();
+ marker.remove();
+ toRemove.push(sessionId);
+ }
+ });
+ toRemove.forEach(id => markersMap.delete(id));
+
+ // Create or update markers for unclustered sessions
+ unclusteredFeatures.forEach(feature => {
+ const session = feature.properties as GetSessionsResponse[number];
+ if (!session?.session_id) return;
+
+ const existing = markersMap.get(session.session_id);
+ const [lng, lat] = (feature.geometry as any).coordinates;
+
+ if (existing) {
+ // Update position if needed
+ const currentLngLat = existing.marker.getLngLat();
+ if (currentLngLat.lng !== lng || currentLngLat.lat !== lat) {
+ existing.marker.setLngLat([lng, lat]);
+ }
+ } else {
+ // Create new marker
+ const markerData = createAvatarMarker(
+ session,
+ lng,
+ lat,
+ mapInstance,
+ popupRef,
+ openTooltipSessionIdRef,
+ map,
+ setSelectedSession
+ );
+ markersMap.set(session.session_id, markerData);
+ }
+ });
+}
+
+/**
+ * Remove all markers from the map and clear the markers map
+ */
+export function clearAllMarkers(markersMap: Map<string, MarkerData>): void {
+ markersMap.forEach(({ marker, cleanup }) => {
+ cleanup();
+ marker.remove();
+ });
+ markersMap.clear();
+}
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineTooltipBuilder.ts b/client/src/app/[site]/globe/hooks/timelineLayer/timelineTooltipBuilder.ts
new file mode 100644
index 000000000..862ba84b9
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/timelineTooltipBuilder.ts
@@ -0,0 +1,112 @@
+import { DateTime } from "luxon";
+import { createElement } from "react";
+// @ts-ignore - React 19 has built-in types
+import { renderToStaticMarkup } from "react-dom/server";
+import { Eye, MousePointerClick } from "lucide-react";
+import { generateName } from "../../../../../components/Avatar";
+import { formatShortDuration, hour12, userLocale } from "../../../../../lib/dateTimeUtils";
+import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import { extractDomain, getDisplayName } from "../../../../../components/Channel";
+import {
+ generateAvatarSVG,
+ renderCountryFlag,
+ renderDeviceIcon,
+ renderChannelIcon,
+ getBrowserIconPath,
+ getOSIconPath,
+} from "./timelineMarkerHelpers";
+
+/**
+ * Build the HTML content for a session tooltip
+ */
+export function buildTooltipHTML(
+ session: GetSessionsResponse[number],
+ lng: number,
+ lat: number
+): string {
+ const avatarSVG = generateAvatarSVG(session.user_id, 36);
+ const countryCode = session.country?.length === 2 ? session.country : "";
+ const flagSVG = renderCountryFlag(countryCode);
+ const deviceIconSVG = renderDeviceIcon(session.device_type || "");
+ const browserIconPath = getBrowserIconPath(session.browser || "");
+ const osIconPath = getOSIconPath(session.operating_system || "");
+
+ // Duration formatting
+ const durationDisplay = formatShortDuration(session.session_duration || 0);
+
+ // Start time formatting
+ const startTime = DateTime.fromSQL(session.session_start, { zone: "utc" })
+ .setLocale(userLocale)
+ .toLocal()
+ .toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm");
+
+ // Pageview and event icons
+ const pageviewIconSVG = renderToStaticMarkup(
+ createElement(Eye, { size: 14, className: "inline-block text-blue-400" })
+ );
+ const eventIconSVG = renderToStaticMarkup(
+ createElement(MousePointerClick, { size: 14, className: "inline-block text-amber-400" })
+ );
+
+ // Referrer/Channel display
+ const domain = extractDomain(session.referrer);
+ let referrerIconSVG = "";
+ let referrerText = "";
+
+ if (domain) {
+ referrerText = getDisplayName(domain);
+ referrerIconSVG = renderChannelIcon(session.channel);
+ } else {
+ referrerText = session.channel;
+ referrerIconSVG = renderChannelIcon(session.channel);
+ }
+
+ const name = generateName(session.user_id);
+
+ return `
+ <div class="flex flex-col gap-3 p-3 bg-neutral-850 border border-neutral-750 rounded-lg">
+ <div class="flex items-start gap-2.5">
+ <div class="flex-shrink-0 w-9 h-9 rounded-full overflow-hidden">
+ ${avatarSVG}
+ </div>
+ <div class="flex-1 min-w-0">
+ <h3 class="text-sm font-semibold text-white truncate">${name}</h3>
+ <div class="flex items-center gap-1 text-xs text-neutral-300 mt-0.5">
+ ${flagSVG}
+ <span>${session.city || "Unknown"}, ${session.country || "Unknown"}</span>
+ </div>
+ </div>
+ </div>
+ <div class="flex flex-wrap items-center gap-1.5">
+ ${browserIconPath ? `<img src="${browserIconPath}" alt="${session.browser}" title="${session.browser}" class="w-4 h-4" />` : ""}
+ ${osIconPath ? `<img src="${osIconPath}" alt="${session.operating_system}" title="${session.operating_system}" class="w-4 h-4" />` : ""}
+ <span class="flex items-center" title="${session.device_type}">${deviceIconSVG}</span>
+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-neutral-800 text-neutral-300 text-xs">
+ ${pageviewIconSVG}
+ <span>${session.pageviews || 0}</span>
+ </span>
+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-neutral-800 text-neutral-300 text-xs">
+ ${eventIconSVG}
+ <span>${session.events || 0}</span>
+ </span>
+ </div>
+ <div class="flex items-center gap-1.5">
+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-neutral-800 text-neutral-300 text-xs">
+ ${referrerIconSVG}
+ <span>${referrerText}</span>
+ </span>
+ </div>
+ <div class="flex items-center justify-between gap-2 text-xs text-neutral-400 pt-1.5 border-t border-neutral-700">
+ <span>${startTime}</span>
+ <span class="text-neutral-200">${durationDisplay}</span>
+ </div>
+ <button
+ class="view-session-btn w-full px-2 py-1 bg-accent-600 hover:bg-accent-700 text-white text-xs font-medium rounded transition-colors"
+ data-session-id="${session.session_id}"
+ tabindex="-1"
+ >
+ View Details
+ </button>
+ </div>
+ `;
+}
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineLayer.ts b/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineLayer.ts
new file mode 100644
index 000000000..d4282aa3a
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineLayer.ts
@@ -0,0 +1,158 @@
+import mapboxgl from "mapbox-gl";
+import { useEffect, useRef, useState, useCallback } from "react";
+import { throttle } from "lodash";
+import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import { useTimelineStore, useActiveSessions } from "../../timelineStore";
+import { initializeClusterSource, setupClusterClickHandler } from "./timelineClusterUtils";
+import {
+ SOURCE_ID,
+ CLUSTER_LAYER_ID,
+ CLUSTER_MAX_ZOOM,
+ CLUSTER_RADIUS,
+ CLUSTERING_THRESHOLD,
+ SPREAD_START_ZOOM,
+} from "./timelineLayerConstants";
+import { setClusterLayersVisibility, updateGeoJSONData } from "./timelineLayerManager";
+import { updateMarkers as updateMarkersUtil, clearAllMarkers, type MarkerData } from "./timelineMarkerManager";
+import {
+ createTooltipPopup,
+ addClusterLayers,
+ disableClusterTransitions,
+ setupClusterHoverHandlers,
+} from "./timelineLayerSetup";
+
+export function useTimelineLayer({
+ map,
+ mapLoaded,
+ mapView,
+}: {
+ map: React.RefObject<mapboxgl.Map | null>;
+ mapLoaded: boolean;
+ mapView: string;
+}) {
+ const activeSessions = useActiveSessions();
+ const { currentTime } = useTimelineStore();
+ const popupRef = useRef<mapboxgl.Popup | null>(null);
+ const markersMapRef = useRef<Map<string, MarkerData>>(new Map());
+ const openTooltipSessionIdRef = useRef<string | null>(null);
+ const [selectedSession, setSelectedSession] = useState<GetSessionsResponse[number] | null>(null);
+
+ // Close tooltip when timeline time changes
+ useEffect(() => {
+ if (popupRef.current && popupRef.current.isOpen()) {
+ popupRef.current.remove();
+ openTooltipSessionIdRef.current = null;
+ }
+ }, [currentTime]);
+
+ // Initialize Mapbox source and layers for clustering
+ useEffect(() => {
+ if (!map.current || !mapLoaded) return;
+
+ const mapInstance = map.current;
+
+ // Initialize popup once
+ if (!popupRef.current) {
+ popupRef.current = createTooltipPopup();
+ }
+
+ // Add source and layers if they don't exist
+ if (!mapInstance.getSource(SOURCE_ID)) {
+ initializeClusterSource(mapInstance, CLUSTER_MAX_ZOOM, CLUSTER_RADIUS);
+ addClusterLayers(mapInstance);
+ disableClusterTransitions(mapInstance);
+ }
+
+ // Setup interaction handlers
+ const cleanupClusterClick = setupClusterClickHandler(mapInstance, CLUSTER_LAYER_ID);
+ const cleanupClusterHover = setupClusterHoverHandlers(mapInstance, CLUSTER_LAYER_ID);
+
+ return () => {
+ cleanupClusterClick();
+ cleanupClusterHover();
+ };
+ }, [map, mapLoaded]);
+
+ // Update GeoJSON data and HTML markers
+ useEffect(() => {
+ if (!map.current || !mapLoaded) return;
+
+ const mapInstance = map.current;
+ const markersMap = markersMapRef.current;
+
+ // Hide layers and markers if not in timeline view
+ if (mapView !== "timeline") {
+ setClusterLayersVisibility(mapInstance, false);
+ clearAllMarkers(markersMap);
+ return;
+ }
+
+ // Show/hide cluster layers based on number of sessions
+ const shouldShowClusters = activeSessions.length > CLUSTERING_THRESHOLD;
+ setClusterLayersVisibility(mapInstance, shouldShowClusters);
+
+ // Update GeoJSON data source
+ updateGeoJSONData(mapInstance, activeSessions, SPREAD_START_ZOOM);
+
+ // Update GeoJSON when zoom changes (for point spreading)
+ const handleZoomChange = () => {
+ updateGeoJSONData(mapInstance, activeSessions, SPREAD_START_ZOOM);
+ };
+
+ // Function to update HTML markers for unclustered points
+ const updateMarkers = async () => {
+ await updateMarkersUtil(
+ mapInstance,
+ markersMap,
+ shouldShowClusters,
+ activeSessions,
+ popupRef,
+ openTooltipSessionIdRef,
+ map,
+ setSelectedSession,
+ SPREAD_START_ZOOM
+ );
+ };
+
+ // Throttle the marker updates to run at most once every 150ms
+ const throttledUpdateMarkers = throttle(updateMarkers, 150, {
+ leading: true,
+ trailing: true,
+ });
+
+ // Initial update
+ updateMarkers();
+
+ // Update GeoJSON and markers on zoom (for point spreading)
+ mapInstance.on("zoom", handleZoomChange);
+ mapInstance.on("zoom", throttledUpdateMarkers);
+ mapInstance.on("move", throttledUpdateMarkers);
+ mapInstance.on("sourcedata", throttledUpdateMarkers);
+
+ // Handle map click to close tooltip
+ const handleMapClick = () => {
+ if (popupRef.current && popupRef.current.isOpen()) {
+ popupRef.current.remove();
+ openTooltipSessionIdRef.current = null;
+ }
+ };
+
+ mapInstance.on("click", handleMapClick);
+
+ // Cleanup function
+ return () => {
+ clearAllMarkers(markersMap);
+ throttledUpdateMarkers.cancel(); // Cancel any pending throttled calls
+ mapInstance.off("zoom", handleZoomChange);
+ mapInstance.off("zoom", throttledUpdateMarkers);
+ mapInstance.off("move", throttledUpdateMarkers);
+ mapInstance.off("sourcedata", throttledUpdateMarkers);
+ mapInstance.off("click", handleMapClick);
+ };
+ }, [activeSessions, mapLoaded, map, mapView]);
+
+ return {
+ selectedSession,
+ setSelectedSession,
+ };
+}
diff --git a/client/src/app/[site]/globe/hooks/useTimelineSessions.ts b/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineSessions.ts
similarity index 69%
rename from client/src/app/[site]/globe/hooks/useTimelineSessions.ts
rename to client/src/app/[site]/globe/hooks/timelineLayer/useTimelineSessions.ts
index 8f23ca026..89ace19c7 100644
--- a/client/src/app/[site]/globe/hooks/useTimelineSessions.ts
+++ b/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineSessions.ts
@@ -1,16 +1,17 @@
import { useQuery } from "@tanstack/react-query";
import { DateTime } from "luxon";
import { useEffect, useMemo } from "react";
-import { GetSessionsResponse } from "../../../../api/analytics/userSessions";
-import { APIResponse } from "../../../../api/types";
-import { authedFetch, getQueryParams } from "../../../../api/utils";
-import { getFilteredFilters, SESSION_PAGE_FILTERS, useStore } from "../../../../lib/store";
-import { useTimelineStore } from "../timelineStore";
-import { calculateWindowSize, getActiveSessions } from "../timelineUtils";
+import { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import { APIResponse } from "../../../../../api/types";
+import { authedFetch, getQueryParams } from "../../../../../api/utils";
+import { getFilteredFilters, SESSION_PAGE_FILTERS, useStore } from "../../../../../lib/store";
+import { useTimelineStore } from "../../timelineStore";
+import { calculateWindowSize } from "../../timelineUtils";
+import { MAX_PAGES, PAGE_SIZE } from "./timelineLayerConstants";
export function useTimelineSessions() {
const { time, site } = useStore();
- const { currentTime, windowSize, manualWindowSize, setTimeRange, setWindowSize } = useTimelineStore();
+ const { manualWindowSize, setTimeRange, setWindowSize, setAllSessions, setLoading, setError } = useTimelineStore();
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
@@ -19,16 +20,14 @@ export function useTimelineSessions() {
queryKey: ["timeline-sessions", time, site, filteredFilters],
queryFn: async () => {
const allSessions = [];
- const maxPages = 5;
- const limit = 10000;
let reachedMaxPages = false;
- for (let page = 1; page <= maxPages; page++) {
+ for (let page = 1; page <= MAX_PAGES; page++) {
const requestParams = {
...getQueryParams(time),
filters: filteredFilters,
page,
- limit,
+ limit: PAGE_SIZE,
};
const response = await authedFetch<APIResponse<GetSessionsResponse>>(`/sessions/${site}`, requestParams);
@@ -37,12 +36,12 @@ export function useTimelineSessions() {
allSessions.push(...response.data);
// If we got fewer results than the limit, we've reached the end
- if (response.data.length < limit) {
+ if (response.data.length < PAGE_SIZE) {
break;
}
// If we're on the last page and got a full page, there might be more
- if (page === maxPages && response.data.length === limit) {
+ if (page === MAX_PAGES && response.data.length === PAGE_SIZE) {
reachedMaxPages = true;
}
} else {
@@ -64,6 +63,22 @@ export function useTimelineSessions() {
return data.data;
}, [data]);
+ // Update store with loading/error state
+ useEffect(() => {
+ setLoading(isLoading);
+ }, [isLoading, setLoading]);
+
+ useEffect(() => {
+ setError(isError);
+ }, [isError, setError]);
+
+ // Update store with allSessions
+ useEffect(() => {
+ if (allSessions.length > 0) {
+ setAllSessions(allSessions, data?.hasMoreData || false);
+ }
+ }, [allSessions, data?.hasMoreData, setAllSessions]);
+
// Calculate time range from fetched sessions and initialize timeline
useEffect(() => {
if (allSessions.length === 0) return;
@@ -93,18 +108,4 @@ export function useTimelineSessions() {
setTimeRange(earliest, latest);
}
}, [allSessions, setTimeRange, setWindowSize, manualWindowSize, time]);
-
- // Filter sessions based on current time window
- const activeSessions = useMemo(() => {
- if (!currentTime || !allSessions.length) return [];
- return getActiveSessions(allSessions, currentTime, windowSize);
- }, [allSessions, currentTime, windowSize]);
-
- return {
- allSessions,
- activeSessions,
- isLoading,
- isError,
- hasMoreData: data?.hasMoreData || false,
- };
}
diff --git a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts b/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
index 0ec0ed239..9add6acdb 100644
--- a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
+++ b/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
@@ -192,7 +192,7 @@ export function useCoordinatesLayer({
const coordinates = e.lngLat;
const html = `
- <div class="bg-neutral-850 border border-neutral-750 rounded-lg p-2">
+ <div class="bg-neutral-850 border border-neutral-750 rounded-lg p-2" style="pointer-events: none;">
<div class="flex items-center gap-2 mb-1">
${flagSVG}
<span class="text-sm font-medium text-white">${city}</span>
diff --git a/client/src/app/[site]/globe/hooks/useMapbox.ts b/client/src/app/[site]/globe/hooks/useMapbox.ts
index bcb833475..a9fd1e650 100644
--- a/client/src/app/[site]/globe/hooks/useMapbox.ts
+++ b/client/src/app/[site]/globe/hooks/useMapbox.ts
@@ -1,16 +1,19 @@
import { useEffect, useRef, useState } from "react";
import mapboxgl from "mapbox-gl";
+import { useConfigs } from "../../../../lib/configs";
export function useMapbox(containerRef: React.RefObject<HTMLDivElement | null>) {
const map = useRef<mapboxgl.Map | null>(null);
const [mapLoaded, setMapLoaded] = useState(false);
+ const { configs } = useConfigs();
+
useEffect(() => {
- if (!containerRef.current || !process.env.NEXT_PUBLIC_MAPBOX_TOKEN) {
+ if (!containerRef.current || !configs?.mapboxToken) {
return;
}
- mapboxgl.accessToken = process.env.NEXT_PUBLIC_MAPBOX_TOKEN || "";
+ mapboxgl.accessToken = configs.mapboxToken;
map.current = new mapboxgl.Map({
container: containerRef.current,
@@ -49,7 +52,7 @@ export function useMapbox(containerRef: React.RefObject<HTMLDivElement | null>)
map.current?.remove();
map.current = null;
};
- }, [containerRef]);
+ }, [containerRef, configs?.mapboxToken]);
return { map, mapLoaded };
}
diff --git a/client/src/app/[site]/globe/hooks/useTimelineLayer.ts b/client/src/app/[site]/globe/hooks/useTimelineLayer.ts
deleted file mode 100644
index 7bfe3ee8b..000000000
--- a/client/src/app/[site]/globe/hooks/useTimelineLayer.ts
+++ /dev/null
@@ -1,411 +0,0 @@
-import BoringAvatar from "boring-avatars";
-import { round } from "lodash";
-import { DateTime } from "luxon";
-import mapboxgl from "mapbox-gl";
-import { createElement, useEffect, useRef, useState } from "react";
-// @ts-ignore - React 19 has built-in types
-import { renderToStaticMarkup } from "react-dom/server";
-import * as CountryFlags from "country-flag-icons/react/3x2";
-import {
- Monitor,
- Smartphone,
- Link,
- Eye,
- MousePointerClick,
- Search,
- ExternalLink,
- Users,
- Mail,
- HelpCircle,
- DollarSign,
- Video,
- Handshake,
- FileText,
- ShoppingCart,
- Calendar,
- Headphones,
-} from "lucide-react";
-import { useTimelineSessions } from "./useTimelineSessions";
-import { generateName } from "../../../../components/Avatar";
-import { formatShortDuration, hour12, userLocale } from "../../../../lib/dateTimeUtils";
-import type { GetSessionsResponse } from "../../../../api/analytics/userSessions";
-import { useTimelineStore } from "../timelineStore";
-import { extractDomain, getDisplayName } from "../../../../components/Channel";
-
-// Generate avatar SVG using boring-avatars
-function generateAvatarSVG(userId: string, size: number): string {
- const avatarElement = createElement(BoringAvatar, {
- size,
- name: userId,
- variant: "beam",
- colors: ["#92A1C6", "#146A7C", "#F0AB3D", "#C271B4", "#C20D90"],
- });
- return renderToStaticMarkup(avatarElement);
-}
-
-// Render country flag to static SVG
-function renderCountryFlag(countryCode: string): string {
- if (!countryCode || countryCode.length !== 2) return "";
- const FlagComponent = CountryFlags[countryCode.toUpperCase() as keyof typeof CountryFlags];
- if (!FlagComponent) return "";
- const flagElement = createElement(FlagComponent, { className: "w-4 h-3 inline-block" });
- return renderToStaticMarkup(flagElement);
-}
-
-// Render device icon based on device type
-function renderDeviceIcon(deviceType: string): string {
- const type = deviceType?.toLowerCase() || "";
- const Icon = type.includes("mobile") || type.includes("tablet") ? Smartphone : Monitor;
- const iconElement = createElement(Icon, { size: 14, className: "inline-block" });
- return renderToStaticMarkup(iconElement);
-}
-
-// Get channel icon component
-function getChannelIconComponent(channel: string) {
- switch (channel) {
- case "Direct":
- return Link;
- case "Organic Search":
- return Search;
- case "Referral":
- return ExternalLink;
- case "Organic Social":
- return Users;
- case "Email":
- return Mail;
- case "Unknown":
- return HelpCircle;
- case "Paid Search":
- return Search;
- case "Paid Unknown":
- return DollarSign;
- case "Paid Social":
- return Users;
- case "Display":
- return Monitor;
- case "Organic Video":
- return Video;
- case "Affiliate":
- return Handshake;
- case "Content":
- return FileText;
- case "Organic Shopping":
- return ShoppingCart;
- case "Event":
- return Calendar;
- case "Audio":
- return Headphones;
- default:
- return null;
- }
-}
-
-// Render channel icon
-function renderChannelIcon(channel: string): string {
- const IconComponent = getChannelIconComponent(channel);
- if (!IconComponent) return "";
- const iconElement = createElement(IconComponent, { size: 14, className: "inline-block" });
- return renderToStaticMarkup(iconElement);
-}
-
-// Get browser icon path
-function getBrowserIconPath(browser: string): string {
- const BROWSER_TO_LOGO: Record<string, string> = {
- Chrome: "Chrome.svg",
- "Mobile Chrome": "Chrome.svg",
- Firefox: "Firefox.svg",
- "Mobile Firefox": "Firefox.svg",
- Safari: "Safari.svg",
- "Mobile Safari": "Safari.svg",
- Edge: "Edge.svg",
- Opera: "Opera.svg",
- Brave: "Brave.svg",
- };
- return BROWSER_TO_LOGO[browser] ? `/browsers/${BROWSER_TO_LOGO[browser]}` : "";
-}
-
-// Get OS icon path
-function getOSIconPath(os: string): string {
- const OS_TO_LOGO: Record<string, string> = {
- Windows: "Windows.svg",
- Android: "Android.svg",
- android: "Android.svg",
- Linux: "Tux.svg",
- macOS: "macOS.svg",
- iOS: "Apple.svg",
- "Chrome OS": "Chrome.svg",
- };
- return OS_TO_LOGO[os] ? `/operating-systems/${OS_TO_LOGO[os]}` : "";
-}
-
-export function useTimelineLayer({
- map,
- mapLoaded,
- mapView,
-}: {
- map: React.RefObject<mapboxgl.Map | null>;
- mapLoaded: boolean;
- mapView: string;
-}) {
- const { activeSessions } = useTimelineSessions();
- const { currentTime } = useTimelineStore();
- const popupRef = useRef<mapboxgl.Popup | null>(null);
- const markersMapRef = useRef<
- Map<string, { marker: mapboxgl.Marker; element: HTMLDivElement; cleanup: () => void }>
- >(new Map());
- const openTooltipSessionIdRef = useRef<string | null>(null);
- const [selectedSession, setSelectedSession] = useState<GetSessionsResponse[number] | null>(null);
-
- // Close tooltip when timeline time changes
- useEffect(() => {
- if (popupRef.current && popupRef.current.isOpen()) {
- popupRef.current.remove();
- openTooltipSessionIdRef.current = null;
- }
- }, [currentTime]);
-
- useEffect(() => {
- if (!map.current || !mapLoaded) return;
-
- // Initialize popup once
- if (!popupRef.current) {
- popupRef.current = new mapboxgl.Popup({
- closeButton: false,
- closeOnClick: false,
- className: "globe-tooltip",
- anchor: "top-left",
- offset: [-30, -30], // Offset to align avatar center (padding 12px + avatar 36px/2 = 30px)
- });
- }
-
- const markersMap = markersMapRef.current;
-
- // Add global click handler to close tooltip when clicking outside
- const handleMapClick = () => {
- if (popupRef.current && popupRef.current.isOpen()) {
- popupRef.current.remove();
- openTooltipSessionIdRef.current = null;
- }
- };
-
- if (map.current) {
- map.current.on("click", handleMapClick);
- }
-
- // Hide all markers if not in timeline view
- if (mapView !== "timeline") {
- markersMap.forEach(({ marker, cleanup }) => {
- cleanup(); // Remove event listeners
- marker.remove();
- });
- // Still need to return cleanup function to remove map click handler
- return () => {
- if (map.current) {
- map.current.off("click", handleMapClick);
- }
- };
- }
-
- // Build set of active session IDs
- const activeSessionIds = new Set(activeSessions.filter(s => s.lat && s.lon).map(s => s.session_id));
-
- // Remove markers for sessions that are no longer active
- const toRemove: string[] = [];
- markersMap.forEach(({ marker, cleanup }, sessionId) => {
- if (!activeSessionIds.has(sessionId)) {
- cleanup(); // Remove event listeners
- marker.remove();
- toRemove.push(sessionId);
- }
- });
- toRemove.forEach(id => markersMap.delete(id));
-
- // Create or update markers for active sessions
- activeSessions.forEach(session => {
- if (!map.current) return;
-
- const roundedLat = round(session.lat, 4);
- const roundedLon = round(session.lon, 4);
- const existing = markersMap.get(session.session_id);
-
- if (existing) {
- // Update existing marker position if needed
- const currentLngLat = existing.marker.getLngLat();
- if (currentLngLat.lng !== roundedLon || currentLngLat.lat !== roundedLat) {
- existing.marker.setLngLat([roundedLon, roundedLat]);
- }
- // Re-add marker if it was removed
- if (!existing.marker.getElement().isConnected) {
- existing.marker.addTo(map.current);
- }
- } else {
- // Create new marker
- const avatarContainer = document.createElement("div");
- avatarContainer.className = "timeline-avatar-marker";
- avatarContainer.style.cursor = "pointer";
- avatarContainer.style.borderRadius = "50%";
- avatarContainer.style.overflow = "hidden";
- avatarContainer.style.width = "32px";
- avatarContainer.style.height = "32px";
- avatarContainer.style.boxShadow = "0 2px 8px rgba(0,0,0,0.3)";
-
- // Generate avatar SVG
- const avatarSVG = generateAvatarSVG(session.user_id, 32);
- avatarContainer.innerHTML = avatarSVG;
-
- // Create marker
- const marker = new mapboxgl.Marker({
- element: avatarContainer,
- anchor: "center",
- })
- .setLngLat([roundedLon, roundedLat])
- .addTo(map.current);
-
- // Add click event for tooltip
- const toggleTooltip = (e: MouseEvent) => {
- e.stopPropagation();
- if (!map.current || !popupRef.current) return;
-
- // If clicking the same marker that has the tooltip open, close it
- if (popupRef.current.isOpen() && openTooltipSessionIdRef.current === session.session_id) {
- popupRef.current.remove();
- openTooltipSessionIdRef.current = null;
- return;
- }
-
- // If clicking a different marker (or no tooltip is open), show this one
- if (popupRef.current.isOpen()) {
- popupRef.current.remove();
- }
-
- const avatarSVG = generateAvatarSVG(session.user_id, 36);
- const countryCode = session.country?.length === 2 ? session.country : "";
- const flagSVG = renderCountryFlag(countryCode);
- const deviceIconSVG = renderDeviceIcon(session.device_type || "");
- const browserIconPath = getBrowserIconPath(session.browser || "");
- const osIconPath = getOSIconPath(session.operating_system || "");
-
- // Duration formatting
- const durationDisplay = formatShortDuration(session.session_duration || 0);
-
- // Start time formatting
- const startTime = DateTime.fromSQL(session.session_start, { zone: "utc" })
- .setLocale(userLocale)
- .toLocal()
- .toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm");
-
- // Pageview and event icons
- const pageviewIconSVG = renderToStaticMarkup(
- createElement(Eye, { size: 14, className: "inline-block text-blue-400" })
- );
- const eventIconSVG = renderToStaticMarkup(
- createElement(MousePointerClick, { size: 14, className: "inline-block text-amber-400" })
- );
-
- // Referrer/Channel display
- const domain = extractDomain(session.referrer);
- let referrerIconSVG = "";
- let referrerText = "";
-
- if (domain) {
- referrerText = getDisplayName(domain);
- referrerIconSVG = renderChannelIcon(session.channel);
- } else {
- referrerText = session.channel;
- referrerIconSVG = renderChannelIcon(session.channel);
- }
-
- const name = generateName(session.user_id);
-
- const html = `
- <div class="flex flex-col gap-3 p-3 bg-neutral-850 border border-neutral-750 rounded-lg">
- <div class="flex items-start gap-2.5">
- <div class="flex-shrink-0 w-9 h-9 rounded-full overflow-hidden">
- ${avatarSVG}
- </div>
- <div class="flex-1 min-w-0">
- <h3 class="text-sm font-semibold text-white truncate">${name}</h3>
- <div class="flex items-center gap-1 text-xs text-neutral-300 mt-0.5">
- ${flagSVG}
- <span>${session.city || "Unknown"}, ${session.country || "Unknown"}</span>
- </div>
- </div>
- </div>
- <div class="flex flex-wrap items-center gap-1.5">
- ${browserIconPath ? `<img src="${browserIconPath}" alt="${session.browser}" title="${session.browser}" class="w-4 h-4" />` : ""}
- ${osIconPath ? `<img src="${osIconPath}" alt="${session.operating_system}" title="${session.operating_system}" class="w-4 h-4" />` : ""}
- <span class="flex items-center" title="${session.device_type}">${deviceIconSVG}</span>
- <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-neutral-800 text-neutral-300 text-xs">
- ${pageviewIconSVG}
- <span>${session.pageviews || 0}</span>
- </span>
- <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-neutral-800 text-neutral-300 text-xs">
- ${eventIconSVG}
- <span>${session.events || 0}</span>
- </span>
- </div>
- <div class="flex items-center gap-1.5">
- <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-neutral-800 text-neutral-300 text-xs">
- ${referrerIconSVG}
- <span>${referrerText}</span>
- </span>
- </div>
- <div class="flex items-center justify-between gap-2 text-xs text-neutral-400 pt-1.5 border-t border-neutral-700">
- <span>${startTime}</span>
- <span class="text-neutral-200">${durationDisplay}</span>
- </div>
- <button
- class="view-session-btn w-full px-2 py-1 bg-accent-600 hover:bg-accent-700 text-white text-xs font-medium rounded transition-colors"
- data-session-id="${session.session_id}"
- tabindex="-1"
- >
- View Details
- </button>
- </div>
- `;
-
- popupRef.current.setLngLat([roundedLon, roundedLat]).setHTML(html).addTo(map.current);
- openTooltipSessionIdRef.current = session.session_id;
-
- // Add click handler to the button
- const button = document.querySelector(`[data-session-id="${session.session_id}"]`);
- if (button) {
- button.addEventListener("click", e => {
- e.stopPropagation();
- setSelectedSession(session);
- popupRef.current?.remove();
- openTooltipSessionIdRef.current = null;
- });
- }
- };
-
- avatarContainer.addEventListener("click", toggleTooltip);
-
- // Create cleanup function to remove event listener
- const cleanup = () => {
- avatarContainer.removeEventListener("click", toggleTooltip);
- };
-
- // Store marker with cleanup function
- markersMap.set(session.session_id, { marker, element: avatarContainer, cleanup });
- }
- });
-
- // Cleanup function
- return () => {
- // Clean up all markers and their event listeners
- markersMap.forEach(({ marker, cleanup }) => {
- cleanup(); // Remove event listeners
- marker.remove();
- });
- if (map.current) {
- map.current.off("click", handleMapClick);
- }
- };
- }, [activeSessions, mapLoaded, map, mapView]);
-
- return {
- selectedSession,
- setSelectedSession,
- };
-}
diff --git a/client/src/app/[site]/globe/page.tsx b/client/src/app/[site]/globe/page.tsx
index 4b050321b..5808eb08a 100644
--- a/client/src/app/[site]/globe/page.tsx
+++ b/client/src/app/[site]/globe/page.tsx
@@ -4,6 +4,7 @@ import "mapbox-gl/dist/mapbox-gl.css";
import { useRef } from "react";
import "./globe.css";
+import { VisuallyHidden } from "radix-ui";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { NothingFound } from "../../../components/NothingFound";
import { SessionCard } from "../../../components/Sessions/SessionCard";
@@ -14,17 +15,31 @@ import { GlobeSessions } from "./components/GlobeSessions";
import MapViewSelector from "./components/ModeSelector";
import { TimelineScrubber } from "./components/TimelineScrubber";
import { useGlobeStore } from "./globeStore";
+import { useTimelineLayer } from "./hooks/timelineLayer/useTimelineLayer";
import { useCoordinatesLayer } from "./hooks/useCoordinatesLayer";
import { useCountriesLayer } from "./hooks/useCountriesLayer";
import { useLayerVisibility } from "./hooks/useLayerVisibility";
import { useMapbox } from "./hooks/useMapbox";
import { useSubdivisionsLayer } from "./hooks/useSubdivisionsLayer";
-import { useTimelineLayer } from "./hooks/useTimelineLayer";
-import { VisuallyHidden } from "radix-ui";
+import { useTimelineStore } from "./timelineStore";
+import { useTimelineSessions } from "./hooks/timelineLayer/useTimelineSessions";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";
+import { WINDOW_SIZE_OPTIONS } from "./timelineUtils";
+import { useConfigs } from "../../../lib/configs";
export default function GlobePage() {
useSetPageTitle("Rybbit · Globe");
const mapContainer = useRef<HTMLDivElement>(null);
+ const { windowSize, setManualWindowSize } = useTimelineStore();
+
+ // Fetch timeline sessions and update store
+ useTimelineSessions();
+
+ // Handle window size change
+ const handleWindowSizeChange = (value: string) => {
+ const newSize = parseInt(value, 10);
+ setManualWindowSize(newSize);
+ };
const mapView = useGlobeStore(state => state.mapView);
@@ -57,6 +72,8 @@ export default function GlobePage() {
useLayerVisibility(map, mapView, mapLoaded);
+ const { configs, isLoading } = useConfigs();
+
return (
<DisabledOverlay message="Globe" featurePath="globe">
<div className="relative w-full h-dvh overflow-hidden">
@@ -64,19 +81,19 @@ export default function GlobePage() {
<SubHeader />
</div>
<div className="absolute top-0 left-0 right-0 bottom-0 z-10">
- {process.env.NEXT_PUBLIC_MAPBOX_TOKEN ? (
+ {configs?.mapboxToken ? (
<div
ref={mapContainer}
className="w-full h-full [&_.mapboxgl-ctrl-bottom-left]:!hidden [&_.mapboxgl-ctrl-logo]:!hidden"
/>
- ) : (
+ ) : isLoading ? null : (
<div className="w-full h-full flex items-center justify-center">
<NothingFound
title="Mapbox access token not found"
description={
<p className="text-sm max-w-[600px] text-center">
- Please set the <code>NEXT_PUBLIC_MAPBOX_TOKEN</code> environment variable and rebuild all
- containers. To get a Mapbox token, please visit{" "}
+ Please set the <code>MAPBOX_TOKEN</code> environment variable and rebuild all containers. To get a
+ Mapbox token, please visit{" "}
<a
href="https://docs.mapbox.com/help/dive-deeper/access-tokens/"
target="_blank"
@@ -96,7 +113,22 @@ export default function GlobePage() {
<div className="pointer-events-auto">
<MapViewSelector />
</div>
- {mapView !== "timeline" && (
+ {mapView === "timeline" ? (
+ <div className="pointer-events-auto">
+ <Select value={windowSize.toString()} onValueChange={handleWindowSizeChange}>
+ <SelectTrigger className="w-[100px]" size="sm">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {WINDOW_SIZE_OPTIONS.map(option => (
+ <SelectItem key={option.value} value={option.value.toString()}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ ) : (
<div className="pointer-events-auto">
<GlobeSessions />
</div>
diff --git a/client/src/app/[site]/globe/timelineStore.ts b/client/src/app/[site]/globe/timelineStore.ts
index d4ea308a5..73b638a21 100644
--- a/client/src/app/[site]/globe/timelineStore.ts
+++ b/client/src/app/[site]/globe/timelineStore.ts
@@ -1,15 +1,25 @@
import { DateTime } from "luxon";
import { create } from "zustand";
+import { useMemo } from "react";
+import type { GetSessionsResponse } from "../../../api/analytics/userSessions";
+import { getActiveSessions } from "./timelineUtils";
interface TimelineStore {
currentTime: DateTime | null;
timeRange: { start: DateTime; end: DateTime } | null;
windowSize: number; // in minutes
manualWindowSize: number | null; // User-selected window size, overrides auto-calculated
+ allSessions: GetSessionsResponse;
+ isLoading: boolean;
+ isError: boolean;
+ hasMoreData: boolean;
setCurrentTime: (time: DateTime) => void;
setTimeRange: (start: DateTime, end: DateTime) => void;
setWindowSize: (size: number) => void;
setManualWindowSize: (size: number | null) => void;
+ setAllSessions: (sessions: GetSessionsResponse, hasMoreData: boolean) => void;
+ setLoading: (loading: boolean) => void;
+ setError: (error: boolean) => void;
reset: () => void;
}
@@ -18,9 +28,40 @@ export const useTimelineStore = create<TimelineStore>(set => ({
timeRange: null,
windowSize: 60,
manualWindowSize: null,
+ allSessions: [],
+ isLoading: false,
+ isError: false,
+ hasMoreData: false,
setCurrentTime: time => set({ currentTime: time }),
setTimeRange: (start, end) => set({ timeRange: { start, end }, currentTime: start }),
setWindowSize: size => set({ windowSize: size }),
setManualWindowSize: size => set({ manualWindowSize: size, windowSize: size || 60 }),
- reset: () => set({ currentTime: null, timeRange: null, windowSize: 60, manualWindowSize: null }),
+ setAllSessions: (sessions, hasMoreData) => set({ allSessions: sessions, hasMoreData }),
+ setLoading: loading => set({ isLoading: loading }),
+ setError: error => set({ isError: error }),
+ reset: () =>
+ set({
+ currentTime: null,
+ timeRange: null,
+ windowSize: 60,
+ manualWindowSize: null,
+ allSessions: [],
+ isLoading: false,
+ isError: false,
+ hasMoreData: false,
+ }),
}));
+
+// Hook to compute active sessions based on current time and window size
+// Uses useMemo to prevent infinite re-renders
+export function useActiveSessions(): GetSessionsResponse {
+ const currentTime = useTimelineStore(state => state.currentTime);
+ const windowSize = useTimelineStore(state => state.windowSize);
+ const allSessions = useTimelineStore(state => state.allSessions);
+
+ return useMemo(() => {
+ if (!currentTime || allSessions.length === 0) return [];
+ const activeSessions = getActiveSessions(allSessions, currentTime, windowSize);
+ return activeSessions;
+ }, [currentTime, windowSize, allSessions]);
+}
diff --git a/client/src/app/[site]/globe/timelineUtils.ts b/client/src/app/[site]/globe/timelineUtils.ts
index 31f88a828..69ff56410 100644
--- a/client/src/app/[site]/globe/timelineUtils.ts
+++ b/client/src/app/[site]/globe/timelineUtils.ts
@@ -83,6 +83,76 @@ export function getActiveSessions(
return sessions.filter(session => sessionOverlapsWindow(session, windowStart, windowEnd));
}
+/**
+ * Optimized function to count sessions per time window
+ * Uses sweep-line algorithm with binary search for O(W log N) complexity
+ */
+export function getSessionCountsPerWindow(
+ sessions: GetSessionsResponse,
+ timeWindows: DateTime[],
+ windowSize: number
+): number[] {
+ // Parse all session times once upfront and convert to epoch ms
+ const startTimes: number[] = [];
+ const endTimes: number[] = [];
+
+ for (const session of sessions) {
+ const start = DateTime.fromSQL(session.session_start, { zone: "utc" }).toLocal();
+ const end = DateTime.fromSQL(session.session_end, { zone: "utc" }).toLocal();
+ startTimes.push(start.toMillis());
+ endTimes.push(end.toMillis());
+ }
+
+ // Sort both arrays independently
+ startTimes.sort((a, b) => a - b);
+ endTimes.sort((a, b) => a - b);
+
+ // Binary search to find first index where value >= target
+ const findFirstGTE = (arr: number[], target: number): number => {
+ let left = 0;
+ let right = arr.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (arr[mid] < target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+ return left;
+ };
+
+ // Binary search to find first index where value > target
+ const findFirstGT = (arr: number[], target: number): number => {
+ let left = 0;
+ let right = arr.length;
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2);
+ if (arr[mid] <= target) {
+ left = mid + 1;
+ } else {
+ right = mid;
+ }
+ }
+ return left;
+ };
+
+ // Count sessions for each window using sweep-line
+ return timeWindows.map(windowStart => {
+ const windowEnd = windowStart.plus({ minutes: windowSize });
+ const windowStartMs = windowStart.toMillis();
+ const windowEndMs = windowEnd.toMillis();
+
+ // Count = (sessions that started before window end) - (sessions that ended at or before window start)
+ const startsBeforeEnd = findFirstGTE(startTimes, windowEndMs);
+ const endsBeforeOrAtStart = findFirstGT(endTimes, windowStartMs);
+
+ return startsBeforeEnd - endsBeforeOrAtStart;
+ });
+}
+
/**
* Format time for display in the timeline
*/
diff --git a/client/src/components/Avatar.tsx b/client/src/components/Avatar.tsx
index 4e7434167..9f935525a 100644
--- a/client/src/components/Avatar.tsx
+++ b/client/src/components/Avatar.tsx
@@ -1,15 +1,31 @@
import BoringAvatar from "boring-avatars";
import { animals, colors, uniqueNamesGenerator } from "unique-names-generator";
+export const AVATAR_COLORS = [
+ "#ec4899",
+ "#be185d",
+ "#f97316",
+ "#c2410c",
+ "#eab308",
+ "#a16207",
+ "#10b981",
+ "#059669",
+ "#14b8a6",
+ "#0d9488",
+ "#06b6d4",
+ "#0e7490",
+ "#3b82f6",
+ "#1d4ed8",
+ "#6366f1",
+ "#8b5cf6",
+ "#475569",
+ "#6b7280",
+ "#9ca3af",
+ "#d1d5db",
+];
+
export function Avatar({ id, size = 20 }: { id: string; size?: number }) {
- return (
- <BoringAvatar
- size={size}
- name={id}
- variant="beam"
- colors={["#92A1C6", "#146A7C", "#F0AB3D", "#C271B4", "#C20D90"]}
- />
- );
+ return <BoringAvatar size={size} name={id} variant="beam" colors={AVATAR_COLORS} />;
}
export function generateName(id: string) {
diff --git a/client/src/lib/configs.ts b/client/src/lib/configs.ts
index 0e13a62a8..7dd9e7746 100644
--- a/client/src/lib/configs.ts
+++ b/client/src/lib/configs.ts
@@ -3,6 +3,7 @@ import { authedFetch } from "../api/utils";
interface Configs {
disableSignup: boolean;
+ mapboxToken: string;
}
export function useConfigs() {
diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml
index 2a1c0c971..5d844346e 100644
--- a/docker-compose.cloud.yml
+++ b/docker-compose.cloud.yml
@@ -114,6 +114,7 @@ services:
# Axiom logging configuration (optional)
- AXIOM_DATASET=${AXIOM_DATASET}
- AXIOM_TOKEN=${AXIOM_TOKEN}
+ - MAPBOX_TOKEN=${MAPBOX_TOKEN}
depends_on:
clickhouse:
condition: service_healthy
diff --git a/docker-compose.yml b/docker-compose.yml
index c8cbd6586..3881da3ff 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -94,6 +94,7 @@ services:
- BASE_URL=${BASE_URL}
- DISABLE_SIGNUP=${DISABLE_SIGNUP}
- DISABLE_TELEMETRY=${DISABLE_TELEMETRY}
+ - MAPBOX_TOKEN=${MAPBOX_TOKEN}
# # Redis configuration
# - REDIS_HOST=redis
# - REDIS_PORT=6379
diff --git a/server/src/api/getConfig.ts b/server/src/api/getConfig.ts
index e428a2147..602ff9935 100644
--- a/server/src/api/getConfig.ts
+++ b/server/src/api/getConfig.ts
@@ -1,8 +1,9 @@
import { FastifyRequest, FastifyReply } from "fastify";
-import { DISABLE_SIGNUP } from "../lib/const.js";
+import { DISABLE_SIGNUP, MAPBOX_TOKEN } from "../lib/const.js";
export async function getConfig(_: FastifyRequest, reply: FastifyReply) {
return reply.send({
disableSignup: DISABLE_SIGNUP,
+ mapboxToken: MAPBOX_TOKEN,
});
}
diff --git a/server/src/lib/const.ts b/server/src/lib/const.ts
index 745d78be9..a30e10446 100644
--- a/server/src/lib/const.ts
+++ b/server/src/lib/const.ts
@@ -6,6 +6,7 @@ export const IS_CLOUD = process.env.CLOUD === "true";
export const DISABLE_SIGNUP = process.env.DISABLE_SIGNUP === "true";
export const DISABLE_TELEMETRY = process.env.DISABLE_TELEMETRY === "true";
export const SECRET = process.env.BETTER_AUTH_SECRET;
+export const MAPBOX_TOKEN = process.env.MAPBOX_TOKEN;
// Trial constants (commented out as we're replacing with free tier)
// export const TRIAL_DURATION_DAYS = 14;