@rapidmx/web-client 0.5.0 → 0.6.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 (164) hide show
  1. package/README.md +88 -0
  2. package/apps/shared/components/admin/layout/AdminShell.tsx +25 -8
  3. package/apps/shared/components/calendar/layout/CalendarShell.tsx +194 -192
  4. package/apps/shared/components/contacts/layout/ContactsShell.tsx +199 -197
  5. package/apps/shared/components/layout/AppShell.tsx +36 -18
  6. package/apps/shared/components/mail/layout/MailShell.tsx +420 -418
  7. package/apps/shared/components/settings/layout/SettingsShell.tsx +23 -9
  8. package/apps/shared/components/tasks/layout/TasksShell.tsx +201 -199
  9. package/apps/shared/plugins/pluginNav.ts +73 -0
  10. package/apps/shared/search/localIndexRpcClient.ts +3 -1
  11. package/dist/apps/admin/_404.d.ts +2 -0
  12. package/dist/apps/admin/_500.d.ts +2 -0
  13. package/dist/apps/admin/_layout.d.ts +8 -0
  14. package/dist/apps/admin/audit-log/index.d.ts +11 -0
  15. package/dist/apps/admin/branding/index.d.ts +3 -0
  16. package/dist/apps/admin/data-requests/index.d.ts +3 -0
  17. package/dist/apps/admin/distribution-lists/[uid].d.ts +7 -0
  18. package/dist/apps/admin/distribution-lists/index.d.ts +3 -0
  19. package/dist/apps/admin/distribution-lists/new/index.d.ts +3 -0
  20. package/dist/apps/admin/domains/[uid].d.ts +7 -0
  21. package/dist/apps/admin/domains/index.d.ts +3 -0
  22. package/dist/apps/admin/domains/new/index.d.ts +3 -0
  23. package/dist/apps/admin/encryption-policy/index.d.ts +3 -0
  24. package/dist/apps/admin/escrow-scopes/[uid].d.ts +21 -0
  25. package/dist/apps/admin/escrow-scopes/index.d.ts +3 -0
  26. package/dist/apps/admin/escrow-scopes/new/index.d.ts +3 -0
  27. package/dist/apps/admin/index.d.ts +3 -0
  28. package/dist/apps/admin/ingest-queue/index.d.ts +4 -0
  29. package/dist/apps/admin/mailbox-policy/index.d.ts +3 -0
  30. package/dist/apps/admin/mailboxes/[uid].d.ts +7 -0
  31. package/dist/apps/admin/mailboxes/new/index.d.ts +3 -0
  32. package/dist/apps/admin/plugins/index.d.ts +3 -0
  33. package/dist/apps/admin/quarantine/index.d.ts +6 -0
  34. package/dist/apps/admin/retention-policy/index.d.ts +3 -0
  35. package/dist/apps/admin/setup/index.d.ts +3 -0
  36. package/dist/apps/admin/transport-rules/[uid].d.ts +7 -0
  37. package/dist/apps/admin/transport-rules/_transportRuleConfig.d.ts +21 -0
  38. package/dist/apps/admin/transport-rules/index.d.ts +3 -0
  39. package/dist/apps/admin/transport-rules/new/index.d.ts +3 -0
  40. package/dist/apps/escrow/_layout.d.ts +10 -0
  41. package/dist/apps/escrow/audit-log/index.d.ts +9 -0
  42. package/dist/apps/escrow/index.d.ts +3 -0
  43. package/dist/apps/escrow/matters/[uid].d.ts +7 -0
  44. package/dist/apps/escrow/matters/new/index.d.ts +3 -0
  45. package/dist/apps/shared/components/admin/distributionLists/MemberListCard.d.ts +17 -0
  46. package/dist/apps/shared/components/admin/escrowScopes/EscrowScopeKeyAndHoldersFields.d.ts +32 -0
  47. package/dist/apps/shared/components/admin/layout/AdminShell.d.ts +32 -0
  48. package/dist/apps/shared/components/admin/layout/AdminShell.js +12 -5
  49. package/dist/apps/shared/components/admin/mailboxes/EscrowScopeCard.d.ts +12 -0
  50. package/dist/apps/shared/components/admin/mailboxes/MailboxTable.d.ts +6 -0
  51. package/dist/apps/shared/components/admin/mailboxes/ResourceSettingsCard.d.ts +19 -0
  52. package/dist/apps/shared/components/admin/mailboxes/ShareAccessCard.d.ts +12 -0
  53. package/dist/apps/shared/components/admin/settings/BrandingForm.d.ts +9 -0
  54. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.d.ts +12 -0
  55. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.d.ts +12 -0
  56. package/dist/apps/shared/components/admin/settings/LoadedSettingsForm.d.ts +9 -0
  57. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.d.ts +19 -0
  58. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.d.ts +10 -0
  59. package/dist/apps/shared/components/admin/settings/PluginsManager.d.ts +4 -0
  60. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.d.ts +9 -0
  61. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.d.ts +14 -0
  62. package/dist/apps/shared/components/admin/setup/SetupWizard.d.ts +36 -0
  63. package/dist/apps/shared/components/admin/signOut.d.ts +23 -0
  64. package/dist/apps/shared/components/admin/usePagedList.d.ts +39 -0
  65. package/dist/apps/shared/components/calendar/CalendarListSidebar.d.ts +26 -0
  66. package/dist/apps/shared/components/calendar/EventModal.d.ts +46 -0
  67. package/dist/apps/shared/components/calendar/MonthView.d.ts +15 -0
  68. package/dist/apps/shared/components/calendar/RecurrenceEditor.d.ts +20 -0
  69. package/dist/apps/shared/components/calendar/ResourcePicker.d.ts +19 -0
  70. package/dist/apps/shared/components/calendar/SplitDayView.d.ts +28 -0
  71. package/dist/apps/shared/components/calendar/TimeGridView.d.ts +17 -0
  72. package/dist/apps/shared/components/calendar/allDay.d.ts +51 -0
  73. package/dist/apps/shared/components/calendar/layout/CalendarShell.d.ts +40 -0
  74. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +2 -2
  75. package/dist/apps/shared/components/contacts/ContactDetailPane.d.ts +23 -0
  76. package/dist/apps/shared/components/contacts/ContactForm.d.ts +20 -0
  77. package/dist/apps/shared/components/contacts/ContactsSidebar.d.ts +40 -0
  78. package/dist/apps/shared/components/contacts/ContactsToolbar.d.ts +25 -0
  79. package/dist/apps/shared/components/contacts/KeyChangeReview.d.ts +40 -0
  80. package/dist/apps/shared/components/contacts/contactKeys.d.ts +29 -0
  81. package/dist/apps/shared/components/contacts/layout/ContactsShell.d.ts +21 -0
  82. package/dist/apps/shared/components/contacts/layout/ContactsShell.js +2 -2
  83. package/dist/apps/shared/components/escrow/layout/EscrowShell.d.ts +25 -0
  84. package/dist/apps/shared/components/forms/StringListField.d.ts +22 -0
  85. package/dist/apps/shared/components/layout/AppShell.d.ts +49 -0
  86. package/dist/apps/shared/components/layout/AppShell.js +15 -13
  87. package/dist/apps/shared/components/layout/BrandingChrome.d.ts +18 -0
  88. package/dist/apps/shared/components/layout/KeyEnrollmentGate.d.ts +51 -0
  89. package/dist/apps/shared/components/layout/MailboxProvisioning.d.ts +13 -0
  90. package/dist/apps/shared/components/layout/RecoveryCodeUnlock.d.ts +66 -0
  91. package/dist/apps/shared/components/layout/UnlockPromptProvider.d.ts +45 -0
  92. package/dist/apps/shared/components/layout/UserMenu.d.ts +23 -0
  93. package/dist/apps/shared/components/mail/ConversationList.d.ts +11 -0
  94. package/dist/apps/shared/components/mail/ConversationThreadPane.d.ts +23 -0
  95. package/dist/apps/shared/components/mail/MessageDetailPane.d.ts +93 -0
  96. package/dist/apps/shared/components/mail/compose/ComposeContext.d.ts +58 -0
  97. package/dist/apps/shared/components/mail/compose/ComposeToolbar.d.ts +15 -0
  98. package/dist/apps/shared/components/mail/compose/ComposeWindow.d.ts +37 -0
  99. package/dist/apps/shared/components/mail/compose/EmojiPicker.d.ts +14 -0
  100. package/dist/apps/shared/components/mail/compose/GifPicker.d.ts +13 -0
  101. package/dist/apps/shared/components/mail/compose/RichTextEditor.d.ts +34 -0
  102. package/dist/apps/shared/components/mail/compose/ScheduleSendPicker.d.ts +16 -0
  103. package/dist/apps/shared/components/mail/compose/composeFlushRegistry.d.ts +27 -0
  104. package/dist/apps/shared/components/mail/layout/MailShell.d.ts +57 -0
  105. package/dist/apps/shared/components/mail/layout/MailShell.js +2 -2
  106. package/dist/apps/shared/components/mail/pinnedSigners.d.ts +33 -0
  107. package/dist/apps/shared/components/mail/verificationSeals.d.ts +22 -0
  108. package/dist/apps/shared/components/mail/writableMailboxes.d.ts +15 -0
  109. package/dist/apps/shared/components/rules/RuleBuilder.d.ts +70 -0
  110. package/dist/apps/shared/components/settings/layout/SettingsShell.d.ts +41 -0
  111. package/dist/apps/shared/components/settings/layout/SettingsShell.js +19 -9
  112. package/dist/apps/shared/components/tasks/TasksSidebar.d.ts +41 -0
  113. package/dist/apps/shared/components/tasks/TasksToolbar.d.ts +14 -0
  114. package/dist/apps/shared/components/tasks/layout/TasksShell.d.ts +24 -0
  115. package/dist/apps/shared/components/tasks/layout/TasksShell.js +2 -2
  116. package/dist/apps/shared/mail/findWellKnownFolderUid.d.ts +5 -0
  117. package/dist/apps/shared/mail/listAllPages.d.ts +17 -0
  118. package/dist/apps/shared/plugins/pluginNav.d.ts +39 -0
  119. package/dist/apps/shared/plugins/pluginNav.js +33 -0
  120. package/dist/apps/shared/search/LocalIndexLifecycle.d.ts +13 -0
  121. package/dist/apps/shared/search/localIndexBlockCipher.d.ts +36 -0
  122. package/dist/apps/shared/search/localIndexBuilder.d.ts +85 -0
  123. package/dist/apps/shared/search/localIndexKey.d.ts +4 -0
  124. package/dist/apps/shared/search/localIndexRpcClient.d.ts +71 -0
  125. package/dist/apps/shared/search/localIndexRpcClient.js +3 -1
  126. package/dist/apps/shared/search/localIndexSchema.d.ts +111 -0
  127. package/dist/apps/shared/search/localIndexSizePreference.d.ts +27 -0
  128. package/dist/apps/shared/search/localIndexStorage.d.ts +28 -0
  129. package/dist/apps/shared/search/localIndexVFS.d.ts +101 -0
  130. package/dist/apps/shared/search/localIndexWorker.d.ts +145 -0
  131. package/dist/apps/shared/search/searchTier2.d.ts +30 -0
  132. package/dist/apps/www/_404.d.ts +2 -0
  133. package/dist/apps/www/_500.d.ts +2 -0
  134. package/dist/apps/www/_layout.d.ts +14 -0
  135. package/dist/apps/www/calendar/index.d.ts +3 -0
  136. package/dist/apps/www/contacts/[uid].d.ts +13 -0
  137. package/dist/apps/www/contacts/index.d.ts +3 -0
  138. package/dist/apps/www/index.d.ts +3 -0
  139. package/dist/apps/www/messages/[uid].d.ts +11 -0
  140. package/dist/apps/www/settings/auto-reply/index.d.ts +4 -0
  141. package/dist/apps/www/settings/encryption/index.d.ts +7 -0
  142. package/dist/apps/www/settings/filters/[uid].d.ts +8 -0
  143. package/dist/apps/www/settings/filters/_mailFilterRuleConfig.d.ts +11 -0
  144. package/dist/apps/www/settings/filters/index.d.ts +4 -0
  145. package/dist/apps/www/settings/filters/new/index.d.ts +4 -0
  146. package/dist/apps/www/settings/focused-inbox/index.d.ts +4 -0
  147. package/dist/apps/www/settings/labels/index.d.ts +4 -0
  148. package/dist/apps/www/settings/privacy/index.d.ts +4 -0
  149. package/dist/apps/www/settings/read-receipts/index.d.ts +4 -0
  150. package/dist/apps/www/settings/sharing/index.d.ts +4 -0
  151. package/dist/apps/www/settings/signatures/[uid].d.ts +8 -0
  152. package/dist/apps/www/settings/signatures/index.d.ts +4 -0
  153. package/dist/apps/www/settings/signatures/new/index.d.ts +4 -0
  154. package/dist/apps/www/settings/signatures/signatureDefaults.d.ts +10 -0
  155. package/dist/apps/www/tasks/index.d.ts +3 -0
  156. package/package.json +3 -3
  157. package/apps/shared/components/booking/AvailabilityEditor.tsx +0 -118
  158. package/apps/www/settings/booking-types/[uid].tsx +0 -306
  159. package/apps/www/settings/booking-types/index.tsx +0 -98
  160. package/apps/www/settings/booking-types/new/index.tsx +0 -212
  161. package/dist/apps/shared/components/booking/AvailabilityEditor.js +0 -45
  162. package/dist/apps/www/settings/booking-types/[uid].js +0 -134
  163. package/dist/apps/www/settings/booking-types/index.js +0 -29
  164. package/dist/apps/www/settings/booking-types/new/index.js +0 -86
