# AppShell, Sidebar & Topbar

# AppShell, Sidebar & Topbar

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [src/app.css](src/app.css)
- [src/app.d.ts](src/app.d.ts)
- [src/lib/api-types.ts](src/lib/api-types.ts)
- [src/lib/app-connectivity-events.ts](src/lib/app-connectivity-events.ts)
- [src/lib/backend-availability.svelte.ts](src/lib/backend-availability.svelte.ts)
- [src/lib/backend-availability.ts](src/lib/backend-availability.ts)
- [src/lib/components/AppShell.svelte](src/lib/components/AppShell.svelte)
- [src/lib/components/AppSidebar.svelte](src/lib/components/AppSidebar.svelte)
- [src/lib/components/AppTopbar.svelte](src/lib/components/AppTopbar.svelte)
- [src/lib/components/entity-list-table/components/EntityListTableHeaderRow.svelte](src/lib/components/entity-list-table/components/EntityListTableHeaderRow.svelte)
- [src/lib/components/ui/checkbox/checkbox.svelte](src/lib/components/ui/checkbox/checkbox.svelte)
- [src/lib/version.ts](src/lib/version.ts)

</details>



The application shell provides the foundational layout, navigation, and global monitoring systems for the Primebrick Backoffice. It integrates the root wrapper, module navigation, and real-time backend health monitoring into a cohesive user interface.

## AppShell Overview

`AppShell.svelte` acts as the root layout wrapper for the entire authenticated application. It manages the lifecycle of global event listeners, backend health probing, and the layout structure using the `Sidebar.Provider` and `Sidebar.Inset` components.

### Implementation Details
*   **Global Event Listeners**: During `onMount`, the shell attaches listeners for `unhandledrejection` and `error` to the window object. These capture runtime exceptions and push them to the global error store via `pushAppError` [src/lib/components/AppShell.svelte:26-45]().
*   **Health Probe Lifecycle**: The shell initiates an immediate health check on mount [src/lib/components/AppShell.svelte:23](). It also maintains an `$effect` that polls `/api/v1/health` every 5 seconds if the backend, database, or IDP is detected as offline [src/lib/components/AppShell.svelte:49-58]().
*   **Connectivity Restoration**: If the backend recovers from an offline state, the shell triggers a reload of the module navigation via `loadShellNav()` [src/lib/components/AppShell.svelte:60-71]().
*   **Layout Structure**: The shell uses a single `{@render children()}` block to avoid duplicate route mounting. It layers the `AppTopbar` and `AppServerBanner` at a higher z-index (`z-40`) to ensure they overlay scrolling content [src/lib/components/AppShell.svelte:74-98]().

**Sources:** [src/lib/components/AppShell.svelte:1-100](), [src/lib/backend-availability.svelte.ts:125-169]()

---

## AppSidebar

`AppSidebar.svelte` provides the primary navigation interface, organization switching, and system status visibility.

### Key Components & Logic
*   **Module Navigation**: It consumes `shellNav` from `modules-shell.svelte` to render dynamic module links. It includes logic to map module IDs to Lucide icons (e.g., `Users` for CRM, `Package` for Warehouse) [src/lib/components/AppSidebar.svelte:136-142]().
*   **Organization Switcher**: A reactive dropdown allowing users to switch contexts. It currently utilizes a demo state (`selectedOrgId`) which is derived into localized labels [src/lib/components/AppSidebar.svelte:46-50]().
*   **Health Chip**: A status indicator derived from `backendState.healthChip`. It displays different visual states (colors and labels) for `ok`, `backend_offline`, `db_offline`, and `idp_offline` [src/lib/components/AppSidebar.svelte:144-166]().
*   **User Profile & Logout**: Displays the current user's avatar and email, sourced from `userProfileState`. The `handleLogout` function clears `access_token` and `refresh_token` cookies and wipes `sessionStorage` before redirecting to `/login` [src/lib/components/AppSidebar.svelte:109-119]().

### Backend Health States
| State | Label Key | CSS Classes |
| :--- | :--- | :--- |
| `ok` | `shell.health.beOnline` | `bg-emerald-500/10 text-emerald-700` |
| `backend_offline` | `shell.health.beOffline` | `bg-red-500/10 text-red-700` |
| `db_offline` | `shell.health.dbOffline` | `bg-red-500/10 text-red-700` |
| `idp_offline` | `shell.health.idpOffline` | `bg-orange-500/10 text-orange-700` |

