@open-workspace/email 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -6,7 +6,13 @@ import type {
6
6
  } from "@tanstack/react-query";
7
7
  import { z } from "zod";
8
8
 
9
- import type { Mailbox, MailFolder } from "./types";
9
+ import {
10
+ conversationFolder,
11
+ DRAFTS_FOLDER_ID,
12
+ } from "../../shared/folder-order";
13
+ import type { MailboxState } from "../../shared/mail";
14
+ import { newerThan } from "./conversation-order";
15
+ import type { ConversationSummary, Mailbox, MailFolder } from "./types";
10
16
 
11
17
  /**
12
18
  * Mail data in React Query carries the mailbox change counter it reflects
@@ -44,9 +50,11 @@ const pagesVersions = z.object({
44
50
  pages: z.array(z.object({ version: z.number() })),
45
51
  });
46
52
 
53
+ /** How long a change of this person's waits for its realtime echo before the mailbox is read again anyway. */
54
+ const ECHO_WAIT_MS = 3000;
55
+
47
56
  type MailRefreshState = {
48
57
  timer: ReturnType<typeof setTimeout> | null;
49
- running: boolean;
50
58
  /** Mailboxes whose data is refreshed regardless of versions. */
51
59
  forced: Set<string>;
52
60
  /** Mailboxes to compare with their announced version. */
@@ -55,6 +63,8 @@ type MailRefreshState = {
55
63
  announced: Map<string, number>;
56
64
  /** Queries already refetched for an announced version, so a refetch that comes back older does not loop. */
57
65
  refetchedFor: Map<string, number>;
66
+ /** Own changes answered before their echo: the mailbox is read again if none comes. */
67
+ echoWaits: Map<string, ReturnType<typeof setTimeout>>;
58
68
  };
59
69
 
60
70
  const refreshStates = new WeakMap<QueryClient, MailRefreshState>();
@@ -65,11 +75,11 @@ function refreshState(client: QueryClient) {
65
75
  if (!state) {
66
76
  state = {
67
77
  timer: null,
68
- running: false,
69
78
  forced: new Set(),
70
79
  checked: new Set(),
71
80
  announced: new Map(),
72
81
  refetchedFor: new Map(),
82
+ echoWaits: new Map(),
73
83
  };
74
84
  refreshStates.set(client, state);
75
85
  }
@@ -77,8 +87,15 @@ function refreshState(client: QueryClient) {
77
87
  return state;
78
88
  }
79
89
 
90
+ /**
91
+ * The mutation key of this person's changes of a mailbox that the cache
92
+ * shows at once (`beginOwnChange`).
93
+ */
94
+ export const ownChangeKey = (mailboxId: string | undefined) =>
95
+ ["mail", mailboxId] as const;
96
+
80
97
  /** The oldest version a query's data reflects for `mailboxId`; undefined without data. */
81
- function queryVersion(query: Query, mailboxId: string): number | undefined {
98
+ function queryVersion(query: Query, mailboxId: string) {
82
99
  const [group] = query.queryKey;
83
100
  const { data } = query.state;
84
101
 
@@ -145,11 +162,13 @@ async function refreshMailboxQueries(
145
162
 
146
163
  if (version === undefined || version >= announced) continue;
147
164
 
148
- if ((state.refetchedFor.get(query.queryHash) ?? -1) >= announced) {
165
+ const refreshKey = `${mailboxId}\0${query.queryHash}`;
166
+
167
+ if ((state.refetchedFor.get(refreshKey) ?? -1) >= announced) {
149
168
  continue;
150
169
  }
151
170
 
152
- state.refetchedFor.set(query.queryHash, announced);
171
+ state.refetchedFor.set(refreshKey, announced);
153
172
  stale.set(query.queryHash, query.queryKey);
154
173
  }
155
174
  }
@@ -169,36 +188,49 @@ async function refreshMailboxQueries(
169
188
  }
170
189
  }
171
190
 
191
+ /**
192
+ * Reads mailboxes again shortly. A mailbox with an own change in flight
193
+ * waits until the last one settles (`ownChangeSettled`): data read
194
+ * meanwhile could predate the change and bring a row it took away back for
195
+ * a moment. A refresh while another one reads cancels that read
196
+ * (`invalidateQueries` refetches with `cancelRefetch`), so an older
197
+ * response never overwrites a newer one.
198
+ */
172
199
  function schedule(client: QueryClient, state: MailRefreshState) {
173
- if (state.timer || state.running) return;
200
+ if (state.timer) return;
174
201
  state.timer = setTimeout(() => {
175
202
  state.timer = null;
176
- state.running = true;
177
- const forced = [...state.forced];
203
+
204
+ const ready = (mailboxId: string) =>
205
+ !client.isMutating({ mutationKey: ownChangeKey(mailboxId) });
206
+
207
+ const forced = [...state.forced].filter(ready);
178
208
 
179
209
  const checked = [...state.checked].filter(
180
- (mailboxId) => !state.forced.has(mailboxId)
210
+ (mailboxId) => ready(mailboxId) && !state.forced.has(mailboxId)
181
211
  );
182
212
 
183
- state.forced.clear();
184
- state.checked.clear();
213
+ for (const mailboxId of forced) state.forced.delete(mailboxId);
185
214
 
186
- void refreshMailboxQueries(client, state, forced, checked)
187
- .catch((error) => {
188
- console.error("Could not refresh mail data", error);
189
- })
190
- .finally(() => {
191
- state.running = false;
215
+ for (const mailboxId of checked) state.checked.delete(mailboxId);
192
216
 
193
- // Events received during the request are drained only after it ends,
194
- // so an older response can never overwrite a newer refresh.
195
- if (state.forced.size || state.checked.size) schedule(client, state);
196
- });
217
+ if (!forced.length && !checked.length) return;
218
+
219
+ void refreshMailboxQueries(client, state, forced, checked).catch(
220
+ (error) => {
221
+ console.error("Could not refresh mail data", error);
222
+ }
223
+ );
197
224
  }, 100);
198
225
  }
199
226
 
200
- /** Refetches all of a mailbox's mail data shortly, e.g. after an action changed it. */
201
- export function scheduleMailboxRefresh(client: QueryClient, mailboxId: string) {
227
+ /**
228
+ * Follows a change of a mailbox that has no optimistic form here (a sent
229
+ * message, a draft, a folder renamed): all of its mail data is read again
230
+ * shortly. A bare invalidation of some queries would leave others (counts,
231
+ * a list nobody shows now) behind.
232
+ */
233
+ export function applyMailboxChange(client: QueryClient, mailboxId: string) {
202
234
  const state = refreshState(client);
203
235
  state.forced.add(mailboxId);
204
236
  schedule(client, state);
@@ -211,10 +243,16 @@ export function noteMailboxVersion(
211
243
  version: number
212
244
  ) {
213
245
  const state = refreshState(client);
214
- state.announced.set(
215
- mailboxId,
216
- Math.max(state.announced.get(mailboxId) ?? -1, version)
217
- );
246
+ const known = state.announced.get(mailboxId);
247
+
248
+ // Something changed since an own change was answered: its echo, or a
249
+ // later change, whose check reads the mailbox after it anyway.
250
+ if (known === undefined || version > known) {
251
+ clearTimeout(state.echoWaits.get(mailboxId));
252
+ state.echoWaits.delete(mailboxId);
253
+ }
254
+
255
+ state.announced.set(mailboxId, Math.max(known ?? -1, version));
218
256
  state.checked.add(mailboxId);
219
257
  schedule(client, state);
220
258
  }
@@ -260,11 +298,12 @@ export function watchMailboxVersions(client: QueryClient) {
260
298
  }
261
299
 
262
300
  type ConversationPage = Versioned & {
263
- mailboxState: string;
301
+ mailboxState: MailboxState;
264
302
  folderId: string | null;
265
303
  hasIncoming: boolean;
266
304
  hasOutgoing: boolean;
267
305
  unreadCount: number;
306
+ nextCursor: string | null;
268
307
  messages: {
269
308
  id: string;
270
309
  direction: string;
@@ -274,19 +313,100 @@ type ConversationPage = Versioned & {
274
313
  };
275
314
 
276
315
  type ConversationListPage = Versioned & {
277
- conversations: {
278
- conversationId: string;
279
- unreadCount: number;
280
- isUnread: boolean;
281
- }[];
316
+ conversations: ConversationSummary[];
317
+ nextCursor: string | null;
282
318
  };
283
319
 
284
- function folderContains(folder: MailFolder, conversation: ConversationPage) {
285
- const inInbox =
286
- conversation.hasIncoming && conversation.mailboxState === "active";
320
+ type ConversationUpdate = {
321
+ mailboxState?: MailboxState;
322
+ folderId?: string | null;
323
+ };
324
+
325
+ type Reader = { userId: string; name: string };
326
+
327
+ /**
328
+ * A change this person makes to conversations, as the cache shows it the
329
+ * moment they make it (`beginOwnChange`):
330
+ * - `move`: out of `sourceFolderId` (where they were acted on) by `update`,
331
+ * as the bulk update does; into Spam is Report spam, out of it Not spam;
332
+ * - `delete`: deleted for good;
333
+ * - `empty`: everything in Trash or Spam deleted for good;
334
+ * - `read`: whole conversations read or unread;
335
+ * - `message-read`: one message read or unread (opening it reads it).
336
+ */
337
+ export type OwnChange =
338
+ | {
339
+ type: "move";
340
+ sourceFolderId: string;
341
+ conversationIds: readonly string[];
342
+ update: ConversationUpdate;
343
+ undoSnapshot?: UndoSnapshot;
344
+ }
345
+ | { type: "delete"; conversationIds: readonly string[] }
346
+ | { type: "empty"; folder: "trash" | "spam" }
347
+ | {
348
+ type: "read";
349
+ sourceFolderId: string;
350
+ conversationIds: readonly string[];
351
+ isRead: boolean;
352
+ reader?: Reader;
353
+ }
354
+ | {
355
+ type: "message-read";
356
+ conversationId: string;
357
+ messageId: string;
358
+ isRead: boolean;
359
+ reader?: Reader;
360
+ };
361
+
362
+ export type UndoSnapshot = ReadonlyMap<string, ConversationSummary>;
363
+
364
+ /**
365
+ * What the cache knows of where a conversation is; a field it can't tell
366
+ * is undefined, and so is whether a folder lists it (`lists`).
367
+ */
368
+ type Place = {
369
+ mailboxState?: MailboxState;
370
+ folderId?: string | null;
371
+ hasIncoming?: boolean;
372
+ hasOutgoing?: boolean;
373
+ /** Deleted for good. */
374
+ gone?: boolean;
375
+ /** Listed in Sent, so not in Trash, whatever its state. */
376
+ inSent?: boolean;
377
+ };
378
+
379
+ type Maybe = boolean | undefined;
380
+
381
+ function all(...values: Maybe[]) {
382
+ if (values.includes(false)) return false;
383
+
384
+ return values.includes(undefined) ? undefined : true;
385
+ }
386
+
387
+ function is<T>(value: T | undefined, expected: T) {
388
+ return value === undefined ? undefined : value === expected;
389
+ }
390
+
391
+ type FolderKind = Pick<MailFolder, "id" | "kind" | "systemType">;
392
+
393
+ const SYSTEM_FOLDERS: readonly NonNullable<MailFolder["systemType"]>[] = [
394
+ "inbox",
395
+ "sent",
396
+ "archive",
397
+ "spam",
398
+ "trash",
399
+ DRAFTS_FOLDER_ID,
400
+ ];
401
+
402
+ /** Whether `folder` lists a conversation at `place`, as the server's folder predicates say. */
403
+ function lists(folder: FolderKind, place: Place) {
404
+ if (place.gone) return false;
405
+
406
+ const inInbox = all(is(place.mailboxState, "active"), place.hasIncoming);
287
407
 
288
408
  if (folder.kind === "custom") {
289
- return inInbox && conversation.folderId === folder.id;
409
+ return all(inInbox, is(place.folderId, folder.id));
290
410
  }
291
411
 
292
412
  switch (folder.systemType) {
@@ -295,13 +415,23 @@ function folderContains(folder: MailFolder, conversation: ConversationPage) {
295
415
  }
296
416
 
297
417
  case "sent": {
298
- return conversation.hasOutgoing && conversation.mailboxState !== "trash";
418
+ return all(
419
+ place.hasOutgoing,
420
+ place.mailboxState === undefined
421
+ ? undefined
422
+ : place.mailboxState !== "trash"
423
+ );
299
424
  }
300
425
 
301
- case "archive":
302
- case "spam":
303
426
  case "trash": {
304
- return conversation.mailboxState === folder.systemType;
427
+ return place.inSent && place.mailboxState === undefined
428
+ ? false
429
+ : is(place.mailboxState, "trash");
430
+ }
431
+
432
+ case "archive":
433
+ case "spam": {
434
+ return is(place.mailboxState, folder.systemType);
305
435
  }
306
436
 
307
437
  default: {
@@ -310,177 +440,959 @@ function folderContains(folder: MailFolder, conversation: ConversationPage) {
310
440
  }
311
441
  }
312
442
 
443
+ /** A folder by id, from the cached folders or, without them, from the id. */
444
+ function folderKind(client: QueryClient, mailboxId: string, folderId: string) {
445
+ const cached = client
446
+ .getQueryData<FoldersData>(["folders", mailboxId])
447
+ ?.folders.find((folder) => folder.id === folderId);
448
+
449
+ if (cached) return cached satisfies FolderKind;
450
+ const systemType = SYSTEM_FOLDERS.find((type) => type === folderId);
451
+
452
+ return systemType
453
+ ? ({ id: folderId, kind: "system", systemType } satisfies FolderKind)
454
+ : ({ id: folderId, kind: "custom", systemType: null } satisfies FolderKind);
455
+ }
456
+
457
+ type ListQuery = {
458
+ queryKey: QueryKey;
459
+ folder: FolderKind;
460
+ search: string;
461
+ unreadOnly: boolean;
462
+ data: Paged<ConversationListPage>;
463
+ };
464
+
465
+ /** A list's key (`conversationsQuery`): mailbox, folder, search, unread only. */
466
+ const conversationListKey = z
467
+ .tuple([
468
+ z.literal("conversations"),
469
+ z.string(),
470
+ z.string(),
471
+ z.string(),
472
+ z.boolean(),
473
+ ])
474
+ .transform((key) => ({
475
+ folderId: key[2],
476
+ search: key[3],
477
+ unreadOnly: key[4],
478
+ }));
479
+
480
+ /** The mailbox's cached conversation lists (not Drafts, whose rows are drafts). */
481
+ function cachedLists(client: QueryClient, mailboxId: string) {
482
+ return client
483
+ .getQueriesData<Paged<ConversationListPage>>({
484
+ queryKey: ["conversations", mailboxId],
485
+ })
486
+ .flatMap(([queryKey, data]) => {
487
+ const key = conversationListKey.safeParse(queryKey);
488
+
489
+ if (!data || !key.success) return [];
490
+ const { folderId, search, unreadOnly } = key.data;
491
+
492
+ if (folderId === DRAFTS_FOLDER_ID) return [];
493
+
494
+ return [
495
+ {
496
+ queryKey,
497
+ folder: folderKind(client, mailboxId, folderId),
498
+ search,
499
+ unreadOnly,
500
+ data,
501
+ } satisfies ListQuery,
502
+ ];
503
+ });
504
+ }
505
+
506
+ function rowIn(pages: ConversationListPage[], conversationId: string) {
507
+ for (const page of pages) {
508
+ const row = page.conversations.find(
509
+ (item) => item.conversationId === conversationId
510
+ );
511
+
512
+ if (row) return row;
513
+ }
514
+
515
+ return undefined;
516
+ }
517
+
518
+ function conversationHead(
519
+ client: QueryClient,
520
+ mailboxId: string,
521
+ conversationId: string
522
+ ) {
523
+ return client.getQueryData<Paged<ConversationPage>>([
524
+ "conversation",
525
+ mailboxId,
526
+ conversationId,
527
+ ])?.pages[0];
528
+ }
529
+
313
530
  /**
314
- * Applies this person's own read change to the cache instead of refetching:
315
- * every query that reflected the version just before the change (`version`
316
- * − 1) gets the change and moves to `version`, so the realtime echo of it
317
- * refetches nothing. Data at any other version is left to the version check.
318
- * Returns false when the message's previous state is not known that exactly;
319
- * the caller then refreshes the mailbox.
531
+ * Where a conversation acted on in `sourceFolderId` is, as far as the cache
532
+ * tells: its open conversation or current list row, else its source folder.
320
533
  */
321
- export function applyOwnReadChange(
534
+ function placeOf(
322
535
  client: QueryClient,
323
- input: {
324
- mailboxId: string;
325
- conversationId: string;
326
- messageId: string;
327
- isRead: boolean;
328
- version: number;
329
- reader: { userId: string; name: string };
536
+ mailboxId: string,
537
+ sourceFolderId: string | undefined,
538
+ conversationId: string,
539
+ fallbackRow?: ConversationSummary
540
+ ) {
541
+ const cachedRow = cachedLists(client, mailboxId)
542
+ .map((list) => rowIn(list.data.pages, conversationId))
543
+ .find((item) => item !== undefined);
544
+
545
+ const row = cachedRow ?? fallbackRow;
546
+
547
+ const current =
548
+ conversationHead(client, mailboxId, conversationId) ??
549
+ (cachedRow?.draftId === null ? cachedRow : undefined);
550
+
551
+ if (current) {
552
+ const { mailboxState, folderId, hasIncoming, hasOutgoing } = current;
553
+
554
+ return { place: { mailboxState, folderId, hasIncoming, hasOutgoing }, row };
330
555
  }
556
+
557
+ // Undo can supply a row from before the move. Only its message directions
558
+ // still describe it; its current location comes from the undo's source.
559
+ const place: Place =
560
+ row?.draftId === null
561
+ ? { hasIncoming: row.hasIncoming, hasOutgoing: row.hasOutgoing }
562
+ : {};
563
+
564
+ if (sourceFolderId) {
565
+ const folder = folderKind(client, mailboxId, sourceFolderId);
566
+
567
+ if (folder.kind === "custom") {
568
+ Object.assign(place, {
569
+ mailboxState: "active",
570
+ folderId: folder.id,
571
+ hasIncoming: true,
572
+ });
573
+ } else if (folder.systemType === "inbox") {
574
+ Object.assign(place, { mailboxState: "active", hasIncoming: true });
575
+ } else if (folder.systemType === "sent") {
576
+ Object.assign(place, { hasOutgoing: true, inSent: true });
577
+ } else if (
578
+ folder.systemType === "archive" ||
579
+ folder.systemType === "spam" ||
580
+ folder.systemType === "trash"
581
+ ) {
582
+ place.mailboxState = folder.systemType;
583
+ }
584
+ }
585
+
586
+ return { place, row };
587
+ }
588
+
589
+ /** Where a conversation at `before` is after `update`, as `placeConversations` files it. */
590
+ function placeAfter(before: Place, update: ConversationUpdate, undo: boolean) {
591
+ const state = update.mailboxState ?? (update.folderId ? "active" : undefined);
592
+
593
+ const intoInbox =
594
+ update.folderId !== undefined &&
595
+ (state === undefined || state === "active");
596
+
597
+ // Filing in the Inbox, or Spam, takes received mail only.
598
+ if ((intoInbox || state === "spam") && before.hasIncoming === false) {
599
+ return before;
600
+ }
601
+
602
+ return {
603
+ ...before,
604
+ mailboxState: state ?? before.mailboxState,
605
+ folderId:
606
+ !undo && state && state !== "active"
607
+ ? before.folderId
608
+ : update.folderId === undefined
609
+ ? before.folderId
610
+ : update.folderId,
611
+ };
612
+ }
613
+
614
+ /** The folder a place is listed in, as places name it (`conversationFolder`); undefined when unknown. */
615
+ function placeFolder(place: Place) {
616
+ if (place.gone) return null;
617
+
618
+ if (place.mailboxState === undefined) return undefined;
619
+
620
+ return conversationFolder({
621
+ mailboxState: place.mailboxState,
622
+ folderId: place.folderId ?? null,
623
+ hasIncoming: place.hasIncoming,
624
+ });
625
+ }
626
+
627
+ type Moved = {
628
+ conversationId: string;
629
+ row?: ConversationSummary;
630
+ before: Place;
631
+ after: Place;
632
+ /** Its unread messages, for the counts. */
633
+ unread: number;
634
+ };
635
+
636
+ function movedBy(
637
+ client: QueryClient,
638
+ mailboxId: string,
639
+ change: Extract<OwnChange, { type: "move" | "delete" }>,
640
+ sourceFolderId?: string
331
641
  ) {
332
- const before = input.version - 1;
642
+ return change.conversationIds.map((conversationId) => {
643
+ const { place, row } = placeOf(
644
+ client,
645
+ mailboxId,
646
+ change.type === "move" ? change.sourceFolderId : sourceFolderId,
647
+ conversationId,
648
+ change.type === "move"
649
+ ? change.undoSnapshot?.get(conversationId)
650
+ : undefined
651
+ );
333
652
 
334
- const conversationKey = [
335
- "conversation",
336
- input.mailboxId,
337
- input.conversationId,
338
- ];
653
+ const head = conversationHead(client, mailboxId, conversationId);
654
+
655
+ return {
656
+ conversationId,
657
+ row,
658
+ before: place,
659
+ after:
660
+ change.type === "move"
661
+ ? placeAfter(place, change.update, Boolean(change.undoSnapshot))
662
+ : { ...place, gone: true },
663
+ unread: row?.unreadCount ?? head?.unreadCount ?? 0,
664
+ };
665
+ });
666
+ }
667
+
668
+ /**
669
+ * Where the conversations go, as the server's answer will say if nothing
670
+ * surprises it (`ConversationPlace`): for the view to follow at once.
671
+ * A thread its mail rejoins, or mail split off to Spam, is only known
672
+ * from the answer.
673
+ */
674
+ export function expectedPlaces(
675
+ client: QueryClient,
676
+ mailboxId: string,
677
+ change: OwnChange
678
+ ) {
679
+ if (change.type === "empty") {
680
+ return cachedLists(client, mailboxId)
681
+ .filter((list) => list.folder.id === change.folder)
682
+ .flatMap((list) => list.data.pages)
683
+ .flatMap((page) => page.conversations)
684
+ .map((row) => ({
685
+ from: row.conversationId,
686
+ conversationId: row.conversationId,
687
+ folder: null,
688
+ left: true,
689
+ }));
690
+ }
339
691
 
340
- const conversation =
341
- client.getQueryData<Paged<ConversationPage>>(conversationKey);
692
+ if (change.type !== "move" && change.type !== "delete") return [];
342
693
 
343
- const head = conversation?.pages[0];
694
+ return movedBy(client, mailboxId, change).flatMap((moved) => {
695
+ const from = placeFolder(moved.before);
696
+ const to = placeFolder(moved.after);
344
697
 
345
- const holding = conversation?.pages.find((page) =>
346
- page.messages.some((message) => message.id === input.messageId)
698
+ if (to === undefined) return [];
699
+
700
+ return [
701
+ {
702
+ from: moved.conversationId,
703
+ conversationId: moved.conversationId,
704
+ folder: to,
705
+ left: from !== to,
706
+ },
707
+ ];
708
+ });
709
+ }
710
+
711
+ /** Keep list rows so Undo can put them back before its request completes. */
712
+ export function captureUndo(
713
+ client: QueryClient,
714
+ mailboxId: string,
715
+ conversationIds: readonly string[]
716
+ ) {
717
+ const rows = new Map<string, ConversationSummary>();
718
+ const selected = new Set(conversationIds);
719
+
720
+ for (const list of cachedLists(client, mailboxId)) {
721
+ for (const page of list.data.pages) {
722
+ for (const row of page.conversations) {
723
+ if (selected.has(row.conversationId) && !rows.has(row.conversationId)) {
724
+ rows.set(row.conversationId, row);
725
+ }
726
+ }
727
+ }
728
+ }
729
+
730
+ return rows;
731
+ }
732
+
733
+ function withoutRow(pages: ConversationListPage[], conversationId: string) {
734
+ return pages.map((page) =>
735
+ page.conversations.some((item) => item.conversationId === conversationId)
736
+ ? {
737
+ ...page,
738
+ conversations: page.conversations.filter(
739
+ (item) => item.conversationId !== conversationId
740
+ ),
741
+ }
742
+ : page
347
743
  );
744
+ }
348
745
 
349
- const message = holding?.messages.find((item) => item.id === input.messageId);
746
+ /**
747
+ * `pages` with `row` in its place. A row older than everything loaded
748
+ * belongs to a page not loaded yet, unless the list has no more.
749
+ */
750
+ function withRow(pages: ConversationListPage[], row: ConversationSummary) {
751
+ for (const [pageIndex, page] of pages.entries()) {
752
+ const index = page.conversations.findIndex((item) => newerThan(row, item));
753
+
754
+ if (index !== -1) {
755
+ const next = [...pages];
756
+ next[pageIndex] = {
757
+ ...page,
758
+ conversations: [
759
+ ...page.conversations.slice(0, index),
760
+ row,
761
+ ...page.conversations.slice(index),
762
+ ],
763
+ };
764
+
765
+ return next;
766
+ }
767
+ }
350
768
 
351
- if (
352
- !head ||
353
- !holding ||
354
- !message ||
355
- head.version !== before ||
356
- holding.version !== before
357
- ) {
358
- return false;
769
+ const last = pages.at(-1);
770
+
771
+ if (!last || last.nextCursor) return pages;
772
+
773
+ return [
774
+ ...pages.slice(0, -1),
775
+ { ...last, conversations: [...last.conversations, row] },
776
+ ];
777
+ }
778
+
779
+ function setLists(
780
+ client: QueryClient,
781
+ mailboxId: string,
782
+ update: (list: ListQuery) => ConversationListPage[] | null
783
+ ) {
784
+ for (const list of cachedLists(client, mailboxId)) {
785
+ const pages = update(list);
786
+
787
+ if (pages) {
788
+ client.setQueryData<Paged<ConversationListPage>>(list.queryKey, {
789
+ ...list.data,
790
+ pages: pages.map((page, index) => ({
791
+ ...page,
792
+ version: list.data.pages[index]?.version ?? page.version,
793
+ })),
794
+ });
795
+ }
359
796
  }
797
+ }
798
+
799
+ /** Adds `delta(folder)` to each folder's counts, and the Inbox's to the mailbox's. */
800
+ function adjustCounts(
801
+ client: QueryClient,
802
+ mailboxId: string,
803
+ delta: (folder: FolderKind) => { total: number; unread: number }
804
+ ) {
805
+ client.setQueryData<FoldersData>(
806
+ ["folders", mailboxId],
807
+ (data) =>
808
+ data && {
809
+ ...data,
810
+ folders: data.folders.map((folder) => {
811
+ const { total, unread } = delta(folder);
812
+
813
+ return total || unread
814
+ ? {
815
+ ...folder,
816
+ totalCount: Math.max(0, folder.totalCount + total),
817
+ unreadCount: Math.max(0, folder.unreadCount + unread),
818
+ }
819
+ : folder;
820
+ }),
821
+ }
822
+ );
823
+
824
+ const inbox = delta({ id: "inbox", kind: "system", systemType: "inbox" });
360
825
 
361
- const delta =
362
- message.direction === "incoming" && message.isRead !== input.isRead
363
- ? input.isRead
364
- ? -1
365
- : 1
366
- : 0;
826
+ if (!inbox.unread) return;
367
827
 
368
- const bump = <T extends Versioned>(page: T): T =>
369
- page.version === before ? { ...page, version: input.version } : page;
828
+ client.setQueryData<MailboxesData>(
829
+ ["mailboxes"],
830
+ (data) =>
831
+ data && {
832
+ ...data,
833
+ mailboxes: data.mailboxes.map((mailbox) =>
834
+ mailbox.id === mailboxId
835
+ ? {
836
+ ...mailbox,
837
+ unreadCount: Math.max(0, mailbox.unreadCount + inbox.unread),
838
+ }
839
+ : mailbox
840
+ ),
841
+ }
842
+ );
843
+ }
844
+
845
+ function movedRow(row: ConversationSummary, after: Place) {
846
+ if (row.draftId !== null) return row;
847
+ const mailboxState = after.mailboxState ?? row.mailboxState;
848
+ const folderId = after.folderId === undefined ? row.folderId : after.folderId;
849
+
850
+ return mailboxState === row.mailboxState && folderId === row.folderId
851
+ ? row
852
+ : { ...row, mailboxState, folderId };
853
+ }
854
+
855
+ function applyMoves(client: QueryClient, mailboxId: string, moves: Moved[]) {
856
+ const byId = new Map(moves.map((move) => [move.conversationId, move]));
857
+
858
+ setLists(client, mailboxId, (list) => {
859
+ const unseen = new Map(byId);
860
+ let changed = false;
861
+
862
+ let pages = list.data.pages.map((page) => {
863
+ const conversations = page.conversations.flatMap((row) => {
864
+ const move = byId.get(row.conversationId);
865
+
866
+ if (!move) return [row];
867
+ unseen.delete(row.conversationId);
868
+
869
+ if (lists(list.folder, move.after) === false) return [];
870
+
871
+ // Inbox and Sent can keep a row across a move.
872
+ return [movedRow(row, move.after)];
873
+ });
874
+
875
+ if (
876
+ conversations.length === page.conversations.length &&
877
+ conversations.every((row, i) => row === page.conversations[i])
878
+ ) {
879
+ return page;
880
+ }
881
+
882
+ changed = true;
883
+
884
+ return { ...page, conversations };
885
+ });
886
+
887
+ for (const moved of unseen.values()) {
888
+ if (
889
+ moved.row &&
890
+ !list.search &&
891
+ lists(list.folder, moved.after) === true &&
892
+ lists(list.folder, moved.before) !== true &&
893
+ (!list.unreadOnly || moved.row.isUnread)
894
+ ) {
895
+ const next = withRow(pages, {
896
+ ...movedRow(moved.row, moved.after),
897
+ searchMatch: null,
898
+ });
899
+
900
+ changed ||= next !== pages;
901
+ pages = next;
902
+ }
903
+ }
904
+
905
+ return changed ? pages : null;
906
+ });
907
+
908
+ adjustCounts(client, mailboxId, (folder) => {
909
+ let total = 0;
910
+ let unread = 0;
911
+
912
+ for (const moved of moves) {
913
+ const was = lists(folder, moved.before);
914
+ const will = lists(folder, moved.after);
915
+
916
+ if (was === undefined || will === undefined || was === will) continue;
917
+ const sign = will ? 1 : -1;
918
+ total += sign;
919
+ unread += sign * moved.unread;
920
+ }
921
+
922
+ return { total, unread };
923
+ });
924
+
925
+ for (const moved of moves) {
926
+ if (moved.after.gone) continue;
927
+ const { mailboxState, folderId } = moved.after;
370
928
 
371
- for (const query of client
372
- .getQueryCache()
373
- .findAll({ queryKey: ["conversation", input.mailboxId] })) {
374
929
  client.setQueryData<Paged<ConversationPage>>(
375
- query.queryKey,
930
+ ["conversation", mailboxId, moved.conversationId],
376
931
  (data) =>
377
932
  data && {
378
933
  ...data,
379
- pages: data.pages.map((page, index) => {
380
- if (page.version !== before) return page;
381
-
382
- if (query.queryKey[2] !== input.conversationId) return bump(page);
383
-
384
- return {
385
- ...page,
386
- version: input.version,
387
- unreadCount:
388
- index === 0
389
- ? Math.max(0, page.unreadCount + delta)
390
- : page.unreadCount,
391
- messages: page.messages.map((item) =>
392
- item.id === input.messageId
393
- ? {
394
- ...item,
395
- isRead: input.isRead,
396
- viewedBy: input.isRead
397
- ? item.viewedBy.some(
398
- (viewer) => viewer.userId === input.reader.userId
399
- )
400
- ? item.viewedBy
401
- : [
402
- ...item.viewedBy,
403
- {
404
- ...input.reader,
405
- readAt: new Date().toISOString(),
406
- },
407
- ]
408
- : item.viewedBy.filter(
409
- (viewer) => viewer.userId !== input.reader.userId
410
- ),
411
- }
412
- : item
413
- ),
414
- };
415
- }),
934
+ pages: data.pages.map((page) => ({
935
+ ...page,
936
+ mailboxState: mailboxState ?? page.mailboxState,
937
+ folderId: folderId === undefined ? page.folderId : folderId,
938
+ })),
416
939
  }
417
940
  );
418
941
  }
942
+ }
419
943
 
420
- for (const query of client
421
- .getQueryCache()
422
- .findAll({ queryKey: ["conversations", input.mailboxId] })) {
423
- client.setQueryData<Paged<ConversationListPage>>(
424
- query.queryKey,
425
- (data) =>
426
- data && {
427
- ...data,
428
- pages: data.pages.map((page) =>
429
- page.version === before
430
- ? {
431
- ...page,
432
- version: input.version,
433
- conversations: page.conversations.map((item) => {
434
- if (item.conversationId !== input.conversationId) {
435
- return item;
436
- }
944
+ function emptyFolder(
945
+ client: QueryClient,
946
+ mailboxId: string,
947
+ folder: "trash" | "spam"
948
+ ) {
949
+ const deleted = [
950
+ ...new Set(
951
+ expectedPlaces(client, mailboxId, { type: "empty", folder }).map(
952
+ (place) => place.from
953
+ )
954
+ ),
955
+ ];
437
956
 
438
- const unreadCount = Math.max(0, item.unreadCount + delta);
957
+ applyMoves(
958
+ client,
959
+ mailboxId,
960
+ movedBy(
961
+ client,
962
+ mailboxId,
963
+ { type: "delete", conversationIds: deleted },
964
+ folder
965
+ )
966
+ );
439
967
 
440
- return { ...item, unreadCount, isUnread: unreadCount > 0 };
441
- }),
442
- }
443
- : page
444
- ),
445
- }
446
- );
968
+ // What wasn't loaded goes too.
969
+ setLists(client, mailboxId, (list) =>
970
+ list.folder.id === folder
971
+ ? list.data.pages.map((page) => ({
972
+ ...page,
973
+ conversations: [],
974
+ nextCursor: null,
975
+ }))
976
+ : null
977
+ );
978
+
979
+ client.setQueryData<FoldersData>(
980
+ ["folders", mailboxId],
981
+ (data) =>
982
+ data && {
983
+ ...data,
984
+ folders: data.folders.map((item) =>
985
+ item.id === folder ? { ...item, totalCount: 0, unreadCount: 0 } : item
986
+ ),
987
+ }
988
+ );
989
+ }
990
+
991
+ function withViewer(
992
+ viewers: ConversationPage["messages"][number]["viewedBy"],
993
+ isRead: boolean,
994
+ reader: Reader | undefined
995
+ ) {
996
+ if (!reader) return viewers;
997
+
998
+ if (!isRead) {
999
+ return viewers.filter((viewer) => viewer.userId !== reader.userId);
447
1000
  }
448
1001
 
449
- client.setQueryData<FoldersData>(["folders", input.mailboxId], (data) =>
450
- data && data.version === before
451
- ? {
452
- ...data,
453
- version: input.version,
454
- folders: data.folders.map((folder) =>
455
- folderContains(folder, head)
1002
+ return viewers.some((viewer) => viewer.userId === reader.userId)
1003
+ ? viewers
1004
+ : [...viewers, { ...reader, readAt: new Date().toISOString() }];
1005
+ }
1006
+
1007
+ /**
1008
+ * Read state of whole conversations (`messageId` absent) or one message:
1009
+ * the conversation's messages, its rows, and the counts of the folders
1010
+ * that list it.
1011
+ */
1012
+ function applyRead(
1013
+ client: QueryClient,
1014
+ mailboxId: string,
1015
+ input: {
1016
+ sourceFolderId?: string;
1017
+ conversationId: string;
1018
+ messageId?: string;
1019
+ isRead: boolean;
1020
+ reader?: Reader;
1021
+ }
1022
+ ) {
1023
+ const key = ["conversation", mailboxId, input.conversationId];
1024
+ const conversation = client.getQueryData<Paged<ConversationPage>>(key);
1025
+
1026
+ const { place, row } = placeOf(
1027
+ client,
1028
+ mailboxId,
1029
+ input.sourceFolderId,
1030
+ input.conversationId
1031
+ );
1032
+
1033
+ const allIncoming = !input.messageId && input.isRead;
1034
+ // The first page is the newest. Within each page the newest message is last.
1035
+ let target: ConversationPage["messages"][number] | undefined;
1036
+
1037
+ if (!allIncoming) {
1038
+ for (const page of conversation?.pages ?? []) {
1039
+ target = input.messageId
1040
+ ? page.messages.find((message) => message.id === input.messageId)
1041
+ : page.messages.findLast((message) => message.direction === "incoming");
1042
+
1043
+ if (target) break;
1044
+ }
1045
+ }
1046
+
1047
+ const unreadBefore = conversation?.pages[0]?.unreadCount ?? row?.unreadCount;
1048
+ let delta = 0;
1049
+
1050
+ if (allIncoming) {
1051
+ delta = -(unreadBefore ?? 0);
1052
+ } else if (target) {
1053
+ if (target.direction === "incoming" && target.isRead !== input.isRead) {
1054
+ delta = input.isRead ? -1 : 1;
1055
+ }
1056
+ } else if (!input.messageId && place.hasIncoming && unreadBefore === 0) {
1057
+ // The newest incoming message may be outside the loaded pages.
1058
+ delta = 1;
1059
+ }
1060
+
1061
+ client.setQueryData<Paged<ConversationPage>>(
1062
+ key,
1063
+ (data) =>
1064
+ data && {
1065
+ ...data,
1066
+ pages: data.pages.map((page) => ({
1067
+ ...page,
1068
+ unreadCount: Math.max(0, page.unreadCount + delta),
1069
+ messages: page.messages.map((item) =>
1070
+ (allIncoming && item.direction === "incoming") ||
1071
+ item.id === target?.id
456
1072
  ? {
457
- ...folder,
458
- unreadCount: Math.max(0, folder.unreadCount + delta),
1073
+ ...item,
1074
+ isRead: input.isRead,
1075
+ viewedBy: withViewer(
1076
+ item.viewedBy,
1077
+ input.isRead,
1078
+ input.reader
1079
+ ),
459
1080
  }
460
- : folder
1081
+ : item
461
1082
  ),
462
- }
463
- : data
1083
+ })),
1084
+ }
1085
+ );
1086
+
1087
+ if (!delta) return;
1088
+ const unconfirmed = new Set<QueryKey>();
1089
+
1090
+ setLists(client, mailboxId, (list) => {
1091
+ const { pages: listPages } = list.data;
1092
+ const listed = rowIn(listPages, input.conversationId);
1093
+
1094
+ if (!listed) {
1095
+ if (!list.unreadOnly || delta < 0) return null;
1096
+ const member = lists(list.folder, place);
1097
+
1098
+ if (member === false) return null;
1099
+
1100
+ const matches = list.search
1101
+ ? client.getQueryData<Paged<ConversationListPage>>([
1102
+ "conversations",
1103
+ mailboxId,
1104
+ list.folder.id,
1105
+ list.search,
1106
+ false,
1107
+ ])
1108
+ : undefined;
1109
+
1110
+ const candidate = list.search
1111
+ ? rowIn(matches?.pages ?? [], input.conversationId)
1112
+ : row;
1113
+
1114
+ if (!candidate || member !== true) {
1115
+ // The server can resolve a search match or folder membership missing from the cache.
1116
+ unconfirmed.add(list.queryKey);
1117
+
1118
+ return null;
1119
+ }
1120
+
1121
+ return withRow(listPages, {
1122
+ ...candidate,
1123
+ ...(!list.search && { searchMatch: null }),
1124
+ unreadCount: (unreadBefore ?? 0) + delta,
1125
+ isUnread: true,
1126
+ });
1127
+ }
1128
+
1129
+ const unreadCount = Math.max(0, listed.unreadCount + delta);
1130
+
1131
+ if (list.unreadOnly && !unreadCount) {
1132
+ return withoutRow(listPages, input.conversationId);
1133
+ }
1134
+
1135
+ return listPages.map((page) => ({
1136
+ ...page,
1137
+ conversations: page.conversations.map((item) =>
1138
+ item.conversationId === input.conversationId
1139
+ ? { ...item, unreadCount, isUnread: unreadCount > 0 }
1140
+ : item
1141
+ ),
1142
+ }));
1143
+ });
1144
+
1145
+ adjustCounts(client, mailboxId, (folder) => ({
1146
+ total: 0,
1147
+ unread: lists(folder, place) === true ? delta : 0,
1148
+ }));
1149
+
1150
+ return unconfirmed;
1151
+ }
1152
+
1153
+ function applyOwnChange(
1154
+ client: QueryClient,
1155
+ mailboxId: string,
1156
+ change: OwnChange
1157
+ ) {
1158
+ switch (change.type) {
1159
+ case "move":
1160
+ case "delete": {
1161
+ applyMoves(client, mailboxId, movedBy(client, mailboxId, change));
1162
+ break;
1163
+ }
1164
+
1165
+ case "empty": {
1166
+ emptyFolder(client, mailboxId, change.folder);
1167
+ break;
1168
+ }
1169
+
1170
+ case "read": {
1171
+ for (const conversationId of change.conversationIds) {
1172
+ applyRead(client, mailboxId, {
1173
+ sourceFolderId: change.sourceFolderId,
1174
+ conversationId,
1175
+ isRead: change.isRead,
1176
+ reader: change.reader,
1177
+ });
1178
+ }
1179
+
1180
+ break;
1181
+ }
1182
+
1183
+ default: {
1184
+ return applyRead(client, mailboxId, change);
1185
+ }
1186
+ }
1187
+ }
1188
+
1189
+ /**
1190
+ * Data that reflected `previousVersion` reflects `version` now: the own
1191
+ * change between them is in it already, so its echo refetches nothing.
1192
+ */
1193
+ function confirmVersion(
1194
+ client: QueryClient,
1195
+ mailboxId: string,
1196
+ { previousVersion, version }: { previousVersion: number; version: number },
1197
+ unconfirmed: ReadonlySet<QueryKey> | undefined
1198
+ ) {
1199
+ const bump = <T extends Versioned>(item: T) =>
1200
+ item.version === previousVersion ? { ...item, version } : item;
1201
+
1202
+ for (const group of ["conversations", "conversation"] as const) {
1203
+ for (const [queryKey, data] of client.getQueriesData<Paged<Versioned>>({
1204
+ queryKey: [group, mailboxId],
1205
+ })) {
1206
+ if (data && !unconfirmed?.has(queryKey)) {
1207
+ client.setQueryData(queryKey, { ...data, pages: data.pages.map(bump) });
1208
+ }
1209
+ }
1210
+ }
1211
+
1212
+ client.setQueryData<Versioned>(
1213
+ ["folders", mailboxId],
1214
+ (data) => data && bump(data)
464
1215
  );
465
- const inInbox = head.hasIncoming && head.mailboxState === "active";
1216
+
466
1217
  client.setQueryData<MailboxesData>(
467
1218
  ["mailboxes"],
468
1219
  (data) =>
469
1220
  data && {
470
1221
  ...data,
471
1222
  mailboxes: data.mailboxes.map((mailbox) =>
472
- mailbox.id !== input.mailboxId || mailbox.version !== before
473
- ? mailbox
474
- : {
475
- ...mailbox,
476
- version: input.version,
477
- unreadCount: inInbox
478
- ? Math.max(0, mailbox.unreadCount + delta)
479
- : mailbox.unreadCount,
480
- }
1223
+ mailbox.id === mailboxId ? bump(mailbox) : mailbox
481
1224
  ),
482
1225
  }
483
1226
  );
1227
+ }
1228
+
1229
+ /** What `beginOwnChange` showed, for the mutation's other callbacks. */
1230
+ export type OwnChangeContext = {
1231
+ /** The mailbox's data before the change, to put back if it fails. */
1232
+ snapshot: [QueryKey, unknown][];
1233
+ previousMailbox: (Mailbox & Versioned) | undefined;
1234
+ /** The version announced when the change began. */
1235
+ announcedAtStart: number | undefined;
1236
+ /** Lists the server may not have as the cache shows them. */
1237
+ unconfirmed: Set<QueryKey>;
1238
+ };
1239
+
1240
+ /**
1241
+ * The one way the cache shows this person's own changes of a mailbox at
1242
+ * once: the `onMutate` of a mutation keyed `ownChangeKey(mailboxId)`.
1243
+ * Fetches in flight are cancelled, and the cached lists (rows out of the
1244
+ * folder they left, into the one they went to), conversations and counts
1245
+ * of the mailbox change. Its data isn't read again until the last such
1246
+ * mutation settles (`ownChangeSettled`); `ownChangeDone` reads it once
1247
+ * (with the realtime echo, not twice), `ownChangeFailed` puts it back.
1248
+ */
1249
+ export async function beginOwnChange(
1250
+ client: QueryClient,
1251
+ mailboxId: string,
1252
+ ...changes: OwnChange[]
1253
+ ) {
1254
+ const state = refreshState(client);
1255
+
1256
+ // A read in flight may predate the change; it is read again after it. A
1257
+ // first load is left alone: cancelled, it would have nothing to show.
1258
+ const fetching = mailboxQueries(client, mailboxId).filter(
1259
+ (query) =>
1260
+ query.state.fetchStatus === "fetching" && query.state.data !== undefined
1261
+ );
1262
+
1263
+ await Promise.all(
1264
+ fetching.map((query) =>
1265
+ client.cancelQueries({ queryKey: query.queryKey, exact: true })
1266
+ )
1267
+ );
1268
+
1269
+ for (const query of fetching) {
1270
+ state.refetchedFor.delete(`${mailboxId}\0${query.queryHash}`);
1271
+ }
1272
+
1273
+ if (fetching.length) state.checked.add(mailboxId);
1274
+
1275
+ const previousMailbox = client
1276
+ .getQueryData<MailboxesData>(["mailboxes"])
1277
+ ?.mailboxes.find((mailbox) => mailbox.id === mailboxId);
1278
+
1279
+ const snapshot = MAILBOX_GROUPS.flatMap((group) =>
1280
+ client.getQueriesData({ queryKey: [group, mailboxId] })
1281
+ );
1282
+
1283
+ const announcedAtStart = state.announced.get(mailboxId);
1284
+ const unconfirmed = new Set<QueryKey>();
1285
+
1286
+ for (const change of changes) {
1287
+ for (const key of applyOwnChange(client, mailboxId, change) ?? []) {
1288
+ unconfirmed.add(key);
1289
+ }
1290
+ }
1291
+
1292
+ return {
1293
+ snapshot,
1294
+ previousMailbox,
1295
+ announcedAtStart,
1296
+ unconfirmed,
1297
+ } satisfies OwnChangeContext;
1298
+ }
1299
+
1300
+ /**
1301
+ * The server made the change (`onSuccess`). With the versions it went
1302
+ * between, data at the first moves on; without, the mailbox is read once
1303
+ * its echo comes.
1304
+ */
1305
+ export function ownChangeDone(
1306
+ client: QueryClient,
1307
+ mailboxId: string,
1308
+ context: OwnChangeContext,
1309
+ versions?: { previousVersion: number; version: number }
1310
+ ) {
1311
+ const state = refreshState(client);
1312
+ // React Query keeps settled mutations, and their context, in memory.
1313
+ context.snapshot.length = 0;
1314
+
1315
+ if (versions) {
1316
+ confirmVersion(client, mailboxId, versions, context.unconfirmed);
1317
+ state.announced.set(
1318
+ mailboxId,
1319
+ Math.max(state.announced.get(mailboxId) ?? -1, versions.version)
1320
+ );
1321
+ state.checked.add(mailboxId);
1322
+ } else if (context.announcedAtStart === undefined) {
1323
+ // No realtime here: nothing will say the change is in.
1324
+ state.forced.add(mailboxId);
1325
+ } else if (
1326
+ (state.announced.get(mailboxId) ?? -1) > context.announcedAtStart
1327
+ ) {
1328
+ state.checked.add(mailboxId);
1329
+ } else {
1330
+ clearTimeout(state.echoWaits.get(mailboxId));
1331
+ state.echoWaits.set(
1332
+ mailboxId,
1333
+ setTimeout(() => {
1334
+ state.echoWaits.delete(mailboxId);
1335
+ state.forced.add(mailboxId);
1336
+ schedule(client, state);
1337
+ }, ECHO_WAIT_MS)
1338
+ );
1339
+ }
1340
+ }
484
1341
 
485
- return true;
1342
+ /**
1343
+ * The server refused the change (`onError`): the cache goes back as it
1344
+ * was. When a later own change of the mailbox began meanwhile, restoring
1345
+ * would take that one out too, so the mailbox is read again instead.
1346
+ */
1347
+ export function ownChangeFailed(
1348
+ client: QueryClient,
1349
+ mailboxId: string,
1350
+ context: OwnChangeContext | undefined
1351
+ ) {
1352
+ // Without a context the change never showed.
1353
+ if (!context) return;
1354
+ const state = refreshState(client);
1355
+
1356
+ const last = client
1357
+ .getMutationCache()
1358
+ .findAll({ mutationKey: ownChangeKey(mailboxId) })
1359
+ .at(-1);
1360
+
1361
+ if (last?.state.context === context) {
1362
+ const { previousMailbox } = context;
1363
+
1364
+ if (previousMailbox) {
1365
+ client.setQueryData<MailboxesData>(
1366
+ ["mailboxes"],
1367
+ (data) =>
1368
+ data && {
1369
+ ...data,
1370
+ mailboxes: data.mailboxes.map((mailbox) =>
1371
+ mailbox.id === mailboxId &&
1372
+ mailbox.version === previousMailbox.version
1373
+ ? { ...mailbox, unreadCount: previousMailbox.unreadCount }
1374
+ : mailbox
1375
+ ),
1376
+ }
1377
+ );
1378
+ }
1379
+
1380
+ for (const [queryKey, data] of context.snapshot) {
1381
+ client.setQueryData(queryKey, data);
1382
+ }
1383
+
1384
+ state.checked.add(mailboxId);
1385
+ } else state.forced.add(mailboxId);
1386
+
1387
+ context.snapshot.length = 0;
1388
+ }
1389
+
1390
+ /**
1391
+ * Either way (`onSettled`): the last own change of the mailbox in flight
1392
+ * reads what the changes left to read.
1393
+ */
1394
+ export function ownChangeSettled(client: QueryClient, mailboxId: string) {
1395
+ if (client.isMutating({ mutationKey: ownChangeKey(mailboxId) }) === 1) {
1396
+ schedule(client, refreshState(client));
1397
+ }
486
1398
  }