🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Live users (#760)
Bill Yangd100dadd12ae
diff --git a/client/package-lock.json b/client/package-lock.jsonindex e1bf884dc..30abd25f7 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -78,6 +78,7 @@"tailwind-merge": "2.6.0","tailwindcss-animate": "1.0.7","unique-names-generator": "^4.7.1",+ "vaul": "^1.1.2","zod": "3.24.4","zustand": "5.0.4"},@@ -12728,6 +12729,19 @@"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==","license": "MIT"},+ "node_modules/vaul": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",+ "integrity": "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-dialog": "^1.1.1"+ },+ "peerDependencies": {+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"+ }+ },"node_modules/walk-up-path": {"version": "4.0.0","resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz",diff --git a/client/package.json b/client/package.jsonindex a4007c94a..89d121b2a 100644--- a/client/package.json+++ b/client/package.json@@ -82,6 +82,7 @@"tailwind-merge": "2.6.0","tailwindcss-animate": "1.0.7","unique-names-generator": "^4.7.1",+ "vaul": "^1.1.2","zod": "3.24.4","zustand": "5.0.4"},diff --git a/client/src/api/analytics/hooks/useGetUserSessions.ts b/client/src/api/analytics/hooks/useGetUserSessions.tsindex 1565261fe..893342f24 100644--- a/client/src/api/analytics/hooks/useGetUserSessions.ts+++ b/client/src/api/analytics/hooks/useGetUserSessions.ts@@ -10,13 +10,21 @@ import {SessionPageviewsAndEvents,UserSessionCountResponse,} from "../endpoints";+import { Time } from "../../../components/DateSelector/types";-export function useGetSessions(- userId?: string,- page: number = 1,- limit: number = 100,- identifiedOnly: boolean = false-) {+export function useGetSessions({+ userId,+ page = 1,+ limit = 100,+ identifiedOnly = false,+ timeOverride,+}: {+ userId?: string;+ page?: number;+ limit?: number;+ identifiedOnly?: boolean;+ timeOverride?: Time;+}) {const { time, site } = useStore();const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);@@ -25,10 +33,10 @@ export function useGetSessions(// Otherwise use buildApiParams which handles past-minutes modeconst params = userId? { startDate: "", endDate: "", timeZone, filters: filteredFilters }- : buildApiParams(time, { filters: filteredFilters });+ : buildApiParams(timeOverride || time, { filters: filteredFilters });return useQuery<{ data: GetSessionsResponse }>({- queryKey: ["sessions", time, site, filteredFilters, userId, page, limit, identifiedOnly],+ queryKey: ["sessions", timeOverride || time, site, filteredFilters, userId, page, limit, identifiedOnly],queryFn: () => {return fetchSessions(site, {...params,@@ -42,7 +50,15 @@ export function useGetSessions(});}-export function useGetSessionsInfinite(userId?: string) {+export function useGetSessionsInfinite({+ userId,+ timeOverride,+ limit = 100,+}: {+ userId?: string;+ timeOverride?: Time;+ limit?: number;+}) {const { time, site } = useStore();const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);@@ -51,21 +67,22 @@ export function useGetSessionsInfinite(userId?: string) {// Otherwise use buildApiParams which handles past-minutes modeconst params = userId? { startDate: "", endDate: "", timeZone, filters: filteredFilters }- : buildApiParams(time, { filters: filteredFilters });+ : buildApiParams(timeOverride || time, { filters: filteredFilters });return useInfiniteQuery<{ data: GetSessionsResponse }>({- queryKey: ["sessions-infinite", time, site, filteredFilters, userId],+ queryKey: ["sessions-infinite", timeOverride || time, site, filteredFilters, userId],queryFn: ({ pageParam = 1 }) => {return fetchSessions(site, {...params,page: pageParam as number,userId,+ limit,});},initialPageParam: 1,getNextPageParam: (lastPage: { data: GetSessionsResponse }, allPages) => {// If we have data and it's a full page (100 items), there might be more- if (lastPage?.data && lastPage.data.length === 100) {+ if (lastPage?.data && lastPage.data.length === limit) {return allPages.length + 1;}return undefined;diff --git a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsxindex e250cfd4d..027a848e1 100644--- a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx+++ b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx@@ -1,30 +1,109 @@+import NumberFlow from "@number-flow/react";+import { useIntersectionObserver } from "@uidotdev/usehooks";+import { Rewind } from "lucide-react";+import { useEffect, useMemo } from "react";import { useGetLiveUserCount } from "../../../../api/analytics/hooks/useGetLiveUserCount";+import { useGetSessionsInfinite } from "../../../../api/analytics/hooks/useGetUserSessions";+import { NothingFound } from "../../../../components/NothingFound";+import { SessionCard, SessionCardSkeleton } from "../../../../components/Sessions/SessionCard";+import { Button } from "../../../../components/ui/button";+import { Drawer, DrawerContent, DrawerHeader, DrawerTitle, DrawerTrigger } from "../../../../components/ui/drawer";import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";-import NumberFlow from "@number-flow/react";+import { VisuallyHidden } from "@radix-ui/react-visually-hidden";+import { ScrollArea } from "../../../../components/ui/scroll-area";export function LiveUserCount() {const { data } = useGetLiveUserCount(5);- return (- <div className="flex items-center gap-1 text-base text-neutral-700 dark:text-neutral-200 mr-1">- <div className="flex justify-center">- <span className="relative flex h-3 w-3">- <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"></span>- <span className="relative inline-flex h-3 w-3 rounded-full bg-green-500"></span>- </span>- </div>+ const {+ data: sessionsData,+ isLoading,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ } = useGetSessionsInfinite({+ timeOverride: {+ mode: "past-minutes",+ pastMinutesStart: 5,+ pastMinutesEnd: 0,+ },+ limit: 25,+ });++ // Use the intersection observer hook+ const [ref, entry] = useIntersectionObserver({+ threshold: 0,+ root: null,+ rootMargin: "0px 0px 200px 0px",+ });- <Tooltip>- <TooltipTrigger>- <span className="text-sm text-neutral-700 dark:text-neutral-200 ml-1 font-medium">- {<NumberFlow respectMotionPreference={false} value={data?.count ?? 0} />}- <span className="ml-1"></span>- </span>- </TooltipTrigger>- <TooltipContent>- <p>Users online in past 5 minutes</p>- </TooltipContent>- </Tooltip>- </div>+ const sessions = useMemo(() => {+ if (!sessionsData) return [];+ return sessionsData.pages.flatMap(page => page.data || []);+ }, [sessionsData]);++ // Fetch next page when intersection observer detects the target is visible+ useEffect(() => {+ if (entry?.isIntersecting && hasNextPage && !isFetchingNextPage && !isLoading) {+ fetchNextPage();+ }+ }, [entry?.isIntersecting, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading]);++ return (+ <Drawer>+ <DrawerTrigger>+ <Tooltip>+ <TooltipTrigger>+ <Button className="h-8" variant="ghost">+ <div className="flex items-center gap-1 text-base text-neutral-700 dark:text-neutral-200 cursor-pointer">+ <span className="relative flex h-3 w-3">+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"></span>+ <span className="relative inline-flex h-3 w-3 rounded-full bg-green-500"></span>+ </span>+ <span className="text-sm text-neutral-700 dark:text-neutral-200 ml-1 font-medium">+ {<NumberFlow respectMotionPreference={false} value={data?.count ?? 0} />}+ </span>+ </div>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Users online in past 5 minutes</p>+ </TooltipContent>+ </Tooltip>+ </DrawerTrigger>+ <DrawerContent>+ <VisuallyHidden>+ <DrawerHeader>+ <DrawerTitle>Users online in past 5 minutes</DrawerTitle>+ </DrawerHeader>+ </VisuallyHidden>+ <ScrollArea+ className="h-[75vh]"+ maskClassName="before:from-white dark:before:from-neutral-950 after:from-white dark:after:from-neutral-950"+ >+ <div className="space-y-3 p-2 md:p-4 ">+ {isLoading ? (+ <SessionCardSkeleton count={5} />+ ) : sessions.length === 0 ? (+ <NothingFound+ icon={<Rewind className="w-10 h-10" />}+ title="No sessions found"+ description="No users online in the past 5 minutes"+ />+ ) : (+ <>+ {sessions.map((session, index) => (+ <SessionCard key={`${session.session_id}-${index}`} session={session} />+ ))}+ {/* Infinite scroll sentinel */}+ <div ref={ref} className="space-y-3">+ {isFetchingNextPage && <SessionCardSkeleton count={3} />}+ </div>+ </>+ )}+ </div>+ </ScrollArea>+ </DrawerContent>+ </Drawer>);}diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsxindex ca04adf51..eadd0e4fe 100644--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx@@ -162,7 +162,7 @@ function SessionCard({ session, onClick }: { session: GetSessionsResponse[number}export function GlobeSessions() {- const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetSessionsInfinite();+ const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useGetSessionsInfinite({});const [expanded, setExpanded] = useState(false);const [selectedSession, setSelectedSession] = useState<GetSessionsResponse[number] | null>(null);diff --git a/client/src/app/[site]/sessions/page.tsx b/client/src/app/[site]/sessions/page.tsxindex 4d784d876..3fe5fc07d 100644--- a/client/src/app/[site]/sessions/page.tsx+++ b/client/src/app/[site]/sessions/page.tsx@@ -15,7 +15,11 @@ export default function SessionsPage() {const [page, setPage] = useState(1);const [identifiedOnly, setIdentifiedOnly] = useState(false);- const { data, isLoading } = useGetSessions(undefined, page, LIMIT + 1, identifiedOnly);+ const { data, isLoading } = useGetSessions({+ page: page,+ limit: LIMIT + 1,+ identifiedOnly: identifiedOnly,+ });const allSessions = data?.data || [];const hasNextPage = allSessions.length > LIMIT;const sessions = allSessions.slice(0, LIMIT);diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsxindex 5795fe85f..58a1f1fa5 100644--- a/client/src/app/[site]/user/[userId]/page.tsx+++ b/client/src/app/[site]/user/[userId]/page.tsx@@ -34,7 +34,11 @@ export default function UserPage() {const { data, isLoading } = useUserInfo(Number(site), userId as string);const { data: sessionCount } = useGetUserSessionCount(userId as string);- const { data: sessionsData, isLoading: isLoadingSessions } = useGetSessions(userId as string, page, LIMIT + 1);+ const { data: sessionsData, isLoading: isLoadingSessions } = useGetSessions({+ userId: userId as string,+ page: page,+ limit: LIMIT + 1,+ });const allSessions = sessionsData?.data || [];const hasNextPage = allSessions.length > LIMIT;diff --git a/client/src/app/globals.css b/client/src/app/globals.cssindex 5fc627af5..9181e1d78 100644--- a/client/src/app/globals.css+++ b/client/src/app/globals.css@@ -118,7 +118,7 @@::before,::backdrop,::file-selector-button {- border-color: var(--color-gray-200, currentcolor);+ border-color: var(--color-border, currentcolor);}}diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsxindex 90b11d8ef..39cfc1c6c 100644--- a/client/src/components/Sessions/SessionCard.tsx+++ b/client/src/components/Sessions/SessionCard.tsx@@ -160,7 +160,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault }: Ses);}-export const SessionCardSkeleton = memo(({ userId }: { userId?: string }) => {+export const SessionCardSkeleton = memo(({ userId, count }: { userId?: string; count?: number }) => {// Function to get a random width class for skeletonsconst getRandomWidth = () => {const widths = ["w-16", "w-20", "w-24", "w-28", "w-32", "w-36", "w-40", "w-44", "w-48"];@@ -180,7 +180,7 @@ export const SessionCardSkeleton = memo(({ userId }: { userId?: string }) => {};// Create multiple skeletons for a realistic loading state- const skeletons = Array.from({ length: 25 }).map((_, index) => (+ const skeletons = Array.from({ length: count || 25 }).map((_, index) => (<divclassName="rounded-lg bg-white dark:bg-neutral-900 border border-neutral-100 dark:border-neutral-850 overflow-hidden"key={index}diff --git a/client/src/components/Sessions/SessionsList.tsx b/client/src/components/Sessions/SessionsList.tsxindex f9c6870b6..c092fff9b 100644--- a/client/src/components/Sessions/SessionsList.tsx+++ b/client/src/components/Sessions/SessionsList.tsx@@ -17,6 +17,7 @@ interface SessionsListProps {userId?: string;identifiedOnly?: boolean;setIdentifiedOnly?: (identifiedOnly: boolean) => void;+ pageSize?: number;}export function SessionsList({@@ -30,6 +31,7 @@ export function SessionsList({userId,identifiedOnly,setIdentifiedOnly,+ pageSize,}: SessionsListProps) {if (sessions.length === 0 && !isLoading) {return (@@ -64,7 +66,7 @@ export function SessionsList({{/* Session cards */}{isLoading ? (- <SessionCardSkeleton userId={userId} />+ <SessionCardSkeleton userId={userId} count={pageSize} />) : (sessions.map((session, index) => (<SessionCard key={`${session.session_id}-${index}`} session={session} userId={userId} />diff --git a/client/src/components/ui/drawer.tsx b/client/src/components/ui/drawer.tsxnew file mode 100644index 000000000..f88832d89--- /dev/null+++ b/client/src/components/ui/drawer.tsx@@ -0,0 +1,108 @@+"use client";++import * as React from "react";+import { Drawer as DrawerPrimitive } from "vaul";++import { cn } from "@/lib/utils";++function Drawer({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) {+ return <DrawerPrimitive.Root data-slot="drawer" {...props} />;+}++function DrawerTrigger({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {+ return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;+}++function DrawerPortal({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Portal>) {+ return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;+}++function DrawerClose({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Close>) {+ return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;+}++function DrawerOverlay({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {+ return (+ <DrawerPrimitive.Overlay+ data-slot="drawer-overlay"+ className={cn(+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",+ className+ )}+ {...props}+ />+ );+}++function DrawerContent({ className, children, ...props }: React.ComponentProps<typeof DrawerPrimitive.Content>) {+ return (+ <DrawerPortal data-slot="drawer-portal">+ <DrawerOverlay />+ <DrawerPrimitive.Content+ data-slot="drawer-content"+ className={cn(+ "group/drawer-content bg-background fixed z-50 flex h-auto flex-col",+ "data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",+ "data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",+ "data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",+ "data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",+ className+ )}+ {...props}+ >+ <div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />+ {children}+ </DrawerPrimitive.Content>+ </DrawerPortal>+ );+}++function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="drawer-header"+ className={cn(+ "flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",+ className+ )}+ {...props}+ />+ );+}++function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {+ return <div data-slot="drawer-footer" className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} />;+}++function DrawerTitle({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Title>) {+ return (+ <DrawerPrimitive.Title+ data-slot="drawer-title"+ className={cn("text-foreground font-semibold", className)}+ {...props}+ />+ );+}++function DrawerDescription({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Description>) {+ return (+ <DrawerPrimitive.Description+ data-slot="drawer-description"+ className={cn("text-muted-foreground text-sm", className)}+ {...props}+ />+ );+}++export {+ Drawer,+ DrawerPortal,+ DrawerOverlay,+ DrawerTrigger,+ DrawerClose,+ DrawerContent,+ DrawerHeader,+ DrawerFooter,+ DrawerTitle,+ DrawerDescription,+};