@open-workspace/email 0.4.1 → 0.5.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 (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -1,20 +1,58 @@
1
- import { useDebouncedValue } from "@open-workspace/core/ui";
2
- import { useEffect, useMemo, useState } from "react";
3
- import { useNavigate } from "react-router";
1
+ import {
2
+ ApiError,
3
+ queryErrorBlocksContent,
4
+ useDebouncedValue,
5
+ useNotificationClicks,
6
+ usePrefetchOnIntent,
7
+ } from "@open-workspace/core/ui";
8
+ import { skipToken, useQuery, useQueryClient } from "@tanstack/react-query";
9
+ import { useQueryStates } from "nuqs";
10
+ import {
11
+ useEffect,
12
+ useEffectEvent,
13
+ useLayoutEffect,
14
+ useRef,
15
+ useState,
16
+ } from "react";
17
+ import { useLocation, useNavigate, useSearchParams } from "react-router";
4
18
  import { toast } from "sonner";
5
19
 
20
+ import {
21
+ conversationFolder,
22
+ DRAFTS_FOLDER_ID,
23
+ } from "../../shared/folder-order";
24
+ import type { ConversationPlace } from "../../shared/mail";
6
25
  import { mailPath, parseMailPath } from "../../shared/mail-path";
7
- import { folderDisplayName } from "./mail-folders";
26
+ import {
27
+ actionFolder,
28
+ conversationActionsIn,
29
+ } from "./conversation-actions-model";
30
+ import { focusListAfter, rowsAround } from "./mail-focus";
31
+ import { folderAfterMailboxSwitch, folderDisplayName } from "./mail-folders";
8
32
  import {
9
33
  mailboxForRoute,
10
34
  resolveMailLocation,
11
35
  routePath,
12
36
  } from "./mail-location";
13
37
  import type { MailRoute } from "./mail-location";
14
- import type { Folder, MessageDetail } from "./types";
38
+ import {
39
+ conversationsQuery as conversationList,
40
+ foldersQuery as mailboxFolders,
41
+ prefetchMailboxSwitch,
42
+ } from "./mail-queries";
43
+ import {
44
+ composeDraftId,
45
+ mailHref,
46
+ mailSearchParams,
47
+ } from "./mail-search-params";
48
+ import type { ConversationSummary, Folder, MessageDetail } from "./types";
49
+ import { useComposerNavigation } from "./use-composer-navigation";
50
+ import { useConversationActions } from "./use-conversation-actions";
51
+ import { useConversationPosition } from "./use-conversation-position";
15
52
  import { useConversationSelection } from "./use-conversation-selection";
53
+ import { loadComposerDraft, newDraftId } from "./use-drafts";
54
+ import type { ForwardSource, SavedDraft } from "./use-drafts";
16
55
  import {
17
- useBulkConversationAction,
18
56
  useConversation,
19
57
  useConversations,
20
58
  useFolders,
@@ -24,28 +62,134 @@ import {
24
62
 
25
63
  export type MailController = ReturnType<typeof useMailController>;
26
64
 
65
+ /** The open composer: a new message, a forward, or a reopened draft. */
66
+ type Composer = {
67
+ /** The id its draft is saved under. */
68
+ draftId: string;
69
+ draft?: SavedDraft;
70
+ forwarded?: ForwardSource;
71
+ };
72
+
27
73
  /**
28
74
  * Mail state and actions shared by every mail frontend: the route-derived
29
75
  * location, list and conversation queries, selection, composer, and
30
76
  * conversation mutations. Frontends only decide how to present them.
31
77
  */
32
- export function useMailController(
33
- route: MailRoute,
34
- options: { listWithConversation?: boolean } = {}
35
- ) {
78
+ export function useMailController(route: MailRoute) {
36
79
  const { mailboxId } = route;
37
- const navigateRoute = useNavigate();
80
+ const navigate = useNavigate();
81
+ const queryClient = useQueryClient();
82
+
83
+ const [{ q: search, match: matchParam, quote }, setParams] = useQueryStates({
84
+ q: mailSearchParams.q,
85
+ match: mailSearchParams.match,
86
+ quote: mailSearchParams.quote,
87
+ });
88
+
89
+ const matchId = matchParam ?? undefined;
90
+
91
+ // ?compose= is React Router's: its blocker holds a Back while the composer
92
+ // saves, which needs entries the router pushed. nuqs pushes its own and
93
+ // follows popstate before the router restores a blocked one.
94
+ const [searchParams, setSearchParams] = useSearchParams();
95
+ const compose = searchParams.get("compose");
96
+ const requestedDraftId = composeDraftId(compose);
97
+
98
+ // The window opened here, with the message it forwards: its draft is not
99
+ // saved yet, so it opens without loading it. Once the URL has shown it,
100
+ // leaving it (Back, another draft) forgets it, and Forward loads it.
101
+ const [started, setStarted] = useState<{
102
+ draftId: string;
103
+ forwarded?: ForwardSource;
104
+ shown: boolean;
105
+ } | null>(null);
106
+
107
+ if (started) {
108
+ const showing = started.draftId === requestedDraftId;
109
+
110
+ if (showing && !started.shown) setStarted({ ...started, shown: true });
111
+ else if (!showing && started.shown) setStarted(null);
112
+ }
113
+
114
+ /**
115
+ * Shows the composer at ?compose=`value`, an entry of its own: Back closes
116
+ * it. Opened on a page without one, the entry is marked: closing it goes
117
+ * back to that page, as a modal route does, so Back then leaves the page
118
+ * instead of repeating it.
119
+ */
120
+ function showComposer(value: string) {
121
+ setSearchParams(
122
+ (params) => {
123
+ params.set("compose", value);
124
+
125
+ return params;
126
+ },
127
+ {
128
+ preventScrollReset: true,
129
+ state: live.current.compose ? undefined : { composerOpened: true },
130
+ }
131
+ );
132
+ }
133
+
134
+ // The marked entry while it is the current one. A sheet's entry, which
135
+ // nuqs pushes with a copy of its state, and a search nuqs replaces it
136
+ // with are other entries, each with a state object of its own: those
137
+ // close by removing ?compose= in place.
138
+ const routerLocation = useLocation();
139
+ const composerEntry = useRef<unknown>(null);
140
+
141
+ useLayoutEffect(() => {
142
+ composerEntry.current =
143
+ routerLocation.state?.composerOpened === true
144
+ ? window.history.state
145
+ : null;
146
+ }, [routerLocation]);
147
+
148
+ function hideComposer() {
149
+ if (
150
+ composerEntry.current &&
151
+ composerEntry.current === window.history.state
152
+ ) {
153
+ composerEntry.current = null;
154
+ void navigate(-1);
155
+
156
+ return;
157
+ }
158
+
159
+ setSearchParams(
160
+ (params) => {
161
+ params.delete("compose");
162
+
163
+ return params;
164
+ },
165
+ { replace: true, preventScrollReset: true }
166
+ );
167
+ }
38
168
 
39
- const [composerMailboxId, setComposerMailboxId] = useState<string | null>(
40
- null
169
+ // The draft of the open composer discarded from the Drafts list: the
170
+ // window stops saving it before it closes.
171
+ const [listDiscarded, setListDiscarded] = useState<string | null>(null);
172
+
173
+ // Drafts this tab's composer closed (sent or discarded).
174
+ const [closedDraftIds, setClosedDraftIds] = useState<ReadonlySet<string>>(
175
+ () => new Set()
41
176
  );
42
177
 
43
- const [forwardedMessage, setForwardedMessage] = useState<
44
- MessageDetail | undefined
45
- >();
178
+ // Where the screen is now, with its ?compose=, for actions that settle
179
+ // after a render: the person may have moved on meanwhile.
180
+ const live = useRef({ route, compose, search, mounted: true });
181
+
182
+ useLayoutEffect(() => {
183
+ live.current = { route, compose, search, mounted: true };
46
184
 
47
- const [search, setSearch] = useState("");
48
- const [unreadOnly, setUnreadOnly] = useState(false);
185
+ // A save can finish after switching mailboxes unmounted this controller.
186
+ return () => {
187
+ live.current.mounted = false;
188
+ };
189
+ });
190
+
191
+ const [unreadFilter, setUnreadFilter] = useState(false);
192
+ const intent = usePrefetchOnIntent();
49
193
  const mailboxQuery = useMailboxes();
50
194
  const mailboxes = mailboxQuery.data?.mailboxes ?? [];
51
195
 
@@ -72,103 +216,267 @@ export function useMailController(
72
216
  canonicalPath,
73
217
  } = location;
74
218
 
219
+ const unreadIn = (target: Folder) =>
220
+ target !== DRAFTS_FOLDER_ID && unreadFilter;
221
+
222
+ const unreadOnly = unreadIn(folder);
75
223
  const activeMailboxId = mailbox?.id;
76
- const composeOpen = composerMailboxId === activeMailboxId;
77
224
  const currentPath = routePath(route);
78
225
 
79
- // Moving to another mailbox (e.g. back in history) discards its draft
80
- // window: adjusted while rendering, so the old composer never shows.
81
- if (
82
- composerMailboxId &&
83
- activeMailboxId &&
84
- composerMailboxId !== activeMailboxId
85
- ) {
86
- setComposerMailboxId(null);
87
- setForwardedMessage(undefined);
88
- }
226
+ // A notification clicked while the screen is open opens its conversation
227
+ // as a page of its own, with the open composer while the mailbox stays.
228
+ useNotificationClicks((href: string) => {
229
+ const target = parseMailPath(
230
+ new URL(href, window.location.origin).pathname
231
+ );
232
+
233
+ if (!target) return false;
234
+ const here = target.mailboxId === activeMailboxId;
235
+
236
+ void navigate(
237
+ mailHref(
238
+ mailPath(target.mailboxId, target.folder, target.conversationId),
239
+ { compose: here ? compose : null, q: here ? search : null }
240
+ )
241
+ );
242
+
243
+ return true;
244
+ });
245
+
246
+ const redirectToCanonical = useEffectEvent((path: string) => {
247
+ void navigate(mailHref(path, { compose, q: search }), { replace: true });
248
+ });
89
249
 
90
250
  useEffect(() => {
91
251
  if (locationReady && canonicalPath && currentPath !== canonicalPath) {
92
- navigateRoute(canonicalPath, { replace: true });
252
+ redirectToCanonical(canonicalPath);
253
+ }
254
+ }, [canonicalPath, currentPath, locationReady]);
255
+
256
+ const canSend = Boolean(activeMailboxId && mailbox?.canSend);
257
+
258
+ const startedHere = started !== null && started.draftId === requestedDraftId;
259
+
260
+ // ?compose=<draft id> of a draft not open here (a reload, a Drafts row,
261
+ // Back) loads it: a new message or forward opens in the composer, a reply
262
+ // in its conversation. Other drafts wait in Drafts. Each opening reads it
263
+ // again; while open, the composer is its editor.
264
+ const draftQuery = useQuery({
265
+ queryKey: ["draft", activeMailboxId, requestedDraftId],
266
+ queryFn:
267
+ activeMailboxId && requestedDraftId
268
+ ? ({ signal }) =>
269
+ loadComposerDraft(activeMailboxId, requestedDraftId, signal)
270
+ : skipToken,
271
+ enabled: canSend && !startedHere,
272
+ staleTime: Infinity,
273
+ gcTime: 0,
274
+ });
275
+
276
+ const loadedDraft = draftQuery.data;
277
+
278
+ // A window opened here and never saved has no draft to load.
279
+ const unsaved =
280
+ loadedDraft === null &&
281
+ requestedDraftId !== null &&
282
+ compose === `new-${requestedDraftId}` &&
283
+ !closedDraftIds.has(requestedDraftId);
284
+
285
+ const composer: Composer | null =
286
+ canSend && requestedDraftId
287
+ ? startedHere
288
+ ? { draftId: requestedDraftId, forwarded: started.forwarded }
289
+ : loadedDraft && loadedDraft.draft.kind !== "reply"
290
+ ? { draftId: requestedDraftId, ...loadedDraft }
291
+ : unsaved
292
+ ? { draftId: requestedDraftId }
293
+ : null
294
+ : null;
295
+
296
+ const composerNavigation = useComposerNavigation(
297
+ mailboxId,
298
+ composer?.draftId
299
+ );
300
+
301
+ const draftSettled = useEffectEvent(() => {
302
+ if (draftQuery.error) {
303
+ toast.error(draftQuery.error.message || "Could not load the draft");
304
+ hideComposer();
305
+ } else if (mailbox && loadedDraft?.draft.kind === "reply") {
306
+ void navigate(
307
+ mailHref(
308
+ mailPath(mailbox.id, folder, loadedDraft.draft.conversationId),
309
+ {
310
+ q: search,
311
+ }
312
+ ),
313
+ { replace: true }
314
+ );
315
+ } else if (loadedDraft === null && !unsaved) {
316
+ if (requestedDraftId && !closedDraftIds.has(requestedDraftId)) {
317
+ toast.error("That draft was sent or discarded");
318
+ }
319
+
320
+ hideComposer();
93
321
  }
94
- }, [canonicalPath, currentPath, locationReady, navigateRoute]);
95
- const debouncedSearch = useDebouncedValue(search.trim(), 250);
322
+ });
323
+
324
+ useEffect(() => {
325
+ if (loadedDraft !== undefined || draftQuery.error) draftSettled();
326
+ }, [loadedDraft, draftQuery.error]);
327
+
328
+ // Typing waits for a pause; clearing the search shows the full list at once.
329
+ const typedSearch = useDebouncedValue(search.trim(), 250);
330
+ const debouncedSearch = search.trim() ? typedSearch : "";
96
331
 
97
332
  const conversationsQuery = useConversations(
98
333
  location.mailboxId,
99
334
  folder,
100
335
  debouncedSearch,
101
- unreadOnly,
102
- // Layouts that keep the list beside an open conversation load it too.
103
- !conversationId || Boolean(options.listWithConversation)
336
+ unreadOnly
104
337
  );
105
338
 
106
- const conversationQuery = useConversation(location.mailboxId, conversationId);
107
- const sharedConversationAction = useBulkConversationAction();
339
+ const conversationQuery = useConversation(
340
+ location.mailboxId,
341
+ conversationId,
342
+ matchId
343
+ );
344
+
345
+ const openPlace = conversationQuery.data?.pages[0];
346
+
347
+ // A background refresh can discover a deletion while the reader still has cached pages.
348
+ const removed =
349
+ Boolean(openPlace) &&
350
+ conversationQuery.error instanceof ApiError &&
351
+ conversationQuery.error.status === 404 &&
352
+ !conversationQuery.isFetchNextPageError;
108
353
 
109
- const conversations = useMemo(
110
- () =>
111
- conversationsQuery.data?.pages.flatMap((page) => page.conversations) ??
112
- [],
113
- [conversationsQuery.data?.pages]
354
+ const leaveDeletedConversation = useEffectEvent((id: string) =>
355
+ closeConversation(id, true)
114
356
  );
115
357
 
358
+ useEffect(() => {
359
+ if (removed && conversationId) leaveDeletedConversation(conversationId);
360
+ }, [removed, conversationId]);
361
+
362
+ // Where the open conversation is: its actions are offered for that
363
+ // folder and act in it, whichever list it was opened from (Drafts, a
364
+ // view a teammate's move left behind).
365
+ const openFolder = openPlace ? conversationFolder(openPlace) : folder;
366
+
367
+ const conversationActions = useConversationActions({
368
+ mailboxId: mailbox?.id,
369
+ folderId: openFolder,
370
+ follow: (places) => followChange(places),
371
+ });
372
+
373
+ const conversations =
374
+ conversationsQuery.data?.pages.flatMap((page) => page.conversations) ?? [];
375
+
376
+ // The rows shown now, for focus after an action takes some away.
377
+ const listed = useRef(conversations);
378
+
379
+ useLayoutEffect(() => {
380
+ listed.current = conversations;
381
+ });
382
+
116
383
  // Until the mailbox and folder are confirmed, a failed request may only
117
384
  // mean the URL is stale, which the canonical redirect fixes.
385
+ const blockingQuery = [mailboxQuery, mailbox && foldersQuery].find(
386
+ (query) => query && queryErrorBlocksContent(query)
387
+ );
388
+
389
+ const queryError = locationReady ? conversationsQuery.error : null;
390
+
391
+ // Only keep confirmed rows of this query after a transient refresh failure.
392
+ const refreshError =
393
+ !blockingQuery &&
394
+ conversations.length > 0 &&
395
+ !conversationsQuery.isPlaceholderData &&
396
+ !(queryError instanceof ApiError && queryError.status < 500)
397
+ ? queryError?.message
398
+ : undefined;
399
+
118
400
  const listError =
119
- mailboxQuery.error?.message ??
120
- (mailbox ? foldersQuery.error?.message : undefined) ??
121
- (locationReady ? conversationsQuery.error?.message : undefined);
401
+ blockingQuery?.error?.message ??
402
+ (refreshError ? undefined : queryError?.message);
122
403
 
123
404
  const conversationPages = conversationQuery.data?.pages;
124
405
 
125
- const conversationMessages = useMemo(
126
- () =>
127
- conversationPages
128
- ? [...conversationPages].reverse().flatMap((page) => page.messages)
129
- : [],
130
- [conversationPages]
131
- );
406
+ const head = conversationPages?.[0];
407
+ const pin = head?.pinnedMessageId;
408
+
409
+ const threadMessages = (conversationPages ?? [])
410
+ .toReversed()
411
+ .flatMap((page) =>
412
+ page === head && pin
413
+ ? page.messages.filter((message) => message.id !== pin)
414
+ : page.messages
415
+ );
416
+
417
+ // Once paging reaches the hit, it takes its normal place in the thread.
418
+ const pinned =
419
+ pin &&
420
+ pin === matchId &&
421
+ !threadMessages.some((message) => message.id === pin)
422
+ ? head.messages[0]
423
+ : undefined;
424
+
425
+ const conversationMessages = pinned
426
+ ? [pinned, ...threadMessages]
427
+ : threadMessages;
132
428
 
133
429
  const conversation = conversationPages?.[0];
134
430
  const prefetchConversation = usePrefetchConversation();
135
431
 
432
+ const listedRow = (id: string) =>
433
+ conversations.find((item) => item.conversationId === id);
434
+
136
435
  // With a conversation open, the previous and next one load in the
137
436
  // background, so stepping through the list does not wait.
138
- const openIndex =
139
- conversationId && conversation
140
- ? conversations.findIndex(
141
- (item) => item.conversationId === conversationId
142
- )
143
- : -1;
144
-
145
- const neighbourIds =
146
- openIndex >= 0
147
- ? [conversations[openIndex + 1], conversations[openIndex - 1]].flatMap(
148
- (item) => (item ? [item.conversationId] : [])
149
- )
150
- : [];
151
-
152
- const neighbourKey = neighbourIds.join("\0");
153
- useEffect(() => {
154
- if (!neighbourKey) return;
437
+ const listScope = `${activeMailboxId ?? ""}\0${folder}\0${debouncedSearch}\0${unreadOnly}`;
438
+
439
+ const position = useConversationPosition(
440
+ conversations,
441
+ conversationId,
442
+ unreadOnly && !conversationsQuery.isPlaceholderData ? listScope : null
443
+ );
444
+
445
+ const { next: nextRow, previous: previousRow } = position;
155
446
 
156
- const timer = setTimeout(() => {
157
- for (const id of neighbourKey.split("\0")) {
158
- prefetchConversation(location.mailboxId, id);
447
+ const prefetchNeighbours = useEffectEvent(() => {
448
+ for (const row of [nextRow, previousRow]) {
449
+ if (row && row.draftId !== row.conversationId) {
450
+ prefetchConversation(
451
+ location.mailboxId,
452
+ row.conversationId,
453
+ row.searchMatch?.id
454
+ );
159
455
  }
160
- }, 150);
456
+ }
457
+ });
458
+
459
+ useEffect(() => {
460
+ if (!conversation || (!nextRow && !previousRow)) return;
461
+ const timer = setTimeout(prefetchNeighbours, 150);
161
462
 
162
463
  return () => clearTimeout(timer);
163
- }, [location.mailboxId, neighbourKey, prefetchConversation]);
464
+ }, [conversation, nextRow, previousRow]);
164
465
  const folderName = folderDisplayName(folder, folders);
165
466
  const activeFolder = folders?.find((item) => item.id === folder);
166
467
 
167
468
  const selection = useConversationSelection({
168
- scope: `${activeMailboxId ?? ""}\0${folder}\0${debouncedSearch}\0${unreadOnly}`,
469
+ scope: listScope,
169
470
  mailboxId: activeMailboxId,
170
471
  folderId: folder,
171
472
  conversations,
473
+ follow: (places) => followChange(places),
474
+ // A composer open on a draft discarded from the list closes with it.
475
+ onDraftsDiscarded: (draftIds) => {
476
+ if (composer && draftIds.includes(composer.draftId)) {
477
+ setListDiscarded(composer.draftId);
478
+ }
479
+ },
172
480
  });
173
481
 
174
482
  const moreConversationsExist = Boolean(
@@ -180,139 +488,280 @@ export function useMailController(
180
488
  ? `${conversations.length}${moreConversationsExist ? "+" : ""}`
181
489
  : String(activeFolder?.totalCount ?? conversations.length);
182
490
 
183
- /** `replace` swaps the current history entry, e.g. the one an open mailbox sheet added. */
184
- function navigate(
185
- next: {
186
- folder?: Folder;
187
- mailbox?: string;
188
- conversation?: string | null;
189
- },
190
- replace = false
191
- ) {
192
- const targetMailboxId = next.mailbox ?? mailbox?.id;
491
+ /** `path` with the open composer, which stays open across this mailbox's pages. */
492
+ function withComposer(path: string) {
493
+ return mailHref(path, {
494
+ compose: live.current.compose,
495
+ q: live.current.search,
496
+ });
497
+ }
193
498
 
194
- if (!targetMailboxId) return;
499
+ /**
500
+ * A folder's list, of this mailbox or another (whose composer closes as
501
+ * the page changes); `replace` takes the current entry's place, e.g. the
502
+ * one an open mailbox sheet added.
503
+ */
504
+ function openList(targetMailboxId: string, target: Folder, replace = false) {
505
+ const path = mailPath(targetMailboxId, target);
195
506
 
196
- const targetConversation =
197
- next.conversation === null ? null : (next.conversation ?? conversationId);
507
+ if (targetMailboxId === mailbox?.id) {
508
+ void navigate(withComposer(path), { replace });
198
509
 
199
- navigateRoute(
200
- mailPath(targetMailboxId, next.folder ?? folder, targetConversation),
201
- { replace }
510
+ return;
511
+ }
512
+
513
+ // What it was picked from can go as the other mailbox loads (the
514
+ // phone's dock switcher, and its sheet, while no mailbox is known):
515
+ // the list takes focus.
516
+ focusListAfter([]);
517
+ void navigate(path, { replace });
518
+ }
519
+
520
+ /**
521
+ * Opens a conversation (in `target`, else this folder): from the list as
522
+ * an entry of its own, so Back returns to the list; `replace` in the place
523
+ * of an open one (Next and Previous, a thread its mail rejoined, a
524
+ * detached reply's), so stepping through the list doesn't pile up
525
+ * entries, or of the list it closed to.
526
+ */
527
+ function showConversation(
528
+ id: string,
529
+ history: "push" | "replace",
530
+ target: Folder = folder,
531
+ match?: ConversationSummary["searchMatch"]
532
+ ) {
533
+ const current = live.current.route;
534
+
535
+ if (!current.mailboxId) return;
536
+
537
+ // Cached without the hit (opened before, or from another list), it
538
+ // loads the page with it.
539
+ if (match) prefetchConversation(current.mailboxId, id, match.id);
540
+
541
+ void navigate(
542
+ mailHref(mailPath(current.mailboxId, target, id), {
543
+ compose: live.current.compose,
544
+ q: live.current.search,
545
+ match: match?.id,
546
+ quote: Boolean(match?.quoted),
547
+ }),
548
+ { replace: history === "replace" }
202
549
  );
203
550
  }
204
551
 
205
- function openCompose() {
206
- if (!mailbox?.canSend) return;
207
- setForwardedMessage(undefined);
208
- setComposerMailboxId(mailbox.id);
552
+ /**
553
+ * Opens the conversation after the open one, which ends the loaded list:
554
+ * its next page loads first (a phone's reader hides the list and its
555
+ * "Load older" button). Nothing opens if the person moved on meanwhile.
556
+ */
557
+ async function openNextAfterLoading() {
558
+ const actedOn = conversationId;
559
+ const loaded = await conversationsQuery.fetchNextPage();
560
+
561
+ const list = loaded.data?.pages.flatMap((page) => page.conversations) ?? [];
562
+
563
+ const index = list.findIndex((item) => item.conversationId === actedOn);
564
+ const next = list[index === -1 ? position.nextIndex(list) : index + 1];
565
+
566
+ if (!next || live.current.route.conversationId !== actedOn) {
567
+ return;
568
+ }
569
+
570
+ if (next.draftId === next.conversationId) showComposer(next.conversationId);
571
+ else {
572
+ showConversation(
573
+ next.conversationId,
574
+ "replace",
575
+ folder,
576
+ next.searchMatch
577
+ );
578
+ }
209
579
  }
210
580
 
211
- function openForward(message: MessageDetail) {
581
+ async function openCompose(forwarded?: MessageDetail) {
212
582
  if (!mailbox?.canSend) return;
213
- setForwardedMessage(message);
214
- setComposerMailboxId(mailbox.id);
583
+ const previous = live.current.compose;
584
+ const ready = composerNavigation.canReplaceWindow();
585
+
586
+ if (
587
+ ready !== true &&
588
+ (!(await ready) ||
589
+ !live.current.mounted ||
590
+ live.current.compose !== previous ||
591
+ live.current.route.mailboxId !== mailbox.id)
592
+ ) {
593
+ return;
594
+ }
595
+
596
+ const draftId = newDraftId();
597
+ setStarted({ draftId, forwarded, shown: false });
598
+ showComposer(`new-${draftId}`);
215
599
  }
216
600
 
217
- function closeComposer() {
218
- setComposerMailboxId(null);
219
- setForwardedMessage(undefined);
601
+ /** `ended` when the composer's draft was sent or discarded; closed, it stays in Drafts to open again. */
602
+ function closeComposer(ended = false) {
603
+ if (ended && composer) {
604
+ const { draftId } = composer;
605
+ setClosedDraftIds((ids) => new Set(ids).add(draftId));
606
+ }
607
+
608
+ composerNavigation.register("new", null);
609
+ hideComposer();
220
610
  }
221
611
 
222
- // Reads the live URL: a mutation can settle after the user already moved to
223
- // another folder, and the captured `folder` would drag them back.
224
- function closeConversation() {
225
- const current = parseMailPath(window.location.pathname);
612
+ /**
613
+ * Back to the list the open conversation is in, as a new entry (Back
614
+ * opens it again), or, `replace`, in its place, for one that left it.
615
+ * Reads where the screen is now: a mutation can settle after the person
616
+ * moved to another folder, and the captured `folder` would drag them
617
+ * back. Given the conversation an action was on, closes only that one,
618
+ * never one the person opened while it ran. Focus, which was in the
619
+ * reader, goes to the first of `focus`'s rows listed (by default the one
620
+ * that was open), else the list.
621
+ */
622
+ function closeConversation(
623
+ actedOn?: string | null,
624
+ replace = false,
625
+ focus?: readonly string[]
626
+ ) {
627
+ const current = live.current.route;
628
+
629
+ if (!current.mailboxId || !current.conversationId) return;
226
630
 
227
- if (!current?.conversationId) return;
228
- navigateRoute(mailPath(current.mailboxId, current.folder));
631
+ if (actedOn !== undefined && current.conversationId !== actedOn) return;
632
+ focusListAfter(focus ?? [current.conversationId]);
633
+ void navigate(withComposer(mailPath(current.mailboxId, current.folder)), {
634
+ replace,
635
+ });
229
636
  }
230
637
 
638
+ /**
639
+ * The one way the view follows this person's own change of
640
+ * conversations (`places`, as the server says where they went): the open
641
+ * one, if it left where it was listed, closes; or, when its mail went
642
+ * into another conversation (out of Spam, rejoining a thread), that one
643
+ * takes its place. Reads where the screen is now, so one opened meanwhile
644
+ * stays open.
645
+ */
646
+ function followOwnChange(places: readonly ConversationPlace[]) {
647
+ const open = live.current.route.conversationId;
648
+ const place = places.find((item) => item.from === open && item.left);
649
+
650
+ if (!open || !place) return;
651
+
652
+ if (place.folder && place.conversationId !== place.from) {
653
+ showConversation(place.conversationId, "replace", place.folder);
654
+ } else {
655
+ // Focus goes on to the next row that stays, as it would in the list.
656
+ const leaving = new Set(
657
+ places.flatMap((item) => (item.left ? [item.from] : []))
658
+ );
659
+
660
+ closeConversation(open, true, rowsAround(listed.current, leaving));
661
+ }
662
+ }
663
+
664
+ /** Whether the person is still on the list `route` showed, with no conversation open. */
665
+ function stillOnList(list: MailRoute) {
666
+ const now = live.current.route;
667
+
668
+ return (
669
+ !now.conversationId &&
670
+ now.mailboxId === list.mailboxId &&
671
+ // A list's path names Inbox by leaving the folder out.
672
+ (now.folder ?? "inbox") === (list.folder ?? "inbox")
673
+ );
674
+ }
675
+
676
+ /**
677
+ * Follows an own change before the server answers, as `followOwnChange`
678
+ * would with the places it is expected to answer: the open conversation
679
+ * closes at once. The returned function follows the answer where it
680
+ * differs, while the person is still on the list it closed to: a failed
681
+ * change, or one that left the conversation where it was, opens it
682
+ * again; mail that rejoined a thread opens that thread.
683
+ */
684
+ function followChange(expected: readonly ConversationPlace[]) {
685
+ const { route: before } = live.current;
686
+ const open = before.conversationId;
687
+ const closing = expected.some((item) => item.from === open && item.left);
688
+
689
+ if (!open || !closing) {
690
+ return (actual: readonly ConversationPlace[] | null) => {
691
+ if (actual) followOwnChange(actual);
692
+ };
693
+ }
694
+
695
+ followOwnChange(expected);
696
+
697
+ return (actual: readonly ConversationPlace[] | null) => {
698
+ if (!stillOnList(before)) return;
699
+ const place = actual?.find((item) => item.from === open);
700
+
701
+ if (!actual || place?.left === false) {
702
+ showConversation(open, "replace", before.folder);
703
+ } else if (place?.folder && place.conversationId !== open) {
704
+ showConversation(place.conversationId, "replace", place.folder);
705
+ }
706
+ };
707
+ }
708
+
709
+ /** Moves the open conversation, with Undo. */
231
710
  function mutateConversation(
232
711
  input: {
233
712
  mailboxState?: "active" | "archive" | "trash";
234
713
  folderId?: string | null;
235
714
  },
236
- returnToList = false,
237
- successMessage?: string
715
+ successMessage: string
238
716
  ) {
239
- if (!conversationId || !mailbox) return;
240
- sharedConversationAction.mutate(
717
+ if (!conversationId) return;
718
+ void conversationActions.apply(
719
+ [conversationId],
720
+ { type: "update", update: input },
241
721
  {
242
- mailboxId: mailbox.id,
243
- sourceFolderId: folder,
244
- conversationIds: [conversationId],
245
- action: { type: "update", update: input },
722
+ done: () => successMessage,
723
+ unchanged: "Conversation was not changed because its folder changed.",
246
724
  },
247
- {
248
- onSuccess: ({ updatedCount }) => {
249
- if (!updatedCount) {
250
- toast.warning(
251
- "Conversation was not changed because its folder changed."
252
- );
253
-
254
- return;
255
- }
256
-
257
- if (successMessage) toast.success(successMessage);
258
-
259
- if (returnToList) closeConversation();
260
- },
261
- onError: (error) => toast.error(error.message),
262
- }
725
+ { undoable: true }
263
726
  );
264
727
  }
265
728
 
266
729
  function deleteConversationPermanently() {
267
- if (!conversationId || !mailbox) return;
268
- sharedConversationAction.mutate(
730
+ if (!conversationId) return;
731
+ void conversationActions.apply(
732
+ [conversationId],
733
+ { type: "delete_permanently" },
269
734
  {
270
- mailboxId: mailbox.id,
271
- sourceFolderId: folder,
272
- conversationIds: [conversationId],
273
- action: { type: "delete_permanently" },
274
- },
275
- {
276
- onSuccess: ({ updatedCount }) => {
277
- if (!updatedCount) {
278
- toast.warning(
279
- "Conversation was not deleted because its folder changed."
280
- );
281
-
282
- return;
283
- }
284
-
285
- toast.success("Conversation deleted permanently");
286
- closeConversation();
287
- },
288
- onError: (error) => toast.error(error.message),
735
+ done: () => "Conversation deleted permanently",
736
+ unchanged: "Conversation was not deleted because its folder changed.",
289
737
  }
290
738
  );
291
739
  }
292
740
 
293
- async function changeConversationRead(isRead: boolean, returnToList = false) {
294
- if (!conversationId || !mailbox) return;
295
-
296
- try {
297
- const { updatedCount } = await sharedConversationAction.mutateAsync({
298
- mailboxId: mailbox.id,
299
- sourceFolderId: folder,
300
- conversationIds: [conversationId],
301
- action: { type: "read", isRead },
302
- });
741
+ function changeConversationRead(isRead: boolean) {
742
+ if (!conversationId) return Promise.resolve(null);
303
743
 
304
- if (!updatedCount) {
305
- toast.warning("Conversation no longer contains incoming messages.");
744
+ return conversationActions.apply(
745
+ [conversationId],
746
+ { type: "read", isRead },
747
+ { unchanged: "Conversation no longer contains incoming messages." }
748
+ );
749
+ }
306
750
 
307
- return;
751
+ // Marked unread, the conversation is left for the list at once, as it
752
+ // would be read again if it stayed open: a new entry, so Back opens it.
753
+ // It opens again if the change fails while the list is still on screen.
754
+ function markConversationUnread() {
755
+ const actedOn = conversationId;
756
+ const { route: before } = live.current;
757
+
758
+ if (!actedOn) return;
759
+ closeConversation(actedOn);
760
+ void changeConversationRead(false).then((result) => {
761
+ if (result === null && stillOnList(before)) {
762
+ showConversation(actedOn, "replace", before.folder);
308
763
  }
309
-
310
- if (returnToList) closeConversation();
311
- } catch (error) {
312
- toast.error(
313
- error instanceof Error ? error.message : "Could not update read state"
314
- );
315
- }
764
+ });
316
765
  }
317
766
 
318
767
  return {
@@ -330,87 +779,181 @@ export function useMailController(
330
779
  conversations,
331
780
  conversation,
332
781
  conversationMessages,
782
+ matchId,
783
+ matchQuoted: quote,
784
+ pinnedId: pinned?.id,
785
+ position,
333
786
  displayedConversationCount,
334
787
  selection,
335
788
  search,
336
789
  debouncedSearch,
337
790
  unreadOnly,
338
- composeOpen,
339
- forwardedMessage,
340
- sharedActionPending: sharedConversationAction.isPending,
791
+ registerComposerLeaveCheck: composerNavigation.register,
792
+ composer,
793
+ composerDiscarded: composer !== null && composer.draftId === listDiscarded,
341
794
  listLoading: !listError && conversationsQuery.isPending,
795
+ /** The list shown is the previous one while this one loads. */
796
+ listStale:
797
+ search.trim() !== debouncedSearch || conversationsQuery.isPlaceholderData,
342
798
  listError,
799
+ refreshError,
343
800
  retryList() {
344
- void (mailboxQuery.isError
345
- ? mailboxQuery.refetch()
346
- : foldersQuery.isError
347
- ? foldersQuery.refetch()
801
+ void (blockingQuery
802
+ ? blockingQuery.refetch()
803
+ : conversationsQuery.isFetchNextPageError
804
+ ? conversationsQuery.fetchNextPage()
348
805
  : conversationsQuery.refetch());
349
806
  },
350
807
  setSearch(value: string) {
351
- setSearch(value);
808
+ void setParams({ q: value });
352
809
  selection.exit();
353
810
  },
354
811
  toggleUnreadOnly() {
355
812
  selection.exit();
356
- setUnreadOnly((current) => !current);
813
+ setUnreadFilter((current) => !current);
357
814
  },
358
815
  selectFolder(next: Folder) {
816
+ if (!mailbox) return;
359
817
  selection.exit();
360
- navigate({ folder: next, conversation: null });
818
+ openList(mailbox.id, next);
361
819
  },
362
- selectMailbox(id: string) {
363
- closeComposer();
820
+ /**
821
+ * The one way to another mailbox, from the sidebar, the rail or the
822
+ * phone's sheet: the folder open here when it has one too, else its
823
+ * Inbox. `replace` swaps the current history entry (the sheet's).
824
+ */
825
+ switchMailbox(id: string, replace = false) {
364
826
  selection.exit();
365
- navigate({ mailbox: id, folder: "inbox", conversation: null });
827
+ const known = queryClient.getQueryData(mailboxFolders(id).queryKey);
828
+ // A cold switch follows the URL immediately. resolveMailLocation checks
829
+ // the requested folder when its list arrives, just as for a direct link.
830
+ openList(
831
+ id,
832
+ known ? folderAfterMailboxSwitch(folder, known.folders) : folder,
833
+ replace
834
+ );
366
835
  },
367
836
  /**
368
837
  * A folder of any mailbox, e.g. from an expanded mailbox in the sidebar;
369
838
  * `replace` swaps the current history entry instead of adding one.
370
839
  */
371
840
  openFolder(nextMailboxId: string, next: Folder, replace = false) {
372
- if (nextMailboxId !== mailbox?.id) closeComposer();
373
841
  selection.exit();
374
- navigate(
375
- { mailbox: nextMailboxId, folder: next, conversation: null },
376
- replace
377
- );
842
+ openList(nextMailboxId, next, replace);
843
+ },
844
+ listIntent(targetMailboxId: string | undefined, next?: Folder) {
845
+ if (!targetMailboxId) return intent(undefined);
846
+
847
+ return intent((client) => {
848
+ if (targetMailboxId !== activeMailboxId) {
849
+ return prefetchMailboxSwitch(client, targetMailboxId, folder, next);
850
+ }
851
+
852
+ const target = next ?? folder;
853
+
854
+ return client.prefetchInfiniteQuery(
855
+ conversationList(
856
+ targetMailboxId,
857
+ target,
858
+ debouncedSearch,
859
+ unreadIn(target)
860
+ )
861
+ );
862
+ });
378
863
  },
379
864
  /** Starts loading a conversation the person is likely to open next. */
380
865
  prefetchConversation(id: string) {
381
- prefetchConversation(location.mailboxId, id);
382
- },
383
- openConversation(id: string, folderOverride?: Folder) {
384
- // An absent folder keeps the current one.
385
- navigate({ conversation: id, folder: folderOverride });
866
+ const row = listedRow(id);
867
+
868
+ if (row?.draftId !== id) {
869
+ prefetchConversation(location.mailboxId, id, row?.searchMatch?.id);
870
+ }
386
871
  },
387
- closeConversation() {
388
- navigate({ conversation: null });
872
+ /**
873
+ * Opens a conversation, or a draft's composer: from the list as an entry
874
+ * of its own; `replace` in the place of the one open (Next, Previous).
875
+ */
876
+ openConversation(
877
+ id: string,
878
+ history: "push" | "replace" = "push",
879
+ folderOverride?: Folder
880
+ ) {
881
+ const row = listedRow(id);
882
+
883
+ if (row?.draftId === id) showComposer(id);
884
+ else {
885
+ showConversation(
886
+ id,
887
+ history,
888
+ folderOverride,
889
+ folderOverride ? undefined : row?.searchMatch
890
+ );
891
+ }
389
892
  },
893
+ openNextAfterLoading: () => void openNextAfterLoading(),
894
+ // The one open when they settle: sender actions close it.
895
+ closeConversation: () => closeConversation(),
896
+ followOwnChange,
897
+ followChange,
390
898
  openAdministration() {
391
- navigateRoute("/admin");
899
+ void navigate("/admin");
392
900
  },
393
901
  openSettings() {
394
- navigateRoute("/settings");
902
+ void navigate("/settings");
395
903
  },
396
- openCompose,
397
- openForward,
904
+ openCompose: () => openCompose(),
905
+ openForward: (message: MessageDetail) => openCompose(message),
398
906
  closeComposer,
399
- archive: () => mutateConversation({ mailboxState: "archive" }, true),
400
- restore: () => mutateConversation({ mailboxState: "active" }, true),
401
- trash: () => mutateConversation({ mailboxState: "trash" }, true),
907
+ archive: () =>
908
+ mutateConversation({ mailboxState: "archive" }, "Conversation archived"),
909
+ restore: () =>
910
+ mutateConversation({ mailboxState: "active" }, "Conversation restored"),
911
+ trash: () =>
912
+ mutateConversation(
913
+ { mailboxState: "trash" },
914
+ "Conversation moved to Trash"
915
+ ),
402
916
  /** Moves the open conversation to a custom folder, or back to Inbox with null. */
403
917
  moveToFolder: (target: { id: string | null; name: string }) =>
404
918
  mutateConversation(
405
919
  { mailboxState: "active", folderId: target.id },
406
- true,
407
920
  `Moved to ${target.name}`
408
921
  ),
409
- /** Reporting spam fits active and archived mail people received. */
410
- canReport:
411
- (conversation?.mailboxState === "active" ||
412
- conversation?.mailboxState === "archive") &&
413
- activeFolder?.systemType !== "sent",
922
+ /** Report spam of the open conversation's received mail. */
923
+ reportSpam() {
924
+ if (!conversationId) return;
925
+ void conversationActions.apply(
926
+ [conversationId],
927
+ { type: "report" },
928
+ {
929
+ done: () => "Reported as spam",
930
+ unchanged: "There was no mail to report here any more",
931
+ },
932
+ { undoable: true }
933
+ );
934
+ },
935
+ /** Not spam for the open conversation's received mail: it also trusts the senders and teaches the classifier. */
936
+ notSpam() {
937
+ if (!conversationId) return;
938
+ void conversationActions.apply(
939
+ [conversationId],
940
+ { type: "not_spam" },
941
+ {
942
+ done: () =>
943
+ "Moved to Inbox. Its senders' mail won't be treated as spam.",
944
+ rejoined:
945
+ "Moved back to its conversation. Its senders' mail won't be treated as spam.",
946
+ unchanged: "It isn't in Spam any more",
947
+ },
948
+ { undoable: true }
949
+ );
950
+ },
951
+ /** Reporting spam fits received mail in the Inbox or Archive. */
952
+ canReport: Boolean(
953
+ conversation && conversationActionsIn(actionFolder(openFolder)).report
954
+ ),
955
+ /** The folder the open conversation is in, which its actions act in. */
956
+ openConversationFolder: openFolder,
414
957
  /** Only from Trash, and only for people who can send from the mailbox. */
415
958
  deletePermanently:
416
959
  conversation?.mailboxState === "trash" && mailbox?.canSend
@@ -420,8 +963,6 @@ export function useMailController(
420
963
  (conversation?.unreadCount ?? 0) > 0
421
964
  ? () => void changeConversationRead(true)
422
965
  : undefined,
423
- markUnread: conversation?.hasIncoming
424
- ? () => void changeConversationRead(false, true)
425
- : undefined,
966
+ markUnread: conversation?.hasIncoming ? markConversationUnread : undefined,
426
967
  };
427
968
  }