Files
gunshiz b5e6588958
CI / Verify (push) Successful in 1m28s
CI / Build immutable images and deploy (push) Successful in 2m2s
fix : reaible vistor count
2026-09-22 21:34:18 +07:00

119 lines
3.3 KiB
TypeScript

"use client";
import { useEffect, useEffectEvent, useRef, useState } from "react";
import { PRESENCE_HEARTBEAT_MS } from "@/lib/presence-constants";
type VisitorCounts = {
global: number;
guide: number | null;
byGuide: Record<string, number>;
};
export type EditorsByGuide = Record<
string,
Array<{ userId: string; name: string; sections: string[] }>
>;
const visitorIdStorageKey = "buzz-sheet:visitor-id";
let currentTabId: string | undefined;
let fallbackVisitorId: string | undefined;
function tabId(): string {
currentTabId ??= crypto.randomUUID();
return currentTabId;
}
function visitorId(): string {
try {
const existing = window.localStorage.getItem(visitorIdStorageKey);
if (existing) return existing;
const created = crypto.randomUUID();
window.localStorage.setItem(visitorIdStorageKey, created);
return created;
} catch {
fallbackVisitorId ??= crypto.randomUUID();
return fallbackVisitorId;
}
}
function useHeartbeat<T>({
endpoint,
guideId,
section,
identifyBy,
}: {
endpoint: string;
guideId: string | null;
section?: string | null;
identifyBy: "browser" | "tab";
}) {
const [value, setValue] = useState<T | null>(null);
const pending = useRef(false);
const send = useEffectEvent(async (active = true) => {
if (active && (document.visibilityState !== "visible" || pending.current)) return;
pending.current = true;
try {
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
tabId: tabId(),
...(identifyBy === "browser" ? { browserId: visitorId() } : {}),
guideId,
...(section !== undefined ? { section } : {}),
active,
}),
cache: "no-store",
keepalive: !active,
});
if (!response.ok) throw new Error("presence unavailable");
if (active) setValue(await response.json() as T);
} catch {
if (active) setValue(null);
} finally {
pending.current = false;
}
});
useEffect(() => {
const immediate = window.setTimeout(() => void send(), 0);
const interval = window.setInterval(() => void send(), PRESENCE_HEARTBEAT_MS);
const refresh = () => {
if (document.visibilityState === "visible") void send();
};
const leave = () => {
void send(false);
};
window.addEventListener("focus", refresh);
window.addEventListener("pagehide", leave);
document.addEventListener("visibilitychange", refresh);
return () => {
window.clearInterval(interval);
window.clearTimeout(immediate);
window.removeEventListener("focus", refresh);
window.removeEventListener("pagehide", leave);
document.removeEventListener("visibilitychange", refresh);
};
}, [endpoint, guideId, identifyBy, section]);
return value;
}
export function useVisitorPresence(guideId: string | null) {
return useHeartbeat<VisitorCounts>({
endpoint: "/api/presence/visitors",
guideId,
identifyBy: "browser",
});
}
export function useAdminPresence(guideId: string | null, section: string | null = null) {
return useHeartbeat<{ editorsByGuide: EditorsByGuide }>({
endpoint: "/api/presence/admin",
guideId,
section,
identifyBy: "tab",
});
}