🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor timelineUtils and TimelineScrubber for improved session window calculations and loading state handling
Bill Yangb6b727453d39
diff --git a/client/src/app/[site]/globe/components/TimelineScrubber.tsx b/client/src/app/[site]/globe/components/TimelineScrubber.tsxindex c05c04908..7cbcba274 100644--- a/client/src/app/[site]/globe/components/TimelineScrubber.tsx+++ b/client/src/app/[site]/globe/components/TimelineScrubber.tsx@@ -1,15 +1,16 @@import { debounce } from "lodash";-import { Pause, Play } from "lucide-react";+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";export function TimelineScrubber() {const { currentTime, timeRange, windowSize, setCurrentTime, setManualWindowSize } = useTimelineStore();- const { activeSessions, allSessions, isLoading } = useTimelineSessions();+ const { activeSessions, allSessions, isLoading, hasMoreData } = useTimelineSessions();const [isPlaying, setIsPlaying] = useState(false);const [localSliderIndex, setLocalSliderIndex] = useState(0);@@ -107,7 +108,16 @@ export function TimelineScrubber() {return sessionCounts.length > 0 ? Math.max(...sessionCounts, 1) : 1;}, [sessionCounts]);- if (isLoading || !timeRange || timeWindows.length === 0) {+ if (isLoading) {+ return (+ <div className="flex items-center justify-center gap-2 text-xs text-neutral-400 h-[66px] w-full">+ <div className="w-4 h-4 border-2 border-neutral-600 border-t-accent-500 rounded-full animate-spin" />+ <span>Loading sessions...</span>+ </div>+ );+ }++ if (!timeRange || timeWindows.length === 0) {return null;}@@ -172,6 +182,18 @@ export function TimelineScrubber() {{activeSessions.length} / {allSessions.length}</span>{" "}sessions+ {hasMoreData && (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <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>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}</div></div></div>diff --git a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts b/client/src/app/[site]/globe/hooks/useCoordinatesLayer.tsindex f3b684537..0ec0ed239 100644--- a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts+++ b/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts@@ -44,11 +44,8 @@ export function useCoordinatesLayer({const addCoordinatesLayer = () => {if (!map.current) return;- const topSize =- Math.pow(- liveSessionLocations.reduce((acc, curr) => Math.max(acc, curr.count), 0),- 0.5- ) || 1;+ const maxCount = liveSessionLocations.reduce((acc, curr) => Math.max(acc, curr.count), 0) || 1;+ const topSize = Math.pow(maxCount, 0.5);// Calculate size scale based on total number of locationsconst totalLocations = liveSessionLocations.length;@@ -113,13 +110,45 @@ export function useCoordinatesLayer({["exponential", 2],["zoom"],0,- ["interpolate", ["linear"], ["get", "count"], 1, 1 * sizeMultiplier, topSize, 5 * sizeMultiplier],+ [+ "interpolate",+ ["linear"],+ ["sqrt", ["get", "count"]],+ 1,+ 1 * sizeMultiplier,+ topSize,+ 5 * sizeMultiplier,+ ],5,- ["interpolate", ["linear"], ["get", "count"], 1, 3 * sizeMultiplier, topSize, 10 * sizeMultiplier],+ [+ "interpolate",+ ["linear"],+ ["sqrt", ["get", "count"]],+ 1,+ 3 * sizeMultiplier,+ topSize,+ 10 * sizeMultiplier,+ ],10,- ["interpolate", ["linear"], ["get", "count"], 1, 7 * sizeMultiplier, topSize, 20 * sizeMultiplier],+ [+ "interpolate",+ ["linear"],+ ["sqrt", ["get", "count"]],+ 1,+ 7 * sizeMultiplier,+ topSize,+ 20 * sizeMultiplier,+ ],15,- ["interpolate", ["linear"], ["get", "count"], 1, 15 * sizeMultiplier, topSize, 40 * sizeMultiplier],+ [+ "interpolate",+ ["linear"],+ ["sqrt", ["get", "count"]],+ 1,+ 15 * sizeMultiplier,+ topSize,+ 40 * sizeMultiplier,+ ],],// "circle-radius": [// "interpolate",@@ -231,13 +260,13 @@ export function useCoordinatesLayer({["exponential", 2],["zoom"],0,- ["interpolate", ["linear"], ["get", "count"], 1, 1 * sizeMultiplier, topSize, 5 * sizeMultiplier],+ ["interpolate", ["linear"], ["sqrt", ["get", "count"]], 1, 1 * sizeMultiplier, topSize, 5 * sizeMultiplier],5,- ["interpolate", ["linear"], ["get", "count"], 1, 3 * sizeMultiplier, topSize, 10 * sizeMultiplier],+ ["interpolate", ["linear"], ["sqrt", ["get", "count"]], 1, 3 * sizeMultiplier, topSize, 10 * sizeMultiplier],10,- ["interpolate", ["linear"], ["get", "count"], 1, 7 * sizeMultiplier, topSize, 20 * sizeMultiplier],+ ["interpolate", ["linear"], ["sqrt", ["get", "count"]], 1, 7 * sizeMultiplier, topSize, 20 * sizeMultiplier],15,- ["interpolate", ["linear"], ["get", "count"], 1, 15 * sizeMultiplier, topSize, 40 * sizeMultiplier],+ ["interpolate", ["linear"], ["sqrt", ["get", "count"]], 1, 15 * sizeMultiplier, topSize, 40 * sizeMultiplier],]);map.current.setPaintProperty("realtime-coordinates-layer", "circle-color", ["case",diff --git a/client/src/app/[site]/globe/hooks/useTimelineSessions.ts b/client/src/app/[site]/globe/hooks/useTimelineSessions.tsindex bb09806c7..8f23ca026 100644--- a/client/src/app/[site]/globe/hooks/useTimelineSessions.ts+++ b/client/src/app/[site]/globe/hooks/useTimelineSessions.ts@@ -14,18 +14,47 @@ export function useTimelineSessions() {const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);- // Fetch all sessions with a large page size (10000) without pagination- const { data, isLoading, isError } = useQuery<APIResponse<GetSessionsResponse>>({+ // Fetch all sessions with pagination (up to 5 pages, 50k sessions total)+ const { data, isLoading, isError } = useQuery<APIResponse<GetSessionsResponse> & { hasMoreData?: boolean }>({queryKey: ["timeline-sessions", time, site, filteredFilters],- queryFn: () => {- const requestParams = {- ...getQueryParams(time),- filters: filteredFilters,- page: 1,- limit: 10000,- };-- return authedFetch<APIResponse<GetSessionsResponse>>(`/sessions/${site}`, requestParams);+ queryFn: async () => {+ const allSessions = [];+ const maxPages = 5;+ const limit = 10000;+ let reachedMaxPages = false;++ for (let page = 1; page <= maxPages; page++) {+ const requestParams = {+ ...getQueryParams(time),+ filters: filteredFilters,+ page,+ limit,+ };++ const response = await authedFetch<APIResponse<GetSessionsResponse>>(`/sessions/${site}`, requestParams);++ if (response?.data) {+ allSessions.push(...response.data);++ // If we got fewer results than the limit, we've reached the end+ if (response.data.length < limit) {+ break;+ }++ // If we're on the last page and got a full page, there might be more+ if (page === maxPages && response.data.length === limit) {+ reachedMaxPages = true;+ }+ } else {+ break;+ }+ }++ // Return in the same format as the original API response+ return {+ data: allSessions,+ hasMoreData: reachedMaxPages,+ } as APIResponse<GetSessionsResponse> & { hasMoreData: boolean };},staleTime: Infinity,});@@ -63,7 +92,7 @@ export function useTimelineSessions() {}setTimeRange(earliest, latest);}- }, [allSessions, setTimeRange, setWindowSize, manualWindowSize]);+ }, [allSessions, setTimeRange, setWindowSize, manualWindowSize, time]);// Filter sessions based on current time windowconst activeSessions = useMemo(() => {@@ -76,5 +105,6 @@ export function useTimelineSessions() {activeSessions,isLoading,isError,+ hasMoreData: data?.hasMoreData || false,};}diff --git a/client/src/app/[site]/globe/timelineUtils.ts b/client/src/app/[site]/globe/timelineUtils.tsindex d10ca03de..31f88a828 100644--- a/client/src/app/[site]/globe/timelineUtils.ts+++ b/client/src/app/[site]/globe/timelineUtils.ts@@ -7,21 +7,18 @@ import { GetSessionsResponse } from "../../../api/analytics/userSessions";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) {+ if (diffInMinutes <= 4320) {// 3 days or less: 3 hour windows- return 180;+ return 60;} else if (diffInMinutes <= 10080) {- // 1 week or less: 6 hour windows- return 360;+ // 1 week or less: 3 hour windows+ return 180;} else if (diffInMinutes <= 43200) {- // 30 days or less: 1 day windows- return 1440;+ // 30 days or less: 6 hour windows+ return 360;} else {- // More than 30 days: 3 day windows- return 4320;+ // More than 30 days: 1 day windows+ return 1440;}}diff --git a/server/src/api/analytics/getSessions.ts b/server/src/api/analytics/getSessions.tsindex cccacd2c2..65078da72 100644--- a/server/src/api/analytics/getSessions.ts+++ b/server/src/api/analytics/getSessions.ts@@ -105,11 +105,11 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:GROUP BYsession_id,user_id+ ORDER BY session_end DESC)SELECT *FROM AggregatedSessionsWHERE 1 = 1 ${filterStatement}- ORDER BY session_end DESCLIMIT {limit:Int32} OFFSET {offset:Int32}`;