All files / src/hooks useActiveRole.ts

100% Statements 16/16
100% Branches 6/6
100% Functions 3/3
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40                    1x     9x   9x 7x 6x 6x 6x       5x     9x   9x 2x 2x 2x           9x    
/**
 * useActiveRole hook
 * For multi-role users: tracks which role's portal is currently active.
 * Persists selection to localStorage so it survives page refreshes.
 * Single-role users always get their one role returned; no localStorage interaction.
 */
 
import { useState } from 'react';
import type { UserRole } from '@/types/auth';
 
const STORAGE_KEY = 'batbern:active-role';
 
export function useActiveRole(userRoles: UserRole[]): [UserRole, (role: UserRole) => void] {
  const primaryRole = userRoles[0];
 
  const resolveInitial = (): UserRole => {
    if (userRoles.length <= 1) return primaryRole;
    try {
      const stored = localStorage.getItem(STORAGE_KEY) as UserRole | null;
      if (stored && userRoles.includes(stored)) return stored;
    } catch {
      // localStorage unavailable (e.g. private browsing)
    }
    return primaryRole;
  };
 
  const [activeRole, setActiveRoleState] = useState<UserRole>(resolveInitial);
 
  const setActiveRole = (role: UserRole) => {
    setActiveRoleState(role);
    try {
      localStorage.setItem(STORAGE_KEY, role);
    } catch {
      // ignore
    }
  };
 
  return [activeRole, setActiveRole];
}