@rapidmx/web-client 0.18.0 → 0.20.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 (131) hide show
  1. package/README.md +381 -381
  2. package/apps/admin/branding/index.tsx +39 -39
  3. package/apps/admin/data-requests/index.tsx +482 -482
  4. package/apps/admin/domains/[uid].tsx +166 -166
  5. package/apps/admin/escrow-scopes/[uid].tsx +350 -350
  6. package/apps/admin/index.tsx +129 -129
  7. package/apps/admin/mailboxes/[uid].tsx +271 -271
  8. package/apps/admin/mailboxes/new/index.tsx +30 -30
  9. package/apps/admin/plugins/index.tsx +15 -15
  10. package/apps/admin/retention-policy/index.tsx +39 -39
  11. package/apps/admin/signing-certificates/index.tsx +343 -343
  12. package/apps/escrow/audit-log/index.tsx +196 -196
  13. package/apps/escrow/matters/[uid].tsx +621 -621
  14. package/apps/shared/auth/adminAccess.ts +99 -99
  15. package/apps/shared/components/admin/diagnostics/HostCard.tsx +2 -0
  16. package/apps/shared/components/admin/diagnostics/PressureTiles.tsx +108 -0
  17. package/apps/shared/components/admin/diagnostics/PvcTable.tsx +20 -6
  18. package/apps/shared/components/admin/diagnostics/diagnosticsApi.ts +21 -2
  19. package/apps/shared/components/admin/layout/AdminShell.tsx +384 -384
  20. package/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.tsx +238 -238
  21. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -152
  22. package/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.tsx +194 -194
  23. package/apps/shared/components/admin/settings/BrandingForm.tsx +423 -423
  24. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -119
  25. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +198 -198
  26. package/apps/shared/components/admin/settings/PluginsManager.tsx +2093 -1545
  27. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +182 -182
  28. package/apps/shared/components/admin/settings/pluginPreferences.ts +34 -0
  29. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -288
  30. package/apps/shared/components/admin/setup/SetupWizard.tsx +446 -446
  31. package/apps/shared/components/admin/usePagedList.tsx +129 -129
  32. package/apps/shared/components/calendar/EventModal.tsx +206 -206
  33. package/apps/shared/components/calendar/MonthView.tsx +185 -185
  34. package/apps/shared/components/calendar/RecurrenceEditor.tsx +227 -227
  35. package/apps/shared/components/calendar/SplitDayView.tsx +144 -144
  36. package/apps/shared/components/calendar/TimeGridView.tsx +246 -246
  37. package/apps/shared/components/calendar/allDay.ts +124 -124
  38. package/apps/shared/components/contacts/ContactForm.tsx +383 -383
  39. package/apps/shared/components/contacts/ContactsToolbar.tsx +103 -103
  40. package/apps/shared/components/escrow/layout/EscrowShell.tsx +155 -155
  41. package/apps/shared/components/layout/AppShell.tsx +461 -461
  42. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +398 -398
  43. package/apps/shared/components/layout/MailboxProvisioning.tsx +168 -168
  44. package/apps/shared/components/layout/ResponsiveToolbar.tsx +315 -315
  45. package/apps/shared/components/layout/ThemeSwitch.tsx +84 -84
  46. package/apps/shared/components/layout/UserMenu.tsx +439 -439
  47. package/apps/shared/components/mail/ConversationList.tsx +332 -323
  48. package/apps/shared/components/mail/ConversationThreadPane.tsx +613 -613
  49. package/apps/shared/components/mail/MailSelectionBar.tsx +240 -240
  50. package/apps/shared/components/mail/MenuButton.tsx +404 -404
  51. package/apps/shared/components/mail/MessageDetailPane.tsx +1757 -1757
  52. package/apps/shared/components/mail/compose/ComposeContext.tsx +312 -312
  53. package/apps/shared/components/mail/compose/ComposeToolbar.tsx +422 -422
  54. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1681 -1681
  55. package/apps/shared/components/mail/compose/RichTextEditor.tsx +147 -147
  56. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -60
  57. package/apps/shared/components/mail/compose/quotedBody.ts +161 -161
  58. package/apps/shared/components/mail/listPreferences.ts +3 -3
  59. package/apps/shared/components/mail/reading/MessageMoreMenu.tsx +258 -258
  60. package/apps/shared/components/mail/reading/MessageSourceDialog.tsx +79 -79
  61. package/apps/shared/components/mail/reading/messageExport.ts +59 -59
  62. package/apps/shared/components/mail/reading/printMessage.ts +99 -99
  63. package/apps/shared/components/mail/reading/useMessageActions.ts +443 -443
  64. package/apps/shared/components/mail/verificationSeals.ts +125 -125
  65. package/apps/shared/components/rules/RuleBuilder.tsx +311 -311
  66. package/apps/shared/components/settings/SigningCertificateCard.tsx +344 -344
  67. package/apps/shared/keyboard/GlobalShortcuts.tsx +51 -51
  68. package/apps/shared/keyboard/ShortcutProvider.tsx +62 -62
  69. package/apps/shared/keyboard/ShortcutsDialog.tsx +84 -84
  70. package/apps/shared/keyboard/dispatch.ts +124 -124
  71. package/apps/shared/keyboard/format.ts +89 -89
  72. package/apps/shared/keyboard/keymap.ts +114 -114
  73. package/apps/shared/keyboard/registry.ts +65 -65
  74. package/apps/shared/keyboard/targets.ts +79 -79
  75. package/apps/shared/mail/folderOfType.ts +49 -49
  76. package/apps/shared/mail/folderTree.ts +143 -143
  77. package/apps/shared/mail/listAllPages.ts +39 -39
  78. package/apps/shared/mail/newMailNotifications.ts +171 -171
  79. package/apps/shared/mail/outbox/sendJob.ts +445 -445
  80. package/apps/shared/mail/outbox/sendOutcomes.ts +155 -155
  81. package/apps/shared/mail/reportNotices.ts +66 -66
  82. package/apps/shared/mail/senderBlocking.ts +141 -141
  83. package/apps/shared/mail/useMailConnection.ts +205 -205
  84. package/apps/shared/mail/useMailLiveUpdates.ts +277 -277
  85. package/apps/shared/mail/useMailboxUpdateAccess.ts +60 -60
  86. package/apps/shared/mail/useMarkMessageRead.ts +47 -47
  87. package/apps/shared/mail/useNewMailNotifications.ts +178 -178
  88. package/apps/shared/notifications/store.ts +560 -560
  89. package/apps/shared/search/LocalIndexLifecycle.tsx +114 -114
  90. package/apps/shared/search/localIndexBuilder.ts +481 -481
  91. package/apps/shared/signing/enrollmentStorage.ts +33 -33
  92. package/apps/shared/signing/enrollmentTracker.ts +385 -385
  93. package/apps/shared/signing/enrollmentView.ts +251 -251
  94. package/apps/shared/signing/useNow.ts +19 -19
  95. package/apps/shared/signing/useSigningEnrollmentWatcher.ts +90 -90
  96. package/apps/shared/styles/app.css +396 -396
  97. package/apps/www/calendar/index.tsx +581 -581
  98. package/apps/www/contacts/[uid].tsx +112 -112
  99. package/apps/www/index.tsx +3012 -2962
  100. package/apps/www/messages/[uid].tsx +139 -139
  101. package/apps/www/settings/auto-reply/index.tsx +136 -136
  102. package/apps/www/settings/blocked-senders/index.tsx +303 -303
  103. package/apps/www/settings/encryption/index.tsx +1290 -1290
  104. package/apps/www/settings/filters/[uid].tsx +179 -179
  105. package/apps/www/settings/filters/index.tsx +105 -105
  106. package/apps/www/settings/filters/new/index.tsx +165 -165
  107. package/apps/www/settings/labels/index.tsx +207 -207
  108. package/apps/www/settings/privacy/index.tsx +495 -495
  109. package/apps/www/settings/profile/index.tsx +251 -251
  110. package/apps/www/settings/read-receipts/index.tsx +150 -150
  111. package/apps/www/settings/sharing/index.tsx +259 -259
  112. package/apps/www/settings/signatures/[uid].tsx +175 -175
  113. package/apps/www/settings/signatures/index.tsx +91 -91
  114. package/apps/www/settings/signatures/new/index.tsx +138 -138
  115. package/apps/www/tasks/index.tsx +654 -654
  116. package/dist/apps/shared/components/admin/diagnostics/HostCard.js +2 -1
  117. package/dist/apps/shared/components/admin/diagnostics/PressureTiles.d.ts +22 -0
  118. package/dist/apps/shared/components/admin/diagnostics/PressureTiles.js +52 -0
  119. package/dist/apps/shared/components/admin/diagnostics/PvcTable.js +9 -4
  120. package/dist/apps/shared/components/admin/diagnostics/diagnosticsApi.d.ts +35 -2
  121. package/dist/apps/shared/components/admin/settings/BrandingForm.js +3 -3
  122. package/dist/apps/shared/components/admin/settings/PluginsManager.js +328 -48
  123. package/dist/apps/shared/components/admin/settings/pluginPreferences.d.ts +2 -0
  124. package/dist/apps/shared/components/admin/settings/pluginPreferences.js +35 -0
  125. package/dist/apps/shared/components/mail/ConversationList.d.ts +10 -3
  126. package/dist/apps/shared/components/mail/ConversationList.js +9 -5
  127. package/dist/apps/shared/components/mail/listPreferences.d.ts +1 -1
  128. package/dist/apps/shared/components/mail/reading/printMessage.js +11 -11
  129. package/dist/apps/shared/styles/app.css +396 -396
  130. package/dist/apps/www/index.js +51 -10
  131. package/package.json +2 -2
