@rapidmx/web-client 0.6.0 → 0.8.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 (79) hide show
  1. package/apps/shared/components/admin/settings/BrandingForm.tsx +398 -385
  2. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -112
  3. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +198 -152
  4. package/apps/shared/components/admin/settings/PluginsManager.tsx +1288 -1235
  5. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +9 -1
  6. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -290
  7. package/apps/shared/components/admin/setup/SetupWizard.tsx +443 -416
  8. package/apps/shared/components/layout/AppShell.tsx +288 -288
  9. package/apps/shared/components/mail/ConversationList.tsx +225 -33
  10. package/apps/shared/components/mail/ConversationThreadPane.tsx +434 -216
  11. package/apps/shared/components/mail/MailListToolbar.tsx +265 -0
  12. package/apps/shared/components/mail/MailSelectionBar.tsx +222 -0
  13. package/apps/shared/components/mail/MenuButton.tsx +384 -0
  14. package/apps/shared/components/mail/MessageDetailPane.tsx +280 -215
  15. package/apps/shared/components/mail/MoveToFolderDialog.tsx +263 -0
  16. package/apps/shared/components/mail/compose/ComposeContext.tsx +29 -2
  17. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1700 -1652
  18. package/apps/shared/components/mail/compose/RecipientInput.tsx +356 -0
  19. package/apps/shared/components/mail/compose/RichTextEditor.tsx +38 -3
  20. package/apps/shared/components/mail/compose/quotedBody.ts +100 -0
  21. package/apps/shared/components/mail/compose/recipients.ts +104 -0
  22. package/apps/shared/components/mail/labelMenu.tsx +278 -0
  23. package/apps/shared/components/mail/layout/MailShell.tsx +445 -420
  24. package/apps/shared/components/mail/listPreferences.ts +228 -0
  25. package/apps/shared/components/settings/layout/SettingsShell.tsx +0 -1
  26. package/apps/shared/styles/app.css +28 -5
  27. package/apps/www/index.tsx +1854 -1314
  28. package/apps/www/messages/[uid].tsx +5 -4
  29. package/dist/apps/shared/components/admin/settings/BrandingForm.d.ts +7 -3
  30. package/dist/apps/shared/components/admin/settings/BrandingForm.js +6 -5
  31. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.d.ts +4 -1
  32. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +2 -2
  33. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.d.ts +9 -2
  34. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.js +20 -4
  35. package/dist/apps/shared/components/admin/settings/PluginsManager.d.ts +8 -1
  36. package/dist/apps/shared/components/admin/settings/PluginsManager.js +33 -14
  37. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.d.ts +4 -1
  38. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.js +2 -2
  39. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.js +1 -1
  40. package/dist/apps/shared/components/admin/setup/SetupWizard.js +14 -10
  41. package/dist/apps/shared/components/mail/ConversationList.d.ts +42 -6
  42. package/dist/apps/shared/components/mail/ConversationList.js +84 -10
  43. package/dist/apps/shared/components/mail/ConversationThreadPane.d.ts +52 -13
  44. package/dist/apps/shared/components/mail/ConversationThreadPane.js +217 -60
  45. package/dist/apps/shared/components/mail/MailListToolbar.d.ts +55 -0
  46. package/dist/apps/shared/components/mail/MailListToolbar.js +149 -0
  47. package/dist/apps/shared/components/mail/MailSelectionBar.d.ts +59 -0
  48. package/dist/apps/shared/components/mail/MailSelectionBar.js +48 -0
  49. package/dist/apps/shared/components/mail/MenuButton.d.ts +71 -0
  50. package/dist/apps/shared/components/mail/MenuButton.js +211 -0
  51. package/dist/apps/shared/components/mail/MessageDetailPane.d.ts +27 -19
  52. package/dist/apps/shared/components/mail/MessageDetailPane.js +126 -129
  53. package/dist/apps/shared/components/mail/MoveToFolderDialog.d.ts +57 -0
  54. package/dist/apps/shared/components/mail/MoveToFolderDialog.js +138 -0
  55. package/dist/apps/shared/components/mail/compose/ComposeContext.d.ts +16 -1
  56. package/dist/apps/shared/components/mail/compose/ComposeContext.js +3 -1
  57. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +52 -20
  58. package/dist/apps/shared/components/mail/compose/RecipientInput.d.ts +36 -0
  59. package/dist/apps/shared/components/mail/compose/RecipientInput.js +203 -0
  60. package/dist/apps/shared/components/mail/compose/RichTextEditor.d.ts +10 -1
  61. package/dist/apps/shared/components/mail/compose/RichTextEditor.js +21 -3
  62. package/dist/apps/shared/components/mail/compose/quotedBody.d.ts +37 -0
  63. package/dist/apps/shared/components/mail/compose/quotedBody.js +85 -0
  64. package/dist/apps/shared/components/mail/compose/recipients.d.ts +24 -0
  65. package/dist/apps/shared/components/mail/compose/recipients.js +87 -0
  66. package/dist/apps/shared/components/mail/labelMenu.d.ts +97 -0
  67. package/dist/apps/shared/components/mail/labelMenu.js +134 -0
  68. package/dist/apps/shared/components/mail/layout/MailShell.d.ts +8 -0
  69. package/dist/apps/shared/components/mail/layout/MailShell.js +15 -3
  70. package/dist/apps/shared/components/mail/listPreferences.d.ts +101 -0
  71. package/dist/apps/shared/components/mail/listPreferences.js +186 -0
  72. package/dist/apps/shared/components/settings/layout/SettingsShell.js +0 -1
  73. package/dist/apps/shared/styles/app.css +28 -5
  74. package/dist/apps/www/index.js +506 -112
  75. package/dist/apps/www/messages/[uid].js +2 -3
  76. package/package.json +2 -2
  77. package/apps/www/settings/focused-inbox/index.tsx +0 -150
  78. package/dist/apps/www/settings/focused-inbox/index.d.ts +0 -4
  79. package/dist/apps/www/settings/focused-inbox/index.js +0 -71
