/opt/canhelp/apps/web/src/hooks
Edit: /opt/canhelp/apps/web/src/hooks/useEffectiveRole.ts (1313B)
'use client'
import { useSession } from '@/lib/auth'
import { useEffect, useState } from 'react'
function readPreviewRole(): string | null {
if (typeof document === 'undefined') return null
const m = document.cookie.match(/(?:^|;\s*)canhelp_preview_role=([^;]+)/)
return m?.[1] ?? null
}
/**
* Returns the effective role for the current user.
* For admins, respects the `canhelp_preview_role` cookie set by AdminRolePreview widget.
* Updates reactively when the widget dispatches `canhelp:preview-role`.
*/
export function useEffectiveRole(): string | null {
const { data: session } = useSession()
const userRole = (session?.user as any)?.role as string | undefined
const isAdmin = userRole === 'admin'
const [previewRole, setPreviewRole] = useState
(null)
useEffect(() => {
if (!isAdmin) return
setPreviewRole(readPreviewRole())
const sync = () => setPreviewRole(readPreviewRole())
window.addEventListener('canhelp:preview-role', sync)
document.addEventListener('visibilitychange', sync)
return () => {
window.removeEventListener('canhelp:preview-role', sync)
document.removeEventListener('visibilitychange', sync)
}
}, [isAdmin])
if (!userRole) return null
if (isAdmin && previewRole) return previewRole
return userRole
}