Skip to content

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

Enhance user session analytics with geographical data and timeline vi… (#623)

Bill Yangc4e5769df8de
diff --git a/client/src/api/analytics/userSessions.ts b/client/src/api/analytics/userSessions.ts
index 30b27e386..0ba838e16 100644
--- a/client/src/api/analytics/userSessions.ts
+++ b/client/src/api/analytics/userSessions.ts
@@ -35,6 +35,8 @@ export type GetSessionsResponse = {
errors: number;
outbound: number;
ip: string;
+ lat: number;
+ lon: number;
}[];
export function useGetSessionsInfinite(userId?: string) {
diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsx
index 11f60a214..23554ab6b 100644
--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx
+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx
@@ -2,11 +2,13 @@ import { ArrowRight, ChevronDown, ChevronUp, ExternalLink } from "lucide-react";
import { DateTime } from "luxon";
import Link from "next/link";
import { useMemo, useState } from "react";
+import { VisuallyHidden } from "radix-ui";
import { useCurrentSite } from "../../../../api/admin/sites";
import { GetSessionsResponse, useGetSessionsInfinite } from "../../../../api/analytics/userSessions";
import { Avatar, generateName } from "../../../../components/Avatar";
import { Channel } from "../../../../components/Channel";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
+import { SessionCard as FullSessionCard } from "../../../../components/Sessions/SessionCard";
import {
BrowserTooltipIcon,
CountryFlagTooltipIcon,
@@ -15,6 +17,7 @@ import {
} from "../../../../components/TooltipIcons/TooltipIcons";
import { Badge } from "../../../../components/ui/badge";
import { Button } from "../../../../components/ui/button";
+import { Dialog, DialogContent, DialogTitle } from "../../../../components/ui/dialog";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
import { formatShortDuration, hour12, userLocale } from "../../../../lib/dateTimeUtils";
import { cn, formatter } from "../../../../lib/utils";
@@ -60,7 +63,7 @@ function SessionCardSkeleton() {
);
}
-function SessionCard({ session }: { session: GetSessionsResponse[number] }) {
+function SessionCard({ session, onClick }: { session: GetSessionsResponse[number]; onClick?: () => void }) {
// Calculate session duration in minutes
const start = DateTime.fromSQL(session.session_start);
const end = DateTime.fromSQL(session.session_end);
@@ -71,16 +74,14 @@ function SessionCard({ session }: { session: GetSessionsResponse[number] }) {
const name = generateName(session.user_id);
return (
- <div className="rounded-lg bg-neutral-850 border border-neutral-800 overflow-hidden p-2 space-y-2">
+ <div
+ className="rounded-lg bg-neutral-850 border border-neutral-800 overflow-hidden p-2 space-y-2 cursor-pointer hover:bg-neutral-800 transition-colors"
+ onClick={onClick}
+ >
<div className="flex justify-between border-b border-neutral-700 pb-2">
<div className="text-sm text-neutral-100 flex items-center gap-1.5">
<Avatar id={session.user_id} size={16} />
- <Link
- href={`/${siteId.site?.siteId}/user/${session.user_id}`}
- className="text-xs text-neutral-200 max-w-32 truncate hover:underline"
- >
- {name}
- </Link>
+ <span className="text-xs text-neutral-200 max-w-32 truncate hover:underline">{name}</span>
</div>
<div className="flex space-x-2 items-center pr-2">
<div className="flex items-center gap-1.5 text-xs text-neutral-300">
@@ -164,6 +165,7 @@ export function GlobeSessions() {
const { data, isLoading, error, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetSessionsInfinite();
const [expanded, setExpanded] = useState(false);
+ const [selectedSession, setSelectedSession] = useState<GetSessionsResponse[number] | null>(null);
// Combine all pages of data
const flattenedData = useMemo(() => {
@@ -172,24 +174,37 @@ export function GlobeSessions() {
}, [data]);
return (
- <div className="space-y-2 bg-neutral-900 p-2 rounded-lg w-[371px]">
- <div className="text-sm text-neutral-300 font-medium flex items-center justify-between">
- SESSIONS
- <Button variant="ghost" size="smIcon" onClick={() => setExpanded(!expanded)}>
- {expanded ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />}
- </Button>
- </div>
- <div className={cn("space-y-2 overflow-y-auto", expanded ? "max-h-[calc(100vh-210px)]" : "max-h-[210px]")}>
- {isLoading ? (
- <>
- <SessionCardSkeleton />
- <SessionCardSkeleton />
- <SessionCardSkeleton />
- </>
- ) : (
- flattenedData.map(session => <SessionCard key={session.session_id} session={session} />)
- )}
+ <>
+ <div className="space-y-2 bg-neutral-900 p-2 rounded-lg w-[371px]">
+ <div className="text-sm text-neutral-300 font-medium flex items-center justify-between">
+ SESSIONS
+ <Button variant="ghost" size="smIcon" onClick={() => setExpanded(!expanded)}>
+ {expanded ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />}
+ </Button>
+ </div>
+ <div className={cn("space-y-2 overflow-y-auto", expanded ? "max-h-[calc(100vh-210px)]" : "max-h-[210px]")}>
+ {isLoading ? (
+ <>
+ <SessionCardSkeleton />
+ <SessionCardSkeleton />
+ <SessionCardSkeleton />
+ </>
+ ) : (
+ flattenedData.map(session => (
+ <SessionCard key={session.session_id} session={session} onClick={() => setSelectedSession(session)} />
+ ))
+ )}
+ </div>
</div>
- </div>
+
+ <Dialog open={!!selectedSession} onOpenChange={open => !open && setSelectedSession(null)}>
+ <VisuallyHidden.Root>
+ <DialogTitle>Session Details</DialogTitle>
+ </VisuallyHidden.Root>
+ <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto bg-transparent border-0 p-0 shadow-none gap-0 [&>button]:hidden">
+ {selectedSession && <FullSessionCard session={selectedSession} expandedByDefault />}
+ </DialogContent>
+ </Dialog>
+ </>
);
}
diff --git a/client/src/app/[site]/globe/components/ModeSelector.tsx b/client/src/app/[site]/globe/components/ModeSelector.tsx
index 0e3679302..f0697722f 100644
--- a/client/src/app/[site]/globe/components/ModeSelector.tsx
+++ b/client/src/app/[site]/globe/components/ModeSelector.tsx
@@ -1,39 +1,63 @@
-import { Globe2, HouseIcon, Radio } from "lucide-react";
-
-import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Clock, Globe2, HouseIcon, Radio } from "lucide-react";
+import { cn } from "@/lib/utils";
import { useGlobeStore } from "../globeStore";
-export type MapView = "countries" | "subdivisions" | "coordinates";
+export type MapView = "countries" | "subdivisions" | "coordinates" | "timeline";
+
+interface TabButtonProps {
+ active: boolean;
+ onClick: () => void;
+ icon: React.ReactNode;
+ label: string;
+}
+
+function TabButton({ active, onClick, icon, label }: TabButtonProps) {
+ return (
+ <button
+ onClick={onClick}
+ className={cn(
+ "inline-flex items-center justify-center whitespace-nowrap rounded px-2 py-1 text-xs font-medium transition-all",
+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400",
+ active ? "bg-white/10 text-white" : "text-neutral-400 hover:text-neutral-200 hover:bg-white/[0.03]"
+ )}
+ >
+ {icon}
+ {label}
+ </button>
+ );
+}
export default function MapViewSelector() {
const { mapView, setMapView } = useGlobeStore();
- const mapViewToTab: Record<MapView, string> = {
- coordinates: "tab-1",
- countries: "tab-2",
- subdivisions: "tab-3",
- };
-
return (
- <Tabs value={mapViewToTab[mapView]}>
- <ScrollArea>
- <TabsList className="mb-3">
- <TabsTrigger value="tab-1" className="group" onClick={() => setMapView("coordinates")}>
- <Radio className="-ms-0.5 me-1.5 opacity-60" size={16} aria-hidden="true" />
- Coordinates
- </TabsTrigger>
- <TabsTrigger value="tab-2" onClick={() => setMapView("countries")}>
- <Globe2 className="-ms-0.5 me-1.5 opacity-60" size={16} aria-hidden="true" />
- Countries
- </TabsTrigger>
- <TabsTrigger value="tab-3" className="group" onClick={() => setMapView("subdivisions")}>
- <HouseIcon className="-ms-0.5 me-1.5 opacity-60" size={16} aria-hidden="true" />
- Subdivisions
- </TabsTrigger>
- </TabsList>
- <ScrollBar orientation="horizontal" />
- </ScrollArea>
- </Tabs>
+ <div>
+ <div className="inline-flex items-center gap-0.5 rounded-lg bg-neutral-900/40 backdrop-blur-sm p-0.5 border border-white/10">
+ <TabButton
+ active={mapView === "timeline"}
+ onClick={() => setMapView("timeline")}
+ icon={<Clock className="mr-1 opacity-60" size={14} />}
+ label="Timeline"
+ />
+ <TabButton
+ active={mapView === "coordinates"}
+ onClick={() => setMapView("coordinates")}
+ icon={<Radio className="mr-1 opacity-60" size={14} />}
+ label="Coordinates"
+ />
+ <TabButton
+ active={mapView === "countries"}
+ onClick={() => setMapView("countries")}
+ icon={<Globe2 className="mr-1 opacity-60" size={14} />}
+ label="Countries"
+ />
+ <TabButton
+ active={mapView === "subdivisions"}
+ onClick={() => setMapView("subdivisions")}
+ icon={<HouseIcon className="mr-1 opacity-60" size={14} />}
+ label="Subdivisions"
+ />
+ </div>
+ </div>
);
}
diff --git a/client/src/app/[site]/globe/components/TimelineScrubber.tsx b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
new file mode 100644
index 000000000..c05c04908
--- /dev/null
+++ b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
@@ -0,0 +1,180 @@
+import { debounce } from "lodash";
+import { 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 { useTimelineSessions } from "../hooks/useTimelineSessions";
+import { useTimelineStore } from "../timelineStore";
+import { formatTimelineTime, generateTimeWindows, getActiveSessions, WINDOW_SIZE_OPTIONS } from "../timelineUtils";
+
+export function TimelineScrubber() {
+ const { currentTime, timeRange, windowSize, setCurrentTime, setManualWindowSize } = useTimelineStore();
+ const { activeSessions, allSessions, isLoading } = useTimelineSessions();
+ 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);
+ };
+
+ // Generate time windows for the slider
+ const timeWindows = useMemo(() => {
+ if (!timeRange) return [];
+ return generateTimeWindows(timeRange.start, timeRange.end, windowSize);
+ }, [timeRange, windowSize]);
+
+ // Get current window index from store
+ const currentIndex = useMemo(() => {
+ if (!currentTime || timeWindows.length === 0) return 0;
+ const index = timeWindows.findIndex(w => w.equals(currentTime));
+ return index >= 0 ? index : 0;
+ }, [currentTime, timeWindows]);
+
+ // Sync local slider index with store (on initial load and during playback)
+ const isInitialMount = useRef(true);
+ useEffect(() => {
+ if (isInitialMount.current) {
+ setLocalSliderIndex(currentIndex);
+ isInitialMount.current = false;
+ } else if (isPlaying) {
+ setLocalSliderIndex(currentIndex);
+ }
+ }, [currentIndex, isPlaying]);
+
+ // Create debounced update function
+ const debouncedUpdateTime = useRef(
+ debounce((index: number, windows: ReturnType<typeof generateTimeWindows>) => {
+ if (windows[index]) {
+ setCurrentTime(windows[index]);
+ }
+ }, 100)
+ ).current;
+
+ // Cleanup debounce on unmount
+ useEffect(() => {
+ return () => {
+ debouncedUpdateTime.cancel();
+ };
+ }, [debouncedUpdateTime]);
+
+ // Handle slider change - update local state immediately, debounce the expensive update
+ const handleSliderChange = useCallback(
+ (value: number[]) => {
+ const index = value[0];
+ setLocalSliderIndex(index);
+ debouncedUpdateTime(index, timeWindows);
+ },
+ [timeWindows, debouncedUpdateTime]
+ );
+
+ // Auto-play functionality
+ useEffect(() => {
+ if (!isPlaying || timeWindows.length === 0) return;
+
+ const interval = setInterval(() => {
+ const nextIndex = currentIndex + 1;
+ if (nextIndex >= timeWindows.length) {
+ // Loop back to start
+ setCurrentTime(timeWindows[0]);
+ setIsPlaying(false);
+ } else {
+ setCurrentTime(timeWindows[nextIndex]);
+ }
+ }, 500); // Update every 500ms
+
+ return () => clearInterval(interval);
+ }, [isPlaying, currentIndex, timeWindows, setCurrentTime]);
+
+ // Get the display time based on local slider position
+ const displayTime = useMemo(() => {
+ 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 [];
+
+ return timeWindows.map(windowStart => {
+ const sessionsInWindow = getActiveSessions(allSessions, windowStart, windowSize);
+ return sessionsInWindow.length;
+ });
+ }, [timeWindows, allSessions, windowSize]);
+
+ // Get max count for scaling the histogram
+ const maxCount = useMemo(() => {
+ return sessionCounts.length > 0 ? Math.max(...sessionCounts, 1) : 1;
+ }, [sessionCounts]);
+
+ if (isLoading || !timeRange || timeWindows.length === 0) {
+ return null;
+ }
+
+ 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) => {
+ const heightPercentage = (count / maxCount) * 100;
+ const isActive = index === localSliderIndex;
+
+ return (
+ <div
+ key={index}
+ className="flex-1 transition-all duration-150 cursor-pointer hover:opacity-80"
+ style={{
+ height: `${heightPercentage}%`,
+ backgroundColor: isActive ? "hsl(var(--accent-600))" : "rgba(115, 115, 115, 0.4)",
+ minHeight: count > 0 ? "2px" : "0px",
+ }}
+ title={`${count} session${count !== 1 ? "s" : ""}`}
+ onClick={() => {
+ setLocalSliderIndex(index);
+ if (timeWindows[index]) {
+ setCurrentTime(timeWindows[index]);
+ }
+ }}
+ />
+ );
+ })}
+ </div>
+ <TimelineSlider value={[localSliderIndex]} max={timeWindows.length - 1} onValueChange={handleSliderChange} />
+
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-1 w-full">
+ <button
+ onClick={() => setIsPlaying(!isPlaying)}
+ className="p-1.5 rounded hover:bg-neutral-800 transition-colors"
+ aria-label={isPlaying ? "Pause" : "Play"}
+ >
+ {isPlaying ? <Pause className="w-4 h-4 text-neutral-300" /> : <Play className="w-4 h-4 text-neutral-300" />}
+ </button>
+ <span className="text-xs text-neutral-400 min-w-[80px]">
+ {displayTime ? formatTimelineTime(displayTime, windowSize) : ""}
+ </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}
+ </span>{" "}
+ sessions
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/globe/globe.css b/client/src/app/[site]/globe/globe.css
index 90391459f..2b8021430 100644
--- a/client/src/app/[site]/globe/globe.css
+++ b/client/src/app/[site]/globe/globe.css
@@ -1,14 +1,19 @@
/* Globe Mapbox Popup Styling */
+.mapboxgl-popup.globe-tooltip {
+ pointer-events: auto;
+}
+
.mapboxgl-popup.globe-tooltip .mapboxgl-popup-content {
- background-color: #0a0a0a;
+ background-color: transparent;
color: white;
- border-radius: 0.375rem;
- padding: 0.5rem;
- box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
+ border-radius: 0;
+ padding: 0;
+ box-shadow: none;
+ pointer-events: auto;
}
.mapboxgl-popup.globe-tooltip .mapboxgl-popup-tip {
- border-top-color: #0a0a0a;
+ display: none;
}
.mapboxgl-popup.globe-tooltip .mapboxgl-popup-close-button {
diff --git a/client/src/app/[site]/globe/globeStore.ts b/client/src/app/[site]/globe/globeStore.ts
index ce43a0e1b..2205a25ca 100644
--- a/client/src/app/[site]/globe/globeStore.ts
+++ b/client/src/app/[site]/globe/globeStore.ts
@@ -7,6 +7,6 @@ interface GlobeStore {
}
export const useGlobeStore = create<GlobeStore>(set => ({
- mapView: "coordinates",
+ mapView: "timeline",
setMapView: view => set({ mapView: view }),
}));
diff --git a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts b/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
index 2cd42b2fe..f2fe8075a 100644
--- a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
+++ b/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
@@ -1,6 +1,4 @@
import { FilterParameter } from "@rybbit/shared/dist/filters";
-import { scaleSequentialSqrt } from "d3-scale";
-import { interpolateYlOrRd } from "d3-scale-chromatic";
import { round } from "lodash";
import mapboxgl from "mapbox-gl";
import { useEffect, useRef } from "react";
@@ -46,9 +44,6 @@ export function useCoordinatesLayer({
if (!map.current) return;
const highest = liveSessionLocations.reduce((acc, curr) => Math.max(acc, curr.count), 0) || 1;
- const normalized = 5 / Number(minutes);
- const weightColor = scaleSequentialSqrt(interpolateYlOrRd).domain([0, highest * normalized * 15]);
- const singleColor = weightColor(0); // Use the start color for all hexbins
// Calculate size scale based on total number of locations
const totalLocations = liveSessionLocations.length;
@@ -133,7 +128,7 @@ export function useCoordinatesLayer({
// 15,
// ["interpolate", ["linear"], ["get", "count"], 1, 8 * sizeMultiplier, highest, 20 * sizeMultiplier],
// ],
- "circle-color": ["case", ["get", "isFiltered"], "#3b82f6", singleColor],
+ "circle-color": ["case", ["get", "isFiltered"], "#3b82f6", "#fff4d6"],
"circle-opacity": ["case", ["get", "isFiltered"], 0.9, 0.7],
"circle-stroke-width": ["case", ["get", "isFiltered"], 2, 1],
"circle-stroke-color": ["case", ["get", "isFiltered"], "#60a5fa", "#fff"],
@@ -159,12 +154,14 @@ export function useCoordinatesLayer({
const coordinates = e.lngLat;
const html = `
- <div class="flex items-center gap-1 mb-1">
- <span class="text-sm font-medium">${city}</span>
- </div>
- <div class="text-sm">
- <span class="font-bold text-accent-400">${count.toLocaleString()}</span>
- <span class="text-neutral-300"> sessions</span>
+ <div class="bg-neutral-850 border border-neutral-750 rounded-lg p-2">
+ <div class="flex items-center gap-1 mb-1">
+ <span class="text-sm font-medium text-white">${city}</span>
+ </div>
+ <div class="text-sm">
+ <span class="font-bold text-accent-400">${count.toLocaleString()}</span>
+ <span class="text-neutral-300"> sessions</span>
+ </div>
</div>
`;
@@ -223,7 +220,7 @@ export function useCoordinatesLayer({
"case",
["get", "isFiltered"],
"#3b82f6",
- singleColor,
+ "#fff4d6",
]);
map.current.setPaintProperty("realtime-coordinates-layer", "circle-opacity", [
"case",
diff --git a/client/src/app/[site]/globe/hooks/useCountriesLayer.ts b/client/src/app/[site]/globe/hooks/useCountriesLayer.ts
index 8ffcafeda..01009c597 100644
--- a/client/src/app/[site]/globe/hooks/useCountriesLayer.ts
+++ b/client/src/app/[site]/globe/hooks/useCountriesLayer.ts
@@ -97,12 +97,14 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
// Use Mapbox native popup
const coordinates = e.lngLat;
const html = `
- <div class="flex items-center gap-1 mb-1">
- <span class="text-sm font-medium">${name}</span>
- </div>
- <div class="text-sm">
- <span class="font-bold text-accent-400">${count.toLocaleString()}</span>
- <span class="text-neutral-300"> (${percentage.toFixed(1)}%) sessions</span>
+ <div class="bg-neutral-850 border border-neutral-700 rounded-lg p-3">
+ <div class="flex items-center gap-1 mb-1">
+ <span class="text-sm font-medium text-white">${name}</span>
+ </div>
+ <div class="text-sm">
+ <span class="font-bold text-accent-400">${count.toLocaleString()}</span>
+ <span class="text-neutral-300"> (${percentage.toFixed(1)}%) sessions</span>
+ </div>
</div>
`;
diff --git a/client/src/app/[site]/globe/hooks/useLayerVisibility.ts b/client/src/app/[site]/globe/hooks/useLayerVisibility.ts
index aab3982ea..a5300c83e 100644
--- a/client/src/app/[site]/globe/hooks/useLayerVisibility.ts
+++ b/client/src/app/[site]/globe/hooks/useLayerVisibility.ts
@@ -45,5 +45,6 @@ export function useLayerVisibility(
mapView === "coordinates" ? "visible" : "none"
);
}
+ // Note: Timeline view uses HTML markers instead of layers, visibility is handled in useTimelineLayer
}, [mapView, mapLoaded, map]);
}
diff --git a/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts b/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts
index a82bdff21..2c7ef990b 100644
--- a/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts
+++ b/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts
@@ -96,12 +96,14 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
const coordinates = e.lngLat;
const html = `
- <div class="flex items-center gap-1 mb-1">
- <span class="text-sm font-medium">${name}</span>
- </div>
- <div class="text-sm">
- <span class="font-bold text-accent-400">${count.toLocaleString()}</span>
- <span class="text-neutral-300"> (${percentage.toFixed(1)}%) sessions</span>
+ <div class="bg-neutral-850 border border-neutral-700 rounded-lg p-3">
+ <div class="flex items-center gap-1 mb-1">
+ <span class="text-sm font-medium text-white">${name}</span>
+ </div>
+ <div class="text-sm">
+ <span class="font-bold text-accent-400">${count.toLocaleString()}</span>
+ <span class="text-neutral-300"> (${percentage.toFixed(1)}%) sessions</span>
+ </div>
</div>
`;
diff --git a/client/src/app/[site]/globe/hooks/useTimelineLayer.ts b/client/src/app/[site]/globe/hooks/useTimelineLayer.ts
new file mode 100644
index 000000000..7bfe3ee8b
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/useTimelineLayer.ts
@@ -0,0 +1,411 @@
+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/hooks/useTimelineSessions.ts b/client/src/app/[site]/globe/hooks/useTimelineSessions.ts
new file mode 100644
index 000000000..bb09806c7
--- /dev/null
+++ b/client/src/app/[site]/globe/hooks/useTimelineSessions.ts
@@ -0,0 +1,80 @@
+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";
+
+export function useTimelineSessions() {
+ const { time, site } = useStore();
+ const { currentTime, windowSize, manualWindowSize, setTimeRange, setWindowSize } = useTimelineStore();
+
+ const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
+
+ // Fetch all sessions with a large page size (10000) without pagination
+ const { data, isLoading, isError } = useQuery<APIResponse<GetSessionsResponse>>({
+ queryKey: ["timeline-sessions", time, site, filteredFilters],
+ queryFn: () => {
+ const requestParams = {
+ ...getQueryParams(time),
+ filters: filteredFilters,
+ page: 1,
+ limit: 10000,
+ };
+
+ return authedFetch<APIResponse<GetSessionsResponse>>(`/sessions/${site}`, requestParams);
+ },
+ staleTime: Infinity,
+ });
+
+ const allSessions = useMemo(() => {
+ if (!data?.data) return [];
+ return data.data;
+ }, [data]);
+
+ // Calculate time range from fetched sessions and initialize timeline
+ useEffect(() => {
+ if (allSessions.length === 0) return;
+
+ // Find the earliest and latest session times
+ let earliest: DateTime | null = null;
+ let latest: DateTime | null = null;
+
+ allSessions.forEach(session => {
+ const start = DateTime.fromSQL(session.session_start, { zone: "utc" }).toLocal();
+ const end = DateTime.fromSQL(session.session_end, { zone: "utc" }).toLocal();
+
+ if (!earliest || start < earliest) {
+ earliest = start;
+ }
+ if (!latest || end > latest) {
+ latest = end;
+ }
+ });
+
+ if (earliest && latest) {
+ // Only auto-calculate window size if user hasn't manually set it
+ if (manualWindowSize === null) {
+ const calculatedWindowSize = calculateWindowSize(earliest, latest);
+ setWindowSize(calculatedWindowSize);
+ }
+ setTimeRange(earliest, latest);
+ }
+ }, [allSessions, setTimeRange, setWindowSize, manualWindowSize]);
+
+ // 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,
+ };
+}
diff --git a/client/src/app/[site]/globe/page.tsx b/client/src/app/[site]/globe/page.tsx
index 7e07a213a..151e4db7c 100644
--- a/client/src/app/[site]/globe/page.tsx
+++ b/client/src/app/[site]/globe/page.tsx
@@ -6,16 +6,21 @@ import "./globe.css";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { NothingFound } from "../../../components/NothingFound";
+import { SessionCard } from "../../../components/Sessions/SessionCard";
+import { Dialog, DialogContent, DialogTitle } from "../../../components/ui/dialog";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { SubHeader } from "../components/SubHeader/SubHeader";
import { GlobeSessions } from "./components/GlobeSessions";
import MapViewSelector from "./components/ModeSelector";
+import { TimelineScrubber } from "./components/TimelineScrubber";
import { useGlobeStore } from "./globeStore";
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";
export default function GlobePage() {
useSetPageTitle("Rybbit · Globe");
@@ -44,11 +49,17 @@ export default function GlobePage() {
mapView,
});
+ const { selectedSession, setSelectedSession } = useTimelineLayer({
+ map,
+ mapLoaded,
+ mapView,
+ });
+
useLayerVisibility(map, mapView, mapLoaded);
return (
<DisabledOverlay message="Globe" featurePath="globe">
- <div className="relative w-full h-dvh">
+ <div className="relative w-full h-dvh overflow-hidden">
<div className="p-2 md:p-4 relative z-50">
<SubHeader />
</div>
@@ -80,14 +91,22 @@ export default function GlobePage() {
/>
</div>
)}
- <div className="absolute bottom-0 left-4 z-99999">
+ <div className="absolute bottom-2 left-4 z-99999 right-4 flex flex-col gap-2">
+ {mapView !== "timeline" && <GlobeSessions />}
<MapViewSelector />
- </div>
- <div className="absolute bottom-[60px] left-4 z-99999">
- <GlobeSessions />
+ {mapView === "timeline" && <TimelineScrubber />}
</div>
</div>
</div>
+
+ <Dialog open={!!selectedSession} onOpenChange={open => !open && setSelectedSession(null)}>
+ <VisuallyHidden.Root>
+ <DialogTitle>Session Details</DialogTitle>
+ </VisuallyHidden.Root>
+ <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto bg-transparent border-0 p-0 shadow-none [&>button]:hidden">
+ {selectedSession && <SessionCard session={selectedSession} expandedByDefault />}
+ </DialogContent>
+ </Dialog>
</DisabledOverlay>
);
}
diff --git a/client/src/app/[site]/globe/timelineStore.ts b/client/src/app/[site]/globe/timelineStore.ts
new file mode 100644
index 000000000..d4ea308a5
--- /dev/null
+++ b/client/src/app/[site]/globe/timelineStore.ts
@@ -0,0 +1,26 @@
+import { DateTime } from "luxon";
+import { create } from "zustand";
+
+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
+ setCurrentTime: (time: DateTime) => void;
+ setTimeRange: (start: DateTime, end: DateTime) => void;
+ setWindowSize: (size: number) => void;
+ setManualWindowSize: (size: number | null) => void;
+ reset: () => void;
+}
+
+export const useTimelineStore = create<TimelineStore>(set => ({
+ currentTime: null,
+ timeRange: null,
+ windowSize: 60,
+ manualWindowSize: null,
+ 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 }),
+}));
diff --git a/client/src/app/[site]/globe/timelineUtils.ts b/client/src/app/[site]/globe/timelineUtils.ts
new file mode 100644
index 000000000..d10ca03de
--- /dev/null
+++ b/client/src/app/[site]/globe/timelineUtils.ts
@@ -0,0 +1,103 @@
+import { DateTime } from "luxon";
+import { GetSessionsResponse } from "../../../api/analytics/userSessions";
+
+/**
+ * Calculate the appropriate window size in minutes based on the total time range
+ */
+export function calculateWindowSize(startTime: DateTime, endTime: DateTime): number {
+ const diffInMinutes = endTime.diff(startTime, "minutes").minutes;
+
+ if (diffInMinutes <= 1440) {
+ // 1 day or less: 1 hour windows
+ return 60;
+ } else if (diffInMinutes <= 4320) {
+ // 3 days or less: 3 hour windows
+ return 180;
+ } else if (diffInMinutes <= 10080) {
+ // 1 week or less: 6 hour windows
+ return 360;
+ } else if (diffInMinutes <= 43200) {
+ // 30 days or less: 1 day windows
+ return 1440;
+ } else {
+ // More than 30 days: 3 day windows
+ return 4320;
+ }
+}
+
+/**
+ * Available window size options for the dropdown
+ */
+export const WINDOW_SIZE_OPTIONS = [
+ { value: 1, label: "1 minute" },
+ { value: 5, label: "5 minutes" },
+ { value: 15, label: "15 minutes" },
+ { value: 30, label: "30 minutes" },
+ { value: 60, label: "1 hour" },
+ { value: 180, label: "3 hours" },
+ { value: 360, label: "6 hours" },
+ { value: 720, label: "12 hours" },
+ { value: 1440, label: "1 day" },
+ { value: 4320, label: "3 days" },
+];
+
+/**
+ * Generate time windows for the timeline scrubber
+ */
+export function generateTimeWindows(startTime: DateTime, endTime: DateTime, windowSize: number): DateTime[] {
+ const windows: DateTime[] = [];
+ let currentTime = startTime;
+
+ while (currentTime <= endTime) {
+ windows.push(currentTime);
+ currentTime = currentTime.plus({ minutes: windowSize });
+ }
+
+ return windows;
+}
+
+/**
+ * Check if a session overlaps with a given time window
+ */
+export function sessionOverlapsWindow(
+ session: GetSessionsResponse[number],
+ windowStart: DateTime,
+ windowEnd: DateTime
+): boolean {
+ const sessionStart = DateTime.fromSQL(session.session_start, { zone: "utc" }).toLocal();
+ const sessionEnd = DateTime.fromSQL(session.session_end, { zone: "utc" }).toLocal();
+
+ // Session overlaps if:
+ // - It starts before the window ends AND
+ // - It ends after the window starts
+ return sessionStart < windowEnd && sessionEnd > windowStart;
+}
+
+/**
+ * Filter sessions that are active during a specific time window
+ */
+export function getActiveSessions(
+ sessions: GetSessionsResponse,
+ windowStart: DateTime,
+ windowSize: number
+): GetSessionsResponse {
+ const windowEnd = windowStart.plus({ minutes: windowSize });
+
+ return sessions.filter(session => sessionOverlapsWindow(session, windowStart, windowEnd));
+}
+
+/**
+ * Format time for display in the timeline
+ */
+export function formatTimelineTime(time: DateTime, windowSize: number): string {
+ if (windowSize < 60) {
+ // Less than 1 hour: show time
+ return time.toFormat("HH:mm");
+ } else if (windowSize < 1440) {
+ // Less than 1 day: show date and time
+ return time.toFormat("MMM d, HH:mm");
+ } else {
+ // 1 day or more: show date only
+ return time.toFormat("MMM d");
+ }
+}
diff --git a/client/src/app/[site]/layout.tsx b/client/src/app/[site]/layout.tsx
index 02d8c44b4..55d7115b3 100644
--- a/client/src/app/[site]/layout.tsx
+++ b/client/src/app/[site]/layout.tsx
@@ -28,7 +28,6 @@ export default function SiteLayout({ children }: { children: React.ReactNode })
if (width && width < 768) {
return (
<div>
- <TopBar />
<Header />
<div>{children}</div>
</div>
diff --git a/client/src/components/Channel.tsx b/client/src/components/Channel.tsx
index 09845a54d..9b75a4b9a 100644
--- a/client/src/components/Channel.tsx
+++ b/client/src/components/Channel.tsx
@@ -18,7 +18,7 @@ import {
import { Badge } from "./ui/badge";
import { Favicon } from "./Favicon";
-const getChannelIcon = (channel: string) => {
+export const getChannelIcon = (channel: string) => {
switch (channel) {
case "Direct":
return <Link className="w-4 h-4 text-gray-400" />;
@@ -57,7 +57,7 @@ const getChannelIcon = (channel: string) => {
}
};
-const getDisplayName = (hostname: string): string => {
+export const getDisplayName = (hostname: string): string => {
// Handle Google domains with startsWith
if (hostname.startsWith("google.") || hostname.startsWith("www.google.")) {
return "Google";
@@ -119,7 +119,7 @@ const getDisplayName = (hostname: string): string => {
return commonSites[hostname] || hostname;
};
-const extractDomain = (url: string): string | null => {
+export const extractDomain = (url: string): string | null => {
try {
if (!url || url === "direct") return null;
if (url.startsWith("android-app://")) {
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index 08a1e5a68..8628d0cc5 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -22,6 +22,7 @@ interface SessionCardProps {
session: GetSessionsResponse[number];
userId?: string;
onClick?: () => void;
+ expandedByDefault?: boolean;
}
// Function to truncate path for display
@@ -33,9 +34,8 @@ function truncatePath(path: string, maxLength: number = 32) {
return `${path.substring(0, maxLength)}...`;
}
-export function SessionCard({ session, onClick, userId }: SessionCardProps) {
- const [expanded, setExpanded] = useState(false);
-
+export function SessionCard({ session, onClick, userId, expandedByDefault }: SessionCardProps) {
+ const [expanded, setExpanded] = useState(expandedByDefault || false);
// Calculate session duration in minutes
const start = DateTime.fromSQL(session.session_start);
const end = DateTime.fromSQL(session.session_end);
@@ -53,7 +53,7 @@ export function SessionCard({ session, onClick, userId }: SessionCardProps) {
const name = generateName(session.user_id);
return (
- <div className="mb-3 rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden">
+ <div className="rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden">
<div className="p-3 cursor-pointer" onClick={handleCardClick}>
<div className="flex items-center gap-2">
<div className="hidden md:flex items-center gap-2">
@@ -177,7 +177,7 @@ export const SessionCardSkeleton = memo(() => {
// Create multiple skeletons for a realistic loading state
const skeletons = Array.from({ length: 10 }).map((_, index) => (
- <div className="mb-3 rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden" key={index}>
+ <div className="rounded-lg bg-neutral-900 border border-neutral-800 overflow-hidden" key={index}>
<div className="p-3">
<div className="flex items-center gap-2">
{/* Avatar and User ID */}
diff --git a/client/src/components/Sessions/SessionsList.tsx b/client/src/components/Sessions/SessionsList.tsx
index 683ba2aff..554fe3d98 100644
--- a/client/src/components/Sessions/SessionsList.tsx
+++ b/client/src/components/Sessions/SessionsList.tsx
@@ -21,7 +21,7 @@ export default function SessionsList({ userId }: { userId?: string }) {
if (error) return <div className="text-red-500 p-4">Error: {(error as Error).message}</div>;
return (
- <div ref={containerRef} className="overflow-auto ">
+ <div ref={containerRef} className="overflow-auto space-y-3">
{isLoading ? (
// Show skeleton cards while loading
<SessionCardSkeleton />
@@ -38,11 +38,7 @@ export default function SessionsList({ userId }: { userId?: string }) {
))
)}
- {isFetchingNextPage && (
- <div className="">
- <SessionCardSkeleton key="loading-more" />
- </div>
- )}
+ {isFetchingNextPage && <SessionCardSkeleton key="loading-more" />}
{hasNextPage && (
<div className="flex justify-center py-2">
diff --git a/client/src/components/ui/timeline-slider.tsx b/client/src/components/ui/timeline-slider.tsx
new file mode 100644
index 000000000..5f441d0cb
--- /dev/null
+++ b/client/src/components/ui/timeline-slider.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import * as React from "react";
+import * as SliderPrimitive from "@radix-ui/react-slider";
+
+import { cn } from "@/lib/utils";
+
+const TimelineSlider = React.forwardRef<
+ React.ElementRef<typeof SliderPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <SliderPrimitive.Root
+ ref={ref}
+ className={cn("relative flex w-full touch-none select-none items-center", className)}
+ {...props}
+ >
+ <SliderPrimitive.Track className="relative h-0.5 w-full grow overflow-hidden rounded-full bg-neutral-800/50">
+ <SliderPrimitive.Range className="absolute h-full bg-accent-400" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="block h-2.5 w-2.5 rounded-full border border-accent-400 bg-accent-400 shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-400 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-900 disabled:pointer-events-none disabled:opacity-50 hover:scale-125 hover:shadow-md cursor-grab active:cursor-grabbing active:scale-110" />
+ </SliderPrimitive.Root>
+));
+TimelineSlider.displayName = SliderPrimitive.Root.displayName;
+
+export { TimelineSlider };
diff --git a/client/src/providers/QueryProvider.tsx b/client/src/providers/QueryProvider.tsx
index a8d56c903..ce6ba9b5d 100644
--- a/client/src/providers/QueryProvider.tsx
+++ b/client/src/providers/QueryProvider.tsx
@@ -10,7 +10,7 @@ export default function QueryProvider({ children }: { children: React.ReactNode
return (
<QueryClientProvider client={queryClient}>
{children}
- <ReactQueryDevtools initialIsOpen={false} />
+ {/* <ReactQueryDevtools initialIsOpen={false} /> */}
</QueryClientProvider>
);
}
diff --git a/server/src/api/analytics/getSessions.ts b/server/src/api/analytics/getSessions.ts
index ce4eaf89d..cccacd2c2 100644
--- a/server/src/api/analytics/getSessions.ts
+++ b/server/src/api/analytics/getSessions.ts
@@ -35,6 +35,8 @@ export type GetSessionsResponse = {
errors: number;
outbound: number;
ip: string;
+ lat: number;
+ lon: number;
}[];
export interface GetSessionsRequest {
@@ -42,13 +44,14 @@ export interface GetSessionsRequest {
site: string;
};
Querystring: FilterParams<{
+ limit: number;
page: number;
userId?: string;
}>;
}
export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res: FastifyReply) {
- const { filters, page, userId } = req.query;
+ const { filters, page, userId, limit } = req.query;
const site = req.params.site;
const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);
if (!userHasAccessToSite) {
@@ -117,8 +120,8 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:
query_params: {
siteId: Number(site),
userId,
- limit: 100,
- offset: (page - 1) * 100,
+ limit: limit || 100,
+ offset: (page - 1) * (limit || 100),
},
});