@rapidmx/web-client 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/README.md +192 -88
  2. package/apps/shared/auth/accountUrl.ts +9 -0
  3. package/apps/shared/auth/adminAccess.ts +99 -0
  4. package/apps/shared/components/admin/elevation.ts +61 -0
  5. package/apps/shared/components/admin/layout/AdminShell.tsx +73 -7
  6. package/apps/shared/components/admin/settings/BrandingForm.tsx +2 -1
  7. package/apps/shared/components/admin/settings/DomainDnsSetup.tsx +87 -24
  8. package/apps/shared/components/calendar/layout/CalendarShell.tsx +8 -2
  9. package/apps/shared/components/contacts/ContactsToolbar.tsx +125 -115
  10. package/apps/shared/components/contacts/layout/ContactsShell.tsx +15 -3
  11. package/apps/shared/components/layout/AppShell.tsx +411 -288
  12. package/apps/shared/components/layout/BrandingChrome.tsx +3 -2
  13. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +398 -389
  14. package/apps/shared/components/layout/MailboxProvisioning.tsx +168 -126
  15. package/apps/shared/components/layout/UserMenu.tsx +303 -150
  16. package/apps/shared/components/mail/ConversationList.tsx +269 -253
  17. package/apps/shared/components/mail/ConversationThreadPane.tsx +475 -434
  18. package/apps/shared/components/mail/LazyReadingPane.tsx +115 -0
  19. package/apps/shared/components/mail/MailAddress.tsx +88 -0
  20. package/apps/shared/components/mail/MailSelectionBar.tsx +235 -222
  21. package/apps/shared/components/mail/MessageDetailPane.tsx +1458 -1383
  22. package/apps/shared/components/mail/NewMailToasts.tsx +141 -0
  23. package/apps/shared/components/mail/compose/ComposeContext.tsx +279 -160
  24. package/apps/shared/components/mail/compose/ComposeToolbar.tsx +422 -418
  25. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1842 -1700
  26. package/apps/shared/components/mail/compose/ComposeWindowPlaceholder.tsx +111 -0
  27. package/apps/shared/components/mail/compose/RichTextEditor.tsx +147 -118
  28. package/apps/shared/components/mail/compose/SendFailureAlert.tsx +48 -0
  29. package/apps/shared/components/mail/compose/composePerf.ts +46 -0
  30. package/apps/shared/components/mail/compose/quotedBody.ts +161 -100
  31. package/apps/shared/components/mail/layout/MailShell.tsx +476 -445
  32. package/apps/shared/components/mail/unreadStyle.tsx +75 -0
  33. package/apps/shared/components/settings/layout/SettingsShell.tsx +252 -240
  34. package/apps/shared/components/tasks/layout/TasksShell.tsx +15 -3
  35. package/apps/shared/keyboard/GlobalShortcuts.tsx +51 -0
  36. package/apps/shared/keyboard/ShortcutProvider.tsx +62 -0
  37. package/apps/shared/keyboard/ShortcutsDialog.tsx +84 -0
  38. package/apps/shared/keyboard/dispatch.ts +124 -0
  39. package/apps/shared/keyboard/format.ts +89 -0
  40. package/apps/shared/keyboard/keymap.ts +114 -0
  41. package/apps/shared/keyboard/match.ts +44 -0
  42. package/apps/shared/keyboard/parse.ts +136 -0
  43. package/apps/shared/keyboard/platform.ts +34 -0
  44. package/apps/shared/keyboard/registry.ts +65 -0
  45. package/apps/shared/keyboard/targets.ts +79 -0
  46. package/apps/shared/keyboard/useShortcut.ts +50 -0
  47. package/apps/shared/keyboard/useShortcutProps.ts +17 -0
  48. package/apps/shared/mail/folderCounts.ts +302 -0
  49. package/apps/shared/mail/listSnapshots.ts +87 -0
  50. package/apps/shared/mail/mergeFirstPage.ts +47 -0
  51. package/apps/shared/mail/messageReadState.ts +85 -0
  52. package/apps/shared/mail/newMailNotifications.ts +183 -0
  53. package/apps/shared/mail/useMailConnection.ts +150 -0
  54. package/apps/shared/mail/useMailLiveUpdates.ts +232 -0
  55. package/apps/shared/mail/useMarkMessageRead.ts +47 -0
  56. package/apps/shared/mail/useNewMailNotifications.ts +163 -0
  57. package/apps/shared/mail/useUnreadTitle.ts +42 -0
  58. package/apps/shared/navigation/AppRouter.tsx +300 -0
  59. package/apps/shared/navigation/appHrefs.ts +23 -0
  60. package/apps/shared/navigation/frameContext.tsx +35 -0
  61. package/apps/shared/navigation/idle.ts +45 -0
  62. package/apps/shared/navigation/routerContext.tsx +83 -0
  63. package/apps/shared/navigation/routes.ts +72 -0
  64. package/apps/shared/search/LocalIndexLifecycle.tsx +114 -98
  65. package/apps/shared/styles/app.css +28 -10
  66. package/apps/www/_routedPage.tsx +24 -0
  67. package/apps/www/_routes.ts +35 -0
  68. package/apps/www/calendar/index.tsx +55 -19
  69. package/apps/www/contacts/[uid].tsx +112 -107
  70. package/apps/www/contacts/index.tsx +584 -567
  71. package/apps/www/index.tsx +2280 -1854
  72. package/apps/www/messages/[uid].tsx +106 -101
  73. package/apps/www/settings/auto-reply/index.tsx +4 -1
  74. package/apps/www/settings/encryption/index.tsx +1252 -1249
  75. package/apps/www/settings/filters/[uid].tsx +4 -1
  76. package/apps/www/settings/filters/index.tsx +102 -99
  77. package/apps/www/settings/filters/new/index.tsx +138 -133
  78. package/apps/www/settings/labels/index.tsx +204 -201
  79. package/apps/www/settings/privacy/index.tsx +4 -1
  80. package/apps/www/settings/read-receipts/index.tsx +4 -1
  81. package/apps/www/settings/sharing/index.tsx +277 -274
  82. package/apps/www/settings/signatures/[uid].tsx +170 -167
  83. package/apps/www/settings/signatures/index.tsx +88 -85
  84. package/apps/www/settings/signatures/new/index.tsx +134 -129
  85. package/apps/www/tasks/index.tsx +18 -2
  86. package/dist/apps/shared/auth/accountUrl.d.ts +2 -0
  87. package/dist/apps/shared/auth/accountUrl.js +8 -0
  88. package/dist/apps/shared/auth/adminAccess.d.ts +30 -0
  89. package/dist/apps/shared/auth/adminAccess.js +89 -0
  90. package/dist/apps/shared/components/admin/elevation.d.ts +24 -0
  91. package/dist/apps/shared/components/admin/elevation.js +56 -0
  92. package/dist/apps/shared/components/admin/layout/AdminShell.d.ts +12 -4
  93. package/dist/apps/shared/components/admin/layout/AdminShell.js +49 -6
  94. package/dist/apps/shared/components/admin/settings/BrandingForm.js +1 -1
  95. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.js +31 -13
  96. package/dist/apps/shared/components/calendar/layout/CalendarShell.d.ts +1 -1
  97. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +8 -4
  98. package/dist/apps/shared/components/contacts/ContactsToolbar.d.ts +3 -1
  99. package/dist/apps/shared/components/contacts/ContactsToolbar.js +7 -4
  100. package/dist/apps/shared/components/contacts/layout/ContactsShell.d.ts +1 -1
  101. package/dist/apps/shared/components/contacts/layout/ContactsShell.js +15 -5
  102. package/dist/apps/shared/components/layout/AppShell.d.ts +29 -4
  103. package/dist/apps/shared/components/layout/AppShell.js +73 -14
  104. package/dist/apps/shared/components/layout/BrandingChrome.d.ts +3 -2
  105. package/dist/apps/shared/components/layout/BrandingChrome.js +3 -2
  106. package/dist/apps/shared/components/layout/KeyEnrollmentGate.js +10 -9
  107. package/dist/apps/shared/components/layout/MailboxProvisioning.d.ts +5 -2
  108. package/dist/apps/shared/components/layout/MailboxProvisioning.js +45 -8
  109. package/dist/apps/shared/components/layout/UserMenu.d.ts +28 -9
  110. package/dist/apps/shared/components/layout/UserMenu.js +87 -14
  111. package/dist/apps/shared/components/mail/ConversationList.js +9 -13
  112. package/dist/apps/shared/components/mail/ConversationThreadPane.d.ts +4 -1
  113. package/dist/apps/shared/components/mail/ConversationThreadPane.js +53 -28
  114. package/dist/apps/shared/components/mail/LazyReadingPane.d.ts +9 -0
  115. package/dist/apps/shared/components/mail/LazyReadingPane.js +82 -0
  116. package/dist/apps/shared/components/mail/MailAddress.d.ts +27 -0
  117. package/dist/apps/shared/components/mail/MailAddress.js +39 -0
  118. package/dist/apps/shared/components/mail/MailSelectionBar.d.ts +4 -1
  119. package/dist/apps/shared/components/mail/MailSelectionBar.js +11 -3
  120. package/dist/apps/shared/components/mail/MessageDetailPane.d.ts +7 -1
  121. package/dist/apps/shared/components/mail/MessageDetailPane.js +87 -36
  122. package/dist/apps/shared/components/mail/NewMailToasts.d.ts +19 -0
  123. package/dist/apps/shared/components/mail/NewMailToasts.js +55 -0
  124. package/dist/apps/shared/components/mail/compose/ComposeContext.d.ts +30 -0
  125. package/dist/apps/shared/components/mail/compose/ComposeContext.js +71 -5
  126. package/dist/apps/shared/components/mail/compose/ComposeToolbar.js +4 -3
  127. package/dist/apps/shared/components/mail/compose/ComposeWindow.d.ts +1 -1
  128. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +122 -27
  129. package/dist/apps/shared/components/mail/compose/ComposeWindowPlaceholder.d.ts +19 -0
  130. package/dist/apps/shared/components/mail/compose/ComposeWindowPlaceholder.js +33 -0
  131. package/dist/apps/shared/components/mail/compose/RichTextEditor.d.ts +9 -1
  132. package/dist/apps/shared/components/mail/compose/RichTextEditor.js +20 -2
  133. package/dist/apps/shared/components/mail/compose/SendFailureAlert.d.ts +14 -0
  134. package/dist/apps/shared/components/mail/compose/SendFailureAlert.js +11 -0
  135. package/dist/apps/shared/components/mail/compose/composePerf.d.ts +16 -0
  136. package/dist/apps/shared/components/mail/compose/composePerf.js +41 -0
  137. package/dist/apps/shared/components/mail/compose/quotedBody.d.ts +13 -0
  138. package/dist/apps/shared/components/mail/compose/quotedBody.js +67 -11
  139. package/dist/apps/shared/components/mail/layout/MailShell.d.ts +19 -4
  140. package/dist/apps/shared/components/mail/layout/MailShell.js +85 -85
  141. package/dist/apps/shared/components/mail/unreadStyle.d.ts +45 -0
  142. package/dist/apps/shared/components/mail/unreadStyle.js +61 -0
  143. package/dist/apps/shared/components/settings/layout/SettingsShell.d.ts +1 -1
  144. package/dist/apps/shared/components/settings/layout/SettingsShell.js +15 -5
  145. package/dist/apps/shared/components/tasks/layout/TasksShell.d.ts +1 -1
  146. package/dist/apps/shared/components/tasks/layout/TasksShell.js +15 -5
  147. package/dist/apps/shared/keyboard/GlobalShortcuts.d.ts +14 -0
  148. package/dist/apps/shared/keyboard/GlobalShortcuts.js +37 -0
  149. package/dist/apps/shared/keyboard/ShortcutProvider.d.ts +20 -0
  150. package/dist/apps/shared/keyboard/ShortcutProvider.js +52 -0
  151. package/dist/apps/shared/keyboard/ShortcutsDialog.d.ts +14 -0
  152. package/dist/apps/shared/keyboard/ShortcutsDialog.js +42 -0
  153. package/dist/apps/shared/keyboard/dispatch.d.ts +16 -0
  154. package/dist/apps/shared/keyboard/dispatch.js +109 -0
  155. package/dist/apps/shared/keyboard/format.d.ts +12 -0
  156. package/dist/apps/shared/keyboard/format.js +74 -0
  157. package/dist/apps/shared/keyboard/keymap.d.ts +294 -0
  158. package/dist/apps/shared/keyboard/keymap.js +84 -0
  159. package/dist/apps/shared/keyboard/match.d.ts +20 -0
  160. package/dist/apps/shared/keyboard/match.js +31 -0
  161. package/dist/apps/shared/keyboard/parse.d.ts +31 -0
  162. package/dist/apps/shared/keyboard/parse.js +107 -0
  163. package/dist/apps/shared/keyboard/platform.d.ts +15 -0
  164. package/dist/apps/shared/keyboard/platform.js +22 -0
  165. package/dist/apps/shared/keyboard/registry.d.ts +39 -0
  166. package/dist/apps/shared/keyboard/registry.js +33 -0
  167. package/dist/apps/shared/keyboard/targets.d.ts +14 -0
  168. package/dist/apps/shared/keyboard/targets.js +67 -0
  169. package/dist/apps/shared/keyboard/useShortcut.d.ts +19 -0
  170. package/dist/apps/shared/keyboard/useShortcut.js +35 -0
  171. package/dist/apps/shared/keyboard/useShortcutProps.d.ts +10 -0
  172. package/dist/apps/shared/keyboard/useShortcutProps.js +15 -0
  173. package/dist/apps/shared/mail/folderCounts.d.ts +78 -0
  174. package/dist/apps/shared/mail/folderCounts.js +212 -0
  175. package/dist/apps/shared/mail/listSnapshots.d.ts +46 -0
  176. package/dist/apps/shared/mail/listSnapshots.js +43 -0
  177. package/dist/apps/shared/mail/mergeFirstPage.d.ts +23 -0
  178. package/dist/apps/shared/mail/mergeFirstPage.js +30 -0
  179. package/dist/apps/shared/mail/messageReadState.d.ts +32 -0
  180. package/dist/apps/shared/mail/messageReadState.js +63 -0
  181. package/dist/apps/shared/mail/newMailNotifications.d.ts +62 -0
  182. package/dist/apps/shared/mail/newMailNotifications.js +138 -0
  183. package/dist/apps/shared/mail/useMailConnection.d.ts +55 -0
  184. package/dist/apps/shared/mail/useMailConnection.js +96 -0
  185. package/dist/apps/shared/mail/useMailLiveUpdates.d.ts +55 -0
  186. package/dist/apps/shared/mail/useMailLiveUpdates.js +182 -0
  187. package/dist/apps/shared/mail/useMarkMessageRead.d.ts +12 -0
  188. package/dist/apps/shared/mail/useMarkMessageRead.js +44 -0
  189. package/dist/apps/shared/mail/useNewMailNotifications.d.ts +41 -0
  190. package/dist/apps/shared/mail/useNewMailNotifications.js +110 -0
  191. package/dist/apps/shared/mail/useUnreadTitle.d.ts +18 -0
  192. package/dist/apps/shared/mail/useUnreadTitle.js +31 -0
  193. package/dist/apps/shared/navigation/AppRouter.d.ts +52 -0
  194. package/dist/apps/shared/navigation/AppRouter.js +242 -0
  195. package/dist/apps/shared/navigation/appHrefs.d.ts +14 -0
  196. package/dist/apps/shared/navigation/appHrefs.js +20 -0
  197. package/dist/apps/shared/navigation/frameContext.d.ts +19 -0
  198. package/dist/apps/shared/navigation/frameContext.js +24 -0
  199. package/dist/apps/shared/navigation/idle.d.ts +14 -0
  200. package/dist/apps/shared/navigation/idle.js +43 -0
  201. package/dist/apps/shared/navigation/routerContext.d.ts +37 -0
  202. package/dist/apps/shared/navigation/routerContext.js +56 -0
  203. package/dist/apps/shared/navigation/routes.d.ts +32 -0
  204. package/dist/apps/shared/navigation/routes.js +37 -0
  205. package/dist/apps/shared/search/LocalIndexLifecycle.js +17 -3
  206. package/dist/apps/shared/styles/app.css +28 -10
  207. package/dist/apps/www/_routedPage.d.ts +12 -0
  208. package/dist/apps/www/_routedPage.js +19 -0
  209. package/dist/apps/www/_routes.d.ts +11 -0
  210. package/dist/apps/www/_routes.js +29 -0
  211. package/dist/apps/www/calendar/index.d.ts +2 -2
  212. package/dist/apps/www/calendar/index.js +39 -8
  213. package/dist/apps/www/contacts/[uid].d.ts +3 -9
  214. package/dist/apps/www/contacts/[uid].js +6 -2
  215. package/dist/apps/www/contacts/index.d.ts +2 -2
  216. package/dist/apps/www/contacts/index.js +17 -4
  217. package/dist/apps/www/index.d.ts +2 -2
  218. package/dist/apps/www/index.js +361 -34
  219. package/dist/apps/www/messages/[uid].d.ts +3 -7
  220. package/dist/apps/www/messages/[uid].js +7 -4
  221. package/dist/apps/www/settings/auto-reply/index.d.ts +2 -2
  222. package/dist/apps/www/settings/auto-reply/index.js +3 -1
  223. package/dist/apps/www/settings/encryption/index.d.ts +2 -2
  224. package/dist/apps/www/settings/encryption/index.js +3 -1
  225. package/dist/apps/www/settings/filters/[uid].d.ts +2 -2
  226. package/dist/apps/www/settings/filters/[uid].js +3 -1
  227. package/dist/apps/www/settings/filters/index.d.ts +2 -2
  228. package/dist/apps/www/settings/filters/index.js +3 -1
  229. package/dist/apps/www/settings/filters/new/index.d.ts +2 -2
  230. package/dist/apps/www/settings/filters/new/index.js +6 -2
  231. package/dist/apps/www/settings/labels/index.d.ts +2 -2
  232. package/dist/apps/www/settings/labels/index.js +3 -1
  233. package/dist/apps/www/settings/privacy/index.d.ts +2 -2
  234. package/dist/apps/www/settings/privacy/index.js +3 -1
  235. package/dist/apps/www/settings/read-receipts/index.d.ts +2 -2
  236. package/dist/apps/www/settings/read-receipts/index.js +3 -1
  237. package/dist/apps/www/settings/sharing/index.d.ts +2 -2
  238. package/dist/apps/www/settings/sharing/index.js +3 -1
  239. package/dist/apps/www/settings/signatures/[uid].d.ts +2 -2
  240. package/dist/apps/www/settings/signatures/[uid].js +3 -1
  241. package/dist/apps/www/settings/signatures/index.d.ts +2 -2
  242. package/dist/apps/www/settings/signatures/index.js +3 -1
  243. package/dist/apps/www/settings/signatures/new/index.d.ts +2 -2
  244. package/dist/apps/www/settings/signatures/new/index.js +6 -2
  245. package/dist/apps/www/tasks/index.d.ts +2 -2
  246. package/dist/apps/www/tasks/index.js +15 -3
  247. package/package.json +2 -2
