nomadro/apps/com/admin/src/lib/useSocialPresenceLive.ts
Eric 499f2d3e26 Ship coffeechat scheduling, notify PB access, and social/admin UI polish for .com.
Document the 2026-11-05 UI/UX upgrade and keep roster/live gates aligned with face-check and presence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 18:19:37 +08:00

98 lines
2.4 KiB
TypeScript

/**
* Poll social who's-online for admin chrome.
* Emits toast when someone newly appears.
*/
import { useEffect, useRef, useState } from 'react'
import { api } from '../api/client'
export type PresencePeer = {
guestId: string
nick: string
city?: string
avatar?: string
}
export type PresenceSnap = {
online: number
peers: PresencePeer[]
cityOnline: number
ok: boolean
fromOffline: boolean
bumped?: PresencePeer | null
}
const EMPTY: PresenceSnap = {
online: 0,
peers: [],
cityOnline: 0,
ok: false,
fromOffline: true,
bumped: null,
}
const POLL_MS = 4000
export function useSocialPresenceLive(): PresenceSnap {
const [snap, setSnap] = useState<PresenceSnap>(EMPTY)
const seen = useRef<Set<string>>(new Set())
const booted = useRef(false)
useEffect(() => {
let cancelled = false
let timer: ReturnType<typeof setInterval> | null = null
const pull = async () => {
if (cancelled || document.hidden) return
try {
const data = await api<{
ok?: boolean
online?: number
peers?: PresencePeer[]
cityOnline?: number
}>('/api/admin/social/ugc/presence?limit=48')
if (cancelled) return
const peers = Array.isArray(data.peers) ? data.peers : []
const online = Number(data.online) || peers.length
let bumped: PresencePeer | null = null
if (booted.current) {
for (const p of peers) {
const id = String(p.guestId || '')
if (id && !seen.current.has(id)) {
bumped = p
break
}
}
}
const nextIds = new Set(peers.map((p) => String(p.guestId || '')).filter(Boolean))
seen.current = nextIds
booted.current = true
setSnap({
online,
peers,
cityOnline: Number(data.cityOnline) || 0,
ok: data.ok !== false,
fromOffline: false,
bumped,
})
} catch {
if (cancelled) return
setSnap((prev) => ({ ...prev, fromOffline: true, bumped: null }))
}
}
void pull()
timer = setInterval(() => void pull(), POLL_MS)
const onVis = () => {
if (!document.hidden) void pull()
}
document.addEventListener('visibilitychange', onVis)
return () => {
cancelled = true
if (timer) clearInterval(timer)
document.removeEventListener('visibilitychange', onVis)
}
}, [])
return snap
}