Skip to content

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

perf(dashboard): poll the live sessions list only while its drawer is open (#1313)

Goldflag7f3ce916c1d0
diff --git a/client/src/api/analytics/analyticsRequest.ts b/client/src/api/analytics/analyticsRequest.ts
index c3e74670b..d731dd28c 100644
--- a/client/src/api/analytics/analyticsRequest.ts
+++ b/client/src/api/analytics/analyticsRequest.ts
@@ -78,7 +78,11 @@ export function buildAnalyticsRequest(descriptor: AnalyticsDescriptor, context:
* Issue an analytics request. Used by the query hooks and by the non-React
* callers (CSV export), so both go through the same seam.
*/
-export async function fetchAnalytics<TData>(site: number | string, request: AnalyticsRequest): Promise<TData> {
+export async function fetchAnalytics<TData>(
+ site: number | string,
+ request: AnalyticsRequest,
+ signal?: AbortSignal
+): Promise<TData> {
const base =
request.organizationId === undefined
? `/sites/${site}`
@@ -86,7 +90,7 @@ export async function fetchAnalytics<TData>(site: number | string, request: Anal
const response = await authedFetch<TData | { data: TData }>(
`${base}/${request.path}`,
request.params,
- request.body === undefined ? {} : { method: "POST", data: request.body }
+ request.body === undefined ? { signal } : { method: "POST", data: request.body, signal }
);
return request.unwrap ? (response as { data: TData }).data : (response as TData);
}
diff --git a/client/src/api/analytics/hooks/useGetUserSessions.ts b/client/src/api/analytics/hooks/useGetUserSessions.ts
index 8efdb2820..7cba4bb74 100644
--- a/client/src/api/analytics/hooks/useGetUserSessions.ts
+++ b/client/src/api/analytics/hooks/useGetUserSessions.ts
@@ -79,11 +79,15 @@ export function useGetSessionsInfinite({
timeOverride,
limit = 100,
refetchInterval,
+ staleTime = Infinity,
+ abortable,
}: {
userId?: string;
timeOverride?: Time;
limit?: number;
refetchInterval?: number;
+ staleTime?: number;
+ abortable?: boolean;
}) {
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
@@ -101,8 +105,25 @@ export function useGetSessionsInfinite({
pageParams: page => ({ page }),
// A full page might have more behind it; a short one is the last.
getNextPageParam: (lastPage, allPages) => (lastPage.length === limit ? allPages.length + 1 : undefined),
- staleTime: Infinity,
+ staleTime,
refetchInterval,
+ abortable,
+ });
+}
+
+export const LIVE_SESSIONS_POLL_MS = 10_000;
+
+/**
+ * The past-5-minute sessions list behind LiveUserCount, polled every 10 s. Its observers are mounted
+ * only while someone needs the list, so unmounting the last one cancels a refetch mid-pages.
+ */
+export function useGetLiveSessions(staleTime: number) {
+ return useGetSessionsInfinite({
+ timeOverride: { mode: "past-minutes", pastMinutesStart: 5, pastMinutesEnd: 0 },
+ limit: 25,
+ refetchInterval: LIVE_SESSIONS_POLL_MS,
+ staleTime,
+ abortable: true,
});
}
diff --git a/client/src/api/analytics/useAnalyticsQuery.ts b/client/src/api/analytics/useAnalyticsQuery.ts
index b0df8cc3d..7f012a7f9 100644
--- a/client/src/api/analytics/useAnalyticsQuery.ts
+++ b/client/src/api/analytics/useAnalyticsQuery.ts
@@ -151,6 +151,9 @@ export interface AnalyticsInfiniteQueryOptions<TPage, TCursor> extends Analytics
refetchInterval?: number;
enabled?: boolean;
refetchOnWindowFocus?: boolean;
+ // Hand the query's abort signal to the request. Cancelling the query (or unmounting its last
+ // observer) then aborts the request and stops a refetch before it walks the remaining pages.
+ abortable?: boolean;
}
export function useAnalyticsInfiniteQuery<TPage, TCursor = number>(
@@ -160,11 +163,13 @@ export function useAnalyticsInfiniteQuery<TPage, TCursor = number>(
return useInfiniteQuery<TPage, Error, InfiniteData<TPage>, readonly unknown[], TCursor>({
queryKey: [...buildQueryKey(options.key, scope, request), "infinite"],
- queryFn: ({ pageParam }) =>
- fetchAnalytics<TPage>(site!, {
- ...request,
- params: { ...request.params, ...options.pageParams(pageParam as TCursor) },
- }),
+ // `signal` is read only when abortable: reading it is what opts a query into cancellation.
+ queryFn: context =>
+ fetchAnalytics<TPage>(
+ site!,
+ { ...request, params: { ...request.params, ...options.pageParams(context.pageParam as TCursor) } },
+ options.abortable ? context.signal : undefined
+ ),
initialPageParam: options.initialPageParam,
getNextPageParam: options.getNextPageParam,
staleTime: options.staleTime ?? 60_000,
diff --git a/client/src/app/[site]/components/Header/NoData.test.tsx b/client/src/app/[site]/components/Header/NoData.test.tsx
index 2aa9d59c2..e41b99346 100644
--- a/client/src/app/[site]/components/Header/NoData.test.tsx
+++ b/client/src/app/[site]/components/Header/NoData.test.tsx
@@ -4,8 +4,9 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MotionGlobalConfig } from "framer-motion";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { useGetLiveUserCount } from "@/api/analytics/hooks/useGetLiveUserCount";
-import { useGetSessionsInfinite } from "@/api/analytics/hooks/useGetUserSessions";
+import { LIVE_SESSIONS_POLL_MS, useGetLiveSessions } from "@/api/analytics/hooks/useGetUserSessions";
import { useStore } from "@/lib/store";
+import { useLiveSessionsForFirstVisitor } from "./firstPageview";
import { NoData } from "./NoData";
const mocks = vi.hoisted(() => ({
@@ -27,14 +28,14 @@ vi.mock("next-intl", () => ({
vi.mock("@/hooks/useIsWhiteLabel", () => ({ useWhiteLabel: () => ({ isWhiteLabel: false }) }));
vi.mock("@/components/CodeSnippet", () => ({ CodeSnippet: ({ code }: { code: string }) => <pre>{code}</pre> }));
-// What SubHeader's LiveUserCount mounts on every dashboard page.
+// What SubHeader's LiveUserCount mounts on every dashboard page, with its drawer closed.
function LiveUserCountProbe() {
useGetLiveUserCount(5);
- useGetSessionsInfinite({
- timeOverride: { mode: "past-minutes", pastMinutesStart: 5, pastMinutesEnd: 0 },
- limit: 25,
- refetchInterval: 10000,
- });
+ return useLiveSessionsForFirstVisitor("7") ? <KeepLiveSessionsProbe /> : null;
+}
+
+function KeepLiveSessionsProbe() {
+ useGetLiveSessions(LIVE_SESSIONS_POLL_MS);
return null;
}
@@ -215,6 +216,24 @@ describe("NoData", () => {
expect(await screen.findByText("from Germany · Firefox")).toBeTruthy();
});
+ it("still names the first visitor when switching tabs remounts LiveUserCount mid-arrival", async () => {
+ const { rerender } = show(<LiveUserCountProbe key="first-tab" />);
+ await waitingHeading();
+ await waitFor(() => expect(callsTo("/sites/7/sessions")).toBe(1));
+ mocks.sessions = [{ session_id: "s1", session_start: "2026-09-28 10:01:00", country: "DE", browser: "Firefox" }];
+
+ await firstPageviewLands();
+ // The page's LiveUserCount goes with the tab; NoData, in the layout, stays.
+ rerender(
+ <QueryClientProvider client={client}>
+ <NoData />
+ <LiveUserCountProbe key="next-tab" />
+ </QueryClientProvider>
+ );
+
+ expect(await screen.findByText("from Germany · Firefox", undefined, { timeout: 3000 })).toBeTruthy();
+ });
+
it("moves focus into the confirmation when it was inside the waiting card", async () => {
show();
await waitingHeading();
diff --git a/client/src/app/[site]/components/Header/NoData.tsx b/client/src/app/[site]/components/Header/NoData.tsx
index f4ea6e7ed..7096f3907 100644
--- a/client/src/app/[site]/components/Header/NoData.tsx
+++ b/client/src/app/[site]/components/Header/NoData.tsx
@@ -46,7 +46,13 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components
import { FADE_IN, FADE_OUT, INSTANT, SPRING_DISCLOSE } from "../../../../lib/motion";
import { useStore } from "../../../../lib/store";
import { FirstPageviewCard } from "./FirstPageviewCard";
-import { useArrivalRefresh, useFirstPageviewJourney, useFirstSession, useLiveVisitorNudge } from "./firstPageview";
+import {
+ useArrivalRefresh,
+ useFirstPageviewJourney,
+ useFirstSession,
+ useHoldLiveSessions,
+ useLiveVisitorNudge,
+} from "./firstPageview";
const ICON = "h-3.5 w-3.5";
@@ -157,6 +163,7 @@ export function NoData() {
const arrived = filling || phase === "ready";
useLiveVisitorNudge(site, waiting);
+ useHoldLiveSessions(site, waiting || arrived);
useArrivalRefresh(site, filling, settle);
const firstSession = useFirstSession(site, arrived);
diff --git a/client/src/app/[site]/components/Header/firstPageview.ts b/client/src/app/[site]/components/Header/firstPageview.ts
index d4006d9a8..3792ca798 100644
--- a/client/src/app/[site]/components/Header/firstPageview.ts
+++ b/client/src/app/[site]/components/Header/firstPageview.ts
@@ -14,6 +14,7 @@ type Session = GetSessionsResponse[number];
// useSiteHasData's key.
const SITE_HAS_DATA_KEY = "site-has-data";
// Both polled every 10 s by SubHeader's LiveUserCount (useGetLiveUserCount, useGetSessionsInfinite).
+// The sessions list only while its drawer is open, or while NoData holds it live (useHoldLiveSessions).
const LIVE_USER_COUNT_KEY = "live-user-count";
const LIVE_SESSIONS_KEY = "sessions-infinite";
// The dashboard refetch waits for the morph (install card fade-out, then the height spring) to mostly
@@ -148,6 +149,49 @@ export function useFirstSession(site: string, enabled: boolean): Session | undef
return useSyncExternalStore(subscribe, getSnapshot, () => undefined);
}
+// Sites whose install card is up: waiting for the first pageview, or celebrating it until dismissed.
+// LiveUserCount keeps its sessions list live for them, since useFirstSession names the first visitor from
+// that list's cache, and an observed list is never garbage-collected from under the card. Kept here, not in
+// LiveUserCount: switching dashboard tabs remounts LiveUserCount mid-journey, while NoData (layout) stays.
+const liveSessionHolds = new Map<string, number>();
+const liveSessionListeners = new Set<() => void>();
+
+const notifyLiveSessionHolds = () => liveSessionListeners.forEach(listener => listener());
+
+/** Keeps `site`'s live sessions list polling until the returned release runs. */
+export function holdLiveSessions(site: string): () => void {
+ liveSessionHolds.set(site, (liveSessionHolds.get(site) ?? 0) + 1);
+ notifyLiveSessionHolds();
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const count = (liveSessionHolds.get(site) ?? 1) - 1;
+ if (count > 0) liveSessionHolds.set(site, count);
+ else liveSessionHolds.delete(site);
+ notifyLiveSessionHolds();
+ };
+}
+
+/** Holds `site`'s live sessions list while `active` (NoData: while its install card is on screen). */
+export function useHoldLiveSessions(site: string, active: boolean) {
+ useEffect(() => (active && site ? holdLiveSessions(site) : undefined), [active, site]);
+}
+
+const subscribeLiveSessionHolds = (listener: () => void) => {
+ liveSessionListeners.add(listener);
+ return () => void liveSessionListeners.delete(listener);
+};
+
+/** Whether LiveUserCount keeps its sessions list polling with the drawer closed. */
+export function useLiveSessionsForFirstVisitor(site: string): boolean {
+ return useSyncExternalStore(
+ subscribeLiveSessionHolds,
+ () => !!site && liveSessionHolds.has(site),
+ () => false
+ );
+}
+
/**
* Shortly after arrival, refetch this site's analytics queries that are on screen and mark the rest
* stale, so the dashboard fills in now rather than after their 60 s staleTime. Calls `onSettled` once
diff --git a/client/src/app/[site]/components/SubHeader/LiveUserCount.test.tsx b/client/src/app/[site]/components/SubHeader/LiveUserCount.test.tsx
new file mode 100644
index 000000000..8e510edcc
--- /dev/null
+++ b/client/src/app/[site]/components/SubHeader/LiveUserCount.test.tsx
@@ -0,0 +1,244 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { onlineManager, QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { useStore } from "@/lib/store";
+
+import { holdLiveSessions } from "../Header/firstPageview";
+import { LiveUserCount } from "./LiveUserCount";
+
+type Session = { session_id: string };
+
+const mocks = vi.hoisted(() => ({
+ fetch: vi.fn(),
+ intersecting: false,
+ // Rows per page number; a page with fewer than 25 rows is the last.
+ pages: {} as Record<number, Session[]>,
+ // When set, the next page-1 request waits for this promise.
+ holdFirstPage: null as Promise<void> | null,
+}));
+
+vi.mock("@/api/utils", async importOriginal => ({
+ ...(await importOriginal<typeof import("@/api/utils")>()),
+ authedFetch: mocks.fetch,
+}));
+vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));
+vi.mock("@uidotdev/usehooks", () => ({
+ useIntersectionObserver: () => [() => {}, mocks.intersecting ? { isIntersecting: true } : null],
+}));
+vi.mock("../../../../components/Sessions/SessionCard", () => ({
+ SessionCard: ({ session }: { session: Session }) => <p>{session.session_id}</p>,
+ SessionCardSkeleton: () => <p>loading sessions</p>,
+}));
+
+let client: QueryClient;
+
+const sessionCalls = (page?: number) =>
+ mocks.fetch.mock.calls.filter(([path, params]) => path === "/sites/7/sessions" && (!page || params.page === page))
+ .length;
+const liveCountCalls = () => mocks.fetch.mock.calls.filter(([path]) => path === "/sites/7/live-user-count").length;
+const tick = (ms: number) => act(() => vi.advanceTimersByTimeAsync(ms));
+const trigger = () => screen.getAllByRole("button", { hidden: true })[0];
+const rows = (prefix: string, count: number) =>
+ Array.from({ length: count }, (_, index) => ({ session_id: `${prefix}${index + 1}` }));
+
+// jsdom never ends vaul's exit animation, so the content would stay mounted after closing. It has no
+// AnimationEvent either, hence the hand-built event carrying the animation's name.
+async function closeDrawer() {
+ const dialog = screen.getByRole("dialog");
+ fireEvent.keyDown(dialog, { key: "Escape" });
+ await waitFor(() => expect(trigger().getAttribute("aria-expanded")).toBe("false"));
+ const animationEnd = Object.assign(new Event("animationend", { bubbles: true }), {
+ animationName: getComputedStyle(dialog).animationName,
+ });
+ act(() => void dialog.dispatchEvent(animationEnd));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+}
+
+let releases: (() => void)[] = [];
+
+// `held`: NoData's install card is up for the site, so the list stays live with the drawer closed.
+function show({ held = false }: { held?: boolean } = {}) {
+ if (held) releases.push(holdLiveSessions("7"));
+ return render(
+ <QueryClientProvider client={client}>
+ <TooltipProvider>
+ <LiveUserCount />
+ </TooltipProvider>
+ </QueryClientProvider>
+ );
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ // vaul reads matchMedia and the scroll area a ResizeObserver; jsdom has neither.
+ vi.stubGlobal(
+ "matchMedia",
+ (query: string) =>
+ ({
+ matches: false,
+ media: query,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ }) as unknown as MediaQueryList
+ );
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ mocks.fetch.mockReset();
+ mocks.intersecting = false;
+ mocks.pages = { 1: [{ session_id: "s1" }] };
+ mocks.holdFirstPage = null;
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ useStore.setState({ site: "7", timezone: "UTC", filters: [] });
+ mocks.fetch.mockImplementation(async (path: string, params: { page?: number }) => {
+ if (path === "/sites/7/live-user-count") return { data: { count: 1 } };
+ if (path === "/sites/7/sessions") {
+ if (params.page === 1 && mocks.holdFirstPage) await mocks.holdFirstPage;
+ return { data: mocks.pages[params.page ?? 1] ?? [] };
+ }
+ return { data: [] };
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ releases.forEach(release => release());
+ releases = [];
+ onlineManager.setOnline(true);
+ client.clear();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("LiveUserCount", () => {
+ it("polls the count but not the sessions list while the drawer is closed", async () => {
+ show();
+ await waitFor(() => expect(liveCountCalls()).toBe(1));
+
+ await tick(30_000);
+
+ expect(liveCountCalls()).toBeGreaterThan(1);
+ expect(sessionCalls()).toBe(0);
+ });
+
+ it("polls the list only while open, and refetches it on reopening", async () => {
+ show();
+ fireEvent.click(trigger());
+ expect(await screen.findByText("s1")).toBeTruthy();
+ expect(sessionCalls()).toBe(1);
+
+ await tick(10_000);
+ await waitFor(() => expect(sessionCalls()).toBe(2));
+
+ await closeDrawer();
+ await tick(30_000);
+ expect(sessionCalls()).toBe(2);
+
+ // Reopening shows the skeleton, not the list from the last opening, until the refetch lands.
+ mocks.pages = { 1: [{ session_id: "s2" }] };
+ fireEvent.click(trigger());
+ expect(await screen.findByText("loading sessions")).toBeTruthy();
+ expect(screen.queryByText("s1")).toBeNull();
+ expect(await screen.findByText("s2")).toBeTruthy();
+ expect(sessionCalls()).toBe(3);
+ });
+
+ it("stops a refetch from walking the remaining pages when the drawer closes", async () => {
+ mocks.pages = { 1: rows("a", 25), 2: rows("b", 3) };
+ mocks.intersecting = true;
+ show();
+ fireEvent.click(trigger());
+ expect(await screen.findByText("b3")).toBeTruthy();
+ expect(sessionCalls(2)).toBe(1);
+ mocks.intersecting = false;
+
+ // The next poll refetches page 1, then would go on to page 2.
+ let releaseFirstPage = () => {};
+ mocks.holdFirstPage = new Promise(resolve => (releaseFirstPage = resolve));
+ await tick(10_000);
+ await waitFor(() => expect(sessionCalls(1)).toBe(2));
+
+ await closeDrawer();
+ const pollConfig = mocks.fetch.mock.calls.filter(([path]) => path === "/sites/7/sessions").at(-1)![2];
+ expect(pollConfig.signal.aborted).toBe(true);
+ releaseFirstPage();
+ await tick(1_000);
+
+ expect(sessionCalls(2)).toBe(1);
+ });
+
+ it("keeps the list live with the drawer closed while the install card holds it", async () => {
+ show({ held: true });
+ await waitFor(() => expect(sessionCalls()).toBe(1));
+
+ await tick(10_000);
+
+ await waitFor(() => expect(sessionCalls()).toBe(2));
+ });
+
+ it("still refetches on reopening a list it keeps live, once per opening", async () => {
+ show({ held: true });
+ await waitFor(() => expect(sessionCalls()).toBe(1));
+
+ fireEvent.click(trigger());
+ expect(await screen.findByText("s1")).toBeTruthy();
+ expect(sessionCalls()).toBe(2);
+
+ // Handing back to the closed-drawer poll doesn't refetch the rows the drawer just fetched.
+ await closeDrawer();
+ expect(sessionCalls()).toBe(2);
+
+ // Reopened between polls: one fresh request, and the skeleton until it lands.
+ mocks.pages = { 1: [{ session_id: "s2" }] };
+ fireEvent.click(trigger());
+ expect(await screen.findByText("loading sessions")).toBeTruthy();
+ expect(await screen.findByText("s2")).toBeTruthy();
+ expect(sessionCalls()).toBe(3);
+ });
+
+ it("shows an error, not the rows from the last opening, when the reopening refetch fails", async () => {
+ show();
+ fireEvent.click(trigger());
+ expect(await screen.findByText("s1")).toBeTruthy();
+ await closeDrawer();
+
+ mocks.fetch.mockImplementation(async (path: string) => {
+ if (path === "/sites/7/sessions") throw new Error("boom");
+ return { data: { count: 1 } };
+ });
+ fireEvent.click(trigger());
+ expect(await screen.findByText("Failed to load data")).toBeTruthy();
+ expect(screen.queryByText("s1")).toBeNull();
+
+ mocks.fetch.mockImplementation(async (path: string) =>
+ path === "/sites/7/sessions" ? { data: [{ session_id: "s2" }] } : { data: { count: 1 } }
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Try Again/ }));
+ expect(await screen.findByText("s2")).toBeTruthy();
+ });
+
+ it("keeps the skeleton, not the old rows, while the reopening refetch is paused offline", async () => {
+ show();
+ fireEvent.click(trigger());
+ expect(await screen.findByText("s1")).toBeTruthy();
+ await closeDrawer();
+
+ act(() => onlineManager.setOnline(false));
+ mocks.pages = { 1: [{ session_id: "s2" }] };
+ fireEvent.click(trigger());
+ expect(await screen.findByText("loading sessions")).toBeTruthy();
+ await tick(15_000);
+ expect(screen.queryByText("s1")).toBeNull();
+ expect(screen.getByText("loading sessions")).toBeTruthy();
+
+ act(() => onlineManager.setOnline(true));
+ expect(await screen.findByText("s2")).toBeTruthy();
+ });
+});
diff --git a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
index f7eced6d5..62dafd283 100644
--- a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
+++ b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
@@ -1,11 +1,12 @@
import { useIntersectionObserver } from "@uidotdev/usehooks";
import { Rewind } from "lucide-react";
import { useExtracted } from "next-intl";
-import { useEffect, useMemo } from "react";
+import { useEffect, useMemo, useState } from "react";
import { FlashNumber } from "@/components/interior/value-flash";
import { useStore } from "@/lib/store";
import { useGetLiveUserCount } from "../../../../api/analytics/hooks/useGetLiveUserCount";
-import { useGetSessionsInfinite } from "../../../../api/analytics/hooks/useGetUserSessions";
+import { LIVE_SESSIONS_POLL_MS, useGetLiveSessions } from "../../../../api/analytics/hooks/useGetUserSessions";
+import { ErrorState } from "../../../../components/ErrorState";
import { NothingFound } from "../../../../components/NothingFound";
import { SessionCard, SessionCardSkeleton } from "../../../../components/Sessions/SessionCard";
import { Button } from "../../../../components/ui/button";
@@ -13,49 +14,24 @@ import { Drawer, DrawerContent, DrawerHeader, DrawerTitle, DrawerTrigger } from
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
import { ScrollArea } from "../../../../components/ui/scroll-area";
+import { useLiveSessionsForFirstVisitor } from "../Header/firstPageview";
export function LiveUserCount() {
const t = useExtracted();
const site = useStore(state => state.site);
const { data, isFetching } = useGetLiveUserCount(5);
+ const [open, setOpen] = useState(false);
+ const [openedAt, setOpenedAt] = useState(0);
+ const keepLive = useLiveSessionsForFirstVisitor(site);
- const {
- data: sessionsData,
- isLoading,
- fetchNextPage,
- hasNextPage,
- isFetchingNextPage,
- } = useGetSessionsInfinite({
- timeOverride: {
- mode: "past-minutes",
- pastMinutesStart: 5,
- pastMinutesEnd: 0,
- },
- limit: 25,
- refetchInterval: 10000,
- });
-
- // Use the intersection observer hook
- const [ref, entry] = useIntersectionObserver({
- threshold: 0,
- root: null,
- rootMargin: "0px 0px 200px 0px",
- });
-
- const sessions = useMemo(() => {
- if (!sessionsData) return [];
- return sessionsData.pages.flatMap(page => page || []);
- }, [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]);
+ const handleOpenChange = (next: boolean) => {
+ setOpen(next);
+ if (next) setOpenedAt(Date.now());
+ };
return (
- <Drawer>
+ <Drawer open={open} onOpenChange={handleOpenChange}>
+ {keepLive && !open && <KeepLiveSessionsPolling />}
<Tooltip>
<TooltipTrigger asChild>
<DrawerTrigger asChild>
@@ -88,33 +64,92 @@ export function LiveUserCount() {
<DrawerTitle>{t("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 overflow-x-hidden">
- {isLoading ? (
- <SessionCardSkeleton count={5} />
- ) : sessions.length === 0 ? (
- <NothingFound
- icon={<Rewind className="w-10 h-10" />}
- title={t("No sessions found")}
- description={t("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>
+ {/* Keyed by opening: every opening mounts a fresh list, even one mid exit animation. */}
+ <LiveSessionsList key={openedAt} openedAt={openedAt} />
</DrawerContent>
</Drawer>
);
}
+
+/**
+ * Keeps the list polling with the drawer closed, for a site useLiveSessionsForFirstVisitor holds live.
+ * Not stale until the next poll is due, so taking over from a closing drawer doesn't refetch.
+ */
+function KeepLiveSessionsPolling() {
+ useGetLiveSessions(LIVE_SESSIONS_POLL_MS);
+ return null;
+}
+
+/**
+ * Mounted only while the drawer is open, so the list polls (and pages) only while someone can see it.
+ * Stale on every mount, so opening refetches. The drawer unmounts it once its exit animation ends, and
+ * that cancels a refetch still walking the loaded pages.
+ */
+function LiveSessionsList({ openedAt }: { openedAt: number }) {
+ const t = useExtracted();
+ const {
+ data,
+ dataUpdatedAt,
+ fetchStatus,
+ isError,
+ isLoading,
+ refetch,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ } = useGetLiveSessions(0);
+
+ // Use the intersection observer hook
+ const [ref, entry] = useIntersectionObserver({
+ threshold: 0,
+ root: null,
+ rootMargin: "0px 0px 200px 0px",
+ });
+
+ const sessions = useMemo(() => {
+ if (!data) return [];
+ return data.pages.flatMap(page => page || []);
+ }, [data]);
+
+ // 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]);
+
+ // Cached rows are from before this opening until one of its fetches succeeds: show the skeleton while
+ // that is in flight (or paused offline), and an error if it failed, never the old rows.
+ const refreshed = dataUpdatedAt >= openedAt;
+
+ return (
+ <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 overflow-x-hidden">
+ {!refreshed && isError && fetchStatus === "idle" ? (
+ <ErrorState title="" message="" refetch={() => void refetch()} />
+ ) : !refreshed ? (
+ <SessionCardSkeleton count={5} />
+ ) : sessions.length === 0 ? (
+ <NothingFound
+ icon={<Rewind className="w-10 h-10" />}
+ title={t("No sessions found")}
+ description={t("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>
+ );
+}