@open-workspace/email 0.4.2 → 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 (266) 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.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -4,11 +4,18 @@ import {
4
4
  AdminPanelFooter,
5
5
  AdminPanelHeader,
6
6
  Button,
7
+ DelayedFallback,
7
8
  Switch,
8
9
  useAuth,
10
+ useDelayedPending,
9
11
  responseJson,
10
12
  } from "@open-workspace/core/ui";
11
- import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
13
+ import {
14
+ skipToken,
15
+ useMutation,
16
+ useQuery,
17
+ useQueryClient,
18
+ } from "@tanstack/react-query";
12
19
  import { Bell, BellOff, LoaderCircle, Smartphone } from "lucide-react";
13
20
  import { toast } from "sonner";
14
21
 
@@ -18,6 +25,10 @@ import {
18
25
  disableCurrentPushSubscription,
19
26
  enableCurrentPushSubscription,
20
27
  } from "../pwa/push-subscription";
28
+ import {
29
+ notificationPreferencesQuery,
30
+ pushConfigQuery,
31
+ } from "./settings-queries";
21
32
 
22
33
  type DeviceStatus =
23
34
  | "loading"
@@ -61,18 +72,8 @@ export function NotificationsSettings() {
61
72
  const client = useQueryClient();
62
73
  const userId = useAuth().user?.id;
63
74
 
64
- const config = useQuery({
65
- queryKey: ["push-config"],
66
- queryFn: async () =>
67
- responseJson(await mailApi.api.notifications.config.$get()),
68
- staleTime: 60_000,
69
- });
70
-
71
- const preferences = useQuery({
72
- queryKey: ["notification-preferences"],
73
- queryFn: async () =>
74
- responseJson(await mailApi.api.notifications.preferences.$get()),
75
- });
75
+ const config = useQuery(pushConfigQuery);
76
+ const preferences = useQuery(notificationPreferencesQuery);
76
77
 
77
78
  const publicKey = config.data?.publicKey ?? null;
78
79
  const deviceStatusKey = ["push-device-status", userId, publicKey] as const;
@@ -80,7 +81,9 @@ export function NotificationsSettings() {
80
81
  const device = useQuery({
81
82
  queryKey: deviceStatusKey,
82
83
  enabled: Boolean(config.data?.enabled && publicKey && userId),
83
- queryFn: () => currentPushRegistrationStatus(),
84
+ queryFn: publicKey
85
+ ? () => currentPushRegistrationStatus(publicKey)
86
+ : skipToken,
84
87
  });
85
88
 
86
89
  const enable = useMutation({
@@ -149,12 +152,19 @@ export function NotificationsSettings() {
149
152
  ? (device.data ?? "loading")
150
153
  : "unsupported";
151
154
 
155
+ // Checking the device is mostly quick: its spinner only shows if it isn't.
156
+ const deviceChecking = useDelayedPending(
157
+ config.isLoading || device.isFetching
158
+ );
159
+
152
160
  const devicePending =
153
161
  config.isLoading ||
154
162
  device.isFetching ||
155
163
  enable.isPending ||
156
164
  disable.isPending;
157
165
 
166
+ const deviceSpinner = deviceChecking || enable.isPending || disable.isPending;
167
+
158
168
  function handleDeviceAction() {
159
169
  if (deviceStatus === "error") {
160
170
  void (config.isError ? config.refetch() : device.refetch());
@@ -211,7 +221,7 @@ export function NotificationsSettings() {
211
221
  }
212
222
  onClick={handleDeviceAction}
213
223
  >
214
- {devicePending ? (
224
+ {deviceSpinner ? (
215
225
  <LoaderCircle className="animate-spin" />
216
226
  ) : (
217
227
  <Bell />
@@ -227,59 +237,64 @@ export function NotificationsSettings() {
227
237
  Choose which mailboxes may send you new-message notifications.
228
238
  </p>
229
239
  <div className="divide-border/70 mt-4 divide-y">
230
- {preferences.isLoading ? (
231
- <div className="text-muted-foreground flex items-center gap-2 py-4 text-xs">
232
- <LoaderCircle className="size-4 animate-spin" /> Loading
233
- mailboxes…
234
- </div>
235
- ) : preferences.isError ? (
236
- <div className="flex items-center justify-between gap-4 py-4">
237
- <p className="text-destructive text-xs">
238
- Could not load mailbox preferences.
239
- </p>
240
- <Button
241
- size="sm"
242
- variant="outline"
243
- disabled={preferences.isFetching}
244
- onClick={() => void preferences.refetch()}
245
- >
246
- {preferences.isFetching && (
247
- <LoaderCircle className="animate-spin" />
248
- )}
249
- Retry
250
- </Button>
251
- </div>
252
- ) : preferences.data?.preferences.length ? (
253
- preferences.data.preferences.map((preference) => (
254
- <label
255
- key={preference.mailboxId}
256
- className="flex items-center gap-4 py-3"
257
- >
258
- <span className="min-w-0 flex-1">
259
- <span className="block truncate text-sm font-medium">
260
- {preference.displayName}
261
- </span>
262
- <span className="text-muted-foreground block truncate text-xs">
263
- {preference.address}
240
+ <DelayedFallback
241
+ pending={preferences.isLoading}
242
+ fallback={
243
+ <div className="text-muted-foreground flex items-center gap-2 py-4 text-xs">
244
+ <LoaderCircle className="size-4 animate-spin" /> Loading
245
+ mailboxes…
246
+ </div>
247
+ }
248
+ >
249
+ {preferences.isError ? (
250
+ <div className="flex items-center justify-between gap-4 py-4">
251
+ <p className="text-destructive text-xs">
252
+ Could not load mailbox preferences.
253
+ </p>
254
+ <Button
255
+ size="sm"
256
+ variant="outline"
257
+ disabled={preferences.isFetching}
258
+ onClick={() => void preferences.refetch()}
259
+ >
260
+ {preferences.isFetching && (
261
+ <LoaderCircle className="animate-spin" />
262
+ )}
263
+ Retry
264
+ </Button>
265
+ </div>
266
+ ) : preferences.data?.preferences.length ? (
267
+ preferences.data.preferences.map((preference) => (
268
+ <label
269
+ key={preference.mailboxId}
270
+ className="flex items-center gap-4 py-3"
271
+ >
272
+ <span className="min-w-0 flex-1">
273
+ <span className="block truncate text-sm font-medium">
274
+ {preference.displayName}
275
+ </span>
276
+ <span className="text-muted-foreground block truncate text-xs">
277
+ {preference.address}
278
+ </span>
264
279
  </span>
265
- </span>
266
- <Switch
267
- checked={preference.enabled}
268
- disabled={updatePreference.isPending}
269
- onCheckedChange={(enabled) =>
270
- updatePreference.mutate({
271
- mailboxId: preference.mailboxId,
272
- enabled,
273
- })
274
- }
275
- />
276
- </label>
277
- ))
278
- ) : (
279
- <p className="text-muted-foreground py-4 text-xs">
280
- No mailboxes are available for notifications.
281
- </p>
282
- )}
280
+ <Switch
281
+ checked={preference.enabled}
282
+ disabled={updatePreference.isPending}
283
+ onCheckedChange={(enabled) =>
284
+ updatePreference.mutate({
285
+ mailboxId: preference.mailboxId,
286
+ enabled,
287
+ })
288
+ }
289
+ />
290
+ </label>
291
+ ))
292
+ ) : (
293
+ <p className="text-muted-foreground py-4 text-xs">
294
+ No mailboxes are available for notifications.
295
+ </p>
296
+ )}
297
+ </DelayedFallback>
283
298
  </div>
284
299
  </div>
285
300
  </AdminPanelBody>
@@ -0,0 +1,182 @@
1
+ import { forwardRef, useImperativeHandle, useRef, useState } from "react";
2
+ import { toast } from "sonner";
3
+
4
+ import { MAX_RICH_IMAGE_BYTES } from "../../shared/rich-content";
5
+ import type { RichImage } from "../../shared/rich-content";
6
+ import { ComposerAttachmentList } from "../mail/composer-attachment-list";
7
+ import { ComposerEditor } from "../mail/composer-editor";
8
+ import type { ComposerEditorHandle } from "../mail/composer-editor";
9
+ import { useComposerSession } from "../mail/composer-session";
10
+ import { storedImagesHtml } from "../mail/rich-content";
11
+
12
+ /** Saved rich content as its routes return it (worker/mail/rich-content.ts). */
13
+ export type SavedRichContent = {
14
+ ownerId: string;
15
+ html: string;
16
+ images: RichImage[];
17
+ };
18
+
19
+ /** What saving rich content sends (`richContentFields` on the Worker). */
20
+ export type RichContentValue = {
21
+ html: string;
22
+ text: string;
23
+ /** New images by upload id; saved images it keeps by content id alone. */
24
+ images: { contentId: string; uploadId?: string }[];
25
+ uploadMailboxId?: string;
26
+ };
27
+
28
+ export type RichContentEditorHandle = {
29
+ /** The content to save once all its images have uploaded. */
30
+ value: () => RichContentValue;
31
+ };
32
+
33
+ /**
34
+ * Saved rich content (a signature, an auto-reply) in the composer's own
35
+ * editor, so it looks as it will once sent. Saved images show at once from
36
+ * where they are stored (`imageUrl`); new ones upload through
37
+ * `uploadMailboxId`, a mailbox the person can send from.
38
+ */
39
+ export const RichContentEditor = forwardRef<
40
+ RichContentEditorHandle,
41
+ {
42
+ saved: SavedRichContent | null;
43
+ imageUrl: (ownerId: string, contentId: string) => string;
44
+ uploadMailboxId: string | undefined;
45
+ label: string;
46
+ placeholder: string;
47
+ disabled: boolean;
48
+ /** The editor's HTML after each edit (debounced), for a form field. */
49
+ onChange: (html: string) => void;
50
+ onSubmitShortcut?: () => void;
51
+ }
52
+ >(function RichContentEditor(
53
+ {
54
+ saved,
55
+ imageUrl,
56
+ uploadMailboxId,
57
+ label,
58
+ placeholder,
59
+ disabled,
60
+ onChange,
61
+ onSubmitShortcut,
62
+ },
63
+ ref
64
+ ) {
65
+ const editor = useRef<ComposerEditorHandle>(null);
66
+ const inlineFileInput = useRef<HTMLInputElement>(null);
67
+ const { session, snapshot } = useComposerSession(uploadMailboxId ?? "");
68
+
69
+ const unfinishedImages = snapshot.assets.filter(
70
+ (asset) =>
71
+ snapshot.documentAssetIds.has(asset.id) && asset.status !== "uploaded"
72
+ );
73
+
74
+ // oxlint-disable-next-line react/hook-use-state -- read once, when the editor is created; nothing sets it
75
+ const [initialHtml] = useState(() =>
76
+ saved
77
+ ? storedImagesHtml(saved.html, saved.ownerId, (contentId) =>
78
+ imageUrl(saved.ownerId, contentId)
79
+ )
80
+ : ""
81
+ );
82
+
83
+ useImperativeHandle(ref, () => ({
84
+ value: () => {
85
+ const content = editor.current?.content();
86
+
87
+ const assets = session.documentAssets();
88
+ const failed = assets.find((asset) => asset.status === "error");
89
+
90
+ if (failed) {
91
+ throw new Error(`Retry or remove ${failed.filename} before saving`);
92
+ }
93
+
94
+ if (!content || assets.some((asset) => asset.status === "uploading")) {
95
+ throw new Error("Wait for images to finish uploading");
96
+ }
97
+
98
+ const uploads = content.inlineAssetIds.flatMap((assetId) => {
99
+ const asset = session.getAsset(assetId);
100
+
101
+ return asset?.uploadId && asset.contentId
102
+ ? [{ uploadId: asset.uploadId, contentId: asset.contentId }]
103
+ : [];
104
+ });
105
+
106
+ const kept = content.storedImages.flatMap((image) =>
107
+ image.ownerId === saved?.ownerId ? [{ contentId: image.contentId }] : []
108
+ );
109
+
110
+ return {
111
+ html: content.bodyHtml,
112
+ text: content.bodyText,
113
+ images: [...uploads, ...kept],
114
+ uploadMailboxId,
115
+ };
116
+ },
117
+ }));
118
+
119
+ function addImages(files: File[], position?: number) {
120
+ if (!uploadMailboxId) {
121
+ toast.error("You need a mailbox you can send from to add images");
122
+
123
+ return;
124
+ }
125
+
126
+ const oversized = files.filter((file) => file.size > MAX_RICH_IMAGE_BYTES);
127
+
128
+ if (oversized.length) {
129
+ toast.error(
130
+ `Images are limited to 1 MB each: ${oversized.map((file) => file.name).join(", ")}`
131
+ );
132
+ }
133
+
134
+ const assets = session.addFiles(
135
+ files.filter((file) => file.size <= MAX_RICH_IMAGE_BYTES),
136
+ "inline"
137
+ );
138
+
139
+ if (assets) editor.current?.insertAssets(assets, position);
140
+ }
141
+
142
+ return (
143
+ <div className="border-input bg-background focus-within:ring-ring/40 flex h-56 flex-col overflow-hidden rounded-lg border focus-within:ring-2">
144
+ <ComposerEditor
145
+ ref={editor}
146
+ session={session}
147
+ initialHtml={initialHtml}
148
+ label={label}
149
+ placeholder={placeholder}
150
+ onChange={(content) => onChange(content.editorHtml ?? content.bodyHtml)}
151
+ onAssetsChange={session.setDocumentAssetIds}
152
+ onAddInlineFiles={addImages}
153
+ onAddAttachmentFiles={() => {
154
+ toast.error("Only images can go in here");
155
+ }}
156
+ onChooseInlineImage={() => inlineFileInput.current?.click()}
157
+ onSubmitShortcut={() => onSubmitShortcut?.()}
158
+ dragging={false}
159
+ disabled={disabled}
160
+ />
161
+ <ComposerAttachmentList
162
+ uploads={unfinishedImages}
163
+ progress={session.progress}
164
+ disabled={disabled}
165
+ onRemove={(asset) => editor.current?.removeAsset(asset.id)}
166
+ onRetry={(asset) => void session.retry(asset.id)}
167
+ />
168
+ <input
169
+ ref={inlineFileInput}
170
+ className="sr-only"
171
+ type="file"
172
+ accept="image/png,image/jpeg,image/gif,image/webp"
173
+ tabIndex={-1}
174
+ aria-hidden
175
+ onChange={(event) => {
176
+ addImages(Array.from(event.target.files ?? []));
177
+ event.target.value = "";
178
+ }}
179
+ />
180
+ </div>
181
+ );
182
+ });
@@ -0,0 +1,57 @@
1
+ import { responseJson } from "@open-workspace/core/ui";
2
+ import { queryOptions } from "@tanstack/react-query";
3
+
4
+ import { mailApi } from "../lib/mail-api";
5
+
6
+ /**
7
+ * The queries mail's settings and administration sections open with,
8
+ * shared by the screens and by the prefetch their links start (see
9
+ * client.tsx). Kept free of UI imports so the app's entry stays small.
10
+ */
11
+
12
+ export const pushConfigQuery = queryOptions({
13
+ queryKey: ["push-config"],
14
+ queryFn: async () =>
15
+ responseJson(await mailApi.api.notifications.config.$get()),
16
+ staleTime: 60_000,
17
+ });
18
+
19
+ export const notificationPreferencesQuery = queryOptions({
20
+ queryKey: ["notification-preferences"],
21
+ queryFn: async () =>
22
+ responseJson(await mailApi.api.notifications.preferences.$get()),
23
+ });
24
+
25
+ export const signatureQuery = queryOptions({
26
+ queryKey: ["signature"],
27
+ queryFn: async () => responseJson(await mailApi.api.mail.signature.$get()),
28
+ });
29
+
30
+ export function autoReplyQuery(mailboxId: string) {
31
+ return queryOptions({
32
+ queryKey: ["auto-reply", mailboxId],
33
+ queryFn: async () =>
34
+ responseJson(
35
+ await mailApi.api.mail.mailboxes[":id"]["auto-reply"].$get({
36
+ param: { id: mailboxId },
37
+ })
38
+ ),
39
+ });
40
+ }
41
+
42
+ export const autoReplyMailboxesQuery = queryOptions({
43
+ queryKey: ["auto-reply-mailboxes"],
44
+ queryFn: async () =>
45
+ responseJson(await mailApi.api.mail["auto-replies"].$get()),
46
+ });
47
+
48
+ export const adminBlockedSendersQuery = queryOptions({
49
+ queryKey: ["admin-blocked-senders"],
50
+ queryFn: async () =>
51
+ responseJson(await mailApi.api.admin["blocked-senders"].$get()),
52
+ });
53
+
54
+ export const mailArchiveQuery = queryOptions({
55
+ queryKey: ["admin-mail-archive"],
56
+ queryFn: async () => responseJson(await mailApi.api.mail.archive.$get()),
57
+ });
@@ -0,0 +1,142 @@
1
+ import { Button, Switch, useAddressSection } from "@open-workspace/core/ui";
2
+ import type { SuccessfulResponse } from "@open-workspace/core/ui";
3
+ import { useMutation } from "@tanstack/react-query";
4
+ import { LoaderCircle } from "lucide-react";
5
+ import { useRef } from "react";
6
+ import { useController, useForm } from "react-hook-form";
7
+ import { toast } from "sonner";
8
+
9
+ import type { mailApi } from "../lib/mail-api";
10
+ import { signatureImageUrl } from "../mail/signature";
11
+ import { RichContentEditor } from "./rich-content-editor";
12
+ import type {
13
+ RichContentEditorHandle,
14
+ RichContentValue,
15
+ } from "./rich-content-editor";
16
+
17
+ export type SavedSignature = SuccessfulResponse<
18
+ Awaited<ReturnType<typeof mailApi.api.mail.signature.$get>>
19
+ >["signature"];
20
+
21
+ type SignatureForm = { useOnNew: boolean; useOnReply: boolean; body: string };
22
+
23
+ export type SignatureBody = RichContentValue & {
24
+ useOnNew: boolean;
25
+ useOnReply: boolean;
26
+ };
27
+
28
+ /**
29
+ * A signature: its text and images in the shared rich content editor, and
30
+ * the switches for new messages and for replies and forwards. With a Save
31
+ * button of its own, or, inside an address editor (`section`), saved by
32
+ * the editor's "Save address" through `useAddressSection`.
33
+ */
34
+ export function SignatureEditor({
35
+ saved,
36
+ uploadMailboxId,
37
+ label,
38
+ placeholder,
39
+ section = false,
40
+ onSave,
41
+ }: {
42
+ saved: SavedSignature;
43
+ uploadMailboxId: string | undefined;
44
+ label: string;
45
+ placeholder: string;
46
+ section?: boolean;
47
+ onSave: (body: SignatureBody) => Promise<void>;
48
+ }) {
49
+ const editor = useRef<RichContentEditorHandle>(null);
50
+
51
+ // The editor owns the text; `body` is its HTML, so edits make the form dirty.
52
+ const {
53
+ control,
54
+ formState: { isDirty },
55
+ handleSubmit,
56
+ reset,
57
+ } = useForm<SignatureForm>({
58
+ defaultValues: {
59
+ useOnNew: saved?.useOnNew ?? true,
60
+ useOnReply: saved?.useOnReply ?? true,
61
+ body: "",
62
+ },
63
+ });
64
+
65
+ const body = useController({ control, name: "body" }).field;
66
+ const newMessages = useController({ control, name: "useOnNew" }).field;
67
+ const replies = useController({ control, name: "useOnReply" }).field;
68
+
69
+ async function submit(submitted: SignatureForm) {
70
+ const value = editor.current?.value();
71
+
72
+ if (!value) return;
73
+
74
+ await onSave({
75
+ ...value,
76
+ useOnNew: submitted.useOnNew,
77
+ useOnReply: submitted.useOnReply,
78
+ });
79
+ reset(submitted, { keepValues: true });
80
+ }
81
+
82
+ const save = () => handleSubmit(submit)();
83
+
84
+ // Inside an address editor, its "Save address" saves this; elsewhere a no-op.
85
+ useAddressSection({
86
+ dirty: isDirty,
87
+ save: () =>
88
+ save().catch((error: Error) => {
89
+ throw new Error(`Signature: ${error.message}`, { cause: error });
90
+ }),
91
+ });
92
+
93
+ const saveNow = useMutation({
94
+ mutationFn: save,
95
+ onSuccess: () => toast.success("Signature saved"),
96
+ onError: (error) => toast.error(error.message),
97
+ });
98
+
99
+ return (
100
+ <div className="space-y-3">
101
+ <RichContentEditor
102
+ ref={editor}
103
+ saved={saved}
104
+ imageUrl={signatureImageUrl}
105
+ uploadMailboxId={uploadMailboxId}
106
+ label={label}
107
+ placeholder={placeholder}
108
+ disabled={saveNow.isPending}
109
+ onChange={body.onChange}
110
+ onSubmitShortcut={section ? undefined : () => saveNow.mutate()}
111
+ />
112
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-3">
113
+ <label className="flex items-center gap-2 text-sm">
114
+ <Switch
115
+ checked={newMessages.value}
116
+ onCheckedChange={(checked) => newMessages.onChange(checked)}
117
+ />
118
+ New messages
119
+ </label>
120
+ <label className="flex items-center gap-2 text-sm">
121
+ <Switch
122
+ checked={replies.value}
123
+ onCheckedChange={(checked) => replies.onChange(checked)}
124
+ />
125
+ Replies and forwards
126
+ </label>
127
+ {section ? null : (
128
+ <Button
129
+ type="button"
130
+ size="sm"
131
+ className="ml-auto"
132
+ disabled={saveNow.isPending || !isDirty}
133
+ onClick={() => saveNow.mutate()}
134
+ >
135
+ {saveNow.isPending && <LoaderCircle className="animate-spin" />}
136
+ Save
137
+ </Button>
138
+ )}
139
+ </div>
140
+ </div>
141
+ );
142
+ }
@@ -0,0 +1,70 @@
1
+ import {
2
+ adminPanelClass,
3
+ AdminPanelBody,
4
+ AdminPanelHeader,
5
+ DelayedFallback,
6
+ responseJson,
7
+ } from "@open-workspace/core/ui";
8
+ import { useQuery, useQueryClient } from "@tanstack/react-query";
9
+ import { LoaderCircle, PenLine } from "lucide-react";
10
+
11
+ import { mailApi } from "../lib/mail-api";
12
+ import { mailboxesQuery } from "../mail/mail-queries";
13
+ import { signatureQuery } from "./settings-queries";
14
+ import { SignatureEditor } from "./signature-editor";
15
+ import type { SignatureBody } from "./signature-editor";
16
+
17
+ export function SignatureSettings() {
18
+ const client = useQueryClient();
19
+ const mailboxes = useQuery(mailboxesQuery());
20
+
21
+ // The editor keeps its own state once loaded; a save refreshes the cache.
22
+ const saved = useQuery(signatureQuery);
23
+
24
+ const uploadMailbox = mailboxes.data?.mailboxes.find(
25
+ (mailbox) => mailbox.kind === "personal" && mailbox.canSend
26
+ );
27
+
28
+ async function save(body: SignatureBody) {
29
+ await responseJson(await mailApi.api.mail.signature.$put({ json: body }));
30
+ await Promise.all([
31
+ client.invalidateQueries({ queryKey: signatureQuery.queryKey }),
32
+ client.invalidateQueries({ queryKey: mailboxesQuery().queryKey }),
33
+ ]);
34
+ }
35
+
36
+ return (
37
+ <div className={adminPanelClass}>
38
+ <AdminPanelHeader
39
+ Icon={PenLine}
40
+ title="Signature"
41
+ description="Added to messages you send from your own mailboxes. Shared inboxes use the signature their team sets."
42
+ />
43
+ <AdminPanelBody>
44
+ <DelayedFallback
45
+ pending={saved.isPending || mailboxes.isPending}
46
+ fallback={
47
+ <div className="text-muted-foreground flex items-center gap-2 py-5 text-sm">
48
+ <LoaderCircle className="size-4 animate-spin" /> Loading
49
+ signature…
50
+ </div>
51
+ }
52
+ >
53
+ {saved.data ? (
54
+ <SignatureEditor
55
+ saved={saved.data.signature}
56
+ uploadMailboxId={uploadMailbox?.id}
57
+ label="Your signature"
58
+ placeholder="Your name, role, phone…"
59
+ onSave={save}
60
+ />
61
+ ) : (
62
+ <p className="text-destructive py-4 text-sm">
63
+ Your signature couldn't be loaded.
64
+ </p>
65
+ )}
66
+ </DelayedFallback>
67
+ </AdminPanelBody>
68
+ </div>
69
+ );
70
+ }