@rapidmx/web-client 0.14.1 → 0.15.1

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 (171) hide show
  1. package/apps/admin/domains/[uid].tsx +3 -2
  2. package/apps/shared/appearance/AppearanceForm.tsx +9 -1
  3. package/apps/shared/calendar/bookingPlugin.ts +100 -0
  4. package/apps/shared/calendar/calendarLiveUpdates.ts +27 -0
  5. package/apps/shared/components/admin/layout/AdminShell.tsx +37 -5
  6. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +3 -1
  7. package/apps/shared/components/admin/settings/PluginsManager.tsx +1545 -1491
  8. package/apps/shared/components/calendar/AppointmentQuickForm.tsx +327 -0
  9. package/apps/shared/components/calendar/DescriptionEditor.tsx +274 -0
  10. package/apps/shared/components/calendar/EventDescriptionView.tsx +70 -0
  11. package/apps/shared/components/calendar/EventDetails.tsx +401 -0
  12. package/apps/shared/components/calendar/EventEditor.tsx +640 -0
  13. package/apps/shared/components/calendar/EventExpandedForm.tsx +210 -0
  14. package/apps/shared/components/calendar/EventFormParts.tsx +622 -0
  15. package/apps/shared/components/calendar/EventModal.tsx +126 -866
  16. package/apps/shared/components/calendar/EventQuickForm.tsx +116 -0
  17. package/apps/shared/components/calendar/EventShell.tsx +202 -0
  18. package/apps/shared/components/calendar/FindATime.tsx +379 -0
  19. package/apps/shared/components/calendar/LazyDescriptionEditor.tsx +70 -0
  20. package/apps/shared/components/calendar/MonthView.tsx +15 -3
  21. package/apps/shared/components/calendar/QuickCreateFaces.tsx +87 -0
  22. package/apps/shared/components/calendar/QuickCreateTabs.tsx +81 -0
  23. package/apps/shared/components/calendar/QuickFaceFrame.tsx +81 -0
  24. package/apps/shared/components/calendar/RecurrenceEditor.tsx +10 -5
  25. package/apps/shared/components/calendar/RequestChangeForm.tsx +271 -0
  26. package/apps/shared/components/calendar/SplitDayView.tsx +6 -5
  27. package/apps/shared/components/calendar/TaskQuickForm.tsx +289 -0
  28. package/apps/shared/components/calendar/TimeGridView.tsx +8 -6
  29. package/apps/shared/components/calendar/eventDialogFields.ts +86 -0
  30. package/apps/shared/components/calendar/eventForm.ts +108 -0
  31. package/apps/shared/components/calendar/eventFormat.ts +183 -0
  32. package/apps/shared/components/calendar/findTimeGrid.ts +90 -0
  33. package/apps/shared/components/calendar/swipeNavigation.ts +14 -0
  34. package/apps/shared/components/layout/UserMenu.tsx +80 -28
  35. package/apps/shared/components/mail/ConversationList.tsx +100 -48
  36. package/apps/shared/components/mail/ConversationThreadPane.tsx +490 -486
  37. package/apps/shared/components/mail/InviteCard.tsx +387 -0
  38. package/apps/shared/components/mail/MessageDetailPane.tsx +24 -2
  39. package/apps/shared/components/mail/SwipeRow.tsx +120 -0
  40. package/apps/shared/components/mail/compose/ComposeWindow.tsx +7 -3
  41. package/apps/shared/components/mail/invite/InviteRowChip.tsx +104 -0
  42. package/apps/shared/components/mail/invite/InviteRsvpPopover.tsx +271 -0
  43. package/apps/shared/components/mail/invite/InviteTimeline.tsx +200 -0
  44. package/apps/shared/components/mail/invite/ProposeTimeForm.tsx +109 -0
  45. package/apps/shared/components/mail/invite/inviteFormat.ts +110 -0
  46. package/apps/shared/components/mail/invite/inviteStore.ts +114 -0
  47. package/apps/shared/components/mail/layout/MailShell.tsx +522 -490
  48. package/apps/shared/components/settings/layout/SettingsShell.tsx +1 -0
  49. package/apps/shared/gestures/useEnterSlide.ts +54 -0
  50. package/apps/shared/gestures/useSwipe.ts +114 -0
  51. package/apps/shared/gestures/useSwipeSlide.ts +113 -0
  52. package/apps/shared/gestures/useWheelPaging.ts +107 -0
  53. package/apps/shared/mail/newMailNotifications.ts +171 -183
  54. package/apps/shared/mail/useNewMailNotifications.ts +178 -178
  55. package/apps/shared/notifications/preferences.ts +36 -0
  56. package/apps/shared/notifications/store.ts +560 -551
  57. package/apps/www/_routes.ts +1 -0
  58. package/apps/www/calendar/index.tsx +139 -37
  59. package/apps/www/index.tsx +273 -126
  60. package/apps/www/messages/[uid].tsx +31 -4
  61. package/apps/www/settings/profile/index.tsx +248 -0
  62. package/dist/apps/admin/domains/[uid].js +4 -2
  63. package/dist/apps/shared/appearance/AppearanceForm.js +9 -1
  64. package/dist/apps/shared/calendar/bookingPlugin.d.ts +50 -0
  65. package/dist/apps/shared/calendar/bookingPlugin.js +57 -0
  66. package/dist/apps/shared/calendar/calendarLiveUpdates.d.ts +11 -0
  67. package/dist/apps/shared/calendar/calendarLiveUpdates.js +23 -0
  68. package/dist/apps/shared/components/admin/layout/AdminShell.d.ts +1 -1
  69. package/dist/apps/shared/components/admin/layout/AdminShell.js +7 -3
  70. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +3 -1
  71. package/dist/apps/shared/components/admin/settings/PluginsManager.js +40 -6
  72. package/dist/apps/shared/components/calendar/AppointmentQuickForm.d.ts +47 -0
  73. package/dist/apps/shared/components/calendar/AppointmentQuickForm.js +135 -0
  74. package/dist/apps/shared/components/calendar/DescriptionEditor.d.ts +26 -0
  75. package/dist/apps/shared/components/calendar/DescriptionEditor.js +192 -0
  76. package/dist/apps/shared/components/calendar/EventDescriptionView.d.ts +14 -0
  77. package/dist/apps/shared/components/calendar/EventDescriptionView.js +39 -0
  78. package/dist/apps/shared/components/calendar/EventDetails.d.ts +33 -0
  79. package/dist/apps/shared/components/calendar/EventDetails.js +137 -0
  80. package/dist/apps/shared/components/calendar/EventEditor.d.ts +59 -0
  81. package/dist/apps/shared/components/calendar/EventEditor.js +549 -0
  82. package/dist/apps/shared/components/calendar/EventExpandedForm.d.ts +14 -0
  83. package/dist/apps/shared/components/calendar/EventExpandedForm.js +44 -0
  84. package/dist/apps/shared/components/calendar/EventFormParts.d.ts +69 -0
  85. package/dist/apps/shared/components/calendar/EventFormParts.js +202 -0
  86. package/dist/apps/shared/components/calendar/EventModal.d.ts +26 -13
  87. package/dist/apps/shared/components/calendar/EventModal.js +57 -459
  88. package/dist/apps/shared/components/calendar/EventQuickForm.d.ts +18 -0
  89. package/dist/apps/shared/components/calendar/EventQuickForm.js +25 -0
  90. package/dist/apps/shared/components/calendar/EventShell.d.ts +64 -0
  91. package/dist/apps/shared/components/calendar/EventShell.js +134 -0
  92. package/dist/apps/shared/components/calendar/FindATime.d.ts +18 -0
  93. package/dist/apps/shared/components/calendar/FindATime.js +190 -0
  94. package/dist/apps/shared/components/calendar/LazyDescriptionEditor.d.ts +8 -0
  95. package/dist/apps/shared/components/calendar/LazyDescriptionEditor.js +44 -0
  96. package/dist/apps/shared/components/calendar/MonthView.d.ts +5 -1
  97. package/dist/apps/shared/components/calendar/MonthView.js +11 -5
  98. package/dist/apps/shared/components/calendar/QuickCreateFaces.d.ts +30 -0
  99. package/dist/apps/shared/components/calendar/QuickCreateFaces.js +44 -0
  100. package/dist/apps/shared/components/calendar/QuickCreateTabs.d.ts +24 -0
  101. package/dist/apps/shared/components/calendar/QuickCreateTabs.js +46 -0
  102. package/dist/apps/shared/components/calendar/QuickFaceFrame.d.ts +25 -0
  103. package/dist/apps/shared/components/calendar/QuickFaceFrame.js +19 -0
  104. package/dist/apps/shared/components/calendar/RecurrenceEditor.d.ts +4 -1
  105. package/dist/apps/shared/components/calendar/RecurrenceEditor.js +2 -2
  106. package/dist/apps/shared/components/calendar/RequestChangeForm.d.ts +36 -0
  107. package/dist/apps/shared/components/calendar/RequestChangeForm.js +138 -0
  108. package/dist/apps/shared/components/calendar/SplitDayView.d.ts +3 -2
  109. package/dist/apps/shared/components/calendar/SplitDayView.js +3 -2
  110. package/dist/apps/shared/components/calendar/TaskQuickForm.d.ts +40 -0
  111. package/dist/apps/shared/components/calendar/TaskQuickForm.js +101 -0
  112. package/dist/apps/shared/components/calendar/TimeGridView.d.ts +4 -2
  113. package/dist/apps/shared/components/calendar/TimeGridView.js +3 -2
  114. package/dist/apps/shared/components/calendar/eventDialogFields.d.ts +28 -0
  115. package/dist/apps/shared/components/calendar/eventDialogFields.js +59 -0
  116. package/dist/apps/shared/components/calendar/eventForm.d.ts +98 -0
  117. package/dist/apps/shared/components/calendar/eventForm.js +1 -0
  118. package/dist/apps/shared/components/calendar/eventFormat.d.ts +67 -0
  119. package/dist/apps/shared/components/calendar/eventFormat.js +163 -0
  120. package/dist/apps/shared/components/calendar/findTimeGrid.d.ts +30 -0
  121. package/dist/apps/shared/components/calendar/findTimeGrid.js +83 -0
  122. package/dist/apps/shared/components/calendar/swipeNavigation.d.ts +9 -0
  123. package/dist/apps/shared/components/calendar/swipeNavigation.js +8 -0
  124. package/dist/apps/shared/components/layout/UserMenu.d.ts +10 -8
  125. package/dist/apps/shared/components/layout/UserMenu.js +70 -23
  126. package/dist/apps/shared/components/mail/ConversationList.d.ts +12 -1
  127. package/dist/apps/shared/components/mail/ConversationList.js +21 -4
  128. package/dist/apps/shared/components/mail/ConversationThreadPane.d.ts +4 -1
  129. package/dist/apps/shared/components/mail/InviteCard.d.ts +20 -0
  130. package/dist/apps/shared/components/mail/InviteCard.js +150 -0
  131. package/dist/apps/shared/components/mail/MessageDetailPane.js +13 -2
  132. package/dist/apps/shared/components/mail/SwipeRow.d.ts +22 -0
  133. package/dist/apps/shared/components/mail/SwipeRow.js +71 -0
  134. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +8 -3
  135. package/dist/apps/shared/components/mail/invite/InviteRowChip.d.ts +23 -0
  136. package/dist/apps/shared/components/mail/invite/InviteRowChip.js +46 -0
  137. package/dist/apps/shared/components/mail/invite/InviteRsvpPopover.d.ts +20 -0
  138. package/dist/apps/shared/components/mail/invite/InviteRsvpPopover.js +141 -0
  139. package/dist/apps/shared/components/mail/invite/InviteTimeline.d.ts +27 -0
  140. package/dist/apps/shared/components/mail/invite/InviteTimeline.js +120 -0
  141. package/dist/apps/shared/components/mail/invite/ProposeTimeForm.d.ts +17 -0
  142. package/dist/apps/shared/components/mail/invite/ProposeTimeForm.js +45 -0
  143. package/dist/apps/shared/components/mail/invite/inviteFormat.d.ts +28 -0
  144. package/dist/apps/shared/components/mail/invite/inviteFormat.js +94 -0
  145. package/dist/apps/shared/components/mail/invite/inviteStore.d.ts +28 -0
  146. package/dist/apps/shared/components/mail/invite/inviteStore.js +95 -0
  147. package/dist/apps/shared/components/mail/layout/MailShell.d.ts +5 -0
  148. package/dist/apps/shared/components/mail/layout/MailShell.js +14 -3
  149. package/dist/apps/shared/components/settings/layout/SettingsShell.js +1 -0
  150. package/dist/apps/shared/gestures/useEnterSlide.d.ts +14 -0
  151. package/dist/apps/shared/gestures/useEnterSlide.js +47 -0
  152. package/dist/apps/shared/gestures/useSwipe.d.ts +45 -0
  153. package/dist/apps/shared/gestures/useSwipe.js +90 -0
  154. package/dist/apps/shared/gestures/useSwipeSlide.d.ts +40 -0
  155. package/dist/apps/shared/gestures/useSwipeSlide.js +95 -0
  156. package/dist/apps/shared/gestures/useWheelPaging.d.ts +32 -0
  157. package/dist/apps/shared/gestures/useWheelPaging.js +85 -0
  158. package/dist/apps/shared/mail/newMailNotifications.d.ts +3 -8
  159. package/dist/apps/shared/mail/newMailNotifications.js +3 -12
  160. package/dist/apps/shared/mail/useNewMailNotifications.js +3 -2
  161. package/dist/apps/shared/notifications/preferences.d.ts +13 -0
  162. package/dist/apps/shared/notifications/preferences.js +36 -0
  163. package/dist/apps/shared/notifications/store.d.ts +1 -0
  164. package/dist/apps/shared/notifications/store.js +7 -23
  165. package/dist/apps/www/_routes.js +1 -0
  166. package/dist/apps/www/calendar/index.js +76 -6
  167. package/dist/apps/www/index.js +140 -39
  168. package/dist/apps/www/messages/[uid].js +13 -5
  169. package/dist/apps/www/settings/profile/index.d.ts +4 -0
  170. package/dist/apps/www/settings/profile/index.js +124 -0
  171. package/package.json +2 -2
