From 06f51486e0444643bfbe8a7891c128467e32425b Mon Sep 17 00:00:00 2001 From: bartfaizoli76 Date: Sat, 5 Sep 2026 11:14:10 +0200 Subject: [PATCH] feat: add attachment-actions and composer-attachment-source plugin slots Two new extension points for third-party attachment/cloud-storage plugins (e.g. a WebDAV/Nextcloud file browser), neither of which the plugin API currently supports: - attachment-actions: a new slot rendered into every attachment's hover action row (all six render paths: beside-sender/below-header/mobile, each in its compact and expanded-popup form), with the AttachmentInfo (name, type, size, blobId, emailId) passed through extraProps. Lets a plugin offer a 'save this attachment elsewhere' action next to the existing download/preview buttons - previously the only per-attachment hook was the read-only onAttachmentDownload observer. - composer-attachment-source: a new slot rendered in the composer toolbar next to the existing composer-toolbar slot, with an onAttach(upload) callback in extraProps. Lets a plugin that has already uploaded a file to the JMAP server itself (api.jmap.uploadBlob) - e.g. a file picked from an external cloud storage browser - have it added to the current draft as a real attachment. Previously there was no way for a plugin to add an attachment to the draft at all; the closest existing mechanism (onBeforeBlobUpload's ExternalAttachmentResult) only replaces a locally picked file with body text/a link, it cannot add a brand-new attachment from an external source. Both slots follow the existing PluginSlot pattern (calendar-event-actions): render nothing when no plugin offers the slot, so this is purely additive. Motivating use case: the existing nextcloud-attachments community plugin uploads local files to Nextcloud and appends a share link to the message body - useful for large files, but there was no way for a plugin to do the inverse (attach a file that already lives in cloud storage as a real binary attachment, not a link) or to let attachment recipients save an incoming attachment back out to their own cloud storage. These two slots make both directions possible without touching plugin-store or the sandbox bridge - existing slot/extraProps plumbing (see calendar-event-actions) already supports arbitrary POJO props. --- ...composer-plugin-attachment-source.test.tsx | 255 ++++++++++++++++++ components/email/email-composer.tsx | 29 +- components/email/email-viewer.tsx | 78 ++++++ lib/plugin-types.ts | 18 +- 4 files changed, 378 insertions(+), 2 deletions(-) create mode 100644 components/email/__tests__/composer-plugin-attachment-source.test.tsx diff --git a/components/email/__tests__/composer-plugin-attachment-source.test.tsx b/components/email/__tests__/composer-plugin-attachment-source.test.tsx new file mode 100644 index 000000000..5d56503b9 --- /dev/null +++ b/components/email/__tests__/composer-plugin-attachment-source.test.tsx @@ -0,0 +1,255 @@ +import { render, screen, fireEvent, act } from '@testing-library/react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import React from 'react'; +import { EmailComposer } from '../email-composer'; +import { useAuthStore } from '@/stores/auth-store'; + +// ─── Heavy component mocks (mirrors composer-draft-attachments.test.tsx) ───── + +vi.mock('@/components/email/rich-text-editor', () => ({ + RichTextEditor: () => React.createElement('div', { 'data-testid': 'rich-text-editor' }), +})); + +// A stand-in "cloud storage" plugin: renders a single button for the +// composer-attachment-source slot which, on click, calls the `onAttach` +// callback the host passed through extraProps - exactly what a real plugin +// does after it has uploaded a picked file to JMAP itself (api.jmap.uploadBlob). +// Every other slot renders nothing, matching the rest of the test suite. +vi.mock('@/components/plugins/plugin-slot', () => ({ + PluginSlot: ({ name, extraProps }: { name: string; extraProps?: Record }) => { + if (name !== 'composer-attachment-source') return null; + const onAttach = extraProps?.onAttach as + | ((f: { blobId: string; name: string; type: string; size: number }) => void) + | undefined; + return React.createElement( + 'button', + { + type: 'button', + 'data-testid': 'fake-cloud-storage-plugin', + onClick: () => + onAttach?.({ blobId: 'cloud-blob-1', name: 'vacation.jpg', type: 'image/jpeg', size: 42_000 }), + }, + 'Attach from cloud storage', + ); + }, +})); + +vi.mock('@/components/identity/sub-address-helper', () => ({ SubAddressHelper: () => null })); +vi.mock('@/components/templates/template-picker', () => ({ TemplatePicker: () => null })); +vi.mock('@/components/templates/template-form', () => ({ TemplateForm: () => null })); +vi.mock('@/components/files/file-preview-modal', () => ({ FilePreviewModal: () => null })); +vi.mock('@/hooks/use-focus-trap', () => ({ + useFocusTrap: () => ({ current: null }), +})); +vi.mock('@/hooks/use-pro-multi-account-identities', () => ({ + useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }), + stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }), +})); + +// ─── Store mocks ────────────────────────────────────────────────────────────── + +vi.mock('@/stores/auth-store', () => { + const state = { + client: null, + identities: [], + primaryIdentity: null, + isAuthenticated: false, + isDemoMode: false, + activeAccountId: null, + connectionLost: false, + getClientForAccount: () => undefined, + getAllConnectedClients: () => new Map(), + syncIdentities: () => {}, + refreshIdentities: async () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useAuthStore: hook }; +}); + +vi.mock('@/stores/identity-store', () => { + const state = { + identities: [{ id: 'id-me', email: 'me@example.com', name: 'Me' }], + defaultIdentityId: 'id-me', + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useIdentityStore: hook }; +}); + +vi.mock('@/stores/account-store', () => { + const state = { accounts: [], getAccountById: () => undefined }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useAccountStore: hook }; +}); + +vi.mock('@/stores/email-store', () => { + const state = { + draftSaveEnabled: false, + sendRawEmail: async () => ({ sent: true }), + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useEmailStore: hook }; +}); + +vi.mock('@/stores/settings-store', () => { + const state = { + timeFormat: '24h', + plainTextMode: false, + subAddressDelimiter: '+', + autoSelectReplyIdentity: true, + attachmentReminderEnabled: false, + attachmentReminderKeywords: [], + emptySubjectWarningEnabled: true, + sendDelaySeconds: 0, + signaturePosition: 'above_quote', + signatureSeparatorEnabled: false, + requestReadReceiptDefault: false, + addTrustedSender: () => {}, + trustedSendersAddressBook: null, + updateSetting: () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useSettingsStore: hook }; +}); + +vi.mock('@/stores/contact-store', () => { + const state = { + contacts: [], + getAutocomplete: async () => [], + addToTrustedSendersBook: async () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useContactStore: hook }; +}); + +vi.mock('@/stores/template-store', () => { + const state = { templates: [], addTemplate: async () => {} }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useTemplateStore: hook }; +}); + +// ─── Misc dependency mocks ──────────────────────────────────────────────────── + +vi.mock('@/stores/toast-store', () => ({ + toast: { info: () => {}, error: () => {}, success: () => {} }, +})); + +vi.mock('@/lib/plugin-hooks', () => ({ + emailHooks: { + onComposerOpen: { call: async () => [] }, + onRecipientChange: { call: async () => [] }, + getRecipientSuggestions: { call: async () => [] }, + onRecipientChipsChange: { transform: async (chips: unknown) => chips }, + onDraftChange: { emit: () => {} }, + onBeforeDraftAutoSave: { transform: async (draft: unknown) => draft }, + onBeforeEmailSend: { intercept: async () => true }, + onComposeSend: { intercept: async () => true }, + onTransformOutgoingEmail: { transform: async (email: unknown) => email }, + }, + contactHooks: { + search: { call: async () => [] }, + onProvideRecipientSuggestions: { transform: async (initial: unknown) => initial }, + }, +})); + +vi.mock('@/lib/email-sanitization', () => ({ + sanitizeSignatureHtml: (v: string) => v, + sanitizeEmailHtml: (v: string) => v, + parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'), +})); + +vi.mock('@/lib/email-threading', () => ({ + computeReplyThreadingHeaders: () => ({ inReplyTo: [], references: [] }), +})); +vi.mock('@/lib/signature-utils', () => ({ + appendPlainTextSignature: (body: string) => body, + getPlainTextSignature: () => '', + plainTextBodyHasSignature: () => false, + plainTextBodyWithoutSignature: (body: string) => body, +})); +vi.mock('@/lib/sub-addressing', () => ({ generateSubAddress: () => '' })); +vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } })); +vi.mock('@/components/email/quoted-html', () => ({ + buildQuotedHtmlBlock: () => '', + serializeEditorContent: () => '', +})); +vi.mock('@/lib/template-utils', () => ({ substitutePlaceholders: (s: string) => s })); + +// ─── Tests ──────────────────────────────────────────────────────────────────── + +/** + * A plugin rendered into the composer-attachment-source slot (e.g. a WebDAV / + * cloud-storage file browser) uploads the file it picked to JMAP itself, then + * calls the `onAttach` callback the host handed it via extraProps to have the + * result added to the draft - without ever touching the local file picker or + * drag-drop path. + */ +describe('composer-attachment-source plugin slot', () => { + afterEach(() => { + useAuthStore.setState({ client: null }); + vi.clearAllMocks(); + }); + + it('adds a plugin-supplied blob as an attachment chip when onAttach is called', async () => { + render(); + + fireEvent.click(screen.getByTestId('fake-cloud-storage-plugin')); + + expect(await screen.findByText('vacation.jpg')).toBeInTheDocument(); + }); + + it('includes the plugin-supplied attachment (by blobId, no local File) in the next save', async () => { + const createDraft = vi.fn().mockResolvedValueOnce('draft-1'); + useAuthStore.setState({ + client: { + createDraft, + getEmail: vi.fn(), + hasDelayedSend: () => false, + getMaxDelayedSend: () => 0, + } as never, + }); + + render(); + fireEvent.click(screen.getByTestId('fake-cloud-storage-plugin')); + expect(screen.getByText('vacation.jpg')).toBeInTheDocument(); + + // Fake timers only from here on - the autosave debounce below needs + // vi.advanceTimersByTimeAsync, but findBy*'s own internal polling (not + // used above, kept in mind for future edits to this test) would hang + // forever under fake time with nothing driving it forward. + vi.useFakeTimers(); + + // Any edit marks the draft dirty and arms the autosave debounce. + fireEvent.change(screen.getByPlaceholderText(/subject/i), { + target: { value: 'Photos from the trip' }, + }); + await act(async () => { await vi.advanceTimersByTimeAsync(2500); }); + + expect(createDraft).toHaveBeenCalledTimes(1); + expect(createDraft.mock.calls[0][8]).toEqual([ + expect.objectContaining({ blobId: 'cloud-blob-1', name: 'vacation.jpg', size: 42_000 }), + ]); + + vi.useRealTimers(); + }); +}); diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx index b19bb55e0..493b55531 100644 --- a/components/email/email-composer.tsx +++ b/components/email/email-composer.tsx @@ -19,7 +19,7 @@ import { buildQuotedHtmlBlock, serializeEditorContent } from "@/components/email import { buildSignatureBlock, containsEmbeddedSignature, SIGNATURE_RANGE_MARKER } from "@/components/email/signature-block"; import { emailHooks, contactHooks, isExternalAttachmentResult } from "@/lib/plugin-hooks"; import { onUploadProgress } from "@/lib/upload-progress"; -import type { AlmostSavedDraft, OutgoingEmail, RecipientSuggestion } from "@/lib/plugin-types"; +import type { AlmostSavedDraft, OutgoingEmail, PluginAttachmentUpload, RecipientSuggestion } from "@/lib/plugin-types"; import { useAuthStore } from "@/stores/auth-store"; import { useIdentityStore } from "@/stores/identity-store"; import { useProMultiAccountIdentities, stripCrossAccountIdentityPrefix } from "@/hooks/use-pro-multi-account-identities"; @@ -1616,6 +1616,24 @@ export function EmailComposer({ setAttachments(prev => prev.filter((_, i) => i !== index)); }; + // Lets a plugin attach a file it has already uploaded to the JMAP server + // (via api.jmap.uploadBlob) without going through the local file-picker / + // drag-drop path - e.g. a plugin that browses an external WebDAV store and + // offers "attach from there". No `file` is set, matching the existing + // draft-part hydration path above (a blobId-only attachment is already a + // supported shape, just never previously reachable from a plugin). + const handlePluginAttachmentAdd = useCallback((upload: PluginAttachmentUpload) => { + setAttachments(prev => [ + ...prev, + { + name: upload.name, + type: upload.type, + size: upload.size, + blobId: upload.blobId, + }, + ]); + }, []); + // Inline preview for composer attachments, reusing the message viewer's // FilePreviewModal (so previewability and the open-in-new-tab safety gate are // handled there). Prefer the local File - no network - and fall back to the @@ -3107,6 +3125,15 @@ export function EmailComposer({ )} + {/* Lets a plugin offer an alternative attachment source (an + external file browser, cloud storage picker, etc). The plugin + calls `onAttach` once it has uploaded the chosen file to JMAP + itself (api.jmap.uploadBlob) and just wants it added to this + draft. */} + {/* Right side - Discard + Send (desktop) */} diff --git a/components/email/email-viewer.tsx b/components/email/email-viewer.tsx index 956ea9d4a..2407bdabb 100644 --- a/components/email/email-viewer.tsx +++ b/components/email/email-viewer.tsx @@ -4030,6 +4030,19 @@ export function EmailViewer({ )} + )} @@ -4090,6 +4103,19 @@ export function EmailViewer({ )} + )} @@ -4821,6 +4847,19 @@ export function EmailViewer({ )} + )} @@ -4881,6 +4920,19 @@ export function EmailViewer({ )} + )} @@ -4962,6 +5014,19 @@ export function EmailViewer({ )} + )} @@ -5021,6 +5086,19 @@ export function EmailViewer({ )} + )} diff --git a/lib/plugin-types.ts b/lib/plugin-types.ts index dde32867a..2332071b3 100644 --- a/lib/plugin-types.ts +++ b/lib/plugin-types.ts @@ -288,7 +288,9 @@ export type SlotName = | 'navigation-rail-bottom' | 'calendar-event-actions' | 'admin-plugin-page' - | 'contact-cryptokeys'; + | 'contact-cryptokeys' + | 'attachment-actions' + | 'composer-attachment-source'; export interface SlotRegistration { pluginId: string; @@ -874,6 +876,20 @@ export interface AttachmentInfo { emailId?: string; } +/** + * A file a plugin has already uploaded to the JMAP server (via + * `api.jmap.uploadBlob`) and wants attached to the email the user is + * currently composing. Passed to the `onAttach` callback a plugin receives + * through the `composer-attachment-source` slot's extraProps. + */ +export interface PluginAttachmentUpload { + /** JMAP blob id of the already-uploaded content. */ + blobId: string; + name: string; + type: string; + size: number; +} + /** * Initial value passed to the onAttachmentPreview transform hook. A handler * may return a different `previewUrl` (e.g. a proxied/sanitised URL) or a