@@ -1,613 +1,613 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
6
- import { flushSync } from "react-dom";
7
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
- import { Attachment, Folder, Message, listAttachments } from "@rapidmx/react-shared/mail/mailApi.js";
9
- import { ConversationSummary, listConversationMessages } from "@rapidmx/react-shared/mail/conversationsApi.js";
10
- import { Label } from "@rapidmx/react-shared/mail/labelsApi.js";
11
- import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
12
- import MessageDetailPane from "./MessageDetailPane.js";
13
- import { EncryptedPreview, displaySubject } from "./reading/EncryptedPreview.js";
14
- import { CollapsedCard, SkeletonCards, SubjectCard } from "./reading/MessageCard.js";
15
- import PendingMessageCard from "./reading/PendingMessageCard.js";
16
- import { useMailShell } from "./layout/MailShell.js";
17
- import { setReadState } from "../../mail/messageReadState.js";
18
- import { adoptedOutgoing, belongsToThread, settleOutgoing, useOutgoingReplies } from "../../mail/outbox/outgoingReplies.js";
19
- import { dateClass, isUnread, senderClass } from "./unreadStyle.js";
20
-
21
- /** One request's worth of the thread. The server's own default for `listConversationMessages()`. */
22
- export const THREAD_PAGE_SIZE = 100;
23
- /**
24
- * How many of a conversation's messages this pane will load. The server reads at most
25
- * `CONVERSATION_SCAN_LIMIT` (500) messages when it groups conversations, so a `ConversationSummary` never
26
- * describes more than this many anyway; the cap is here so a thread that somehow reports more can't turn
27
- * into an unbounded run of requests. Past it the pane says so and the rest stay readable from the list.
28
- */
29
- export const THREAD_MESSAGE_LIMIT = 500;
30
-
31
- /** What the pane needs to know of a conversation up front: the thread itself is loaded by `conversationId`. The subject and
32
- * count fill the header while it loads, so a caller that only has a message (the mobile route) gives its subject and a count of 1. */
33
- export type ConversationThreadHead = Pick<ConversationSummary, "conversationId" | "subject" | "messageCount">;
34
-
35
- export interface ConversationThreadPaneProps {
36
- conversation: ConversationThreadHead | null;
37
- /** The mailbox the conversation was listed from - `listConversationMessages()` is mailbox-scoped. */
38
- mailboxUid: string;
39
- /**
40
- * The message the reader opened: the thread is scrolled to it, it takes focus, and it is the *oldest*
41
- * message left expanded (see `expandedFrom()`). `null`, or a uid this thread doesn't hold, falls back
42
- * to the newest message - which is also what a parent row means by "open the conversation".
43
- */
44
- selectedUid: string | null;
45
- /** The mailbox's full folder list. A conversation spans folders (an Inbox message and the Sent Items
46
- * copy of its reply), so each message's own folder type is looked up against its own `folderUid`. */
47
- folders: Folder[];
48
- /** The mailbox's labels, passed through to every expanded message's own `MessageDetailPane`. */
49
- labels?: Label[];
50
- /**
51
- * A newer copy of one of the thread's messages - read, flagged, labelled, classified, recalled - for
52
- * the caller's own list to stay in step with what was done in here.
53
- *
54
- * `previous` is the copy this pane held before the change, where it has one: the conversation row this
55
- * thread came from is a *summary* (a message count, an unread count), so a list showing those rows has
56
- * no way to tell "this message has just been read" from "this already-read message was relabelled"
57
- * without it - which is what left a row reporting "2 unread" after both had been read.
58
- */
59
- onMessagePatched: (updated: Message, previous?: Message) => void;
60
- /** A message that left the folder being listed (archived, or a scheduled send sent back to Drafts). */
61
- onMessageRemoved: (updated: Message) => void;
62
- onLabelCreated?: (label: Label) => void;
63
- /** A folder created from a message's own Move to prompt, for the folder sidebar to pick up. */
64
- onFolderCreated?: (folder: Folder) => void;
65
- /** Registers the keyboard shortcuts (Reply, Reply all, Forward, Archive, Move to) of the message that was opened - see `MessageDetailPane`'s
66
- * `shortcuts`. The caller turns it off while it is doing something else with the keyboard (select mode). */
67
- shortcuts?: boolean;
68
- }
69
-
70
- /**
71
- * Every message from `selectedUid` through to the newest - the run the reader is reading. Anything older
72
- * stays collapsed to its one-line summary. Selecting the newest message therefore expands just that one.
73
- *
74
- * The pane lists newest first (see `loadThread()`), so that run is the opened message together with
75
- * everything *above* it, and the opened message is the set's **last** entry rather than its first.
76
- */
77
- function expandedFrom(messages: Message[], selectedUid: string | null): Set<string> {
78
- const index = messages.findIndex((message) => message.uid === selectedUid);
79
- // `messages` is never empty here (the callers below check), so -1 means "not in this thread" and the
80
- // newest message - the first entry - is the anchor, exactly as a parent row's own click means.
81
- const anchor = index === -1 ? 0 : index;
82
- return new Set(messages.slice(0, anchor + 1).map((message) => message.uid));
83
- }
84
-
85
- /**
86
- * The element a message of this thread actually scrolls inside. The pane is not itself the scroll
87
- * container in the mail shell - `MailShell`'s own `<main>` is - so an adjustment has to be applied where
88
- * the scrolling really happens, which is whichever ancestor is both scrollable and overflowing.
89
- */
90
- function scrollingAncestor(node: HTMLElement): HTMLElement {
91
- for (let el = node.parentElement; el; el = el.parentElement) {
92
- const overflowY = getComputedStyle(el).overflowY;
93
- if ((overflowY === "auto" || overflowY === "scroll") && el.scrollHeight > el.clientHeight) {
94
- return el;
95
- }
96
- }
97
- // Nothing between the row and the root scrolls, so the page itself does - which in standards mode is
98
- // `documentElement`, the same element `document.scrollingElement` names there.
99
- return document.documentElement;
100
- }
101
-
102
- /**
103
- * The thread's messages, **newest first**, in pages of `THREAD_PAGE_SIZE` up to `THREAD_MESSAGE_LIMIT`.
104
- *
105
- * `listConversationMessages()` pages oldest first and has no order of its own to ask for, so the pages are
106
- * collected in that order - which is also the order the `THREAD_MESSAGE_LIMIT` cap has to apply in, since it
107
- * is the oldest messages that are dropped when a thread is too long to load - and reversed once at the end.
108
- * The pane reads newest first always, whatever the *list* is sorted by: it is the reading order for mail,
109
- * and it means the message a conversation row stands for is the entry at the top.
110
- */
111
- async function loadThread(mailboxUid: string, conversationId: string): Promise<{ messages: Message[]; truncated: boolean }> {
112
- const messages: Message[] = [];
113
- let more = true;
114
- while (more && messages.length < THREAD_MESSAGE_LIMIT) {
115
- const page = await listConversationMessages(mailboxUid, conversationId, {
116
- page: messages.length / THREAD_PAGE_SIZE,
117
- limit: THREAD_PAGE_SIZE,
118
- });
119
- messages.push(...page);
120
- // A short page is the last one; a full page means asking for another.
121
- more = page.length === THREAD_PAGE_SIZE;
122
- }
123
- messages.reverse();
124
- return { messages, truncated: more };
125
- }
126
-
127
- /**
128
- * `next` - the thread as it was just read again - for the pane to show in place of `previous`. A message the pane holds a newer copy of (one that
129
- * was read, flagged or labelled here a moment ago, whose change the read may have started before) keeps that copy, and a read that changed
130
- * nothing gives back `previous` itself, so the pane is not drawn again.
131
- */
132
- function mergeThread(previous: Message[], next: Message[]): Message[] {
133
- const held = new Map(previous.map((message) => [message.uid, message]));
134
- const merged = next.map((message) => {
135
- const own = held.get(message.uid);
136
- return own && own.version > message.version ? own : message;
137
- });
138
- const unchanged = merged.length === previous.length && merged.every((message, index) => message.uid === previous[index].uid && message.version === previous[index].version);
139
- return unchanged ? previous : merged;
140
- }
141
-
142
- /** Whether the browser is showing a focus ring on `element` - it was focused from the keyboard (or by a key press's handler), not by a click. */
143
- function hasFocusRing(element: HTMLElement): boolean {
144
- try {
145
- return element.matches(":focus-visible");
146
- } catch {
147
- return false;
148
- }
149
- }
150
-
151
- /**
152
- * The reading pane for the conversation list: the conversation's subject in a card of its own, pinned at the top, and under it the whole thread as
153
- * a stack of message cards (each exactly as tall as its message; the list scrolls as a whole), **newest at the top**, opened at the message
154
- * the reader picked. Every message from that one through to the newest is expanded - which in this order is
155
- * the opened message and the entries above it - and the older ones, below it, are collapsed to a one-line
156
- * summary (sender, date, preview) that expands on click or Enter. So opening the newest message shows just
157
- * the top entry expanded, and opening 5 of 10 expands 10 down to 5.
158
- *
159
- * Newest first regardless of how the *list* is sorted: the list's own order arranges rows to pick from,
160
- * while this is one conversation being read, and the entry a conversation row stands for - its latest
161
- * message - is the one that should be at the top of the pane every time it is opened.
162
- *
163
- * Each *expanded* message is a `MessageDetailPane` of its own rather than a reimplementation of it, so the
164
- * signature and verification badges, the verification-seal and decryption behaviour, the labels chips and
165
- * menu, the attachments and Reply/Reply All/Forward/Archive all behave exactly as they do in the
166
- * single-message pane, and each acts on the message it belongs to. A collapsed message mounts none of
167
- * that - mounting a body iframe per message up front would be wasteful in a long thread.
168
- */
169
- export default function ConversationThreadPane({
170
- conversation,
171
- mailboxUid,
172
- selectedUid,
173
- folders,
174
- labels,
175
- onMessagePatched,
176
- onMessageRemoved,
177
- onLabelCreated,
178
- onFolderCreated,
179
- shortcuts,
180
- }: ConversationThreadPaneProps) {
181
- const { trackMessageChange, live } = useMailShell();
182
- // The replies and forwards this tab has sent, drawn at the top of the thread they continue until the server's own copy is in it.
183
- const outgoing = useOutgoingReplies();
184
- const [messages, setMessages] = useState<Message[]>([]);
185
- const [attachmentsByUid, setAttachmentsByUid] = useState<Record<string, Attachment[]>>({});
186
- const [expandedUids, setExpandedUids] = useState<Set<string>>(new Set());
187
- const [truncated, setTruncated] = useState(false);
188
- const [loading, setLoading] = useState(false);
189
- const [error, setError] = useState<string | null>(null);
190
- /** The message to scroll to and focus once it has rendered, or `null` once that has happened. */
191
- const [pendingFocusUid, setPendingFocusUid] = useState<string | null>(null);
192
-
193
- // Bumped on every conversation switch - an in-flight load/attachments/mark-read response carrying an
194
- // older generation belongs to a superseded conversation and is dropped rather than applied.
195
- const generationRef = useRef(0);
196
- const markReadRequestedRef = useRef<Set<string>>(new Set());
197
- const attachmentsRequestedRef = useRef<Set<string>>(new Set());
198
- /** The `conversationId:selectedUid` the expansion run below has already been applied for, so patching
199
- * a message (which changes `messages`) doesn't re-expand what the reader has since collapsed. */
200
- const appliedSelectionRef = useRef<string | null>(null);
201
- /** Which conversation the messages currently in state belong to. A render with a new conversation and
202
- * the previous one's messages still in state happens before the load effect has cleared them, and the
203
- * expansion run below must sit that render out rather than anchor on a message from another thread. */
204
- const loadedIdRef = useRef<string | null>(null);
205
- const rowRefs = useRef<Record<string, HTMLLIElement | null>>({});
206
- const headerRefs = useRef<Record<string, HTMLElement | null>>({});
207
- /** Where the toggled message's header sat in the viewport before it expanded, so the run below can put
208
- * it back there - expanding a message above the one being read must not shove that one off-screen. */
209
- const anchorRef = useRef<{ uid: string; top: number } | null>(null);
210
- /** The message whose header button had the focus when it was toggled: expanding or collapsing swaps that button for the other state's, so the
211
- * focus is put back on the new one. */
212
- const refocusRef = useRef<string | null>(null);
213
- /** The pending cards that have already been scrolled to, so that only a message that has just been sent takes the view and the focus. */
214
- const announcedRef = useRef<Set<string>>(new Set());
215
- /** Messages that left the thread here (archived, moved, a scheduled send taken back): a read of the thread again still lists them, since a conversation spans folders. */
216
- const removedRef = useRef<Set<string>>(new Set());
217
- /** The last live update this pane has answered - one already in the shell's hands when the pane opened is not news. */
218
- const seenLiveRef = useRef(live);
219
-
220
- const conversationId = conversation?.conversationId;
221
-
222
- useEffect(() => {
223
- const generation = ++generationRef.current;
224
- markReadRequestedRef.current = new Set();
225
- attachmentsRequestedRef.current = new Set();
226
- announcedRef.current = new Set();
227
- removedRef.current = new Set();
228
- appliedSelectionRef.current = null;
229
- loadedIdRef.current = null;
230
- setMessages([]);
231
- setAttachmentsByUid({});
232
- setExpandedUids(new Set());
233
- setTruncated(false);
234
- setError(null);
235
- // The message the previous conversation was to be scrolled to went with it; leaving it set would
236
- // point the run below at a row that is no longer rendered.
237
- setPendingFocusUid(null);
238
- if (!conversationId) {
239
- setLoading(false);
240
- return;
241
- }
242
- setLoading(true);
243
- loadThread(mailboxUid, conversationId)
244
- .then((loaded) => {
245
- if (generation !== generationRef.current) return;
246
- loadedIdRef.current = conversationId;
247
- // A message sent from here whose Sent Items copy is already in the thread is drawn as that copy, not as a pending card.
248
- settleOutgoing(mailboxUid, loaded.messages);
249
- setMessages(loaded.messages);
250
- setTruncated(loaded.truncated);
251
- })
252
- .catch((err) => {
253
- if (generation !== generationRef.current) return;
254
- setError(err instanceof ApiRequestError ? err.message : "Could not load this conversation.");
255
- })
256
- .finally(() => {
257
- if (generation === generationRef.current) setLoading(false);
258
- });
259
- }, [conversationId, mailboxUid]);
260
-
261
- // Opening the thread, and opening a different message of the same thread, both set the run of expanded
262
- // messages and ask for that message to be scrolled to. `messages` is a dependency because the thread's
263
- // messages arrive after the click that selected one of them; the ref guard keeps a later change to
264
- // `messages` (a patched copy) from re-running it.
265
- useEffect(() => {
266
- if (messages.length === 0 || loadedIdRef.current !== conversationId) return;
267
- const key = `${conversationId}:${selectedUid}`;
268
- if (appliedSelectionRef.current === key) return;
269
- appliedSelectionRef.current = key;
270
- const expanded = expandedFrom(messages, selectedUid);
271
- setExpandedUids(expanded);
272
- // The oldest expanded message is the one that was opened - `expandedFrom()`'s own anchor - which in
273
- // this newest-first order is the *last* of the run, not the first.
274
- setPendingFocusUid([...expanded][expanded.size - 1]);
275
- }, [conversationId, selectedUid, messages]);
276
-
277
- useLayoutEffect(() => {
278
- if (!pendingFocusUid) return;
279
- // The row is always rendered by now: this runs after the DOM update that added the message it
280
- // names, and that message came out of `messages` in the first place.
281
- //
282
- // Scrolled inside the thread's own list and nowhere else. `scrollIntoView()` scrolls *every*
283
- // scrollable ancestor, the window included, which with a run of full-height messages expanded
284
- // took the app header and the folder rail off the screen - so the adjustment goes on whichever
285
- // ancestor actually scrolls, exactly as the toggle below already does it. When that is the page
286
- // itself, nothing inside the pane scrolls and the row is already in view, so it is left alone.
287
- const row = rowRefs.current[pendingFocusUid]!;
288
- const scroller = scrollingAncestor(row);
289
- if (scroller !== document.documentElement) {
290
- const rect = row.getBoundingClientRect();
291
- const top = rect.top - scroller.getBoundingClientRect().top;
292
- // "nearest": the least that brings it into view, and nothing at all when it is already there.
293
- if (top < 0 || top + rect.height > scroller.clientHeight) {
294
- scroller.scrollTop += top;
295
- }
296
- }
297
- // A key press (j, k, the arrows) that opened this thread left the focus on its list row on purpose, so Enter goes on to open the
298
- // message's page; taking the focus here would make Enter toggle this header instead. A click leaves no focus ring, and hands
299
- // the focus to the thread as before.
300
- const active = document.activeElement;
301
- if (!(active instanceof HTMLElement && active.hasAttribute("data-row-open") && hasFocusRing(active))) {
302
- // `preventScroll` so focusing doesn't scroll it somewhere else again.
303
- // (A card's header button is drawn by the message pane, which registers it; a stand-in pane that doesn't has none to focus.)
304
- headerRefs.current[pendingFocusUid]?.focus({ preventScroll: true });
305
- }
306
- setPendingFocusUid(null);
307
- }, [pendingFocusUid, expandedUids]);
308
-
309
- // Keeps the message whose header was just clicked where it was on screen. Expanding one above the
310
- // message being read otherwise pushes everything below it down by however tall the new body is.
311
- useLayoutEffect(() => {
312
- const anchor = anchorRef.current;
313
- if (!anchor) return;
314
- anchorRef.current = null;
315
- // The row is still there: the anchor was taken from a rendered row, and toggling never removes one.
316
- const row = rowRefs.current[anchor.uid]!;
317
- scrollingAncestor(row).scrollTop += row.getBoundingClientRect().top - anchor.top;
318
- // The button the reader had focused is gone (a collapsed card and an expanded one each draw their own): keep them where they were.
319
- if (refocusRef.current === anchor.uid) {
320
- headerRefs.current[anchor.uid]?.focus({ preventScroll: true });
321
- }
322
- refocusRef.current = null;
323
- }, [expandedUids]);
324
-
325
- // Attachments and mark-as-read, for expanded messages only - mirrors `mailDetailHooks.ts`'s
326
- // `useMessageAttachments`/`useMarkMessageRead`, reimplemented here (rather than called in a loop, which
327
- // the rules of hooks don't allow) because a thread expands several messages at once.
328
- useEffect(() => {
329
- const generation = generationRef.current;
330
- for (const message of messages) {
331
- const uid = message.uid;
332
- if (!expandedUids.has(uid)) continue;
333
- if (message.hasAttachments && !attachmentsRequestedRef.current.has(uid)) {
334
- attachmentsRequestedRef.current.add(uid);
335
- listAttachments(message.folderUid, uid)
336
- .then((loaded) => {
337
- if (generation === generationRef.current) {
338
- setAttachmentsByUid((prev) => ({ ...prev, [uid]: loaded }));
339
- }
340
- })
341
- .catch(() => {
342
- // Best-effort, as in `useMessageAttachments`: no attachments render meanwhile, and
343
- // forgetting the request lets a later re-expand retry it.
344
- attachmentsRequestedRef.current.delete(uid);
345
- });
346
- }
347
- if (!markReadRequestedRef.current.has(uid)) {
348
- // Asked once per opened conversation and per expanding of the message: a failure is not retried from here, because
349
- // undoing the optimistic change changes `messages`, which would run this effect again and ask again, for ever. A message
350
- // that is already read is asked about too (there is nothing to send), so marking it unread while it is open - the
351
- // keyboard's Ctrl+U - doesn't make this run again and read it straight back.
352
- markReadRequestedRef.current.add(uid);
353
- if (message.flags.read === true) {
354
- continue;
355
- }
356
- // `message` is this render's copy, so the request carries its current `version`. The row, the conversation row's
357
- // unread count and the folder badge all change at once; `previous` is what tells the list's conversation row
358
- // that its count moved (see `setReadState()`).
359
- void setReadState(message, true, {
360
- patch: (updated, previous) => {
361
- if (generation === generationRef.current) {
362
- patchMessage(updated, previous);
363
- }
364
- },
365
- track: trackMessageChange,
366
- });
367
- }
368
- }
369
- }, [expandedUids, messages]);
370
-
371
- /**
372
- * Reads the thread again, quietly: what is on screen stays until the answer is here (a read that fails changes nothing), a message that arrived
373
- * is added at the top, and the reader's expanded and collapsed cards are left as they are. A message this tab sent - which the server has
374
- * now filed in Sent Items under the same `uid` - takes the place of its pending card, expanded as that card was, with the focus if the
375
- * card had it. A thread that has not finished its first load is not read again: that load is the fresh read.
376
- */
377
- function refreshThread() {
378
- const id = loadedIdRef.current;
379
- if (!id) {
380
- return;
381
- }
382
- const generation = generationRef.current;
383
- loadThread(mailboxUid, id).then(
384
- (loaded) => {
385
- if (generation !== generationRef.current) return;
386
- const current = loaded.messages.filter((message) => !removedRef.current.has(message.uid));
387
- const adopted = adoptedOutgoing(mailboxUid, current);
388
- const refocus = adopted.find((uid) => document.activeElement === headerRefs.current[uid]);
389
- // Drawn first, and only then is the pending card forgotten: there is never a frame with neither it nor the real message.
390
- flushSync(() => {
391
- setMessages((previous) => mergeThread(previous, current));
392
- setTruncated(loaded.truncated);
393
- if (adopted.length > 0) {
394
- setExpandedUids((previous) => new Set([...previous, ...adopted]));
395
- }
396
- if (refocus) {
397
- setPendingFocusUid(refocus);
398
- }
399
- });
400
- settleOutgoing(mailboxUid, current);
401
- },
402
- // Quietly: the next live update reads it again, and what is shown is still right.
403
- () => undefined,
404
- );
405
- }
406
-
407
- // Another message of this conversation may have arrived - a recipient's reply, one sent from another tab or device, or this tab's own reply
408
- // filed in Sent Items - whenever the shell announces a live update that touched one of this mailbox's folders (or does not say which).
409
- useEffect(() => {
410
- if (live === seenLiveRef.current) return;
411
- seenLiveRef.current = live;
412
- if (live.folderUids === null || folders.some((folder) => live.folderUids!.has(folder.uid))) {
413
- refreshThread();
414
- }
415
- }, [live]);
416
-
417
- // The server has relayed a message this tab sent: its Sent Items copy is read for at once, without waiting for the live update that follows.
418
- const sentKey = outgoing
419
- .filter((reply) => reply.state === "sent" && reply.mailboxUid === mailboxUid)
420
- .map((reply) => reply.uid)
421
- .join(",");
422
- useEffect(() => {
423
- if (sentKey) {
424
- refreshThread();
425
- }
426
- }, [sentKey]);
427
-
428
- // The messages sent from here that continue this thread and whose real copy it does not hold yet, newest first (the pane's order). A message
429
- // that replies to nothing here - a new message, or a reply to another conversation - is not in this list, and never is.
430
- const pendingCards = outgoing
431
- .filter((reply) => reply.mailboxUid === mailboxUid && !messages.some((message) => message.uid === reply.uid) && belongsToThread(reply, messages))
432
- .reverse();
433
- // A message that has just been sent is scrolled into view and takes the focus - the compose window it was sent from has just closed, and the focus
434
- // with it - once. A failed one, or one that was already there when the thread was opened, is left where it is.
435
- const pendingKey = pendingCards.map((reply) => reply.uid).join(",");
436
- useEffect(() => {
437
- const fresh = pendingCards.filter((reply) => reply.state === "sending" && !announcedRef.current.has(reply.uid));
438
- if (fresh.length === 0) return;
439
- for (const reply of fresh) {
440
- announcedRef.current.add(reply.uid);
441
- }
442
- setPendingFocusUid(fresh[0].uid);
443
- }, [pendingKey]);
444
-
445
- /** A newer copy of one of the thread's messages, kept here and handed to the list - with the copy it
446
- * replaces where the caller was given one, so a conversation row can tell what actually changed. */
447
- function patchMessage(updated: Message, previous?: Message) {
448
- setMessages((prev) => prev.map((message) => (message.uid === updated.uid ? updated : message)));
449
- onMessagePatched(updated, previous);
450
- }
451
-
452
- /** A message that left the folder being listed - it leaves the thread too, as it left the list. */
453
- function removeMessage(updated: Message) {
454
- removedRef.current.add(updated.uid);
455
- setMessages((prev) => prev.filter((message) => message.uid !== updated.uid));
456
- onMessageRemoved(updated);
457
- }
458
-
459
- function toggleExpanded(uid: string) {
460
- // Opening a message again asks to mark it read again - that is how one whose request failed is retried.
461
- markReadRequestedRef.current.delete(uid);
462
- // The row this button lives in has rendered, so its ref is set.
463
- anchorRef.current = { uid, top: rowRefs.current[uid]!.getBoundingClientRect().top };
464
- refocusRef.current = document.activeElement === headerRefs.current[uid] ? uid : null;
465
- setExpandedUids((prev) => {
466
- const next = new Set(prev);
467
- if (next.has(uid)) {
468
- next.delete(uid);
469
- } else {
470
- next.add(uid);
471
- }
472
- return next;
473
- });
474
- }
475
-
476
- // The keyboard acts on the message that was opened - or the newest, when the opened one isn't in this thread - never on all the expanded
477
- // ones at once (each is a `MessageDetailPane`, and two of them must not both answer Ctrl+R).
478
- const keyboardUid = messages.some((message) => message.uid === selectedUid) ? selectedUid : messages[0]?.uid;
479
-
480
- function folderTypeOf(message: Message): string | undefined {
481
- return folders.find((folder) => folder.uid === message.folderUid)?.type;
482
- }
483
-
484
- if (!conversation) {
485
- return <p className="p-8 text-sm text-text-muted">Select a conversation to read it.</p>;
486
- }
487
- const subject = displaySubject(conversation.subject) || "(no subject)";
488
- // The newest message that is open carries the Reply / Forward buttons at the foot of its card.
489
- const footerUid = messages.find((message) => expandedUids.has(message.uid))?.uid;
490
-
491
- return (
492
- // The pane is the window's height, not the thread's: a full-height flex column whose header card is fixed and whose list of
493
- // message cards is the one scrolling, growing child (`min-h-0`, or the list would stretch the column past the pane instead of
494
- // scrolling inside it). Each card is exactly as tall as its message.
495
- // The subject card is the same element while the messages load and once they are here (the subject and the count are known from the
496
- // list's row), so nothing shifts or is drawn again when they arrive: a skeleton card per message (up to three) stands where they will be.
497
- <div className="flex-1 min-w-0 min-h-0 flex flex-col">
498
- <SubjectCard
499
- subject={subject}
500
- meta={
501
- loading
502
- ? conversation.messageCount > 1
503
- ? `${conversation.messageCount} messages`
504
- : undefined
505
- : error
506
- ? undefined
507
- : `${messages.length + pendingCards.length} message${messages.length + pendingCards.length === 1 ? "" : "s"}`
508
- }
509
- >
510
- {truncated && !loading && !error && (
511
- <p className="text-xs text-text-muted mt-1">
512
- Only the oldest {THREAD_MESSAGE_LIMIT} messages of this conversation are shown here. The rest
513
- are still in the message list.
514
- </p>
515
- )}
516
- </SubjectCard>
517
- {loading ? (
518
- <SkeletonCards messageCount={conversation.messageCount} />
519
- ) : error ? (
520
- <div className="p-2 sm:p-3">
521
- <Alert>{error}</Alert>
522
- </div>
523
- ) : (
524
- <ul className="flex-1 min-h-0 overflow-y-auto p-2 sm:p-3 flex flex-col gap-3">
525
- {pendingCards.map((reply) => (
526
- <li
527
- key={reply.uid}
528
- ref={(node) => {
529
- rowRefs.current[reply.uid] = node;
530
- }}
531
- data-outgoing="true"
532
- >
533
- <PendingMessageCard
534
- reply={reply}
535
- headerRef={(node) => {
536
- headerRefs.current[reply.uid] = node;
537
- }}
538
- />
539
- </li>
540
- ))}
541
- {messages.map((message) => {
542
- const uid = message.uid;
543
- const expanded = expandedUids.has(uid);
544
- const bodyId = `thread-message-${uid}`;
545
- const messageUnread = isUnread(message);
546
- return (
547
- <li
548
- key={uid}
549
- ref={(node) => {
550
- rowRefs.current[uid] = node;
551
- }}
552
- data-unread={messageUnread ? "true" : undefined}
553
- >
554
- {expanded ? (
555
- <MessageDetailPane
556
- inThread
557
- threadSubject={subject}
558
- threadHeader={{
559
- bodyId,
560
- unread: messageUnread,
561
- onToggle: () => toggleExpanded(uid),
562
- buttonRef: (node) => {
563
- headerRefs.current[uid] = node;
564
- },
565
- }}
566
- footer={uid === footerUid}
567
- shortcuts={!!shortcuts && uid === keyboardUid}
568
- message={message}
569
- attachments={attachmentsByUid[uid] ?? []}
570
- isSentItems={folderTypeOf(message) === "sent_items"}
571
- isOutbox={folderTypeOf(message) === "outbox"}
572
- draftsFolderUid={folders.find((folder) => folder.type === "drafts")?.uid}
573
- folders={folders}
574
- onMoved={removeMessage}
575
- onFolderCreated={onFolderCreated}
576
- onRecalled={patchMessage}
577
- onReceiptHandled={patchMessage}
578
- onScheduledSendCanceled={removeMessage}
579
- onArchived={removeMessage}
580
- onChanged={patchMessage}
581
- labels={labels}
582
- onLabelsChanged={patchMessage}
583
- onLabelCreated={onLabelCreated}
584
- />
585
- ) : (
586
- <>
587
- <CollapsedCard
588
- from={message.from}
589
- date={new Date(message.receivedDate).toLocaleString()}
590
- preview={message.bodyPreview || (message.encrypted ? <EncryptedPreview /> : "")}
591
- unread={messageUnread}
592
- senderClassName={senderClass(messageUnread)}
593
- dateClassName={dateClass(messageUnread)}
594
- buttonRef={(node) => {
595
- headerRefs.current[uid] = node;
596
- }}
597
- buttonProps={{
598
- onClick: () => toggleExpanded(uid),
599
- "aria-expanded": false,
600
- "aria-controls": bodyId,
601
- }}
602
- />
603
- <div id={bodyId} hidden />
604
- </>
605
- )}
606
- </li>
607
- );
608
- })}
609
- </ul>
610
- )}
611
- </div>
612
- );
613
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
6
+ import { flushSync } from "react-dom";
7
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
+ import { Attachment, Folder, Message, listAttachments } from "@rapidmx/react-shared/mail/mailApi.js";
9
+ import { ConversationSummary, listConversationMessages } from "@rapidmx/react-shared/mail/conversationsApi.js";
10
+ import { Label } from "@rapidmx/react-shared/mail/labelsApi.js";
11
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
12
+ import MessageDetailPane from "./MessageDetailPane.js";
13
+ import { EncryptedPreview, displaySubject } from "./reading/EncryptedPreview.js";
14
+ import { CollapsedCard, SkeletonCards, SubjectCard } from "./reading/MessageCard.js";
15
+ import PendingMessageCard from "./reading/PendingMessageCard.js";
16
+ import { useMailShell } from "./layout/MailShell.js";
17
+ import { setReadState } from "../../mail/messageReadState.js";
18
+ import { adoptedOutgoing, belongsToThread, settleOutgoing, useOutgoingReplies } from "../../mail/outbox/outgoingReplies.js";
19
+ import { dateClass, isUnread, senderClass } from "./unreadStyle.js";
20
+
21
+ /** One request's worth of the thread. The server's own default for `listConversationMessages()`. */
22
+ export const THREAD_PAGE_SIZE = 100;
23
+ /**
24
+ * How many of a conversation's messages this pane will load. The server reads at most
25
+ * `CONVERSATION_SCAN_LIMIT` (500) messages when it groups conversations, so a `ConversationSummary` never
26
+ * describes more than this many anyway; the cap is here so a thread that somehow reports more can't turn
27
+ * into an unbounded run of requests. Past it the pane says so and the rest stay readable from the list.
28
+ */
29
+ export const THREAD_MESSAGE_LIMIT = 500;
30
+
31
+ /** What the pane needs to know of a conversation up front: the thread itself is loaded by `conversationId`. The subject and
32
+ * count fill the header while it loads, so a caller that only has a message (the mobile route) gives its subject and a count of 1. */
33
+ export type ConversationThreadHead = Pick<ConversationSummary, "conversationId" | "subject" | "messageCount">;
34
+
35
+ export interface ConversationThreadPaneProps {
36
+ conversation: ConversationThreadHead | null;
37
+ /** The mailbox the conversation was listed from - `listConversationMessages()` is mailbox-scoped. */
38
+ mailboxUid: string;
39
+ /**
40
+ * The message the reader opened: the thread is scrolled to it, it takes focus, and it is the *oldest*
41
+ * message left expanded (see `expandedFrom()`). `null`, or a uid this thread doesn't hold, falls back
42
+ * to the newest message - which is also what a parent row means by "open the conversation".
43
+ */
44
+ selectedUid: string | null;
45
+ /** The mailbox's full folder list. A conversation spans folders (an Inbox message and the Sent Items
46
+ * copy of its reply), so each message's own folder type is looked up against its own `folderUid`. */
47
+ folders: Folder[];
48
+ /** The mailbox's labels, passed through to every expanded message's own `MessageDetailPane`. */
49
+ labels?: Label[];
50
+ /**
51
+ * A newer copy of one of the thread's messages - read, flagged, labelled, classified, recalled - for
52
+ * the caller's own list to stay in step with what was done in here.
53
+ *
54
+ * `previous` is the copy this pane held before the change, where it has one: the conversation row this
55
+ * thread came from is a *summary* (a message count, an unread count), so a list showing those rows has
56
+ * no way to tell "this message has just been read" from "this already-read message was relabelled"
57
+ * without it - which is what left a row reporting "2 unread" after both had been read.
58
+ */
59
+ onMessagePatched: (updated: Message, previous?: Message) => void;
60
+ /** A message that left the folder being listed (archived, or a scheduled send sent back to Drafts). */
61
+ onMessageRemoved: (updated: Message) => void;
62
+ onLabelCreated?: (label: Label) => void;
63
+ /** A folder created from a message's own Move to prompt, for the folder sidebar to pick up. */
64
+ onFolderCreated?: (folder: Folder) => void;
65
+ /** Registers the keyboard shortcuts (Reply, Reply all, Forward, Archive, Move to) of the message that was opened - see `MessageDetailPane`'s
66
+ * `shortcuts`. The caller turns it off while it is doing something else with the keyboard (select mode). */
67
+ shortcuts?: boolean;
68
+ }
69
+
70
+ /**
71
+ * Every message from `selectedUid` through to the newest - the run the reader is reading. Anything older
72
+ * stays collapsed to its one-line summary. Selecting the newest message therefore expands just that one.
73
+ *
74
+ * The pane lists newest first (see `loadThread()`), so that run is the opened message together with
75
+ * everything *above* it, and the opened message is the set's **last** entry rather than its first.
76
+ */
77
+ function expandedFrom(messages: Message[], selectedUid: string | null): Set<string> {
78
+ const index = messages.findIndex((message) => message.uid === selectedUid);
79
+ // `messages` is never empty here (the callers below check), so -1 means "not in this thread" and the
80
+ // newest message - the first entry - is the anchor, exactly as a parent row's own click means.
81
+ const anchor = index === -1 ? 0 : index;
82
+ return new Set(messages.slice(0, anchor + 1).map((message) => message.uid));
83
+ }
84
+
85
+ /**
86
+ * The element a message of this thread actually scrolls inside. The pane is not itself the scroll
87
+ * container in the mail shell - `MailShell`'s own `<main>` is - so an adjustment has to be applied where
88
+ * the scrolling really happens, which is whichever ancestor is both scrollable and overflowing.
89
+ */
90
+ function scrollingAncestor(node: HTMLElement): HTMLElement {
91
+ for (let el = node.parentElement; el; el = el.parentElement) {
92
+ const overflowY = getComputedStyle(el).overflowY;
93
+ if ((overflowY === "auto" || overflowY === "scroll") && el.scrollHeight > el.clientHeight) {
94
+ return el;
95
+ }
96
+ }
97
+ // Nothing between the row and the root scrolls, so the page itself does - which in standards mode is
98
+ // `documentElement`, the same element `document.scrollingElement` names there.
99
+ return document.documentElement;
100
+ }
101
+
102
+ /**
103
+ * The thread's messages, **newest first**, in pages of `THREAD_PAGE_SIZE` up to `THREAD_MESSAGE_LIMIT`.
104
+ *
105
+ * `listConversationMessages()` pages oldest first and has no order of its own to ask for, so the pages are
106
+ * collected in that order - which is also the order the `THREAD_MESSAGE_LIMIT` cap has to apply in, since it
107
+ * is the oldest messages that are dropped when a thread is too long to load - and reversed once at the end.
108
+ * The pane reads newest first always, whatever the *list* is sorted by: it is the reading order for mail,
109
+ * and it means the message a conversation row stands for is the entry at the top.
110
+ */
111
+ async function loadThread(mailboxUid: string, conversationId: string): Promise<{ messages: Message[]; truncated: boolean }> {
112
+ const messages: Message[] = [];
113
+ let more = true;
114
+ while (more && messages.length < THREAD_MESSAGE_LIMIT) {
115
+ const page = await listConversationMessages(mailboxUid, conversationId, {
116
+ page: messages.length / THREAD_PAGE_SIZE,
117
+ limit: THREAD_PAGE_SIZE,
118
+ });
119
+ messages.push(...page);
120
+ // A short page is the last one; a full page means asking for another.
121
+ more = page.length === THREAD_PAGE_SIZE;
122
+ }
123
+ messages.reverse();
124
+ return { messages, truncated: more };
125
+ }
126
+
127
+ /**
128
+ * `next` - the thread as it was just read again - for the pane to show in place of `previous`. A message the pane holds a newer copy of (one that
129
+ * was read, flagged or labelled here a moment ago, whose change the read may have started before) keeps that copy, and a read that changed
130
+ * nothing gives back `previous` itself, so the pane is not drawn again.
131
+ */
132
+ function mergeThread(previous: Message[], next: Message[]): Message[] {
133
+ const held = new Map(previous.map((message) => [message.uid, message]));
134
+ const merged = next.map((message) => {
135
+ const own = held.get(message.uid);
136
+ return own && own.version > message.version ? own : message;
137
+ });
138
+ const unchanged = merged.length === previous.length && merged.every((message, index) => message.uid === previous[index].uid && message.version === previous[index].version);
139
+ return unchanged ? previous : merged;
140
+ }
141
+
142
+ /** Whether the browser is showing a focus ring on `element` - it was focused from the keyboard (or by a key press's handler), not by a click. */
143
+ function hasFocusRing(element: HTMLElement): boolean {
144
+ try {
145
+ return element.matches(":focus-visible");
146
+ } catch {
147
+ return false;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * The reading pane for the conversation list: the conversation's subject in a card of its own, pinned at the top, and under it the whole thread as
153
+ * a stack of message cards (each exactly as tall as its message; the list scrolls as a whole), **newest at the top**, opened at the message
154
+ * the reader picked. Every message from that one through to the newest is expanded - which in this order is
155
+ * the opened message and the entries above it - and the older ones, below it, are collapsed to a one-line
156
+ * summary (sender, date, preview) that expands on click or Enter. So opening the newest message shows just
157
+ * the top entry expanded, and opening 5 of 10 expands 10 down to 5.
158
+ *
159
+ * Newest first regardless of how the *list* is sorted: the list's own order arranges rows to pick from,
160
+ * while this is one conversation being read, and the entry a conversation row stands for - its latest
161
+ * message - is the one that should be at the top of the pane every time it is opened.
162
+ *
163
+ * Each *expanded* message is a `MessageDetailPane` of its own rather than a reimplementation of it, so the
164
+ * signature and verification badges, the verification-seal and decryption behaviour, the labels chips and
165
+ * menu, the attachments and Reply/Reply All/Forward/Archive all behave exactly as they do in the
166
+ * single-message pane, and each acts on the message it belongs to. A collapsed message mounts none of
167
+ * that - mounting a body iframe per message up front would be wasteful in a long thread.
168
+ */
169
+ export default function ConversationThreadPane({
170
+ conversation,
171
+ mailboxUid,
172
+ selectedUid,
173
+ folders,
174
+ labels,
175
+ onMessagePatched,
176
+ onMessageRemoved,
177
+ onLabelCreated,
178
+ onFolderCreated,
179
+ shortcuts,
180
+ }: ConversationThreadPaneProps) {
181
+ const { trackMessageChange, live } = useMailShell();
182
+ // The replies and forwards this tab has sent, drawn at the top of the thread they continue until the server's own copy is in it.
183
+ const outgoing = useOutgoingReplies();
184
+ const [messages, setMessages] = useState<Message[]>([]);
185
+ const [attachmentsByUid, setAttachmentsByUid] = useState<Record<string, Attachment[]>>({});
186
+ const [expandedUids, setExpandedUids] = useState<Set<string>>(new Set());
187
+ const [truncated, setTruncated] = useState(false);
188
+ const [loading, setLoading] = useState(false);
189
+ const [error, setError] = useState<string | null>(null);
190
+ /** The message to scroll to and focus once it has rendered, or `null` once that has happened. */
191
+ const [pendingFocusUid, setPendingFocusUid] = useState<string | null>(null);
192
+
193
+ // Bumped on every conversation switch - an in-flight load/attachments/mark-read response carrying an
194
+ // older generation belongs to a superseded conversation and is dropped rather than applied.
195
+ const generationRef = useRef(0);
196
+ const markReadRequestedRef = useRef<Set<string>>(new Set());
197
+ const attachmentsRequestedRef = useRef<Set<string>>(new Set());
198
+ /** The `conversationId:selectedUid` the expansion run below has already been applied for, so patching
199
+ * a message (which changes `messages`) doesn't re-expand what the reader has since collapsed. */
200
+ const appliedSelectionRef = useRef<string | null>(null);
201
+ /** Which conversation the messages currently in state belong to. A render with a new conversation and
202
+ * the previous one's messages still in state happens before the load effect has cleared them, and the
203
+ * expansion run below must sit that render out rather than anchor on a message from another thread. */
204
+ const loadedIdRef = useRef<string | null>(null);
205
+ const rowRefs = useRef<Record<string, HTMLLIElement | null>>({});
206
+ const headerRefs = useRef<Record<string, HTMLElement | null>>({});
207
+ /** Where the toggled message's header sat in the viewport before it expanded, so the run below can put
208
+ * it back there - expanding a message above the one being read must not shove that one off-screen. */
209
+ const anchorRef = useRef<{ uid: string; top: number } | null>(null);
210
+ /** The message whose header button had the focus when it was toggled: expanding or collapsing swaps that button for the other state's, so the
211
+ * focus is put back on the new one. */
212
+ const refocusRef = useRef<string | null>(null);
213
+ /** The pending cards that have already been scrolled to, so that only a message that has just been sent takes the view and the focus. */
214
+ const announcedRef = useRef<Set<string>>(new Set());
215
+ /** Messages that left the thread here (archived, moved, a scheduled send taken back): a read of the thread again still lists them, since a conversation spans folders. */
216
+ const removedRef = useRef<Set<string>>(new Set());
217
+ /** The last live update this pane has answered - one already in the shell's hands when the pane opened is not news. */
218
+ const seenLiveRef = useRef(live);
219
+
220
+ const conversationId = conversation?.conversationId;
221
+
222
+ useEffect(() => {
223
+ const generation = ++generationRef.current;
224
+ markReadRequestedRef.current = new Set();
225
+ attachmentsRequestedRef.current = new Set();
226
+ announcedRef.current = new Set();
227
+ removedRef.current = new Set();
228
+ appliedSelectionRef.current = null;
229
+ loadedIdRef.current = null;
230
+ setMessages([]);
231
+ setAttachmentsByUid({});
232
+ setExpandedUids(new Set());
233
+ setTruncated(false);
234
+ setError(null);
235
+ // The message the previous conversation was to be scrolled to went with it; leaving it set would
236
+ // point the run below at a row that is no longer rendered.
237
+ setPendingFocusUid(null);
238
+ if (!conversationId) {
239
+ setLoading(false);
240
+ return;
241
+ }
242
+ setLoading(true);
243
+ loadThread(mailboxUid, conversationId)
244
+ .then((loaded) => {
245
+ if (generation !== generationRef.current) return;
246
+ loadedIdRef.current = conversationId;
247
+ // A message sent from here whose Sent Items copy is already in the thread is drawn as that copy, not as a pending card.
248
+ settleOutgoing(mailboxUid, loaded.messages);
249
+ setMessages(loaded.messages);
250
+ setTruncated(loaded.truncated);
251
+ })
252
+ .catch((err) => {
253
+ if (generation !== generationRef.current) return;
254
+ setError(err instanceof ApiRequestError ? err.message : "Could not load this conversation.");
255
+ })
256
+ .finally(() => {
257
+ if (generation === generationRef.current) setLoading(false);
258
+ });
259
+ }, [conversationId, mailboxUid]);
260
+
261
+ // Opening the thread, and opening a different message of the same thread, both set the run of expanded
262
+ // messages and ask for that message to be scrolled to. `messages` is a dependency because the thread's
263
+ // messages arrive after the click that selected one of them; the ref guard keeps a later change to
264
+ // `messages` (a patched copy) from re-running it.
265
+ useEffect(() => {
266
+ if (messages.length === 0 || loadedIdRef.current !== conversationId) return;
267
+ const key = `${conversationId}:${selectedUid}`;
268
+ if (appliedSelectionRef.current === key) return;
269
+ appliedSelectionRef.current = key;
270
+ const expanded = expandedFrom(messages, selectedUid);
271
+ setExpandedUids(expanded);
272
+ // The oldest expanded message is the one that was opened - `expandedFrom()`'s own anchor - which in
273
+ // this newest-first order is the *last* of the run, not the first.
274
+ setPendingFocusUid([...expanded][expanded.size - 1]);
275
+ }, [conversationId, selectedUid, messages]);
276
+
277
+ useLayoutEffect(() => {
278
+ if (!pendingFocusUid) return;
279
+ // The row is always rendered by now: this runs after the DOM update that added the message it
280
+ // names, and that message came out of `messages` in the first place.
281
+ //
282
+ // Scrolled inside the thread's own list and nowhere else. `scrollIntoView()` scrolls *every*
283
+ // scrollable ancestor, the window included, which with a run of full-height messages expanded
284
+ // took the app header and the folder rail off the screen - so the adjustment goes on whichever
285
+ // ancestor actually scrolls, exactly as the toggle below already does it. When that is the page
286
+ // itself, nothing inside the pane scrolls and the row is already in view, so it is left alone.
287
+ const row = rowRefs.current[pendingFocusUid]!;
288
+ const scroller = scrollingAncestor(row);
289
+ if (scroller !== document.documentElement) {
290
+ const rect = row.getBoundingClientRect();
291
+ const top = rect.top - scroller.getBoundingClientRect().top;
292
+ // "nearest": the least that brings it into view, and nothing at all when it is already there.
293
+ if (top < 0 || top + rect.height > scroller.clientHeight) {
294
+ scroller.scrollTop += top;
295
+ }
296
+ }
297
+ // A key press (j, k, the arrows) that opened this thread left the focus on its list row on purpose, so Enter goes on to open the
298
+ // message's page; taking the focus here would make Enter toggle this header instead. A click leaves no focus ring, and hands
299
+ // the focus to the thread as before.
300
+ const active = document.activeElement;
301
+ if (!(active instanceof HTMLElement && active.hasAttribute("data-row-open") && hasFocusRing(active))) {
302
+ // `preventScroll` so focusing doesn't scroll it somewhere else again.
303
+ // (A card's header button is drawn by the message pane, which registers it; a stand-in pane that doesn't has none to focus.)
304
+ headerRefs.current[pendingFocusUid]?.focus({ preventScroll: true });
305
+ }
306
+ setPendingFocusUid(null);
307
+ }, [pendingFocusUid, expandedUids]);
308
+
309
+ // Keeps the message whose header was just clicked where it was on screen. Expanding one above the
310
+ // message being read otherwise pushes everything below it down by however tall the new body is.
311
+ useLayoutEffect(() => {
312
+ const anchor = anchorRef.current;
313
+ if (!anchor) return;
314
+ anchorRef.current = null;
315
+ // The row is still there: the anchor was taken from a rendered row, and toggling never removes one.
316
+ const row = rowRefs.current[anchor.uid]!;
317
+ scrollingAncestor(row).scrollTop += row.getBoundingClientRect().top - anchor.top;
318
+ // The button the reader had focused is gone (a collapsed card and an expanded one each draw their own): keep them where they were.
319
+ if (refocusRef.current === anchor.uid) {
320
+ headerRefs.current[anchor.uid]?.focus({ preventScroll: true });
321
+ }
322
+ refocusRef.current = null;
323
+ }, [expandedUids]);
324
+
325
+ // Attachments and mark-as-read, for expanded messages only - mirrors `mailDetailHooks.ts`'s
326
+ // `useMessageAttachments`/`useMarkMessageRead`, reimplemented here (rather than called in a loop, which
327
+ // the rules of hooks don't allow) because a thread expands several messages at once.
328
+ useEffect(() => {
329
+ const generation = generationRef.current;
330
+ for (const message of messages) {
331
+ const uid = message.uid;
332
+ if (!expandedUids.has(uid)) continue;
333
+ if (message.hasAttachments && !attachmentsRequestedRef.current.has(uid)) {
334
+ attachmentsRequestedRef.current.add(uid);
335
+ listAttachments(message.folderUid, uid)
336
+ .then((loaded) => {
337
+ if (generation === generationRef.current) {
338
+ setAttachmentsByUid((prev) => ({ ...prev, [uid]: loaded }));
339
+ }
340
+ })
341
+ .catch(() => {
342
+ // Best-effort, as in `useMessageAttachments`: no attachments render meanwhile, and
343
+ // forgetting the request lets a later re-expand retry it.
344
+ attachmentsRequestedRef.current.delete(uid);
345
+ });
346
+ }
347
+ if (!markReadRequestedRef.current.has(uid)) {
348
+ // Asked once per opened conversation and per expanding of the message: a failure is not retried from here, because
349
+ // undoing the optimistic change changes `messages`, which would run this effect again and ask again, for ever. A message
350
+ // that is already read is asked about too (there is nothing to send), so marking it unread while it is open - the
351
+ // keyboard's Ctrl+U - doesn't make this run again and read it straight back.
352
+ markReadRequestedRef.current.add(uid);
353
+ if (message.flags.read === true) {
354
+ continue;
355
+ }
356
+ // `message` is this render's copy, so the request carries its current `version`. The row, the conversation row's
357
+ // unread count and the folder badge all change at once; `previous` is what tells the list's conversation row
358
+ // that its count moved (see `setReadState()`).
359
+ void setReadState(message, true, {
360
+ patch: (updated, previous) => {
361
+ if (generation === generationRef.current) {
362
+ patchMessage(updated, previous);
363
+ }
364
+ },
365
+ track: trackMessageChange,
366
+ });
367
+ }
368
+ }
369
+ }, [expandedUids, messages]);
370
+
371
+ /**
372
+ * Reads the thread again, quietly: what is on screen stays until the answer is here (a read that fails changes nothing), a message that arrived
373
+ * is added at the top, and the reader's expanded and collapsed cards are left as they are. A message this tab sent - which the server has
374
+ * now filed in Sent Items under the same `uid` - takes the place of its pending card, expanded as that card was, with the focus if the
375
+ * card had it. A thread that has not finished its first load is not read again: that load is the fresh read.
376
+ */
377
+ function refreshThread() {
378
+ const id = loadedIdRef.current;
379
+ if (!id) {
380
+ return;
381
+ }
382
+ const generation = generationRef.current;
383
+ loadThread(mailboxUid, id).then(
384
+ (loaded) => {
385
+ if (generation !== generationRef.current) return;
386
+ const current = loaded.messages.filter((message) => !removedRef.current.has(message.uid));
387
+ const adopted = adoptedOutgoing(mailboxUid, current);
388
+ const refocus = adopted.find((uid) => document.activeElement === headerRefs.current[uid]);
389
+ // Drawn first, and only then is the pending card forgotten: there is never a frame with neither it nor the real message.
390
+ flushSync(() => {
391
+ setMessages((previous) => mergeThread(previous, current));
392
+ setTruncated(loaded.truncated);
393
+ if (adopted.length > 0) {
394
+ setExpandedUids((previous) => new Set([...previous, ...adopted]));
395
+ }
396
+ if (refocus) {
397
+ setPendingFocusUid(refocus);
398
+ }
399
+ });
400
+ settleOutgoing(mailboxUid, current);
401
+ },
402
+ // Quietly: the next live update reads it again, and what is shown is still right.
403
+ () => undefined,
404
+ );
405
+ }
406
+
407
+ // Another message of this conversation may have arrived - a recipient's reply, one sent from another tab or device, or this tab's own reply
408
+ // filed in Sent Items - whenever the shell announces a live update that touched one of this mailbox's folders (or does not say which).
409
+ useEffect(() => {
410
+ if (live === seenLiveRef.current) return;
411
+ seenLiveRef.current = live;
412
+ if (live.folderUids === null || folders.some((folder) => live.folderUids!.has(folder.uid))) {
413
+ refreshThread();
414
+ }
415
+ }, [live]);
416
+
417
+ // The server has relayed a message this tab sent: its Sent Items copy is read for at once, without waiting for the live update that follows.
418
+ const sentKey = outgoing
419
+ .filter((reply) => reply.state === "sent" && reply.mailboxUid === mailboxUid)
420
+ .map((reply) => reply.uid)
421
+ .join(",");
422
+ useEffect(() => {
423
+ if (sentKey) {
424
+ refreshThread();
425
+ }
426
+ }, [sentKey]);
427
+
428
+ // The messages sent from here that continue this thread and whose real copy it does not hold yet, newest first (the pane's order). A message
429
+ // that replies to nothing here - a new message, or a reply to another conversation - is not in this list, and never is.
430
+ const pendingCards = outgoing
431
+ .filter((reply) => reply.mailboxUid === mailboxUid && !messages.some((message) => message.uid === reply.uid) && belongsToThread(reply, messages))
432
+ .reverse();
433
+ // A message that has just been sent is scrolled into view and takes the focus - the compose window it was sent from has just closed, and the focus
434
+ // with it - once. A failed one, or one that was already there when the thread was opened, is left where it is.
435
+ const pendingKey = pendingCards.map((reply) => reply.uid).join(",");
436
+ useEffect(() => {
437
+ const fresh = pendingCards.filter((reply) => reply.state === "sending" && !announcedRef.current.has(reply.uid));
438
+ if (fresh.length === 0) return;
439
+ for (const reply of fresh) {
440
+ announcedRef.current.add(reply.uid);
441
+ }
442
+ setPendingFocusUid(fresh[0].uid);
443
+ }, [pendingKey]);
444
+
445
+ /** A newer copy of one of the thread's messages, kept here and handed to the list - with the copy it
446
+ * replaces where the caller was given one, so a conversation row can tell what actually changed. */
447
+ function patchMessage(updated: Message, previous?: Message) {
448
+ setMessages((prev) => prev.map((message) => (message.uid === updated.uid ? updated : message)));
449
+ onMessagePatched(updated, previous);
450
+ }
451
+
452
+ /** A message that left the folder being listed - it leaves the thread too, as it left the list. */
453
+ function removeMessage(updated: Message) {
454
+ removedRef.current.add(updated.uid);
455
+ setMessages((prev) => prev.filter((message) => message.uid !== updated.uid));
456
+ onMessageRemoved(updated);
457
+ }
458
+
459
+ function toggleExpanded(uid: string) {
460
+ // Opening a message again asks to mark it read again - that is how one whose request failed is retried.
461
+ markReadRequestedRef.current.delete(uid);
462
+ // The row this button lives in has rendered, so its ref is set.
463
+ anchorRef.current = { uid, top: rowRefs.current[uid]!.getBoundingClientRect().top };
464
+ refocusRef.current = document.activeElement === headerRefs.current[uid] ? uid : null;
465
+ setExpandedUids((prev) => {
466
+ const next = new Set(prev);
467
+ if (next.has(uid)) {
468
+ next.delete(uid);
469
+ } else {
470
+ next.add(uid);
471
+ }
472
+ return next;
473
+ });
474
+ }
475
+
476
+ // The keyboard acts on the message that was opened - or the newest, when the opened one isn't in this thread - never on all the expanded
477
+ // ones at once (each is a `MessageDetailPane`, and two of them must not both answer Ctrl+R).
478
+ const keyboardUid = messages.some((message) => message.uid === selectedUid) ? selectedUid : messages[0]?.uid;
479
+
480
+ function folderTypeOf(message: Message): string | undefined {
481
+ return folders.find((folder) => folder.uid === message.folderUid)?.type;
482
+ }
483
+
484
+ if (!conversation) {
485
+ return <p className="p-8 text-sm text-text-muted">Select a conversation to read it.</p>;
486
+ }
487
+ const subject = displaySubject(conversation.subject) || "(no subject)";
488
+ // The newest message that is open carries the Reply / Forward buttons at the foot of its card.
489
+ const footerUid = messages.find((message) => expandedUids.has(message.uid))?.uid;
490
+
491
+ return (
492
+ // The pane is the window's height, not the thread's: a full-height flex column whose header card is fixed and whose list of
493
+ // message cards is the one scrolling, growing child (`min-h-0`, or the list would stretch the column past the pane instead of
494
+ // scrolling inside it). Each card is exactly as tall as its message.
495
+ // The subject card is the same element while the messages load and once they are here (the subject and the count are known from the
496
+ // list's row), so nothing shifts or is drawn again when they arrive: a skeleton card per message (up to three) stands where they will be.
497
+ <div className="flex-1 min-w-0 min-h-0 flex flex-col">
498
+ <SubjectCard
499
+ subject={subject}
500
+ meta={
501
+ loading
502
+ ? conversation.messageCount > 1
503
+ ? `${conversation.messageCount} messages`
504
+ : undefined
505
+ : error
506
+ ? undefined
507
+ : `${messages.length + pendingCards.length} message${messages.length + pendingCards.length === 1 ? "" : "s"}`
508
+ }
509
+ >
510
+ {truncated && !loading && !error && (
511
+ <p className="text-xs text-text-muted mt-1">
512
+ Only the oldest {THREAD_MESSAGE_LIMIT} messages of this conversation are shown here. The rest
513
+ are still in the message list.
514
+ </p>
515
+ )}
516
+ </SubjectCard>
517
+ {loading ? (
518
+ <SkeletonCards messageCount={conversation.messageCount} />
519
+ ) : error ? (
520
+ <div className="p-2 sm:p-3">
521
+ <Alert>{error}</Alert>
522
+ </div>
523
+ ) : (
524
+ <ul className="flex-1 min-h-0 overflow-y-auto p-2 sm:p-3 flex flex-col gap-3">
525
+ {pendingCards.map((reply) => (
526
+ <li
527
+ key={reply.uid}
528
+ ref={(node) => {
529
+ rowRefs.current[reply.uid] = node;
530
+ }}
531
+ data-outgoing="true"
532
+ >
533
+ <PendingMessageCard
534
+ reply={reply}
535
+ headerRef={(node) => {
536
+ headerRefs.current[reply.uid] = node;
537
+ }}
538
+ />
539
+ </li>
540
+ ))}
541
+ {messages.map((message) => {
542
+ const uid = message.uid;
543
+ const expanded = expandedUids.has(uid);
544
+ const bodyId = `thread-message-${uid}`;
545
+ const messageUnread = isUnread(message);
546
+ return (
547
+ <li
548
+ key={uid}
549
+ ref={(node) => {
550
+ rowRefs.current[uid] = node;
551
+ }}
552
+ data-unread={messageUnread ? "true" : undefined}
553
+ >
554
+ {expanded ? (
555
+ <MessageDetailPane
556
+ inThread
557
+ threadSubject={subject}
558
+ threadHeader={{
559
+ bodyId,
560
+ unread: messageUnread,
561
+ onToggle: () => toggleExpanded(uid),
562
+ buttonRef: (node) => {
563
+ headerRefs.current[uid] = node;
564
+ },
565
+ }}
566
+ footer={uid === footerUid}
567
+ shortcuts={!!shortcuts && uid === keyboardUid}
568
+ message={message}
569
+ attachments={attachmentsByUid[uid] ?? []}
570
+ isSentItems={folderTypeOf(message) === "sent_items"}
571
+ isOutbox={folderTypeOf(message) === "outbox"}
572
+ draftsFolderUid={folders.find((folder) => folder.type === "drafts")?.uid}
573
+ folders={folders}
574
+ onMoved={removeMessage}
575
+ onFolderCreated={onFolderCreated}
576
+ onRecalled={patchMessage}
577
+ onReceiptHandled={patchMessage}
578
+ onScheduledSendCanceled={removeMessage}
579
+ onArchived={removeMessage}
580
+ onChanged={patchMessage}
581
+ labels={labels}
582
+ onLabelsChanged={patchMessage}
583
+ onLabelCreated={onLabelCreated}
584
+ />
585
+ ) : (
586
+ <>
587
+ <CollapsedCard
588
+ from={message.from}
589
+ date={new Date(message.receivedDate).toLocaleString()}
590
+ preview={message.bodyPreview || (message.encrypted ? <EncryptedPreview /> : "")}
591
+ unread={messageUnread}
592
+ senderClassName={senderClass(messageUnread)}
593
+ dateClassName={dateClass(messageUnread)}
594
+ buttonRef={(node) => {
595
+ headerRefs.current[uid] = node;
596
+ }}
597
+ buttonProps={{
598
+ onClick: () => toggleExpanded(uid),
599
+ "aria-expanded": false,
600
+ "aria-controls": bodyId,
601
+ }}
602
+ />
603
+ <div id={bodyId} hidden />
604
+ </>
605
+ )}
606
+ </li>
607
+ );
608
+ })}
609
+ </ul>
610
+ )}
611
+ </div>
612
+ );
613
+ }