@@ -1,490 +1,522 @@
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 { MAILBOX_LIST_LIMIT, MailConnectionContext, useMailConnection } from "../../../mail/useMailConnection.js";
19
- import { folderRows } from "../../../mail/folderTree.js";
20
- import {
21
- CountTracker,
22
- FolderBadge,
23
- FolderCount,
24
- badgeFor,
25
- badgeLabel,
26
- countOfFolder,
27
- inboxUnreadTotal,
28
- } from "../../../mail/folderCounts.js";
29
- import { useUnreadTitle } from "../../../mail/useUnreadTitle.js";
30
- import { pendingCountFor, usePendingSends } from "../../../mail/outbox/pendingSends.js";
31
- import OutboxBadge from "../OutboxBadge.js";
32
- import { ariaKeyShortcuts, withHint } from "../../../keyboard/format.js";
33
- import { SHORTCUTS } from "../../../keyboard/keymap.js";
34
- import { useKeyEnvironment } from "../../../keyboard/ShortcutProvider.js";
35
- import { useShortcut } from "../../../keyboard/useShortcut.js";
36
-
37
- export type MailShellProps = Omit<AppShellProps, "active">;
38
-
39
- /** One mailbox's own mail folders (already filtered to `MAIL_FOLDER_TYPES` and unsorted) - one entry per
40
- * mailbox in `mailboxes`, fetched in parallel so every accessible mailbox's folder tree can render
41
- * simultaneously (see `MailShell`'s own doc comment on why this replaced the old single-mailbox `folders`
42
- * field). `error` is set (and `folders` left empty) for a mailbox whose own `listFolders()` call failed -
43
- * one mailbox's fetch failure must never blank out every other mailbox's section. */
44
- export interface MailboxFolders {
45
- mailbox: Mailbox;
46
- folders: Folder[];
47
- error?: string;
48
- }
49
-
50
- /** The well-known mail folder types an "aggregate" pseudo-folder can merge across every accessible
51
- * mailbox - a fixed, small set: `outbox` is deliberately excluded (transient per-mailbox send-queue
52
- * state, not a "merge across mailboxes" concept), and there's no aggregate concept for `calendar`/
53
- * `contacts`/`tasks`/`notes`/`user` folders (Mail's own sidebar already excludes those - see
54
- * `MAIL_FOLDER_TYPES`). */
55
- export const AGGREGATE_FOLDER_TYPES = ["inbox", "sent_items", "drafts", "deleted_items", "junk"] as const;
56
- export type AggregateFolderType = (typeof AGGREGATE_FOLDER_TYPES)[number];
57
-
58
- function isAggregateFolderType(value: string | null): value is AggregateFolderType {
59
- return !!value && (AGGREGATE_FOLDER_TYPES as readonly string[]).includes(value);
60
- }
61
-
62
- export interface MailShellContextValue {
63
- /** The mailbox currently selected (`?mailboxUid=`) - `undefined` while an aggregate pseudo-folder is
64
- * active instead (`aggregateFolderType` set), since there's no single mailbox to speak of then. */
65
- mailboxUid?: string;
66
- /** The folder currently selected (`?folderUid=`, or the selected mailbox's Inbox) - `undefined` in
67
- * aggregate mode, for the same reason. */
68
- folderUid?: string;
69
- /** Set only when an aggregate pseudo-folder (`?aggregate=inbox` etc.) is selected instead of a real,
70
- * single mailbox+folder - mutually exclusive with `mailboxUid`/`folderUid` above. */
71
- aggregateFolderType?: AggregateFolderType;
72
- mailboxes: Mailbox[];
73
- /** Every accessible mailbox's own mail folders - replaces the old single-mailbox `folders: Folder[]`
74
- * now that every mailbox's tree renders at once (see `MailboxFolders`'s own doc comment). */
75
- mailboxFolders: MailboxFolders[];
76
- /**
77
- * Adds a folder a page has just created (the Move to prompt's "New folder") to the tree this shell
78
- * already fetched, so it appears in the sidebar and in every folder picker without a reload - this
79
- * framework has no client-side router, so a reload is a whole page load.
80
- *
81
- * A no-op on the default context value, which is only ever read outside a real shell.
82
- */
83
- onFolderCreated: (folder: Folder) => void;
84
- /** Says which folders the messages on screen live in: one the sidebar does not know is looked for (see `MailConnection.noteFolderUids`). A no-op on the default context value. */
85
- noteFolderUids: (folderUids: Iterable<string>) => void;
86
- /**
87
- * Bumped whenever new mail (or another change to a message) may have arrived - a push event, a reconnect or the safety-net
88
- * poll - so the list on screen can quietly refetch its first page. See `useMailLiveUpdates()`. Never changes on the default
89
- * context value, which is only ever read outside a real shell.
90
- */
91
- live: LiveUpdates;
92
- /**
93
- * Applies a change to a message (`previous` to `next`; `next` absent when it was deleted) to the folder badges at once, and
94
- * hands back what to call when the server has answered: `settle()` keeps it, `revert()` takes it back. Every place that
95
- * reads, moves or deletes a message goes through this (see `setReadState()`), so the badges follow. A no-op on the default
96
- * context value, which is only ever read outside a real shell.
97
- */
98
- trackMessageChange: (previous: Message, next: Message | null) => CountTracker;
99
- }
100
-
101
- const NO_TRACKER: CountTracker = { settle: () => undefined, revert: () => undefined };
102
-
103
- const MailShellContext = createContext<MailShellContextValue>({
104
- mailboxes: [],
105
- mailboxFolders: [],
106
- onFolderCreated: () => undefined,
107
- noteFolderUids: () => undefined,
108
- live: NO_LIVE_UPDATES,
109
- trackMessageChange: () => NO_TRACKER,
110
- });
111
-
112
- /** Reads the mailbox/folder a page is currently showing, as resolved by the enclosing `MailShell`. */
113
- export function useMailShell(): MailShellContextValue {
114
- return useContext(MailShellContext);
115
- }
116
-
117
- const FOLDER_LABELS: Record<string, string> = {
118
- inbox: "Inbox",
119
- sent_items: "Sent Items",
120
- drafts: "Drafts",
121
- outbox: "Outbox",
122
- junk: "Junk Email",
123
- archive: "Archive",
124
- deleted_items: "Deleted Items",
125
- };
126
-
127
- /** 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. */
128
- function aggregateBadge(mailboxFolders: MailboxFolders[], type: AggregateFolderType, counts: Record<string, FolderCount>): FolderBadge | undefined {
129
- const sum = mailboxFolders.reduce(
130
- (total, mf) => {
131
- const folder = mf.folders.find((f) => f.type === type);
132
- const count = folder ? countOfFolder(folder, counts) : { unread: 0, total: 0 };
133
- return { unread: total.unread + count.unread, total: total.total + count.total };
134
- },
135
- { unread: 0, total: 0 },
136
- );
137
- return badgeFor(type, sum);
138
- }
139
-
140
- /** A folder's badge: an accent pill with the unread count, or - for the folders that show how many they hold - plain muted text. */
141
- function FolderBadgeChip({ badge }: { badge: FolderBadge }) {
142
- return (
143
- <span
144
- className={[
145
- "text-xs rounded-pill py-0.5 px-1.5",
146
- badge.kind === "unread" ? "font-bold bg-primary/15 text-primary-dark" : "font-medium text-text-muted",
147
- ].join(" ")}
148
- >
149
- <span aria-hidden="true">{badge.value}</span>
150
- <span className="sr-only"> {badgeLabel(badge)}</span>
151
- </span>
152
- );
153
- }
154
-
155
- type Status = "checking" | "error" | "ready";
156
-
157
- export { MAILBOX_LIST_LIMIT };
158
-
159
- /**
160
- * A separate component (not inlined into `MailShell`'s own render) so `useCompose()` resolves against
161
- * `ComposeProvider` correctly: that provider is rendered *inside* the `AppShell` that `MailShell` itself
162
- * returns, i.e. a descendant of `MailShell`, not an ancestor — a hook call made directly in `MailShell`'s
163
- * own function body would see only whatever context exists *above* `MailShell`, never a provider one of
164
- * its own descendants creates. This button, rendered as part of `AppShell`'s `children`, sits correctly
165
- * inside that subtree.
166
- *
167
- * Opens with the caller's own mailbox (the shell has already listed them), so the window can start on its
168
- * signature, draft and encryption lookups straight away instead of first asking which mailbox that is; the
169
- * compose window's own From field is where the sender is chosen. Fetches the window's code as the pointer or
170
- * keyboard reaches the button, so the click finds it already here.
171
- */
172
- function ComposeButton({ mailboxUid }: { mailboxUid?: string }) {
173
- const { openCompose } = useCompose();
174
- const env = useKeyEnvironment();
175
- return (
176
- <button
177
- type="button"
178
- title={withHint("Compose", SHORTCUTS.mail.create, env)}
179
- aria-keyshortcuts={ariaKeyShortcuts(SHORTCUTS.mail.create, env)}
180
- onClick={() => openCompose({ mailboxUid })}
181
- onPointerEnter={prefetchComposeWindow}
182
- onFocus={prefetchComposeWindow}
183
- 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"
184
- >
185
- Compose
186
- </button>
187
- );
188
- }
189
-
190
- /**
191
- * 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`
192
- * is - `useCompose()` only resolves below `ComposeProvider`, i.e. inside the `AppShell` this shell renders - and mounted once, whatever number
193
- * of Compose buttons (the sidebar, the folders drawer) are on screen. Opens the same window, for the same mailbox, as the button.
194
- */
195
- function MailShortcuts({ mailboxUid }: { mailboxUid?: string }) {
196
- const { openCompose } = useCompose();
197
- useShortcut(SHORTCUTS.mail.create, () => openCompose({ mailboxUid }));
198
- return null;
199
- }
200
-
201
- /**
202
- * Mail's own contextual sidebar (every accessible mailbox's own folder tree, plus a merged "All Mailboxes"
203
- * aggregate section) + content area, rendered inside the shared `AppShell` chrome (icon rail, header,
204
- * impersonation banner — see that component). There is no client-side router in this framework (see
205
- * `ReactRoute`'s file-convention resolver) — the selected mailbox/folder (or aggregate pseudo-folder) live
206
- * in the URL's `?mailboxUid=`/`?folderUid=`/`?aggregate=` query params, read once on mount (never during
207
- * the initial render itself, matching every other query-param reader in this codebase — e.g.
208
- * `apps/admin/quarantine`'s `readMailboxUid()` — so the server-rendered and just-hydrated client markup
209
- * match).
210
- *
211
- * Every accessible mailbox's folder tree renders at once - there is no "switch mailbox" affordance
212
- * anymore (the mailbox `<select>` this shell used to have is gone) - so a single-mailbox user sees zero
213
- * behavior change from before this, and a multi-mailbox user sees every mailbox's folders (and the new
214
- * aggregate section) simultaneously, matching the shared-mailbox feature's own "display as a separate set
215
- * of folders" requirement.
216
- */
217
- export default function MailShell({
218
- userUid,
219
- authServerUrl,
220
- impersonating,
221
- impersonationBaseUrl,
222
- trusted,
223
- trustedRoles,
224
- pluginNav,
225
- children,
226
- }: PropsWithChildren<MailShellProps>) {
227
- // The mailboxes, their folders and the live connection come from the persistent app frame when there is one (`AppChrome` owns them, so
228
- // they survive Mail -> Calendar -> Mail and the push socket, pop-ups, counters and tab title work in every app). A page rendered
229
- // 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.
230
- const navigate = useNavigate();
231
- const hosted = useContext(MailConnectionContext);
232
- const own = useMailConnection({ userUid, enabled: !hosted, open: navigate });
233
- const { status, error, mailboxes, mailboxFolders, foldersLoading, onFolderCreated, noteFolderUids, live, folderCounts, outbox: outboxStatuses } = hosted ?? own;
234
- // The messages this tab is still handing to the server: the Outbox pill counts them at once.
235
- const pendingSends = usePendingSends();
236
- const [requestedMailboxUid, setRequestedMailboxUid] = useState<string | null>(null);
237
- const [requestedFolderUid, setRequestedFolderUid] = useState<string | null>(null);
238
- const [requestedAggregateType, setRequestedAggregateType] = useState<string | null>(null);
239
- const [drawerOpen, setDrawerOpen] = useState(false);
240
-
241
- // The selection lives in the URL, and the router (`AppRouter`) changes the URL without a page load when a folder link is
242
- // clicked - so it is read from the router's location, which updates, rather than once from `window.location`. Still read
243
- // in an effect, never during the first render, so the server render and the hydrating render agree.
244
- const search = useLocationSearch();
245
- useEffect(() => {
246
- const params = new URLSearchParams(search);
247
- setRequestedMailboxUid(params.get("mailboxUid"));
248
- setRequestedFolderUid(params.get("folderUid"));
249
- setRequestedAggregateType(params.get("aggregate"));
250
- }, [search]);
251
- // Choosing a folder (or mailbox) changes the URL without a page load now, so the drawer that held the choice - which used to go
252
- // with the page - is closed here.
253
- useEffect(() => {
254
- setDrawerOpen(false);
255
- }, [search]);
256
-
257
- const aggregateFolderType: AggregateFolderType | undefined = isAggregateFolderType(requestedAggregateType)
258
- ? requestedAggregateType
259
- : undefined;
260
-
261
- const mailboxUid: string | undefined = aggregateFolderType
262
- ? undefined
263
- : (requestedMailboxUid && mailboxes.some((mb) => mb.uid === requestedMailboxUid) ? requestedMailboxUid : undefined) ??
264
- mailboxes[0]?.uid;
265
-
266
- const selectedMailboxFolders = mailboxFolders.find((mf) => mf.mailbox.uid === mailboxUid)?.folders ?? [];
267
- const folderUid: string | undefined = aggregateFolderType
268
- ? undefined
269
- : (requestedFolderUid && selectedMailboxFolders.some((f) => f.uid === requestedFolderUid) ? requestedFolderUid : undefined) ??
270
- selectedMailboxFolders.find((f) => f.type === "inbox")?.uid;
271
-
272
- // The mailbox `KeyEnrollmentGate`/`LocalIndexLifecycle`/`ComposeButton` treat as "the" mailbox when
273
- // there's no single selected one to use (aggregate mode) - the caller's own owned mailbox if they
274
- // have one, else whichever accessible mailbox happens to be first. See MailShell's own doc comment on
275
- // this being an accepted limitation: an aggregate-view message from a *different*, not-yet-visited
276
- // mailbox may still need that mailbox's own folder view opened directly to unlock/decrypt it.
277
- const defaultMailboxUid = mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
278
- const activeMailboxUid = mailboxUid ?? defaultMailboxUid;
279
-
280
- const counts = folderCounts.counts;
281
- const trackMessageChange = folderCounts.track;
282
- // `(3) Acme: Mail` in the tab strip while there is unread mail in an Inbox - kept by the frame when there is one.
283
- useUnreadTitle(inboxUnreadTotal(mailboxFolders, counts), { enabled: !hosted });
284
-
285
- const contextValue = useMemo<MailShellContextValue>(
286
- () => ({ mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders, onFolderCreated, noteFolderUids, live, trackMessageChange }),
287
- [mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders, onFolderCreated, noteFolderUids, live, trackMessageChange],
288
- );
289
-
290
- // A full-screen takeover, not nested inside the rest of the app's chrome — there's nothing else for a
291
- // mailbox-less caller to do here yet, so the icon rail/header/folder tree don't render at all. Checks
292
- // `mailboxes.length` directly (not `!mailboxUid`) since `mailboxUid` is legitimately undefined in
293
- // aggregate mode even with mailboxes present.
294
- if (userUid && status === "ready" && mailboxes.length === 0) {
295
- return <MailboxProvisioning />;
296
- }
297
-
298
- let inner: ReactNode = null;
299
- if (userUid && status === "checking") {
300
- // Renders immediately (no network round trip needed) so switching into Mail never shows a blank
301
- // pane while `listMailboxes()` is in flight — the outline below mirrors the real sidebar's shape.
302
- inner = (
303
- <aside className="w-64 shrink-0 bg-surface border-r border-border flex flex-col p-3 gap-4">
304
- <Skeleton height="h-9" className="rounded-sm" />
305
- <SkeletonList count={6} />
306
- </aside>
307
- );
308
- } else if (userUid && status === "error") {
309
- inner = (
310
- <div className="flex-1 flex items-center justify-center p-8">
311
- <div className="w-full max-w-md">
312
- <Alert>{error}</Alert>
313
- </div>
314
- </div>
315
- );
316
- } else if (userUid && status === "ready") {
317
- // A function, not a plain JSX constant — it's rendered twice (desktop `<aside>` + mobile
318
- // `Drawer`), possibly *simultaneously* mounted (the aside is only CSS-hidden below `md`, not
319
- // unmounted).
320
- const sidebarContent = () => (
321
- <>
322
- <div className="p-3">
323
- <ComposeButton mailboxUid={defaultMailboxUid} />
324
- </div>
325
- {foldersLoading ? (
326
- <div className="flex-1 overflow-y-auto px-3 pb-3">
327
- <SkeletonList count={6} className="pt-1" />
328
- </div>
329
- ) : (
330
- <nav className="flex-1 overflow-y-auto px-3 pb-3 flex flex-col gap-3">
331
- {mailboxes.length > 1 && (
332
- <div>
333
- <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5">
334
- All Mailboxes
335
- </div>
336
- <div className="flex flex-col gap-0.5">
337
- {AGGREGATE_FOLDER_TYPES.map((type) => {
338
- const badge = aggregateBadge(mailboxFolders, type, counts);
339
- return (
340
- <a
341
- key={type}
342
- href={`/?aggregate=${encodeURIComponent(type)}`}
343
- className={[
344
- "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
345
- aggregateFolderType === type
346
- ? "bg-primary/10 text-primary-dark font-semibold"
347
- : "text-text hover:bg-surface-alt",
348
- ].join(" ")}
349
- >
350
- <span className={badge?.kind === "unread" ? "font-semibold" : undefined}>{FOLDER_LABELS[type]}</span>
351
- {badge && <FolderBadgeChip badge={badge} />}
352
- </a>
353
- );
354
- })}
355
- </div>
356
- </div>
357
- )}
358
- {mailboxFolders.map(({ mailbox, folders, error: mailboxError }) => (
359
- <div key={mailbox.uid}>
360
- <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5 truncate">
361
- {mailbox.displayName}
362
- {mailbox.ownerUserUid ? "" : " (shared)"}
363
- </div>
364
- {mailboxError && (
365
- <div className="px-2.5 pb-1">
366
- <Alert>{mailboxError}</Alert>
367
- </div>
368
- )}
369
- <div className="flex flex-col gap-0.5">
370
- {folderRows(folders, pendingCountFor(mailbox.uid, pendingSends)).map((row) => {
371
- if (row.kind === "placeholder") {
372
- // A folder the server has not made (or told us about) yet - the Outbox and Sent Items are made with the first message
373
- // sent - shown the moment a message is on its way. Nothing to open; the real folder replaces it when it arrives.
374
- const sending = pendingCountFor(mailbox.uid, pendingSends);
375
- return (
376
- <div
377
- key={`placeholder-${row.type}`}
378
- data-folder-placeholder={row.type}
379
- className="flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5 text-text-muted"
380
- >
381
- <span>{FOLDER_LABELS[row.type]}</span>
382
- {row.type === "outbox" && <OutboxBadge total={sending} pendingHere={sending} />}
383
- </div>
384
- );
385
- }
386
- const folder = row.folder;
387
- const badge = badgeFor(folder.type, countOfFolder(folder, counts));
388
- return (
389
- <a
390
- key={folder.uid}
391
- href={`/?mailboxUid=${encodeURIComponent(mailbox.uid)}&folderUid=${encodeURIComponent(folder.uid)}`}
392
- className={[
393
- "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
394
- folder.uid === folderUid
395
- ? "bg-primary/10 text-primary-dark font-semibold"
396
- : "text-text hover:bg-surface-alt",
397
- ].join(" ")}
398
- >
399
- <span className={badge?.kind === "unread" ? "font-semibold" : undefined}>
400
- {FOLDER_LABELS[folder.type] ?? folder.name}
401
- </span>
402
- {badge &&
403
- (folder.type === "outbox" ? (
404
- <OutboxBadge
405
- total={badge.value}
406
- status={outboxStatuses[folder.uid]}
407
- pendingHere={pendingCountFor(mailbox.uid, pendingSends)}
408
- />
409
- ) : (
410
- <FolderBadgeChip badge={badge} />
411
- ))}
412
- </a>
413
- );
414
- })}
415
- </div>
416
- </div>
417
- ))}
418
- </nav>
419
- )}
420
- </>
421
- );
422
-
423
- inner = (
424
- <>
425
- <MailShortcuts mailboxUid={defaultMailboxUid} />
426
- <aside className="hidden md:flex w-64 shrink-0 bg-surface border-r border-border flex-col">{sidebarContent()}</aside>
427
- <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} title="Folders">
428
- <div className="flex flex-col">{sidebarContent()}</div>
429
- </Drawer>
430
- <main className="flex-1 min-w-0 overflow-y-auto">
431
- <button
432
- type="button"
433
- 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"
434
- aria-label="Open folders"
435
- onClick={() => setDrawerOpen(true)}
436
- >
437
- <HiOutlineBars3 size={20} aria-hidden="true" />
438
- </button>
439
- <MailShellContext.Provider value={contextValue}>{children}</MailShellContext.Provider>
440
- </main>
441
- </>
442
- );
443
- }
444
-
445
- // Wraps AppShell unconditionally, at a stable tree position regardless of whether mailboxUid has
446
- // resolved yet - KeyEnrollmentGate itself passes `children` through untouched until a real
447
- // mailboxUid is supplied (see its own doc comment). Wrapping only once ready (a conditional tree
448
- // position) would make AppShell itself remount the moment mailboxUid resolves, tearing down
449
- // whatever state/effects it had already started (confirmed by direct reproduction: the
450
- // impersonation banner's own internal state was lost exactly at that transition).
451
- const activeMailbox = mailboxes.find((mb) => mb.uid === activeMailboxUid);
452
- return (
453
- <KeyEnrollmentGate
454
- mailboxUid={activeMailboxUid}
455
- mailboxAddress={activeMailbox?.primarySmtpAddress}
456
- mailboxKeys={activeMailbox?.keys}
457
- // Unlocking is only actually required to sign/encrypt a compose, read an already-encrypted
458
- // message, or change encryption settings - not merely to open Mail. Those specific call sites
459
- // (ComposeWindow, MessageDetailPane) request an unlock on demand via useUnlockPrompt() instead.
460
- // First-time provisioning (a mailbox with no vault at all yet) still always blocks - see this
461
- // prop's own doc comment on KeyEnrollmentGateProps.
462
- blocking={false}
463
- // A shared/delegated mailbox the caller doesn't own is never provisioned from here - its keys
464
- // belong to its owner (or its admins), not to whoever happens to open it first - and neither is
465
- // the impersonated user's own mailbox: an administrator must never choose its password/recovery codes.
466
- canProvision={!impersonating && activeMailbox?.ownerUserUid === userUid}
467
- >
468
- <LocalIndexLifecycle
469
- mailboxUid={activeMailboxUid}
470
- mailboxKeys={activeMailbox?.keys}
471
- folders={mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? []}
472
- // A full page may be truncated - pruning against it would delete indexes of accessible mailboxes
473
- // beyond the limit, so it's only trusted as the complete list when it came back short.
474
- accessibleMailboxUids={status === "ready" && mailboxes.length < MAILBOX_LIST_LIMIT ? mailboxes.map((mb) => mb.uid) : undefined}
475
- />
476
- <AppShell
477
- active="mail"
478
- userUid={userUid}
479
- authServerUrl={authServerUrl}
480
- impersonating={impersonating}
481
- impersonationBaseUrl={impersonationBaseUrl}
482
- trusted={trusted}
483
- trustedRoles={trustedRoles}
484
- pluginNav={pluginNav}
485
- >
486
- {inner}
487
- </AppShell>
488
- </KeyEnrollmentGate>
489
- );
490
- }
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, HiOutlinePencilSquare } 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 { MAILBOX_LIST_LIMIT, MailConnectionContext, useMailConnection } from "../../../mail/useMailConnection.js";
19
+ import { folderRows } from "../../../mail/folderTree.js";
20
+ import {
21
+ CountTracker,
22
+ FolderBadge,
23
+ FolderCount,
24
+ badgeFor,
25
+ badgeLabel,
26
+ countOfFolder,
27
+ inboxUnreadTotal,
28
+ } from "../../../mail/folderCounts.js";
29
+ import { useUnreadTitle } from "../../../mail/useUnreadTitle.js";
30
+ import { pendingCountFor, usePendingSends } from "../../../mail/outbox/pendingSends.js";
31
+ import OutboxBadge from "../OutboxBadge.js";
32
+ import { ariaKeyShortcuts, withHint } from "../../../keyboard/format.js";
33
+ import { SHORTCUTS } from "../../../keyboard/keymap.js";
34
+ import { useKeyEnvironment } from "../../../keyboard/ShortcutProvider.js";
35
+ import { useShortcut } from "../../../keyboard/useShortcut.js";
36
+
37
+ export type MailShellProps = Omit<AppShellProps, "active">;
38
+
39
+ /** One mailbox's own mail folders (already filtered to `MAIL_FOLDER_TYPES` and unsorted) - one entry per
40
+ * mailbox in `mailboxes`, fetched in parallel so every accessible mailbox's folder tree can render
41
+ * simultaneously (see `MailShell`'s own doc comment on why this replaced the old single-mailbox `folders`
42
+ * field). `error` is set (and `folders` left empty) for a mailbox whose own `listFolders()` call failed -
43
+ * one mailbox's fetch failure must never blank out every other mailbox's section. */
44
+ export interface MailboxFolders {
45
+ mailbox: Mailbox;
46
+ folders: Folder[];
47
+ error?: string;
48
+ }
49
+
50
+ /** The well-known mail folder types an "aggregate" pseudo-folder can merge across every accessible
51
+ * mailbox - a fixed, small set: `outbox` is deliberately excluded (transient per-mailbox send-queue
52
+ * state, not a "merge across mailboxes" concept), and there's no aggregate concept for `calendar`/
53
+ * `contacts`/`tasks`/`notes`/`user` folders (Mail's own sidebar already excludes those - see
54
+ * `MAIL_FOLDER_TYPES`). */
55
+ export const AGGREGATE_FOLDER_TYPES = ["inbox", "sent_items", "drafts", "deleted_items", "junk"] as const;
56
+ export type AggregateFolderType = (typeof AGGREGATE_FOLDER_TYPES)[number];
57
+
58
+ function isAggregateFolderType(value: string | null): value is AggregateFolderType {
59
+ return !!value && (AGGREGATE_FOLDER_TYPES as readonly string[]).includes(value);
60
+ }
61
+
62
+ export interface MailShellContextValue {
63
+ /** The mailbox currently selected (`?mailboxUid=`) - `undefined` while an aggregate pseudo-folder is
64
+ * active instead (`aggregateFolderType` set), since there's no single mailbox to speak of then. */
65
+ mailboxUid?: string;
66
+ /** The folder currently selected (`?folderUid=`, or the selected mailbox's Inbox) - `undefined` in
67
+ * aggregate mode, for the same reason. */
68
+ folderUid?: string;
69
+ /** Set only when an aggregate pseudo-folder (`?aggregate=inbox` etc.) is selected instead of a real,
70
+ * single mailbox+folder - mutually exclusive with `mailboxUid`/`folderUid` above. */
71
+ aggregateFolderType?: AggregateFolderType;
72
+ mailboxes: Mailbox[];
73
+ /** Every accessible mailbox's own mail folders - replaces the old single-mailbox `folders: Folder[]`
74
+ * now that every mailbox's tree renders at once (see `MailboxFolders`'s own doc comment). */
75
+ mailboxFolders: MailboxFolders[];
76
+ /**
77
+ * Adds a folder a page has just created (the Move to prompt's "New folder") to the tree this shell
78
+ * already fetched, so it appears in the sidebar and in every folder picker without a reload - this
79
+ * framework has no client-side router, so a reload is a whole page load.
80
+ *
81
+ * A no-op on the default context value, which is only ever read outside a real shell.
82
+ */
83
+ onFolderCreated: (folder: Folder) => void;
84
+ /** Says which folders the messages on screen live in: one the sidebar does not know is looked for (see `MailConnection.noteFolderUids`). A no-op on the default context value. */
85
+ noteFolderUids: (folderUids: Iterable<string>) => void;
86
+ /**
87
+ * Bumped whenever new mail (or another change to a message) may have arrived - a push event, a reconnect or the safety-net
88
+ * poll - so the list on screen can quietly refetch its first page. See `useMailLiveUpdates()`. Never changes on the default
89
+ * context value, which is only ever read outside a real shell.
90
+ */
91
+ live: LiveUpdates;
92
+ /**
93
+ * Applies a change to a message (`previous` to `next`; `next` absent when it was deleted) to the folder badges at once, and
94
+ * hands back what to call when the server has answered: `settle()` keeps it, `revert()` takes it back. Every place that
95
+ * reads, moves or deletes a message goes through this (see `setReadState()`), so the badges follow. A no-op on the default
96
+ * context value, which is only ever read outside a real shell.
97
+ */
98
+ trackMessageChange: (previous: Message, next: Message | null) => CountTracker;
99
+ /**
100
+ * The phone layout's header row beside the folders button, for the page to put its search box in (`createPortal()`): the shell
101
+ * owns the row, the page owns the search state. `null` until the row has rendered, and on the default context value.
102
+ */
103
+ mobileSearchSlot: HTMLElement | null;
104
+ }
105
+
106
+ const NO_TRACKER: CountTracker = { settle: () => undefined, revert: () => undefined };
107
+
108
+ const MailShellContext = createContext<MailShellContextValue>({
109
+ mailboxes: [],
110
+ mailboxFolders: [],
111
+ onFolderCreated: () => undefined,
112
+ noteFolderUids: () => undefined,
113
+ live: NO_LIVE_UPDATES,
114
+ trackMessageChange: () => NO_TRACKER,
115
+ mobileSearchSlot: null,
116
+ });
117
+
118
+ /** Reads the mailbox/folder a page is currently showing, as resolved by the enclosing `MailShell`. */
119
+ export function useMailShell(): MailShellContextValue {
120
+ return useContext(MailShellContext);
121
+ }
122
+
123
+ const FOLDER_LABELS: Record<string, string> = {
124
+ inbox: "Inbox",
125
+ sent_items: "Sent Items",
126
+ drafts: "Drafts",
127
+ outbox: "Outbox",
128
+ junk: "Junk Email",
129
+ archive: "Archive",
130
+ deleted_items: "Deleted Items",
131
+ };
132
+
133
+ /** 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. */
134
+ function aggregateBadge(mailboxFolders: MailboxFolders[], type: AggregateFolderType, counts: Record<string, FolderCount>): FolderBadge | undefined {
135
+ const sum = mailboxFolders.reduce(
136
+ (total, mf) => {
137
+ const folder = mf.folders.find((f) => f.type === type);
138
+ const count = folder ? countOfFolder(folder, counts) : { unread: 0, total: 0 };
139
+ return { unread: total.unread + count.unread, total: total.total + count.total };
140
+ },
141
+ { unread: 0, total: 0 },
142
+ );
143
+ return badgeFor(type, sum);
144
+ }
145
+
146
+ /** A folder's badge: an accent pill with the unread count, or - for the folders that show how many they hold - plain muted text. */
147
+ function FolderBadgeChip({ badge }: { badge: FolderBadge }) {
148
+ return (
149
+ <span
150
+ className={[
151
+ "text-xs rounded-pill py-0.5 px-1.5",
152
+ badge.kind === "unread" ? "font-bold bg-primary/15 text-primary-dark" : "font-medium text-text-muted",
153
+ ].join(" ")}
154
+ >
155
+ <span aria-hidden="true">{badge.value}</span>
156
+ <span className="sr-only"> {badgeLabel(badge)}</span>
157
+ </span>
158
+ );
159
+ }
160
+
161
+ type Status = "checking" | "error" | "ready";
162
+
163
+ export { MAILBOX_LIST_LIMIT };
164
+
165
+ /**
166
+ * A separate component (not inlined into `MailShell`'s own render) so `useCompose()` resolves against
167
+ * `ComposeProvider` correctly: that provider is rendered *inside* the `AppShell` that `MailShell` itself
168
+ * returns, i.e. a descendant of `MailShell`, not an ancestor — a hook call made directly in `MailShell`'s
169
+ * own function body would see only whatever context exists *above* `MailShell`, never a provider one of
170
+ * its own descendants creates. This button, rendered as part of `AppShell`'s `children`, sits correctly
171
+ * inside that subtree.
172
+ *
173
+ * Opens with the caller's own mailbox (the shell has already listed them), so the window can start on its
174
+ * signature, draft and encryption lookups straight away instead of first asking which mailbox that is; the
175
+ * compose window's own From field is where the sender is chosen. Fetches the window's code as the pointer or
176
+ * keyboard reaches the button, so the click finds it already here.
177
+ */
178
+ function ComposeButton({ mailboxUid }: { mailboxUid?: string }) {
179
+ const { openCompose } = useCompose();
180
+ const env = useKeyEnvironment();
181
+ return (
182
+ <button
183
+ type="button"
184
+ title={withHint("Compose", SHORTCUTS.mail.create, env)}
185
+ aria-keyshortcuts={ariaKeyShortcuts(SHORTCUTS.mail.create, env)}
186
+ onClick={() => openCompose({ mailboxUid })}
187
+ onPointerEnter={prefetchComposeWindow}
188
+ onFocus={prefetchComposeWindow}
189
+ 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"
190
+ >
191
+ Compose
192
+ </button>
193
+ );
194
+ }
195
+
196
+ /**
197
+ * A small round Compose button floating at the bottom right on a phone, just above the bottom tab bar (which is `h-14`, fixed), for the
198
+ * layout where the sidebar's Compose button is behind the folders drawer. Opens the same window, for the same mailbox, as that button.
199
+ */
200
+ function MobileComposeButton({ mailboxUid }: { mailboxUid?: string }) {
201
+ const { openCompose } = useCompose();
202
+ return (
203
+ <button
204
+ type="button"
205
+ aria-label="New message"
206
+ onClick={() => openCompose({ mailboxUid })}
207
+ onPointerEnter={prefetchComposeWindow}
208
+ onFocus={prefetchComposeWindow}
209
+ className="md:hidden fixed right-4 bottom-[4.5rem] z-30 w-12 h-12 flex items-center justify-center rounded-full bg-primary text-white shadow-lg hover:bg-primary-dark"
210
+ >
211
+ <HiOutlinePencilSquare size={22} aria-hidden="true" />
212
+ </button>
213
+ );
214
+ }
215
+
216
+ /**
217
+ * 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`
218
+ * is - `useCompose()` only resolves below `ComposeProvider`, i.e. inside the `AppShell` this shell renders - and mounted once, whatever number
219
+ * of Compose buttons (the sidebar, the folders drawer) are on screen. Opens the same window, for the same mailbox, as the button.
220
+ */
221
+ function MailShortcuts({ mailboxUid }: { mailboxUid?: string }) {
222
+ const { openCompose } = useCompose();
223
+ useShortcut(SHORTCUTS.mail.create, () => openCompose({ mailboxUid }));
224
+ return null;
225
+ }
226
+
227
+ /**
228
+ * Mail's own contextual sidebar (every accessible mailbox's own folder tree, plus a merged "All Mailboxes"
229
+ * aggregate section) + content area, rendered inside the shared `AppShell` chrome (icon rail, header,
230
+ * impersonation banner — see that component). There is no client-side router in this framework (see
231
+ * `ReactRoute`'s file-convention resolver) — the selected mailbox/folder (or aggregate pseudo-folder) live
232
+ * in the URL's `?mailboxUid=`/`?folderUid=`/`?aggregate=` query params, read once on mount (never during
233
+ * the initial render itself, matching every other query-param reader in this codebase — e.g.
234
+ * `apps/admin/quarantine`'s `readMailboxUid()` — so the server-rendered and just-hydrated client markup
235
+ * match).
236
+ *
237
+ * Every accessible mailbox's folder tree renders at once - there is no "switch mailbox" affordance
238
+ * anymore (the mailbox `<select>` this shell used to have is gone) - so a single-mailbox user sees zero
239
+ * behavior change from before this, and a multi-mailbox user sees every mailbox's folders (and the new
240
+ * aggregate section) simultaneously, matching the shared-mailbox feature's own "display as a separate set
241
+ * of folders" requirement.
242
+ */
243
+ export default function MailShell({
244
+ userUid,
245
+ authServerUrl,
246
+ impersonating,
247
+ impersonationBaseUrl,
248
+ trusted,
249
+ trustedRoles,
250
+ pluginNav,
251
+ children,
252
+ }: PropsWithChildren<MailShellProps>) {
253
+ // The mailboxes, their folders and the live connection come from the persistent app frame when there is one (`AppChrome` owns them, so
254
+ // they survive Mail -> Calendar -> Mail and the push socket, pop-ups, counters and tab title work in every app). A page rendered
255
+ // 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.
256
+ const navigate = useNavigate();
257
+ const hosted = useContext(MailConnectionContext);
258
+ const own = useMailConnection({ userUid, enabled: !hosted, open: navigate });
259
+ const { status, error, mailboxes, mailboxFolders, foldersLoading, onFolderCreated, noteFolderUids, live, folderCounts, outbox: outboxStatuses } = hosted ?? own;
260
+ // The messages this tab is still handing to the server: the Outbox pill counts them at once.
261
+ const pendingSends = usePendingSends();
262
+ const [requestedMailboxUid, setRequestedMailboxUid] = useState<string | null>(null);
263
+ const [requestedFolderUid, setRequestedFolderUid] = useState<string | null>(null);
264
+ const [requestedAggregateType, setRequestedAggregateType] = useState<string | null>(null);
265
+ const [drawerOpen, setDrawerOpen] = useState(false);
266
+
267
+ // The selection lives in the URL, and the router (`AppRouter`) changes the URL without a page load when a folder link is
268
+ // clicked - so it is read from the router's location, which updates, rather than once from `window.location`. Still read
269
+ // in an effect, never during the first render, so the server render and the hydrating render agree.
270
+ const search = useLocationSearch();
271
+ useEffect(() => {
272
+ const params = new URLSearchParams(search);
273
+ setRequestedMailboxUid(params.get("mailboxUid"));
274
+ setRequestedFolderUid(params.get("folderUid"));
275
+ setRequestedAggregateType(params.get("aggregate"));
276
+ }, [search]);
277
+ // Choosing a folder (or mailbox) changes the URL without a page load now, so the drawer that held the choice - which used to go
278
+ // with the page - is closed here.
279
+ useEffect(() => {
280
+ setDrawerOpen(false);
281
+ }, [search]);
282
+
283
+ const aggregateFolderType: AggregateFolderType | undefined = isAggregateFolderType(requestedAggregateType)
284
+ ? requestedAggregateType
285
+ : undefined;
286
+
287
+ const mailboxUid: string | undefined = aggregateFolderType
288
+ ? undefined
289
+ : (requestedMailboxUid && mailboxes.some((mb) => mb.uid === requestedMailboxUid) ? requestedMailboxUid : undefined) ??
290
+ mailboxes[0]?.uid;
291
+
292
+ const selectedMailboxFolders = mailboxFolders.find((mf) => mf.mailbox.uid === mailboxUid)?.folders ?? [];
293
+ const folderUid: string | undefined = aggregateFolderType
294
+ ? undefined
295
+ : (requestedFolderUid && selectedMailboxFolders.some((f) => f.uid === requestedFolderUid) ? requestedFolderUid : undefined) ??
296
+ selectedMailboxFolders.find((f) => f.type === "inbox")?.uid;
297
+
298
+ // The mailbox `KeyEnrollmentGate`/`LocalIndexLifecycle`/`ComposeButton` treat as "the" mailbox when
299
+ // there's no single selected one to use (aggregate mode) - the caller's own owned mailbox if they
300
+ // have one, else whichever accessible mailbox happens to be first. See MailShell's own doc comment on
301
+ // this being an accepted limitation: an aggregate-view message from a *different*, not-yet-visited
302
+ // mailbox may still need that mailbox's own folder view opened directly to unlock/decrypt it.
303
+ const defaultMailboxUid = mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
304
+ const activeMailboxUid = mailboxUid ?? defaultMailboxUid;
305
+
306
+ const counts = folderCounts.counts;
307
+ const trackMessageChange = folderCounts.track;
308
+ // `(3) Acme: Mail` in the tab strip while there is unread mail in an Inbox - kept by the frame when there is one.
309
+ useUnreadTitle(inboxUnreadTotal(mailboxFolders, counts), { enabled: !hosted });
310
+
311
+ // A state rather than a ref: the page reads it during its render, so it has to re-render once the row it names is in the document.
312
+ const [mobileSearchSlot, setMobileSearchSlot] = useState<HTMLElement | null>(null);
313
+ const contextValue = useMemo<MailShellContextValue>(
314
+ () => ({ mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders, onFolderCreated, noteFolderUids, live, trackMessageChange, mobileSearchSlot }),
315
+ [mailboxUid, folderUid, aggregateFolderType, mailboxes, mailboxFolders, onFolderCreated, noteFolderUids, live, trackMessageChange, mobileSearchSlot],
316
+ );
317
+
318
+ // A full-screen takeover, not nested inside the rest of the app's chrome — there's nothing else for a
319
+ // mailbox-less caller to do here yet, so the icon rail/header/folder tree don't render at all. Checks
320
+ // `mailboxes.length` directly (not `!mailboxUid`) since `mailboxUid` is legitimately undefined in
321
+ // aggregate mode even with mailboxes present.
322
+ if (userUid && status === "ready" && mailboxes.length === 0) {
323
+ return <MailboxProvisioning />;
324
+ }
325
+
326
+ let inner: ReactNode = null;
327
+ if (userUid && status === "checking") {
328
+ // Renders immediately (no network round trip needed) so switching into Mail never shows a blank
329
+ // pane while `listMailboxes()` is in flight — the outline below mirrors the real sidebar's shape.
330
+ inner = (
331
+ <aside className="w-64 shrink-0 bg-surface border-r border-border flex flex-col p-3 gap-4">
332
+ <Skeleton height="h-9" className="rounded-sm" />
333
+ <SkeletonList count={6} />
334
+ </aside>
335
+ );
336
+ } else if (userUid && status === "error") {
337
+ inner = (
338
+ <div className="flex-1 flex items-center justify-center p-8">
339
+ <div className="w-full max-w-md">
340
+ <Alert>{error}</Alert>
341
+ </div>
342
+ </div>
343
+ );
344
+ } else if (userUid && status === "ready") {
345
+ // A function, not a plain JSX constant — it's rendered twice (desktop `<aside>` + mobile
346
+ // `Drawer`), possibly *simultaneously* mounted (the aside is only CSS-hidden below `md`, not
347
+ // unmounted).
348
+ const sidebarContent = () => (
349
+ <>
350
+ <div className="p-3">
351
+ <ComposeButton mailboxUid={defaultMailboxUid} />
352
+ </div>
353
+ {foldersLoading ? (
354
+ <div className="flex-1 overflow-y-auto px-3 pb-3">
355
+ <SkeletonList count={6} className="pt-1" />
356
+ </div>
357
+ ) : (
358
+ <nav className="flex-1 overflow-y-auto px-3 pb-3 flex flex-col gap-3">
359
+ {mailboxes.length > 1 && (
360
+ <div>
361
+ <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5">
362
+ All Mailboxes
363
+ </div>
364
+ <div className="flex flex-col gap-0.5">
365
+ {AGGREGATE_FOLDER_TYPES.map((type) => {
366
+ const badge = aggregateBadge(mailboxFolders, type, counts);
367
+ return (
368
+ <a
369
+ key={type}
370
+ href={`/?aggregate=${encodeURIComponent(type)}`}
371
+ className={[
372
+ "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
373
+ aggregateFolderType === type
374
+ ? "bg-primary/10 text-primary-dark font-semibold"
375
+ : "text-text hover:bg-surface-alt",
376
+ ].join(" ")}
377
+ >
378
+ <span className={badge?.kind === "unread" ? "font-semibold" : undefined}>{FOLDER_LABELS[type]}</span>
379
+ {badge && <FolderBadgeChip badge={badge} />}
380
+ </a>
381
+ );
382
+ })}
383
+ </div>
384
+ </div>
385
+ )}
386
+ {mailboxFolders.map(({ mailbox, folders, error: mailboxError }) => (
387
+ <div key={mailbox.uid}>
388
+ <div className="text-xs font-bold uppercase tracking-wide text-text-muted mb-1 px-2.5 truncate">
389
+ {mailbox.displayName}
390
+ {mailbox.ownerUserUid ? "" : " (shared)"}
391
+ </div>
392
+ {mailboxError && (
393
+ <div className="px-2.5 pb-1">
394
+ <Alert>{mailboxError}</Alert>
395
+ </div>
396
+ )}
397
+ <div className="flex flex-col gap-0.5">
398
+ {folderRows(folders, pendingCountFor(mailbox.uid, pendingSends)).map((row) => {
399
+ if (row.kind === "placeholder") {
400
+ // A folder the server has not made (or told us about) yet - the Outbox and Sent Items are made with the first message
401
+ // sent - shown the moment a message is on its way. Nothing to open; the real folder replaces it when it arrives.
402
+ const sending = pendingCountFor(mailbox.uid, pendingSends);
403
+ return (
404
+ <div
405
+ key={`placeholder-${row.type}`}
406
+ data-folder-placeholder={row.type}
407
+ className="flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5 text-text-muted"
408
+ >
409
+ <span>{FOLDER_LABELS[row.type]}</span>
410
+ {row.type === "outbox" && <OutboxBadge total={sending} pendingHere={sending} />}
411
+ </div>
412
+ );
413
+ }
414
+ const folder = row.folder;
415
+ const badge = badgeFor(folder.type, countOfFolder(folder, counts));
416
+ return (
417
+ <a
418
+ key={folder.uid}
419
+ href={`/?mailboxUid=${encodeURIComponent(mailbox.uid)}&folderUid=${encodeURIComponent(folder.uid)}`}
420
+ className={[
421
+ "flex items-center justify-between text-sm rounded-sm py-1.5 px-2.5",
422
+ folder.uid === folderUid
423
+ ? "bg-primary/10 text-primary-dark font-semibold"
424
+ : "text-text hover:bg-surface-alt",
425
+ ].join(" ")}
426
+ >
427
+ <span className={badge?.kind === "unread" ? "font-semibold" : undefined}>
428
+ {FOLDER_LABELS[folder.type] ?? folder.name}
429
+ </span>
430
+ {badge &&
431
+ (folder.type === "outbox" ? (
432
+ <OutboxBadge
433
+ total={badge.value}
434
+ status={outboxStatuses[folder.uid]}
435
+ pendingHere={pendingCountFor(mailbox.uid, pendingSends)}
436
+ />
437
+ ) : (
438
+ <FolderBadgeChip badge={badge} />
439
+ ))}
440
+ </a>
441
+ );
442
+ })}
443
+ </div>
444
+ </div>
445
+ ))}
446
+ </nav>
447
+ )}
448
+ </>
449
+ );
450
+
451
+ inner = (
452
+ <>
453
+ <MailShortcuts mailboxUid={defaultMailboxUid} />
454
+ <aside className="hidden md:flex w-64 shrink-0 bg-surface border-r border-border flex-col">{sidebarContent()}</aside>
455
+ <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} title="Folders">
456
+ <div className="flex flex-col">{sidebarContent()}</div>
457
+ </Drawer>
458
+ <main className="flex-1 min-w-0 overflow-y-auto">
459
+ <div className="md:hidden flex items-center gap-2 p-3">
460
+ <button
461
+ type="button"
462
+ className="shrink-0 w-9 h-9 flex items-center justify-center rounded-sm text-text-muted hover:bg-surface-alt hover:text-text"
463
+ aria-label="Open folders"
464
+ onClick={() => setDrawerOpen(true)}
465
+ >
466
+ <HiOutlineBars3 size={20} aria-hidden="true" />
467
+ </button>
468
+ <div ref={setMobileSearchSlot} className="flex-1 min-w-0" />
469
+ </div>
470
+ <MobileComposeButton mailboxUid={defaultMailboxUid} />
471
+ <MailShellContext.Provider value={contextValue}>{children}</MailShellContext.Provider>
472
+ </main>
473
+ </>
474
+ );
475
+ }
476
+
477
+ // Wraps AppShell unconditionally, at a stable tree position regardless of whether mailboxUid has
478
+ // resolved yet - KeyEnrollmentGate itself passes `children` through untouched until a real
479
+ // mailboxUid is supplied (see its own doc comment). Wrapping only once ready (a conditional tree
480
+ // position) would make AppShell itself remount the moment mailboxUid resolves, tearing down
481
+ // whatever state/effects it had already started (confirmed by direct reproduction: the
482
+ // impersonation banner's own internal state was lost exactly at that transition).
483
+ const activeMailbox = mailboxes.find((mb) => mb.uid === activeMailboxUid);
484
+ return (
485
+ <KeyEnrollmentGate
486
+ mailboxUid={activeMailboxUid}
487
+ mailboxAddress={activeMailbox?.primarySmtpAddress}
488
+ mailboxKeys={activeMailbox?.keys}
489
+ // Unlocking is only actually required to sign/encrypt a compose, read an already-encrypted
490
+ // message, or change encryption settings - not merely to open Mail. Those specific call sites
491
+ // (ComposeWindow, MessageDetailPane) request an unlock on demand via useUnlockPrompt() instead.
492
+ // First-time provisioning (a mailbox with no vault at all yet) still always blocks - see this
493
+ // prop's own doc comment on KeyEnrollmentGateProps.
494
+ blocking={false}
495
+ // A shared/delegated mailbox the caller doesn't own is never provisioned from here - its keys
496
+ // belong to its owner (or its admins), not to whoever happens to open it first - and neither is
497
+ // the impersonated user's own mailbox: an administrator must never choose its password/recovery codes.
498
+ canProvision={!impersonating && activeMailbox?.ownerUserUid === userUid}
499
+ >
500
+ <LocalIndexLifecycle
501
+ mailboxUid={activeMailboxUid}
502
+ mailboxKeys={activeMailbox?.keys}
503
+ folders={mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? []}
504
+ // A full page may be truncated - pruning against it would delete indexes of accessible mailboxes
505
+ // beyond the limit, so it's only trusted as the complete list when it came back short.
506
+ accessibleMailboxUids={status === "ready" && mailboxes.length < MAILBOX_LIST_LIMIT ? mailboxes.map((mb) => mb.uid) : undefined}
507
+ />
508
+ <AppShell
509
+ active="mail"
510
+ userUid={userUid}
511
+ authServerUrl={authServerUrl}
512
+ impersonating={impersonating}
513
+ impersonationBaseUrl={impersonationBaseUrl}
514
+ trusted={trusted}
515
+ trustedRoles={trustedRoles}
516
+ pluginNav={pluginNav}
517
+ >
518
+ {inner}
519
+ </AppShell>
520
+ </KeyEnrollmentGate>
521
+ );
522
+ }