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