Something went wrong. Try again.
A local-first note taking app
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import { createContext, useContext, useMemo, useSyncExternalStore, type ReactNode,} from 'react';
import { habitatAuth } from './habitatAuth';
export type UserIdentity = { name: string; color?: string;};
const UserIdentityContext = createContext<UserIdentity | undefined>(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 ( <UserIdentityContext.Provider value={identity}> {children} </UserIdentityContext.Provider> );}
/** Collaborative editor display name; undefined when signed out. */export function useUserIdentity(): UserIdentity | undefined { return useContext(UserIdentityContext);}