@@ -1,418 +1,420 @@
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
- children,
152
- }: PropsWithChildren<MailShellProps>) {
153
- const [status, setStatus] = useState<Status>("checking");
154
- const [error, setError] = useState<string | null>(null);
155
- const [mailboxes, setMailboxes] = useState<Mailbox[]>([]);
156
- const [mailboxFolders, setMailboxFolders] = useState<MailboxFolders[]>([]);
157
- const [foldersLoading, setFoldersLoading] = useState(true);
158
- const [requestedMailboxUid, setRequestedMailboxUid] = useState<string | null>(null);
159
- const [requestedFolderUid, setRequestedFolderUid] = useState<string | null>(null);
160
- const [requestedAggregateType, setRequestedAggregateType] = useState<string | null>(null);
161
- const [drawerOpen, setDrawerOpen] = useState(false);
162
-
163
- useEffect(() => {
164
- const params = new URLSearchParams(window.location.search);
165
- setRequestedMailboxUid(params.get("mailboxUid"));
166
- setRequestedFolderUid(params.get("folderUid"));
167
- setRequestedAggregateType(params.get("aggregate"));
168
- }, []);
169
-
170
- useEffect(() => {
171
- if (!userUid) {
172
- return;
173
- }
174
- listMailboxes({ limit: MAILBOX_LIST_LIMIT })
175
- .then((result) => {
176
- setMailboxes(result);
177
- setStatus("ready");
178
- })
179
- .catch((err) => {
180
- setError(err instanceof ApiRequestError ? err.message : "Could not load your mailboxes.");
181
- setStatus("error");
182
- });
183
- }, [userUid]);
184
-
185
- const aggregateFolderType: AggregateFolderType | undefined = isAggregateFolderType(requestedAggregateType)
186
- ? requestedAggregateType
187
- : undefined;
188
-
189
- const mailboxUid: string | undefined = aggregateFolderType
190
- ? undefined
191
- : (requestedMailboxUid && mailboxes.some((mb) => mb.uid === requestedMailboxUid) ? requestedMailboxUid : undefined) ??
192
- mailboxes[0]?.uid;
193
-
194
- // Fans out one listFolders() call per accessible mailbox in parallel - each call catches its own
195
- // failure into an MailboxFolders.error rather than letting Promise.all reject, so one mailbox's fetch
196
- // failure renders that section's own inline Alert instead of blanking out every other mailbox's
197
- // folder tree.
198
- useEffect(() => {
199
- if (mailboxes.length === 0) {
200
- // Deliberately leaves foldersLoading as-is: this also runs once before listMailboxes() has
201
- // resolved, and clearing it here would briefly render an empty sidebar the moment mailboxes
202
- // arrive, before their folders do. A genuinely mailbox-less caller gets MailboxProvisioning.
203
- setMailboxFolders([]);
204
- return;
205
- }
206
- setFoldersLoading(true);
207
- void Promise.all(
208
- mailboxes.map((mailbox) =>
209
- listFolders(mailbox.uid)
210
- .then((result): MailboxFolders => ({ mailbox, folders: result.filter((f) => MAIL_FOLDER_TYPES.has(f.type)) }))
211
- .catch(
212
- (err): MailboxFolders => ({
213
- mailbox,
214
- folders: [],
215
- error: err instanceof ApiRequestError ? err.message : "Could not load folders.",
216
- }),
217
- ),
218
- ),
219
- )
220
- .then(setMailboxFolders)
221
- .finally(() => setFoldersLoading(false));
222
- }, [mailboxes]);
223
-
224
- const selectedMailboxFolders = mailboxFolders.find((mf) => mf.mailbox.uid === mailboxUid)?.folders ?? [];
225
- const folderUid: string | undefined = aggregateFolderType
226
- ? undefined
227
- : (requestedFolderUid && selectedMailboxFolders.some((f) => f.uid === requestedFolderUid) ? requestedFolderUid : undefined) ??
228
- selectedMailboxFolders.find((f) => f.type === "inbox")?.uid;
229
-
230
- // The mailbox `KeyEnrollmentGate`/`LocalIndexLifecycle`/`ComposeButton` treat as "the" mailbox when
231
- // there's no single selected one to use (aggregate mode) - the caller's own owned mailbox if they
232
- // have one, else whichever accessible mailbox happens to be first. See MailShell's own doc comment on
233
- // this being an accepted limitation: an aggregate-view message from a *different*, not-yet-visited
234
- // mailbox may still need that mailbox's own folder view opened directly to unlock/decrypt it.
235
- const defaultMailboxUid = mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
236
- const activeMailboxUid = mailboxUid ?? defaultMailboxUid;
237
-
238
- const contextValue = useMemo<MailShellContextValue>(
239
- () => ({ mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders }),
240
- [mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders],
241
- );
242
-
243
- // A full-screen takeover, not nested inside the rest of the app's chrome — there's nothing else for a
244
- // mailbox-less caller to do here yet, so the icon rail/header/folder tree don't render at all. Checks
245
- // `mailboxes.length` directly (not `!mailboxUid`) since `mailboxUid` is legitimately undefined in
246
- // aggregate mode even with mailboxes present.
247
- if (userUid && status === "ready" && mailboxes.length === 0) {
248
- return <MailboxProvisioning />;
249
- }
250
-
251
- let inner: ReactNode = null;
252
- if (userUid && status === "checking") {
253
- // Renders immediately (no network round trip needed) so switching into Mail never shows a blank
254
- // pane while `listMailboxes()` is in flight — the outline below mirrors the real sidebar's shape.
255
- inner = (
256
- <aside className="w-64 shrink-0 bg-surface border-r border-border flex flex-col p-3 gap-4">
257
- <Skeleton height="h-9" className="rounded-sm" />
258
- <SkeletonList count={6} />
259
- </aside>
260
- );
261
- } else if (userUid && status === "error") {
262
- inner = (
263
- <div className="flex-1 flex items-center justify-center p-8">
264
- <div className="w-full max-w-md">
265
- <Alert>{error}</Alert>
266
- </div>
267
- </div>
268
- );
269
- } else if (userUid && status === "ready") {
270
- // A function, not a plain JSX constant — it's rendered twice (desktop `<aside>` + mobile
271
- // `Drawer`), possibly *simultaneously* mounted (the aside is only CSS-hidden below `md`, not
272
- // unmounted).
273
- const sidebarContent = () => (
274
- <>
275
- <div className="p-3">
276
- <ComposeButton />
277
- </div>
278
- {foldersLoading ? (
279
- <div className="flex-1 overflow-y-auto px-3 pb-3">
280
- <SkeletonList count={6} className="pt-1" />
281
- </div>
282
- ) : (
283
- <nav className="flex-1 overflow-y-auto px-3 pb-3 flex flex-col gap-3">
284
- {mailboxes.length > 1 && (
285
- <div>
286
- <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5">
287
- All Mailboxes
288
- </div>
289
- <div className="flex flex-col gap-0.5">
290
- {AGGREGATE_FOLDER_TYPES.map((type) => {
291
- const unread = aggregateUnreadCount(mailboxFolders, type);
292
- return (
293
- <a
294
- key={type}
295
- href={`/?aggregate=${encodeURIComponent(type)}`}
296
- className={[
297
- "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
298
- aggregateFolderType === type
299
- ? "bg-primary/10 text-primary-dark font-semibold"
300
- : "text-text hover:bg-surface-alt",
301
- ].join(" ")}
302
- >
303
- <span>{FOLDER_LABELS[type]}</span>
304
- {unread > 0 && (
305
- <span className="text-xs font-bold rounded-pill py-0.5 px-1.5 bg-surface-alt text-text-muted">
306
- {unread}
307
- </span>
308
- )}
309
- </a>
310
- );
311
- })}
312
- </div>
313
- </div>
314
- )}
315
- {mailboxFolders.map(({ mailbox, folders, error: mailboxError }) => (
316
- <div key={mailbox.uid}>
317
- <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5 truncate">
318
- {mailbox.displayName}
319
- {mailbox.ownerUserUid ? "" : " (shared)"}
320
- </div>
321
- {mailboxError && (
322
- <div className="px-2.5 pb-1">
323
- <Alert>{mailboxError}</Alert>
324
- </div>
325
- )}
326
- <div className="flex flex-col gap-0.5">
327
- {sortedFoldersOf(folders).map((folder) => (
328
- <a
329
- key={folder.uid}
330
- href={`/?mailboxUid=${encodeURIComponent(mailbox.uid)}&folderUid=${encodeURIComponent(folder.uid)}`}
331
- className={[
332
- "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
333
- folder.uid === folderUid
334
- ? "bg-primary/10 text-primary-dark font-semibold"
335
- : "text-text hover:bg-surface-alt",
336
- ].join(" ")}
337
- >
338
- <span>{FOLDER_LABELS[folder.type] ?? folder.name}</span>
339
- {folder.unreadCount > 0 && (
340
- <span className="text-xs font-bold rounded-pill py-0.5 px-1.5 bg-surface-alt text-text-muted">
341
- {folder.unreadCount}
342
- </span>
343
- )}
344
- </a>
345
- ))}
346
- </div>
347
- </div>
348
- ))}
349
- </nav>
350
- )}
351
- </>
352
- );
353
-
354
- inner = (
355
- <>
356
- <aside className="hidden md:flex w-64 shrink-0 bg-surface border-r border-border flex-col">{sidebarContent()}</aside>
357
- <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} title="Folders">
358
- <div className="flex flex-col">{sidebarContent()}</div>
359
- </Drawer>
360
- <main className="flex-1 min-w-0 overflow-y-auto">
361
- <button
362
- type="button"
363
- 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"
364
- aria-label="Open folders"
365
- onClick={() => setDrawerOpen(true)}
366
- >
367
- <HiOutlineBars3 size={20} aria-hidden="true" />
368
- </button>
369
- <MailShellContext.Provider value={contextValue}>{children}</MailShellContext.Provider>
370
- </main>
371
- </>
372
- );
373
- }
374
-
375
- // Wraps AppShell unconditionally, at a stable tree position regardless of whether mailboxUid has
376
- // resolved yet - KeyEnrollmentGate itself passes `children` through untouched until a real
377
- // mailboxUid is supplied (see its own doc comment). Wrapping only once ready (a conditional tree
378
- // position) would make AppShell itself remount the moment mailboxUid resolves, tearing down
379
- // whatever state/effects it had already started (confirmed by direct reproduction: the
380
- // impersonation banner's own internal state was lost exactly at that transition).
381
- const activeMailbox = mailboxes.find((mb) => mb.uid === activeMailboxUid);
382
- return (
383
- <KeyEnrollmentGate
384
- mailboxUid={activeMailboxUid}
385
- mailboxAddress={activeMailbox?.primarySmtpAddress}
386
- mailboxKeys={activeMailbox?.keys}
387
- // Unlocking is only actually required to sign/encrypt a compose, read an already-encrypted
388
- // message, or change encryption settings - not merely to open Mail. Those specific call sites
389
- // (ComposeWindow, MessageDetailPane) request an unlock on demand via useUnlockPrompt() instead.
390
- // First-time provisioning (a mailbox with no vault at all yet) still always blocks - see this
391
- // prop's own doc comment on KeyEnrollmentGateProps.
392
- blocking={false}
393
- // A shared/delegated mailbox the caller doesn't own is never provisioned from here - its keys
394
- // belong to its owner (or its admins), not to whoever happens to open it first - and neither is
395
- // the impersonated user's own mailbox: an administrator must never choose its password/recovery codes.
396
- canProvision={!impersonating && activeMailbox?.ownerUserUid === userUid}
397
- >
398
- <LocalIndexLifecycle
399
- mailboxUid={activeMailboxUid}
400
- mailboxKeys={activeMailbox?.keys}
401
- folders={mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? []}
402
- // A full page may be truncated - pruning against it would delete indexes of accessible mailboxes
403
- // beyond the limit, so it's only trusted as the complete list when it came back short.
404
- accessibleMailboxUids={status === "ready" && mailboxes.length < MAILBOX_LIST_LIMIT ? mailboxes.map((mb) => mb.uid) : undefined}
405
- />
406
- <AppShell
407
- active="mail"
408
- userUid={userUid}
409
- authServerUrl={authServerUrl}
410
- impersonating={impersonating}
411
- impersonationBaseUrl={impersonationBaseUrl}
412
- trusted={trusted}
413
- >
414
- {inner}
415
- </AppShell>
416
- </KeyEnrollmentGate>
417
- );
418
- }
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
+ }