All files / blong-browser/src/state appStore.ts

76.23% Statements 170/223
88.88% Branches 16/18
22.72% Functions 5/22
76.23% Lines 170/223

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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 2241x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 2x 2x 1x         1x 2x 2x 2x 2x 2x 1x   2x 2x         2x 2x 2x 1x               1x     1x         1x 2x 2x 2x 2x 2x 2x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x                     1x 1x         1x 1x 1x               1x 1x     1x   1x   1x 1x 1x 1x 1x   1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Global application Zustand store.
 * Manages auth state, portal tabs, toasts, and loader.
 */
import type {ReactNode} from 'react';
import {create} from 'zustand';
import type {ActionRegistry, IBlongError} from '../types/action.js';
import type {IAuthState, IUserProfile, PermissionMap} from '../types/permission.js';
import type {IPortalConfig, IPortalState, ITab} from '../types/portal.js';
 
/** Toast notification */
export interface IToast {
    id: string;
    severity: 'success' | 'info' | 'warn' | 'error';
    summary?: string;
    detail?: ReactNode;
    life?: number;
}
 
/** Translation dictionary */
export type TranslationDict = Record<string, string>;

/** Inline hint shown near a button (success or error feedback) */
export interface IHint {
    target: HTMLElement | null;
    message: string;
    error: boolean;
}

/** Complete app state */
export interface IAppState {
    auth: IAuthState;
    portal: IPortalState;
    toasts: IToast[];
    loader: {active: boolean; message?: string; count: number};
    translations: TranslationDict;
    language: string;
    actions: ActionRegistry;
    error: IBlongError | null;
    hint: IHint | null;
}

/** App store actions */
export interface IAppActions {
    // Auth
    setToken: (token: string | null) => void;
    setProfile: (profile: IUserProfile | null) => void;
    setPermissions: (permissions: PermissionMap) => void;
    logout: () => void;

    // Portal
    openTab: (tab: ITab) => void;
    closeTab: (id: string) => void;
    setActiveTab: (id: string | null) => void;
    setTabDirty: (id: string, dirty: boolean) => void;
    setTabTitle: (id: string, title: string) => void;
    updateTabComponent: (
        id: string,
        component: React.ComponentType<Record<string, unknown>>,
    ) => void;
    setPortalConfig: (config: IPortalConfig | null) => void;

    // Toasts
    showToast: (toast: Omit<IToast, 'id'>) => void;
    clearToast: (id: string) => void;
    clearAllToasts: () => void;
 
    // Loader
    setLoading: (active: boolean, message?: string) => void;
 
    // Translations
    setTranslations: (dict: TranslationDict) => void;
    setLanguage: (language: string) => void;

    // Actions registry
    registerActions: (actions: ActionRegistry) => void;
 
    // Error
    showError: (error: IBlongError) => void;
    clearError: () => void;
 
    // Hint
    showHint: (target: HTMLElement | null, message: string, error: boolean) => void;
    clearHint: () => void;
}

const initialAuth: IAuthState = {
    token: null,
    profile: null,
    permissions: {},
    isAuthenticated: false,
};

const initialPortal: IPortalState = {
    tabs: [],
    activeTabId: null,
    portalConfig: null,
};

let toastIdCounter = 0;
 
export const useAppStore = create<IAppState & IAppActions>((set, get) => ({
    auth: initialAuth,
    portal: initialPortal,
    toasts: [],
    loader: {active: false, count: 0},
    translations: {},
    language: 'en',
    actions: {},
    error: null,
    hint: null,

    // Auth actions
    setToken: token =>
        set(state => ({
            auth: {...state.auth, token, isAuthenticated: token != null},
        })),
    setProfile: profile =>
        set(state => ({
            auth: {...state.auth, profile},
        })),
    setPermissions: permissions =>
        set(state => ({
            auth: {...state.auth, permissions},
        })),
    logout: () =>
        set({
            auth: initialAuth,
            portal: initialPortal,
            toasts: [],
        }),
 
    // Portal actions
    openTab: tab =>
        set(state => {
            // Navigate to existing tab with same action+params instead of duplicating
            const existing = state.portal.tabs.find(
                t =>
                    t.actionName === tab.actionName &&
                    JSON.stringify(t.params) === JSON.stringify(tab.params),
            );
            if (existing) {
                return {portal: {...state.portal, activeTabId: existing.id}};
            }
            return {
                portal: {
                    ...state.portal,
                    tabs: [...state.portal.tabs, tab],
                    activeTabId: tab.id,
                },
            };
        }),
    closeTab: id =>
        set(state => {
            const tabs = state.portal.tabs.filter(t => t.id !== id);
            const activeTabId =
                state.portal.activeTabId === id
                    ? (tabs[tabs.length - 1]?.id ?? null)
                    : state.portal.activeTabId;
            return {portal: {...state.portal, tabs, activeTabId}};
        }),
    setActiveTab: id => set(state => ({portal: {...state.portal, activeTabId: id}})),
    setTabDirty: (id, dirty) =>
        set(state => ({
            portal: {
                ...state.portal,
                tabs: state.portal.tabs.map(t => (t.id === id ? {...t, dirty} : t)),
            },
        })),
    setTabTitle: (id, title) =>
        set(state => ({
            portal: {
                ...state.portal,
                tabs: state.portal.tabs.map(t => (t.id === id ? {...t, title} : t)),
            },
        })),
    updateTabComponent: (id, component) =>
        set(state => ({
            portal: {
                ...state.portal,
                tabs: state.portal.tabs.map(t => (t.id === id ? {...t, component} : t)),
            },
        })),
    setPortalConfig: config => set(state => ({portal: {...state.portal, portalConfig: config}})),
 
    // Toast actions
    showToast: toast => {
        const id = String(++toastIdCounter);
        set(state => ({toasts: [...state.toasts, {...toast, id}]}));
        // Auto-dismiss
        const life = toast.life ?? (toast.severity === 'error' ? 8000 : 4000);
        setTimeout(() => get().clearToast(id), life);
    },
    clearToast: id => set(state => ({toasts: state.toasts.filter(t => t.id !== id)})),
    clearAllToasts: () => set({toasts: []}),
 
    // Loader actions
    setLoading: (active, message) =>
        set(state => {
            const count = state.loader.count + (active ? 1 : -1);
            return {loader: {active: count > 0, message, count: Math.max(0, count)}};
        }),
 
    // Translations
    setTranslations: dict => set({translations: dict}),
    setLanguage: language => set({language}),
 
    // Actions registry
    registerActions: actions => set(state => ({actions: {...state.actions, ...actions}})),
 
    // Error
    showError: error => set({error}),
    clearError: () => set({error: null}),
 
    // Hint
    showHint: (target, message, error) => set({hint: {target, message, error}}),
    clearHint: () => set({hint: null}),
}));
 
// Expose for Playwright / E2E tests
if (typeof window !== 'undefined') {
    (window as unknown as Record<string, unknown>).__blongStore = useAppStore;
}