@rapidmx/web-client 0.15.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/README.md +373 -373
  2. package/apps/admin/branding/index.tsx +39 -39
  3. package/apps/admin/data-requests/index.tsx +482 -480
  4. package/apps/admin/domains/[uid].tsx +164 -164
  5. package/apps/admin/escrow-scopes/[uid].tsx +348 -348
  6. package/apps/admin/index.tsx +127 -124
  7. package/apps/admin/mailboxes/[uid].tsx +269 -224
  8. package/apps/admin/mailboxes/new/index.tsx +28 -28
  9. package/apps/admin/plugins/index.tsx +15 -15
  10. package/apps/admin/retention-policy/index.tsx +39 -39
  11. package/apps/admin/signing-certificates/index.tsx +343 -343
  12. package/apps/escrow/audit-log/index.tsx +196 -196
  13. package/apps/escrow/matters/[uid].tsx +621 -621
  14. package/apps/shared/auth/adminAccess.ts +99 -99
  15. package/apps/shared/components/admin/layout/AdminShell.tsx +378 -378
  16. package/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.tsx +238 -0
  17. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -152
  18. package/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.tsx +194 -0
  19. package/apps/shared/components/admin/settings/BrandingForm.tsx +423 -423
  20. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -119
  21. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +50 -3
  22. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +198 -198
  23. package/apps/shared/components/admin/settings/PluginsManager.tsx +1545 -1545
  24. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +182 -182
  25. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -288
  26. package/apps/shared/components/admin/setup/SetupWizard.tsx +444 -444
  27. package/apps/shared/components/admin/usePagedList.tsx +129 -129
  28. package/apps/shared/components/calendar/EventEditor.tsx +5 -10
  29. package/apps/shared/components/calendar/EventFormParts.tsx +16 -47
  30. package/apps/shared/components/calendar/EventModal.tsx +206 -206
  31. package/apps/shared/components/calendar/GuestInput.tsx +100 -0
  32. package/apps/shared/components/calendar/MonthView.tsx +185 -185
  33. package/apps/shared/components/calendar/RecurrenceEditor.tsx +227 -227
  34. package/apps/shared/components/calendar/RequestChangeForm.tsx +23 -54
  35. package/apps/shared/components/calendar/SplitDayView.tsx +144 -144
  36. package/apps/shared/components/calendar/TimeGridView.tsx +246 -246
  37. package/apps/shared/components/calendar/allDay.ts +124 -124
  38. package/apps/shared/components/calendar/eventForm.ts +2 -2
  39. package/apps/shared/components/calendar/eventFormat.ts +49 -22
  40. package/apps/shared/components/calendar/layout/CalendarShell.tsx +201 -200
  41. package/apps/shared/components/contacts/ContactForm.tsx +383 -383
  42. package/apps/shared/components/contacts/ContactsSidebar.tsx +1 -1
  43. package/apps/shared/components/contacts/ContactsToolbar.tsx +103 -98
  44. package/apps/shared/components/contacts/layout/ContactsShell.tsx +217 -216
  45. package/apps/shared/components/escrow/layout/EscrowShell.tsx +155 -155
  46. package/apps/shared/components/layout/AppShell.tsx +480 -480
  47. package/apps/shared/components/layout/FloatingActionButton.tsx +31 -0
  48. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +398 -398
  49. package/apps/shared/components/layout/MailboxProvisioning.tsx +168 -168
  50. package/apps/shared/components/layout/ResponsiveToolbar.tsx +315 -315
  51. package/apps/shared/components/layout/ThemeSwitch.tsx +84 -84
  52. package/apps/shared/components/layout/UserMenu.tsx +439 -424
  53. package/apps/shared/components/mail/ConversationList.tsx +323 -323
  54. package/apps/shared/components/mail/ConversationThreadPane.tsx +612 -491
  55. package/apps/shared/components/mail/MailSelectionBar.tsx +236 -227
  56. package/apps/shared/components/mail/MessageDetailPane.tsx +1559 -1559
  57. package/apps/shared/components/mail/compose/ComposeContext.tsx +312 -312
  58. package/apps/shared/components/mail/compose/ComposeToolbar.tsx +422 -422
  59. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1681 -1677
  60. package/apps/shared/components/mail/compose/RecipientInput.tsx +54 -11
  61. package/apps/shared/components/mail/compose/RichTextEditor.tsx +147 -147
  62. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -60
  63. package/apps/shared/components/mail/compose/quotedBody.ts +161 -161
  64. package/apps/shared/components/mail/layout/FolderBadgeChip.tsx +21 -0
  65. package/apps/shared/components/mail/layout/MailShell.tsx +137 -113
  66. package/apps/shared/components/mail/layout/SidebarSection.tsx +66 -0
  67. package/apps/shared/components/mail/reading/PendingMessageCard.tsx +68 -0
  68. package/apps/shared/components/mail/verificationSeals.ts +125 -125
  69. package/apps/shared/components/rules/RuleBuilder.tsx +311 -311
  70. package/apps/shared/components/settings/SigningCertificateCard.tsx +344 -344
  71. package/apps/shared/components/settings/layout/SettingsShell.tsx +255 -254
  72. package/apps/shared/components/tasks/TasksSidebar.tsx +1 -1
  73. package/apps/shared/components/tasks/layout/TasksShell.tsx +218 -217
  74. package/apps/shared/keyboard/GlobalShortcuts.tsx +51 -51
  75. package/apps/shared/keyboard/ShortcutProvider.tsx +62 -62
  76. package/apps/shared/keyboard/ShortcutsDialog.tsx +84 -84
  77. package/apps/shared/keyboard/dispatch.ts +124 -124
  78. package/apps/shared/keyboard/format.ts +89 -89
  79. package/apps/shared/keyboard/keymap.ts +114 -114
  80. package/apps/shared/keyboard/registry.ts +65 -65
  81. package/apps/shared/keyboard/targets.ts +79 -79
  82. package/apps/shared/mail/folderCounts.ts +17 -0
  83. package/apps/shared/mail/folderTree.ts +143 -143
  84. package/apps/shared/mail/listAllPages.ts +39 -39
  85. package/apps/shared/mail/newMailNotifications.ts +171 -171
  86. package/apps/shared/mail/outbox/outgoingReplies.ts +192 -0
  87. package/apps/shared/mail/outbox/sendJob.ts +19 -1
  88. package/apps/shared/mail/outbox/sendOutcomes.ts +13 -4
  89. package/apps/shared/mail/primaryMailbox.ts +71 -0
  90. package/apps/shared/mail/useCollapsedSections.ts +146 -0
  91. package/apps/shared/mail/useMailConnection.ts +205 -203
  92. package/apps/shared/mail/useMailLiveUpdates.ts +277 -277
  93. package/apps/shared/mail/useMarkMessageRead.ts +47 -47
  94. package/apps/shared/mail/useNewMailNotifications.ts +178 -178
  95. package/apps/shared/navigation/AppRouter.tsx +300 -300
  96. package/apps/shared/navigation/routerContext.tsx +83 -83
  97. package/apps/shared/notifications/store.ts +560 -560
  98. package/apps/shared/search/LocalIndexLifecycle.tsx +114 -114
  99. package/apps/shared/search/crossMailboxSearch.ts +169 -0
  100. package/apps/shared/search/localIndexBuilder.ts +481 -481
  101. package/apps/shared/signing/enrollmentStorage.ts +33 -33
  102. package/apps/shared/signing/enrollmentTracker.ts +385 -385
  103. package/apps/shared/signing/enrollmentView.ts +251 -251
  104. package/apps/shared/signing/useNow.ts +19 -19
  105. package/apps/shared/signing/useSigningEnrollmentWatcher.ts +90 -90
  106. package/apps/shared/styles/app.css +396 -386
  107. package/apps/www/calendar/index.tsx +578 -571
  108. package/apps/www/contacts/[uid].tsx +109 -109
  109. package/apps/www/contacts/index.tsx +6 -0
  110. package/apps/www/index.tsx +2847 -2479
  111. package/apps/www/messages/[uid].tsx +135 -135
  112. package/apps/www/settings/auto-reply/index.tsx +133 -133
  113. package/apps/www/settings/encryption/index.tsx +1287 -1287
  114. package/apps/www/settings/filters/[uid].tsx +176 -176
  115. package/apps/www/settings/filters/index.tsx +102 -102
  116. package/apps/www/settings/filters/new/index.tsx +140 -140
  117. package/apps/www/settings/labels/index.tsx +204 -204
  118. package/apps/www/settings/privacy/index.tsx +492 -492
  119. package/apps/www/settings/profile/index.tsx +248 -248
  120. package/apps/www/settings/read-receipts/index.tsx +147 -147
  121. package/apps/www/settings/sharing/index.tsx +256 -256
  122. package/apps/www/settings/signatures/[uid].tsx +172 -172
  123. package/apps/www/settings/signatures/index.tsx +88 -88
  124. package/apps/www/settings/signatures/new/index.tsx +135 -135
  125. package/apps/www/tasks/index.tsx +649 -649
  126. package/dist/apps/admin/data-requests/index.js +1 -1
  127. package/dist/apps/admin/index.js +2 -1
  128. package/dist/apps/admin/mailboxes/[uid].js +12 -2
  129. package/dist/apps/shared/components/admin/layout/AdminShell.js +2 -2
  130. package/dist/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.d.ts +35 -0
  131. package/dist/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.js +115 -0
  132. package/dist/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.d.ts +16 -0
  133. package/dist/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.js +92 -0
  134. package/dist/apps/shared/components/admin/settings/BrandingForm.js +3 -3
  135. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +25 -3
  136. package/dist/apps/shared/components/calendar/EventEditor.js +5 -10
  137. package/dist/apps/shared/components/calendar/EventFormParts.d.ts +3 -2
  138. package/dist/apps/shared/components/calendar/EventFormParts.js +5 -16
  139. package/dist/apps/shared/components/calendar/GuestInput.d.ts +45 -0
  140. package/dist/apps/shared/components/calendar/GuestInput.js +30 -0
  141. package/dist/apps/shared/components/calendar/RequestChangeForm.js +11 -22
  142. package/dist/apps/shared/components/calendar/eventForm.d.ts +2 -2
  143. package/dist/apps/shared/components/calendar/eventFormat.d.ts +21 -8
  144. package/dist/apps/shared/components/calendar/eventFormat.js +50 -23
  145. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +3 -2
  146. package/dist/apps/shared/components/contacts/ContactsSidebar.js +1 -1
  147. package/dist/apps/shared/components/contacts/ContactsToolbar.d.ts +3 -1
  148. package/dist/apps/shared/components/contacts/ContactsToolbar.js +4 -2
  149. package/dist/apps/shared/components/contacts/layout/ContactsShell.js +4 -3
  150. package/dist/apps/shared/components/layout/FloatingActionButton.d.ts +13 -0
  151. package/dist/apps/shared/components/layout/FloatingActionButton.js +9 -0
  152. package/dist/apps/shared/components/layout/UserMenu.d.ts +4 -1
  153. package/dist/apps/shared/components/layout/UserMenu.js +6 -5
  154. package/dist/apps/shared/components/mail/ConversationThreadPane.js +127 -22
  155. package/dist/apps/shared/components/mail/MailSelectionBar.d.ts +6 -1
  156. package/dist/apps/shared/components/mail/MailSelectionBar.js +3 -3
  157. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +8 -4
  158. package/dist/apps/shared/components/mail/compose/RecipientInput.d.ts +21 -1
  159. package/dist/apps/shared/components/mail/compose/RecipientInput.js +18 -10
  160. package/dist/apps/shared/components/mail/layout/FolderBadgeChip.d.ts +6 -0
  161. package/dist/apps/shared/components/mail/layout/FolderBadgeChip.js +9 -0
  162. package/dist/apps/shared/components/mail/layout/MailShell.d.ts +5 -0
  163. package/dist/apps/shared/components/mail/layout/MailShell.js +64 -45
  164. package/dist/apps/shared/components/mail/layout/SidebarSection.d.ts +23 -0
  165. package/dist/apps/shared/components/mail/layout/SidebarSection.js +16 -0
  166. package/dist/apps/shared/components/mail/reading/PendingMessageCard.d.ts +14 -0
  167. package/dist/apps/shared/components/mail/reading/PendingMessageCard.js +16 -0
  168. package/dist/apps/shared/components/settings/layout/SettingsShell.js +6 -5
  169. package/dist/apps/shared/components/tasks/TasksSidebar.js +1 -1
  170. package/dist/apps/shared/components/tasks/layout/TasksShell.js +4 -3
  171. package/dist/apps/shared/mail/folderCounts.d.ts +10 -0
  172. package/dist/apps/shared/mail/folderCounts.js +12 -0
  173. package/dist/apps/shared/mail/outbox/outgoingReplies.d.ts +80 -0
  174. package/dist/apps/shared/mail/outbox/outgoingReplies.js +131 -0
  175. package/dist/apps/shared/mail/outbox/sendJob.d.ts +5 -1
  176. package/dist/apps/shared/mail/outbox/sendJob.js +14 -1
  177. package/dist/apps/shared/mail/outbox/sendOutcomes.js +13 -4
  178. package/dist/apps/shared/mail/primaryMailbox.d.ts +29 -0
  179. package/dist/apps/shared/mail/primaryMailbox.js +61 -0
  180. package/dist/apps/shared/mail/useCollapsedSections.d.ts +32 -0
  181. package/dist/apps/shared/mail/useCollapsedSections.js +110 -0
  182. package/dist/apps/shared/mail/useMailConnection.js +3 -1
  183. package/dist/apps/shared/search/crossMailboxSearch.d.ts +72 -0
  184. package/dist/apps/shared/search/crossMailboxSearch.js +136 -0
  185. package/dist/apps/shared/styles/app.css +396 -386
  186. package/dist/apps/www/calendar/index.js +3 -2
  187. package/dist/apps/www/contacts/index.js +3 -1
  188. package/dist/apps/www/index.js +426 -189
  189. package/package.json +2 -2
