Files
IdP/apps/frontend/lib/selected-family-storage.ts
2026-07-01 23:27:48 +03:00

44 lines
1.1 KiB
TypeScript

export const SELECTED_FAMILY_STORAGE_KEY = 'id-selected-family-group-id';
export function readStoredFamilyGroupId(): string | null {
if (typeof window === 'undefined') {
return null;
}
const stored = window.localStorage.getItem(SELECTED_FAMILY_STORAGE_KEY);
return stored?.trim() ? stored : null;
}
export function writeStoredFamilyGroupId(groupId: string | null) {
if (typeof window === 'undefined') {
return;
}
if (groupId) {
window.localStorage.setItem(SELECTED_FAMILY_STORAGE_KEY, groupId);
} else {
window.localStorage.removeItem(SELECTED_FAMILY_STORAGE_KEY);
}
}
export function resolveFamilyGroupId(
groups: Array<{ id: string }>,
selectedGroupId: string | null,
isSelectionHydrated: boolean
): string | null {
if (!groups.length) {
return null;
}
const candidates: Array<string | null> = [selectedGroupId];
if (!isSelectionHydrated) {
candidates.unshift(readStoredFamilyGroupId());
}
for (const candidate of candidates) {
if (candidate && groups.some((group) => group.id === candidate)) {
return candidate;
}
}
return isSelectionHydrated ? groups[0]!.id : null;
}