import { createContext, useContext, useMemo, useSyncExternalStore, type ReactNode, } from 'react'; import { habitatAuth } from './habitatAuth'; export type UserIdentity = { name: string; color?: string; }; const UserIdentityContext = createContext(undefined); function subscribeAuth(listener: () => void) { return habitatAuth.subscribe(listener); } function getAuthHandleSnapshot(): string | null { return habitatAuth.getAuthInfo()?.handle ?? null; } export function UserIdentityProvider({ children }: { children: ReactNode }) { // Snapshot must be stable (primitive) — a new object each call makes // useSyncExternalStore think the store changed every render. const handle = useSyncExternalStore( subscribeAuth, getAuthHandleSnapshot, () => null, ); const identity = useMemo( (): UserIdentity | undefined => (handle ? { name: handle } : undefined), [handle], ); return ( {children} ); } /** Collaborative editor display name; undefined when signed out. */ export function useUserIdentity(): UserIdentity | undefined { return useContext(UserIdentityContext); }