f0a1552
ZhenYi
feat(chat): add chat module with room management, message handling, and session revocation
f0a1552
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import type { ReactNode } from 'react'
import { adminAuth } from '@/shared/api'
import type { AdminDto } from '@/shared/api'
interface SessionValue {
me: AdminDto | null
loading: boolean
refresh: () => Promise<void>
logout: () => Promise<void>
}
const SessionContext = createContext<SessionValue>({
me: null,
loading: true,
refresh: async () => {},
logout: async () => {},
})
export function SessionProvider({ children }: { children: ReactNode }) {
const [me, setMe] = useState<AdminDto | null>(null)
const [loading, setLoading] = useState(true)
const refresh = useCallback(async () => {
try {
const value = await adminAuth.me()
setMe(value)
} catch {
setMe(null)
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
void refresh()
}, [refresh])
const logout = useCallback(async () => {
try {
await adminAuth.logout()
} catch {
}
setMe(null)
}, [])
const value = useMemo(() => ({ me, loading, refresh, logout }), [me, loading, refresh, logout])
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>
}
export function useSession() {
return useContext(SessionContext)
}