@open-workspace/email 0.3.0 → 0.4.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 (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -0,0 +1,409 @@
1
+ import { closeHistory } from "@tiptap/pm/history";
2
+ import { Fragment } from "@tiptap/pm/model";
3
+ import type { Node as ProseMirrorNode, Schema } from "@tiptap/pm/model";
4
+ import { Plugin, PluginKey, Selection } from "@tiptap/pm/state";
5
+ import type { EditorState, Transaction } from "@tiptap/pm/state";
6
+ import { Step, StepResult } from "@tiptap/pm/transform";
7
+ import type { Mappable } from "@tiptap/pm/transform";
8
+ import type { EditorView } from "@tiptap/pm/view";
9
+
10
+ import type {
11
+ ComposerAsset,
12
+ ComposerAssetIntent,
13
+ ComposerSession,
14
+ } from "./composer-session";
15
+
16
+ type AssetBookmark = {
17
+ assetId: string;
18
+ intent: ComposerAssetIntent;
19
+ pos: number;
20
+ };
21
+
22
+ type BookmarkState = ReadonlyMap<string, AssetBookmark>;
23
+
24
+ /** A transaction's note to keep these assets' bookmarks though their nodes went. */
25
+ class PreserveRemoved {
26
+ constructor(readonly assetIds: ReadonlySet<string>) {}
27
+ }
28
+
29
+ const composerAssetBookmarksKey = new PluginKey<BookmarkState>(
30
+ "composerAssetBookmarks"
31
+ );
32
+
33
+ class AssetBookmarkStep extends Step {
34
+ constructor(
35
+ readonly bookmark: AssetBookmark,
36
+ readonly add: boolean
37
+ ) {
38
+ super();
39
+ }
40
+
41
+ apply(doc: ProseMirrorNode) {
42
+ return StepResult.ok(doc);
43
+ }
44
+
45
+ invert() {
46
+ return new AssetBookmarkStep(this.bookmark, !this.add);
47
+ }
48
+
49
+ map(mapping: Mappable) {
50
+ return new AssetBookmarkStep(
51
+ {
52
+ ...this.bookmark,
53
+ pos: mapping.map(this.bookmark.pos, 1),
54
+ },
55
+ this.add
56
+ );
57
+ }
58
+
59
+ toJSON() {
60
+ return {
61
+ stepType: "openworkspaceAssetBookmark",
62
+ bookmark: this.bookmark,
63
+ add: this.add,
64
+ };
65
+ }
66
+
67
+ static fromJSON(
68
+ _schema: Schema,
69
+ value: {
70
+ bookmark: AssetBookmark;
71
+ add: boolean;
72
+ }
73
+ ) {
74
+ return new AssetBookmarkStep(value.bookmark, value.add);
75
+ }
76
+ }
77
+
78
+ // History keeps the Step instances in memory, while JSON registration makes
79
+ // the operation safe if ProseMirror history is serialized in the future.
80
+ try {
81
+ Step.jsonID("openworkspaceAssetBookmark", AssetBookmarkStep);
82
+ } catch (error) {
83
+ if (
84
+ !(error instanceof RangeError && error.message.includes("Duplicate use"))
85
+ ) {
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ function visibleAssets(doc: ProseMirrorNode) {
91
+ const result = new Map<string, AssetBookmark>();
92
+ doc.descendants((node, pos) => {
93
+ if (node.type.name !== "composerAsset") return;
94
+ const assetId = String(node.attrs.assetId ?? "");
95
+ const intent = node.attrs.intent === "inline" ? "inline" : "attachment";
96
+
97
+ if (assetId) result.set(assetId, { assetId, intent, pos });
98
+ });
99
+
100
+ return result;
101
+ }
102
+
103
+ function applyBookmarkTransaction(
104
+ transaction: Transaction,
105
+ value: BookmarkState,
106
+ oldState: EditorState,
107
+ newState: EditorState
108
+ ) {
109
+ const next = new Map<string, AssetBookmark>();
110
+
111
+ for (const bookmark of value.values()) {
112
+ next.set(bookmark.assetId, {
113
+ ...bookmark,
114
+ pos: transaction.mapping.map(bookmark.pos, 1),
115
+ });
116
+ }
117
+
118
+ const before = visibleAssets(oldState.doc);
119
+ const after = visibleAssets(newState.doc);
120
+
121
+ const meta: unknown = transaction.getMeta(composerAssetBookmarksKey);
122
+ const preserved = meta instanceof PreserveRemoved ? meta.assetIds : null;
123
+
124
+ for (const assetId of before.keys()) {
125
+ if (!after.has(assetId) && !preserved?.has(assetId)) {
126
+ next.delete(assetId);
127
+ }
128
+ }
129
+
130
+ for (const bookmark of after.values()) next.set(bookmark.assetId, bookmark);
131
+
132
+ // Explicit bookmark steps must win over the document-derived projection.
133
+ // That lets undo remove a link card inserted by reconciliation.
134
+ for (const step of transaction.steps) {
135
+ if (!(step instanceof AssetBookmarkStep)) continue;
136
+
137
+ if (step.add) next.set(step.bookmark.assetId, step.bookmark);
138
+ else next.delete(step.bookmark.assetId);
139
+ }
140
+
141
+ return next;
142
+ }
143
+
144
+ function bookmarkSignature(bookmarks: BookmarkState) {
145
+ return [...bookmarks.keys()].sort().join("\0");
146
+ }
147
+
148
+ export function reconcileComposerAssetNodes(
149
+ view: EditorView,
150
+ session: ComposerSession
151
+ ) {
152
+ const bookmarks = composerAssetBookmarksKey.getState(view.state);
153
+
154
+ if (!bookmarks) return;
155
+ const snapshot = session.getSnapshot();
156
+ const assets = new Map(snapshot.assets.map((asset) => [asset.id, asset]));
157
+ const visible = visibleAssets(view.state.doc);
158
+ const hide: { assetId: string; from: number; to: number }[] = [];
159
+ const show: AssetBookmark[] = [];
160
+
161
+ for (const node of visible.values()) {
162
+ if (!bookmarks.has(node.assetId)) {
163
+ hide.push({
164
+ assetId: node.assetId,
165
+ from: node.pos,
166
+ to: node.pos + 1,
167
+ });
168
+ }
169
+ }
170
+
171
+ for (const bookmark of bookmarks.values()) {
172
+ const asset = assets.get(bookmark.assetId);
173
+ const node = visible.get(bookmark.assetId);
174
+
175
+ if (!asset) {
176
+ if (node) {
177
+ hide.push({
178
+ assetId: bookmark.assetId,
179
+ from: node.pos,
180
+ to: node.pos + 1,
181
+ });
182
+ }
183
+
184
+ continue;
185
+ }
186
+
187
+ const shouldBeVisible =
188
+ asset.intent === "inline" ||
189
+ asset.status === "error" ||
190
+ snapshot.linkedAssetIds.has(asset.id);
191
+
192
+ if (shouldBeVisible && !node) show.push(bookmark);
193
+
194
+ if (!shouldBeVisible && node) {
195
+ hide.push({
196
+ assetId: bookmark.assetId,
197
+ from: node.pos,
198
+ to: node.pos + 1,
199
+ });
200
+ }
201
+ }
202
+
203
+ if (!hide.length && !show.length) return;
204
+
205
+ let transaction = view.state.tr;
206
+ const preserved = new Set<string>();
207
+
208
+ for (const range of hide.sort((left, right) => right.from - left.from)) {
209
+ transaction = transaction.delete(range.from, range.to);
210
+ preserved.add(range.assetId);
211
+ }
212
+
213
+ for (const bookmark of show) {
214
+ const asset = assets.get(bookmark.assetId);
215
+
216
+ if (!asset) continue;
217
+
218
+ const position = Math.min(
219
+ transaction.doc.content.size,
220
+ transaction.mapping.map(bookmark.pos, 1)
221
+ );
222
+
223
+ transaction = transaction.insert(
224
+ position,
225
+ view.state.schema.node("composerAsset", {
226
+ assetId: asset.id,
227
+ intent: asset.intent,
228
+ })
229
+ );
230
+ }
231
+
232
+ if (!transaction.docChanged) return;
233
+ view.dispatch(
234
+ transaction
235
+ .setMeta(composerAssetBookmarksKey, new PreserveRemoved(preserved))
236
+ .setMeta("addToHistory", false)
237
+ );
238
+ }
239
+
240
+ export function createComposerAssetBookmarksPlugin(
241
+ session: ComposerSession,
242
+ onAssetsChanged: (assetIds: string[]) => void
243
+ ) {
244
+ return new Plugin<BookmarkState>({
245
+ key: composerAssetBookmarksKey,
246
+ state: {
247
+ init: () => new Map(),
248
+ apply: applyBookmarkTransaction,
249
+ },
250
+ view(initialView) {
251
+ let view = initialView;
252
+ let destroyed = false;
253
+ let reconcileQueued = false;
254
+ let lastSignature = "";
255
+
256
+ const notifyBookmarks = () => {
257
+ const bookmarks =
258
+ composerAssetBookmarksKey.getState(view.state) ?? new Map();
259
+
260
+ const signature = bookmarkSignature(bookmarks);
261
+
262
+ if (signature === lastSignature) return false;
263
+ lastSignature = signature;
264
+ onAssetsChanged([...bookmarks.keys()]);
265
+
266
+ return true;
267
+ };
268
+
269
+ const queueReconcile = () => {
270
+ if (reconcileQueued || destroyed) return;
271
+ reconcileQueued = true;
272
+ queueMicrotask(() => {
273
+ reconcileQueued = false;
274
+
275
+ if (!destroyed) reconcileComposerAssetNodes(view, session);
276
+ });
277
+ };
278
+
279
+ let sessionAssets = session.getSnapshot().assets;
280
+ let { linkedAssetIds } = session.getSnapshot();
281
+
282
+ const unsubscribe = session.subscribe(() => {
283
+ const snapshot = session.getSnapshot();
284
+
285
+ if (
286
+ snapshot.assets === sessionAssets &&
287
+ snapshot.linkedAssetIds === linkedAssetIds
288
+ ) {
289
+ return;
290
+ }
291
+
292
+ sessionAssets = snapshot.assets;
293
+ linkedAssetIds = snapshot.linkedAssetIds;
294
+ queueReconcile();
295
+ });
296
+
297
+ notifyBookmarks();
298
+ queueReconcile();
299
+
300
+ return {
301
+ update(nextView) {
302
+ view = nextView;
303
+
304
+ if (notifyBookmarks()) queueReconcile();
305
+ },
306
+ destroy() {
307
+ destroyed = true;
308
+ unsubscribe();
309
+ },
310
+ };
311
+ },
312
+ });
313
+ }
314
+
315
+ export function insertComposerAssets(
316
+ state: EditorState,
317
+ assets: ComposerAsset[],
318
+ position?: number
319
+ ) {
320
+ if (!assets.length) return null;
321
+
322
+ const start = Math.min(
323
+ position ?? state.selection.from,
324
+ state.doc.content.size
325
+ );
326
+
327
+ let transaction = closeHistory(state.tr);
328
+ let insertionPosition = start;
329
+
330
+ for (const asset of assets) {
331
+ if (asset.intent === "inline") {
332
+ transaction = transaction.insert(
333
+ insertionPosition,
334
+ state.schema.node("composerAsset", {
335
+ assetId: asset.id,
336
+ intent: asset.intent,
337
+ })
338
+ );
339
+ transaction = transaction.step(
340
+ new AssetBookmarkStep(
341
+ {
342
+ assetId: asset.id,
343
+ intent: asset.intent,
344
+ pos: insertionPosition,
345
+ },
346
+ true
347
+ )
348
+ );
349
+ insertionPosition += 1;
350
+ continue;
351
+ }
352
+
353
+ transaction = transaction.step(
354
+ new AssetBookmarkStep(
355
+ {
356
+ assetId: asset.id,
357
+ intent: asset.intent,
358
+ pos: insertionPosition,
359
+ },
360
+ true
361
+ )
362
+ );
363
+ }
364
+
365
+ if (assets.some((asset) => asset.intent === "inline")) {
366
+ transaction = transaction.setSelection(
367
+ Selection.near(
368
+ transaction.doc.resolve(
369
+ Math.min(insertionPosition, transaction.doc.content.size)
370
+ ),
371
+ 1
372
+ )
373
+ );
374
+ }
375
+
376
+ return transaction;
377
+ }
378
+
379
+ export function removeComposerAsset(state: EditorState, assetId: string) {
380
+ const visible = visibleAssets(state.doc).get(assetId);
381
+
382
+ if (visible) {
383
+ return closeHistory(state.tr).delete(visible.pos, visible.pos + 1);
384
+ }
385
+
386
+ const bookmark = composerAssetBookmarksKey.getState(state)?.get(assetId);
387
+
388
+ return bookmark
389
+ ? closeHistory(state.tr).step(new AssetBookmarkStep(bookmark, false))
390
+ : null;
391
+ }
392
+
393
+ export function composerAssetIds(state: EditorState) {
394
+ return [...(composerAssetBookmarksKey.getState(state)?.keys() ?? [])];
395
+ }
396
+
397
+ export function withoutComposerAssetNodes(fragment: Fragment): Fragment {
398
+ const children: ProseMirrorNode[] = [];
399
+ fragment.forEach((node) => {
400
+ if (node.type.name === "composerAsset") return;
401
+ children.push(
402
+ node.content.size > 0
403
+ ? node.copy(withoutComposerAssetNodes(node.content))
404
+ : node
405
+ );
406
+ });
407
+
408
+ return Fragment.fromArray(children);
409
+ }
@@ -0,0 +1,229 @@
1
+ import { required } from "@open-workspace/core/shared";
2
+ import { Button, cn } from "@open-workspace/core/ui";
3
+ import { closeHistory } from "@tiptap/pm/history";
4
+ import {
5
+ mergeAttributes,
6
+ Node,
7
+ NodeViewWrapper,
8
+ ReactNodeViewRenderer,
9
+ } from "@tiptap/react";
10
+ import type { ReactNodeViewProps } from "@tiptap/react";
11
+ import { FileText, GripVertical, Link2, LoaderCircle, X } from "lucide-react";
12
+ import { useSyncExternalStore } from "react";
13
+
14
+ import { createComposerAssetBookmarksPlugin } from "./composer-asset-bookmarks";
15
+ import { linkedAttachmentPlainText } from "./composer-linked-attachment-text";
16
+ import type {
17
+ ComposerAsset as ComposerAssetRecord,
18
+ ComposerSession,
19
+ } from "./composer-session";
20
+ import { formatBytes } from "./format-bytes";
21
+
22
+ function LinkedAssetContent({ asset }: { asset: ComposerAssetRecord }) {
23
+ return (
24
+ <>
25
+ <GripVertical
26
+ className="text-muted-foreground/55 group-hover/composer-asset:text-muted-foreground size-3.5 shrink-0 transition-colors"
27
+ aria-hidden
28
+ />
29
+ <span className="bg-info/10 text-info grid size-8 shrink-0 place-items-center rounded-md">
30
+ <FileText className="size-4" />
31
+ </span>
32
+ <span className="min-w-0 flex-1">
33
+ <span className="block truncate text-xs font-semibold">
34
+ {asset.filename}
35
+ </span>
36
+ <span className="text-muted-foreground mt-0.5 flex items-center gap-1.5 text-[10px]">
37
+ <span>{formatBytes(asset.size)}</span>
38
+ <span aria-hidden>·</span>
39
+ <span className="inline-flex items-center gap-1">
40
+ {asset.status === "uploading" ? (
41
+ <LoaderCircle className="size-2.5 animate-spin" />
42
+ ) : (
43
+ <Link2 className="size-2.5" />
44
+ )}
45
+ {asset.status === "uploading"
46
+ ? "Uploading"
47
+ : asset.status === "error"
48
+ ? "Upload failed"
49
+ : "30-day link"}
50
+ </span>
51
+ </span>
52
+ </span>
53
+ </>
54
+ );
55
+ }
56
+
57
+ function ComposerAssetNodeView({
58
+ editor,
59
+ getPos,
60
+ node,
61
+ selected,
62
+ session,
63
+ }: ReactNodeViewProps & { session: ComposerSession }) {
64
+ const snapshot = useSyncExternalStore(
65
+ session.subscribe,
66
+ session.getSnapshot,
67
+ session.getSnapshot
68
+ );
69
+
70
+ const assetId = String(node.attrs.assetId ?? "");
71
+ const asset = snapshot.assets.find((candidate) => candidate.id === assetId);
72
+
73
+ if (!asset) {
74
+ return <NodeViewWrapper as="span" className="hidden" />;
75
+ }
76
+
77
+ const linked = snapshot.linkedAssetIds.has(asset.id);
78
+
79
+ const imageUrl =
80
+ asset.intent === "inline" && !linked ? asset.previewUrl : null;
81
+
82
+ const remove = () => {
83
+ const position = getPos();
84
+
85
+ if (position === undefined) return;
86
+ editor.view.dispatch(
87
+ closeHistory(editor.state.tr).delete(position, position + node.nodeSize)
88
+ );
89
+ };
90
+
91
+ if (imageUrl) {
92
+ return (
93
+ <NodeViewWrapper
94
+ as="span"
95
+ data-drag-handle
96
+ className="inline-block max-w-full align-middle"
97
+ >
98
+ <img
99
+ className={cn(
100
+ "composer-inline-image",
101
+ selected && "outline-primary/70 outline-2"
102
+ )}
103
+ src={imageUrl}
104
+ alt={asset.filename}
105
+ title={asset.filename}
106
+ draggable={false}
107
+ />
108
+ </NodeViewWrapper>
109
+ );
110
+ }
111
+
112
+ return (
113
+ <NodeViewWrapper
114
+ as="span"
115
+ data-drag-handle
116
+ data-linked-attachment-node
117
+ role="group"
118
+ aria-label={`${asset.filename}, linked attachment`}
119
+ className={cn(
120
+ "group/composer-asset border-border bg-surface-sunken/70 my-2 inline-flex min-h-12 w-full max-w-full cursor-grab items-center gap-2.5 rounded-lg border px-2.5 py-2 align-middle shadow-xs transition-[border-color,box-shadow,background-color] active:cursor-grabbing",
121
+ "hover:border-primary/45 hover:bg-accent/45",
122
+ selected && "border-primary/70 ring-primary/25 ring-2"
123
+ )}
124
+ >
125
+ <LinkedAssetContent asset={asset} />
126
+ <Button
127
+ type="button"
128
+ variant="ghost"
129
+ size="icon-xs"
130
+ aria-label={`Remove ${asset.filename}`}
131
+ contentEditable={false}
132
+ draggable={false}
133
+ onClick={remove}
134
+ >
135
+ <X />
136
+ </Button>
137
+ </NodeViewWrapper>
138
+ );
139
+ }
140
+
141
+ /** The composer's session; set with `configure()` (null only until then). */
142
+ function configuredSession(session: ComposerSession | null) {
143
+ return required(session, "ComposerAsset needs configure({ session })");
144
+ }
145
+
146
+ export const ComposerAsset = Node.create<{
147
+ session: ComposerSession | null;
148
+ onAssetsChanged: (assetIds: string[]) => void;
149
+ }>({
150
+ name: "composerAsset",
151
+ group: "inline",
152
+ inline: true,
153
+ atom: true,
154
+ draggable: true,
155
+ selectable: true,
156
+
157
+ addOptions() {
158
+ return {
159
+ session: null,
160
+ onAssetsChanged: () => {},
161
+ };
162
+ },
163
+
164
+ addAttributes() {
165
+ return {
166
+ assetId: { default: "", rendered: false },
167
+ intent: { default: "attachment", rendered: false },
168
+ };
169
+ },
170
+
171
+ parseHTML() {
172
+ return [
173
+ {
174
+ tag: "span[data-composer-asset]",
175
+ getAttrs: (element) => {
176
+ if (!(element instanceof HTMLElement)) return false;
177
+
178
+ return {
179
+ assetId: element.dataset.composerAsset ?? "",
180
+ intent:
181
+ element.dataset.composerAssetIntent === "inline"
182
+ ? "inline"
183
+ : "attachment",
184
+ };
185
+ },
186
+ },
187
+ ];
188
+ },
189
+
190
+ renderHTML({ node, HTMLAttributes }) {
191
+ return [
192
+ "span",
193
+ mergeAttributes(HTMLAttributes, {
194
+ "data-composer-asset": node.attrs.assetId,
195
+ "data-composer-asset-intent": node.attrs.intent,
196
+ }),
197
+ ];
198
+ },
199
+
200
+ renderText({ node }) {
201
+ const session = configuredSession(this.options.session);
202
+ const asset = session.getAsset(String(node.attrs.assetId));
203
+
204
+ if (!asset) return "";
205
+
206
+ return session.isLinked(asset.id)
207
+ ? linkedAttachmentPlainText(asset.uploadId, asset.filename)
208
+ : asset.intent === "inline"
209
+ ? asset.filename
210
+ : "";
211
+ },
212
+
213
+ addNodeView() {
214
+ const session = configuredSession(this.options.session);
215
+
216
+ return ReactNodeViewRenderer((props) => (
217
+ <ComposerAssetNodeView {...props} session={session} />
218
+ ));
219
+ },
220
+
221
+ addProseMirrorPlugins() {
222
+ return [
223
+ createComposerAssetBookmarksPlugin(
224
+ configuredSession(this.options.session),
225
+ this.options.onAssetsChanged
226
+ ),
227
+ ];
228
+ },
229
+ });