**Sources:** [src/lib/components/AppSidebar.svelte:1-175](), [src/lib/backend-availability.svelte.ts:42-52]()

---

## AppTopbar

`AppTopbar.svelte` manages global utility actions and system-wide notifications. It is laid out using a `grid-cols-[1fr_auto_1fr]` pattern to ensure the `CommandPalette` remains perfectly centered [src/lib/components/AppTopbar.svelte:122]().

### Features
*   **Error Badge**: Monitors the `appErrors` store. It calculates the `maxImpact` of all current errors (CRITICAL > HIGH > MEDIUM > LOW) and applies semantic coloring to the badge (e.g., `bg-critical` for critical errors) [src/lib/components/AppTopbar.svelte:54-74](). Clicking the alert icon opens the `shell.errors` side sheet [src/lib/components/AppTopbar.svelte:151]().
*   **IANA Timezone Display**: On mount, it resolves the browser's IANA timezone using `getResolvedIanaTimeZone()` and displays it with a `Globe` icon [src/lib/components/AppTopbar.svelte:132-141]().
*   **Notification Count**: Displays a badge with the number of unread notifications, defaulting to a `bg-info` style [src/lib/components/AppTopbar.svelte:170-175]().
*   **Theme & Language**: Integrates `ThemeToggle` for dark mode and `LangSelect` for i18n locale switching [src/lib/components/AppTopbar.svelte:142-177]().

**Sources:** [src/lib/components/AppTopbar.svelte:1-180](), [src/lib/browser-iana-timezone.ts:1-21]()

---

## Data Flow & State Diagrams

### Health Monitoring Lifecycle
This diagram illustrates how the system transitions between health states and how the UI reacts to backend availability.

```mermaid
graph TD
    subgraph "Code Entity Space"
        PS["probeHealth()"]
        BS["backendState (Runes)"]
        HC["computeHealthChip()"]
        ASB["AppSidebar.svelte"]
        ASH["AppShell.svelte"]
    end

    ASH -- "onMount / Interval" --> PS
    PS -- "fetch /api/v1/health" --> API["Backend API"]
    API -- "503 (DB Down)" --> PS
    PS -- "Update" --> BS
    BS -- "Derive" --> HC
    HC -- "Render Chip" --> ASB
    BS -- "If offline, poll 5s" --> ASH
```
**Sources:** [src/lib/backend-availability.svelte.ts:19-52](), [src/lib/components/AppShell.svelte:49-58]()

### Shell Component Hierarchy
Association of system layout names with their respective code entities and data providers.

```mermaid
graph BT
    subgraph "UI Components"
        TOP["AppTopbar.svelte"]
        SIDE["AppSidebar.svelte"]
        SHELL["AppShell.svelte"]
        BANNER["AppServerBanner.svelte"]
    end

    subgraph "State Providers"
        NAV["shellNav (modules-shell.svelte)"]
        ERR["appErrors (app-errors.ts)"]
        USER["userProfileState (user-profile-store.svelte)"]
    end

    TOP -- "reads" --> ERR
    SIDE -- "reads" --> NAV
    SIDE -- "reads" --> USER
    SHELL -- "contains" --> TOP
    SHELL -- "contains" --> SIDE
    SHELL -- "contains" --> BANNER
```
**Sources:** [src/lib/components/AppShell.svelte:82-97](), [src/lib/components/AppSidebar.svelte:10-19](), [src/lib/components/AppTopbar.svelte:20-22]()

## Module Loading State
The `shellNav` object tracks the loading state of the sidebar modules:
1.  **Loading**: Initial state while `fetchModules` is in flight.
2.  **Ready**: Successfully populated from `/api/v1/modules`.
3.  **Unreachable/Error**: Set if the API call fails or the backend is offline [src/lib/components/AppSidebar.svelte:134](). The `AppShell` attempts to recover this state automatically upon connectivity restoration [src/lib/components/AppShell.svelte:70]().

**Sources:** [src/lib/shell/modules-shell.svelte:1-20](), [src/lib/components/AppShell.svelte:61-71]()

---
