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

73.56% Statements 64/87
55.76% Branches 29/52
76.47% Functions 39/51
76.92% Lines 50/65

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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327                                                                                    40x     40x 40x 40x 40x                       2x 2x 2x     2x                                                                                                                                                                             40x             40x           40x   40x                               4x       5x       5x       23x               34x   34x   21x     34x 19x   15x                 8x 10x   8x     8x   2x   2x     2x                                 6x       19x       19x 7x   19x   19x 19x   1x 41x       24x 24x 24x       3x                       3x                     9x           7x 7x   21x       2x 2x                    
/**
 * 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;
}
 
/**
 * The user's explicit theme choice (set by the theme switcher). Undefined
 * fields mean "not chosen" — the Theme component then derives them from the
 * `IThemeConfig` prop. Persisted to `localStorage` so the choice survives a
 * reload.
 */
export interface IThemeSelection {
    /** Selected theme-option id (e.g. `lara-blue`, `glass`). */
    themeId?: string;
    /** Selected palette for themes that offer both light and dark variants. */
    palette?: 'light' | 'dark';
}
 
const THEME_STORAGE_KEY = 'blong.theme';
 
function readThemeSelection(): IThemeSelection {
    Iif (typeof localStorage === 'undefined') return {};
    try {
        const raw = localStorage.getItem(THEME_STORAGE_KEY);
        Eif (!raw) return {};
        const parsed = JSON.parse(raw) as {themeId?: unknown; palette?: unknown};
        const selection: IThemeSelection = {};
        if (typeof parsed.themeId === 'string') selection.themeId = parsed.themeId;
        if (parsed.palette === 'light' || parsed.palette === 'dark') selection.palette = parsed.palette;
        return selection;
    } catch {
        return {};
    }
}
 
function writeThemeSelection(selection: IThemeSelection): void {
    Iif (typeof localStorage === 'undefined') return;
    try {
        Iif (!selection.themeId && !selection.palette) {
            localStorage.removeItem(THEME_STORAGE_KEY);
        } else {
            localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify(selection));
        }
    } catch {
        // Ignore storage failures (private mode, quota, …).
    }
}
 
/** Complete app state */
export interface IAppState {
    auth: IAuthState;
    portal: IPortalState;
    toasts: IToast[];
    loader: {active: boolean; message?: string; count: number};
    translations: TranslationDict;
    /**
     * Per-language dictionaries registered by the app via
     * `setTranslationsByLanguage`.  When non-empty, `setLanguage` swaps the
     * active `translations` table to the matching language's dictionary
     * (English falls back to an empty dict = English strings).
     */
    translationsByLanguage: Record<string, TranslationDict>;
    language: string;
    actions: ActionRegistry;
    error: IBlongError | null;
    hint: IHint | null;
    /** Explicit theme choice made via the theme switcher (see IThemeSelection). */
    theme: IThemeSelection;
    /**
     * When true, the login popup is shown — set when an operation hits an
     * expired/invalid session (401) and the client-side token renewal failed.
     * The user logs in via the popup and re-invokes the operation.
     */
    loginPrompt: boolean;
}
 
/** 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;
    setTranslationsByLanguage: (dicts: Record<string, TranslationDict>) => void;
    setLanguage: (language: string) => void;
 
    // Actions registry
    registerActions: (actions: ActionRegistry) => void;
 
    // Error
    showError: (error: IBlongError) => void;
    clearError: () => void;
 
    // Theme
    /** Replace the explicit theme selection (persisted to localStorage). */
    setTheme: (selection: IThemeSelection) => void;
 
    // Login prompt
    setLoginPrompt: (visible: boolean) => 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: {},
    translationsByLanguage: {},
    language: 'en',
    actions: {},
    error: null,
    hint: null,
    theme: readThemeSelection(),
    loginPrompt: false,
 
    // 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);
        // Mirror error toasts to the browser console so agents and Playwright
        // tests can observe them via page.on('console') even when a transient
        // toast is missed by screenshot assertions.
        if (toast.severity === 'error') {
            console.error('[blong] error toast', toast.summary ?? '', toast.detail ?? '');
        }
        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}),
    setTranslationsByLanguage: dicts =>
        set(state => ({
            translationsByLanguage: dicts,
            // Re-apply the current language's dictionary immediately so the UI
            // reflects it even if the language was set before the dicts loaded.
            translations:
                Object.keys(dicts).length > 0
                    ? (dicts[state.language] ?? {})
                    : state.translations,
        })),
    setLanguage: language =>
        set(state => ({
            language,
            // When the app registered per-language dictionaries, switching the
            // language also swaps the active translation table (English = {}).
            translations:
                Object.keys(state.translationsByLanguage).length > 0
                    ? (state.translationsByLanguage[language] ?? {})
                    : state.translations,
        })),
 
    // Actions registry
    registerActions: actions => set(state => ({actions: {...state.actions, ...actions}})),
 
    // Error
    showError: error => {
        // Mirror the error popup (ErrorDialog) to the browser console so agents
        // and Playwright tests can observe it via page.on('console').
        console.error('[blong] error dialog', error.type, error.print ?? error.message, error);
        set({error});
    },
    clearError: () => set({error: null}),
 
    // Theme
    setTheme: selection => {
        writeThemeSelection(selection);
        set({theme: selection});
    },
 
    // Login prompt
    setLoginPrompt: visible => set({loginPrompt: visible}),
 
    // Hint
    showHint: (target, message, error) => set({hint: {target, message, error}}),
    clearHint: () => set({hint: null}),
}));