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