@@ -1,420 +1,445 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import React, { createContext, PropsWithChildren, ReactNode, useContext, useEffect, useMemo, useState } from "react";
6
- import { HiOutlineBars3 } from "react-icons/hi2";
7
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
- import Drawer from "@rapidmx/react-shared/components/overlays/Drawer.js";
9
- import { Folder, Mailbox, listFolders, listMailboxes } from "@rapidmx/react-shared/mail/mailApi.js";
10
- import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
11
- import Skeleton, { SkeletonList } from "@rapidmx/react-shared/components/feedback/Skeleton.js";
12
- import AppShell, { AppShellProps } from "../../layout/AppShell.js";
13
- import KeyEnrollmentGate from "../../layout/KeyEnrollmentGate.js";
14
- import MailboxProvisioning from "../../layout/MailboxProvisioning.js";
15
- import { useCompose } from "../compose/ComposeContext.js";
16
- import LocalIndexLifecycle from "../../../search/LocalIndexLifecycle.js";
17
-
18
- export type MailShellProps = Omit<AppShellProps, "active">;
19
-
20
- /** One mailbox's own mail folders (already filtered to `MAIL_FOLDER_TYPES` and unsorted) - one entry per
21
- * mailbox in `mailboxes`, fetched in parallel so every accessible mailbox's folder tree can render
22
- * simultaneously (see `MailShell`'s own doc comment on why this replaced the old single-mailbox `folders`
23
- * field). `error` is set (and `folders` left empty) for a mailbox whose own `listFolders()` call failed -
24
- * one mailbox's fetch failure must never blank out every other mailbox's section. */
25
- export interface MailboxFolders {
26
- mailbox: Mailbox;
27
- folders: Folder[];
28
- error?: string;
29
- }
30
-
31
- /** The well-known mail folder types an "aggregate" pseudo-folder can merge across every accessible
32
- * mailbox - a fixed, small set: `outbox` is deliberately excluded (transient per-mailbox send-queue
33
- * state, not a "merge across mailboxes" concept), and there's no aggregate concept for `calendar`/
34
- * `contacts`/`tasks`/`notes`/`user` folders (Mail's own sidebar already excludes those - see
35
- * `MAIL_FOLDER_TYPES`). */
36
- export const AGGREGATE_FOLDER_TYPES = ["inbox", "sent_items", "drafts", "deleted_items", "junk"] as const;
37
- export type AggregateFolderType = (typeof AGGREGATE_FOLDER_TYPES)[number];
38
-
39
- function isAggregateFolderType(value: string | null): value is AggregateFolderType {
40
- return !!value && (AGGREGATE_FOLDER_TYPES as readonly string[]).includes(value);
41
- }
42
-
43
- export interface MailShellContextValue {
44
- /** The mailbox currently selected (`?mailboxUid=`) - `undefined` while an aggregate pseudo-folder is
45
- * active instead (`aggregateFolderType` set), since there's no single mailbox to speak of then. */
46
- mailboxUid?: string;
47
- /** The folder currently selected (`?folderUid=`, or the selected mailbox's Inbox) - `undefined` in
48
- * aggregate mode, for the same reason. */
49
- folderUid?: string;
50
- /** Set only when an aggregate pseudo-folder (`?aggregate=inbox` etc.) is selected instead of a real,
51
- * single mailbox+folder - mutually exclusive with `mailboxUid`/`folderUid` above. */
52
- aggregateFolderType?: AggregateFolderType;
53
- mailboxes: Mailbox[];
54
- /** Every accessible mailbox's own mail folders - replaces the old single-mailbox `folders: Folder[]`
55
- * now that every mailbox's tree renders at once (see `MailboxFolders`'s own doc comment). */
56
- mailboxFolders: MailboxFolders[];
57
- }
58
-
59
- const MailShellContext = createContext<MailShellContextValue>({ mailboxes: [], mailboxFolders: [] });
60
-
61
- /** Reads the mailbox/folder a page is currently showing, as resolved by the enclosing `MailShell`. */
62
- export function useMailShell(): MailShellContextValue {
63
- return useContext(MailShellContext);
64
- }
65
-
66
- const FOLDER_LABELS: Record<string, string> = {
67
- inbox: "Inbox",
68
- sent_items: "Sent Items",
69
- drafts: "Drafts",
70
- outbox: "Outbox",
71
- junk: "Junk Email",
72
- archive: "Archive",
73
- deleted_items: "Deleted Items",
74
- };
75
-
76
- /** Well-known folders sort first, in Gmail/Outlook's conventional order; anything else (incl. `user`) sorts after, alphabetically. */
77
- const FOLDER_ORDER = ["inbox", "drafts", "outbox", "sent_items", "junk", "archive", "deleted_items"];
78
-
79
- /**
80
- * A mailbox's `calendar`/`contacts`/`tasks`/`notes` folders back their own dedicated apps (see
81
- * `CalendarShell`/`ContactsShell`/`TasksShell`), not Mail — `listFolders()` returns every well-known
82
- * folder for the mailbox regardless of which app owns it, so Mail's own folder tree must filter down
83
- * to just the mail ones itself, or those other apps' folders leak into this sidebar.
84
- */
85
- const MAIL_FOLDER_TYPES = new Set([...FOLDER_ORDER, "user"]);
86
-
87
- function folderSortKey(folder: Folder): number {
88
- const idx = FOLDER_ORDER.indexOf(folder.type);
89
- return idx === -1 ? FOLDER_ORDER.length : idx;
90
- }
91
-
92
- function sortedFoldersOf(folders: Folder[]): Folder[] {
93
- return [...folders].sort((a, b) => folderSortKey(a) - folderSortKey(b) || a.name.localeCompare(b.name));
94
- }
95
-
96
- function aggregateUnreadCount(mailboxFolders: MailboxFolders[], type: AggregateFolderType): number {
97
- return mailboxFolders.reduce((total, mf) => total + (mf.folders.find((f) => f.type === type)?.unreadCount ?? 0), 0);
98
- }
99
-
100
- type Status = "checking" | "error" | "ready";
101
-
102
- /** Page size of the one `listMailboxes()` call this shell makes. */
103
- export const MAILBOX_LIST_LIMIT = 100;
104
-
105
- /**
106
- * A separate component (not inlined into `MailShell`'s own render) so `useCompose()` resolves against
107
- * `ComposeProvider` correctly: that provider is rendered *inside* the `AppShell` that `MailShell` itself
108
- * returns, i.e. a descendant of `MailShell`, not an ancestor — a hook call made directly in `MailShell`'s
109
- * own function body would see only whatever context exists *above* `MailShell`, never a provider one of
110
- * its own descendants creates. This button, rendered as part of `AppShell`'s `children`, sits correctly
111
- * inside that subtree.
112
- *
113
- * Opens with no mailbox: a fresh message defaults to the caller's own mailbox, and the compose window's
114
- * own From field is where the sender is chosen.
115
- */
116
- function ComposeButton() {
117
- const { openCompose } = useCompose();
118
- return (
119
- <button
120
- type="button"
121
- onClick={() => openCompose({})}
122
- className="block text-center w-full py-2.5 px-4 rounded-sm font-semibold text-sm bg-primary text-white hover:bg-primary-dark"
123
- >
124
- Compose
125
- </button>
126
- );
127
- }
128
-
129
- /**
130
- * Mail's own contextual sidebar (every accessible mailbox's own folder tree, plus a merged "All Mailboxes"
131
- * aggregate section) + content area, rendered inside the shared `AppShell` chrome (icon rail, header,
132
- * impersonation banner — see that component). There is no client-side router in this framework (see
133
- * `ReactRoute`'s file-convention resolver) — the selected mailbox/folder (or aggregate pseudo-folder) live
134
- * in the URL's `?mailboxUid=`/`?folderUid=`/`?aggregate=` query params, read once on mount (never during
135
- * the initial render itself, matching every other query-param reader in this codebase — e.g.
136
- * `apps/admin/quarantine`'s `readMailboxUid()` — so the server-rendered and just-hydrated client markup
137
- * match).
138
- *
139
- * Every accessible mailbox's folder tree renders at once - there is no "switch mailbox" affordance
140
- * anymore (the mailbox `<select>` this shell used to have is gone) - so a single-mailbox user sees zero
141
- * behavior change from before this, and a multi-mailbox user sees every mailbox's folders (and the new
142
- * aggregate section) simultaneously, matching the shared-mailbox feature's own "display as a separate set
143
- * of folders" requirement.
144
- */
145
- export default function MailShell({
146
- userUid,
147
- authServerUrl,
148
- impersonating,
149
- impersonationBaseUrl,
150
- trusted,
151
- pluginNav,
152
- children,
153
- }: PropsWithChildren<MailShellProps>) {
154
- const [status, setStatus] = useState<Status>("checking");
155
- const [error, setError] = useState<string | null>(null);
156
- const [mailboxes, setMailboxes] = useState<Mailbox[]>([]);
157
- const [mailboxFolders, setMailboxFolders] = useState<MailboxFolders[]>([]);
158
- const [foldersLoading, setFoldersLoading] = useState(true);
159
- const [requestedMailboxUid, setRequestedMailboxUid] = useState<string | null>(null);
160
- const [requestedFolderUid, setRequestedFolderUid] = useState<string | null>(null);
161
- const [requestedAggregateType, setRequestedAggregateType] = useState<string | null>(null);
162
- const [drawerOpen, setDrawerOpen] = useState(false);
163
-
164
- useEffect(() => {
165
- const params = new URLSearchParams(window.location.search);
166
- setRequestedMailboxUid(params.get("mailboxUid"));
167
- setRequestedFolderUid(params.get("folderUid"));
168
- setRequestedAggregateType(params.get("aggregate"));
169
- }, []);
170
-
171
- useEffect(() => {
172
- if (!userUid) {
173
- return;
174
- }
175
- listMailboxes({ limit: MAILBOX_LIST_LIMIT })
176
- .then((result) => {
177
- setMailboxes(result);
178
- setStatus("ready");
179
- })
180
- .catch((err) => {
181
- setError(err instanceof ApiRequestError ? err.message : "Could not load your mailboxes.");
182
- setStatus("error");
183
- });
184
- }, [userUid]);
185
-
186
- const aggregateFolderType: AggregateFolderType | undefined = isAggregateFolderType(requestedAggregateType)
187
- ? requestedAggregateType
188
- : undefined;
189
-
190
- const mailboxUid: string | undefined = aggregateFolderType
191
- ? undefined
192
- : (requestedMailboxUid && mailboxes.some((mb) => mb.uid === requestedMailboxUid) ? requestedMailboxUid : undefined) ??
193
- mailboxes[0]?.uid;
194
-
195
- // Fans out one listFolders() call per accessible mailbox in parallel - each call catches its own
196
- // failure into an MailboxFolders.error rather than letting Promise.all reject, so one mailbox's fetch
197
- // failure renders that section's own inline Alert instead of blanking out every other mailbox's
198
- // folder tree.
199
- useEffect(() => {
200
- if (mailboxes.length === 0) {
201
- // Deliberately leaves foldersLoading as-is: this also runs once before listMailboxes() has
202
- // resolved, and clearing it here would briefly render an empty sidebar the moment mailboxes
203
- // arrive, before their folders do. A genuinely mailbox-less caller gets MailboxProvisioning.
204
- setMailboxFolders([]);
205
- return;
206
- }
207
- setFoldersLoading(true);
208
- void Promise.all(
209
- mailboxes.map((mailbox) =>
210
- listFolders(mailbox.uid)
211
- .then((result): MailboxFolders => ({ mailbox, folders: result.filter((f) => MAIL_FOLDER_TYPES.has(f.type)) }))
212
- .catch(
213
- (err): MailboxFolders => ({
214
- mailbox,
215
- folders: [],
216
- error: err instanceof ApiRequestError ? err.message : "Could not load folders.",
217
- }),
218
- ),
219
- ),
220
- )
221
- .then(setMailboxFolders)
222
- .finally(() => setFoldersLoading(false));
223
- }, [mailboxes]);
224
-
225
- const selectedMailboxFolders = mailboxFolders.find((mf) => mf.mailbox.uid === mailboxUid)?.folders ?? [];
226
- const folderUid: string | undefined = aggregateFolderType
227
- ? undefined
228
- : (requestedFolderUid && selectedMailboxFolders.some((f) => f.uid === requestedFolderUid) ? requestedFolderUid : undefined) ??
229
- selectedMailboxFolders.find((f) => f.type === "inbox")?.uid;
230
-
231
- // The mailbox `KeyEnrollmentGate`/`LocalIndexLifecycle`/`ComposeButton` treat as "the" mailbox when
232
- // there's no single selected one to use (aggregate mode) - the caller's own owned mailbox if they
233
- // have one, else whichever accessible mailbox happens to be first. See MailShell's own doc comment on
234
- // this being an accepted limitation: an aggregate-view message from a *different*, not-yet-visited
235
- // mailbox may still need that mailbox's own folder view opened directly to unlock/decrypt it.
236
- const defaultMailboxUid = mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
237
- const activeMailboxUid = mailboxUid ?? defaultMailboxUid;
238
-
239
- const contextValue = useMemo<MailShellContextValue>(
240
- () => ({ mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders }),
241
- [mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders],
242
- );
243
-
244
- // A full-screen takeover, not nested inside the rest of the app's chrome — there's nothing else for a
245
- // mailbox-less caller to do here yet, so the icon rail/header/folder tree don't render at all. Checks
246
- // `mailboxes.length` directly (not `!mailboxUid`) since `mailboxUid` is legitimately undefined in
247
- // aggregate mode even with mailboxes present.
248
- if (userUid && status === "ready" && mailboxes.length === 0) {
249
- return <MailboxProvisioning />;
250
- }
251
-
252
- let inner: ReactNode = null;
253
- if (userUid && status === "checking") {
254
- // Renders immediately (no network round trip needed) so switching into Mail never shows a blank
255
- // pane while `listMailboxes()` is in flight — the outline below mirrors the real sidebar's shape.
256
- inner = (
257
- <aside className="w-64 shrink-0 bg-surface border-r border-border flex flex-col p-3 gap-4">
258
- <Skeleton height="h-9" className="rounded-sm" />
259
- <SkeletonList count={6} />
260
- </aside>
261
- );
262
- } else if (userUid && status === "error") {
263
- inner = (
264
- <div className="flex-1 flex items-center justify-center p-8">
265
- <div className="w-full max-w-md">
266
- <Alert>{error}</Alert>
267
- </div>
268
- </div>
269
- );
270
- } else if (userUid && status === "ready") {
271
- // A function, not a plain JSX constant — it's rendered twice (desktop `<aside>` + mobile
272
- // `Drawer`), possibly *simultaneously* mounted (the aside is only CSS-hidden below `md`, not
273
- // unmounted).
274
- const sidebarContent = () => (
275
- <>
276
- <div className="p-3">
277
- <ComposeButton />
278
- </div>
279
- {foldersLoading ? (
280
- <div className="flex-1 overflow-y-auto px-3 pb-3">
281
- <SkeletonList count={6} className="pt-1" />
282
- </div>
283
- ) : (
284
- <nav className="flex-1 overflow-y-auto px-3 pb-3 flex flex-col gap-3">
285
- {mailboxes.length > 1 && (
286
- <div>
287
- <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5">
288
- All Mailboxes
289
- </div>
290
- <div className="flex flex-col gap-0.5">
291
- {AGGREGATE_FOLDER_TYPES.map((type) => {
292
- const unread = aggregateUnreadCount(mailboxFolders, type);
293
- return (
294
- <a
295
- key={type}
296
- href={`/?aggregate=${encodeURIComponent(type)}`}
297
- className={[
298
- "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
299
- aggregateFolderType === type
300
- ? "bg-primary/10 text-primary-dark font-semibold"
301
- : "text-text hover:bg-surface-alt",
302
- ].join(" ")}
303
- >
304
- <span>{FOLDER_LABELS[type]}</span>
305
- {unread > 0 && (
306
- <span className="text-xs font-bold rounded-pill py-0.5 px-1.5 bg-surface-alt text-text-muted">
307
- {unread}
308
- </span>
309
- )}
310
- </a>
311
- );
312
- })}
313
- </div>
314
- </div>
315
- )}
316
- {mailboxFolders.map(({ mailbox, folders, error: mailboxError }) => (
317
- <div key={mailbox.uid}>
318
- <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5 truncate">
319
- {mailbox.displayName}
320
- {mailbox.ownerUserUid ? "" : " (shared)"}
321
- </div>
322
- {mailboxError && (
323
- <div className="px-2.5 pb-1">
324
- <Alert>{mailboxError}</Alert>
325
- </div>
326
- )}
327
- <div className="flex flex-col gap-0.5">
328
- {sortedFoldersOf(folders).map((folder) => (
329
- <a
330
- key={folder.uid}
331
- href={`/?mailboxUid=${encodeURIComponent(mailbox.uid)}&folderUid=${encodeURIComponent(folder.uid)}`}
332
- className={[
333
- "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
334
- folder.uid === folderUid
335
- ? "bg-primary/10 text-primary-dark font-semibold"
336
- : "text-text hover:bg-surface-alt",
337
- ].join(" ")}
338
- >
339
- <span>{FOLDER_LABELS[folder.type] ?? folder.name}</span>
340
- {folder.unreadCount > 0 && (
341
- <span className="text-xs font-bold rounded-pill py-0.5 px-1.5 bg-surface-alt text-text-muted">
342
- {folder.unreadCount}
343
- </span>
344
- )}
345
- </a>
346
- ))}
347
- </div>
348
- </div>
349
- ))}
350
- </nav>
351
- )}
352
- </>
353
- );
354
-
355
- inner = (
356
- <>
357
- <aside className="hidden md:flex w-64 shrink-0 bg-surface border-r border-border flex-col">{sidebarContent()}</aside>
358
- <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} title="Folders">
359
- <div className="flex flex-col">{sidebarContent()}</div>
360
- </Drawer>
361
- <main className="flex-1 min-w-0 overflow-y-auto">
362
- <button
363
- type="button"
364
- className="md:hidden m-3 w-9 h-9 flex items-center justify-center rounded-sm text-text-muted hover:bg-surface-alt hover:text-text"
365
- aria-label="Open folders"
366
- onClick={() => setDrawerOpen(true)}
367
- >
368
- <HiOutlineBars3 size={20} aria-hidden="true" />
369
- </button>
370
- <MailShellContext.Provider value={contextValue}>{children}</MailShellContext.Provider>
371
- </main>
372
- </>
373
- );
374
- }
375
-
376
- // Wraps AppShell unconditionally, at a stable tree position regardless of whether mailboxUid has
377
- // resolved yet - KeyEnrollmentGate itself passes `children` through untouched until a real
378
- // mailboxUid is supplied (see its own doc comment). Wrapping only once ready (a conditional tree
379
- // position) would make AppShell itself remount the moment mailboxUid resolves, tearing down
380
- // whatever state/effects it had already started (confirmed by direct reproduction: the
381
- // impersonation banner's own internal state was lost exactly at that transition).
382
- const activeMailbox = mailboxes.find((mb) => mb.uid === activeMailboxUid);
383
- return (
384
- <KeyEnrollmentGate
385
- mailboxUid={activeMailboxUid}
386
- mailboxAddress={activeMailbox?.primarySmtpAddress}
387
- mailboxKeys={activeMailbox?.keys}
388
- // Unlocking is only actually required to sign/encrypt a compose, read an already-encrypted
389
- // message, or change encryption settings - not merely to open Mail. Those specific call sites
390
- // (ComposeWindow, MessageDetailPane) request an unlock on demand via useUnlockPrompt() instead.
391
- // First-time provisioning (a mailbox with no vault at all yet) still always blocks - see this
392
- // prop's own doc comment on KeyEnrollmentGateProps.
393
- blocking={false}
394
- // A shared/delegated mailbox the caller doesn't own is never provisioned from here - its keys
395
- // belong to its owner (or its admins), not to whoever happens to open it first - and neither is
396
- // the impersonated user's own mailbox: an administrator must never choose its password/recovery codes.
397
- canProvision={!impersonating && activeMailbox?.ownerUserUid === userUid}
398
- >
399
- <LocalIndexLifecycle
400
- mailboxUid={activeMailboxUid}
401
- mailboxKeys={activeMailbox?.keys}
402
- folders={mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? []}
403
- // A full page may be truncated - pruning against it would delete indexes of accessible mailboxes
404
- // beyond the limit, so it's only trusted as the complete list when it came back short.
405
- accessibleMailboxUids={status === "ready" && mailboxes.length < MAILBOX_LIST_LIMIT ? mailboxes.map((mb) => mb.uid) : undefined}
406
- />
407
- <AppShell
408
- active="mail"
409
- userUid={userUid}
410
- authServerUrl={authServerUrl}
411
- impersonating={impersonating}
412
- impersonationBaseUrl={impersonationBaseUrl}
413
- trusted={trusted}
414
- pluginNav={pluginNav}
415
- >
416
- {inner}
417
- </AppShell>
418
- </KeyEnrollmentGate>
419
- );
420
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import React, { createContext, PropsWithChildren, ReactNode, useCallback, useContext, useEffect, useMemo, useState } from "react";
6
+ import { HiOutlineBars3 } from "react-icons/hi2";
7
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
+ import Drawer from "@rapidmx/react-shared/components/overlays/Drawer.js";
9
+ import { Folder, Mailbox, listFolders, listMailboxes } from "@rapidmx/react-shared/mail/mailApi.js";
10
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
11
+ import Skeleton, { SkeletonList } from "@rapidmx/react-shared/components/feedback/Skeleton.js";
12
+ import AppShell, { AppShellProps } from "../../layout/AppShell.js";
13
+ import KeyEnrollmentGate from "../../layout/KeyEnrollmentGate.js";
14
+ import MailboxProvisioning from "../../layout/MailboxProvisioning.js";
15
+ import { useCompose } from "../compose/ComposeContext.js";
16
+ import LocalIndexLifecycle from "../../../search/LocalIndexLifecycle.js";
17
+
18
+ export type MailShellProps = Omit<AppShellProps, "active">;
19
+
20
+ /** One mailbox's own mail folders (already filtered to `MAIL_FOLDER_TYPES` and unsorted) - one entry per
21
+ * mailbox in `mailboxes`, fetched in parallel so every accessible mailbox's folder tree can render
22
+ * simultaneously (see `MailShell`'s own doc comment on why this replaced the old single-mailbox `folders`
23
+ * field). `error` is set (and `folders` left empty) for a mailbox whose own `listFolders()` call failed -
24
+ * one mailbox's fetch failure must never blank out every other mailbox's section. */
25
+ export interface MailboxFolders {
26
+ mailbox: Mailbox;
27
+ folders: Folder[];
28
+ error?: string;
29
+ }
30
+
31
+ /** The well-known mail folder types an "aggregate" pseudo-folder can merge across every accessible
32
+ * mailbox - a fixed, small set: `outbox` is deliberately excluded (transient per-mailbox send-queue
33
+ * state, not a "merge across mailboxes" concept), and there's no aggregate concept for `calendar`/
34
+ * `contacts`/`tasks`/`notes`/`user` folders (Mail's own sidebar already excludes those - see
35
+ * `MAIL_FOLDER_TYPES`). */
36
+ export const AGGREGATE_FOLDER_TYPES = ["inbox", "sent_items", "drafts", "deleted_items", "junk"] as const;
37
+ export type AggregateFolderType = (typeof AGGREGATE_FOLDER_TYPES)[number];
38
+
39
+ function isAggregateFolderType(value: string | null): value is AggregateFolderType {
40
+ return !!value && (AGGREGATE_FOLDER_TYPES as readonly string[]).includes(value);
41
+ }
42
+
43
+ export interface MailShellContextValue {
44
+ /** The mailbox currently selected (`?mailboxUid=`) - `undefined` while an aggregate pseudo-folder is
45
+ * active instead (`aggregateFolderType` set), since there's no single mailbox to speak of then. */
46
+ mailboxUid?: string;
47
+ /** The folder currently selected (`?folderUid=`, or the selected mailbox's Inbox) - `undefined` in
48
+ * aggregate mode, for the same reason. */
49
+ folderUid?: string;
50
+ /** Set only when an aggregate pseudo-folder (`?aggregate=inbox` etc.) is selected instead of a real,
51
+ * single mailbox+folder - mutually exclusive with `mailboxUid`/`folderUid` above. */
52
+ aggregateFolderType?: AggregateFolderType;
53
+ mailboxes: Mailbox[];
54
+ /** Every accessible mailbox's own mail folders - replaces the old single-mailbox `folders: Folder[]`
55
+ * now that every mailbox's tree renders at once (see `MailboxFolders`'s own doc comment). */
56
+ mailboxFolders: MailboxFolders[];
57
+ /**
58
+ * Adds a folder a page has just created (the Move to prompt's "New folder") to the tree this shell
59
+ * already fetched, so it appears in the sidebar and in every folder picker without a reload - this
60
+ * framework has no client-side router, so a reload is a whole page load.
61
+ *
62
+ * A no-op on the default context value, which is only ever read outside a real shell.
63
+ */
64
+ onFolderCreated: (folder: Folder) => void;
65
+ }
66
+
67
+ const MailShellContext = createContext<MailShellContextValue>({
68
+ mailboxes: [],
69
+ mailboxFolders: [],
70
+ onFolderCreated: () => undefined,
71
+ });
72
+
73
+ /** Reads the mailbox/folder a page is currently showing, as resolved by the enclosing `MailShell`. */
74
+ export function useMailShell(): MailShellContextValue {
75
+ return useContext(MailShellContext);
76
+ }
77
+
78
+ const FOLDER_LABELS: Record<string, string> = {
79
+ inbox: "Inbox",
80
+ sent_items: "Sent Items",
81
+ drafts: "Drafts",
82
+ outbox: "Outbox",
83
+ junk: "Junk Email",
84
+ archive: "Archive",
85
+ deleted_items: "Deleted Items",
86
+ };
87
+
88
+ /** Well-known folders sort first, in Gmail/Outlook's conventional order; anything else (incl. `user`) sorts after, alphabetically. */
89
+ const FOLDER_ORDER = ["inbox", "drafts", "outbox", "sent_items", "junk", "archive", "deleted_items"];
90
+
91
+ /**
92
+ * A mailbox's `calendar`/`contacts`/`tasks`/`notes` folders back their own dedicated apps (see
93
+ * `CalendarShell`/`ContactsShell`/`TasksShell`), not Mail — `listFolders()` returns every well-known
94
+ * folder for the mailbox regardless of which app owns it, so Mail's own folder tree must filter down
95
+ * to just the mail ones itself, or those other apps' folders leak into this sidebar.
96
+ */
97
+ const MAIL_FOLDER_TYPES = new Set([...FOLDER_ORDER, "user"]);
98
+
99
+ function folderSortKey(folder: Folder): number {
100
+ const idx = FOLDER_ORDER.indexOf(folder.type);
101
+ return idx === -1 ? FOLDER_ORDER.length : idx;
102
+ }
103
+
104
+ function sortedFoldersOf(folders: Folder[]): Folder[] {
105
+ return [...folders].sort((a, b) => folderSortKey(a) - folderSortKey(b) || a.name.localeCompare(b.name));
106
+ }
107
+
108
+ function aggregateUnreadCount(mailboxFolders: MailboxFolders[], type: AggregateFolderType): number {
109
+ return mailboxFolders.reduce((total, mf) => total + (mf.folders.find((f) => f.type === type)?.unreadCount ?? 0), 0);
110
+ }
111
+
112
+ type Status = "checking" | "error" | "ready";
113
+
114
+ /** Page size of the one `listMailboxes()` call this shell makes. */
115
+ export const MAILBOX_LIST_LIMIT = 100;
116
+
117
+ /**
118
+ * A separate component (not inlined into `MailShell`'s own render) so `useCompose()` resolves against
119
+ * `ComposeProvider` correctly: that provider is rendered *inside* the `AppShell` that `MailShell` itself
120
+ * returns, i.e. a descendant of `MailShell`, not an ancestor — a hook call made directly in `MailShell`'s
121
+ * own function body would see only whatever context exists *above* `MailShell`, never a provider one of
122
+ * its own descendants creates. This button, rendered as part of `AppShell`'s `children`, sits correctly
123
+ * inside that subtree.
124
+ *
125
+ * Opens with no mailbox: a fresh message defaults to the caller's own mailbox, and the compose window's
126
+ * own From field is where the sender is chosen.
127
+ */
128
+ function ComposeButton() {
129
+ const { openCompose } = useCompose();
130
+ return (
131
+ <button
132
+ type="button"
133
+ onClick={() => openCompose({})}
134
+ className="block text-center w-full py-2.5 px-4 rounded-sm font-semibold text-sm bg-primary text-white hover:bg-primary-dark"
135
+ >
136
+ Compose
137
+ </button>
138
+ );
139
+ }
140
+
141
+ /**
142
+ * Mail's own contextual sidebar (every accessible mailbox's own folder tree, plus a merged "All Mailboxes"
143
+ * aggregate section) + content area, rendered inside the shared `AppShell` chrome (icon rail, header,
144
+ * impersonation banner — see that component). There is no client-side router in this framework (see
145
+ * `ReactRoute`'s file-convention resolver) — the selected mailbox/folder (or aggregate pseudo-folder) live
146
+ * in the URL's `?mailboxUid=`/`?folderUid=`/`?aggregate=` query params, read once on mount (never during
147
+ * the initial render itself, matching every other query-param reader in this codebase — e.g.
148
+ * `apps/admin/quarantine`'s `readMailboxUid()` — so the server-rendered and just-hydrated client markup
149
+ * match).
150
+ *
151
+ * Every accessible mailbox's folder tree renders at once - there is no "switch mailbox" affordance
152
+ * anymore (the mailbox `<select>` this shell used to have is gone) - so a single-mailbox user sees zero
153
+ * behavior change from before this, and a multi-mailbox user sees every mailbox's folders (and the new
154
+ * aggregate section) simultaneously, matching the shared-mailbox feature's own "display as a separate set
155
+ * of folders" requirement.
156
+ */
157
+ export default function MailShell({
158
+ userUid,
159
+ authServerUrl,
160
+ impersonating,
161
+ impersonationBaseUrl,
162
+ trusted,
163
+ pluginNav,
164
+ children,
165
+ }: PropsWithChildren<MailShellProps>) {
166
+ const [status, setStatus] = useState<Status>("checking");
167
+ const [error, setError] = useState<string | null>(null);
168
+ const [mailboxes, setMailboxes] = useState<Mailbox[]>([]);
169
+ const [mailboxFolders, setMailboxFolders] = useState<MailboxFolders[]>([]);
170
+ const [foldersLoading, setFoldersLoading] = useState(true);
171
+ const [requestedMailboxUid, setRequestedMailboxUid] = useState<string | null>(null);
172
+ const [requestedFolderUid, setRequestedFolderUid] = useState<string | null>(null);
173
+ const [requestedAggregateType, setRequestedAggregateType] = useState<string | null>(null);
174
+ const [drawerOpen, setDrawerOpen] = useState(false);
175
+
176
+ useEffect(() => {
177
+ const params = new URLSearchParams(window.location.search);
178
+ setRequestedMailboxUid(params.get("mailboxUid"));
179
+ setRequestedFolderUid(params.get("folderUid"));
180
+ setRequestedAggregateType(params.get("aggregate"));
181
+ }, []);
182
+
183
+ useEffect(() => {
184
+ if (!userUid) {
185
+ return;
186
+ }
187
+ listMailboxes({ limit: MAILBOX_LIST_LIMIT })
188
+ .then((result) => {
189
+ setMailboxes(result);
190
+ setStatus("ready");
191
+ })
192
+ .catch((err) => {
193
+ setError(err instanceof ApiRequestError ? err.message : "Could not load your mailboxes.");
194
+ setStatus("error");
195
+ });
196
+ }, [userUid]);
197
+
198
+ const aggregateFolderType: AggregateFolderType | undefined = isAggregateFolderType(requestedAggregateType)
199
+ ? requestedAggregateType
200
+ : undefined;
201
+
202
+ const mailboxUid: string | undefined = aggregateFolderType
203
+ ? undefined
204
+ : (requestedMailboxUid && mailboxes.some((mb) => mb.uid === requestedMailboxUid) ? requestedMailboxUid : undefined) ??
205
+ mailboxes[0]?.uid;
206
+
207
+ // Fans out one listFolders() call per accessible mailbox in parallel - each call catches its own
208
+ // failure into an MailboxFolders.error rather than letting Promise.all reject, so one mailbox's fetch
209
+ // failure renders that section's own inline Alert instead of blanking out every other mailbox's
210
+ // folder tree.
211
+ useEffect(() => {
212
+ if (mailboxes.length === 0) {
213
+ // Deliberately leaves foldersLoading as-is: this also runs once before listMailboxes() has
214
+ // resolved, and clearing it here would briefly render an empty sidebar the moment mailboxes
215
+ // arrive, before their folders do. A genuinely mailbox-less caller gets MailboxProvisioning.
216
+ setMailboxFolders([]);
217
+ return;
218
+ }
219
+ setFoldersLoading(true);
220
+ void Promise.all(
221
+ mailboxes.map((mailbox) =>
222
+ listFolders(mailbox.uid)
223
+ .then((result): MailboxFolders => ({ mailbox, folders: result.filter((f) => MAIL_FOLDER_TYPES.has(f.type)) }))
224
+ .catch(
225
+ (err): MailboxFolders => ({
226
+ mailbox,
227
+ folders: [],
228
+ error: err instanceof ApiRequestError ? err.message : "Could not load folders.",
229
+ }),
230
+ ),
231
+ ),
232
+ )
233
+ .then(setMailboxFolders)
234
+ .finally(() => setFoldersLoading(false));
235
+ }, [mailboxes]);
236
+
237
+ const selectedMailboxFolders = mailboxFolders.find((mf) => mf.mailbox.uid === mailboxUid)?.folders ?? [];
238
+ const folderUid: string | undefined = aggregateFolderType
239
+ ? undefined
240
+ : (requestedFolderUid && selectedMailboxFolders.some((f) => f.uid === requestedFolderUid) ? requestedFolderUid : undefined) ??
241
+ selectedMailboxFolders.find((f) => f.type === "inbox")?.uid;
242
+
243
+ // The mailbox `KeyEnrollmentGate`/`LocalIndexLifecycle`/`ComposeButton` treat as "the" mailbox when
244
+ // there's no single selected one to use (aggregate mode) - the caller's own owned mailbox if they
245
+ // have one, else whichever accessible mailbox happens to be first. See MailShell's own doc comment on
246
+ // this being an accepted limitation: an aggregate-view message from a *different*, not-yet-visited
247
+ // mailbox may still need that mailbox's own folder view opened directly to unlock/decrypt it.
248
+ const defaultMailboxUid = mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
249
+ const activeMailboxUid = mailboxUid ?? defaultMailboxUid;
250
+
251
+ /** Files a newly created folder under its own mailbox, leaving every other mailbox's list untouched -
252
+ * and ignoring a type this sidebar doesn't list at all, the same filter the fetch above applies. */
253
+ const onFolderCreated = useCallback((folder: Folder) => {
254
+ if (!MAIL_FOLDER_TYPES.has(folder.type)) {
255
+ return;
256
+ }
257
+ setMailboxFolders((prev) =>
258
+ prev.map((entry) =>
259
+ entry.mailbox.uid === folder.mailboxUid ? { ...entry, folders: [...entry.folders, folder] } : entry,
260
+ ),
261
+ );
262
+ }, []);
263
+
264
+ const contextValue = useMemo<MailShellContextValue>(
265
+ () => ({ mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders, onFolderCreated }),
266
+ [mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders, onFolderCreated],
267
+ );
268
+
269
+ // A full-screen takeover, not nested inside the rest of the app's chrome — there's nothing else for a
270
+ // mailbox-less caller to do here yet, so the icon rail/header/folder tree don't render at all. Checks
271
+ // `mailboxes.length` directly (not `!mailboxUid`) since `mailboxUid` is legitimately undefined in
272
+ // aggregate mode even with mailboxes present.
273
+ if (userUid && status === "ready" && mailboxes.length === 0) {
274
+ return <MailboxProvisioning />;
275
+ }
276
+
277
+ let inner: ReactNode = null;
278
+ if (userUid && status === "checking") {
279
+ // Renders immediately (no network round trip needed) so switching into Mail never shows a blank
280
+ // pane while `listMailboxes()` is in flight — the outline below mirrors the real sidebar's shape.
281
+ inner = (
282
+ <aside className="w-64 shrink-0 bg-surface border-r border-border flex flex-col p-3 gap-4">
283
+ <Skeleton height="h-9" className="rounded-sm" />
284
+ <SkeletonList count={6} />
285
+ </aside>
286
+ );
287
+ } else if (userUid && status === "error") {
288
+ inner = (
289
+ <div className="flex-1 flex items-center justify-center p-8">
290
+ <div className="w-full max-w-md">
291
+ <Alert>{error}</Alert>
292
+ </div>
293
+ </div>
294
+ );
295
+ } else if (userUid && status === "ready") {
296
+ // A function, not a plain JSX constant — it's rendered twice (desktop `<aside>` + mobile
297
+ // `Drawer`), possibly *simultaneously* mounted (the aside is only CSS-hidden below `md`, not
298
+ // unmounted).
299
+ const sidebarContent = () => (
300
+ <>
301
+ <div className="p-3">
302
+ <ComposeButton />
303
+ </div>
304
+ {foldersLoading ? (
305
+ <div className="flex-1 overflow-y-auto px-3 pb-3">
306
+ <SkeletonList count={6} className="pt-1" />
307
+ </div>
308
+ ) : (
309
+ <nav className="flex-1 overflow-y-auto px-3 pb-3 flex flex-col gap-3">
310
+ {mailboxes.length > 1 && (
311
+ <div>
312
+ <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5">
313
+ All Mailboxes
314
+ </div>
315
+ <div className="flex flex-col gap-0.5">
316
+ {AGGREGATE_FOLDER_TYPES.map((type) => {
317
+ const unread = aggregateUnreadCount(mailboxFolders, type);
318
+ return (
319
+ <a
320
+ key={type}
321
+ href={`/?aggregate=${encodeURIComponent(type)}`}
322
+ className={[
323
+ "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
324
+ aggregateFolderType === type
325
+ ? "bg-primary/10 text-primary-dark font-semibold"
326
+ : "text-text hover:bg-surface-alt",
327
+ ].join(" ")}
328
+ >
329
+ <span>{FOLDER_LABELS[type]}</span>
330
+ {unread > 0 && (
331
+ <span className="text-xs font-bold rounded-pill py-0.5 px-1.5 bg-surface-alt text-text-muted">
332
+ {unread}
333
+ </span>
334
+ )}
335
+ </a>
336
+ );
337
+ })}
338
+ </div>
339
+ </div>
340
+ )}
341
+ {mailboxFolders.map(({ mailbox, folders, error: mailboxError }) => (
342
+ <div key={mailbox.uid}>
343
+ <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5 truncate">
344
+ {mailbox.displayName}
345
+ {mailbox.ownerUserUid ? "" : " (shared)"}
346
+ </div>
347
+ {mailboxError && (
348
+ <div className="px-2.5 pb-1">
349
+ <Alert>{mailboxError}</Alert>
350
+ </div>
351
+ )}
352
+ <div className="flex flex-col gap-0.5">
353
+ {sortedFoldersOf(folders).map((folder) => (
354
+ <a
355
+ key={folder.uid}
356
+ href={`/?mailboxUid=${encodeURIComponent(mailbox.uid)}&folderUid=${encodeURIComponent(folder.uid)}`}
357
+ className={[
358
+ "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
359
+ folder.uid === folderUid
360
+ ? "bg-primary/10 text-primary-dark font-semibold"
361
+ : "text-text hover:bg-surface-alt",
362
+ ].join(" ")}
363
+ >
364
+ <span>{FOLDER_LABELS[folder.type] ?? folder.name}</span>
365
+ {folder.unreadCount > 0 && (
366
+ <span className="text-xs font-bold rounded-pill py-0.5 px-1.5 bg-surface-alt text-text-muted">
367
+ {folder.unreadCount}
368
+ </span>
369
+ )}
370
+ </a>
371
+ ))}
372
+ </div>
373
+ </div>
374
+ ))}
375
+ </nav>
376
+ )}
377
+ </>
378
+ );
379
+
380
+ inner = (
381
+ <>
382
+ <aside className="hidden md:flex w-64 shrink-0 bg-surface border-r border-border flex-col">{sidebarContent()}</aside>
383
+ <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} title="Folders">
384
+ <div className="flex flex-col">{sidebarContent()}</div>
385
+ </Drawer>
386
+ <main className="flex-1 min-w-0 overflow-y-auto">
387
+ <button
388
+ type="button"
389
+ className="md:hidden m-3 w-9 h-9 flex items-center justify-center rounded-sm text-text-muted hover:bg-surface-alt hover:text-text"
390
+ aria-label="Open folders"
391
+ onClick={() => setDrawerOpen(true)}
392
+ >
393
+ <HiOutlineBars3 size={20} aria-hidden="true" />
394
+ </button>
395
+ <MailShellContext.Provider value={contextValue}>{children}</MailShellContext.Provider>
396
+ </main>
397
+ </>
398
+ );
399
+ }
400
+
401
+ // Wraps AppShell unconditionally, at a stable tree position regardless of whether mailboxUid has
402
+ // resolved yet - KeyEnrollmentGate itself passes `children` through untouched until a real
403
+ // mailboxUid is supplied (see its own doc comment). Wrapping only once ready (a conditional tree
404
+ // position) would make AppShell itself remount the moment mailboxUid resolves, tearing down
405
+ // whatever state/effects it had already started (confirmed by direct reproduction: the
406
+ // impersonation banner's own internal state was lost exactly at that transition).
407
+ const activeMailbox = mailboxes.find((mb) => mb.uid === activeMailboxUid);
408
+ return (
409
+ <KeyEnrollmentGate
410
+ mailboxUid={activeMailboxUid}
411
+ mailboxAddress={activeMailbox?.primarySmtpAddress}
412
+ mailboxKeys={activeMailbox?.keys}
413
+ // Unlocking is only actually required to sign/encrypt a compose, read an already-encrypted
414
+ // message, or change encryption settings - not merely to open Mail. Those specific call sites
415
+ // (ComposeWindow, MessageDetailPane) request an unlock on demand via useUnlockPrompt() instead.
416
+ // First-time provisioning (a mailbox with no vault at all yet) still always blocks - see this
417
+ // prop's own doc comment on KeyEnrollmentGateProps.
418
+ blocking={false}
419
+ // A shared/delegated mailbox the caller doesn't own is never provisioned from here - its keys
420
+ // belong to its owner (or its admins), not to whoever happens to open it first - and neither is
421
+ // the impersonated user's own mailbox: an administrator must never choose its password/recovery codes.
422
+ canProvision={!impersonating && activeMailbox?.ownerUserUid === userUid}
423
+ >
424
+ <LocalIndexLifecycle
425
+ mailboxUid={activeMailboxUid}
426
+ mailboxKeys={activeMailbox?.keys}
427
+ folders={mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? []}
428
+ // A full page may be truncated - pruning against it would delete indexes of accessible mailboxes
429
+ // beyond the limit, so it's only trusted as the complete list when it came back short.
430
+ accessibleMailboxUids={status === "ready" && mailboxes.length < MAILBOX_LIST_LIMIT ? mailboxes.map((mb) => mb.uid) : undefined}
431
+ />
432
+ <AppShell
433
+ active="mail"
434
+ userUid={userUid}
435
+ authServerUrl={authServerUrl}
436
+ impersonating={impersonating}
437
+ impersonationBaseUrl={impersonationBaseUrl}
438
+ trusted={trusted}
439
+ pluginNav={pluginNav}
440
+ >
441
+ {inner}
442
+ </AppShell>
443
+ </KeyEnrollmentGate>
444
+ );
445
+ }