@@ -1,480 +1,480 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import "../../styles/app.css";
6
- import React, { PropsWithChildren, useEffect, useRef, useState } from "react";
7
- import type { IconType } from "react-icons";
8
- import {
9
- HiOutlineCalendarDays,
10
- HiOutlineClipboardDocumentList,
11
- HiOutlineEnvelope,
12
- HiOutlinePuzzlePiece,
13
- HiOutlineUsers,
14
- } from "react-icons/hi2";
15
- import { useRedirectIfUnauthenticated } from "@rapidmx/react-shared/auth/session.js";
16
- import { getSetupStatus } from "@rapidmx/react-shared/admin/setupApi.js";
17
- import { stopImpersonating } from "@rapidmx/react-shared/mail/mailApi.js";
18
- import useBranding from "@rapidmx/react-shared/branding/useBranding.js";
19
- import { useIdleKeyTimeout } from "@rapidmx/react-shared/crypto/useIdleKeyTimeout.js";
20
- import ComposeProvider from "../mail/compose/ComposeContext.js";
21
- import { flushComposeDrafts, markSigningOut } from "../mail/compose/composeFlushRegistry.js";
22
- import BottomTabBar, { NavItem } from "@rapidmx/react-shared/components/navigation/BottomTabBar.js";
23
- import { FrameBrandingFooter, FrameBrandingHeader, useBrandingHtml } from "./BrandingChrome.js";
24
- import RailIcon from "./RailIcon.js";
25
- import AppearanceProvider from "../../appearance/AppearanceProvider.js";
26
- import { clearAppearanceCache } from "../../appearance/appearanceCache.js";
27
- import type { Branding } from "@rapidmx/react-shared/branding/brandingApi.js";
28
- import UserMenu from "./UserMenu.js";
29
- import { UnlockPromptProvider } from "./UnlockPromptProvider.js";
30
- import { SIGN_OUT_CHANNEL, destroyAllLocalIndexes } from "../../search/localIndexRpcClient.js";
31
- import { authApiFetch, setApiUnauthorizedObserver } from "@rapidmx/react-shared/util/api.js";
32
- import { destroyUnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
33
- import { clearPinnedSignerCache } from "../mail/pinnedSigners.js";
34
- import { mergePluginNavItems, PluginNav, PluginNavProps } from "../../plugins/pluginNav.js";
35
- import { useInAppFrame } from "../../navigation/frameContext.js";
36
- import { APP_HREFS } from "../../navigation/appHrefs.js";
37
- import { useNavigate } from "../../navigation/routerContext.js";
38
- import { GlobalShortcuts } from "../../keyboard/GlobalShortcuts.js";
39
- import { ShortcutProvider } from "../../keyboard/ShortcutProvider.js";
40
- import ShortcutsDialog from "../../keyboard/ShortcutsDialog.js";
41
- import { inboxUnreadTotal } from "../../mail/folderCounts.js";
42
- import { MailConnectionContext, useMailConnection } from "../../mail/useMailConnection.js";
43
- import { useUnreadTitle } from "../../mail/useUnreadTitle.js";
44
- import UnlockBridge from "../../mail/outbox/UnlockBridge.js";
45
- import NotificationCenter from "../../notifications/NotificationCenter.js";
46
- import { useHeaderHeightRef } from "../../notifications/headerOffset.js";
47
- import NotificationHistoryDialog from "../../notifications/NotificationHistoryDialog.js";
48
- import { notifySessionExpired, setSignInUrl } from "../../notifications/apiErrors.js";
49
- import { useUnseenErrorCount } from "../../notifications/useNotifications.js";
50
- import { useSigningEnrollmentWatcher } from "../../signing/useSigningEnrollmentWatcher.js";
51
- import { useCalendarReminders } from "../../calendar/useCalendarReminders.js";
52
-
53
- /** How long sign-out waits for auth-server's logout before navigating anyway. */
54
- export const LOGOUT_TIMEOUT_MS = 3_000;
55
-
56
- /**
57
- * Calls auth-server's logout (`POST /api/auth/logout`, cross-origin with credentials), which clears the auth
58
- * cookie and invalidates the session's refresh token. Bounded by `LOGOUT_TIMEOUT_MS` and never rejects - a
59
- * failure (unreachable server, CORS) must not keep the user from leaving.
60
- */
61
- async function logOutOfAuthServer(authServerUrl: string | undefined): Promise<void> {
62
- if (!authServerUrl) {
63
- return;
64
- }
65
- const controller = new AbortController();
66
- const timer = setTimeout(() => controller.abort(), LOGOUT_TIMEOUT_MS);
67
- try {
68
- await authApiFetch(authServerUrl, "/auth/logout", { method: "POST", signal: controller.signal });
69
- } catch {
70
- // Navigate anyway - see this function's doc comment.
71
- } finally {
72
- clearTimeout(timer);
73
- }
74
- }
75
-
76
- export type AppShellApp = "mail" | "calendar" | "contacts" | "tasks";
77
-
78
- /** `"settings"` is a valid `active` value but deliberately has no entry in `APPS` below — Settings is
79
- * reached via a `UserMenu` item, not a 5th rail icon (see `SettingsShell.tsx`), so it highlights no
80
- * rail/tab icon at all; only the header title needs to account for it. Any other string is a plugin's
81
- * `appRail` item id (see `PluginNav`). */
82
- export type AppShellActive = AppShellApp | "settings" | (string & {});
83
-
84
- export interface AppShellProps extends PluginNavProps {
85
- /** Which icon in the rail is highlighted as the current app — `"settings"` highlights none, and a plugin
86
- * app page passes its own `appRail` item id. */
87
- active: AppShellActive;
88
- /** Populated automatically by the framework from an authenticated request (e.g. a valid `jwt` cookie). */
89
- userUid?: string;
90
- /** auth-server's base URL, injected via the route's `fetchProps`. */
91
- authServerUrl?: string;
92
- /**
93
- * `true` when this session is an admin "log in as user" impersonation (a `jwt_impersonator` cookie is
94
- * present) — see `MailShell`'s original doc comment, unchanged now that this lives here. Drives the
95
- * "you are viewing as this user — stop impersonating" banner below.
96
- */
97
- impersonating?: boolean;
98
- /** Where `mailApi.ts`'s `stopImpersonating()` should call — see `MailShell`'s original doc comment. */
99
- impersonationBaseUrl?: string;
100
- /** `true` when the caller's JWT carries a trusted role — shows an "Admin Console" item in the user menu below. A token
101
- * only carries one once elevated, so a real administrator with an ordinary session is `false` here; the user menu
102
- * asks auth-server about them separately (see `UserMenu`'s `detectAdmin`). */
103
- trusted?: boolean;
104
- /** The role names the server treats as trusted (its `trusted_roles` config, injected via the route's `fetchProps`) -
105
- * what that lookup looks for. Absent means the server's own default, `["admin"]`. */
106
- trustedRoles?: string[];
107
- /** The deployment's branding as the server rendered the page (its `branding` prop). Used until the frame's own fetch answers, so a custom header is there from the first paint - and the frame knows to drop its own title bar - instead of appearing (and moving everything) once the request returns. */
108
- branding?: Branding;
109
- /** The signed-in user's stored appearance preferences as the server rendered the page (its `appearance` prop), so the first paint already wears the theme and background - see `AppearanceProvider`. */
110
- appearance?: unknown;
111
- }
112
-
113
- export interface AppDef {
114
- id: AppShellApp;
115
- href: string;
116
- label: string;
117
- icon: IconType;
118
- }
119
-
120
- export const APPS: AppDef[] = [
121
- { id: "mail", href: APP_HREFS.mail, label: "Mail", icon: HiOutlineEnvelope },
122
- { id: "calendar", href: APP_HREFS.calendar, label: "Calendar", icon: HiOutlineCalendarDays },
123
- { id: "contacts", href: APP_HREFS.contacts, label: "Contacts", icon: HiOutlineUsers },
124
- { id: "tasks", href: APP_HREFS.tasks, label: "Tasks", icon: HiOutlineClipboardDocumentList },
125
- ];
126
-
127
- /** Ids plugin `appRail` items can't take besides `APPS`' own - `"settings"` has no rail icon but is still a
128
- * core `active` value. */
129
- const RESERVED_APP_IDS = ["settings"];
130
-
131
- /** `APPS` followed by the plugins' `appRail` items (generic icon), core ids winning - see `mergePluginNavItems`. */
132
- export function appRailItems(pluginNav?: PluginNav): NavItem[] {
133
- return mergePluginNavItems<NavItem>(
134
- APPS,
135
- pluginNav?.appRail,
136
- ({ id, href, label }) => ({ id, href, label, icon: HiOutlinePuzzlePiece }),
137
- RESERVED_APP_IDS,
138
- );
139
- }
140
-
141
- /** What only the persistent frame (`AppRouter`) passes to the chrome it keeps mounted. */
142
- export interface AppChromeProps extends AppShellProps {
143
- /** Changes whenever the router shows a different page: the chrome then moves focus to the content, scrolls to its top,
144
- * sets the document title and announces the page. Absent outside the router, when nothing does. */
145
- routeKey?: string;
146
- /** The router is loading the next page's code - the content is `aria-busy`. */
147
- busy?: boolean;
148
- /** A screen that takes over the window (`FrameTakeover`) is showing: the rail, header, banner and footer are hidden - not
149
- * unmounted, so what is inside them (and the page in the content region) keeps its state. */
150
- hideChrome?: boolean;
151
- }
152
-
153
- /**
154
- * The persistent chrome shared by every webmail app (Mail, Calendar, Contacts, Tasks): a left icon rail for
155
- * switching apps, a header with the current app's name and `UserMenu`, and the impersonation banner.
156
- * Each app's own shell (e.g. `MailShell`) renders its own contextual sidebar + content as `children`, inside
157
- * the area to the right of the icon rail and below the header.
158
- *
159
- * Rendered by `AppRouter`, once, for the life of the page, so that moving between apps replaces only `children` - see
160
- * `AppShell` below for what a page's own shell renders instead.
161
- */
162
- export function AppChrome({
163
- active,
164
- userUid,
165
- authServerUrl,
166
- impersonating,
167
- impersonationBaseUrl,
168
- trusted,
169
- trustedRoles,
170
- branding: initialBranding,
171
- appearance,
172
- pluginNav,
173
- routeKey,
174
- busy,
175
- hideChrome,
176
- children,
177
- }: PropsWithChildren<AppChromeProps>) {
178
- const [stoppingImpersonation, setStoppingImpersonation] = useState(false);
179
- // The keyboard shortcuts dialog: opened by `?`/Ctrl+/ (`GlobalShortcuts`) and by the account menu's item.
180
- const [shortcutsOpen, setShortcutsOpen] = useState(false);
181
- // The pop-up history ("Recent notifications" in the account menu). The pop-ups themselves are drawn by `NotificationCenter`, below.
182
- const [historyOpen, setHistoryOpen] = useState(false);
183
- // Only the count is read, so the whole frame does not render again for every pop-up that comes and goes.
184
- const unseenErrors = useUnseenErrorCount();
185
- // The title bar's height for the pop-up stack, which sticks just below the header (a branding header publishes its own - `FrameBrandingHeader`).
186
- const headerRef = useHeaderHeightRef();
187
- const signingOutRef = useRef(false);
188
- const { branding: fetchedBranding, iconSrc: fetchedIconSrc } = useBranding();
189
- // The server's copy until the fetch answers, so the frame's shape (a custom header replaces the title bar) never changes after the first paint.
190
- const branding = fetchedBranding ?? initialBranding ?? null;
191
- const iconSrc = fetchedBranding ? fetchedIconSrc : initialBranding?.iconUrl || initialBranding?.logoUrl || fetchedIconSrc;
192
- // The custom header and footer, sanitized and with their `{USER_MENU}` / `{APP_TITLE}` placeholders (`undefined` until parsed, `null` when there is none).
193
- const header = useBrandingHtml(branding?.headerHtml);
194
- const footer = useBrandingHtml(branding?.footerHtml);
195
- // The mailboxes, their folders and the one push connection live here, in the frame that stays mounted as the router swaps pages - so
196
- // new-mail pop-ups, the folder counters and the tab title's unread count work in Calendar, Contacts, Tasks and Settings too, and moving
197
- // between apps never opens a second socket (the server allows ten per user). `MailShell` reads them from `MailConnectionContext`. Outside
198
- // the router (`AppShell` rendered as a page's own chrome: tests, plugin pages) it stays off, and a Mail shell owns its connection itself.
199
- const inFrame = useInAppFrame();
200
- const navigate = useNavigate();
201
- const mail = useMailConnection({ userUid, enabled: inFrame, open: navigate });
202
- // A signing certificate the user asked for is announced when it is issued (or fails), on whichever page they are - see the hook.
203
- useSigningEnrollmentWatcher({ userUid, mailboxes: mail.mailboxes, enabled: inFrame });
204
- // A meeting reminder pops up on whichever page they are - see the hook.
205
- useCalendarReminders({ userUid, enabled: inFrame });
206
-
207
- useRedirectIfUnauthenticated(userUid, authServerUrl);
208
- // Any request this app makes that the server answers with a 401 - the session ended - raises one "Your session expired" pop-up with a
209
- // Sign in action (see `notifySessionExpired()`), whichever request noticed first, a background refresh included.
210
- useEffect(() => {
211
- setSignInUrl(authServerUrl);
212
- if (!userUid) {
213
- return;
214
- }
215
- setApiUnauthorizedObserver(() => void notifySessionExpired());
216
- return () => setApiUnauthorizedObserver(undefined);
217
- }, [userUid, authServerUrl]);
218
- // Mounted here, not scoped to Mail/Settings (the only shells that actually read unlocked keys),
219
- // specifically so activity in *any* app resets the idle clock - see that hook's own doc comment.
220
- useIdleKeyTimeout();
221
-
222
- // An administrator on a server that hasn't finished first-run setup is sent to the setup wizard. The status
223
- // check is admin-only, so it's only made for a trusted caller - everyone else would just get a 403 on every
224
- // page load. Any failure is ignored.
225
- useEffect(() => {
226
- if (!userUid || impersonating || !trusted) {
227
- return;
228
- }
229
- getSetupStatus()
230
- .then((status) => {
231
- if (status.required) {
232
- window.location.href = "/admin/setup";
233
- }
234
- })
235
- .catch(() => undefined);
236
- }, [userUid, impersonating, trusted]);
237
-
238
- // Another tab signing out (this app's `handleSignOut`, or the admin/escrow consoles' `signOutOfConsole()`)
239
- // ended this session too - its auth cookie is gone - so this tab destroys its own unlocked keys and every
240
- // local search index on the device, then leaves as well. The consoles have no local-index client of their
241
- // own, so this is what actually removes the indexes after a console sign-out (the console also records a
242
- // pending deletion, retried on the next mail load, in case no mail tab is open). `destroyAllLocalIndexes()`
243
- // announces the sign-out on this same channel, which this tab then hears itself, so the ref is set first:
244
- // each tab reacts once, and the tab that started the sign-out ignores its own announcement.
245
- useEffect(() => {
246
- if (!userUid || typeof BroadcastChannel === "undefined") {
247
- return;
248
- }
249
- const channel = new BroadcastChannel(SIGN_OUT_CHANNEL);
250
- channel.addEventListener("message", (event: MessageEvent<{ type?: string }>) => {
251
- if (event.data?.type !== "sign-out" || signingOutRef.current) {
252
- return;
253
- }
254
- signingOutRef.current = true;
255
- // Compose windows must not ask "Leave site?" - that would let this forced navigation be cancelled.
256
- markSigningOut();
257
- destroyUnlockedKeys();
258
- clearPinnedSignerCache();
259
- clearAppearanceCache();
260
- // Bounded by its own timeout and never rejects - awaited so navigating doesn't kill the Worker mid-delete.
261
- void destroyAllLocalIndexes().then(() => {
262
- window.location.href = authServerUrl ?? "/";
263
- });
264
- });
265
- return () => channel.close();
266
- }, [userUid, authServerUrl]);
267
-
268
- async function handleSignOut() {
269
- signingOutRef.current = true;
270
- // Before flushing and navigating: compose windows then skip their "Leave site?" prompt, which could
271
- // otherwise cancel the sign-out's own navigation.
272
- markSigningOut();
273
- // Unlocked private keys never outlive an explicit sign-out.
274
- destroyUnlockedKeys();
275
- // Trusted signer pins read from contacts don't outlive the session either.
276
- clearPinnedSignerCache();
277
- clearAppearanceCache();
278
- // Open compose windows save edits still waiting on their autosave debounce while the session is still
279
- // valid - logout invalidates it. Bounded the same way as logout itself, and never rejects.
280
- await flushComposeDrafts(LOGOUT_TIMEOUT_MS);
281
- // The Tier 2 local index MUST be destroyed on explicit logout, the same as unlocked keys themselves
282
- // (spec §11). Destroys every index on this device (not only mailboxes opened this page load) and is
283
- // awaited before navigating - a navigation tears down the Worker mid-delete otherwise.
284
- // destroyAllLocalIndexes() is bounded by its own timeout and never rejects, so sign-out can't hang.
285
- // In parallel, auth-server's logout clears the auth cookie and invalidates the session's refresh
286
- // token - without it, "Sign Out" would only navigate away from a still-valid session.
287
- await Promise.all([destroyAllLocalIndexes(), logOutOfAuthServer(authServerUrl)]);
288
- window.location.href = authServerUrl ?? "/";
289
- }
290
-
291
- async function handleStopImpersonating() {
292
- setStoppingImpersonation(true);
293
- try {
294
- await stopImpersonating(impersonationBaseUrl ?? "");
295
- } catch {
296
- // Navigate either way: a failed call leaves the impersonator cookie (and this banner) exactly as
297
- // they were, so there's nothing else useful to show — matching this app's other network-error
298
- // handling, which surfaces via a full reload rather than an inline retry affordance.
299
- } finally {
300
- window.location.href = "/admin";
301
- }
302
- }
303
-
304
- // What the persistent frame (`AppRouter`) needs on top of a page that never changes: the document title follows the page, and
305
- // after the router replaces the page the keyboard focus, the scroll position and a screen reader are told about it - a
306
- // page load did all of that by itself. Nothing here runs for a page shown outside the router (`routeKey` is undefined).
307
- const contentRef = useRef<HTMLDivElement>(null);
308
- const [announcement, setAnnouncement] = useState("");
309
- const firstRouteKeyRef = useRef(routeKey);
310
- const pageLabel = active === "settings" ? "Settings" : appRailItems(pluginNav).find((app) => app.id === active)?.label;
311
- useEffect(() => {
312
- if (routeKey !== undefined) {
313
- const brand = branding?.title || branding?.companyName || "RapidMX";
314
- document.title = pageLabel ? `${brand}: ${pageLabel}` : brand;
315
- }
316
- }, [routeKey, pageLabel, branding]);
317
- // After the title effect above, so a page change (which rewrites the title) is followed by the unread count going back in front of it.
318
- useUnreadTitle(inboxUnreadTotal(mail.mailboxFolders, mail.folderCounts.counts), {
319
- enabled: inFrame,
320
- resetKey: `${routeKey}|${pageLabel}|${branding?.title}|${branding?.companyName}`,
321
- });
322
- useEffect(() => {
323
- if (routeKey === undefined || routeKey === firstRouteKeyRef.current) {
324
- return;
325
- }
326
- setAnnouncement(pageLabel ?? "");
327
- contentRef.current?.focus({ preventScroll: true });
328
- window.scrollTo(0, 0);
329
- }, [routeKey]);
330
-
331
- if (!userUid) {
332
- return <div className="min-h-screen" />;
333
- }
334
-
335
- const apps = appRailItems(pluginNav);
336
- // The header title: "settings" has no rail item, everything else is labelled by its own rail item.
337
- const activeLabel = active === "settings" ? "Settings" : apps.find((app) => app.id === active)?.label;
338
- // A custom header (`Branding.headerHtml`) replaces the app's own title bar and the icon at the top of the rail: it is the top of the app, and the
339
- // account menu moves into it. While it is still being parsed it already counts, so the frame's shape doesn't change under the user.
340
- const customHeader = header !== null;
341
- // Where the one account menu lives: the header's `{USER_MENU}`, else the footer's, else a small cell at the header's right end - never lost.
342
- const menuInHeader = !!header?.hasUserMenu;
343
- const menuInFooter = customHeader && !!header && !menuInHeader && !!footer?.hasUserMenu;
344
- const renderUserMenu = (placement: "down" | "up") => (
345
- <UserMenu
346
- userUid={userUid}
347
- authServerUrl={authServerUrl}
348
- onSignOut={handleSignOut}
349
- // An impersonating administrator acts as the impersonated user, so the console link is hidden then.
350
- showAdminLink={!!trusted && !impersonating}
351
- detectAdmin={!trusted && !impersonating}
352
- trustedRoles={trustedRoles}
353
- showSettingsLink
354
- showNotificationSettings
355
- onShowShortcuts={() => setShortcutsOpen(true)}
356
- onShowNotifications={() => setHistoryOpen(true)}
357
- unseenErrors={unseenErrors}
358
- placement={placement}
359
- />
360
- );
361
-
362
- return (
363
- // Mounted here, not scoped to Mail/Settings, for the same reason as useIdleKeyTimeout() above -
364
- // ComposeWindow's sign/encrypt toggles and MessageDetailPane's encrypted-message view (both Mail)
365
- // are today's only useUnlockPrompt() callers, but this needs to be available to any app shell.
366
- // Asks the server for the user's appearance only in the persistent frame (every core page); a page that renders its own chrome (a plugin's) uses the
367
- // `appearance` it was given and what this browser cached.
368
- <AppearanceProvider userUid={userUid} initial={appearance} lookUp={inFrame}>
369
- <ShortcutProvider>
370
- <MailConnectionContext.Provider value={inFrame ? mail : null}>
371
- <GlobalShortcuts authServerUrl={authServerUrl} onToggleHelp={() => setShortcutsOpen((open) => !open)} />
372
- <ShortcutsDialog open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
373
- <UnlockPromptProvider>
374
- <UnlockBridge />
375
- {/* An impersonating admin acts with the impersonated user's access, so their own trusted role
376
- mustn't skip the per-mailbox checks. */}
377
- <ComposeProvider userUid={userUid} trusted={!!trusted && !impersonating}>
378
- <div className="rr-frame-bg min-h-screen flex flex-col">
379
- {!hideChrome && customHeader && (
380
- <FrameBrandingHeader
381
- parsed={header}
382
- userMenu={menuInHeader ? renderUserMenu("down") : undefined}
383
- fallbackMenu={header && !menuInHeader && !menuInFooter ? renderUserMenu("down") : undefined}
384
- appTitle={activeLabel}
385
- />
386
- )}
387
- {impersonating && !hideChrome && (
388
- <div className="h-10 shrink-0 bg-warning text-warning-contrast flex items-center justify-center gap-3 text-sm font-medium px-4">
389
- <span>
390
- You are viewing as <strong>{userUid}</strong>.
391
- </span>
392
- <button
393
- type="button"
394
- onClick={handleStopImpersonating}
395
- disabled={stoppingImpersonation}
396
- className="underline hover:no-underline disabled:opacity-60"
397
- >
398
- {stoppingImpersonation ? "Returning to admin…" : "Return to admin"}
399
- </button>
400
- </div>
401
- )}
402
- <div className="flex-1 flex min-h-0">
403
- {!hideChrome && (
404
- <nav
405
- aria-label="Apps"
406
- className={[
407
- "hidden md:flex w-16 shrink-0 bg-surface border-r border-border flex-col items-center gap-1",
408
- // Under a custom header the rail starts with the app icons; without one its own icon is flush with the top of the window.
409
- customHeader ? "py-3" : "pb-3",
410
- ].join(" ")}
411
- >
412
- {!customHeader && (
413
- <RailIcon src={iconSrc} />
414
- )}
415
- {apps.map(({ id, href, label, icon: Icon }) => (
416
- <a
417
- key={id}
418
- href={href}
419
- aria-label={label}
420
- aria-current={id === active ? "page" : undefined}
421
- title={label}
422
- className={[
423
- "w-10 h-10 flex items-center justify-center rounded-sm",
424
- id === active
425
- ? "bg-primary/10 text-primary-dark"
426
- : "text-text-muted hover:bg-surface-alt hover:text-text",
427
- ].join(" ")}
428
- >
429
- <Icon size={20} aria-hidden="true" />
430
- </a>
431
- ))}
432
- </nav>
433
- )}
434
- {!hideChrome && <BottomTabBar apps={apps} active={active} />}
435
- <div className="flex-1 flex flex-col min-w-0">
436
- {!hideChrome && !customHeader && (
437
- <header ref={headerRef} className="rr-solid sticky top-0 z-30 h-16 shrink-0 bg-surface border-b border-border flex items-center justify-between gap-4 px-6">
438
- <span className="font-display font-bold text-lg uppercase tracking-wide">{activeLabel}</span>
439
- {renderUserMenu("down")}
440
- </header>
441
- )}
442
- {/* The one pop-up stack for the whole app: right under the header row, so it never covers the account menu. */}
443
- <NotificationCenter />
444
- <div
445
- ref={contentRef}
446
- id="app-content"
447
- tabIndex={-1}
448
- aria-busy={busy || undefined}
449
- className={["flex-1 flex min-h-0 outline-none", hideChrome ? "" : "pb-14 md:pb-0"].join(" ")}
450
- >
451
- {children}
452
- </div>
453
- </div>
454
- </div>
455
- {routeKey !== undefined && (
456
- <div role="status" aria-live="polite" className="sr-only">
457
- {announcement}
458
- </div>
459
- )}
460
- {!hideChrome && <FrameBrandingFooter parsed={footer} userMenu={menuInFooter ? renderUserMenu("up") : undefined} appTitle={activeLabel} />}
461
- </div>
462
- </ComposeProvider>
463
- </UnlockPromptProvider>
464
- <NotificationHistoryDialog open={historyOpen} onClose={() => setHistoryOpen(false)} />
465
- </MailConnectionContext.Provider>
466
- </ShortcutProvider>
467
- </AppearanceProvider>
468
- );
469
- }
470
-
471
- /**
472
- * What a page's own shell (`MailShell`, `CalendarShell`, ...) renders around its content. Outside the client-side router it
473
- * is the whole `AppChrome`, as it always was. Inside it (`AppRouter`) the chrome is already mounted above the page - and stays
474
- * mounted as the page is replaced - so this is only its children; everything it would have been given comes from the router
475
- * frame instead (the props are the same for every page, and `active` is the route's).
476
- */
477
- export default function AppShell(props: PropsWithChildren<AppShellProps>) {
478
- const inFrame = useInAppFrame();
479
- return inFrame ? <>{props.children}</> : <AppChrome {...props} />;
480
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import "../../styles/app.css";
6
+ import React, { PropsWithChildren, useEffect, useRef, useState } from "react";
7
+ import type { IconType } from "react-icons";
8
+ import {
9
+ HiOutlineCalendarDays,
10
+ HiOutlineClipboardDocumentList,
11
+ HiOutlineEnvelope,
12
+ HiOutlinePuzzlePiece,
13
+ HiOutlineUsers,
14
+ } from "react-icons/hi2";
15
+ import { useRedirectIfUnauthenticated } from "@rapidmx/react-shared/auth/session.js";
16
+ import { getSetupStatus } from "@rapidmx/react-shared/admin/setupApi.js";
17
+ import { stopImpersonating } from "@rapidmx/react-shared/mail/mailApi.js";
18
+ import useBranding from "@rapidmx/react-shared/branding/useBranding.js";
19
+ import { useIdleKeyTimeout } from "@rapidmx/react-shared/crypto/useIdleKeyTimeout.js";
20
+ import ComposeProvider from "../mail/compose/ComposeContext.js";
21
+ import { flushComposeDrafts, markSigningOut } from "../mail/compose/composeFlushRegistry.js";
22
+ import BottomTabBar, { NavItem } from "@rapidmx/react-shared/components/navigation/BottomTabBar.js";
23
+ import { FrameBrandingFooter, FrameBrandingHeader, useBrandingHtml } from "./BrandingChrome.js";
24
+ import RailIcon from "./RailIcon.js";
25
+ import AppearanceProvider from "../../appearance/AppearanceProvider.js";
26
+ import { clearAppearanceCache } from "../../appearance/appearanceCache.js";
27
+ import type { Branding } from "@rapidmx/react-shared/branding/brandingApi.js";
28
+ import UserMenu from "./UserMenu.js";
29
+ import { UnlockPromptProvider } from "./UnlockPromptProvider.js";
30
+ import { SIGN_OUT_CHANNEL, destroyAllLocalIndexes } from "../../search/localIndexRpcClient.js";
31
+ import { authApiFetch, setApiUnauthorizedObserver } from "@rapidmx/react-shared/util/api.js";
32
+ import { destroyUnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
33
+ import { clearPinnedSignerCache } from "../mail/pinnedSigners.js";
34
+ import { mergePluginNavItems, PluginNav, PluginNavProps } from "../../plugins/pluginNav.js";
35
+ import { useInAppFrame } from "../../navigation/frameContext.js";
36
+ import { APP_HREFS } from "../../navigation/appHrefs.js";
37
+ import { useNavigate } from "../../navigation/routerContext.js";
38
+ import { GlobalShortcuts } from "../../keyboard/GlobalShortcuts.js";
39
+ import { ShortcutProvider } from "../../keyboard/ShortcutProvider.js";
40
+ import ShortcutsDialog from "../../keyboard/ShortcutsDialog.js";
41
+ import { inboxUnreadTotal } from "../../mail/folderCounts.js";
42
+ import { MailConnectionContext, useMailConnection } from "../../mail/useMailConnection.js";
43
+ import { useUnreadTitle } from "../../mail/useUnreadTitle.js";
44
+ import UnlockBridge from "../../mail/outbox/UnlockBridge.js";
45
+ import NotificationCenter from "../../notifications/NotificationCenter.js";
46
+ import { useHeaderHeightRef } from "../../notifications/headerOffset.js";
47
+ import NotificationHistoryDialog from "../../notifications/NotificationHistoryDialog.js";
48
+ import { notifySessionExpired, setSignInUrl } from "../../notifications/apiErrors.js";
49
+ import { useUnseenErrorCount } from "../../notifications/useNotifications.js";
50
+ import { useSigningEnrollmentWatcher } from "../../signing/useSigningEnrollmentWatcher.js";
51
+ import { useCalendarReminders } from "../../calendar/useCalendarReminders.js";
52
+
53
+ /** How long sign-out waits for auth-server's logout before navigating anyway. */
54
+ export const LOGOUT_TIMEOUT_MS = 3_000;
55
+
56
+ /**
57
+ * Calls auth-server's logout (`POST /api/auth/logout`, cross-origin with credentials), which clears the auth
58
+ * cookie and invalidates the session's refresh token. Bounded by `LOGOUT_TIMEOUT_MS` and never rejects - a
59
+ * failure (unreachable server, CORS) must not keep the user from leaving.
60
+ */
61
+ async function logOutOfAuthServer(authServerUrl: string | undefined): Promise<void> {
62
+ if (!authServerUrl) {
63
+ return;
64
+ }
65
+ const controller = new AbortController();
66
+ const timer = setTimeout(() => controller.abort(), LOGOUT_TIMEOUT_MS);
67
+ try {
68
+ await authApiFetch(authServerUrl, "/auth/logout", { method: "POST", signal: controller.signal });
69
+ } catch {
70
+ // Navigate anyway - see this function's doc comment.
71
+ } finally {
72
+ clearTimeout(timer);
73
+ }
74
+ }
75
+
76
+ export type AppShellApp = "mail" | "calendar" | "contacts" | "tasks";
77
+
78
+ /** `"settings"` is a valid `active` value but deliberately has no entry in `APPS` below — Settings is
79
+ * reached via a `UserMenu` item, not a 5th rail icon (see `SettingsShell.tsx`), so it highlights no
80
+ * rail/tab icon at all; only the header title needs to account for it. Any other string is a plugin's
81
+ * `appRail` item id (see `PluginNav`). */
82
+ export type AppShellActive = AppShellApp | "settings" | (string & {});
83
+
84
+ export interface AppShellProps extends PluginNavProps {
85
+ /** Which icon in the rail is highlighted as the current app — `"settings"` highlights none, and a plugin
86
+ * app page passes its own `appRail` item id. */
87
+ active: AppShellActive;
88
+ /** Populated automatically by the framework from an authenticated request (e.g. a valid `jwt` cookie). */
89
+ userUid?: string;
90
+ /** auth-server's base URL, injected via the route's `fetchProps`. */
91
+ authServerUrl?: string;
92
+ /**
93
+ * `true` when this session is an admin "log in as user" impersonation (a `jwt_impersonator` cookie is
94
+ * present) — see `MailShell`'s original doc comment, unchanged now that this lives here. Drives the
95
+ * "you are viewing as this user — stop impersonating" banner below.
96
+ */
97
+ impersonating?: boolean;
98
+ /** Where `mailApi.ts`'s `stopImpersonating()` should call — see `MailShell`'s original doc comment. */
99
+ impersonationBaseUrl?: string;
100
+ /** `true` when the caller's JWT carries a trusted role — shows an "Admin Console" item in the user menu below. A token
101
+ * only carries one once elevated, so a real administrator with an ordinary session is `false` here; the user menu
102
+ * asks auth-server about them separately (see `UserMenu`'s `detectAdmin`). */
103
+ trusted?: boolean;
104
+ /** The role names the server treats as trusted (its `trusted_roles` config, injected via the route's `fetchProps`) -
105
+ * what that lookup looks for. Absent means the server's own default, `["admin"]`. */
106
+ trustedRoles?: string[];
107
+ /** The deployment's branding as the server rendered the page (its `branding` prop). Used until the frame's own fetch answers, so a custom header is there from the first paint - and the frame knows to drop its own title bar - instead of appearing (and moving everything) once the request returns. */
108
+ branding?: Branding;
109
+ /** The signed-in user's stored appearance preferences as the server rendered the page (its `appearance` prop), so the first paint already wears the theme and background - see `AppearanceProvider`. */
110
+ appearance?: unknown;
111
+ }
112
+
113
+ export interface AppDef {
114
+ id: AppShellApp;
115
+ href: string;
116
+ label: string;
117
+ icon: IconType;
118
+ }
119
+
120
+ export const APPS: AppDef[] = [
121
+ { id: "mail", href: APP_HREFS.mail, label: "Mail", icon: HiOutlineEnvelope },
122
+ { id: "calendar", href: APP_HREFS.calendar, label: "Calendar", icon: HiOutlineCalendarDays },
123
+ { id: "contacts", href: APP_HREFS.contacts, label: "Contacts", icon: HiOutlineUsers },
124
+ { id: "tasks", href: APP_HREFS.tasks, label: "Tasks", icon: HiOutlineClipboardDocumentList },
125
+ ];
126
+
127
+ /** Ids plugin `appRail` items can't take besides `APPS`' own - `"settings"` has no rail icon but is still a
128
+ * core `active` value. */
129
+ const RESERVED_APP_IDS = ["settings"];
130
+
131
+ /** `APPS` followed by the plugins' `appRail` items (generic icon), core ids winning - see `mergePluginNavItems`. */
132
+ export function appRailItems(pluginNav?: PluginNav): NavItem[] {
133
+ return mergePluginNavItems<NavItem>(
134
+ APPS,
135
+ pluginNav?.appRail,
136
+ ({ id, href, label }) => ({ id, href, label, icon: HiOutlinePuzzlePiece }),
137
+ RESERVED_APP_IDS,
138
+ );
139
+ }
140
+
141
+ /** What only the persistent frame (`AppRouter`) passes to the chrome it keeps mounted. */
142
+ export interface AppChromeProps extends AppShellProps {
143
+ /** Changes whenever the router shows a different page: the chrome then moves focus to the content, scrolls to its top,
144
+ * sets the document title and announces the page. Absent outside the router, when nothing does. */
145
+ routeKey?: string;
146
+ /** The router is loading the next page's code - the content is `aria-busy`. */
147
+ busy?: boolean;
148
+ /** A screen that takes over the window (`FrameTakeover`) is showing: the rail, header, banner and footer are hidden - not
149
+ * unmounted, so what is inside them (and the page in the content region) keeps its state. */
150
+ hideChrome?: boolean;
151
+ }
152
+
153
+ /**
154
+ * The persistent chrome shared by every webmail app (Mail, Calendar, Contacts, Tasks): a left icon rail for
155
+ * switching apps, a header with the current app's name and `UserMenu`, and the impersonation banner.
156
+ * Each app's own shell (e.g. `MailShell`) renders its own contextual sidebar + content as `children`, inside
157
+ * the area to the right of the icon rail and below the header.
158
+ *
159
+ * Rendered by `AppRouter`, once, for the life of the page, so that moving between apps replaces only `children` - see
160
+ * `AppShell` below for what a page's own shell renders instead.
161
+ */
162
+ export function AppChrome({
163
+ active,
164
+ userUid,
165
+ authServerUrl,
166
+ impersonating,
167
+ impersonationBaseUrl,
168
+ trusted,
169
+ trustedRoles,
170
+ branding: initialBranding,
171
+ appearance,
172
+ pluginNav,
173
+ routeKey,
174
+ busy,
175
+ hideChrome,
176
+ children,
177
+ }: PropsWithChildren<AppChromeProps>) {
178
+ const [stoppingImpersonation, setStoppingImpersonation] = useState(false);
179
+ // The keyboard shortcuts dialog: opened by `?`/Ctrl+/ (`GlobalShortcuts`) and by the account menu's item.
180
+ const [shortcutsOpen, setShortcutsOpen] = useState(false);
181
+ // The pop-up history ("Recent notifications" in the account menu). The pop-ups themselves are drawn by `NotificationCenter`, below.
182
+ const [historyOpen, setHistoryOpen] = useState(false);
183
+ // Only the count is read, so the whole frame does not render again for every pop-up that comes and goes.
184
+ const unseenErrors = useUnseenErrorCount();
185
+ // The title bar's height for the pop-up stack, which sticks just below the header (a branding header publishes its own - `FrameBrandingHeader`).
186
+ const headerRef = useHeaderHeightRef();
187
+ const signingOutRef = useRef(false);
188
+ const { branding: fetchedBranding, iconSrc: fetchedIconSrc } = useBranding();
189
+ // The server's copy until the fetch answers, so the frame's shape (a custom header replaces the title bar) never changes after the first paint.
190
+ const branding = fetchedBranding ?? initialBranding ?? null;
191
+ const iconSrc = fetchedBranding ? fetchedIconSrc : initialBranding?.iconUrl || initialBranding?.logoUrl || fetchedIconSrc;
192
+ // The custom header and footer, sanitized and with their `{USER_MENU}` / `{APP_TITLE}` placeholders (`undefined` until parsed, `null` when there is none).
193
+ const header = useBrandingHtml(branding?.headerHtml);
194
+ const footer = useBrandingHtml(branding?.footerHtml);
195
+ // The mailboxes, their folders and the one push connection live here, in the frame that stays mounted as the router swaps pages - so
196
+ // new-mail pop-ups, the folder counters and the tab title's unread count work in Calendar, Contacts, Tasks and Settings too, and moving
197
+ // between apps never opens a second socket (the server allows ten per user). `MailShell` reads them from `MailConnectionContext`. Outside
198
+ // the router (`AppShell` rendered as a page's own chrome: tests, plugin pages) it stays off, and a Mail shell owns its connection itself.
199
+ const inFrame = useInAppFrame();
200
+ const navigate = useNavigate();
201
+ const mail = useMailConnection({ userUid, enabled: inFrame, open: navigate });
202
+ // A signing certificate the user asked for is announced when it is issued (or fails), on whichever page they are - see the hook.
203
+ useSigningEnrollmentWatcher({ userUid, mailboxes: mail.mailboxes, enabled: inFrame });
204
+ // A meeting reminder pops up on whichever page they are - see the hook.
205
+ useCalendarReminders({ userUid, enabled: inFrame });
206
+
207
+ useRedirectIfUnauthenticated(userUid, authServerUrl);
208
+ // Any request this app makes that the server answers with a 401 - the session ended - raises one "Your session expired" pop-up with a
209
+ // Sign in action (see `notifySessionExpired()`), whichever request noticed first, a background refresh included.
210
+ useEffect(() => {
211
+ setSignInUrl(authServerUrl);
212
+ if (!userUid) {
213
+ return;
214
+ }
215
+ setApiUnauthorizedObserver(() => void notifySessionExpired());
216
+ return () => setApiUnauthorizedObserver(undefined);
217
+ }, [userUid, authServerUrl]);
218
+ // Mounted here, not scoped to Mail/Settings (the only shells that actually read unlocked keys),
219
+ // specifically so activity in *any* app resets the idle clock - see that hook's own doc comment.
220
+ useIdleKeyTimeout();
221
+
222
+ // An administrator on a server that hasn't finished first-run setup is sent to the setup wizard. The status
223
+ // check is admin-only, so it's only made for a trusted caller - everyone else would just get a 403 on every
224
+ // page load. Any failure is ignored.
225
+ useEffect(() => {
226
+ if (!userUid || impersonating || !trusted) {
227
+ return;
228
+ }
229
+ getSetupStatus()
230
+ .then((status) => {
231
+ if (status.required) {
232
+ window.location.href = "/admin/setup";
233
+ }
234
+ })
235
+ .catch(() => undefined);
236
+ }, [userUid, impersonating, trusted]);
237
+
238
+ // Another tab signing out (this app's `handleSignOut`, or the admin/escrow consoles' `signOutOfConsole()`)
239
+ // ended this session too - its auth cookie is gone - so this tab destroys its own unlocked keys and every
240
+ // local search index on the device, then leaves as well. The consoles have no local-index client of their
241
+ // own, so this is what actually removes the indexes after a console sign-out (the console also records a
242
+ // pending deletion, retried on the next mail load, in case no mail tab is open). `destroyAllLocalIndexes()`
243
+ // announces the sign-out on this same channel, which this tab then hears itself, so the ref is set first:
244
+ // each tab reacts once, and the tab that started the sign-out ignores its own announcement.
245
+ useEffect(() => {
246
+ if (!userUid || typeof BroadcastChannel === "undefined") {
247
+ return;
248
+ }
249
+ const channel = new BroadcastChannel(SIGN_OUT_CHANNEL);
250
+ channel.addEventListener("message", (event: MessageEvent<{ type?: string }>) => {
251
+ if (event.data?.type !== "sign-out" || signingOutRef.current) {
252
+ return;
253
+ }
254
+ signingOutRef.current = true;
255
+ // Compose windows must not ask "Leave site?" - that would let this forced navigation be cancelled.
256
+ markSigningOut();
257
+ destroyUnlockedKeys();
258
+ clearPinnedSignerCache();
259
+ clearAppearanceCache();
260
+ // Bounded by its own timeout and never rejects - awaited so navigating doesn't kill the Worker mid-delete.
261
+ void destroyAllLocalIndexes().then(() => {
262
+ window.location.href = authServerUrl ?? "/";
263
+ });
264
+ });
265
+ return () => channel.close();
266
+ }, [userUid, authServerUrl]);
267
+
268
+ async function handleSignOut() {
269
+ signingOutRef.current = true;
270
+ // Before flushing and navigating: compose windows then skip their "Leave site?" prompt, which could
271
+ // otherwise cancel the sign-out's own navigation.
272
+ markSigningOut();
273
+ // Unlocked private keys never outlive an explicit sign-out.
274
+ destroyUnlockedKeys();
275
+ // Trusted signer pins read from contacts don't outlive the session either.
276
+ clearPinnedSignerCache();
277
+ clearAppearanceCache();
278
+ // Open compose windows save edits still waiting on their autosave debounce while the session is still
279
+ // valid - logout invalidates it. Bounded the same way as logout itself, and never rejects.
280
+ await flushComposeDrafts(LOGOUT_TIMEOUT_MS);
281
+ // The Tier 2 local index MUST be destroyed on explicit logout, the same as unlocked keys themselves
282
+ // (spec §11). Destroys every index on this device (not only mailboxes opened this page load) and is
283
+ // awaited before navigating - a navigation tears down the Worker mid-delete otherwise.
284
+ // destroyAllLocalIndexes() is bounded by its own timeout and never rejects, so sign-out can't hang.
285
+ // In parallel, auth-server's logout clears the auth cookie and invalidates the session's refresh
286
+ // token - without it, "Sign Out" would only navigate away from a still-valid session.
287
+ await Promise.all([destroyAllLocalIndexes(), logOutOfAuthServer(authServerUrl)]);
288
+ window.location.href = authServerUrl ?? "/";
289
+ }
290
+
291
+ async function handleStopImpersonating() {
292
+ setStoppingImpersonation(true);
293
+ try {
294
+ await stopImpersonating(impersonationBaseUrl ?? "");
295
+ } catch {
296
+ // Navigate either way: a failed call leaves the impersonator cookie (and this banner) exactly as
297
+ // they were, so there's nothing else useful to show — matching this app's other network-error
298
+ // handling, which surfaces via a full reload rather than an inline retry affordance.
299
+ } finally {
300
+ window.location.href = "/admin";
301
+ }
302
+ }
303
+
304
+ // What the persistent frame (`AppRouter`) needs on top of a page that never changes: the document title follows the page, and
305
+ // after the router replaces the page the keyboard focus, the scroll position and a screen reader are told about it - a
306
+ // page load did all of that by itself. Nothing here runs for a page shown outside the router (`routeKey` is undefined).
307
+ const contentRef = useRef<HTMLDivElement>(null);
308
+ const [announcement, setAnnouncement] = useState("");
309
+ const firstRouteKeyRef = useRef(routeKey);
310
+ const pageLabel = active === "settings" ? "Settings" : appRailItems(pluginNav).find((app) => app.id === active)?.label;
311
+ useEffect(() => {
312
+ if (routeKey !== undefined) {
313
+ const brand = branding?.title || branding?.companyName || "RapidMX";
314
+ document.title = pageLabel ? `${brand}: ${pageLabel}` : brand;
315
+ }
316
+ }, [routeKey, pageLabel, branding]);
317
+ // After the title effect above, so a page change (which rewrites the title) is followed by the unread count going back in front of it.
318
+ useUnreadTitle(inboxUnreadTotal(mail.mailboxFolders, mail.folderCounts.counts), {
319
+ enabled: inFrame,
320
+ resetKey: `${routeKey}|${pageLabel}|${branding?.title}|${branding?.companyName}`,
321
+ });
322
+ useEffect(() => {
323
+ if (routeKey === undefined || routeKey === firstRouteKeyRef.current) {
324
+ return;
325
+ }
326
+ setAnnouncement(pageLabel ?? "");
327
+ contentRef.current?.focus({ preventScroll: true });
328
+ window.scrollTo(0, 0);
329
+ }, [routeKey]);
330
+
331
+ if (!userUid) {
332
+ return <div className="min-h-screen" />;
333
+ }
334
+
335
+ const apps = appRailItems(pluginNav);
336
+ // The header title: "settings" has no rail item, everything else is labelled by its own rail item.
337
+ const activeLabel = active === "settings" ? "Settings" : apps.find((app) => app.id === active)?.label;
338
+ // A custom header (`Branding.headerHtml`) replaces the app's own title bar and the icon at the top of the rail: it is the top of the app, and the
339
+ // account menu moves into it. While it is still being parsed it already counts, so the frame's shape doesn't change under the user.
340
+ const customHeader = header !== null;
341
+ // Where the one account menu lives: the header's `{USER_MENU}`, else the footer's, else a small cell at the header's right end - never lost.
342
+ const menuInHeader = !!header?.hasUserMenu;
343
+ const menuInFooter = customHeader && !!header && !menuInHeader && !!footer?.hasUserMenu;
344
+ const renderUserMenu = (placement: "down" | "up") => (
345
+ <UserMenu
346
+ userUid={userUid}
347
+ authServerUrl={authServerUrl}
348
+ onSignOut={handleSignOut}
349
+ // An impersonating administrator acts as the impersonated user, so the console link is hidden then.
350
+ showAdminLink={!!trusted && !impersonating}
351
+ detectAdmin={!trusted && !impersonating}
352
+ trustedRoles={trustedRoles}
353
+ showSettingsLink
354
+ showNotificationSettings
355
+ onShowShortcuts={() => setShortcutsOpen(true)}
356
+ onShowNotifications={() => setHistoryOpen(true)}
357
+ unseenErrors={unseenErrors}
358
+ placement={placement}
359
+ />
360
+ );
361
+
362
+ return (
363
+ // Mounted here, not scoped to Mail/Settings, for the same reason as useIdleKeyTimeout() above -
364
+ // ComposeWindow's sign/encrypt toggles and MessageDetailPane's encrypted-message view (both Mail)
365
+ // are today's only useUnlockPrompt() callers, but this needs to be available to any app shell.
366
+ // Asks the server for the user's appearance only in the persistent frame (every core page); a page that renders its own chrome (a plugin's) uses the
367
+ // `appearance` it was given and what this browser cached.
368
+ <AppearanceProvider userUid={userUid} initial={appearance} lookUp={inFrame}>
369
+ <ShortcutProvider>
370
+ <MailConnectionContext.Provider value={inFrame ? mail : null}>
371
+ <GlobalShortcuts authServerUrl={authServerUrl} onToggleHelp={() => setShortcutsOpen((open) => !open)} />
372
+ <ShortcutsDialog open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
373
+ <UnlockPromptProvider>
374
+ <UnlockBridge />
375
+ {/* An impersonating admin acts with the impersonated user's access, so their own trusted role
376
+ mustn't skip the per-mailbox checks. */}
377
+ <ComposeProvider userUid={userUid} trusted={!!trusted && !impersonating}>
378
+ <div className="rr-frame-bg min-h-screen flex flex-col">
379
+ {!hideChrome && customHeader && (
380
+ <FrameBrandingHeader
381
+ parsed={header}
382
+ userMenu={menuInHeader ? renderUserMenu("down") : undefined}
383
+ fallbackMenu={header && !menuInHeader && !menuInFooter ? renderUserMenu("down") : undefined}
384
+ appTitle={activeLabel}
385
+ />
386
+ )}
387
+ {impersonating && !hideChrome && (
388
+ <div className="h-10 shrink-0 bg-warning text-warning-contrast flex items-center justify-center gap-3 text-sm font-medium px-4">
389
+ <span>
390
+ You are viewing as <strong>{userUid}</strong>.
391
+ </span>
392
+ <button
393
+ type="button"
394
+ onClick={handleStopImpersonating}
395
+ disabled={stoppingImpersonation}
396
+ className="underline hover:no-underline disabled:opacity-60"
397
+ >
398
+ {stoppingImpersonation ? "Returning to admin…" : "Return to admin"}
399
+ </button>
400
+ </div>
401
+ )}
402
+ <div className="flex-1 flex min-h-0">
403
+ {!hideChrome && (
404
+ <nav
405
+ aria-label="Apps"
406
+ className={[
407
+ "hidden md:flex w-16 shrink-0 bg-surface border-r border-border flex-col items-center gap-1",
408
+ // Under a custom header the rail starts with the app icons; without one its own icon is flush with the top of the window.
409
+ customHeader ? "py-3" : "pb-3",
410
+ ].join(" ")}
411
+ >
412
+ {!customHeader && (
413
+ <RailIcon src={iconSrc} />
414
+ )}
415
+ {apps.map(({ id, href, label, icon: Icon }) => (
416
+ <a
417
+ key={id}
418
+ href={href}
419
+ aria-label={label}
420
+ aria-current={id === active ? "page" : undefined}
421
+ title={label}
422
+ className={[
423
+ "w-10 h-10 flex items-center justify-center rounded-sm",
424
+ id === active
425
+ ? "bg-primary/10 text-primary-dark"
426
+ : "text-text-muted hover:bg-surface-alt hover:text-text",
427
+ ].join(" ")}
428
+ >
429
+ <Icon size={20} aria-hidden="true" />
430
+ </a>
431
+ ))}
432
+ </nav>
433
+ )}
434
+ {!hideChrome && <BottomTabBar apps={apps} active={active} />}
435
+ <div className="flex-1 flex flex-col min-w-0">
436
+ {!hideChrome && !customHeader && (
437
+ <header ref={headerRef} className="rr-solid sticky top-0 z-30 h-16 shrink-0 bg-surface border-b border-border flex items-center justify-between gap-4 px-6">
438
+ <span className="font-display font-bold text-lg uppercase tracking-wide">{activeLabel}</span>
439
+ {renderUserMenu("down")}
440
+ </header>
441
+ )}
442
+ {/* The one pop-up stack for the whole app: right under the header row, so it never covers the account menu. */}
443
+ <NotificationCenter />
444
+ <div
445
+ ref={contentRef}
446
+ id="app-content"
447
+ tabIndex={-1}
448
+ aria-busy={busy || undefined}
449
+ className={["flex-1 flex min-h-0 outline-none", hideChrome ? "" : "pb-14 md:pb-0"].join(" ")}
450
+ >
451
+ {children}
452
+ </div>
453
+ </div>
454
+ </div>
455
+ {routeKey !== undefined && (
456
+ <div role="status" aria-live="polite" className="sr-only">
457
+ {announcement}
458
+ </div>
459
+ )}
460
+ {!hideChrome && <FrameBrandingFooter parsed={footer} userMenu={menuInFooter ? renderUserMenu("up") : undefined} appTitle={activeLabel} />}
461
+ </div>
462
+ </ComposeProvider>
463
+ </UnlockPromptProvider>
464
+ <NotificationHistoryDialog open={historyOpen} onClose={() => setHistoryOpen(false)} />
465
+ </MailConnectionContext.Provider>
466
+ </ShortcutProvider>
467
+ </AppearanceProvider>
468
+ );
469
+ }
470
+
471
+ /**
472
+ * What a page's own shell (`MailShell`, `CalendarShell`, ...) renders around its content. Outside the client-side router it
473
+ * is the whole `AppChrome`, as it always was. Inside it (`AppRouter`) the chrome is already mounted above the page - and stays
474
+ * mounted as the page is replaced - so this is only its children; everything it would have been given comes from the router
475
+ * frame instead (the props are the same for every page, and `active` is the route's).
476
+ */
477
+ export default function AppShell(props: PropsWithChildren<AppShellProps>) {
478
+ const inFrame = useInAppFrame();
479
+ return inFrame ? <>{props.children}</> : <AppChrome {...props} />;
480
+ }