Something went wrong. Try again.
Effortlessly glide through your todos
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import { useSyncExternalStore } from 'react';
import { storage } from '../storage';
/** * The account the local data belongs to. * * The active account for newly-created local rows. * * `null` means signed-out local mode. Existing dogfood rows are treated as adoptable * legacy rows so the first Clerk sign-in can claim them into the authenticated account. */export const DOGFOOD_OWNER = 'dogfood';
const OWNER_BINDINGS_KEY = 'glide.sync.owner-bindings.v1';const MAX_OWNER_BINDINGS = 16;
let activeOwnerId: string | null = null;const listeners = new Set<() => void>();
export function currentOwnerId(): string | null { return activeOwnerId;}
function readOwnerBindings(): Record<string, string> { try { const parsed: unknown = JSON.parse(storage.getString(OWNER_BINDINGS_KEY) ?? '{}'); if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return {}; return Object.fromEntries( Object.entries(parsed) .filter( (entry): entry is [string, string] => entry[0].length > 0 && entry[0].length <= 256 && typeof entry[1] === 'string' && entry[1].length > 0, ) .slice(-MAX_OWNER_BINDINGS), ); } catch { return {}; }}
export function rememberCurrentOwner(userId: string, ownerId: string): void { if (!userId || !ownerId) return; const bindings = readOwnerBindings(); delete bindings[userId]; const entries = [...Object.entries(bindings), [userId, ownerId] as const].slice(-MAX_OWNER_BINDINGS); storage.set(OWNER_BINDINGS_KEY, JSON.stringify(Object.fromEntries(entries))); setCurrentOwnerId(ownerId);}
export function restoreCurrentOwner(userId: string | null | undefined): void { setCurrentOwnerId(userId ? (readOwnerBindings()[userId] ?? null) : null);}
export function forgetCurrentOwner(userId: string): void { const bindings = readOwnerBindings(); if (!(userId in bindings)) return; delete bindings[userId]; storage.set(OWNER_BINDINGS_KEY, JSON.stringify(bindings));}
export function setCurrentOwnerId(ownerId: string | null): void { if (activeOwnerId === ownerId) return; activeOwnerId = ownerId; listeners.forEach((listener) => listener());}
function subscribe(listener: () => void): () => void { listeners.add(listener); return () => listeners.delete(listener);}
export function useCurrentOwnerId(): string | null { return useSyncExternalStore(subscribe, currentOwnerId, currentOwnerId);}
export function isAdoptableOwner(ownerId: string | null): boolean { return ownerId === null || ownerId === DOGFOOD_OWNER;}
export function isVisibleForOwner(taskOwnerId: string | null, ownerId: string | null): boolean { return isAdoptableOwner(taskOwnerId) || (ownerId !== null && taskOwnerId === ownerId);}