@@ -1,1854 +1,2280 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import React, { useCallback, useEffect, useRef, useState } from "react";
6
- import { HiOutlineFlag, HiOutlineLockClosed, HiOutlinePaperClip } from "react-icons/hi2";
7
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
- import {
9
- Folder,
10
- Mailbox,
11
- Message,
12
- MessageListFilter,
13
- MessageListParams,
14
- archiveMessage,
15
- bulkUpdateMessages,
16
- createFolder,
17
- getMessage,
18
- getMessageRawContent,
19
- listMessages,
20
- moveMessages,
21
- setMessagesFlagged,
22
- setMessagesRead,
23
- } from "@rapidmx/react-shared/mail/mailApi.js";
24
- import { Label, listLabels } from "@rapidmx/react-shared/mail/labelsApi.js";
25
- import {
26
- ConversationListParams,
27
- ConversationSummary,
28
- listConversationMessages,
29
- listConversations,
30
- } from "@rapidmx/react-shared/mail/conversationsApi.js";
31
- import { SearchResult, search as searchMailbox } from "@rapidmx/react-shared/search/searchApi.js";
32
- import { parseSearchQuery, type ParsedSearchQuery } from "@rapidmx/react-shared/search/queryGrammar.js";
33
- import { normalizeServerScores } from "@rapidmx/react-shared/search/searchScoring.js";
34
- import { searchEncryptedCandidates } from "@rapidmx/react-shared/search/searchTier3.js";
35
- import { searchLocalIndex } from "../shared/search/searchTier2.js";
36
- import type { Coverage } from "../shared/search/localIndexWorker.js";
37
- import { getUnlockedKeys, subscribeKeySession, UnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
38
- import { evaluateMessageSecurity } from "@rapidmx/react-shared/crypto/messageSecurity.js";
39
- import { useMarkMessageRead, useMessageAttachments } from "@rapidmx/react-shared/mail/mailDetailHooks.js";
40
- import useIsMobile from "@rapidmx/react-shared/util/useIsMobile.js";
41
- import MailShell, {
42
- AggregateFolderType,
43
- MailboxFolders,
44
- MailShellProps,
45
- useMailShell,
46
- } from "../shared/components/mail/layout/MailShell.js";
47
- import MessageDetailPane from "../shared/components/mail/MessageDetailPane.js";
48
- import ConversationList from "../shared/components/mail/ConversationList.js";
49
- import ConversationThreadPane from "../shared/components/mail/ConversationThreadPane.js";
50
- import MailListToolbar from "../shared/components/mail/MailListToolbar.js";
51
- import MailSelectionBar from "../shared/components/mail/MailSelectionBar.js";
52
- import {
53
- CONVERSATION_SORT_NOTE,
54
- CONVERSATION_SORT_UNAVAILABLE,
55
- MAIL_LIST_CLASSIFICATION_FILTERS,
56
- MailListPreferences,
57
- getMailListPreferences,
58
- setMailListPreferences,
59
- sortConversations,
60
- } from "../shared/components/mail/listPreferences.js";
61
- import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
62
- import Skeleton from "@rapidmx/react-shared/components/feedback/Skeleton.js";
63
- import { useUnlockPrompt } from "../shared/components/layout/UnlockPromptProvider.js";
64
-
65
- const MESSAGE_PAGE_SIZE = 50;
66
- const SEARCH_DEBOUNCE_MS = 300;
67
- const LIST_PREVIEW_MAX_LENGTH = 160;
68
-
69
- /** The literal outer-envelope `Subject` every encrypted message carries server-side - RFC 9788's
70
- * `hcp_baseline` policy obscures it to this exact string (see `smimeMessage.ts`'s
71
- * `applyBaselineOuterHeaders()`), which is also all `Message.subject` ever shows for one of these until
72
- * decrypted client-side. Used here to recognize which loaded rows are worth decrypting for display. */
73
- const ENCRYPTED_SUBJECT_PLACEHOLDER = "[...]";
74
-
75
- /** A row's client-recovered subject/preview, once decrypted - `undefined` fields mean nothing better
76
- * than the placeholder/blank server value was recoverable for that field specifically. */
77
- interface DecryptedRow {
78
- subject?: string;
79
- preview?: string;
80
- }
81
-
82
- /** Strips HTML down to plain text, for a short list-row preview of a decrypted body - mirrors
83
- * `searchTier3.ts`'s own private `stripHtml()` (not currently exported from `@rapidmx/react-shared`,
84
- * so duplicated here rather than pulled in through a package change just for this one small, pure
85
- * helper). Not a security boundary - the output only ever feeds plain text display, truncated below,
86
- * never rendered back into any DOM. */
87
- function stripHtmlToText(html: string): string {
88
- return html
89
- .replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, " ")
90
- .replace(/<[^>]+>/g, " ")
91
- .replace(/&nbsp;/gi, " ")
92
- .replace(/&amp;/gi, "&")
93
- .replace(/&lt;/gi, "<")
94
- .replace(/&gt;/gi, ">")
95
- .replace(/&quot;/gi, '"')
96
- .replace(/&#0*39;/gi, "'")
97
- .replace(/\s+/g, " ")
98
- .trim();
99
- }
100
-
101
- /**
102
- * Decrypts the subject/preview of every currently-loaded row whose subject is still the RFC 9788
103
- * placeholder (i.e. every encrypted message this device hasn't already resolved), keyed by uid - the
104
- * inbox-list counterpart to `MessageDetailPane`'s own single-message decrypt and `searchTier3.ts`'s
105
- * per-candidate decrypt. Bounded to `messages` (at most one loaded page, `MESSAGE_PAGE_SIZE`), never the
106
- * whole mailbox - matching `searchEncryptedCandidates()`'s own "bounded, not everything" scope. Runs only
107
- * once `unlocked` is available (the caller decides when to call this - see `InboxContent`'s own effect
108
- * and `handleUnlockList()`), and a single row's fetch/decrypt failure never blocks the rest.
109
- */
110
- async function decryptEncryptedRows(messages: Message[], unlocked: UnlockedKeys): Promise<Record<string, DecryptedRow>> {
111
- const encrypted = messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER);
112
- const entries = await Promise.all(
113
- encrypted.map(async (message): Promise<[string, DecryptedRow] | null> => {
114
- try {
115
- const rawMime = await getMessageRawContent(message.uid);
116
- const security = await evaluateMessageSecurity(rawMime, unlocked);
117
- if (!security.subject && !security.html) {
118
- return null;
119
- }
120
- const preview = security.html ? stripHtmlToText(security.html).slice(0, LIST_PREVIEW_MAX_LENGTH) : undefined;
121
- return [message.uid, { subject: security.subject, preview }];
122
- } catch {
123
- return null;
124
- }
125
- }),
126
- );
127
- const result: Record<string, DecryptedRow> = {};
128
- for (const entry of entries) {
129
- if (entry) {
130
- result[entry[0]] = entry[1];
131
- }
132
- }
133
- return result;
134
- }
135
-
136
- /** Merges Tier 1 (server, possibly `metadataOnly` for an encrypted message), Tier 2 (local index, fully
137
- * decrypted and re-scored), and Tier 3 (server-narrowed candidates, decrypted and re-scored) results into
138
- * one ranked list, per `specs/search.md` §7's "client MUST re-score all results it can see... normalise
139
- * into the same space rather than interleaving raw scores": each tier is normalized independently via
140
- * `normalizeServerScores()` before merging, since a Postgres/OpenSearch score, a local `bm25()` score,
141
- * and this module's own Tier 3 term-count score all occupy unrelated ranges. A uid present in more than
142
- * one list keeps only the last-inserted entry (Tier 2 wins over Tier 3 wins over Tier 1) - Tier 2 and
143
- * Tier 3 both represent genuine, content-verified scores for the same message, so which one "wins" on
144
- * overlap doesn't change correctness, only which of two equally-valid scores is shown; either supersedes
145
- * Tier 1's metadata-only guess for the same uid.
146
- *
147
- * Called progressively - once per tier as it resolves, each time with whatever tiers have reported so
148
- * far (an empty array for the rest) - by `InboxContent`'s own search orchestration below, per §_Progressive
149
- * Results_' "reordering is permitted and preferred over appending." This function itself stays pure and
150
- * stateless; it has no notion of "in progress" versus "final." */
151
- function mergeSearchResults(tier1: SearchResult[], tier2: SearchResult[], tier3: SearchResult[]): SearchResult[] {
152
- const normalizedTier1 = normalizeServerScores(tier1);
153
- const normalizedTier2 = normalizeServerScores(tier2);
154
- const normalizedTier3 = normalizeServerScores(tier3);
155
- const merged = new Map<string, { result: SearchResult; normalizedScore: number }>();
156
- for (const entry of normalizedTier1) {
157
- merged.set(entry.result.entityUid, entry);
158
- }
159
- for (const entry of normalizedTier3) {
160
- merged.set(entry.result.entityUid, entry);
161
- }
162
- for (const entry of normalizedTier2) {
163
- merged.set(entry.result.entityUid, entry);
164
- }
165
- return Array.from(merged.values())
166
- .sort((a, b) => b.normalizedScore - a.normalizedScore)
167
- .map((entry) => entry.result);
168
- }
169
-
170
- /** `type:` narrows `entityTypes`; when absent this still defaults to `["message"]` — a non-message hit
171
- * (contact/calendarEvent/note/task) has no `Message` to resolve via `getMessage()` below and is simply
172
- * dropped by the same eventually-consistent-index fallback that already existed, rather than rendered
173
- * (this inbox list only ever shows message rows; a real multi-entity-type results view is a separate,
174
- * larger UI project outside this pass). Shared by both the fresh-search orchestration and `loadMore()`
175
- * below, which each build this from the same `ParsedSearchQuery` differently only in `cursor`. */
176
- function tier1SearchParams(parsed: ParsedSearchQuery, cursor: string | undefined, mailboxUid: string) {
177
- return {
178
- // The mailbox actually open - omitted, the server searches the caller's *own* mailbox, which is the
179
- // wrong one whenever a shared mailbox's folder is being viewed.
180
- mailboxUid,
181
- types: parsed.entityTypes ?? ["message"],
182
- cursor,
183
- limit: MESSAGE_PAGE_SIZE,
184
- from: parsed.from,
185
- to: parsed.to,
186
- cc: parsed.cc,
187
- subject: parsed.subject,
188
- hasAttachment: parsed.hasAttachment,
189
- before: parsed.before,
190
- after: parsed.after,
191
- folderUid: parsed.folderUid,
192
- flags: parsed.flags,
193
- labels: parsed.labels,
194
- };
195
- }
196
-
197
- /** How many of Tier 1's own `metadataOnly` hits (§7: "an encrypted entity matched only on server-visible
198
- * metadata... MUST be rendered as skeleton entries in place... using the metadata score as a provisional
199
- * position") are shown as skeleton rows at once - §_Progressive Results_' "Skeletons MUST be capped, at
200
- * approximately one and a half pages." A non-`metadataOnly` Tier 1 hit (a real, already-scored content
201
- * match — always the case for unencrypted mail) is never a skeleton and is never subject to this cap.
202
- *
203
- * A Tier 3 candidate that Tier 1 did *not* already surface has no provisional score/position of its own
204
- * under the spec's own wording above, so it is deliberately never pre-rendered as a skeleton here either
205
- * - it simply appears, fully resolved, once Tier 3 confirms it (see `InboxContent`'s search
206
- * orchestration). */
207
- const SKELETON_CAP = Math.round(MESSAGE_PAGE_SIZE * 1.5);
208
-
209
- function capSkeletons(tier1Hits: SearchResult[]): SearchResult[] {
210
- let skeletonsSeen = 0;
211
- return tier1Hits.filter((hit) => {
212
- if (!hit.metadataOnly) {
213
- return true;
214
- }
215
- skeletonsSeen += 1;
216
- return skeletonsSeen <= SKELETON_CAP;
217
- });
218
- }
219
-
220
- /** How many candidates Tier 3 pulls per distinct search - larger than one page's worth so several
221
- * `loadMore()` pages can be sliced from one decrypt pass (see `Tier3Cache` below) instead of a second,
222
- * separately expensive server round trip and re-decrypt for the same query. Bounded, not unlimited - per
223
- * this module's own `tier1SearchParams()` sibling, Tier 3's own candidate-narrowing is already the
224
- * "heaviest single client-side cost" tier (`specs/search.md` §9's identical framing for attachment
225
- * extraction); a query whose true candidate set exceeds this simply pages out once this cache is
226
- * exhausted; `loadMore()` reflects that honestly via `hasMore`. */
227
- const TIER3_CANDIDATE_LIMIT = 200;
228
-
229
- /** One entry per distinct (mailbox, query, "search all mail" toggle, unlocked-or-not) combination this
230
- * tab has already run Tier 3 for - keyed by `tier3CacheKey()` below. Tier 3's decrypt-and-match pass
231
- * (`searchEncryptedCandidates()`) is by far this search's most expensive step, so it runs once per
232
- * combination; every subsequent `loadMore()` page for that same combination slices further into the
233
- * same already-decrypted array. Session-scoped, per tab, with no explicit eviction - a small map that's
234
- * simply never read again once the query changes, the same shape `InboxContent`'s own `decryptedRows`
235
- * state already accepts for a similar "worth keeping around, not worth actively pruning" tradeoff.
236
- *
237
- * The unlocked-or-not dimension matters: re-running an identical query right after an on-demand unlock
238
- * (`handleUnlockSearch()`) MUST NOT reuse the "nothing to contribute" entry that same query cached while
239
- * still locked - `searchEncryptedCandidates()` degrades to `[]` for an absent `unlocked`, and that empty
240
- * result is exactly as cacheable/reusable as a real one, just under a different key. */
241
- type Tier3Cache = Map<string, SearchResult[]>;
242
-
243
- /** Keyed by the exact query windows Tier 3 actually ran (`tier3Windows()` - which already reflect the query,
244
- * the "Search all mail" toggle, and Tier 2's coverage at the time), not just the query: the same query
245
- * narrowed differently (a build finished, new mail moved the coverage end) must not reuse a result that was
246
- * computed over a different date range. */
247
- function tier3CacheKey(mailboxUid: string, windows: ParsedSearchQuery[], unlocked: boolean): string {
248
- return `${mailboxUid}|${JSON.stringify(windows)}|${String(unlocked)}`;
249
- }
250
-
251
- /** A search query's cache/cursor identity - stable across re-parsing the identical raw text, and
252
- * distinct for anything else (§8's "a query fingerprint, so a cursor cannot be replayed against a
253
- * different query"). `JSON.stringify` on `ParsedSearchQuery` is deterministic here because every one of
254
- * its own fields is a primitive or a `Date` (which serializes to a fixed ISO string) - no nested object
255
- * whose key order could vary between two structurally-identical parses of the same text. */
256
- function queryFingerprint(parsed: ParsedSearchQuery): string {
257
- return JSON.stringify(parsed);
258
- }
259
-
260
- /** The date windows Tier 3 still has to search: the query's own range minus Tier 2's guaranteed coverage
261
- * `[coverage.indexedFrom, coverage.indexedUntil]`, unless the reader explicitly asked to "Search all mail".
262
- * Tier 2 already holds fully-decrypted, current content for that range, so re-fetching and re-decrypting it
263
- * through Tier 3's slower candidate-narrowing path would be pure waste. Yields up to two windows - older than
264
- * the coverage (`before:` tightened to `indexedFrom`) and newer than it (`after:` raised to `indexedUntil`,
265
- * since nothing indexes mail that arrived after the build pass started) - never *widening* a bound the query
266
- * already specified, and none at all when the query lies entirely inside the coverage.
267
- *
268
- * Only narrows once Tier 2 reports a finished, complete build pass from this session: while it's still
269
- * building (or a pass stopped early - a failed folder listing, the byte budget) `indexedFrom` is just the
270
- * oldest row that happens to be present, not a guarantee every encrypted message since then is indexed, and
271
- * narrowing on it would silently drop encrypted results neither tier returns. */
272
- function tier3Windows(parsed: ParsedSearchQuery, coverage: Coverage | undefined, searchAllMail: boolean): ParsedSearchQuery[] {
273
- if (searchAllMail || !coverage?.indexedFrom || !coverage.indexedUntil || coverage.building || !coverage.complete) {
274
- return [parsed];
275
- }
276
- const coveredFrom = new Date(coverage.indexedFrom);
277
- const coveredUntil = new Date(coverage.indexedUntil);
278
- const windows: ParsedSearchQuery[] = [];
279
- if (!parsed.after || parsed.after.getTime() < coveredFrom.getTime()) {
280
- windows.push({ ...parsed, before: parsed.before && parsed.before.getTime() < coveredFrom.getTime() ? parsed.before : coveredFrom });
281
- }
282
- if (!parsed.before || parsed.before.getTime() > coveredUntil.getTime()) {
283
- windows.push({ ...parsed, after: parsed.after && parsed.after.getTime() > coveredUntil.getTime() ? parsed.after : coveredUntil });
284
- }
285
- return windows;
286
- }
287
-
288
- /** Runs Tier 3 over each window and merges the candidates (a uid can't match in two disjoint windows, but a
289
- * message whose date sits exactly on a boundary may come back from both). */
290
- async function searchTier3Windows(windows: ParsedSearchQuery[], unlocked: UnlockedKeys | undefined, mailboxUid: string): Promise<SearchResult[]> {
291
- const pages = await Promise.all(
292
- windows.map((window) => searchEncryptedCandidates(window, unlocked, TIER3_CANDIDATE_LIMIT, { mailboxUid })),
293
- );
294
- const merged = new Map<string, SearchResult>();
295
- for (const result of pages.flat()) {
296
- if (!merged.has(result.entityUid)) {
297
- merged.set(result.entityUid, result);
298
- }
299
- }
300
- return [...merged.values()];
301
- }
302
-
303
- /** The paging state for one search, composited across all three tiers (`specs/search.md` §8) - opaque to
304
- * every caller the same way `SearchResultPage.nextCursor` is opaque to callers of `search()` itself.
305
- * Tier 1 keeps the server's own opaque cursor unmodified; Tier 2 (the local index) and Tier 3 (the
306
- * cached, already-decrypted candidate array - see `Tier3Cache` above) are both this client's own state,
307
- * so their "position" is just a plain offset into each. */
308
- interface CompositeCursor {
309
- tier1Cursor?: string;
310
- tier2Offset: number;
311
- tier3Offset: number;
312
- /** The `Tier3Cache` entry the first page was sliced from - later pages keep slicing the same one. */
313
- tier3Key: string;
314
- fingerprint: string;
315
- }
316
-
317
- /** `undefined` for a missing, corrupted, or foreign-query cursor - every caller already treats "no
318
- * cursor" as "start this tier from the beginning," so there's no separate error path needed here. */
319
- function decodeCursor(raw: CompositeCursor | undefined, fingerprint: string): CompositeCursor | undefined {
320
- return raw?.fingerprint === fingerprint ? raw : undefined;
321
- }
322
-
323
- /** Resolves every hit's `entityUid` to a full `Message` via `getMessage()`, reusing `cache` across
324
- * repeated calls within the same search pass - `InboxContent`'s own search orchestration below re-merges
325
- * and re-resolves the *entire* current hit set each time a tier resolves, so without this cache every
326
- * stage would re-fetch messages an earlier stage already fetched. A hit whose message no longer resolves
327
- * (deleted after being indexed, or the fetch itself failed) is cached as `null` and dropped - the same
328
- * "a search hit can briefly outlive the message it points to" tolerance this function's inline
329
- * predecessor already had. */
330
- async function resolveHitsToMessages(
331
- hits: SearchResult[],
332
- cache: Map<string, Message | null>,
333
- ): Promise<{ messages: Message[]; snippets: Record<string, string> }> {
334
- const toFetch = hits.filter((hit) => !cache.has(hit.entityUid));
335
- await Promise.all(
336
- toFetch.map(async (hit) => {
337
- const message = await getMessage(hit.entityUid).catch(() => null);
338
- cache.set(hit.entityUid, message);
339
- }),
340
- );
341
- const messages: Message[] = [];
342
- const snippets: Record<string, string> = {};
343
- for (const hit of hits) {
344
- const message = cache.get(hit.entityUid);
345
- if (!message) {
346
- continue;
347
- }
348
- messages.push(message);
349
- if (hit.snippet) {
350
- snippets[message.uid] = hit.snippet;
351
- }
352
- }
353
- return { messages, snippets };
354
- }
355
-
356
- /** How far outside the scroll container's visible area the load-more sentinel still counts as "in view". */
357
- const LOAD_MORE_ROOT_MARGIN_PX = 200;
358
-
359
- /** How many full pages in a row that added no new rows the list keeps loading on its own before it shows a
360
- * "Load more" button instead. */
361
- const MAX_EMPTY_PAGE_CONTINUATIONS = 3;
362
-
363
- /** `true` when `more` has at least one row `shown` doesn't - i.e. appending it actually adds rows. Generic
364
- * over the row's own identity so both the message list (`uid`) and the conversation list
365
- * (`conversationId`) page the same way. */
366
- function hasUnseenRows<T>(shown: T[], more: T[], idOf: (row: T) => string): boolean {
367
- const seen = new Set(shown.map(idOf));
368
- return more.some((row) => !seen.has(idOf(row)));
369
- }
370
-
371
- /** The load-more sentinel's actual current geometry against its scroll container, with the same margin the
372
- * IntersectionObserver uses. */
373
- function isWithinLoadMoreRange(sentinel: HTMLElement, root: HTMLElement): boolean {
374
- const rect = sentinel.getBoundingClientRect();
375
- const rootRect = root.getBoundingClientRect();
376
- return rect.top <= rootRect.bottom + LOAD_MORE_ROOT_MARGIN_PX && rect.bottom >= rootRect.top - LOAD_MORE_ROOT_MARGIN_PX;
377
- }
378
-
379
- /** Appends `more` to `shown`, skipping any row already shown - a later page can repeat rows (Tier 1 and
380
- * Tier 2/3 cursors advance independently, so the same message can come back from a different tier on a
381
- * later page; a plain folder listing's pages shift when new mail arrives between fetches). Generic for the
382
- * same reason `hasUnseenRows()` is. */
383
- function appendUnseenRows<T>(shown: T[], more: T[], idOf: (row: T) => string): T[] {
384
- const seen = new Set(shown.map(idOf));
385
- const unseen: T[] = [];
386
- for (const row of more) {
387
- if (!seen.has(idOf(row))) {
388
- seen.add(idOf(row));
389
- unseen.push(row);
390
- }
391
- }
392
- return unseen.length === 0 ? shown : [...shown, ...unseen];
393
- }
394
-
395
- const messageUid = (message: Message) => message.uid;
396
- const conversationKey = (conversation: ConversationSummary) => conversation.conversationId;
397
-
398
- /** Flattens and sorts a per-mailbox fetch into one merged, newest-first list - the aggregate ("All
399
- * Inboxes" etc.) equivalent of `mergeSearchResults()` above, but simpler: an aggregated message has no
400
- * natural relevance score to normalize, so this only ever sorts by `receivedDate`. */
401
- function mergeInboxMessages(perMailbox: { mailbox: Mailbox; messages: Message[] }[]): Message[] {
402
- return perMailbox
403
- .flatMap((entry) => entry.messages)
404
- .sort((a, b) => new Date(b.receivedDate).getTime() - new Date(a.receivedDate).getTime());
405
- }
406
-
407
- /**
408
- * Fans out one `listMessages()` call per accessible mailbox that has a folder of `type`, merges the
409
- * results newest-first. A mailbox with no matching folder, or whose fetch fails, simply contributes
410
- * nothing - one mailbox's absence/failure must not blank out every other mailbox's messages.
411
- *
412
- * **Pagination scope trim (deliberate, matching this file's own documented Tier 2/3 tradeoffs)**: there is
413
- * no composite cursor across an arbitrary number of independently-paginated mailboxes in this pass - this
414
- * always fetches exactly each mailbox's own first page (`MESSAGE_PAGE_SIZE`) and the caller never offers a
415
- * "load more" for the result (see `InboxContent`'s own `hasMore` handling in aggregate mode) - a real
416
- * composite-cursor "load more" per mailbox is a natural v2 if usage shows people scrolling past the first
417
- * page in aggregate view often.
418
- */
419
- async function fetchAggregateMessages(
420
- mailboxFolders: MailboxFolders[],
421
- type: AggregateFolderType,
422
- filter: MessageListFilter,
423
- ): Promise<Message[]> {
424
- const perMailbox = await Promise.all(
425
- mailboxFolders.map(async ({ mailbox, folders }) => {
426
- const folder = folders.find((f) => f.type === type);
427
- if (!folder) {
428
- return { mailbox, messages: [] as Message[] };
429
- }
430
- // The filter is a server-side one per mailbox; the *sort* deliberately isn't offered here (see
431
- // this function's own pagination scope trim) - each mailbox contributes its own newest page and
432
- // they're merged newest-first, which a different sort key couldn't be made honest across an
433
- // arbitrary number of independently-paged folders.
434
- const messages = await listMessages(folder.uid, { limit: MESSAGE_PAGE_SIZE, filter }).catch(() => [] as Message[]);
435
- return { mailbox, messages };
436
- }),
437
- );
438
- return mergeInboxMessages(perMailbox);
439
- }
440
-
441
- export default function InboxPage(props: MailShellProps) {
442
- return (
443
- <MailShell {...props}>
444
- <InboxContent userUid={props.userUid} />
445
- </MailShell>
446
- );
447
- }
448
-
449
- function InboxContent({ userUid }: { userUid?: string }) {
450
- const { folderUid, mailboxUid, mailboxes, mailboxFolders, aggregateFolderType, onFolderCreated } = useMailShell();
451
- const isMobile = useIsMobile();
452
- const { requestUnlock } = useUnlockPrompt();
453
- const [messages, setMessages] = useState<Message[]>([]);
454
- const [conversations, setConversations] = useState<ConversationSummary[]>([]);
455
- const [loading, setLoading] = useState(true);
456
- const [loadingMore, setLoadingMore] = useState(false);
457
- const [hasMore, setHasMore] = useState(false);
458
- const [error, setError] = useState<string | null>(null);
459
- const [selectedUid, setSelectedUid] = useState<string | null>(null);
460
- // The thread the conversation list opened, and which of its messages was picked - the reading pane
461
- // shows the whole conversation, positioned at that message (see `ConversationThreadPane`).
462
- const [openThread, setOpenThread] = useState<{ conversation: ConversationSummary; uid: string } | null>(null);
463
- // Messages the page has a newer copy of than `ConversationList` fetched (so far only the one the reading
464
- // pane just marked read), applied over its own child rows so they don't stay bold after being read.
465
- const [conversationPatches, setConversationPatches] = useState<Record<string, Message>>({});
466
- // Folders this session created on demand for a bulk Delete/Report junk - see `resolveFolderOfType()`.
467
- const lazyFoldersRef = useRef<Map<string, string>>(new Map());
468
- const [selectMode, setSelectMode] = useState(false);
469
- const [selectedUids, setSelectedUids] = useState<Set<string>>(new Set());
470
- // Select mode over the *conversation* list ticks whole conversations rather than messages: the rows
471
- // there are conversations, and a bulk action on one means "every message of it that is in this folder".
472
- // Their messages are fetched (once, cached here) as each conversation is ticked, so the selection bar
473
- // and every bulk action below keep working on the `Message[]` they already take.
474
- const [selectedConversationIds, setSelectedConversationIds] = useState<Set<string>>(new Set());
475
- const [conversationMessagesById, setConversationMessagesById] = useState<Record<string, Message[]>>({});
476
- // A ticked conversation whose messages are still being fetched - every bulk action is held meanwhile,
477
- // or it would act on a selection that is still arriving.
478
- const [resolvingSelection, setResolvingSelection] = useState(0);
479
- const [bulkBusy, setBulkBusy] = useState(false);
480
- const [bulkError, setBulkError] = useState<string | null>(null);
481
- // Bumped to force the list effect below to re-run - a bulk update is deliberately neither atomic nor
482
- // all-or-nothing (see `bulkUpdateMessages()`), so a rejection means refetching rather than guessing
483
- // which half of the selection actually landed.
484
- const [refreshKey, setRefreshKey] = useState(0);
485
- const [searchInput, setSearchInput] = useState("");
486
- const [searchQuery, setSearchQuery] = useState("");
487
- const [snippets, setSnippets] = useState<Record<string, string>>({});
488
- // The *open mailbox's* labels, for the Filter menu's Labels submenu, select mode's Apply label, and -
489
- // unless the selected message belongs to another mailbox - the reading pane's own Labels menu.
490
- const [mailboxLabels, setMailboxLabels] = useState<Label[]>([]);
491
- // The selected message's own mailbox's labels, when that is a different mailbox from the open one: in
492
- // search and aggregate views it can be, and its labels must not be offered as a filter for this one.
493
- // Empty (and never fetched) otherwise - see `labels` below.
494
- const [otherMailboxLabels, setOtherMailboxLabels] = useState<Label[]>([]);
495
- // Tier 2's own reported window coverage for the current search - undefined outside a search, or
496
- // before Tier 2 has resolved yet for this search pass.
497
- const [coverage, setCoverage] = useState<Coverage | undefined>(undefined);
498
- // Keyed by message uid - see decryptEncryptedRows(). Never cleared on folder/search switches (a
499
- // decrypted row stays decrypted while its keys stay unlocked; re-decrypting on every navigation would
500
- // waste work for no benefit) - only cleared when the mailbox's keys are locked (see the
501
- // `subscribeKeySession()` effect below).
502
- const [decryptedRows, setDecryptedRows] = useState<Record<string, DecryptedRow>>({});
503
- // Bumped after a successful on-demand unlock to re-run the search effect below - it's not a
504
- // dependency the effect could otherwise react to (getUnlockedKeys() is a plain module-level read, not
505
- // React state; see keySession.ts's own doc comment).
506
- const [unlockRefresh, setUnlockRefresh] = useState(0);
507
- // §_Progressive Results_: which of the current search's uids are still an unconfirmed Tier 1
508
- // `metadataOnly` guess (rendered as a skeleton row - see the JSX below) - empty outside a search, and
509
- // always empty again once every tier has reported for the current pass (each unresolved entry is by
510
- // then either confirmed, real content, or pruned - see the search orchestration effect).
511
- const [pendingUids, setPendingUids] = useState<Set<string>>(new Set());
512
- // Withholds a hard result count until every tier has reported for the current search pass (§_Progressive
513
- // Results_: "Never show a hard count until every tier has reported... A settled count is the signal
514
- // that ordering is final"). Reset on every fresh search; irrelevant outside search mode.
515
- const [tier1Done, setTier1Done] = useState(false);
516
- const [tier2Done, setTier2Done] = useState(false);
517
- const [tier3Done, setTier3Done] = useState(false);
518
- // Toggled by the "Search all mail" action next to the results count - removes Tier 3's own default
519
- // bound (tightened to Tier 2's coverage window otherwise - see tightenBeforeToCoverage()) for one
520
- // re-run. Stored as the mailbox/folder/query it was requested for, not a plain flag, so it resets the
521
- // moment any of those change - derived in the same render, so the search effect never runs a new
522
- // query with a previous query's unbounded Tier 3 window first.
523
- const [searchAllMailKey, setSearchAllMailKey] = useState<string | null>(null);
524
- const searchAllMailScope = `${mailboxUid ?? ""}\n${folderUid ?? ""}\n${searchQuery}`;
525
- const searchAllMail = searchAllMailKey === searchAllMailScope;
526
- // The mailbox unlock/decrypt call sites below treat as "the" mailbox when there's no single selected
527
- // one (aggregate mode) - mirrors `MailShell`'s own identical `defaultMailboxUid` fallback. An
528
- // aggregate-view row from a *different*, not-yet-unlocked mailbox stays locked until that mailbox's
529
- // own folder view is opened directly - an accepted limitation, not a bug (see `MailShell`'s own doc
530
- // comment on the same tradeoff for its `LocalIndexLifecycle`/`KeyEnrollmentGate` wiring).
531
- const activeMailboxUid = mailboxUid ?? mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
532
- const mailboxKeys = mailboxes.find((mb) => mb.uid === activeMailboxUid)?.keys ?? [];
533
- // The Sort/Filter menus' and "Show as conversations"' current settings, remembered per mailbox across
534
- // reloads (`listPreferences.ts`). Read during render, not in an effect, so the very first listing
535
- // already uses the remembered arrangement rather than fetching the default one and immediately
536
- // refetching it - and kept per mailbox rather than as one value plus a "which mailbox is this?" check,
537
- // so switching mailbox simply reads the other entry. What this session has changed wins over the store,
538
- // which a storage-blocked browser refuses to keep.
539
- const [preferencesByMailbox, setPreferencesByMailbox] = useState<Record<string, MailListPreferences>>({});
540
- const preferences: MailListPreferences = preferencesByMailbox[activeMailboxUid] ?? getMailListPreferences(activeMailboxUid);
541
- function updatePreferences(patch: Partial<MailListPreferences>) {
542
- const next = { ...preferences, ...patch };
543
- setPreferencesByMailbox((prev) => ({ ...prev, [activeMailboxUid]: next }));
544
- setMailListPreferences(activeMailboxUid, next);
545
- }
546
- // Search stays real-folder-only - Tier 1/2/3 are all deeply mailbox/folder-scoped, and extending them
547
- // to span an arbitrary number of mailboxes is out of scope for this pass (see the aggregate-fetch
548
- // branch below, which the search effect never reaches while `folderUid` is unset).
549
- const isSearching = !preferences.showAsConversations && searchQuery.length > 0 && !aggregateFolderType;
550
- // Focused/Other is an Inbox-only concept (`FocusedInboxUtils.classifyMessage()` short-circuits to
551
- // Focused for every other folder), and
552
- // search results are ranked across folders rather than listed from one, so neither tab is offered
553
- // there. Not offered for an aggregate view either (each mailbox classifies independently; merging
554
- // that is out of scope).
555
- const currentFolders = mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? [];
556
- const currentFolderIsInbox = currentFolders.find((f) => f.uid === folderUid)?.type === "inbox";
557
- const offerClassificationFilters = currentFolderIsInbox && !isSearching && !aggregateFolderType;
558
- // A remembered Focused/Other filter must not silently narrow a folder that has no Focused Inbox to
559
- // speak of - it stays remembered for when the Inbox is opened again, but doesn't apply meanwhile.
560
- const effectiveFilter: MessageListFilter =
561
- (preferences.filter === "focused" || preferences.filter === "other") && !offerClassificationFilters
562
- ? "all"
563
- : preferences.filter;
564
- // Left out entirely rather than sent empty, so a list with no label filter asks for exactly the URL it
565
- // always did.
566
- const labelFilter = preferences.labelUids.length > 0 ? { labelUids: preferences.labelUids } : {};
567
- // Every server-side list parameter the toolbar controls, in one place so the first page and each
568
- // `loadMore()` page can't drift apart.
569
- const listParams: MessageListParams = {
570
- limit: MESSAGE_PAGE_SIZE,
571
- sortBy: preferences.sortBy,
572
- sortOrder: preferences.sortOrder,
573
- filter: effectiveFilter,
574
- ...labelFilter,
575
- };
576
- // A dependency of the list effect and of `loadMore()`, which can't take the array itself (a new one
577
- // every render would refetch on every render).
578
- const labelFilterKey = preferences.labelUids.join(",");
579
- /** The sort the *server* is being asked for, as one dependency value. Empty while conversations are
580
- * shown: `GET /mail/messages/conversations` takes no sort parameters at all, so those rows are ordered
581
- * in the browser (`sortConversations()`) and rearranging them must not refetch the identical page -
582
- * which would also collapse whichever conversations the reader had expanded. */
583
- const serverSortKey = preferences.showAsConversations ? "" : `${preferences.sortBy}:${preferences.sortOrder}`;
584
- /** The conversation list's own equivalent of `listParams` - a function because the page differs. */
585
- function conversationParams(page: number): ConversationListParams {
586
- return { folderUid, filter: effectiveFilter, ...labelFilter, page, limit: MESSAGE_PAGE_SIZE };
587
- }
588
- // How far into the folder's *current* server-side listing the rows fetched so far reach. Offset
589
- // paging, not a cursor (`listMessages()` has none): a row removed locally (archived, scheduled send
590
- // cancelled) also left the folder server-side, shifting every later message back by one - so each
591
- // removal steps this back too, or the next page would silently skip a message. See `loadMore()`.
592
- const listedOffsetRef = useRef(0);
593
- const scrollContainerRef = useRef<HTMLDivElement | null>(null);
594
- // State (via a callback ref), not a plain ref: the sentinel mounts and unmounts as the list loads,
595
- // filters, and empties, and the observer effect below must re-attach to whichever node is current.
596
- const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
597
- const [loadMoreError, setLoadMoreError] = useState<string | null>(null);
598
- const loadMoreErrorRef = useRef<string | null>(null);
599
- loadMoreErrorRef.current = loadMoreError;
600
- const loadMoreInFlightRef = useRef(false);
601
- // Bumped by `loadMore()` for each page that added at least one row - the only event the continuation
602
- // effect below keeps loading after. A counter rather than watching `loadingMore` flip back to false: a
603
- // fast response can settle before React ever renders the `true`, so that flip isn't reliably observable.
604
- const [appendedPageCount, setAppendedPageCount] = useState(0);
605
- // Consecutive full pages that added no new rows (every row was already shown - e.g. new mail shifted the
606
- // folder's pages). Such a page still counts as progress for the continuation effect, up to
607
- // `MAX_EMPTY_PAGE_CONTINUATIONS` in a row; past that, `loadMoreStalled` shows a "Load more" button
608
- // instead, so a server that keeps repeating rows is never looped on.
609
- const emptyPageStreakRef = useRef(0);
610
- const [loadMoreStalled, setLoadMoreStalled] = useState(false);
611
- const messagesRef = useRef(messages);
612
- messagesRef.current = messages;
613
- const conversationsRef = useRef(conversations);
614
- conversationsRef.current = conversations;
615
- // Reset to a fresh Map at the start of every new search pass (see the search effect below) - see
616
- // resolveHitsToMessages()'s own doc comment on why this needs to persist *within* one pass but not
617
- // across passes (a stale `null` for a uid that's since become resolvable elsewhere must not stick).
618
- const resolvedMessageCacheRef = useRef<Map<string, Message | null>>(new Map());
619
- // Session-scoped, never explicitly cleared - see Tier3Cache's own doc comment above.
620
- const tier3CacheRef = useRef<Tier3Cache>(new Map());
621
- // The latest composite cursor this search pass has reached - read by loadMore(), written at the end
622
- // of both the fresh-search orchestration and loadMore() itself. Not React state: it never drives a
623
- // render on its own, only what loadMore() does with it later.
624
- const compositeCursorRef = useRef<CompositeCursor | undefined>(undefined);
625
- // Guards every async load below - each search stage, the plain folder/conversation/aggregate listings,
626
- // and `loadMore()` - against a stale, still-in-flight pass clobbering state for a newer one that started
627
- // after it (the query, folder, or view changed) - the same `loadSeq`-style monotonic-id pattern already used elsewhere in this codebase (e.g.
628
- // `settings/privacy/index.tsx`'s `ExportSection`), generalized here across three independently-timed
629
- // async stages instead of one.
630
- const searchRunIdRef = useRef(0);
631
- // Bumped whenever `activeMailboxUid`'s keys are locked (see the `subscribeKeySession()` effect below) - a
632
- // decrypt that started before the lock checks it before storing its now-stale plaintext rows.
633
- const lockGenerationRef = useRef(0);
634
- // `messages` themselves aren't a dependency here on purpose - a message uid, once decrypted, is
635
- // never re-decrypted just because the list re-renders with the same rows (e.g. a folder-unrelated
636
- // state update elsewhere). New rows (a fresh page load, load-more, or a completed search) each
637
- // re-trigger this the normal way, by changing `messages` itself.
638
- //
639
- // Scoped to `activeMailboxUid`'s own rows only - in aggregate mode `messages` can span several
640
- // mailboxes, but only one mailbox's keys are ever being unlocked/tracked here (see `activeMailboxUid`'s
641
- // own doc comment above); an encrypted row from any other mailbox simply isn't a candidate for this
642
- // auto-decrypt or the manual unlock banner below.
643
- const undecryptedEncryptedUids = messages
644
- .filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && !decryptedRows[m.uid] && m.mailboxUid === activeMailboxUid)
645
- .map((m) => m.uid);
646
-
647
- // Once unlocked, silently decrypt this page's own encrypted rows to show their real subject/preview -
648
- // no prompt needed here, the same way searchEncryptedCandidates() already auto-includes decrypted
649
- // matches once unlocked without asking again. Only the *first* unlock (or a fresh page of messages
650
- // arriving) needs this; `handleUnlockList()` below covers the not-yet-unlocked case explicitly.
651
- useEffect(() => {
652
- if (undecryptedEncryptedUids.length === 0 || !activeMailboxUid) {
653
- return;
654
- }
655
- const unlocked = getUnlockedKeys(activeMailboxUid);
656
- if (!unlocked) {
657
- return;
658
- }
659
- let cancelled = false;
660
- const lockGeneration = lockGenerationRef.current;
661
- void decryptEncryptedRows(
662
- messages.filter((m) => undecryptedEncryptedUids.includes(m.uid)),
663
- unlocked,
664
- ).then((decrypted) => {
665
- // A lock while this was in flight already cleared `decryptedRows` - never put them back.
666
- if (!cancelled && lockGeneration === lockGenerationRef.current && Object.keys(decrypted).length > 0) {
667
- setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
668
- }
669
- });
670
- return () => {
671
- cancelled = true;
672
- };
673
- }, [messages, unlockRefresh]);
674
-
675
- // Locking a mailbox's keys (idle timeout, "Destroy keys on this device now", sign-out) must take its
676
- // decrypted content off screen too, not just out of memory: decrypted subjects/previews, search
677
- // snippets (Tier 2/3 snippets are decrypted content), and the already-decrypted Tier 3 candidates. A
678
- // live search re-runs, so Tier 2/3 contribute nothing again until the user unlocks. Read through a ref
679
- // so the subscription itself doesn't churn on every render.
680
- const keyLockStateRef = useRef({ activeMailboxUid, isSearching });
681
- keyLockStateRef.current = { activeMailboxUid, isSearching };
682
- useEffect(
683
- () =>
684
- subscribeKeySession(({ mailboxUid: changedMailboxUid, state }) => {
685
- const current = keyLockStateRef.current;
686
- if (state !== "locked" || changedMailboxUid !== current.activeMailboxUid) {
687
- return;
688
- }
689
- lockGenerationRef.current += 1;
690
- setDecryptedRows({});
691
- setSnippets({});
692
- tier3CacheRef.current.clear();
693
- if (current.isSearching) {
694
- setUnlockRefresh((n) => n + 1);
695
- }
696
- }),
697
- [],
698
- );
699
-
700
- async function handleUnlockList() {
701
- try {
702
- const unlocked = await requestUnlock(activeMailboxUid, mailboxKeys);
703
- const lockGeneration = lockGenerationRef.current;
704
- const decrypted = await decryptEncryptedRows(
705
- messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && m.mailboxUid === activeMailboxUid),
706
- unlocked,
707
- );
708
- if (lockGeneration === lockGenerationRef.current) {
709
- setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
710
- }
711
- } catch {
712
- // User dismissed the unlock dialog - rows stay exactly as they were.
713
- }
714
- }
715
-
716
- async function handleUnlockSearch() {
717
- try {
718
- await requestUnlock(activeMailboxUid, mailboxKeys);
719
- setUnlockRefresh((n) => n + 1);
720
- } catch {
721
- // User dismissed the unlock dialog - the search results stay exactly as they were.
722
- }
723
- }
724
-
725
- // Labels are mailbox-wide, not folder-scoped - fetched once per mailbox rather than per message, and
726
- // handed to the detail pane below. A failure here just means the Labels control stays hidden (an empty
727
- // `labels` array) rather than blocking the rest of the inbox. Keyed on the *selected message's own*
728
- // mailbox: aggregate views and search results can show messages from a mailbox other than
729
- // `activeMailboxUid`, and offering that mailbox's labels would let a label from the wrong mailbox be
730
- // applied. The conversation view stays scoped to `activeMailboxUid`, the mailbox its threads come from.
731
- const selectedMessageMailboxUid = messages.find((m) => m.uid === selectedUid)?.mailboxUid;
732
- const labelsMailboxUid = preferences.showAsConversations ? activeMailboxUid : (selectedMessageMailboxUid ?? activeMailboxUid);
733
- // Almost always the open mailbox's own labels, already fetched below - so `labels` reuses that list
734
- // rather than asking for the identical one a second time (which is what this page did on every single
735
- // view). Only a selected message from *another* mailbox - a search hit or an aggregate-view row - needs
736
- // its own fetch, and only then is this state used at all.
737
- const otherMailbox = labelsMailboxUid !== activeMailboxUid;
738
- const labels = otherMailbox ? otherMailboxLabels : mailboxLabels;
739
- // `labelsMailboxUid` is always set: `MailShell` only renders this component once at least one mailbox
740
- // exists, so `activeMailboxUid` (its fallback) always resolves.
741
- useEffect(() => {
742
- if (!otherMailbox) {
743
- setOtherMailboxLabels([]);
744
- return;
745
- }
746
- let cancelled = false;
747
- setOtherMailboxLabels([]);
748
- listLabels(labelsMailboxUid, { limit: 200 })
749
- .then((result) => {
750
- if (!cancelled) {
751
- setOtherMailboxLabels(result);
752
- }
753
- })
754
- .catch(() => undefined);
755
- return () => {
756
- cancelled = true;
757
- };
758
- }, [labelsMailboxUid, otherMailbox]);
759
-
760
- useEffect(() => {
761
- let cancelled = false;
762
- setMailboxLabels([]);
763
- listLabels(activeMailboxUid, { limit: 200 })
764
- .then((result) => {
765
- if (!cancelled) {
766
- setMailboxLabels(result);
767
- }
768
- })
769
- .catch(() => undefined);
770
- return () => {
771
- cancelled = true;
772
- };
773
- }, [activeMailboxUid]);
774
-
775
- // Debounce the raw input into the query actually searched, so every keystroke doesn't fire a request.
776
- useEffect(() => {
777
- const handle = setTimeout(() => setSearchQuery(searchInput.trim()), SEARCH_DEBOUNCE_MS);
778
- return () => clearTimeout(handle);
779
- }, [searchInput]);
780
-
781
- // Loads whichever list the current folder, arrangement and search state call for, and resets every
782
- // piece of per-listing state (selection, paging, select mode) that a previous listing left behind.
783
- useEffect(() => {
784
- setSelectedUid(null);
785
- setOpenThread(null);
786
- setConversationPatches({});
787
- setSelectedUids(new Set());
788
- setSelectedConversationIds(new Set());
789
- setConversationMessagesById({});
790
- listedOffsetRef.current = 0;
791
- compositeCursorRef.current = undefined;
792
- setHasMore(false);
793
- setLoadMoreError(null);
794
- setLoadMoreStalled(false);
795
- emptyPageStreakRef.current = 0;
796
- // Every run - search or not - supersedes whatever an earlier run (or a `loadMore()` it started)
797
- // still has in flight; each async callback below checks this before touching state.
798
- searchRunIdRef.current += 1;
799
- const myRunId = searchRunIdRef.current;
800
- const isCurrentRun = () => searchRunIdRef.current === myRunId;
801
- // Also invalidates on unmount, so nothing lands after the component is gone. Unconditional: this
802
- // cleanup only ever runs for the latest run of this effect (React runs it before the next run
803
- // bumps the id, or on unmount), so the id is always still `myRunId` here.
804
- const invalidate = () => {
805
- searchRunIdRef.current += 1;
806
- };
807
-
808
- if (!folderUid && !aggregateFolderType) {
809
- // The shell hasn't resolved this mailbox's folders yet (the render below says so). Listing
810
- // anything now means a request whose answer is thrown away the moment the Inbox arrives - and
811
- // for conversations a mailbox-wide grouping pass, the most expensive listing there is.
812
- setMessages([]);
813
- setConversations([]);
814
- setLoading(false);
815
- return;
816
- }
817
- if (aggregateFolderType && mailboxFolders.length === 0) {
818
- // The same, for a merged view: it has no folder of its own, but it is built from every
819
- // mailbox's folders, and this effect re-runs the moment they arrive. Listing twice is what
820
- // that cost before.
821
- setMessages([]);
822
- setConversations([]);
823
- setLoading(true);
824
- return;
825
- }
826
-
827
- if (preferences.showAsConversations) {
828
- // Conversations stay single-mailbox (not aggregated across mailboxes in this pass) - in
829
- // aggregate mode this falls back to `activeMailboxUid`, the same mailbox unlock/labels use
830
- // (always set - `MailShell` only renders this component once at least one mailbox exists).
831
- // They're scoped to the selected folder (`folderUid`, absent only in aggregate mode), so the
832
- // conversation list matches the folder the sidebar has selected rather than the whole mailbox.
833
- setLoading(true);
834
- setError(null);
835
- listConversations(activeMailboxUid, conversationParams(0))
836
- .then((result) => {
837
- if (isCurrentRun()) {
838
- setConversations(result);
839
- listedOffsetRef.current = result.length;
840
- setHasMore(result.length === MESSAGE_PAGE_SIZE);
841
- }
842
- })
843
- .catch((err) => {
844
- if (isCurrentRun()) {
845
- setError(err instanceof ApiRequestError ? err.message : "Could not load conversations.");
846
- }
847
- })
848
- .finally(() => {
849
- if (isCurrentRun()) {
850
- setLoading(false);
851
- }
852
- });
853
- return invalidate;
854
- }
855
-
856
- if (aggregateFolderType) {
857
- setLoading(true);
858
- setError(null);
859
- // hasMore stays false (set above) - see fetchAggregateMessages()'s own pagination scope trim.
860
- void fetchAggregateMessages(mailboxFolders, aggregateFolderType, effectiveFilter)
861
- .then((results) => {
862
- if (isCurrentRun()) {
863
- setMessages(results);
864
- }
865
- })
866
- .finally(() => {
867
- if (isCurrentRun()) {
868
- setLoading(false);
869
- }
870
- });
871
- return invalidate;
872
- }
873
-
874
- setLoading(true);
875
- setError(null);
876
-
877
- if (isSearching) {
878
- setCoverage(undefined);
879
- setPendingUids(new Set());
880
- setTier1Done(false);
881
- setTier2Done(false);
882
- setTier3Done(false);
883
- resolvedMessageCacheRef.current = new Map();
884
- const parsed = parseSearchQuery(searchQuery);
885
- const unlocked = getUnlockedKeys(mailboxUid!);
886
- const fingerprint = queryFingerprint(parsed);
887
-
888
- // Recomputes and re-renders the merged list from whatever tiers have reported so far -
889
- // called once after Tier 1+2 (interim: unconfirmed Tier 1 metadataOnly hits render as
890
- // skeletons) and again after Tier 3 (final: anything still unconfirmed is pruned instead -
891
- // §_Progressive Results_' "Skeletons resolve or disappear"). Bails out via `myRunId` if a
892
- // newer search pass has since started.
893
- async function reveal(tier1Hits: SearchResult[], tier2Hits: SearchResult[], tier3Hits: SearchResult[], final: boolean) {
894
- const capped = capSkeletons(tier1Hits);
895
- const confirmed = new Set([...tier2Hits, ...tier3Hits].map((r) => r.entityUid));
896
- const effectiveTier1 = final ? capped.filter((hit) => !hit.metadataOnly || confirmed.has(hit.entityUid)) : capped;
897
- const merged = mergeSearchResults(effectiveTier1, tier2Hits, tier3Hits);
898
- const { messages: resolved, snippets: resolvedSnippets } = await resolveHitsToMessages(
899
- merged,
900
- resolvedMessageCacheRef.current,
901
- );
902
- if (searchRunIdRef.current !== myRunId) {
903
- return;
904
- }
905
- setMessages(resolved);
906
- setSnippets(resolvedSnippets);
907
- if (final) {
908
- setPendingUids(new Set());
909
- } else {
910
- const pending = new Set<string>();
911
- for (const hit of capped) {
912
- if (hit.metadataOnly && !confirmed.has(hit.entityUid)) {
913
- pending.add(hit.entityUid);
914
- }
915
- }
916
- setPendingUids(pending);
917
- }
918
- }
919
-
920
- void (async () => {
921
- try {
922
- const [tier1Page, tier2Page] = await Promise.all([
923
- searchMailbox(parsed.text, tier1SearchParams(parsed, undefined, mailboxUid!)),
924
- searchLocalIndex(mailboxUid!, parsed, unlocked, MESSAGE_PAGE_SIZE, 0),
925
- ]);
926
- if (searchRunIdRef.current !== myRunId) {
927
- return;
928
- }
929
- setTier1Done(true);
930
- setTier2Done(true);
931
- setCoverage(tier2Page.coverage);
932
- setLoading(false);
933
- await reveal(tier1Page.results, tier2Page.results, [], false);
934
-
935
- const windows = tier3Windows(parsed, tier2Page.coverage, searchAllMail);
936
- const cacheKey = tier3CacheKey(mailboxUid!, windows, !!unlocked);
937
- let tier3Full = tier3CacheRef.current.get(cacheKey);
938
- if (!tier3Full) {
939
- tier3Full = await searchTier3Windows(windows, unlocked, mailboxUid!);
940
- if (searchRunIdRef.current !== myRunId) {
941
- return;
942
- }
943
- tier3CacheRef.current.set(cacheKey, tier3Full);
944
- }
945
- const tier3Page = tier3Full.slice(0, MESSAGE_PAGE_SIZE);
946
- setTier3Done(true);
947
- compositeCursorRef.current = {
948
- tier1Cursor: tier1Page.nextCursor,
949
- tier2Offset: tier2Page.results.length,
950
- tier3Offset: tier3Page.length,
951
- tier3Key: cacheKey,
952
- fingerprint,
953
- };
954
- setHasMore(!!tier1Page.nextCursor || tier2Page.hasMore || tier3Page.length < tier3Full.length);
955
- await reveal(tier1Page.results, tier2Page.results, tier3Page, true);
956
- } catch (err) {
957
- if (searchRunIdRef.current === myRunId) {
958
- setError(err instanceof ApiRequestError ? err.message : "Search failed.");
959
- setLoading(false);
960
- }
961
- }
962
- })();
963
- return invalidate;
964
- }
965
-
966
- // Set: the guard at the top of this effect returned for a view with neither a folder nor an
967
- // aggregate type, and the aggregate branch above returned for the one with an aggregate type.
968
- listMessages(folderUid!, listParams)
969
- .then((results) => {
970
- if (isCurrentRun()) {
971
- setMessages(results);
972
- listedOffsetRef.current = results.length;
973
- setHasMore(results.length === MESSAGE_PAGE_SIZE);
974
- }
975
- })
976
- .catch((err) => {
977
- if (isCurrentRun()) {
978
- setError(err instanceof ApiRequestError ? err.message : "Could not load messages.");
979
- }
980
- })
981
- .finally(() => {
982
- if (isCurrentRun()) {
983
- setLoading(false);
984
- }
985
- });
986
- return invalidate;
987
- // `unlockRefresh`/`searchAllMail` are dependencies solely so `handleUnlockSearch()`/"Search all
988
- // mail" can force this effect to re-run the search above - Tier 3 (encrypted) results silently
989
- // contribute nothing without unlocked keys, so this is what actually makes them appear once the
990
- // user unlocks, and what makes "Search all mail" actually remove Tier 3's coverage bound. Neither
991
- // has any effect on the non-search branch below; re-running it with identical inputs just
992
- // re-fetches the same page.
993
- // `refreshKey` is a dependency for the same reason: a failed bulk action bumps it to refetch,
994
- // since a bulk update applies until its first rejection rather than all-or-nothing.
995
- }, [
996
- preferences.showAsConversations,
997
- serverSortKey,
998
- effectiveFilter,
999
- labelFilterKey,
1000
- refreshKey,
1001
- folderUid,
1002
- mailboxUid,
1003
- isSearching,
1004
- searchQuery,
1005
- unlockRefresh,
1006
- searchAllMail,
1007
- aggregateFolderType,
1008
- mailboxFolders,
1009
- activeMailboxUid,
1010
- ]);
1011
-
1012
- function handleSearchAllMail() {
1013
- setSearchAllMailKey(searchAllMailScope);
1014
- }
1015
-
1016
- const loadMore = useCallback(async () => {
1017
- const parsed = parseSearchQuery(searchQuery);
1018
- const fingerprint = queryFingerprint(parsed);
1019
- // While searching, a load-more continues from this query's own cursor - absent until its first page
1020
- // has fully finished (the ref may still hold an earlier query's), in which case there's nowhere to
1021
- // continue from yet.
1022
- const searchCursor = decodeCursor(compositeCursorRef.current, fingerprint);
1023
- if (
1024
- loadMoreInFlightRef.current ||
1025
- !hasMore ||
1026
- loading ||
1027
- (!preferences.showAsConversations && !folderUid) ||
1028
- (isSearching && !searchCursor)
1029
- ) {
1030
- return;
1031
- }
1032
- // A ref, not `loadingMore` state: the observer and the continuation effect below can both call in the
1033
- // same tick, each closing over a render where `loadingMore` was still false.
1034
- loadMoreInFlightRef.current = true;
1035
- setLoadMoreError(null);
1036
- setLoadMoreStalled(false);
1037
- setLoadingMore(true);
1038
- /** Records whether a landed page added rows, and whether the continuation effect should keep going. */
1039
- const notePageLanded = (addedRows: boolean, moreRemain: boolean) => {
1040
- if (addedRows) {
1041
- emptyPageStreakRef.current = 0;
1042
- setAppendedPageCount((n) => n + 1);
1043
- } else if (moreRemain) {
1044
- emptyPageStreakRef.current += 1;
1045
- if (emptyPageStreakRef.current <= MAX_EMPTY_PAGE_CONTINUATIONS) {
1046
- setAppendedPageCount((n) => n + 1);
1047
- } else {
1048
- emptyPageStreakRef.current = 0;
1049
- setLoadMoreStalled(true);
1050
- }
1051
- }
1052
- };
1053
- // A query/folder/view change while this page is in flight bumps the run id (see the effect above) -
1054
- // its rows then belong to a list that's no longer on screen and must not be appended to the new one.
1055
- const myRunId = searchRunIdRef.current;
1056
- const isCurrentRun = () => searchRunIdRef.current === myRunId;
1057
- try {
1058
- if (preferences.showAsConversations) {
1059
- const page = Math.floor(listedOffsetRef.current / MESSAGE_PAGE_SIZE);
1060
- const more = await listConversations(activeMailboxUid, conversationParams(page));
1061
- if (!isCurrentRun()) {
1062
- return;
1063
- }
1064
- const addedRows = hasUnseenRows(conversationsRef.current, more, conversationKey);
1065
- setConversations((prev) => appendUnseenRows(prev, more, conversationKey));
1066
- setHasMore(more.length === MESSAGE_PAGE_SIZE);
1067
- listedOffsetRef.current = page * MESSAGE_PAGE_SIZE + more.length;
1068
- notePageLanded(addedRows, more.length === MESSAGE_PAGE_SIZE);
1069
- } else if (isSearching) {
1070
- const unlocked = getUnlockedKeys(mailboxUid!);
1071
- const cursor = searchCursor!;
1072
-
1073
- const [tier1Page, tier2Page] = await Promise.all([
1074
- searchMailbox(parsed.text, tier1SearchParams(parsed, cursor.tier1Cursor, mailboxUid!)),
1075
- searchLocalIndex(mailboxUid!, parsed, unlocked, MESSAGE_PAGE_SIZE, cursor.tier2Offset),
1076
- ]);
1077
- // The first page cached this pass under `tier3Key` before it created the cursor.
1078
- const tier3Full = tier3CacheRef.current.get(cursor.tier3Key)!;
1079
- const tier3Offset = cursor.tier3Offset;
1080
- const tier3Page = tier3Full.slice(tier3Offset, tier3Offset + MESSAGE_PAGE_SIZE);
1081
-
1082
- // Unlike the fresh-search pass above, a load-more page is resolved and appended in one
1083
- // shot rather than progressively revealed - rows already on screen shouldn't reorder or
1084
- // grow skeletons out from under a reader who has since scrolled past them. Any Tier 1
1085
- // metadataOnly hit this page that neither Tier 2 nor Tier 3 (both already awaited above)
1086
- // confirms simply keeps showing its existing placeholder text rather than a live skeleton
1087
- // - a deliberate, documented scope trim of progressive reveal to the first page only.
1088
- const merged = mergeSearchResults(capSkeletons(tier1Page.results), tier2Page.results, tier3Page);
1089
- const { messages: more, snippets: moreSnippets } = await resolveHitsToMessages(merged, resolvedMessageCacheRef.current);
1090
- if (!isCurrentRun()) {
1091
- return;
1092
- }
1093
- const addedRows = hasUnseenRows(messagesRef.current, more, messageUid);
1094
- setMessages((prev) => appendUnseenRows(prev, more, messageUid));
1095
- setSnippets((prev) => ({ ...prev, ...moreSnippets }));
1096
-
1097
- const nextTier3Offset = tier3Offset + tier3Page.length;
1098
- compositeCursorRef.current = {
1099
- tier1Cursor: tier1Page.nextCursor,
1100
- tier2Offset: cursor.tier2Offset + tier2Page.results.length,
1101
- tier3Offset: nextTier3Offset,
1102
- tier3Key: cursor.tier3Key,
1103
- fingerprint,
1104
- };
1105
- const moreRemain = !!tier1Page.nextCursor || tier2Page.hasMore || nextTier3Offset < tier3Full.length;
1106
- setHasMore(moreRemain);
1107
- notePageLanded(addedRows, moreRemain);
1108
- } else {
1109
- // The page containing the first message not fetched yet. After a local removal that offset is
1110
- // no longer a page boundary, so this page overlaps rows already shown - `appendUnseenRows()`
1111
- // drops those - rather than skipping the message that shifted back across the boundary.
1112
- const page = Math.floor(listedOffsetRef.current / MESSAGE_PAGE_SIZE);
1113
- const more = await listMessages(folderUid!, { ...listParams, page });
1114
- if (!isCurrentRun()) {
1115
- return;
1116
- }
1117
- const addedRows = hasUnseenRows(messagesRef.current, more, messageUid);
1118
- setMessages((prev) => appendUnseenRows(prev, more, messageUid));
1119
- setHasMore(more.length === MESSAGE_PAGE_SIZE);
1120
- listedOffsetRef.current = page * MESSAGE_PAGE_SIZE + more.length;
1121
- notePageLanded(addedRows, more.length === MESSAGE_PAGE_SIZE);
1122
- }
1123
- } catch (err) {
1124
- // Shown next to the sentinel with a Retry button - never auto-retried (see the continuation
1125
- // effect below), so a failing server isn't hammered while the sentinel stays in view.
1126
- if (isCurrentRun()) {
1127
- setLoadMoreError(err instanceof ApiRequestError ? err.message : "Could not load more messages.");
1128
- }
1129
- } finally {
1130
- loadMoreInFlightRef.current = false;
1131
- setLoadingMore(false);
1132
- }
1133
- }, [
1134
- hasMore,
1135
- loading,
1136
- preferences.showAsConversations,
1137
- serverSortKey,
1138
- effectiveFilter,
1139
- labelFilterKey,
1140
- folderUid,
1141
- isSearching,
1142
- searchQuery,
1143
- mailboxUid,
1144
- activeMailboxUid,
1145
- ]);
1146
-
1147
- // Always calls the latest `loadMore` closure so the effect below doesn't need `loadMore` itself in its
1148
- // dependency array (it changes on every keystroke/page load, which would otherwise mean nothing here).
1149
- const loadMoreRef = useRef(loadMore);
1150
- loadMoreRef.current = loadMore;
1151
-
1152
- // Keyed on the sentinel node itself (see `sentinel`'s own comment): it unmounts whenever the list shows
1153
- // "Loading..." and remounts afterwards, so an observer attached once to an earlier node would watch a
1154
- // detached element forever. Only ever rendered in "By date" mode, so no view-mode check is needed.
1155
- useEffect(() => {
1156
- if (!sentinel) {
1157
- return;
1158
- }
1159
- const observer = new IntersectionObserver(
1160
- (entries) => {
1161
- if (entries.some((entry) => entry.isIntersecting) && !loadMoreErrorRef.current) {
1162
- void loadMoreRef.current();
1163
- }
1164
- },
1165
- { root: scrollContainerRef.current, rootMargin: `${LOAD_MORE_ROOT_MARGIN_PX}px` },
1166
- );
1167
- observer.observe(sentinel);
1168
- return () => observer.disconnect();
1169
- }, [sentinel]);
1170
-
1171
- // An observer only reports *changes* - a sentinel still in view after a page lands (the new rows didn't
1172
- // push it out of view, e.g. the Focused/Other filter hid every one of them) never reports again, so
1173
- // keep loading while it's still in view. Only after a page that appended rows, or a full page of rows
1174
- // already shown (bounded - see `emptyPageStreakRef`), never after a failure, and only when the sentinel's
1175
- // real geometry says it's still in view (the observer's last report may predate the rows that just landed).
1176
- useEffect(() => {
1177
- if (appendedPageCount === 0) {
1178
- return;
1179
- }
1180
- // The scroll container is always mounted whenever a sentinel is (the sentinel lives inside it).
1181
- if (sentinel && isWithinLoadMoreRange(sentinel, scrollContainerRef.current!)) {
1182
- void loadMoreRef.current();
1183
- }
1184
- }, [appendedPageCount]);
1185
-
1186
- /**
1187
- * Replaces one listed row - and, in the conversation list, the opened message and the child row
1188
- * standing for it - with a newer copy the reading pane just produced.
1189
- *
1190
- * A conversation's *parent* row has no copy to replace: it is a summary of the whole thread, and its
1191
- * "2 unread" chip and bold styling come from a count the server worked out when the list was fetched.
1192
- * So when the reading pane reports a message it has just read (`previous` unread, `updated` read), that
1193
- * count is decremented here - otherwise a conversation kept claiming unread mail the reader had just
1194
- * read, until the whole list was reloaded.
1195
- */
1196
- function patchListedMessage(updated: Message, previous?: Message) {
1197
- setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m)));
1198
- // `ConversationList` fetched its own copy of this message when the thread was expanded; hand it the
1199
- // newer one so the child row doesn't keep showing a stale read/flag state.
1200
- setConversationPatches((prev) => ({ ...prev, [updated.uid]: updated }));
1201
- if (previous && !previous.flags.read && updated.flags.read) {
1202
- setConversations((prev) =>
1203
- prev.map((conversation) =>
1204
- conversation.messageUids.includes(updated.uid)
1205
- ? { ...conversation, unreadCount: Math.max(0, conversation.unreadCount - 1) }
1206
- : conversation,
1207
- ),
1208
- );
1209
- }
1210
- }
1211
-
1212
- function removeListedMessages(uids: Set<string>) {
1213
- setMessages((prev) => prev.filter((m) => !uids.has(m.uid)));
1214
- listedOffsetRef.current = Math.max(0, listedOffsetRef.current - uids.size);
1215
- setSelectedUid((prev) => (prev && uids.has(prev) ? null : prev));
1216
- }
1217
-
1218
- function removeListedMessage(uid: string) {
1219
- removeListedMessages(new Set([uid]));
1220
- }
1221
-
1222
- // The conversation list opens a whole thread in `ConversationThreadPane`, which loads and marks read
1223
- // its own messages; only the flat list feeds the single-message pane below.
1224
- const selected = preferences.showAsConversations ? null : (messages.find((m) => m.uid === selectedUid) ?? null);
1225
- const attachments = useMessageAttachments(selected);
1226
- useMarkMessageRead(selected, patchListedMessage);
1227
- // Search results can span every folder in the mailbox, not just the one selected in the sidebar - a
1228
- // selected message's own folderUid is the only reliable source for its actual folder type once
1229
- // searching (outside search, every message in `messages` already comes from `folderUid` itself, so
1230
- // this falls back to the sidebar selection unchanged). Aggregate views span every *mailbox* too, so
1231
- // the folder list consulted is the selected message's own mailbox's, not the shell's ambient one. A
1232
- // conversation spans folders for the same reason (an Inbox message and the Sent Items copy of its reply).
1233
- const spansFolders = isSearching || !!aggregateFolderType || preferences.showAsConversations;
1234
- const selectedFolderUid = spansFolders ? (selected?.folderUid ?? folderUid) : folderUid;
1235
- const selectedMailboxUid = spansFolders ? (selected?.mailboxUid ?? activeMailboxUid) : mailboxUid;
1236
- const folders = mailboxFolders.find((mf) => mf.mailbox.uid === selectedMailboxUid)?.folders ?? [];
1237
- const isSentItems = folders.find((f) => f.uid === selectedFolderUid)?.type === "sent_items";
1238
- const isOutbox = folders.find((f) => f.uid === selectedFolderUid)?.type === "outbox";
1239
- const draftsFolderUid = folders.find((f) => f.type === "drafts")?.uid;
1240
-
1241
- /** What a row actually shows as its subject - the decrypted one where this device recovered it, a
1242
- * readable stand-in for an encrypted one it hasn't, and a placeholder for a message with no subject. */
1243
- function rowSubject(message: Message): string {
1244
- return (
1245
- decryptedRows[message.uid]?.subject ||
1246
- (message.subject === ENCRYPTED_SUBJECT_PLACEHOLDER ? "Encrypted message" : message.subject) ||
1247
- "(no subject)"
1248
- );
1249
- }
1250
-
1251
- /** The conversation list's selection as plain messages: every message of every ticked conversation
1252
- * that is in the folder being listed. A conversation spans folders (an Inbox message and the Sent
1253
- * Items copy of its reply), and the list only ever showed this folder's half of it, so a bulk action
1254
- * from here must not reach into the other folders' copies either. */
1255
- const selectedConversationMessages = [...selectedConversationIds].flatMap((id) =>
1256
- (conversationMessagesById[id] ?? []).filter((m) => !folderUid || m.folderUid === folderUid),
1257
- );
1258
- const selectedMessages = preferences.showAsConversations
1259
- ? selectedConversationMessages
1260
- : messages.filter((m) => selectedUids.has(m.uid));
1261
- /** How many rows the list is actually showing - conversations or messages, whichever it lists. What the
1262
- * Select toggle is enabled by: there is nothing to select in a list with no rows. */
1263
- const listedRowCount = preferences.showAsConversations ? conversations.length : messages.length;
1264
- /** The conversation rows in the order the reader arranged them. The endpoint takes no sort parameters
1265
- * of its own (it pages by latest activity), so the arrangement is applied here, to the rows fetched so
1266
- * far - which the Sort menu says on screen. `conversations` itself stays in the order the pages
1267
- * arrived, so paging keeps appending to the same accumulated set. */
1268
- const listedConversations = sortConversations(conversations, preferences.sortBy, preferences.sortOrder);
1269
-
1270
- function leaveSelectMode() {
1271
- setSelectMode(false);
1272
- setSelectedUids(new Set());
1273
- setSelectedConversationIds(new Set());
1274
- setBulkError(null);
1275
- }
1276
-
1277
- function toggleSelected(uid: string) {
1278
- setSelectedUids((prev) => {
1279
- const next = new Set(prev);
1280
- if (next.has(uid)) {
1281
- next.delete(uid);
1282
- } else {
1283
- next.add(uid);
1284
- }
1285
- return next;
1286
- });
1287
- }
1288
-
1289
- /** Loads (once) the messages behind each of `ids`, so a ticked conversation resolves to the messages
1290
- * every bulk action below acts on. If any of them fails to load, none of that batch stays ticked and
1291
- * the bar says why - better than acting on the part of a selection that happened to arrive. */
1292
- async function resolveConversations(ids: string[]) {
1293
- const missing = ids.filter((id) => !conversationMessagesById[id]);
1294
- if (missing.length === 0) {
1295
- return;
1296
- }
1297
- setResolvingSelection((n) => n + 1);
1298
- try {
1299
- const loaded = await Promise.all(
1300
- missing.map(async (id) => [id, await listConversationMessages(activeMailboxUid, id)] as const),
1301
- );
1302
- setConversationMessagesById((prev) => ({ ...prev, ...Object.fromEntries(loaded) }));
1303
- } catch (err) {
1304
- setBulkError(
1305
- err instanceof ApiRequestError ? err.message : "Could not load the messages in one of those conversations.",
1306
- );
1307
- setSelectedConversationIds((prev) => {
1308
- const next = new Set(prev);
1309
- for (const id of missing) {
1310
- next.delete(id);
1311
- }
1312
- return next;
1313
- });
1314
- } finally {
1315
- setResolvingSelection((n) => n - 1);
1316
- }
1317
- }
1318
-
1319
- function toggleConversationSelected(conversation: ConversationSummary) {
1320
- const id = conversation.conversationId;
1321
- const ticking = !selectedConversationIds.has(id);
1322
- setSelectedConversationIds((prev) => {
1323
- const next = new Set(prev);
1324
- if (ticking) {
1325
- next.add(id);
1326
- } else {
1327
- next.delete(id);
1328
- }
1329
- return next;
1330
- });
1331
- if (ticking) {
1332
- void resolveConversations([id]);
1333
- }
1334
- }
1335
-
1336
- function selectAllConversations() {
1337
- const ids = conversations.map(conversationKey);
1338
- setSelectedConversationIds(new Set(ids));
1339
- void resolveConversations(ids);
1340
- }
1341
-
1342
- /**
1343
- * Runs one bulk action over the current selection, then either patches the affected rows in place or
1344
- * drops them (a move takes them out of the folder being listed).
1345
- *
1346
- * A bulk update is applied element by element server-side and stops at its first rejection, so a
1347
- * failure leaves an unknown prefix of the selection already changed (see `bulkUpdateMessages()`) -
1348
- * which is why a failure reloads the list rather than trying to reconcile it, and says so.
1349
- */
1350
- async function runBulkAction(action: (chosen: Message[]) => Promise<Message[]>, removesRows: boolean) {
1351
- const chosen = selectedMessages;
1352
- setBulkBusy(true);
1353
- setBulkError(null);
1354
- try {
1355
- const updated = await action(chosen);
1356
- if (preferences.showAsConversations) {
1357
- // A conversation row is a summary of its messages - its count, unread count, participants
1358
- // and preview all move when a bulk action changes or empties part of it - so the list is
1359
- // reloaded rather than patched row by row.
1360
- setSelectedConversationIds(new Set());
1361
- setConversationMessagesById({});
1362
- setRefreshKey((n) => n + 1);
1363
- } else if (removesRows) {
1364
- removeListedMessages(new Set(chosen.map((m) => m.uid)));
1365
- } else {
1366
- const byUid = new Map(updated.map((m) => [m.uid, m]));
1367
- setMessages((prev) => prev.map((m) => byUid.get(m.uid) ?? m));
1368
- }
1369
- setSelectedUids(new Set());
1370
- } catch (err) {
1371
- setBulkError(
1372
- `${err instanceof ApiRequestError ? err.message : "Those messages couldn't all be updated."} Some of them may already have changed, so the list has been reloaded.`,
1373
- );
1374
- setSelectedUids(new Set());
1375
- setSelectedConversationIds(new Set());
1376
- setConversationMessagesById({});
1377
- setRefreshKey((n) => n + 1);
1378
- } finally {
1379
- setBulkBusy(false);
1380
- }
1381
- }
1382
-
1383
- /** Archive has no folder to move into until the mailbox has one: the server creates it lazily on the
1384
- * first single-message archive, so that call both creates the folder and archives the first message,
1385
- * and the rest of the selection is then moved into the folder it reports. */
1386
- async function bulkArchive(chosen: Message[]): Promise<Message[]> {
1387
- const archiveFolderUid = currentFolders.find((f) => f.type === "archive")?.uid;
1388
- if (archiveFolderUid) {
1389
- return moveMessages(chosen, archiveFolderUid);
1390
- }
1391
- const first = await archiveMessage(chosen[0].uid);
1392
- const rest = chosen.slice(1);
1393
- return rest.length === 0 ? [first] : [first, ...(await moveMessages(rest, first.folderUid))];
1394
- }
1395
-
1396
- /**
1397
- * This mailbox's folder of `type`, created on demand. A mailbox is provisioned with only the folders it
1398
- * has needed so far, so Deleted Items and Junk may genuinely not exist the first time a selection is
1399
- * deleted or reported - and unlike Archive, neither has a server-side lazy-create route to go through.
1400
- *
1401
- * A folder created here isn't in `mailboxFolders` (the shell fetched that once), so it's remembered per
1402
- * mailbox and type until the page reloads; otherwise a second Delete would create a second folder.
1403
- */
1404
- async function resolveFolderOfType(type: Folder["type"], name: string): Promise<string> {
1405
- const key = `${activeMailboxUid}:${type}`;
1406
- const known = currentFolders.find((f) => f.type === type)?.uid ?? lazyFoldersRef.current.get(key);
1407
- if (known) {
1408
- return known;
1409
- }
1410
- const created = await createFolder({ mailboxUid: activeMailboxUid, name, type });
1411
- lazyFoldersRef.current.set(key, created.uid);
1412
- return created.uid;
1413
- }
1414
-
1415
- /**
1416
- * Sets every selected message's labels in one bulk update: each ends up with `labelUids`, plus the
1417
- * ones left partially applied (`keepPartial`) that it already had, plus any label this mailbox no
1418
- * longer defines - a label the menu couldn't show isn't one the reader chose to remove.
1419
- *
1420
- * `bulkUpdateMessages()` rather than `setMessagesLabels()`, which is its one-list-for-everyone special
1421
- * case: with a partially-applied row each message keeps a *different* list.
1422
- */
1423
- function applyLabelsToSelection(labelUids: string[], keepPartial: string[]) {
1424
- void runBulkAction(
1425
- (chosen) =>
1426
- bulkUpdateMessages(
1427
- chosen.map((message) => {
1428
- const kept = (message.labelUids ?? []).filter(
1429
- (uid) => keepPartial.includes(uid) || !mailboxLabels.some((label) => label.uid === uid),
1430
- );
1431
- return { uid: message.uid, version: message.version, labelUids: [...new Set([...labelUids, ...kept])] };
1432
- }),
1433
- ),
1434
- false,
1435
- );
1436
- }
1437
-
1438
- function moveSelectionToType(type: Folder["type"], name: string) {
1439
- void runBulkAction(async (chosen) => moveMessages(chosen, await resolveFolderOfType(type, name)), true);
1440
- }
1441
-
1442
- const loadMoreStatus = loadingMore ? (
1443
- "Loading more\u2026"
1444
- ) : loadMoreError ? (
1445
- <span className="inline-flex items-center gap-2">
1446
- <span role="alert" className="text-danger">
1447
- {loadMoreError}
1448
- </span>
1449
- <button type="button" onClick={() => void loadMoreRef.current()} className="text-primary-dark hover:underline font-medium">
1450
- Retry
1451
- </button>
1452
- </span>
1453
- ) : loadMoreStalled ? (
1454
- <button type="button" onClick={() => void loadMoreRef.current()} className="text-primary-dark hover:underline font-medium">
1455
- Load more
1456
- </button>
1457
- ) : null;
1458
-
1459
- function handleSelect(message: Message) {
1460
- if (selectMode) {
1461
- toggleSelected(message.uid);
1462
- return;
1463
- }
1464
- if (isMobile) {
1465
- window.location.href = `/messages/${encodeURIComponent(message.uid)}`;
1466
- return;
1467
- }
1468
- setSelectedUid(message.uid);
1469
- }
1470
-
1471
- /** Opens a conversation in the reading pane, positioned at one of its messages: the one a child row
1472
- * stands for, or the latest for a parent row. The thread pane loads the thread itself. */
1473
- function handleOpenConversation(conversation: ConversationSummary, uid: string) {
1474
- if (selectMode) {
1475
- // Same rule as `handleSelect()` for a message row: while selecting, a row's own button ticks
1476
- // the row rather than opening it.
1477
- toggleConversationSelected(conversation);
1478
- return;
1479
- }
1480
- if (isMobile) {
1481
- // No dedicated mobile thread route yet - the existing single-message detail route already
1482
- // handles any message uid regardless of conversation grouping.
1483
- window.location.href = `/messages/${encodeURIComponent(uid)}`;
1484
- return;
1485
- }
1486
- setSelectedUid(uid);
1487
- setOpenThread({ conversation, uid });
1488
- }
1489
-
1490
- if (!folderUid && !aggregateFolderType) {
1491
- // `MailShell` never renders this component at all until a mailbox is resolved (see its own
1492
- // full-screen `MailboxProvisioning` takeover otherwise) — this is purely the brief gap before
1493
- // that mailbox's own folder list has finished loading, not a "no mailbox" state. Distinct text
1494
- // from the message list's own "Loading…" below — otherwise the two transient states become
1495
- // indistinguishable to anything (a test, a user re-reading the screen) that catches this one.
1496
- return <p className="p-8 text-sm text-text-muted">Loading your mailbox&hellip;</p>;
1497
- }
1498
-
1499
- return (
1500
- <div className="flex h-full min-h-0">
1501
- <div ref={scrollContainerRef} className="w-full md:w-96 shrink-0 md:border-r border-border overflow-y-auto">
1502
- {selectMode ? (
1503
- <MailSelectionBar
1504
- selected={selectedMessages}
1505
- listed={messages}
1506
- totals={
1507
- preferences.showAsConversations
1508
- ? { selected: selectedConversationIds.size, listed: conversations.length, noun: "conversation" }
1509
- : undefined
1510
- }
1511
- onSelectAll={() =>
1512
- preferences.showAsConversations
1513
- ? selectAllConversations()
1514
- : setSelectedUids(new Set(messages.map((m) => m.uid)))
1515
- }
1516
- onClearSelection={() =>
1517
- preferences.showAsConversations ? setSelectedConversationIds(new Set()) : setSelectedUids(new Set())
1518
- }
1519
- onCancel={leaveSelectMode}
1520
- folders={currentFolders}
1521
- currentFolderUid={folderUid}
1522
- labels={mailboxLabels}
1523
- mailboxUid={activeMailboxUid}
1524
- onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
1525
- onFolderCreated={onFolderCreated}
1526
- onApplyLabels={applyLabelsToSelection}
1527
- onSetRead={(read) => void runBulkAction((chosen) => setMessagesRead(chosen, read), false)}
1528
- onSetFlagged={(flagged) => void runBulkAction((chosen) => setMessagesFlagged(chosen, flagged), false)}
1529
- onArchive={() => void runBulkAction(bulkArchive, true)}
1530
- onMoveTo={(targetFolderUid) => runBulkAction((chosen) => moveMessages(chosen, targetFolderUid), true)}
1531
- onReportJunk={() => moveSelectionToType("junk", "Junk Email")}
1532
- onDelete={() => moveSelectionToType("deleted_items", "Deleted Items")}
1533
- busy={bulkBusy || resolvingSelection > 0}
1534
- error={bulkError}
1535
- />
1536
- ) : (
1537
- <MailListToolbar
1538
- sortBy={preferences.sortBy}
1539
- sortOrder={preferences.sortOrder}
1540
- filter={preferences.filter}
1541
- labelUids={preferences.labelUids}
1542
- labels={mailboxLabels}
1543
- mailboxUid={activeMailboxUid}
1544
- onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
1545
- onLabelUidsChange={(nextLabelUids) => updatePreferences({ labelUids: nextLabelUids })}
1546
- showAsConversations={preferences.showAsConversations}
1547
- onSortChange={(sortBy, sortOrder) => updatePreferences({ sortBy, sortOrder })}
1548
- onFilterChange={(filter) => updatePreferences({ filter })}
1549
- onShowAsConversationsChange={(showAsConversations) => updatePreferences({ showAsConversations })}
1550
- selectMode={selectMode}
1551
- onSelectModeChange={setSelectMode}
1552
- offerClassificationFilters={offerClassificationFilters}
1553
- filterDisabled={isSearching}
1554
- filterDisabledReason="Filters don't apply to search results"
1555
- sortKeysDisabled={isSearching || !!aggregateFolderType}
1556
- // A conversation row is a thread summary, so only some of the keys have anything to
1557
- // order by - the rest stay pickable and are applied to the rows already fetched.
1558
- unavailableSortKeys={preferences.showAsConversations ? CONVERSATION_SORT_UNAVAILABLE : undefined}
1559
- sortKeysNote={
1560
- isSearching
1561
- ? "Search results are ranked by relevance rather than sorted."
1562
- : aggregateFolderType
1563
- ? "This view merges the newest mail from every mailbox and is always listed by date."
1564
- : preferences.showAsConversations
1565
- ? CONVERSATION_SORT_NOTE
1566
- : undefined
1567
- }
1568
- selectDisabled={!!aggregateFolderType || loading || listedRowCount === 0}
1569
- selectDisabledReason={
1570
- aggregateFolderType
1571
- ? "Open a mailbox's own folder to select messages"
1572
- : loading
1573
- ? "Wait for this folder to finish loading"
1574
- : "There is nothing here to select"
1575
- }
1576
- />
1577
- )}
1578
- {!preferences.showAsConversations && (
1579
- <div className="p-2 border-b border-border">
1580
- <input
1581
- type="search"
1582
- value={searchInput}
1583
- onChange={(e) => setSearchInput(e.target.value)}
1584
- placeholder={aggregateFolderType ? "Open a mailbox's own folder to search" : "Search all mail…"}
1585
- aria-label="Search all mail"
1586
- disabled={!!aggregateFolderType}
1587
- className="w-full text-sm px-3 py-1.5 rounded-md border border-border bg-surface disabled:opacity-55"
1588
- />
1589
- </div>
1590
- )}
1591
- {/* Two tabs, as Outlook has: Focused and Other. There is no "All" tab - the whole Inbox is
1592
- still one pick away, in the Filter menu, which is where every other named filter lives
1593
- and the only place that can show which of them is really in force. A stored `all` (or
1594
- Unread, Flagged, ...) therefore still lists what it always did, with neither tab
1595
- pressed, rather than being migrated into one of these two halves behind the reader's
1596
- back - see `MAIL_LIST_FILTERS`, which still offers it. */}
1597
- {offerClassificationFilters && (
1598
- <div className="flex border-b border-border text-xs">
1599
- {MAIL_LIST_CLASSIFICATION_FILTERS.map(({ value, label }) => (
1600
- <button
1601
- key={value}
1602
- type="button"
1603
- aria-pressed={preferences.filter === value}
1604
- onClick={() => updatePreferences({ filter: value })}
1605
- className={[
1606
- "flex-1 py-1.5 font-semibold",
1607
- preferences.filter === value
1608
- ? "text-primary-dark border-b-2 border-primary-dark"
1609
- : "text-text-muted",
1610
- ].join(" ")}
1611
- >
1612
- {label}
1613
- </button>
1614
- ))}
1615
- </div>
1616
- )}
1617
-
1618
- {isSearching && (
1619
- <div className="px-4 py-1.5 text-xs text-text-muted border-b border-border flex items-center justify-between gap-2">
1620
- {/* §_Progressive Results_: "Never show a hard count until every tier has reported.
1621
- Display n of ??, or omit the count. A settled count is the signal that ordering
1622
- is final." */}
1623
- <span>
1624
- {tier1Done && tier2Done && tier3Done
1625
- ? `${messages.length} result${messages.length === 1 ? "" : "s"}`
1626
- : `${messages.length} of ??`}
1627
- </span>
1628
- {tier2Done && !searchAllMail && (
1629
- <button
1630
- type="button"
1631
- onClick={handleSearchAllMail}
1632
- className="text-primary-dark hover:underline font-medium shrink-0"
1633
- >
1634
- Search all mail
1635
- </button>
1636
- )}
1637
- </div>
1638
- )}
1639
- {isSearching && coverage?.indexedFrom && (
1640
- <div className="px-4 py-1.5 text-xs text-text-muted border-b border-border">
1641
- Local search covers messages back to {new Date(coverage.indexedFrom).toLocaleDateString()}
1642
- {coverage.building ? " (still building)" : ""}
1643
- {searchAllMail
1644
- ? " - searching everything, not just recent mail."
1645
- : " - older encrypted mail is still searched, just slower."}
1646
- </div>
1647
- )}
1648
- {isSearching && !getUnlockedKeys(mailboxUid!) && (
1649
- <div className="px-4 py-2 border-b border-border bg-surface-alt">
1650
- <button
1651
- type="button"
1652
- onClick={handleUnlockSearch}
1653
- className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
1654
- >
1655
- <HiOutlineLockClosed size={12} aria-hidden="true" />
1656
- Unlock to include encrypted messages in these results
1657
- </button>
1658
- </div>
1659
- )}
1660
- {!isSearching && !preferences.showAsConversations && undecryptedEncryptedUids.length > 0 && !getUnlockedKeys(activeMailboxUid) && (
1661
- <div className="px-4 py-2 border-b border-border bg-surface-alt">
1662
- <button
1663
- type="button"
1664
- onClick={handleUnlockList}
1665
- className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
1666
- >
1667
- <HiOutlineLockClosed size={12} aria-hidden="true" />
1668
- Unlock to show {undecryptedEncryptedUids.length === 1 ? "an encrypted message's" : "encrypted messages'"} subject
1669
- </button>
1670
- </div>
1671
- )}
1672
-
1673
- {error && (
1674
- <div className="p-4">
1675
- <Alert>{error}</Alert>
1676
- </div>
1677
- )}
1678
-
1679
- {loading ? (
1680
- <p className="p-4 text-sm text-text-muted">Loading&hellip;</p>
1681
- ) : preferences.showAsConversations ? (
1682
- <>
1683
- <ConversationList
1684
- conversations={listedConversations}
1685
- newestFirst={preferences.sortBy === "date" && preferences.sortOrder === "desc"}
1686
- mailboxUid={activeMailboxUid}
1687
- selectedUid={selectedUid}
1688
- messageOverrides={conversationPatches}
1689
- onOpenMessage={handleOpenConversation}
1690
- selectMode={selectMode}
1691
- selectedConversationIds={selectedConversationIds}
1692
- onToggleSelected={toggleConversationSelected}
1693
- />
1694
- {hasMore && (
1695
- <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
1696
- {loadMoreStatus}
1697
- </div>
1698
- )}
1699
- </>
1700
- ) : messages.length === 0 ? (
1701
- <>
1702
- <p className="p-4 text-sm text-text-muted">
1703
- {isSearching
1704
- ? `No messages match "${searchQuery}".`
1705
- : effectiveFilter === "all"
1706
- ? "No messages in this folder."
1707
- : "No messages here."}
1708
- </p>
1709
- {/* Still offered while a filter hides every loaded row - what it's looking for may be
1710
- on a later page. */}
1711
- {hasMore && (
1712
- <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
1713
- {loadMoreStatus}
1714
- </div>
1715
- )}
1716
- </>
1717
- ) : (
1718
- <>
1719
- <ul>
1720
- {messages.map((message) => (
1721
- <li key={message.uid} className="flex items-stretch border-b border-border">
1722
- {selectMode && (
1723
- <span className="shrink-0 flex items-center pl-3">
1724
- <input
1725
- type="checkbox"
1726
- checked={selectedUids.has(message.uid)}
1727
- onChange={() => toggleSelected(message.uid)}
1728
- aria-label={`Select ${rowSubject(message)}`}
1729
- className="w-4 h-4 accent-primary"
1730
- />
1731
- </span>
1732
- )}
1733
- <button
1734
- type="button"
1735
- onClick={() => handleSelect(message)}
1736
- className={[
1737
- "flex-1 min-w-0 text-left px-4 py-3",
1738
- message.uid === selectedUid || selectedUids.has(message.uid)
1739
- ? "bg-primary/10"
1740
- : "hover:bg-surface-alt",
1741
- message.flags.read ? "" : "font-semibold",
1742
- ].join(" ")}
1743
- >
1744
- <div className="flex items-center justify-between gap-2 text-sm">
1745
- <span className="truncate">{message.from.displayName || message.from.address}</span>
1746
- <span className="text-xs text-text-muted shrink-0">
1747
- {new Date(message.receivedDate).toLocaleDateString()}
1748
- </span>
1749
- </div>
1750
- {aggregateFolderType && (
1751
- // The one view where a row needs to say which mailbox it came from.
1752
- <div className="text-xs text-text-muted truncate font-normal">
1753
- {mailboxes.find((mb) => mb.uid === message.mailboxUid)?.displayName}
1754
- </div>
1755
- )}
1756
- {isSearching && pendingUids.has(message.uid) ? (
1757
- // §_Progressive Results_: "Unresolved encrypted results MUST
1758
- // be rendered as skeleton entries in place, not appended on
1759
- // arrival." This uid is a Tier 1 metadataOnly guess Tier 2/3
1760
- // haven't confirmed (or ruled out) yet.
1761
- <div className="flex flex-col gap-1.5 py-0.5">
1762
- <Skeleton height="h-3.5" className="w-2/3 rounded-sm" />
1763
- <Skeleton height="h-3" className="w-full rounded-sm" />
1764
- </div>
1765
- ) : (
1766
- <>
1767
- <div className="text-sm truncate">{rowSubject(message)}</div>
1768
- <div className="flex items-center gap-2 text-xs text-text-muted font-normal">
1769
- <span className="truncate">
1770
- {snippets[message.uid] || decryptedRows[message.uid]?.preview || message.bodyPreview}
1771
- </span>
1772
- {message.hasAttachments && <HiOutlinePaperClip size={12} aria-label="Has attachments" />}
1773
- {message.flags.flagged && (
1774
- <HiOutlineFlag size={12} aria-label="Flagged" className="text-danger" />
1775
- )}
1776
- </div>
1777
- </>
1778
- )}
1779
- </button>
1780
- </li>
1781
- ))}
1782
- </ul>
1783
- {hasMore && (
1784
- <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
1785
- {loadMoreStatus}
1786
- </div>
1787
- )}
1788
- {aggregateFolderType && (
1789
- <p className="p-4 text-center text-xs text-text-muted">
1790
- Showing the most recent mail from each mailbox. Open a specific mailbox&rsquo;s folder to
1791
- see older mail.
1792
- </p>
1793
- )}
1794
- </>
1795
- )}
1796
- </div>
1797
- {/* The reading pane's own height: a row of the full-height mail view, stretched to it by the
1798
- flex chain rather than by a percentage (an explicit height would opt it out of that
1799
- stretching), with `min-h-0` so a long message scrolls inside it instead of pushing it past
1800
- the window. Everything below - the thread pane, each message's `MessageDetailPane`, the
1801
- body iframe that cannot measure itself - takes its height from here, never from a `vh`
1802
- number of its own. */}
1803
- <div className="hidden md:flex flex-1 min-w-0 min-h-0">
1804
- {preferences.showAsConversations ? (
1805
- <ConversationThreadPane
1806
- conversation={openThread?.conversation ?? null}
1807
- selectedUid={openThread?.uid ?? null}
1808
- mailboxUid={activeMailboxUid}
1809
- folders={currentFolders}
1810
- labels={mailboxLabels}
1811
- onMessagePatched={patchListedMessage}
1812
- onMessageRemoved={(updated) => removeListedMessage(updated.uid)}
1813
- onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
1814
- onFolderCreated={onFolderCreated}
1815
- />
1816
- ) : (
1817
- <MessageDetailPane
1818
- message={selected}
1819
- attachments={attachments}
1820
- isSentItems={isSentItems}
1821
- onRecalled={patchListedMessage}
1822
- isOutbox={isOutbox}
1823
- onReceiptHandled={patchListedMessage}
1824
- draftsFolderUid={draftsFolderUid}
1825
- folders={folders}
1826
- onMoved={(updated) => {
1827
- // Same reasoning as onArchived below - a move takes the message out of the folder
1828
- // being listed, so it leaves the list rather than being patched in place.
1829
- removeListedMessage(updated.uid);
1830
- }}
1831
- onFolderCreated={onFolderCreated}
1832
- onScheduledSendCanceled={(updated) => {
1833
- // The message moved out of the currently-viewed Outbox folder (into Drafts)
1834
- // - unlike a recall, which patches a message in place, this removes it from
1835
- // the list entirely, matching what a real folder switch would show.
1836
- removeListedMessage(updated.uid);
1837
- }}
1838
- onArchived={(updated) => {
1839
- // Same reasoning as onScheduledSendCanceled above - the message moved out of
1840
- // whichever folder is currently being viewed (into Archive), so it's removed
1841
- // from the list rather than patched in place.
1842
- removeListedMessage(updated.uid);
1843
- }}
1844
- labels={labels}
1845
- onLabelsChanged={patchListedMessage}
1846
- onLabelCreated={(label) =>
1847
- (otherMailbox ? setOtherMailboxLabels : setMailboxLabels)((prev) => [...prev, label])
1848
- }
1849
- />
1850
- )}
1851
- </div>
1852
- </div>
1853
- );
1854
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import { routedPage } from "./_routedPage.js";
6
+ import { useNavigate } from "../shared/navigation/AppRouter.js";
7
+ import { whenIdle } from "../shared/navigation/idle.js";
8
+ import { prefetchComposeWindow } from "../shared/components/mail/compose/ComposeContext.js";
9
+ import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
10
+ import { HiOutlineFlag, HiOutlineLockClosed, HiOutlinePaperClip } from "react-icons/hi2";
11
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
12
+ import {
13
+ Folder,
14
+ Mailbox,
15
+ Message,
16
+ MessageListFilter,
17
+ MessageListParams,
18
+ archiveMessage,
19
+ bulkUpdateMessages,
20
+ createFolder,
21
+ getMessage,
22
+ getMessageRawContent,
23
+ listMessages,
24
+ moveMessages,
25
+ setMessagesFlagged,
26
+ } from "@rapidmx/react-shared/mail/mailApi.js";
27
+ import { Label, listLabels } from "@rapidmx/react-shared/mail/labelsApi.js";
28
+ import {
29
+ ConversationListParams,
30
+ ConversationSummary,
31
+ listConversationMessages,
32
+ listConversations,
33
+ } from "@rapidmx/react-shared/mail/conversationsApi.js";
34
+ import { SearchResult, search as searchMailbox } from "@rapidmx/react-shared/search/searchApi.js";
35
+ import { parseSearchQuery, type ParsedSearchQuery } from "@rapidmx/react-shared/search/queryGrammar.js";
36
+ import { normalizeServerScores } from "@rapidmx/react-shared/search/searchScoring.js";
37
+ import { searchLocalIndex } from "../shared/search/searchTier2.js";
38
+ import type { Coverage } from "../shared/search/localIndexWorker.js";
39
+ import { getUnlockedKeys, subscribeKeySession, UnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
40
+ import { useMessageAttachments } from "@rapidmx/react-shared/mail/mailDetailHooks.js";
41
+ import useIsMobile from "@rapidmx/react-shared/util/useIsMobile.js";
42
+ import MailShell, {
43
+ AggregateFolderType,
44
+ MailboxFolders,
45
+ MailShellProps,
46
+ useMailShell,
47
+ } from "../shared/components/mail/layout/MailShell.js";
48
+ import MailAddress from "../shared/components/mail/MailAddress.js";
49
+ import { mergeFirstPage } from "../shared/mail/mergeFirstPage.js";
50
+ import { listSnapshotKey, readListSnapshot, saveListScroll, writeListSnapshot } from "../shared/mail/listSnapshots.js";
51
+ import { setReadStateMany } from "../shared/mail/messageReadState.js";
52
+ import { useMarkMessageRead } from "../shared/mail/useMarkMessageRead.js";
53
+ import { ROW_FOCUS_CLASS, UnreadBar, UnreadLabel, dateClass, isUnread, rowClass, senderClass, subjectClass } from "../shared/components/mail/unreadStyle.js";
54
+ import { LazyConversationThreadPane, LazyMessageDetailPane, prefetchReadingPane } from "../shared/components/mail/LazyReadingPane.js";
55
+ import ConversationList from "../shared/components/mail/ConversationList.js";
56
+ import MailListToolbar from "../shared/components/mail/MailListToolbar.js";
57
+ import MailSelectionBar from "../shared/components/mail/MailSelectionBar.js";
58
+ import {
59
+ CONVERSATION_SORT_NOTE,
60
+ CONVERSATION_SORT_UNAVAILABLE,
61
+ MAIL_LIST_CLASSIFICATION_FILTERS,
62
+ MailListPreferences,
63
+ getMailListPreferences,
64
+ setMailListPreferences,
65
+ sortConversations,
66
+ } from "../shared/components/mail/listPreferences.js";
67
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
68
+ import Skeleton, { SkeletonList } from "@rapidmx/react-shared/components/feedback/Skeleton.js";
69
+ import { useUnlockPrompt } from "../shared/components/layout/UnlockPromptProvider.js";
70
+ import { SHORTCUTS } from "../shared/keyboard/keymap.js";
71
+ import { isActivatable } from "../shared/keyboard/targets.js";
72
+ import { useShortcut } from "../shared/keyboard/useShortcut.js";
73
+
74
+ const MESSAGE_PAGE_SIZE = 50;
75
+ const SEARCH_DEBOUNCE_MS = 300;
76
+ const LIST_PREVIEW_MAX_LENGTH = 160;
77
+
78
+ /** The literal outer-envelope `Subject` every encrypted message carries server-side - RFC 9788's
79
+ * `hcp_baseline` policy obscures it to this exact string (see `smimeMessage.ts`'s
80
+ * `applyBaselineOuterHeaders()`), which is also all `Message.subject` ever shows for one of these until
81
+ * decrypted client-side. Used here to recognize which loaded rows are worth decrypting for display. */
82
+ const ENCRYPTED_SUBJECT_PLACEHOLDER = "[...]";
83
+
84
+ /** A row's client-recovered subject/preview, once decrypted - `undefined` fields mean nothing better
85
+ * than the placeholder/blank server value was recoverable for that field specifically. */
86
+ interface DecryptedRow {
87
+ subject?: string;
88
+ preview?: string;
89
+ }
90
+
91
+ /** Strips HTML down to plain text, for a short list-row preview of a decrypted body - mirrors
92
+ * `searchTier3.ts`'s own private `stripHtml()` (not currently exported from `@rapidmx/react-shared`,
93
+ * so duplicated here rather than pulled in through a package change just for this one small, pure
94
+ * helper). Not a security boundary - the output only ever feeds plain text display, truncated below,
95
+ * never rendered back into any DOM. */
96
+ function stripHtmlToText(html: string): string {
97
+ return html
98
+ .replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, " ")
99
+ .replace(/<[^>]+>/g, " ")
100
+ .replace(/&nbsp;/gi, " ")
101
+ .replace(/&amp;/gi, "&")
102
+ .replace(/&lt;/gi, "<")
103
+ .replace(/&gt;/gi, ">")
104
+ .replace(/&quot;/gi, '"')
105
+ .replace(/&#0*39;/gi, "'")
106
+ .replace(/\s+/g, " ")
107
+ .trim();
108
+ }
109
+
110
+ /**
111
+ * Decrypts the subject/preview of every currently-loaded row whose subject is still the RFC 9788
112
+ * placeholder (i.e. every encrypted message this device hasn't already resolved), keyed by uid - the
113
+ * inbox-list counterpart to `MessageDetailPane`'s own single-message decrypt and `searchTier3.ts`'s
114
+ * per-candidate decrypt. Bounded to `messages` (at most one loaded page, `MESSAGE_PAGE_SIZE`), never the
115
+ * whole mailbox - matching `searchEncryptedCandidates()`'s own "bounded, not everything" scope. Runs only
116
+ * once `unlocked` is available (the caller decides when to call this - see `InboxContent`'s own effect
117
+ * and `handleUnlockList()`), and a single row's fetch/decrypt failure never blocks the rest.
118
+ */
119
+ async function decryptEncryptedRows(messages: Message[], unlocked: UnlockedKeys): Promise<Record<string, DecryptedRow>> {
120
+ const encrypted = messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER);
121
+ const entries = await Promise.all(
122
+ encrypted.map(async (message): Promise<[string, DecryptedRow] | null> => {
123
+ try {
124
+ const rawMime = await getMessageRawContent(message.uid);
125
+ // Loaded here, on first use: the S/MIME code (PKI.js, ASN.1, X.509) is over half a megabyte and an inbox with
126
+ // no encrypted mail in it never needs it.
127
+ const { evaluateMessageSecurity } = await import("@rapidmx/react-shared/crypto/messageSecurity.js");
128
+ const security = await evaluateMessageSecurity(rawMime, unlocked);
129
+ if (!security.subject && !security.html) {
130
+ return null;
131
+ }
132
+ const preview = security.html ? stripHtmlToText(security.html).slice(0, LIST_PREVIEW_MAX_LENGTH) : undefined;
133
+ return [message.uid, { subject: security.subject, preview }];
134
+ } catch {
135
+ return null;
136
+ }
137
+ }),
138
+ );
139
+ const result: Record<string, DecryptedRow> = {};
140
+ for (const entry of entries) {
141
+ if (entry) {
142
+ result[entry[0]] = entry[1];
143
+ }
144
+ }
145
+ return result;
146
+ }
147
+
148
+ /** Merges Tier 1 (server, possibly `metadataOnly` for an encrypted message), Tier 2 (local index, fully
149
+ * decrypted and re-scored), and Tier 3 (server-narrowed candidates, decrypted and re-scored) results into
150
+ * one ranked list, per `specs/search.md` §7's "client MUST re-score all results it can see... normalise
151
+ * into the same space rather than interleaving raw scores": each tier is normalized independently via
152
+ * `normalizeServerScores()` before merging, since a Postgres/OpenSearch score, a local `bm25()` score,
153
+ * and this module's own Tier 3 term-count score all occupy unrelated ranges. A uid present in more than
154
+ * one list keeps only the last-inserted entry (Tier 2 wins over Tier 3 wins over Tier 1) - Tier 2 and
155
+ * Tier 3 both represent genuine, content-verified scores for the same message, so which one "wins" on
156
+ * overlap doesn't change correctness, only which of two equally-valid scores is shown; either supersedes
157
+ * Tier 1's metadata-only guess for the same uid.
158
+ *
159
+ * Called progressively - once per tier as it resolves, each time with whatever tiers have reported so
160
+ * far (an empty array for the rest) - by `InboxContent`'s own search orchestration below, per §_Progressive
161
+ * Results_' "reordering is permitted and preferred over appending." This function itself stays pure and
162
+ * stateless; it has no notion of "in progress" versus "final." */
163
+ function mergeSearchResults(tier1: SearchResult[], tier2: SearchResult[], tier3: SearchResult[]): SearchResult[] {
164
+ const normalizedTier1 = normalizeServerScores(tier1);
165
+ const normalizedTier2 = normalizeServerScores(tier2);
166
+ const normalizedTier3 = normalizeServerScores(tier3);
167
+ const merged = new Map<string, { result: SearchResult; normalizedScore: number }>();
168
+ for (const entry of normalizedTier1) {
169
+ merged.set(entry.result.entityUid, entry);
170
+ }
171
+ for (const entry of normalizedTier3) {
172
+ merged.set(entry.result.entityUid, entry);
173
+ }
174
+ for (const entry of normalizedTier2) {
175
+ merged.set(entry.result.entityUid, entry);
176
+ }
177
+ return Array.from(merged.values())
178
+ .sort((a, b) => b.normalizedScore - a.normalizedScore)
179
+ .map((entry) => entry.result);
180
+ }
181
+
182
+ /** `type:` narrows `entityTypes`; when absent this still defaults to `["message"]` — a non-message hit
183
+ * (contact/calendarEvent/note/task) has no `Message` to resolve via `getMessage()` below and is simply
184
+ * dropped by the same eventually-consistent-index fallback that already existed, rather than rendered
185
+ * (this inbox list only ever shows message rows; a real multi-entity-type results view is a separate,
186
+ * larger UI project outside this pass). Shared by both the fresh-search orchestration and `loadMore()`
187
+ * below, which each build this from the same `ParsedSearchQuery` differently only in `cursor`. */
188
+ function tier1SearchParams(parsed: ParsedSearchQuery, cursor: string | undefined, mailboxUid: string) {
189
+ return {
190
+ // The mailbox actually open - omitted, the server searches the caller's *own* mailbox, which is the
191
+ // wrong one whenever a shared mailbox's folder is being viewed.
192
+ mailboxUid,
193
+ types: parsed.entityTypes ?? ["message"],
194
+ cursor,
195
+ limit: MESSAGE_PAGE_SIZE,
196
+ from: parsed.from,
197
+ to: parsed.to,
198
+ cc: parsed.cc,
199
+ subject: parsed.subject,
200
+ hasAttachment: parsed.hasAttachment,
201
+ before: parsed.before,
202
+ after: parsed.after,
203
+ folderUid: parsed.folderUid,
204
+ flags: parsed.flags,
205
+ labels: parsed.labels,
206
+ };
207
+ }
208
+
209
+ /** How many of Tier 1's own `metadataOnly` hits (§7: "an encrypted entity matched only on server-visible
210
+ * metadata... MUST be rendered as skeleton entries in place... using the metadata score as a provisional
211
+ * position") are shown as skeleton rows at once - §_Progressive Results_' "Skeletons MUST be capped, at
212
+ * approximately one and a half pages." A non-`metadataOnly` Tier 1 hit (a real, already-scored content
213
+ * match — always the case for unencrypted mail) is never a skeleton and is never subject to this cap.
214
+ *
215
+ * A Tier 3 candidate that Tier 1 did *not* already surface has no provisional score/position of its own
216
+ * under the spec's own wording above, so it is deliberately never pre-rendered as a skeleton here either
217
+ * - it simply appears, fully resolved, once Tier 3 confirms it (see `InboxContent`'s search
218
+ * orchestration). */
219
+ const SKELETON_CAP = Math.round(MESSAGE_PAGE_SIZE * 1.5);
220
+
221
+ function capSkeletons(tier1Hits: SearchResult[]): SearchResult[] {
222
+ let skeletonsSeen = 0;
223
+ return tier1Hits.filter((hit) => {
224
+ if (!hit.metadataOnly) {
225
+ return true;
226
+ }
227
+ skeletonsSeen += 1;
228
+ return skeletonsSeen <= SKELETON_CAP;
229
+ });
230
+ }
231
+
232
+ /** How many candidates Tier 3 pulls per distinct search - larger than one page's worth so several
233
+ * `loadMore()` pages can be sliced from one decrypt pass (see `Tier3Cache` below) instead of a second,
234
+ * separately expensive server round trip and re-decrypt for the same query. Bounded, not unlimited - per
235
+ * this module's own `tier1SearchParams()` sibling, Tier 3's own candidate-narrowing is already the
236
+ * "heaviest single client-side cost" tier (`specs/search.md` §9's identical framing for attachment
237
+ * extraction); a query whose true candidate set exceeds this simply pages out once this cache is
238
+ * exhausted; `loadMore()` reflects that honestly via `hasMore`. */
239
+ const TIER3_CANDIDATE_LIMIT = 200;
240
+
241
+ /** One entry per distinct (mailbox, query, "search all mail" toggle, unlocked-or-not) combination this
242
+ * tab has already run Tier 3 for - keyed by `tier3CacheKey()` below. Tier 3's decrypt-and-match pass
243
+ * (`searchEncryptedCandidates()`) is by far this search's most expensive step, so it runs once per
244
+ * combination; every subsequent `loadMore()` page for that same combination slices further into the
245
+ * same already-decrypted array. Session-scoped, per tab, with no explicit eviction - a small map that's
246
+ * simply never read again once the query changes, the same shape `InboxContent`'s own `decryptedRows`
247
+ * state already accepts for a similar "worth keeping around, not worth actively pruning" tradeoff.
248
+ *
249
+ * The unlocked-or-not dimension matters: re-running an identical query right after an on-demand unlock
250
+ * (`handleUnlockSearch()`) MUST NOT reuse the "nothing to contribute" entry that same query cached while
251
+ * still locked - `searchEncryptedCandidates()` degrades to `[]` for an absent `unlocked`, and that empty
252
+ * result is exactly as cacheable/reusable as a real one, just under a different key. */
253
+ type Tier3Cache = Map<string, SearchResult[]>;
254
+
255
+ /** Keyed by the exact query windows Tier 3 actually ran (`tier3Windows()` - which already reflect the query,
256
+ * the "Search all mail" toggle, and Tier 2's coverage at the time), not just the query: the same query
257
+ * narrowed differently (a build finished, new mail moved the coverage end) must not reuse a result that was
258
+ * computed over a different date range. */
259
+ function tier3CacheKey(mailboxUid: string, windows: ParsedSearchQuery[], unlocked: boolean): string {
260
+ return `${mailboxUid}|${JSON.stringify(windows)}|${String(unlocked)}`;
261
+ }
262
+
263
+ /** A search query's cache/cursor identity - stable across re-parsing the identical raw text, and
264
+ * distinct for anything else (§8's "a query fingerprint, so a cursor cannot be replayed against a
265
+ * different query"). `JSON.stringify` on `ParsedSearchQuery` is deterministic here because every one of
266
+ * its own fields is a primitive or a `Date` (which serializes to a fixed ISO string) - no nested object
267
+ * whose key order could vary between two structurally-identical parses of the same text. */
268
+ function queryFingerprint(parsed: ParsedSearchQuery): string {
269
+ return JSON.stringify(parsed);
270
+ }
271
+
272
+ /** The date windows Tier 3 still has to search: the query's own range minus Tier 2's guaranteed coverage
273
+ * `[coverage.indexedFrom, coverage.indexedUntil]`, unless the reader explicitly asked to "Search all mail".
274
+ * Tier 2 already holds fully-decrypted, current content for that range, so re-fetching and re-decrypting it
275
+ * through Tier 3's slower candidate-narrowing path would be pure waste. Yields up to two windows - older than
276
+ * the coverage (`before:` tightened to `indexedFrom`) and newer than it (`after:` raised to `indexedUntil`,
277
+ * since nothing indexes mail that arrived after the build pass started) - never *widening* a bound the query
278
+ * already specified, and none at all when the query lies entirely inside the coverage.
279
+ *
280
+ * Only narrows once Tier 2 reports a finished, complete build pass from this session: while it's still
281
+ * building (or a pass stopped early - a failed folder listing, the byte budget) `indexedFrom` is just the
282
+ * oldest row that happens to be present, not a guarantee every encrypted message since then is indexed, and
283
+ * narrowing on it would silently drop encrypted results neither tier returns. */
284
+ function tier3Windows(parsed: ParsedSearchQuery, coverage: Coverage | undefined, searchAllMail: boolean): ParsedSearchQuery[] {
285
+ if (searchAllMail || !coverage?.indexedFrom || !coverage.indexedUntil || coverage.building || !coverage.complete) {
286
+ return [parsed];
287
+ }
288
+ const coveredFrom = new Date(coverage.indexedFrom);
289
+ const coveredUntil = new Date(coverage.indexedUntil);
290
+ const windows: ParsedSearchQuery[] = [];
291
+ if (!parsed.after || parsed.after.getTime() < coveredFrom.getTime()) {
292
+ windows.push({ ...parsed, before: parsed.before && parsed.before.getTime() < coveredFrom.getTime() ? parsed.before : coveredFrom });
293
+ }
294
+ if (!parsed.before || parsed.before.getTime() > coveredUntil.getTime()) {
295
+ windows.push({ ...parsed, after: parsed.after && parsed.after.getTime() > coveredUntil.getTime() ? parsed.after : coveredUntil });
296
+ }
297
+ return windows;
298
+ }
299
+
300
+ /** Runs Tier 3 over each window and merges the candidates (a uid can't match in two disjoint windows, but a
301
+ * message whose date sits exactly on a boundary may come back from both). */
302
+ async function searchTier3Windows(windows: ParsedSearchQuery[], unlocked: UnlockedKeys | undefined, mailboxUid: string): Promise<SearchResult[]> {
303
+ // Loaded on first use, with the S/MIME code it decrypts through (see `decryptEncryptedRows()`).
304
+ const { searchEncryptedCandidates } = await import("@rapidmx/react-shared/search/searchTier3.js");
305
+ const pages = await Promise.all(
306
+ windows.map((window) => searchEncryptedCandidates(window, unlocked, TIER3_CANDIDATE_LIMIT, { mailboxUid })),
307
+ );
308
+ const merged = new Map<string, SearchResult>();
309
+ for (const result of pages.flat()) {
310
+ if (!merged.has(result.entityUid)) {
311
+ merged.set(result.entityUid, result);
312
+ }
313
+ }
314
+ return [...merged.values()];
315
+ }
316
+
317
+ /** The paging state for one search, composited across all three tiers (`specs/search.md` §8) - opaque to
318
+ * every caller the same way `SearchResultPage.nextCursor` is opaque to callers of `search()` itself.
319
+ * Tier 1 keeps the server's own opaque cursor unmodified; Tier 2 (the local index) and Tier 3 (the
320
+ * cached, already-decrypted candidate array - see `Tier3Cache` above) are both this client's own state,
321
+ * so their "position" is just a plain offset into each. */
322
+ interface CompositeCursor {
323
+ tier1Cursor?: string;
324
+ tier2Offset: number;
325
+ tier3Offset: number;
326
+ /** The `Tier3Cache` entry the first page was sliced from - later pages keep slicing the same one. */
327
+ tier3Key: string;
328
+ fingerprint: string;
329
+ }
330
+
331
+ /** `undefined` for a missing, corrupted, or foreign-query cursor - every caller already treats "no
332
+ * cursor" as "start this tier from the beginning," so there's no separate error path needed here. */
333
+ function decodeCursor(raw: CompositeCursor | undefined, fingerprint: string): CompositeCursor | undefined {
334
+ return raw?.fingerprint === fingerprint ? raw : undefined;
335
+ }
336
+
337
+ /** Resolves every hit's `entityUid` to a full `Message` via `getMessage()`, reusing `cache` across
338
+ * repeated calls within the same search pass - `InboxContent`'s own search orchestration below re-merges
339
+ * and re-resolves the *entire* current hit set each time a tier resolves, so without this cache every
340
+ * stage would re-fetch messages an earlier stage already fetched. A hit whose message no longer resolves
341
+ * (deleted after being indexed, or the fetch itself failed) is cached as `null` and dropped - the same
342
+ * "a search hit can briefly outlive the message it points to" tolerance this function's inline
343
+ * predecessor already had. */
344
+ async function resolveHitsToMessages(
345
+ hits: SearchResult[],
346
+ cache: Map<string, Message | null>,
347
+ ): Promise<{ messages: Message[]; snippets: Record<string, string> }> {
348
+ const toFetch = hits.filter((hit) => !cache.has(hit.entityUid));
349
+ await Promise.all(
350
+ toFetch.map(async (hit) => {
351
+ const message = await getMessage(hit.entityUid).catch(() => null);
352
+ cache.set(hit.entityUid, message);
353
+ }),
354
+ );
355
+ const messages: Message[] = [];
356
+ const snippets: Record<string, string> = {};
357
+ for (const hit of hits) {
358
+ const message = cache.get(hit.entityUid);
359
+ if (!message) {
360
+ continue;
361
+ }
362
+ messages.push(message);
363
+ if (hit.snippet) {
364
+ snippets[message.uid] = hit.snippet;
365
+ }
366
+ }
367
+ return { messages, snippets };
368
+ }
369
+
370
+ /** How far outside the scroll container's visible area the load-more sentinel still counts as "in view". */
371
+ const LOAD_MORE_ROOT_MARGIN_PX = 200;
372
+
373
+ /** How many full pages in a row that added no new rows the list keeps loading on its own before it shows a
374
+ * "Load more" button instead. */
375
+ const MAX_EMPTY_PAGE_CONTINUATIONS = 3;
376
+
377
+ /** `true` when `more` has at least one row `shown` doesn't - i.e. appending it actually adds rows. Generic
378
+ * over the row's own identity so both the message list (`uid`) and the conversation list
379
+ * (`conversationId`) page the same way. */
380
+ function hasUnseenRows<T>(shown: T[], more: T[], idOf: (row: T) => string): boolean {
381
+ const seen = new Set(shown.map(idOf));
382
+ return more.some((row) => !seen.has(idOf(row)));
383
+ }
384
+
385
+ /** The load-more sentinel's actual current geometry against its scroll container, with the same margin the
386
+ * IntersectionObserver uses. */
387
+ function isWithinLoadMoreRange(sentinel: HTMLElement, root: HTMLElement): boolean {
388
+ const rect = sentinel.getBoundingClientRect();
389
+ const rootRect = root.getBoundingClientRect();
390
+ return rect.top <= rootRect.bottom + LOAD_MORE_ROOT_MARGIN_PX && rect.bottom >= rootRect.top - LOAD_MORE_ROOT_MARGIN_PX;
391
+ }
392
+
393
+ /** Appends `more` to `shown`, skipping any row already shown - a later page can repeat rows (Tier 1 and
394
+ * Tier 2/3 cursors advance independently, so the same message can come back from a different tier on a
395
+ * later page; a plain folder listing's pages shift when new mail arrives between fetches). Generic for the
396
+ * same reason `hasUnseenRows()` is. */
397
+ function appendUnseenRows<T>(shown: T[], more: T[], idOf: (row: T) => string): T[] {
398
+ const seen = new Set(shown.map(idOf));
399
+ const unseen: T[] = [];
400
+ for (const row of more) {
401
+ if (!seen.has(idOf(row))) {
402
+ seen.add(idOf(row));
403
+ unseen.push(row);
404
+ }
405
+ }
406
+ return unseen.length === 0 ? shown : [...shown, ...unseen];
407
+ }
408
+
409
+ const messageUid = (message: Message) => message.uid;
410
+ const conversationKey = (conversation: ConversationSummary) => conversation.conversationId;
411
+
412
+ /** Flattens and sorts a per-mailbox fetch into one merged, newest-first list - the aggregate ("All
413
+ * Inboxes" etc.) equivalent of `mergeSearchResults()` above, but simpler: an aggregated message has no
414
+ * natural relevance score to normalize, so this only ever sorts by `receivedDate`. */
415
+ function mergeInboxMessages(perMailbox: { mailbox: Mailbox; messages: Message[] }[]): Message[] {
416
+ return perMailbox
417
+ .flatMap((entry) => entry.messages)
418
+ .sort((a, b) => new Date(b.receivedDate).getTime() - new Date(a.receivedDate).getTime());
419
+ }
420
+
421
+ /**
422
+ * Fans out one `listMessages()` call per accessible mailbox that has a folder of `type`, merges the
423
+ * results newest-first. A mailbox with no matching folder, or whose fetch fails, simply contributes
424
+ * nothing - one mailbox's absence/failure must not blank out every other mailbox's messages.
425
+ *
426
+ * **Pagination scope trim (deliberate, matching this file's own documented Tier 2/3 tradeoffs)**: there is
427
+ * no composite cursor across an arbitrary number of independently-paginated mailboxes in this pass - this
428
+ * always fetches exactly each mailbox's own first page (`MESSAGE_PAGE_SIZE`) and the caller never offers a
429
+ * "load more" for the result (see `InboxContent`'s own `hasMore` handling in aggregate mode) - a real
430
+ * composite-cursor "load more" per mailbox is a natural v2 if usage shows people scrolling past the first
431
+ * page in aggregate view often.
432
+ */
433
+ async function fetchAggregateMessages(
434
+ mailboxFolders: MailboxFolders[],
435
+ type: AggregateFolderType,
436
+ filter: MessageListFilter,
437
+ ): Promise<Message[]> {
438
+ const perMailbox = await Promise.all(
439
+ mailboxFolders.map(async ({ mailbox, folders }) => {
440
+ const folder = folders.find((f) => f.type === type);
441
+ if (!folder) {
442
+ return { mailbox, messages: [] as Message[] };
443
+ }
444
+ // The filter is a server-side one per mailbox; the *sort* deliberately isn't offered here (see
445
+ // this function's own pagination scope trim) - each mailbox contributes its own newest page and
446
+ // they're merged newest-first, which a different sort key couldn't be made honest across an
447
+ // arbitrary number of independently-paged folders.
448
+ const messages = await listMessages(folder.uid, { limit: MESSAGE_PAGE_SIZE, filter }).catch(() => [] as Message[]);
449
+ return { mailbox, messages };
450
+ }),
451
+ );
452
+ return mergeInboxMessages(perMailbox);
453
+ }
454
+
455
+ function InboxPage(props: MailShellProps) {
456
+ return (
457
+ <MailShell {...props}>
458
+ <InboxContent userUid={props.userUid} />
459
+ </MailShell>
460
+ );
461
+ }
462
+
463
+ function InboxContent({ userUid }: { userUid?: string }) {
464
+ const { folderUid, mailboxUid, mailboxes, mailboxFolders, aggregateFolderType, onFolderCreated, live, trackMessageChange } = useMailShell();
465
+ const isMobile = useIsMobile();
466
+ const navigate = useNavigate();
467
+ const { requestUnlock } = useUnlockPrompt();
468
+ const [messages, setMessages] = useState<Message[]>([]);
469
+ const [conversations, setConversations] = useState<ConversationSummary[]>([]);
470
+ const [loading, setLoading] = useState(true);
471
+ // Once a list is on screen and the browser has nothing better to do, fetch the code a click on a message (the reading pane)
472
+ // or on Compose/Reply (the compose window, with its editor) would otherwise wait for.
473
+ useEffect(() => {
474
+ if (loading) {
475
+ return;
476
+ }
477
+ return whenIdle(() => {
478
+ prefetchReadingPane();
479
+ prefetchComposeWindow();
480
+ });
481
+ }, [loading]);
482
+ const [loadingMore, setLoadingMore] = useState(false);
483
+ const [hasMore, setHasMore] = useState(false);
484
+ const [error, setError] = useState<string | null>(null);
485
+ const [selectedUid, setSelectedUid] = useState<string | null>(null);
486
+ // The thread the conversation list opened, and which of its messages was picked - the reading pane
487
+ // shows the whole conversation, positioned at that message (see `ConversationThreadPane`).
488
+ const [openThread, setOpenThread] = useState<{ conversation: ConversationSummary; uid: string } | null>(null);
489
+ // Messages the page has a newer copy of than `ConversationList` fetched (so far only the one the reading
490
+ // pane just marked read), applied over its own child rows so they don't stay bold after being read.
491
+ const [conversationPatches, setConversationPatches] = useState<Record<string, Message>>({});
492
+ // Folders this session created on demand for a bulk Delete/Report junk - see `resolveFolderOfType()`.
493
+ const lazyFoldersRef = useRef<Map<string, string>>(new Map());
494
+ const [selectMode, setSelectMode] = useState(false);
495
+ const [selectedUids, setSelectedUids] = useState<Set<string>>(new Set());
496
+ // Select mode over the *conversation* list ticks whole conversations rather than messages: the rows
497
+ // there are conversations, and a bulk action on one means "every message of it that is in this folder".
498
+ // Their messages are fetched (once, cached here) as each conversation is ticked, so the selection bar
499
+ // and every bulk action below keep working on the `Message[]` they already take.
500
+ const [selectedConversationIds, setSelectedConversationIds] = useState<Set<string>>(new Set());
501
+ const [conversationMessagesById, setConversationMessagesById] = useState<Record<string, Message[]>>({});
502
+ // A ticked conversation whose messages are still being fetched - every bulk action is held meanwhile,
503
+ // or it would act on a selection that is still arriving.
504
+ const [resolvingSelection, setResolvingSelection] = useState(0);
505
+ const [bulkBusy, setBulkBusy] = useState(false);
506
+ const [bulkError, setBulkError] = useState<string | null>(null);
507
+ // Bumped to force the list effect below to re-run - a bulk update is deliberately neither atomic nor
508
+ // all-or-nothing (see `bulkUpdateMessages()`), so a rejection means refetching rather than guessing
509
+ // which half of the selection actually landed.
510
+ const [refreshKey, setRefreshKey] = useState(0);
511
+ const [searchInput, setSearchInput] = useState("");
512
+ const [searchQuery, setSearchQuery] = useState("");
513
+ const [snippets, setSnippets] = useState<Record<string, string>>({});
514
+ // The *open mailbox's* labels, for the Filter menu's Labels submenu, select mode's Apply label, and -
515
+ // unless the selected message belongs to another mailbox - the reading pane's own Labels menu.
516
+ const [mailboxLabels, setMailboxLabels] = useState<Label[]>([]);
517
+ // The selected message's own mailbox's labels, when that is a different mailbox from the open one: in
518
+ // search and aggregate views it can be, and its labels must not be offered as a filter for this one.
519
+ // Empty (and never fetched) otherwise - see `labels` below.
520
+ const [otherMailboxLabels, setOtherMailboxLabels] = useState<Label[]>([]);
521
+ // Tier 2's own reported window coverage for the current search - undefined outside a search, or
522
+ // before Tier 2 has resolved yet for this search pass.
523
+ const [coverage, setCoverage] = useState<Coverage | undefined>(undefined);
524
+ // Keyed by message uid - see decryptEncryptedRows(). Never cleared on folder/search switches (a
525
+ // decrypted row stays decrypted while its keys stay unlocked; re-decrypting on every navigation would
526
+ // waste work for no benefit) - only cleared when the mailbox's keys are locked (see the
527
+ // `subscribeKeySession()` effect below).
528
+ const [decryptedRows, setDecryptedRows] = useState<Record<string, DecryptedRow>>({});
529
+ // Bumped after a successful on-demand unlock to re-run the search effect below - it's not a
530
+ // dependency the effect could otherwise react to (getUnlockedKeys() is a plain module-level read, not
531
+ // React state; see keySession.ts's own doc comment).
532
+ const [unlockRefresh, setUnlockRefresh] = useState(0);
533
+ // §_Progressive Results_: which of the current search's uids are still an unconfirmed Tier 1
534
+ // `metadataOnly` guess (rendered as a skeleton row - see the JSX below) - empty outside a search, and
535
+ // always empty again once every tier has reported for the current pass (each unresolved entry is by
536
+ // then either confirmed, real content, or pruned - see the search orchestration effect).
537
+ const [pendingUids, setPendingUids] = useState<Set<string>>(new Set());
538
+ // Withholds a hard result count until every tier has reported for the current search pass (§_Progressive
539
+ // Results_: "Never show a hard count until every tier has reported... A settled count is the signal
540
+ // that ordering is final"). Reset on every fresh search; irrelevant outside search mode.
541
+ const [tier1Done, setTier1Done] = useState(false);
542
+ const [tier2Done, setTier2Done] = useState(false);
543
+ const [tier3Done, setTier3Done] = useState(false);
544
+ // Toggled by the "Search all mail" action next to the results count - removes Tier 3's own default
545
+ // bound (tightened to Tier 2's coverage window otherwise - see tightenBeforeToCoverage()) for one
546
+ // re-run. Stored as the mailbox/folder/query it was requested for, not a plain flag, so it resets the
547
+ // moment any of those change - derived in the same render, so the search effect never runs a new
548
+ // query with a previous query's unbounded Tier 3 window first.
549
+ const [searchAllMailKey, setSearchAllMailKey] = useState<string | null>(null);
550
+ const searchAllMailScope = `${mailboxUid ?? ""}\n${folderUid ?? ""}\n${searchQuery}`;
551
+ const searchAllMail = searchAllMailKey === searchAllMailScope;
552
+ // The mailbox unlock/decrypt call sites below treat as "the" mailbox when there's no single selected
553
+ // one (aggregate mode) - mirrors `MailShell`'s own identical `defaultMailboxUid` fallback. An
554
+ // aggregate-view row from a *different*, not-yet-unlocked mailbox stays locked until that mailbox's
555
+ // own folder view is opened directly - an accepted limitation, not a bug (see `MailShell`'s own doc
556
+ // comment on the same tradeoff for its `LocalIndexLifecycle`/`KeyEnrollmentGate` wiring).
557
+ const activeMailboxUid = mailboxUid ?? mailboxes.find((mb) => mb.ownerUserUid === userUid)?.uid ?? mailboxes[0]?.uid;
558
+ const mailboxKeys = mailboxes.find((mb) => mb.uid === activeMailboxUid)?.keys ?? [];
559
+ // The Sort/Filter menus' and "Show as conversations"' current settings, remembered per mailbox across
560
+ // reloads (`listPreferences.ts`). Read during render, not in an effect, so the very first listing
561
+ // already uses the remembered arrangement rather than fetching the default one and immediately
562
+ // refetching it - and kept per mailbox rather than as one value plus a "which mailbox is this?" check,
563
+ // so switching mailbox simply reads the other entry. What this session has changed wins over the store,
564
+ // which a storage-blocked browser refuses to keep.
565
+ const [preferencesByMailbox, setPreferencesByMailbox] = useState<Record<string, MailListPreferences>>({});
566
+ const preferences: MailListPreferences = preferencesByMailbox[activeMailboxUid] ?? getMailListPreferences(activeMailboxUid);
567
+ function updatePreferences(patch: Partial<MailListPreferences>) {
568
+ const next = { ...preferences, ...patch };
569
+ setPreferencesByMailbox((prev) => ({ ...prev, [activeMailboxUid]: next }));
570
+ setMailListPreferences(activeMailboxUid, next);
571
+ }
572
+ // Search stays real-folder-only - Tier 1/2/3 are all deeply mailbox/folder-scoped, and extending them
573
+ // to span an arbitrary number of mailboxes is out of scope for this pass (see the aggregate-fetch
574
+ // branch below, which the search effect never reaches while `folderUid` is unset).
575
+ const isSearching = !preferences.showAsConversations && searchQuery.length > 0 && !aggregateFolderType;
576
+ // Focused/Other is an Inbox-only concept (`FocusedInboxUtils.classifyMessage()` short-circuits to
577
+ // Focused for every other folder), and
578
+ // search results are ranked across folders rather than listed from one, so neither tab is offered
579
+ // there. Not offered for an aggregate view either (each mailbox classifies independently; merging
580
+ // that is out of scope).
581
+ const currentFolders = mailboxFolders.find((mf) => mf.mailbox.uid === activeMailboxUid)?.folders ?? [];
582
+ const currentFolderIsInbox = currentFolders.find((f) => f.uid === folderUid)?.type === "inbox";
583
+ const offerClassificationFilters = currentFolderIsInbox && !isSearching && !aggregateFolderType;
584
+ // A remembered Focused/Other filter must not silently narrow a folder that has no Focused Inbox to
585
+ // speak of - it stays remembered for when the Inbox is opened again, but doesn't apply meanwhile.
586
+ const effectiveFilter: MessageListFilter =
587
+ (preferences.filter === "focused" || preferences.filter === "other") && !offerClassificationFilters
588
+ ? "all"
589
+ : preferences.filter;
590
+ // Left out entirely rather than sent empty, so a list with no label filter asks for exactly the URL it
591
+ // always did.
592
+ const labelFilter = preferences.labelUids.length > 0 ? { labelUids: preferences.labelUids } : {};
593
+ // Every server-side list parameter the toolbar controls, in one place so the first page and each
594
+ // `loadMore()` page can't drift apart.
595
+ const listParams: MessageListParams = {
596
+ limit: MESSAGE_PAGE_SIZE,
597
+ sortBy: preferences.sortBy,
598
+ sortOrder: preferences.sortOrder,
599
+ filter: effectiveFilter,
600
+ ...labelFilter,
601
+ };
602
+ // A dependency of the list effect and of `loadMore()`, which can't take the array itself (a new one
603
+ // every render would refetch on every render).
604
+ const labelFilterKey = preferences.labelUids.join(",");
605
+ /** The sort the *server* is being asked for, as one dependency value. Empty while conversations are
606
+ * shown: `GET /mail/messages/conversations` takes no sort parameters at all, so those rows are ordered
607
+ * in the browser (`sortConversations()`) and rearranging them must not refetch the identical page -
608
+ * which would also collapse whichever conversations the reader had expanded. */
609
+ const serverSortKey = preferences.showAsConversations ? "" : `${preferences.sortBy}:${preferences.sortOrder}`;
610
+ /** The conversation list's own equivalent of `listParams` - a function because the page differs. */
611
+ function conversationParams(page: number): ConversationListParams {
612
+ return { folderUid, filter: effectiveFilter, ...labelFilter, page, limit: MESSAGE_PAGE_SIZE };
613
+ }
614
+ // How far into the folder's *current* server-side listing the rows fetched so far reach. Offset
615
+ // paging, not a cursor (`listMessages()` has none): a row removed locally (archived, scheduled send
616
+ // cancelled) also left the folder server-side, shifting every later message back by one - so each
617
+ // removal steps this back too, or the next page would silently skip a message. See `loadMore()`.
618
+ const listedOffsetRef = useRef(0);
619
+ const scrollContainerRef = useRef<HTMLDivElement | null>(null);
620
+ const searchInputRef = useRef<HTMLInputElement | null>(null);
621
+ // Where the message the keyboard just removed from the list (deleted, archived, moved) was: the next Down/Up continues from that spot, so
622
+ // clearing an inbox from the keyboard walks down it instead of jumping back to the top. Cleared by any selection.
623
+ const removedAnchorRef = useRef<number | null>(null);
624
+ // State (via a callback ref), not a plain ref: the sentinel mounts and unmounts as the list loads,
625
+ // filters, and empties, and the observer effect below must re-attach to whichever node is current.
626
+ const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
627
+ const [loadMoreError, setLoadMoreError] = useState<string | null>(null);
628
+ const loadMoreErrorRef = useRef<string | null>(null);
629
+ loadMoreErrorRef.current = loadMoreError;
630
+ const loadMoreInFlightRef = useRef(false);
631
+ // Bumped by `loadMore()` for each page that added at least one row - the only event the continuation
632
+ // effect below keeps loading after. A counter rather than watching `loadingMore` flip back to false: a
633
+ // fast response can settle before React ever renders the `true`, so that flip isn't reliably observable.
634
+ const [appendedPageCount, setAppendedPageCount] = useState(0);
635
+ // Consecutive full pages that added no new rows (every row was already shown - e.g. new mail shifted the
636
+ // folder's pages). Such a page still counts as progress for the continuation effect, up to
637
+ // `MAX_EMPTY_PAGE_CONTINUATIONS` in a row; past that, `loadMoreStalled` shows a "Load more" button
638
+ // instead, so a server that keeps repeating rows is never looped on.
639
+ const emptyPageStreakRef = useRef(0);
640
+ const [loadMoreStalled, setLoadMoreStalled] = useState(false);
641
+ const messagesRef = useRef(messages);
642
+ messagesRef.current = messages;
643
+ const conversationsRef = useRef(conversations);
644
+ conversationsRef.current = conversations;
645
+ // Reset to a fresh Map at the start of every new search pass (see the search effect below) - see
646
+ // resolveHitsToMessages()'s own doc comment on why this needs to persist *within* one pass but not
647
+ // across passes (a stale `null` for a uid that's since become resolvable elsewhere must not stick).
648
+ const resolvedMessageCacheRef = useRef<Map<string, Message | null>>(new Map());
649
+ // Session-scoped, never explicitly cleared - see Tier3Cache's own doc comment above.
650
+ const tier3CacheRef = useRef<Tier3Cache>(new Map());
651
+ // The latest composite cursor this search pass has reached - read by loadMore(), written at the end
652
+ // of both the fresh-search orchestration and loadMore() itself. Not React state: it never drives a
653
+ // render on its own, only what loadMore() does with it later.
654
+ const compositeCursorRef = useRef<CompositeCursor | undefined>(undefined);
655
+ // Guards every async load below - each search stage, the plain folder/conversation/aggregate listings,
656
+ // and `loadMore()` - against a stale, still-in-flight pass clobbering state for a newer one that started
657
+ // after it (the query, folder, or view changed) - the same `loadSeq`-style monotonic-id pattern already used elsewhere in this codebase (e.g.
658
+ // `settings/privacy/index.tsx`'s `ExportSection`), generalized here across three independently-timed
659
+ // async stages instead of one.
660
+ const searchRunIdRef = useRef(0);
661
+ // Bumped whenever `activeMailboxUid`'s keys are locked (see the `subscribeKeySession()` effect below) - a
662
+ // decrypt that started before the lock checks it before storing its now-stale plaintext rows.
663
+ const lockGenerationRef = useRef(0);
664
+ // `messages` themselves aren't a dependency here on purpose - a message uid, once decrypted, is
665
+ // never re-decrypted just because the list re-renders with the same rows (e.g. a folder-unrelated
666
+ // state update elsewhere). New rows (a fresh page load, load-more, or a completed search) each
667
+ // re-trigger this the normal way, by changing `messages` itself.
668
+ //
669
+ // Scoped to `activeMailboxUid`'s own rows only - in aggregate mode `messages` can span several
670
+ // mailboxes, but only one mailbox's keys are ever being unlocked/tracked here (see `activeMailboxUid`'s
671
+ // own doc comment above); an encrypted row from any other mailbox simply isn't a candidate for this
672
+ // auto-decrypt or the manual unlock banner below.
673
+ const undecryptedEncryptedUids = messages
674
+ .filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && !decryptedRows[m.uid] && m.mailboxUid === activeMailboxUid)
675
+ .map((m) => m.uid);
676
+
677
+ // Once unlocked, silently decrypt this page's own encrypted rows to show their real subject/preview -
678
+ // no prompt needed here, the same way searchEncryptedCandidates() already auto-includes decrypted
679
+ // matches once unlocked without asking again. Only the *first* unlock (or a fresh page of messages
680
+ // arriving) needs this; `handleUnlockList()` below covers the not-yet-unlocked case explicitly.
681
+ useEffect(() => {
682
+ if (undecryptedEncryptedUids.length === 0 || !activeMailboxUid) {
683
+ return;
684
+ }
685
+ const unlocked = getUnlockedKeys(activeMailboxUid);
686
+ if (!unlocked) {
687
+ return;
688
+ }
689
+ let cancelled = false;
690
+ const lockGeneration = lockGenerationRef.current;
691
+ void decryptEncryptedRows(
692
+ messages.filter((m) => undecryptedEncryptedUids.includes(m.uid)),
693
+ unlocked,
694
+ ).then((decrypted) => {
695
+ // A lock while this was in flight already cleared `decryptedRows` - never put them back.
696
+ if (!cancelled && lockGeneration === lockGenerationRef.current && Object.keys(decrypted).length > 0) {
697
+ setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
698
+ }
699
+ });
700
+ return () => {
701
+ cancelled = true;
702
+ };
703
+ }, [messages, unlockRefresh]);
704
+
705
+ // Locking a mailbox's keys (idle timeout, "Destroy keys on this device now", sign-out) must take its
706
+ // decrypted content off screen too, not just out of memory: decrypted subjects/previews, search
707
+ // snippets (Tier 2/3 snippets are decrypted content), and the already-decrypted Tier 3 candidates. A
708
+ // live search re-runs, so Tier 2/3 contribute nothing again until the user unlocks. Read through a ref
709
+ // so the subscription itself doesn't churn on every render.
710
+ const keyLockStateRef = useRef({ activeMailboxUid, isSearching });
711
+ keyLockStateRef.current = { activeMailboxUid, isSearching };
712
+ useEffect(
713
+ () =>
714
+ subscribeKeySession(({ mailboxUid: changedMailboxUid, state }) => {
715
+ const current = keyLockStateRef.current;
716
+ if (state !== "locked" || changedMailboxUid !== current.activeMailboxUid) {
717
+ return;
718
+ }
719
+ lockGenerationRef.current += 1;
720
+ setDecryptedRows({});
721
+ setSnippets({});
722
+ tier3CacheRef.current.clear();
723
+ if (current.isSearching) {
724
+ setUnlockRefresh((n) => n + 1);
725
+ }
726
+ }),
727
+ [],
728
+ );
729
+
730
+ async function handleUnlockList() {
731
+ try {
732
+ const unlocked = await requestUnlock(activeMailboxUid, mailboxKeys);
733
+ const lockGeneration = lockGenerationRef.current;
734
+ const decrypted = await decryptEncryptedRows(
735
+ messages.filter((m) => m.subject === ENCRYPTED_SUBJECT_PLACEHOLDER && m.mailboxUid === activeMailboxUid),
736
+ unlocked,
737
+ );
738
+ if (lockGeneration === lockGenerationRef.current) {
739
+ setDecryptedRows((prev) => ({ ...prev, ...decrypted }));
740
+ }
741
+ } catch {
742
+ // User dismissed the unlock dialog - rows stay exactly as they were.
743
+ }
744
+ }
745
+
746
+ async function handleUnlockSearch() {
747
+ try {
748
+ await requestUnlock(activeMailboxUid, mailboxKeys);
749
+ setUnlockRefresh((n) => n + 1);
750
+ } catch {
751
+ // User dismissed the unlock dialog - the search results stay exactly as they were.
752
+ }
753
+ }
754
+
755
+ // Labels are mailbox-wide, not folder-scoped - fetched once per mailbox rather than per message, and
756
+ // handed to the detail pane below. A failure here just means the Labels control stays hidden (an empty
757
+ // `labels` array) rather than blocking the rest of the inbox. Keyed on the *selected message's own*
758
+ // mailbox: aggregate views and search results can show messages from a mailbox other than
759
+ // `activeMailboxUid`, and offering that mailbox's labels would let a label from the wrong mailbox be
760
+ // applied. The conversation view stays scoped to `activeMailboxUid`, the mailbox its threads come from.
761
+ const selectedMessageMailboxUid = messages.find((m) => m.uid === selectedUid)?.mailboxUid;
762
+ const labelsMailboxUid = preferences.showAsConversations ? activeMailboxUid : (selectedMessageMailboxUid ?? activeMailboxUid);
763
+ // Almost always the open mailbox's own labels, already fetched below - so `labels` reuses that list
764
+ // rather than asking for the identical one a second time (which is what this page did on every single
765
+ // view). Only a selected message from *another* mailbox - a search hit or an aggregate-view row - needs
766
+ // its own fetch, and only then is this state used at all.
767
+ const otherMailbox = labelsMailboxUid !== activeMailboxUid;
768
+ const labels = otherMailbox ? otherMailboxLabels : mailboxLabels;
769
+ // `labelsMailboxUid` is always set: `MailShell` only renders this component once at least one mailbox
770
+ // exists, so `activeMailboxUid` (its fallback) always resolves.
771
+ useEffect(() => {
772
+ if (!otherMailbox) {
773
+ setOtherMailboxLabels([]);
774
+ return;
775
+ }
776
+ let cancelled = false;
777
+ setOtherMailboxLabels([]);
778
+ listLabels(labelsMailboxUid, { limit: 200 })
779
+ .then((result) => {
780
+ if (!cancelled) {
781
+ setOtherMailboxLabels(result);
782
+ }
783
+ })
784
+ .catch(() => undefined);
785
+ return () => {
786
+ cancelled = true;
787
+ };
788
+ }, [labelsMailboxUid, otherMailbox]);
789
+
790
+ useEffect(() => {
791
+ let cancelled = false;
792
+ setMailboxLabels([]);
793
+ listLabels(activeMailboxUid, { limit: 200 })
794
+ .then((result) => {
795
+ if (!cancelled) {
796
+ setMailboxLabels(result);
797
+ }
798
+ })
799
+ .catch(() => undefined);
800
+ return () => {
801
+ cancelled = true;
802
+ };
803
+ }, [activeMailboxUid]);
804
+
805
+ // Debounce the raw input into the query actually searched, so every keystroke doesn't fire a request.
806
+ useEffect(() => {
807
+ const handle = setTimeout(() => setSearchQuery(searchInput.trim()), SEARCH_DEBOUNCE_MS);
808
+ return () => clearTimeout(handle);
809
+ }, [searchInput]);
810
+
811
+ // Choosing another folder no longer loads a new page, so what was being searched for would follow the reader into it: the
812
+ // search box and its results are cleared instead, as the page load used to. (The first selection resolves after mount - the
813
+ // shell reads the URL and lists the folders in effects - and is not a change of folder.)
814
+ const selectionKey = `${mailboxUid ?? ""}|${folderUid ?? ""}|${aggregateFolderType ?? ""}`;
815
+ const shownSelectionRef = useRef<string | null>(null);
816
+ useEffect(() => {
817
+ const shown = shownSelectionRef.current;
818
+ if (shown !== null && shown !== selectionKey) {
819
+ setSearchInput("");
820
+ setSearchQuery("");
821
+ }
822
+ if (folderUid || aggregateFolderType) {
823
+ shownSelectionRef.current = selectionKey;
824
+ }
825
+ }, [selectionKey]);
826
+
827
+ // Which listing this is, for the short-lived snapshot of each folder that makes going back to one instant (see
828
+ // `listSnapshots.ts`). A search, an aggregate view and a folder that hasn't resolved have no snapshot.
829
+ const listKey = listSnapshotKey({
830
+ mailboxUid: activeMailboxUid,
831
+ folderUid,
832
+ conversations: preferences.showAsConversations,
833
+ filter: effectiveFilter,
834
+ labels: labelFilterKey,
835
+ sort: serverSortKey,
836
+ });
837
+ const snapshotable = !!folderUid && !isSearching && !aggregateFolderType;
838
+ /** The key of the listing `messages`/`conversations` currently hold - not `listKey` while a new folder's rows are still coming. */
839
+ const shownListKeyRef = useRef<string | null>(null);
840
+ /** A scroll position to put the list back at once its rows are on screen (a snapshot's). */
841
+ const pendingScrollRef = useRef<number | null>(null);
842
+ useLayoutEffect(() => {
843
+ if (pendingScrollRef.current !== null && !loading && scrollContainerRef.current) {
844
+ scrollContainerRef.current.scrollTop = pendingScrollRef.current;
845
+ pendingScrollRef.current = null;
846
+ }
847
+ });
848
+ // Keeps the snapshot of the folder on screen current - rows added by "load more" or live updates, a read message, the selection.
849
+ useEffect(() => {
850
+ if (snapshotable && !loading && shownListKeyRef.current === listKey) {
851
+ writeListSnapshot(listKey, { messages, conversations, hasMore, selectedUid });
852
+ }
853
+ }, [snapshotable, loading, listKey, messages, conversations, hasMore, selectedUid]);
854
+
855
+ // Loads whichever list the current folder, arrangement and search state call for, and resets every
856
+ // piece of per-listing state (selection, paging, select mode) that a previous listing left behind.
857
+ useEffect(() => {
858
+ setSelectedUid(null);
859
+ setOpenThread(null);
860
+ setConversationPatches({});
861
+ setSelectedUids(new Set());
862
+ setSelectedConversationIds(new Set());
863
+ setConversationMessagesById({});
864
+ listedOffsetRef.current = 0;
865
+ compositeCursorRef.current = undefined;
866
+ setHasMore(false);
867
+ setLoadMoreError(null);
868
+ setLoadMoreStalled(false);
869
+ emptyPageStreakRef.current = 0;
870
+ // Every run - search or not - supersedes whatever an earlier run (or a `loadMore()` it started)
871
+ // still has in flight; each async callback below checks this before touching state.
872
+ searchRunIdRef.current += 1;
873
+ const myRunId = searchRunIdRef.current;
874
+ const isCurrentRun = () => searchRunIdRef.current === myRunId;
875
+ // Also invalidates on unmount, so nothing lands after the component is gone. Unconditional: this
876
+ // cleanup only ever runs for the latest run of this effect (React runs it before the next run
877
+ // bumps the id, or on unmount), so the id is always still `myRunId` here.
878
+ const invalidate = () => {
879
+ searchRunIdRef.current += 1;
880
+ };
881
+ // A folder shown a moment ago is put on screen at once and revalidated behind the rows; one that was not shows a skeleton.
882
+ const snapshot = snapshotable ? readListSnapshot(listKey) : undefined;
883
+
884
+ if (!folderUid && !aggregateFolderType) {
885
+ // The shell hasn't resolved this mailbox's folders yet (the render below says so). Listing
886
+ // anything now means a request whose answer is thrown away the moment the Inbox arrives - and
887
+ // for conversations a mailbox-wide grouping pass, the most expensive listing there is.
888
+ setMessages([]);
889
+ setConversations([]);
890
+ setLoading(false);
891
+ return;
892
+ }
893
+ if (aggregateFolderType && mailboxFolders.length === 0) {
894
+ // The same, for a merged view: it has no folder of its own, but it is built from every
895
+ // mailbox's folders, and this effect re-runs the moment they arrive. Listing twice is what
896
+ // that cost before.
897
+ setMessages([]);
898
+ setConversations([]);
899
+ setLoading(true);
900
+ return;
901
+ }
902
+
903
+ if (preferences.showAsConversations) {
904
+ // Conversations stay single-mailbox (not aggregated across mailboxes in this pass) - in
905
+ // aggregate mode this falls back to `activeMailboxUid`, the same mailbox unlock/labels use
906
+ // (always set - `MailShell` only renders this component once at least one mailbox exists).
907
+ // They're scoped to the selected folder (`folderUid`, absent only in aggregate mode), so the
908
+ // conversation list matches the folder the sidebar has selected rather than the whole mailbox.
909
+ if (snapshot) {
910
+ setConversations(snapshot.conversations);
911
+ listedOffsetRef.current = snapshot.conversations.length;
912
+ setHasMore(snapshot.hasMore);
913
+ shownListKeyRef.current = listKey;
914
+ pendingScrollRef.current = snapshot.scrollTop;
915
+ setLoading(false);
916
+ } else {
917
+ setLoading(true);
918
+ }
919
+ setError(null);
920
+ listConversations(activeMailboxUid, conversationParams(0))
921
+ .then((result) => {
922
+ if (isCurrentRun()) {
923
+ shownListKeyRef.current = listKey;
924
+ if (snapshot) {
925
+ // Folded into what is already shown, as a live refresh does, so the reader's place is kept.
926
+ const merged = mergeFirstPage(snapshot.conversations, result, conversationKey, MESSAGE_PAGE_SIZE);
927
+ setConversations(merged.rows);
928
+ listedOffsetRef.current = merged.complete ? result.length : snapshot.conversations.length + merged.added;
929
+ setHasMore(!merged.complete);
930
+ return;
931
+ }
932
+ setConversations(result);
933
+ listedOffsetRef.current = result.length;
934
+ setHasMore(result.length === MESSAGE_PAGE_SIZE);
935
+ }
936
+ })
937
+ .catch((err) => {
938
+ if (isCurrentRun()) {
939
+ setError(err instanceof ApiRequestError ? err.message : "Could not load conversations.");
940
+ }
941
+ })
942
+ .finally(() => {
943
+ if (isCurrentRun()) {
944
+ setLoading(false);
945
+ }
946
+ });
947
+ return invalidate;
948
+ }
949
+
950
+ if (aggregateFolderType) {
951
+ setLoading(true);
952
+ setError(null);
953
+ // hasMore stays false (set above) - see fetchAggregateMessages()'s own pagination scope trim.
954
+ void fetchAggregateMessages(mailboxFolders, aggregateFolderType, effectiveFilter)
955
+ .then((results) => {
956
+ if (isCurrentRun()) {
957
+ setMessages(results);
958
+ }
959
+ })
960
+ .finally(() => {
961
+ if (isCurrentRun()) {
962
+ setLoading(false);
963
+ }
964
+ });
965
+ return invalidate;
966
+ }
967
+
968
+ setLoading(!snapshot);
969
+ setError(null);
970
+
971
+ if (isSearching) {
972
+ setCoverage(undefined);
973
+ setPendingUids(new Set());
974
+ setTier1Done(false);
975
+ setTier2Done(false);
976
+ setTier3Done(false);
977
+ resolvedMessageCacheRef.current = new Map();
978
+ const parsed = parseSearchQuery(searchQuery);
979
+ const unlocked = getUnlockedKeys(mailboxUid!);
980
+ const fingerprint = queryFingerprint(parsed);
981
+
982
+ // Recomputes and re-renders the merged list from whatever tiers have reported so far -
983
+ // called once after Tier 1+2 (interim: unconfirmed Tier 1 metadataOnly hits render as
984
+ // skeletons) and again after Tier 3 (final: anything still unconfirmed is pruned instead -
985
+ // §_Progressive Results_' "Skeletons resolve or disappear"). Bails out via `myRunId` if a
986
+ // newer search pass has since started.
987
+ async function reveal(tier1Hits: SearchResult[], tier2Hits: SearchResult[], tier3Hits: SearchResult[], final: boolean) {
988
+ const capped = capSkeletons(tier1Hits);
989
+ const confirmed = new Set([...tier2Hits, ...tier3Hits].map((r) => r.entityUid));
990
+ const effectiveTier1 = final ? capped.filter((hit) => !hit.metadataOnly || confirmed.has(hit.entityUid)) : capped;
991
+ const merged = mergeSearchResults(effectiveTier1, tier2Hits, tier3Hits);
992
+ const { messages: resolved, snippets: resolvedSnippets } = await resolveHitsToMessages(
993
+ merged,
994
+ resolvedMessageCacheRef.current,
995
+ );
996
+ if (searchRunIdRef.current !== myRunId) {
997
+ return;
998
+ }
999
+ setMessages(resolved);
1000
+ setSnippets(resolvedSnippets);
1001
+ if (final) {
1002
+ setPendingUids(new Set());
1003
+ } else {
1004
+ const pending = new Set<string>();
1005
+ for (const hit of capped) {
1006
+ if (hit.metadataOnly && !confirmed.has(hit.entityUid)) {
1007
+ pending.add(hit.entityUid);
1008
+ }
1009
+ }
1010
+ setPendingUids(pending);
1011
+ }
1012
+ }
1013
+
1014
+ void (async () => {
1015
+ try {
1016
+ const [tier1Page, tier2Page] = await Promise.all([
1017
+ searchMailbox(parsed.text, tier1SearchParams(parsed, undefined, mailboxUid!)),
1018
+ searchLocalIndex(mailboxUid!, parsed, unlocked, MESSAGE_PAGE_SIZE, 0),
1019
+ ]);
1020
+ if (searchRunIdRef.current !== myRunId) {
1021
+ return;
1022
+ }
1023
+ setTier1Done(true);
1024
+ setTier2Done(true);
1025
+ setCoverage(tier2Page.coverage);
1026
+ setLoading(false);
1027
+ await reveal(tier1Page.results, tier2Page.results, [], false);
1028
+
1029
+ const windows = tier3Windows(parsed, tier2Page.coverage, searchAllMail);
1030
+ const cacheKey = tier3CacheKey(mailboxUid!, windows, !!unlocked);
1031
+ let tier3Full = tier3CacheRef.current.get(cacheKey);
1032
+ if (!tier3Full) {
1033
+ tier3Full = await searchTier3Windows(windows, unlocked, mailboxUid!);
1034
+ if (searchRunIdRef.current !== myRunId) {
1035
+ return;
1036
+ }
1037
+ tier3CacheRef.current.set(cacheKey, tier3Full);
1038
+ }
1039
+ const tier3Page = tier3Full.slice(0, MESSAGE_PAGE_SIZE);
1040
+ setTier3Done(true);
1041
+ compositeCursorRef.current = {
1042
+ tier1Cursor: tier1Page.nextCursor,
1043
+ tier2Offset: tier2Page.results.length,
1044
+ tier3Offset: tier3Page.length,
1045
+ tier3Key: cacheKey,
1046
+ fingerprint,
1047
+ };
1048
+ setHasMore(!!tier1Page.nextCursor || tier2Page.hasMore || tier3Page.length < tier3Full.length);
1049
+ await reveal(tier1Page.results, tier2Page.results, tier3Page, true);
1050
+ } catch (err) {
1051
+ if (searchRunIdRef.current === myRunId) {
1052
+ setError(err instanceof ApiRequestError ? err.message : "Search failed.");
1053
+ setLoading(false);
1054
+ }
1055
+ }
1056
+ })();
1057
+ return invalidate;
1058
+ }
1059
+
1060
+ // Set: the guard at the top of this effect returned for a view with neither a folder nor an
1061
+ // aggregate type, and the aggregate branch above returned for the one with an aggregate type.
1062
+ if (snapshot) {
1063
+ setMessages(snapshot.messages);
1064
+ listedOffsetRef.current = snapshot.messages.length;
1065
+ setHasMore(snapshot.hasMore);
1066
+ // The selection the reader left the folder with, if that message is still there.
1067
+ setSelectedUid(snapshot.messages.some((m) => m.uid === snapshot.selectedUid) ? snapshot.selectedUid : null);
1068
+ shownListKeyRef.current = listKey;
1069
+ pendingScrollRef.current = snapshot.scrollTop;
1070
+ }
1071
+ listMessages(folderUid!, listParams)
1072
+ .then((results) => {
1073
+ if (isCurrentRun()) {
1074
+ shownListKeyRef.current = listKey;
1075
+ if (snapshot) {
1076
+ // Folded into what is already shown, as a live refresh does: the reader's place, selection and paged-in
1077
+ // rows stay, and a row they changed since (a higher version) is not put back.
1078
+ const merged = mergeFirstPage(snapshot.messages, results, messageUid, MESSAGE_PAGE_SIZE, (current, next) =>
1079
+ current.version >= next.version ? current : next,
1080
+ );
1081
+ setMessages(merged.rows);
1082
+ listedOffsetRef.current = merged.complete ? results.length : snapshot.messages.length + merged.added;
1083
+ setHasMore(!merged.complete);
1084
+ return;
1085
+ }
1086
+ setMessages(results);
1087
+ listedOffsetRef.current = results.length;
1088
+ setHasMore(results.length === MESSAGE_PAGE_SIZE);
1089
+ }
1090
+ })
1091
+ .catch((err) => {
1092
+ if (isCurrentRun()) {
1093
+ setError(err instanceof ApiRequestError ? err.message : "Could not load messages.");
1094
+ }
1095
+ })
1096
+ .finally(() => {
1097
+ if (isCurrentRun()) {
1098
+ setLoading(false);
1099
+ }
1100
+ });
1101
+ return invalidate;
1102
+ // `unlockRefresh`/`searchAllMail` are dependencies solely so `handleUnlockSearch()`/"Search all
1103
+ // mail" can force this effect to re-run the search above - Tier 3 (encrypted) results silently
1104
+ // contribute nothing without unlocked keys, so this is what actually makes them appear once the
1105
+ // user unlocks, and what makes "Search all mail" actually remove Tier 3's coverage bound. Neither
1106
+ // has any effect on the non-search branch below; re-running it with identical inputs just
1107
+ // re-fetches the same page.
1108
+ // `refreshKey` is a dependency for the same reason: a failed bulk action bumps it to refetch,
1109
+ // since a bulk update applies until its first rejection rather than all-or-nothing.
1110
+ }, [
1111
+ preferences.showAsConversations,
1112
+ serverSortKey,
1113
+ effectiveFilter,
1114
+ labelFilterKey,
1115
+ refreshKey,
1116
+ folderUid,
1117
+ mailboxUid,
1118
+ isSearching,
1119
+ searchQuery,
1120
+ unlockRefresh,
1121
+ searchAllMail,
1122
+ aggregateFolderType,
1123
+ mailboxFolders,
1124
+ activeMailboxUid,
1125
+ ]);
1126
+
1127
+ // New mail without a reload. `live` is bumped by a push event, a reconnect, the safety-net poll or the tab coming back (see
1128
+ // `useMailLiveUpdates()`); this then quietly refetches the first page of whatever is listed and folds it in - unlike the
1129
+ // effect above it resets nothing: not the selection, the open thread, select mode, the scroll position or the rows
1130
+ // already paged in, and nothing it fetches is marked read. It stands aside for a search (whose rows aren't a folder's),
1131
+ // a listing still loading and a "load more" in flight, and for events about folders the list isn't showing - a
1132
+ // conversation list, which can span folders, refreshes for any. Any failure is silent: the next tick tries again.
1133
+ const liveRunRef = useRef(0);
1134
+ useEffect(() => {
1135
+ if (live.tick === 0 || isSearching || loading || loadMoreInFlightRef.current || (!folderUid && !aggregateFolderType)) {
1136
+ return;
1137
+ }
1138
+ if (!preferences.showAsConversations && live.folderUids) {
1139
+ const shown = new Set(
1140
+ aggregateFolderType
1141
+ ? mailboxFolders.flatMap((entry) => entry.folders.filter((f) => f.type === aggregateFolderType).map((f) => f.uid))
1142
+ : [folderUid!],
1143
+ );
1144
+ if (![...live.folderUids].some((uid) => shown.has(uid))) {
1145
+ return;
1146
+ }
1147
+ }
1148
+ // Superseded by a newer refresh, or by any reload of the list itself (which bumps the search run id).
1149
+ const listRun = searchRunIdRef.current;
1150
+ const myRun = ++liveRunRef.current;
1151
+ const isCurrent = () => searchRunIdRef.current === listRun && liveRunRef.current === myRun;
1152
+ void (async () => {
1153
+ try {
1154
+ if (preferences.showAsConversations) {
1155
+ const fresh = await listConversations(activeMailboxUid, conversationParams(0));
1156
+ if (!isCurrent()) {
1157
+ return;
1158
+ }
1159
+ const merged = mergeFirstPage(conversationsRef.current, fresh, conversationKey, MESSAGE_PAGE_SIZE);
1160
+ setConversations(merged.rows);
1161
+ listedOffsetRef.current = merged.complete ? fresh.length : listedOffsetRef.current + merged.added;
1162
+ setHasMore(!merged.complete);
1163
+ } else if (aggregateFolderType) {
1164
+ // No paging here (see `fetchAggregateMessages()`): the fresh merged first pages are the list.
1165
+ const fresh = await fetchAggregateMessages(mailboxFolders, aggregateFolderType, effectiveFilter);
1166
+ if (isCurrent()) {
1167
+ setMessages(fresh);
1168
+ }
1169
+ } else {
1170
+ const fresh = await listMessages(folderUid!, listParams);
1171
+ if (!isCurrent()) {
1172
+ return;
1173
+ }
1174
+ // A row the reader has just changed (a higher version) is not put back by a fetch that began before.
1175
+ // Equal versions are the same server state, so the row on screen - which may carry an optimistic read/unread
1176
+ // flip the server has not answered yet - wins too.
1177
+ const merged = mergeFirstPage(messagesRef.current, fresh, messageUid, MESSAGE_PAGE_SIZE, (current, next) =>
1178
+ current.version >= next.version ? current : next,
1179
+ );
1180
+ setMessages(merged.rows);
1181
+ listedOffsetRef.current = merged.complete ? fresh.length : listedOffsetRef.current + merged.added;
1182
+ setHasMore(!merged.complete);
1183
+ }
1184
+ } catch {
1185
+ // Quiet by design - see above.
1186
+ }
1187
+ })();
1188
+ }, [live.tick]);
1189
+
1190
+ function handleSearchAllMail() {
1191
+ setSearchAllMailKey(searchAllMailScope);
1192
+ }
1193
+
1194
+ const loadMore = useCallback(async () => {
1195
+ const parsed = parseSearchQuery(searchQuery);
1196
+ const fingerprint = queryFingerprint(parsed);
1197
+ // While searching, a load-more continues from this query's own cursor - absent until its first page
1198
+ // has fully finished (the ref may still hold an earlier query's), in which case there's nowhere to
1199
+ // continue from yet.
1200
+ const searchCursor = decodeCursor(compositeCursorRef.current, fingerprint);
1201
+ if (
1202
+ loadMoreInFlightRef.current ||
1203
+ !hasMore ||
1204
+ loading ||
1205
+ (!preferences.showAsConversations && !folderUid) ||
1206
+ (isSearching && !searchCursor)
1207
+ ) {
1208
+ return;
1209
+ }
1210
+ // A ref, not `loadingMore` state: the observer and the continuation effect below can both call in the
1211
+ // same tick, each closing over a render where `loadingMore` was still false.
1212
+ loadMoreInFlightRef.current = true;
1213
+ setLoadMoreError(null);
1214
+ setLoadMoreStalled(false);
1215
+ setLoadingMore(true);
1216
+ /** Records whether a landed page added rows, and whether the continuation effect should keep going. */
1217
+ const notePageLanded = (addedRows: boolean, moreRemain: boolean) => {
1218
+ if (addedRows) {
1219
+ emptyPageStreakRef.current = 0;
1220
+ setAppendedPageCount((n) => n + 1);
1221
+ } else if (moreRemain) {
1222
+ emptyPageStreakRef.current += 1;
1223
+ if (emptyPageStreakRef.current <= MAX_EMPTY_PAGE_CONTINUATIONS) {
1224
+ setAppendedPageCount((n) => n + 1);
1225
+ } else {
1226
+ emptyPageStreakRef.current = 0;
1227
+ setLoadMoreStalled(true);
1228
+ }
1229
+ }
1230
+ };
1231
+ // A query/folder/view change while this page is in flight bumps the run id (see the effect above) -
1232
+ // its rows then belong to a list that's no longer on screen and must not be appended to the new one.
1233
+ const myRunId = searchRunIdRef.current;
1234
+ const isCurrentRun = () => searchRunIdRef.current === myRunId;
1235
+ try {
1236
+ if (preferences.showAsConversations) {
1237
+ const page = Math.floor(listedOffsetRef.current / MESSAGE_PAGE_SIZE);
1238
+ const more = await listConversations(activeMailboxUid, conversationParams(page));
1239
+ if (!isCurrentRun()) {
1240
+ return;
1241
+ }
1242
+ const addedRows = hasUnseenRows(conversationsRef.current, more, conversationKey);
1243
+ setConversations((prev) => appendUnseenRows(prev, more, conversationKey));
1244
+ setHasMore(more.length === MESSAGE_PAGE_SIZE);
1245
+ listedOffsetRef.current = page * MESSAGE_PAGE_SIZE + more.length;
1246
+ notePageLanded(addedRows, more.length === MESSAGE_PAGE_SIZE);
1247
+ } else if (isSearching) {
1248
+ const unlocked = getUnlockedKeys(mailboxUid!);
1249
+ const cursor = searchCursor!;
1250
+
1251
+ const [tier1Page, tier2Page] = await Promise.all([
1252
+ searchMailbox(parsed.text, tier1SearchParams(parsed, cursor.tier1Cursor, mailboxUid!)),
1253
+ searchLocalIndex(mailboxUid!, parsed, unlocked, MESSAGE_PAGE_SIZE, cursor.tier2Offset),
1254
+ ]);
1255
+ // The first page cached this pass under `tier3Key` before it created the cursor.
1256
+ const tier3Full = tier3CacheRef.current.get(cursor.tier3Key)!;
1257
+ const tier3Offset = cursor.tier3Offset;
1258
+ const tier3Page = tier3Full.slice(tier3Offset, tier3Offset + MESSAGE_PAGE_SIZE);
1259
+
1260
+ // Unlike the fresh-search pass above, a load-more page is resolved and appended in one
1261
+ // shot rather than progressively revealed - rows already on screen shouldn't reorder or
1262
+ // grow skeletons out from under a reader who has since scrolled past them. Any Tier 1
1263
+ // metadataOnly hit this page that neither Tier 2 nor Tier 3 (both already awaited above)
1264
+ // confirms simply keeps showing its existing placeholder text rather than a live skeleton
1265
+ // - a deliberate, documented scope trim of progressive reveal to the first page only.
1266
+ const merged = mergeSearchResults(capSkeletons(tier1Page.results), tier2Page.results, tier3Page);
1267
+ const { messages: more, snippets: moreSnippets } = await resolveHitsToMessages(merged, resolvedMessageCacheRef.current);
1268
+ if (!isCurrentRun()) {
1269
+ return;
1270
+ }
1271
+ const addedRows = hasUnseenRows(messagesRef.current, more, messageUid);
1272
+ setMessages((prev) => appendUnseenRows(prev, more, messageUid));
1273
+ setSnippets((prev) => ({ ...prev, ...moreSnippets }));
1274
+
1275
+ const nextTier3Offset = tier3Offset + tier3Page.length;
1276
+ compositeCursorRef.current = {
1277
+ tier1Cursor: tier1Page.nextCursor,
1278
+ tier2Offset: cursor.tier2Offset + tier2Page.results.length,
1279
+ tier3Offset: nextTier3Offset,
1280
+ tier3Key: cursor.tier3Key,
1281
+ fingerprint,
1282
+ };
1283
+ const moreRemain = !!tier1Page.nextCursor || tier2Page.hasMore || nextTier3Offset < tier3Full.length;
1284
+ setHasMore(moreRemain);
1285
+ notePageLanded(addedRows, moreRemain);
1286
+ } else {
1287
+ // The page containing the first message not fetched yet. After a local removal that offset is
1288
+ // no longer a page boundary, so this page overlaps rows already shown - `appendUnseenRows()`
1289
+ // drops those - rather than skipping the message that shifted back across the boundary.
1290
+ const page = Math.floor(listedOffsetRef.current / MESSAGE_PAGE_SIZE);
1291
+ const more = await listMessages(folderUid!, { ...listParams, page });
1292
+ if (!isCurrentRun()) {
1293
+ return;
1294
+ }
1295
+ const addedRows = hasUnseenRows(messagesRef.current, more, messageUid);
1296
+ setMessages((prev) => appendUnseenRows(prev, more, messageUid));
1297
+ setHasMore(more.length === MESSAGE_PAGE_SIZE);
1298
+ listedOffsetRef.current = page * MESSAGE_PAGE_SIZE + more.length;
1299
+ notePageLanded(addedRows, more.length === MESSAGE_PAGE_SIZE);
1300
+ }
1301
+ } catch (err) {
1302
+ // Shown next to the sentinel with a Retry button - never auto-retried (see the continuation
1303
+ // effect below), so a failing server isn't hammered while the sentinel stays in view.
1304
+ if (isCurrentRun()) {
1305
+ setLoadMoreError(err instanceof ApiRequestError ? err.message : "Could not load more messages.");
1306
+ }
1307
+ } finally {
1308
+ loadMoreInFlightRef.current = false;
1309
+ setLoadingMore(false);
1310
+ }
1311
+ }, [
1312
+ hasMore,
1313
+ loading,
1314
+ preferences.showAsConversations,
1315
+ serverSortKey,
1316
+ effectiveFilter,
1317
+ labelFilterKey,
1318
+ folderUid,
1319
+ isSearching,
1320
+ searchQuery,
1321
+ mailboxUid,
1322
+ activeMailboxUid,
1323
+ ]);
1324
+
1325
+ // Always calls the latest `loadMore` closure so the effect below doesn't need `loadMore` itself in its
1326
+ // dependency array (it changes on every keystroke/page load, which would otherwise mean nothing here).
1327
+ const loadMoreRef = useRef(loadMore);
1328
+ loadMoreRef.current = loadMore;
1329
+
1330
+ // Keyed on the sentinel node itself (see `sentinel`'s own comment): it unmounts whenever the list shows
1331
+ // "Loading..." and remounts afterwards, so an observer attached once to an earlier node would watch a
1332
+ // detached element forever. Only ever rendered in "By date" mode, so no view-mode check is needed.
1333
+ useEffect(() => {
1334
+ if (!sentinel) {
1335
+ return;
1336
+ }
1337
+ const observer = new IntersectionObserver(
1338
+ (entries) => {
1339
+ if (entries.some((entry) => entry.isIntersecting) && !loadMoreErrorRef.current) {
1340
+ void loadMoreRef.current();
1341
+ }
1342
+ },
1343
+ { root: scrollContainerRef.current, rootMargin: `${LOAD_MORE_ROOT_MARGIN_PX}px` },
1344
+ );
1345
+ observer.observe(sentinel);
1346
+ return () => observer.disconnect();
1347
+ }, [sentinel]);
1348
+
1349
+ // An observer only reports *changes* - a sentinel still in view after a page lands (the new rows didn't
1350
+ // push it out of view, e.g. the Focused/Other filter hid every one of them) never reports again, so
1351
+ // keep loading while it's still in view. Only after a page that appended rows, or a full page of rows
1352
+ // already shown (bounded - see `emptyPageStreakRef`), never after a failure, and only when the sentinel's
1353
+ // real geometry says it's still in view (the observer's last report may predate the rows that just landed).
1354
+ useEffect(() => {
1355
+ if (appendedPageCount === 0) {
1356
+ return;
1357
+ }
1358
+ // The scroll container is always mounted whenever a sentinel is (the sentinel lives inside it).
1359
+ if (sentinel && isWithinLoadMoreRange(sentinel, scrollContainerRef.current!)) {
1360
+ void loadMoreRef.current();
1361
+ }
1362
+ }, [appendedPageCount]);
1363
+
1364
+ /**
1365
+ * Replaces one listed row - and, in the conversation list, the opened message and the child row
1366
+ * standing for it - with a newer copy the reading pane just produced.
1367
+ *
1368
+ * A conversation's *parent* row has no copy to replace: it is a summary of the whole thread, and its
1369
+ * "2 unread" chip and bold styling come from a count the server worked out when the list was fetched.
1370
+ * So when a message changes read state (`previous` and `updated` differ in it - the optimistic copy of a message just
1371
+ * read, or its revert), that count moves by one here - otherwise a conversation kept claiming unread mail the reader
1372
+ * had just read, until the whole list was reloaded.
1373
+ */
1374
+ function patchListedMessage(updated: Message, previous?: Message) {
1375
+ setMessages((prev) => prev.map((m) => (m.uid === updated.uid ? updated : m)));
1376
+ // `ConversationList` fetched its own copy of this message when the thread was expanded; hand it the
1377
+ // newer one so the child row doesn't keep showing a stale read/flag state.
1378
+ setConversationPatches((prev) => ({ ...prev, [updated.uid]: updated }));
1379
+ const unreadChange = previous ? Number(isUnread(updated)) - Number(isUnread(previous)) : 0;
1380
+ if (unreadChange !== 0) {
1381
+ setConversations((prev) =>
1382
+ prev.map((conversation) =>
1383
+ conversation.messageUids.includes(updated.uid)
1384
+ ? { ...conversation, unreadCount: Math.max(0, conversation.unreadCount + unreadChange) }
1385
+ : conversation,
1386
+ ),
1387
+ );
1388
+ }
1389
+ }
1390
+
1391
+ function removeListedMessages(uids: Set<string>) {
1392
+ const selectedIndex = messagesRef.current.findIndex((m) => m.uid === selectedUid);
1393
+ if (selectedUid && uids.has(selectedUid) && selectedIndex !== -1) {
1394
+ removedAnchorRef.current = selectedIndex;
1395
+ }
1396
+ setMessages((prev) => prev.filter((m) => !uids.has(m.uid)));
1397
+ listedOffsetRef.current = Math.max(0, listedOffsetRef.current - uids.size);
1398
+ setSelectedUid((prev) => (prev && uids.has(prev) ? null : prev));
1399
+ }
1400
+
1401
+ function removeListedMessage(uid: string) {
1402
+ removeListedMessages(new Set([uid]));
1403
+ }
1404
+
1405
+ // The conversation list opens a whole thread in `ConversationThreadPane`, which loads and marks read
1406
+ // its own messages; only the flat list feeds the single-message pane below.
1407
+ const selected = preferences.showAsConversations ? null : (messages.find((m) => m.uid === selectedUid) ?? null);
1408
+ const attachments = useMessageAttachments(selected);
1409
+ useMarkMessageRead(selected, patchListedMessage);
1410
+ // Search results can span every folder in the mailbox, not just the one selected in the sidebar - a
1411
+ // selected message's own folderUid is the only reliable source for its actual folder type once
1412
+ // searching (outside search, every message in `messages` already comes from `folderUid` itself, so
1413
+ // this falls back to the sidebar selection unchanged). Aggregate views span every *mailbox* too, so
1414
+ // the folder list consulted is the selected message's own mailbox's, not the shell's ambient one. A
1415
+ // conversation spans folders for the same reason (an Inbox message and the Sent Items copy of its reply).
1416
+ const spansFolders = isSearching || !!aggregateFolderType || preferences.showAsConversations;
1417
+ const selectedFolderUid = spansFolders ? (selected?.folderUid ?? folderUid) : folderUid;
1418
+ const selectedMailboxUid = spansFolders ? (selected?.mailboxUid ?? activeMailboxUid) : mailboxUid;
1419
+ const folders = mailboxFolders.find((mf) => mf.mailbox.uid === selectedMailboxUid)?.folders ?? [];
1420
+ const isSentItems = folders.find((f) => f.uid === selectedFolderUid)?.type === "sent_items";
1421
+ const isOutbox = folders.find((f) => f.uid === selectedFolderUid)?.type === "outbox";
1422
+ const draftsFolderUid = folders.find((f) => f.type === "drafts")?.uid;
1423
+
1424
+ /** What a row actually shows as its subject - the decrypted one where this device recovered it, a
1425
+ * readable stand-in for an encrypted one it hasn't, and a placeholder for a message with no subject. */
1426
+ function rowSubject(message: Message): string {
1427
+ return (
1428
+ decryptedRows[message.uid]?.subject ||
1429
+ (message.subject === ENCRYPTED_SUBJECT_PLACEHOLDER ? "Encrypted message" : message.subject) ||
1430
+ "(no subject)"
1431
+ );
1432
+ }
1433
+
1434
+ /** The conversation list's selection as plain messages: every message of every ticked conversation
1435
+ * that is in the folder being listed. A conversation spans folders (an Inbox message and the Sent
1436
+ * Items copy of its reply), and the list only ever showed this folder's half of it, so a bulk action
1437
+ * from here must not reach into the other folders' copies either. */
1438
+ const selectedConversationMessages = [...selectedConversationIds].flatMap((id) =>
1439
+ (conversationMessagesById[id] ?? []).filter((m) => !folderUid || m.folderUid === folderUid),
1440
+ );
1441
+ const selectedMessages = preferences.showAsConversations
1442
+ ? selectedConversationMessages
1443
+ : messages.filter((m) => selectedUids.has(m.uid));
1444
+ /** How many rows the list is actually showing - conversations or messages, whichever it lists. What the
1445
+ * Select toggle is enabled by: there is nothing to select in a list with no rows. */
1446
+ const listedRowCount = preferences.showAsConversations ? conversations.length : messages.length;
1447
+ /** The conversation rows in the order the reader arranged them. The endpoint takes no sort parameters
1448
+ * of its own (it pages by latest activity), so the arrangement is applied here, to the rows fetched so
1449
+ * far - which the Sort menu says on screen. `conversations` itself stays in the order the pages
1450
+ * arrived, so paging keeps appending to the same accumulated set. */
1451
+ const listedConversations = sortConversations(conversations, preferences.sortBy, preferences.sortOrder);
1452
+
1453
+ function leaveSelectMode() {
1454
+ setSelectMode(false);
1455
+ setSelectedUids(new Set());
1456
+ setSelectedConversationIds(new Set());
1457
+ setBulkError(null);
1458
+ }
1459
+
1460
+ function toggleSelected(uid: string) {
1461
+ setSelectedUids((prev) => {
1462
+ const next = new Set(prev);
1463
+ if (next.has(uid)) {
1464
+ next.delete(uid);
1465
+ } else {
1466
+ next.add(uid);
1467
+ }
1468
+ return next;
1469
+ });
1470
+ }
1471
+
1472
+ /** Loads (once) the messages behind each of `ids`, so a ticked conversation resolves to the messages
1473
+ * every bulk action below acts on. If any of them fails to load, none of that batch stays ticked and
1474
+ * the bar says why - better than acting on the part of a selection that happened to arrive. */
1475
+ async function resolveConversations(ids: string[]) {
1476
+ const missing = ids.filter((id) => !conversationMessagesById[id]);
1477
+ if (missing.length === 0) {
1478
+ return;
1479
+ }
1480
+ setResolvingSelection((n) => n + 1);
1481
+ try {
1482
+ const loaded = await Promise.all(
1483
+ missing.map(async (id) => [id, await listConversationMessages(activeMailboxUid, id)] as const),
1484
+ );
1485
+ setConversationMessagesById((prev) => ({ ...prev, ...Object.fromEntries(loaded) }));
1486
+ } catch (err) {
1487
+ setBulkError(
1488
+ err instanceof ApiRequestError ? err.message : "Could not load the messages in one of those conversations.",
1489
+ );
1490
+ setSelectedConversationIds((prev) => {
1491
+ const next = new Set(prev);
1492
+ for (const id of missing) {
1493
+ next.delete(id);
1494
+ }
1495
+ return next;
1496
+ });
1497
+ } finally {
1498
+ setResolvingSelection((n) => n - 1);
1499
+ }
1500
+ }
1501
+
1502
+ function toggleConversationSelected(conversation: ConversationSummary) {
1503
+ const id = conversation.conversationId;
1504
+ const ticking = !selectedConversationIds.has(id);
1505
+ setSelectedConversationIds((prev) => {
1506
+ const next = new Set(prev);
1507
+ if (ticking) {
1508
+ next.add(id);
1509
+ } else {
1510
+ next.delete(id);
1511
+ }
1512
+ return next;
1513
+ });
1514
+ if (ticking) {
1515
+ void resolveConversations([id]);
1516
+ }
1517
+ }
1518
+
1519
+ function selectAllConversations() {
1520
+ const ids = conversations.map(conversationKey);
1521
+ setSelectedConversationIds(new Set(ids));
1522
+ void resolveConversations(ids);
1523
+ }
1524
+
1525
+ /**
1526
+ * Runs one bulk action over the current selection, then either patches the affected rows in place or
1527
+ * drops them (a move takes them out of the folder being listed).
1528
+ *
1529
+ * A bulk update is applied element by element server-side and stops at its first rejection, so a
1530
+ * failure leaves an unknown prefix of the selection already changed (see `bulkUpdateMessages()`) -
1531
+ * which is why a failure reloads the list rather than trying to reconcile it, and says so.
1532
+ *
1533
+ * `chosen` is the selection bar's ticked messages unless the caller (a keyboard shortcut acting on the one open message or conversation)
1534
+ * names its own. Resolves whether it succeeded.
1535
+ */
1536
+ async function runBulkAction(
1537
+ action: (chosen: Message[]) => Promise<Message[]>,
1538
+ removesRows: boolean,
1539
+ chosen: Message[] = selectedMessages,
1540
+ ): Promise<boolean> {
1541
+ setBulkBusy(true);
1542
+ setBulkError(null);
1543
+ try {
1544
+ const updated = await action(chosen);
1545
+ if (removesRows) {
1546
+ // A move (Delete, Archive, Report junk, Move to): the source folders' badges go down, the target's up. Reading
1547
+ // and unreading are tracked by `setReadStateMany()` itself, as they happen.
1548
+ const movedByUid = new Map(updated.map((m) => [m.uid, m]));
1549
+ for (const before of chosen) {
1550
+ const after = movedByUid.get(before.uid);
1551
+ if (after) {
1552
+ trackMessageChange(before, after).settle();
1553
+ }
1554
+ }
1555
+ }
1556
+ if (preferences.showAsConversations) {
1557
+ // A conversation row is a summary of its messages - its count, unread count, participants
1558
+ // and preview all move when a bulk action changes or empties part of it - so the list is
1559
+ // reloaded rather than patched row by row.
1560
+ setSelectedConversationIds(new Set());
1561
+ setConversationMessagesById({});
1562
+ setRefreshKey((n) => n + 1);
1563
+ } else if (removesRows) {
1564
+ removeListedMessages(new Set(chosen.map((m) => m.uid)));
1565
+ } else {
1566
+ const byUid = new Map(updated.map((m) => [m.uid, m]));
1567
+ setMessages((prev) => prev.map((m) => byUid.get(m.uid) ?? m));
1568
+ }
1569
+ setSelectedUids(new Set());
1570
+ return true;
1571
+ } catch (err) {
1572
+ setBulkError(
1573
+ `${err instanceof ApiRequestError ? err.message : "Those messages couldn't all be updated."} Some of them may already have changed, so the list has been reloaded.`,
1574
+ );
1575
+ setSelectedUids(new Set());
1576
+ setSelectedConversationIds(new Set());
1577
+ setConversationMessagesById({});
1578
+ setRefreshKey((n) => n + 1);
1579
+ return false;
1580
+ } finally {
1581
+ setBulkBusy(false);
1582
+ }
1583
+ }
1584
+
1585
+ /** Archive has no folder to move into until the mailbox has one: the server creates it lazily on the
1586
+ * first single-message archive, so that call both creates the folder and archives the first message,
1587
+ * and the rest of the selection is then moved into the folder it reports. */
1588
+ async function bulkArchive(chosen: Message[]): Promise<Message[]> {
1589
+ const archiveFolderUid = currentFolders.find((f) => f.type === "archive")?.uid;
1590
+ if (archiveFolderUid) {
1591
+ return moveMessages(chosen, archiveFolderUid);
1592
+ }
1593
+ const first = await archiveMessage(chosen[0].uid);
1594
+ const rest = chosen.slice(1);
1595
+ return rest.length === 0 ? [first] : [first, ...(await moveMessages(rest, first.folderUid))];
1596
+ }
1597
+
1598
+ /**
1599
+ * This mailbox's folder of `type`, created on demand. A mailbox is provisioned with only the folders it
1600
+ * has needed so far, so Deleted Items and Junk may genuinely not exist the first time a selection is
1601
+ * deleted or reported - and unlike Archive, neither has a server-side lazy-create route to go through.
1602
+ *
1603
+ * A folder created here isn't in `mailboxFolders` (the shell fetched that once), so it's remembered per
1604
+ * mailbox and type until the page reloads; otherwise a second Delete would create a second folder.
1605
+ */
1606
+ async function resolveFolderOfType(type: Folder["type"], name: string): Promise<string> {
1607
+ const key = `${activeMailboxUid}:${type}`;
1608
+ const known = currentFolders.find((f) => f.type === type)?.uid ?? lazyFoldersRef.current.get(key);
1609
+ if (known) {
1610
+ return known;
1611
+ }
1612
+ const created = await createFolder({ mailboxUid: activeMailboxUid, name, type });
1613
+ lazyFoldersRef.current.set(key, created.uid);
1614
+ return created.uid;
1615
+ }
1616
+
1617
+ /**
1618
+ * Sets every selected message's labels in one bulk update: each ends up with `labelUids`, plus the
1619
+ * ones left partially applied (`keepPartial`) that it already had, plus any label this mailbox no
1620
+ * longer defines - a label the menu couldn't show isn't one the reader chose to remove.
1621
+ *
1622
+ * `bulkUpdateMessages()` rather than `setMessagesLabels()`, which is its one-list-for-everyone special
1623
+ * case: with a partially-applied row each message keeps a *different* list.
1624
+ */
1625
+ function applyLabelsToSelection(labelUids: string[], keepPartial: string[]) {
1626
+ void runBulkAction(
1627
+ (chosen) =>
1628
+ bulkUpdateMessages(
1629
+ chosen.map((message) => {
1630
+ const kept = (message.labelUids ?? []).filter(
1631
+ (uid) => keepPartial.includes(uid) || !mailboxLabels.some((label) => label.uid === uid),
1632
+ );
1633
+ return { uid: message.uid, version: message.version, labelUids: [...new Set([...labelUids, ...kept])] };
1634
+ }),
1635
+ ),
1636
+ false,
1637
+ );
1638
+ }
1639
+
1640
+ function moveSelectionToType(type: Folder["type"], name: string, chosen?: Message[]) {
1641
+ return runBulkAction(async (moving) => moveMessages(moving, await resolveFolderOfType(type, name)), true, chosen);
1642
+ }
1643
+
1644
+ const loadMoreStatus = loadingMore ? (
1645
+ "Loading more\u2026"
1646
+ ) : loadMoreError ? (
1647
+ <span className="inline-flex items-center gap-2">
1648
+ <span role="alert" className="text-danger">
1649
+ {loadMoreError}
1650
+ </span>
1651
+ <button type="button" onClick={() => void loadMoreRef.current()} className="text-primary-dark hover:underline font-medium">
1652
+ Retry
1653
+ </button>
1654
+ </span>
1655
+ ) : loadMoreStalled ? (
1656
+ <button type="button" onClick={() => void loadMoreRef.current()} className="text-primary-dark hover:underline font-medium">
1657
+ Load more
1658
+ </button>
1659
+ ) : null;
1660
+
1661
+ function handleSelect(message: Message) {
1662
+ if (selectMode) {
1663
+ toggleSelected(message.uid);
1664
+ return;
1665
+ }
1666
+ if (isMobile) {
1667
+ navigate(`/messages/${encodeURIComponent(message.uid)}`);
1668
+ return;
1669
+ }
1670
+ removedAnchorRef.current = null;
1671
+ setSelectedUid(message.uid);
1672
+ }
1673
+
1674
+ /** Opens a conversation in the reading pane, positioned at one of its messages: the one a child row
1675
+ * stands for, or the latest for a parent row. The thread pane loads the thread itself. */
1676
+ function handleOpenConversation(conversation: ConversationSummary, uid: string) {
1677
+ if (selectMode) {
1678
+ // Same rule as `handleSelect()` for a message row: while selecting, a row's own button ticks
1679
+ // the row rather than opening it.
1680
+ toggleConversationSelected(conversation);
1681
+ return;
1682
+ }
1683
+ if (isMobile) {
1684
+ // No dedicated mobile thread route yet - the existing single-message detail route already
1685
+ // handles any message uid regardless of conversation grouping.
1686
+ navigate(`/messages/${encodeURIComponent(uid)}`);
1687
+ return;
1688
+ }
1689
+ removedAnchorRef.current = null;
1690
+ setSelectedUid(uid);
1691
+ setOpenThread({ conversation, uid });
1692
+ }
1693
+
1694
+ // ---- Keyboard shortcuts (see `shared/keyboard`). Each is registered only while this view can do it, and calls what the toolbar and
1695
+ // ---- the selection bar call: the same bulk-action path (`runBulkAction()` - so the same optimistic badge tracking, the same rollback,
1696
+ // ---- the same lazily created Deleted Items folder), never a second implementation. Reply, Reply all, Forward, Archive and Move to are
1697
+ // ---- registered by the reading pane itself (`MessageDetailPane`'s `shortcuts`), which owns those handlers.
1698
+ const inConversations = preferences.showAsConversations;
1699
+ /** The selection bar isn't offered in the aggregate view (its rows belong to several mailboxes), and neither are these. */
1700
+ const keyboardActions = !aggregateFolderType;
1701
+ /** What the keyboard acts on exists: the ticked rows in select mode, else the message (or conversation) open in the reading pane. */
1702
+ const keyboardTargetExists = selectMode ? selectedMessages.length > 0 : inConversations ? openThread !== null : selected !== null;
1703
+ const rowCount = inConversations ? listedConversations.length : messages.length;
1704
+ const canMoveSelection = !selectMode && !isMobile && !loading && rowCount > 0;
1705
+
1706
+ function folderTypeOf(folderUidOfMessage: string): Folder["type"] | undefined {
1707
+ return currentFolders.find((f) => f.uid === folderUidOfMessage)?.type;
1708
+ }
1709
+
1710
+ /** Moves the keyboard's focus to a row - and scrolls it into view - once the selection has moved to it. */
1711
+ function focusRow(uid: string) {
1712
+ // Only called from a key press, when the list is on screen.
1713
+ const row = [...scrollContainerRef.current!.querySelectorAll<HTMLElement>("[data-message-uid]")].find(
1714
+ (element) => element.getAttribute("data-message-uid") === uid,
1715
+ );
1716
+ row?.scrollIntoView({ block: "nearest" });
1717
+ row?.querySelector<HTMLElement>("[data-row-open]")?.focus({ preventScroll: true });
1718
+ }
1719
+
1720
+ /** The index of the selected row: the open message's, or the open conversation's; -1 with nothing selected. */
1721
+ function selectedRowIndex(): number {
1722
+ if (inConversations) {
1723
+ return openThread ? listedConversations.findIndex((c) => c.conversationId === openThread.conversation.conversationId) : -1;
1724
+ }
1725
+ return messages.findIndex((m) => m.uid === selectedUid);
1726
+ }
1727
+
1728
+ function selectRow(index: number) {
1729
+ if (inConversations) {
1730
+ const conversation = listedConversations[index];
1731
+ handleOpenConversation(conversation, conversation.latestMessageUid);
1732
+ focusRow(conversation.latestMessageUid);
1733
+ } else {
1734
+ const message = messages[index];
1735
+ handleSelect(message);
1736
+ focusRow(message.uid);
1737
+ }
1738
+ }
1739
+
1740
+ function selectNeighbour(step: 1 | -1) {
1741
+ const current = selectedRowIndex();
1742
+ // After the selected message left the list (deleted, archived) the next row is the one that slid into its place.
1743
+ const anchor = removedAnchorRef.current;
1744
+ const target = current === -1 && anchor !== null ? (step === 1 ? anchor : anchor - 1) : current + step;
1745
+ selectRow(Math.min(rowCount - 1, Math.max(0, target)));
1746
+ }
1747
+
1748
+ function selectNextUnread(step: 1 | -1) {
1749
+ const isRowUnread = (index: number) => (inConversations ? listedConversations[index].unreadCount > 0 : isUnread(messages[index]));
1750
+ for (let index = selectedRowIndex() + step; index >= 0 && index < rowCount; index += step) {
1751
+ if (isRowUnread(index)) {
1752
+ selectRow(index);
1753
+ return;
1754
+ }
1755
+ }
1756
+ }
1757
+
1758
+ /** The messages of the open conversation that are in the folder being listed - fetched (once) like a ticked conversation's. */
1759
+ async function loadOpenConversation(conversation: ConversationSummary): Promise<Message[]> {
1760
+ const id = conversation.conversationId;
1761
+ let all = conversationMessagesById[id];
1762
+ if (!all) {
1763
+ all = await listConversationMessages(activeMailboxUid, id);
1764
+ const loaded = all;
1765
+ setConversationMessagesById((prev) => ({ ...prev, [id]: loaded }));
1766
+ }
1767
+ return all.filter((m) => !folderUid || m.folderUid === folderUid);
1768
+ }
1769
+
1770
+ /**
1771
+ * Runs a bulk action on what the keyboard acts on - the ticked rows in select mode, else the open message or conversation - keeping only
1772
+ * the messages `applies` accepts (Delete leaves out what is already in Deleted Items, Mark read what is already read: nothing to do
1773
+ * then). Held while another bulk action is on the wire, like the bar's buttons. Closes the open thread after a move away from it.
1774
+ */
1775
+ async function runOnKeyboardTargets(
1776
+ action: (chosen: Message[]) => Promise<Message[]>,
1777
+ removesRows: boolean,
1778
+ applies: (message: Message) => boolean = () => true,
1779
+ ) {
1780
+ if (bulkBusy || resolvingSelection > 0) {
1781
+ return;
1782
+ }
1783
+ let chosen: Message[];
1784
+ try {
1785
+ chosen = selectMode ? selectedMessages : inConversations ? await loadOpenConversation(openThread!.conversation) : [selected!];
1786
+ } catch (err) {
1787
+ setBulkError(err instanceof ApiRequestError ? err.message : "Could not load the messages in that conversation.");
1788
+ return;
1789
+ }
1790
+ chosen = chosen.filter(applies);
1791
+ if (chosen.length === 0) {
1792
+ return;
1793
+ }
1794
+ const succeeded = await runBulkAction(action, removesRows, chosen);
1795
+ if (succeeded && removesRows && inConversations && !selectMode) {
1796
+ setOpenThread(null);
1797
+ setSelectedUid(null);
1798
+ }
1799
+ }
1800
+
1801
+ useShortcut(SHORTCUTS.mail.next, () => selectNeighbour(1), { enabled: canMoveSelection });
1802
+ useShortcut(SHORTCUTS.mail.previous, () => selectNeighbour(-1), { enabled: canMoveSelection });
1803
+ useShortcut(SHORTCUTS.mail.nextUnread, () => selectNextUnread(1), { enabled: canMoveSelection });
1804
+ useShortcut(SHORTCUTS.mail.previousUnread, () => selectNextUnread(-1), { enabled: canMoveSelection });
1805
+ useShortcut(
1806
+ SHORTCUTS.mail.delete,
1807
+ () =>
1808
+ void runOnKeyboardTargets(
1809
+ async (chosen) => moveMessages(chosen, await resolveFolderOfType("deleted_items", "Deleted Items")),
1810
+ true,
1811
+ (message) => folderTypeOf(message.folderUid) !== "deleted_items",
1812
+ ),
1813
+ { enabled: keyboardActions && keyboardTargetExists },
1814
+ );
1815
+ useShortcut(
1816
+ SHORTCUTS.mail.markRead,
1817
+ () =>
1818
+ void runOnKeyboardTargets(
1819
+ (chosen) => setReadStateMany(chosen, true, { patch: patchListedMessage, track: trackMessageChange }),
1820
+ false,
1821
+ isUnread,
1822
+ ),
1823
+ { enabled: keyboardActions && keyboardTargetExists },
1824
+ );
1825
+ useShortcut(
1826
+ SHORTCUTS.mail.markUnread,
1827
+ () =>
1828
+ void runOnKeyboardTargets(
1829
+ (chosen) => setReadStateMany(chosen, false, { patch: patchListedMessage, track: trackMessageChange }),
1830
+ false,
1831
+ (message) => !isUnread(message),
1832
+ ),
1833
+ { enabled: keyboardActions && keyboardTargetExists },
1834
+ );
1835
+ useShortcut(
1836
+ SHORTCUTS.mail.flag,
1837
+ () =>
1838
+ // Flags them all unless every one already is - what the bar's Flag and Unflag would do on this selection.
1839
+ void runOnKeyboardTargets((chosen) => setMessagesFlagged(chosen, !chosen.every((m) => m.flags.flagged)), false),
1840
+ { enabled: keyboardActions && keyboardTargetExists },
1841
+ );
1842
+ useShortcut(
1843
+ SHORTCUTS.mail.open,
1844
+ (event) => {
1845
+ // Enter on a row that is not selected yet is the row button's own click (it selects). On the selected one - or with the focus
1846
+ // elsewhere - it opens the message on its own page, as it does in Outlook.
1847
+ const rowUid = (event.target as Element).closest("[data-message-uid]")?.getAttribute("data-message-uid");
1848
+ if (rowUid ? rowUid !== selectedUid : isActivatable(event.target)) {
1849
+ return false;
1850
+ }
1851
+ navigate(`/messages/${encodeURIComponent(selectedUid!)}`);
1852
+ },
1853
+ { enabled: !selectMode && selectedUid !== null },
1854
+ );
1855
+ useShortcut(
1856
+ SHORTCUTS.mail.close,
1857
+ () => {
1858
+ if (document.activeElement === searchInputRef.current && searchInput !== "") {
1859
+ setSearchInput("");
1860
+ } else if (selectMode) {
1861
+ leaveSelectMode();
1862
+ } else {
1863
+ setSelectedUid(null);
1864
+ setOpenThread(null);
1865
+ }
1866
+ },
1867
+ { enabled: selectMode || selectedUid !== null || openThread !== null || searchInput !== "" },
1868
+ );
1869
+ useShortcut(
1870
+ SHORTCUTS.mail.search,
1871
+ () => {
1872
+ searchInputRef.current?.focus();
1873
+ searchInputRef.current?.select();
1874
+ },
1875
+ { enabled: !inConversations && !aggregateFolderType },
1876
+ );
1877
+
1878
+ if (!folderUid && !aggregateFolderType) {
1879
+ // `MailShell` never renders this component at all until a mailbox is resolved (see its own
1880
+ // full-screen `MailboxProvisioning` takeover otherwise) — this is purely the brief gap before
1881
+ // that mailbox's own folder list has finished loading, not a "no mailbox" state. Distinct text
1882
+ // from the message list's own "Loading…" below — otherwise the two transient states become
1883
+ // indistinguishable to anything (a test, a user re-reading the screen) that catches this one.
1884
+ return <p className="p-8 text-sm text-text-muted">Loading your mailbox&hellip;</p>;
1885
+ }
1886
+
1887
+ return (
1888
+ <div className="flex h-full min-h-0">
1889
+ <div
1890
+ ref={scrollContainerRef}
1891
+ // Remembered as it moves (not when the list is left: by then React has already detached the element), so
1892
+ // the folder - or Mail, after another app - comes back where it was.
1893
+ onScroll={(event) => saveListScroll(listKey, event.currentTarget.scrollTop)}
1894
+ className="w-full md:w-96 shrink-0 md:border-r border-border overflow-y-auto"
1895
+ >
1896
+ {selectMode ? (
1897
+ <MailSelectionBar
1898
+ selected={selectedMessages}
1899
+ listed={messages}
1900
+ totals={
1901
+ preferences.showAsConversations
1902
+ ? { selected: selectedConversationIds.size, listed: conversations.length, noun: "conversation" }
1903
+ : undefined
1904
+ }
1905
+ onSelectAll={() =>
1906
+ preferences.showAsConversations
1907
+ ? selectAllConversations()
1908
+ : setSelectedUids(new Set(messages.map((m) => m.uid)))
1909
+ }
1910
+ onClearSelection={() =>
1911
+ preferences.showAsConversations ? setSelectedConversationIds(new Set()) : setSelectedUids(new Set())
1912
+ }
1913
+ onCancel={leaveSelectMode}
1914
+ folders={currentFolders}
1915
+ currentFolderUid={folderUid}
1916
+ labels={mailboxLabels}
1917
+ mailboxUid={activeMailboxUid}
1918
+ onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
1919
+ onFolderCreated={onFolderCreated}
1920
+ onApplyLabels={applyLabelsToSelection}
1921
+ onSetRead={(read) =>
1922
+ void runBulkAction(
1923
+ // Optimistic: the rows and the folder badges change now, and change back if the server refuses.
1924
+ (chosen) => setReadStateMany(chosen, read, { patch: patchListedMessage, track: trackMessageChange }),
1925
+ false,
1926
+ )
1927
+ }
1928
+ onSetFlagged={(flagged) => void runBulkAction((chosen) => setMessagesFlagged(chosen, flagged), false)}
1929
+ shortcuts={keyboardActions}
1930
+ onArchive={() => void runBulkAction(bulkArchive, true)}
1931
+ onMoveTo={async (targetFolderUid) => {
1932
+ await runBulkAction((chosen) => moveMessages(chosen, targetFolderUid), true);
1933
+ }}
1934
+ onReportJunk={() => void moveSelectionToType("junk", "Junk Email")}
1935
+ onDelete={() => void moveSelectionToType("deleted_items", "Deleted Items")}
1936
+ busy={bulkBusy || resolvingSelection > 0}
1937
+ error={bulkError}
1938
+ />
1939
+ ) : (
1940
+ <MailListToolbar
1941
+ sortBy={preferences.sortBy}
1942
+ sortOrder={preferences.sortOrder}
1943
+ filter={preferences.filter}
1944
+ labelUids={preferences.labelUids}
1945
+ labels={mailboxLabels}
1946
+ mailboxUid={activeMailboxUid}
1947
+ onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
1948
+ onLabelUidsChange={(nextLabelUids) => updatePreferences({ labelUids: nextLabelUids })}
1949
+ showAsConversations={preferences.showAsConversations}
1950
+ onSortChange={(sortBy, sortOrder) => updatePreferences({ sortBy, sortOrder })}
1951
+ onFilterChange={(filter) => updatePreferences({ filter })}
1952
+ onShowAsConversationsChange={(showAsConversations) => updatePreferences({ showAsConversations })}
1953
+ selectMode={selectMode}
1954
+ onSelectModeChange={setSelectMode}
1955
+ offerClassificationFilters={offerClassificationFilters}
1956
+ filterDisabled={isSearching}
1957
+ filterDisabledReason="Filters don't apply to search results"
1958
+ sortKeysDisabled={isSearching || !!aggregateFolderType}
1959
+ // A conversation row is a thread summary, so only some of the keys have anything to
1960
+ // order by - the rest stay pickable and are applied to the rows already fetched.
1961
+ unavailableSortKeys={preferences.showAsConversations ? CONVERSATION_SORT_UNAVAILABLE : undefined}
1962
+ sortKeysNote={
1963
+ isSearching
1964
+ ? "Search results are ranked by relevance rather than sorted."
1965
+ : aggregateFolderType
1966
+ ? "This view merges the newest mail from every mailbox and is always listed by date."
1967
+ : preferences.showAsConversations
1968
+ ? CONVERSATION_SORT_NOTE
1969
+ : undefined
1970
+ }
1971
+ selectDisabled={!!aggregateFolderType || loading || listedRowCount === 0}
1972
+ selectDisabledReason={
1973
+ aggregateFolderType
1974
+ ? "Open a mailbox's own folder to select messages"
1975
+ : loading
1976
+ ? "Wait for this folder to finish loading"
1977
+ : "There is nothing here to select"
1978
+ }
1979
+ />
1980
+ )}
1981
+ {!preferences.showAsConversations && (
1982
+ <div className="p-2 border-b border-border">
1983
+ <input
1984
+ ref={searchInputRef}
1985
+ type="search"
1986
+ value={searchInput}
1987
+ onChange={(e) => setSearchInput(e.target.value)}
1988
+ placeholder={aggregateFolderType ? "Open a mailbox's own folder to search" : "Search all mail…"}
1989
+ aria-label="Search all mail"
1990
+ disabled={!!aggregateFolderType}
1991
+ className="w-full text-sm px-3 py-1.5 rounded-md border border-border bg-surface disabled:opacity-55"
1992
+ />
1993
+ </div>
1994
+ )}
1995
+ {/* Two tabs, as Outlook has: Focused and Other. There is no "All" tab - the whole Inbox is
1996
+ still one pick away, in the Filter menu, which is where every other named filter lives
1997
+ and the only place that can show which of them is really in force. A stored `all` (or
1998
+ Unread, Flagged, ...) therefore still lists what it always did, with neither tab
1999
+ pressed, rather than being migrated into one of these two halves behind the reader's
2000
+ back - see `MAIL_LIST_FILTERS`, which still offers it. */}
2001
+ {offerClassificationFilters && (
2002
+ <div className="flex border-b border-border text-xs">
2003
+ {MAIL_LIST_CLASSIFICATION_FILTERS.map(({ value, label }) => (
2004
+ <button
2005
+ key={value}
2006
+ type="button"
2007
+ aria-pressed={preferences.filter === value}
2008
+ onClick={() => updatePreferences({ filter: value })}
2009
+ className={[
2010
+ "flex-1 py-1.5 font-semibold",
2011
+ preferences.filter === value
2012
+ ? "text-primary-dark border-b-2 border-primary-dark"
2013
+ : "text-text-muted",
2014
+ ].join(" ")}
2015
+ >
2016
+ {label}
2017
+ </button>
2018
+ ))}
2019
+ </div>
2020
+ )}
2021
+
2022
+ {isSearching && (
2023
+ <div className="px-4 py-1.5 text-xs text-text-muted border-b border-border flex items-center justify-between gap-2">
2024
+ {/* §_Progressive Results_: "Never show a hard count until every tier has reported.
2025
+ Display n of ??, or omit the count. A settled count is the signal that ordering
2026
+ is final." */}
2027
+ <span>
2028
+ {tier1Done && tier2Done && tier3Done
2029
+ ? `${messages.length} result${messages.length === 1 ? "" : "s"}`
2030
+ : `${messages.length} of ??`}
2031
+ </span>
2032
+ {tier2Done && !searchAllMail && (
2033
+ <button
2034
+ type="button"
2035
+ onClick={handleSearchAllMail}
2036
+ className="text-primary-dark hover:underline font-medium shrink-0"
2037
+ >
2038
+ Search all mail
2039
+ </button>
2040
+ )}
2041
+ </div>
2042
+ )}
2043
+ {isSearching && coverage?.indexedFrom && (
2044
+ <div className="px-4 py-1.5 text-xs text-text-muted border-b border-border">
2045
+ Local search covers messages back to {new Date(coverage.indexedFrom).toLocaleDateString()}
2046
+ {coverage.building ? " (still building)" : ""}
2047
+ {searchAllMail
2048
+ ? " - searching everything, not just recent mail."
2049
+ : " - older encrypted mail is still searched, just slower."}
2050
+ </div>
2051
+ )}
2052
+ {isSearching && !getUnlockedKeys(mailboxUid!) && (
2053
+ <div className="px-4 py-2 border-b border-border bg-surface-alt">
2054
+ <button
2055
+ type="button"
2056
+ onClick={handleUnlockSearch}
2057
+ className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
2058
+ >
2059
+ <HiOutlineLockClosed size={12} aria-hidden="true" />
2060
+ Unlock to include encrypted messages in these results
2061
+ </button>
2062
+ </div>
2063
+ )}
2064
+ {!isSearching && !preferences.showAsConversations && undecryptedEncryptedUids.length > 0 && !getUnlockedKeys(activeMailboxUid) && (
2065
+ <div className="px-4 py-2 border-b border-border bg-surface-alt">
2066
+ <button
2067
+ type="button"
2068
+ onClick={handleUnlockList}
2069
+ className="inline-flex items-center gap-1 text-xs font-medium text-primary-dark hover:underline"
2070
+ >
2071
+ <HiOutlineLockClosed size={12} aria-hidden="true" />
2072
+ Unlock to show {undecryptedEncryptedUids.length === 1 ? "an encrypted message's" : "encrypted messages'"} subject
2073
+ </button>
2074
+ </div>
2075
+ )}
2076
+
2077
+ {error && (
2078
+ <div className="p-4">
2079
+ <Alert>{error}</Alert>
2080
+ </div>
2081
+ )}
2082
+ {/* Select mode shows a bulk action's failure in its own bar; the keyboard's actions on the one open message need somewhere too. */}
2083
+ {!selectMode && bulkError && (
2084
+ <div className="p-4">
2085
+ <Alert>{bulkError}</Alert>
2086
+ </div>
2087
+ )}
2088
+
2089
+ {loading ? (
2090
+ // A skeleton of rows rather than a line of text: the list keeps its shape while a folder that was not shown a
2091
+ // moment ago loads (one that was is shown at once, from its snapshot).
2092
+ <div role="status" aria-busy="true" className="p-4">
2093
+ <span className="sr-only">Loading&hellip;</span>
2094
+ <SkeletonList count={8} />
2095
+ </div>
2096
+ ) : preferences.showAsConversations ? (
2097
+ <>
2098
+ <ConversationList
2099
+ conversations={listedConversations}
2100
+ newestFirst={preferences.sortBy === "date" && preferences.sortOrder === "desc"}
2101
+ mailboxUid={activeMailboxUid}
2102
+ selectedUid={selectedUid}
2103
+ messageOverrides={conversationPatches}
2104
+ onOpenMessage={handleOpenConversation}
2105
+ selectMode={selectMode}
2106
+ selectedConversationIds={selectedConversationIds}
2107
+ onToggleSelected={toggleConversationSelected}
2108
+ />
2109
+ {hasMore && (
2110
+ <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
2111
+ {loadMoreStatus}
2112
+ </div>
2113
+ )}
2114
+ </>
2115
+ ) : messages.length === 0 ? (
2116
+ <>
2117
+ <p className="p-4 text-sm text-text-muted">
2118
+ {isSearching
2119
+ ? `No messages match "${searchQuery}".`
2120
+ : effectiveFilter === "all"
2121
+ ? "No messages in this folder."
2122
+ : "No messages here."}
2123
+ </p>
2124
+ {/* Still offered while a filter hides every loaded row - what it's looking for may be
2125
+ on a later page. */}
2126
+ {hasMore && (
2127
+ <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
2128
+ {loadMoreStatus}
2129
+ </div>
2130
+ )}
2131
+ </>
2132
+ ) : (
2133
+ <>
2134
+ <ul>
2135
+ {messages.map((message) => (
2136
+ <li
2137
+ key={message.uid}
2138
+ data-message-uid={message.uid}
2139
+ data-unread={isUnread(message) ? "true" : undefined}
2140
+ className={rowClass(
2141
+ { unread: isUnread(message), selected: message.uid === selectedUid || selectedUids.has(message.uid) },
2142
+ "flex items-stretch",
2143
+ )}
2144
+ >
2145
+ <UnreadBar unread={isUnread(message)} />
2146
+ {selectMode && (
2147
+ <span className="shrink-0 flex items-center pl-3">
2148
+ <input
2149
+ type="checkbox"
2150
+ checked={selectedUids.has(message.uid)}
2151
+ onChange={() => toggleSelected(message.uid)}
2152
+ aria-label={`Select ${rowSubject(message)}`}
2153
+ className="w-4 h-4 accent-primary"
2154
+ />
2155
+ </span>
2156
+ )}
2157
+ <button
2158
+ type="button"
2159
+ data-row-open
2160
+ onClick={() => handleSelect(message)}
2161
+ className={["flex-1 min-w-0 text-left px-4 py-3", ROW_FOCUS_CLASS].join(" ")}
2162
+ >
2163
+ <UnreadLabel unread={isUnread(message)} />
2164
+ <div className="flex items-center justify-between gap-2 text-sm">
2165
+ <MailAddress recipient={message.from} className={senderClass(isUnread(message))} />
2166
+ <span className={["text-xs shrink-0", dateClass(isUnread(message))].join(" ")}>
2167
+ {new Date(message.receivedDate).toLocaleDateString()}
2168
+ </span>
2169
+ </div>
2170
+ {aggregateFolderType && (
2171
+ // The one view where a row needs to say which mailbox it came from.
2172
+ <div className="text-xs text-text-muted truncate font-normal">
2173
+ {mailboxes.find((mb) => mb.uid === message.mailboxUid)?.displayName}
2174
+ </div>
2175
+ )}
2176
+ {isSearching && pendingUids.has(message.uid) ? (
2177
+ // §_Progressive Results_: "Unresolved encrypted results MUST
2178
+ // be rendered as skeleton entries in place, not appended on
2179
+ // arrival." This uid is a Tier 1 metadataOnly guess Tier 2/3
2180
+ // haven't confirmed (or ruled out) yet.
2181
+ <div className="flex flex-col gap-1.5 py-0.5">
2182
+ <Skeleton height="h-3.5" className="w-2/3 rounded-sm" />
2183
+ <Skeleton height="h-3" className="w-full rounded-sm" />
2184
+ </div>
2185
+ ) : (
2186
+ <>
2187
+ <div className={["text-sm truncate", subjectClass(isUnread(message))].join(" ")}>
2188
+ {rowSubject(message)}
2189
+ </div>
2190
+ <div className="flex items-center gap-2 text-xs text-text-muted font-normal">
2191
+ <span className="truncate">
2192
+ {snippets[message.uid] || decryptedRows[message.uid]?.preview || message.bodyPreview}
2193
+ </span>
2194
+ {message.hasAttachments && <HiOutlinePaperClip size={12} aria-label="Has attachments" />}
2195
+ {message.flags.flagged && (
2196
+ <HiOutlineFlag size={12} aria-label="Flagged" className="text-danger" />
2197
+ )}
2198
+ </div>
2199
+ </>
2200
+ )}
2201
+ </button>
2202
+ </li>
2203
+ ))}
2204
+ </ul>
2205
+ {hasMore && (
2206
+ <div ref={setSentinel} data-testid="load-more-sentinel" className="p-4 text-center text-xs text-text-muted">
2207
+ {loadMoreStatus}
2208
+ </div>
2209
+ )}
2210
+ {aggregateFolderType && (
2211
+ <p className="p-4 text-center text-xs text-text-muted">
2212
+ Showing the most recent mail from each mailbox. Open a specific mailbox&rsquo;s folder to
2213
+ see older mail.
2214
+ </p>
2215
+ )}
2216
+ </>
2217
+ )}
2218
+ </div>
2219
+ {/* The reading pane's own height: a row of the full-height mail view, stretched to it by the
2220
+ flex chain rather than by a percentage (an explicit height would opt it out of that
2221
+ stretching), with `min-h-0` so a long message scrolls inside it instead of pushing it past
2222
+ the window. Everything below - the thread pane, each message's `MessageDetailPane`, the
2223
+ body iframe that cannot measure itself - takes its height from here, never from a `vh`
2224
+ number of its own. */}
2225
+ <div className="hidden md:flex flex-1 min-w-0 min-h-0">
2226
+ {preferences.showAsConversations ? (
2227
+ <LazyConversationThreadPane
2228
+ conversation={openThread?.conversation ?? null}
2229
+ selectedUid={openThread?.uid ?? null}
2230
+ mailboxUid={activeMailboxUid}
2231
+ folders={currentFolders}
2232
+ labels={mailboxLabels}
2233
+ shortcuts={!selectMode}
2234
+ onMessagePatched={patchListedMessage}
2235
+ onMessageRemoved={(updated) => removeListedMessage(updated.uid)}
2236
+ onLabelCreated={(label) => setMailboxLabels((prev) => [...prev, label])}
2237
+ onFolderCreated={onFolderCreated}
2238
+ />
2239
+ ) : (
2240
+ <LazyMessageDetailPane
2241
+ shortcuts={!selectMode}
2242
+ message={selected}
2243
+ attachments={attachments}
2244
+ isSentItems={isSentItems}
2245
+ onRecalled={patchListedMessage}
2246
+ isOutbox={isOutbox}
2247
+ onReceiptHandled={patchListedMessage}
2248
+ draftsFolderUid={draftsFolderUid}
2249
+ folders={folders}
2250
+ onMoved={(updated) => {
2251
+ // Same reasoning as onArchived below - a move takes the message out of the folder
2252
+ // being listed, so it leaves the list rather than being patched in place.
2253
+ removeListedMessage(updated.uid);
2254
+ }}
2255
+ onFolderCreated={onFolderCreated}
2256
+ onScheduledSendCanceled={(updated) => {
2257
+ // The message moved out of the currently-viewed Outbox folder (into Drafts)
2258
+ // - unlike a recall, which patches a message in place, this removes it from
2259
+ // the list entirely, matching what a real folder switch would show.
2260
+ removeListedMessage(updated.uid);
2261
+ }}
2262
+ onArchived={(updated) => {
2263
+ // Same reasoning as onScheduledSendCanceled above - the message moved out of
2264
+ // whichever folder is currently being viewed (into Archive), so it's removed
2265
+ // from the list rather than patched in place.
2266
+ removeListedMessage(updated.uid);
2267
+ }}
2268
+ labels={labels}
2269
+ onLabelsChanged={patchListedMessage}
2270
+ onLabelCreated={(label) =>
2271
+ (otherMailbox ? setOtherMailboxLabels : setMailboxLabels)((prev) => [...prev, label])
2272
+ }
2273
+ />
2274
+ )}
2275
+ </div>
2276
+ </div>
2277
+ );
2278
+ }
2279
+
2280
+ export default routedPage("/", InboxPage);