Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(email): allow sending actual attachments in emails (#935)

dev-rb62e3d93244f3
diff --git a/js/app/packages/block-email/component/AttachMenu.tsx b/js/app/packages/block-email/component/AttachMenu.tsx
index caf07ee5f7..8ddd4c6f8e 100644
--- a/js/app/packages/block-email/component/AttachMenu.tsx
+++ b/js/app/packages/block-email/component/AttachMenu.tsx
@@ -1,30 +1,21 @@
import { EntityIcon } from '@core/component/EntityIcon';
-import { OldMenu, OldMenuItem } from '@core/component/OldMenu';
+import { DropdownMenuContent, MenuItem } from '@core/component/Menu';
import { blockAcceptedFileExtensions } from '@core/constant/allBlocks';
-import clickOutside from '@core/directive/clickOutside';
import { fileSelector } from '@core/directive/fileSelector';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { getItemBlockName } from '@core/util/getItemBlockName';
-import {
- autoUpdate,
- computePosition,
- flip,
- limitShift,
- offset,
- shift,
-} from '@floating-ui/dom';
import DeviceMobileIcon from '@icon/regular/device-mobile-speaker.svg';
import LaptopIcon from '@icon/regular/laptop.svg';
import SearchIcon from '@icon/regular/magnifying-glass.svg';
+import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import type { DocumentMentionInfo } from '@lexical-core';
import type { Item } from '@service-storage/generated/schemas/item';
import { useHistory } from '@service-storage/history';
import fuzzy from 'fuzzy';
import {
- createEffect,
createMemo,
createSignal,
- onCleanup,
+ type JSX,
type Setter,
Show,
} from 'solid-js';
@@ -33,13 +24,11 @@ import { handleFileUpload } from '../util/handleFileUpload';
// NOTE: solid directives
false && fileSelector;
-false && clickOutside;
type AttachMenuProps = {
- open: boolean;
- close: () => void;
- anchorRef: HTMLDivElement;
- containerRef: HTMLElement;
+ open?: boolean;
+ onClose?: () => void;
+ trigger: JSX.Element;
onAttach: (items: Item[]) => void;
onAttachDocuments?: (items: DocumentMentionInfo[]) => void;
attachedItems?: () => Item[];
@@ -52,34 +41,11 @@ function truncate(str: string, maxLength: number = 30) {
}
export function AttachMenu(props: AttachMenuProps) {
- const [position, setPosition] = createSignal({ x: 0, y: 0 });
- const [popupRef, setPopupRef] = createSignal<HTMLDivElement>();
const history = useHistory();
const attachedItems = () => props.attachedItems?.() ?? [];
const [input, setInput] = createSignal('');
- const updatePosition = async () => {
- const popupRef_ = popupRef();
- if (!popupRef_) return;
- const { x, y } = await computePosition(props.anchorRef, popupRef_, {
- placement: 'bottom-start',
- middleware: [
- offset(8),
- flip({
- fallbackStrategy: 'bestFit',
- boundary: props.containerRef,
- }),
- shift({
- padding: 8,
- boundary: props.containerRef,
- limiter: limitShift(),
- }),
- ],
- });
- setPosition({ x, y });
- };
-
const baseHistory = createMemo(() => {
return [...history()].filter(
(item) => !attachedItems().find((a) => a.id === item.id)
@@ -96,149 +62,105 @@ export function AttachMenu(props: AttachMenuProps) {
.map((item) => item.original);
});
- createEffect(() => {
- const popupRef_ = popupRef();
- if (!popupRef_) return;
-
- document.body.style.overflow = 'hidden';
- const cleanup = autoUpdate(props.anchorRef, popupRef_, updatePosition);
-
- onCleanup(() => {
- cleanup();
- document.body.style.overflow = '';
- });
- });
-
- const handleOverlayClick = (e: MouseEvent) => {
- if (e.target === e.currentTarget) {
- props.close();
- }
- };
-
return (
- <Show when={props.open}>
- <div
- class="fixed inset-0 bg-transparent z-item-options-menu"
- onClick={handleOverlayClick}
- onMouseDown={handleOverlayClick}
- >
- <div
- class="absolute z-item-options-menu"
- ref={setPopupRef}
- use:clickOutside={props.close}
- style={{
- left: `${position().x}px`,
- top: `${position().y}px`,
- 'transform-origin': 'top',
- }}
- >
- <OldMenu>
- <div class="flex flex-row items-center w-full p-2 gap-2 text-sm border-b border-edge text-ink mb-1">
- <SearchIcon class="w-3 h-3" />
- <input
- value={input()}
- onInput={(e) => setInput(e.target.value)}
- class="w-full"
- placeholder="Search Attachments"
- />
- </div>
- <div class="flex flex-col gap-1 max-h-[250px] w-[300px] overflow-y-auto">
- <Show
- when={rankedHistory().length > 0}
- fallback={
- <div class="p-2 w-full flex-col justify-center items-center">
- <p class="text-sm text-ink-muted">No results</p>
- </div>
- }
- >
- <VList
- data={rankedHistory()}
- bufferSize={10 * 40}
- itemSize={40}
- style={{ height: '100%', contain: 'content' }}
- >
- {(item) => (
- <OldMenuItem
- text={truncate(item.name)}
- icon={() => (
- <EntityIcon
- targetType={getItemBlockName(item, true)}
- size="xs"
- />
- )}
- onClick={() => {
- props.onAttach([item]);
- props.close();
- }}
- />
- )}
- </VList>
- </Show>
- </div>
- <div class="w-full h-px bg-edge mt-[1px]" />
- <div
+ <DropdownMenu
+ open={props.open}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) props.onClose?.();
+ }}
+ >
+ <DropdownMenu.Trigger>{props.trigger}</DropdownMenu.Trigger>
+
+ <DropdownMenu.Portal>
+ <DropdownMenuContent>
+ <div class="flex flex-row items-center w-full p-2 gap-2 text-sm border-b border-edge text-ink mb-1">
+ <SearchIcon class="w-3 h-3" />
+ <input
+ value={input()}
+ onInput={(e) => setInput(e.target.value)}
+ onKeyDown={(e) => e.stopImmediatePropagation()}
class="w-full"
- use:fileSelector={{
- acceptedFileExtensions: blockAcceptedFileExtensions,
- multiple: true,
- onSelect: async (files) => {
- if (props.setIsPending) {
- await handleFileUpload(
- files,
- props.setIsPending,
- (items) => {
- console.log(
- 'AttachMenu: File upload completed, items:',
- items
- );
- // Use direct DocumentMentionInfo if callback exists
- if (props.onAttachDocuments) {
- console.log(
- 'AttachMenu: Using onAttachDocuments callback'
- );
- props.onAttachDocuments(items);
- } else {
- console.log(
- 'AttachMenu: Using legacy onAttach callback'
- );
- // Fallback to Item conversion for backward compatibility
- const itemsToAttach = items.map((item) => ({
- id: item.documentId,
- name: item.documentName,
- type:
- item.blockName === 'project'
- ? 'project'
- : 'document',
- fileType:
- item.blockName !== 'project'
- ? item.blockName
- : undefined,
- })) as Item[];
- console.log(
- 'AttachMenu: Converted items:',
- itemsToAttach
- );
- props.onAttach(itemsToAttach);
- }
- }
- );
- }
- props.close();
- },
- }}
+ placeholder="Search Attachments"
+ />
+ </div>
+ <div class="flex flex-col gap-1 max-h-[250px] w-[300px] overflow-y-auto">
+ <Show
+ when={rankedHistory().length > 0}
+ fallback={
+ <div class="p-2 w-full flex-col justify-center items-center">
+ <p class="text-sm text-ink-muted">No results</p>
+ </div>
+ }
>
- <OldMenuItem
- text={
- isTouchDevice()
- ? 'Upload from your device'
- : 'Upload from your computer'
+ <VList
+ data={rankedHistory()}
+ bufferSize={10 * 40}
+ itemSize={40}
+ style={{ height: '100%', contain: 'content' }}
+ >
+ {(item) => (
+ <MenuItem
+ text={truncate(item.name)}
+ icon={() => (
+ <EntityIcon
+ targetType={getItemBlockName(item, true)}
+ size="xs"
+ />
+ )}
+ closeOnSelect
+ onClick={() => {
+ props.onAttach([item]);
+ }}
+ />
+ )}
+ </VList>
+ </Show>
+ </div>
+ <div class="w-full h-px bg-edge mt-[1px]" />
+ <div
+ class="w-full"
+ use:fileSelector={{
+ acceptedFileExtensions: blockAcceptedFileExtensions,
+ multiple: true,
+ onSelect: async (files) => {
+ if (props.setIsPending) {
+ await handleFileUpload(files, props.setIsPending, (items) => {
+ // Use direct DocumentMentionInfo if callback exists
+ if (props.onAttachDocuments) {
+ props.onAttachDocuments(items);
+ return;
+ }
+
+ // Fallback to Item conversion for backward compatibility
+ const itemsToAttach = items.map((item) => ({
+ id: item.documentId,
+ name: item.documentName,
+ type:
+ item.blockName === 'project' ? 'project' : 'document',
+ fileType:
+ item.blockName !== 'project'
+ ? item.blockName
+ : undefined,
+ })) as Item[];
+
+ props.onAttach(itemsToAttach);
+ });
}
- icon={isTouchDevice() ? DeviceMobileIcon : LaptopIcon}
- />
- </div>
- </OldMenu>
- </div>
- </div>
- </Show>
+ props.onClose?.();
+ },
+ }}
+ >
+ <MenuItem
+ text={
+ isTouchDevice()
+ ? 'Upload from your device'
+ : 'Upload from your computer'
+ }
+ icon={isTouchDevice() ? DeviceMobileIcon : LaptopIcon}
+ />
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenu.Portal>
+ </DropdownMenu>
);
}
diff --git a/js/app/packages/block-email/component/AttachmentPill.tsx b/js/app/packages/block-email/component/AttachmentPill.tsx
index 7f650a92fe..e46bf8fe6e 100644
--- a/js/app/packages/block-email/component/AttachmentPill.tsx
+++ b/js/app/packages/block-email/component/AttachmentPill.tsx
@@ -1,6 +1,5 @@
import { EntityIcon } from '@core/component/EntityIcon';
import X from '@icon/regular/x.svg';
-import type { Attachment } from '@service-email/generated/schemas/attachment';
import { FileTypeMap } from '@service-storage/fileTypeMap';
import type { FileType } from '@service-storage/generated/schemas/fileType';
import { Show } from 'solid-js';
@@ -9,17 +8,20 @@ const mimeToFileExtTypeMap = new Map<string, string>(
Object.values(FileTypeMap).map((value) => [value.mime, value.extension])
);
-export function EmailAttachmentPill(props: {
- attachment: Attachment;
+type EmailAttachmentPillProps = {
+ attachment: { fileName: string; mimeType?: string };
removable?: boolean;
onRemove?: () => void;
- onClick: (attachment: Attachment, fileType?: FileType) => void;
-}) {
+ onClick?: (fileType?: FileType) => void;
+};
+
+export function EmailAttachmentPill(props: EmailAttachmentPillProps) {
let parentDiv!: HTMLDivElement;
- const fileType = props.attachment.mime_type
- ? (mimeToFileExtTypeMap.get(props.attachment.mime_type) as FileType)
- : undefined;
+ const fileType = () =>
+ props.attachment.mimeType
+ ? (mimeToFileExtTypeMap.get(props.attachment.mimeType) as FileType)
+ : undefined;
return (
<div
@@ -28,15 +30,15 @@ export function EmailAttachmentPill(props: {
classList={{
'pl-2': props.removable,
}}
- onclick={() => props.onClick(props.attachment, fileType)}
+ onClick={() => props.onClick?.(fileType())}
>
- <Show when={fileType !== undefined || props.attachment.mime_type}>
+ <Show when={fileType() !== undefined || props.attachment.mimeType}>
<EntityIcon
- targetType={fileType ?? (props.attachment.mime_type as FileType)}
+ targetType={fileType() ?? (props.attachment.mimeType as FileType)}
size="xs"
/>
</Show>
- <div class="truncate ml-1">{props.attachment.filename}</div>
+ <div class="truncate ml-1">{props.attachment.fileName}</div>
<Show when={props.removable}>
<div
class="ml-auto p-2 hover:text-failure"
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index 290fd1bea2..380fd28361 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -1,3 +1,4 @@
+import { fileSelector } from '@core/directive/fileSelector';
import { FormatRibbon } from '@block-channel/component/FormatRibbon';
import { MacroSignatureButton } from '@block-email/component/MacroSignatureButton';
import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';
@@ -34,20 +35,16 @@ import { ToggleButton as KToggleButton } from '@kobalte/core/toggle-button';
import {
$appendWatermarkNodeToLast,
$removeAllWatermarkNodes,
- type DocumentMentionInfo,
} from '@lexical-core';
import { logger } from '@observability';
import { useEmailLinksQuery } from '@queries/email/link';
import { useSendMessageMutation } from '@queries/email/thread';
import type {
AttachmentMacro,
- MessageToSend,
MessageToSendDbId,
MessageWithBodyReplyless,
} from '@service-email/generated/schemas';
import { useEmail, useUserId } from '@service-gql/client';
-import type { FileType } from '@service-storage/generated/schemas/fileType';
-import type { Item } from '@service-storage/generated/schemas/item';
import { BrightJoins } from '@ui/components/BrightJoins';
import { Button } from '@ui/components/Button';
import {
@@ -72,10 +69,12 @@ import {
createMemo,
createSignal,
For,
+ Match,
onCleanup,
onMount,
type Setter,
Show,
+ Switch,
untrack,
} from 'solid-js';
import { createStore } from 'solid-js/store';
@@ -83,7 +82,6 @@ import { deleteEmailDraft, saveEmailDraft } from '../signal/emailDraft';
import { makeAttachmentPublic } from '../util/makeAttachmentPublic';
import { getFirstName } from '../util/name';
import {
- appendItemsAsMacroMentions,
clearEmailBody,
prepareEmailBody,
prepareMacroBody,
@@ -92,11 +90,20 @@ import {
} from '../util/prepareEmailBody';
import { convertEmailRecipientToContactInfo } from '../util/recipientConversion';
import { getReplyTypeFromDraft } from '../util/replyType';
-import { AttachMenu } from './AttachMenu';
import { type EmailRecipient, useEmailContext } from './EmailContext';
import { getOrInitEmailFormContext } from './EmailFormContext';
+import {
+ useRemoveDraftAttachmentMutation,
+ useUploadDraftAttachmentsMutation,
+} from '@queries/email/attachment';
+import { EmailAttachmentPill } from '@block-email/component/AttachmentPill';
+import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';
+import { plural } from '@core/util/string';
false && fileFolderDrop;
+false && fileSelector;
+
+const MAX_ATTACHMENTS_BYTES_SIZE = 18_000_000;
const getRecipientDisplayName = (item: EmailRecipient): string => {
switch (item.kind) {
@@ -160,11 +167,9 @@ export function BaseInput(props: {
createSignal<HTMLDivElement>();
const [editor, setEditor] = createSignal<LexicalEditor>();
const [showSubject, _] = createSignal(props.newMessage ?? false);
- const [attachMenuOpen, setAttachMenuOpen] = createSignal(false);
const [showExpandedRecipients, setShowExpandedRecipients] =
createSignal<boolean>(false);
const [isDragging, setIsDragging] = createSignal<boolean>();
- const [isPendingUpload, setIsPendingUpload] = createSignal<boolean>(false);
const [showFormatRibbon, setShowFormatRibbon] = createSignal<boolean>(
props.newMessage ?? false
);
@@ -204,6 +209,8 @@ export function BaseInput(props: {
},
});
+ const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();
+
function refetchThreadMessages() {
ctx.query.refetch();
}
@@ -246,12 +253,10 @@ export function BaseInput(props: {
const userId = useUserId();
const [userName] = useDisplayName(tryMacroId(userId() ?? ''));
- let bodyDiv!: HTMLDivElement;
- let attachButtonRef!: HTMLDivElement;
let draftSaveTimer: number | undefined;
const DRAFT_DEBOUNCE_MS = 1000;
- function collectDraft(): Omit<MessageToSend, 'link_id'> | null {
+ function collectDraft() {
$removeAllWatermarkNodes(editor());
const prepared = prepareEmailBody(editor());
if (!prepared) {
@@ -260,8 +265,12 @@ export function BaseInput(props: {
);
return null;
}
- // Fail if no body text
- if (prepared.bodyText.trim() === '') {
+ // Fail if no body text and no attachments
+ // You can have a draft with attachments and no body text
+ if (
+ prepared.bodyText.trim() === '' &&
+ form().attachments.list().length === 0
+ ) {
return null;
}
// We attach the drafts entirely using bodyHTML (because this is how the appended reply parsing works) so we are not including bodyMacro or bodyText
@@ -269,7 +278,6 @@ export function BaseInput(props: {
bcc: form().recipients.bcc.map(convertEmailRecipientToContactInfo),
body_html: prepared.bodyHtml,
cc: form().recipients.cc.map(convertEmailRecipientToContactInfo),
- // db_id: props.draft ? props.draft?.db_id : undefined,
provider_id: props.draft?.provider_id,
replying_to_id: props.replyingTo()?.db_id,
subject: form().subject(),
@@ -335,10 +343,34 @@ export function BaseInput(props: {
provider_thread_id: currentThread?.provider_id,
thread_db_id: currentThread?.db_id,
});
+
if (draftResponse) {
+ // If the email draft saved successfully, we want to upload the
+ // attachments as well. We should grab only the attachments that
+ // haven't been uploaded yet
+ const attachments = form()
+ .attachments.list()
+ .filter((a) => a.type === 'local' && !a.attachmentID) as Extract<
+ DraftFormAttachment,
+ { type: 'local' }
+ >[];
+
+ const uploaded = await uploadAttachmentMutation.mutateAsync({
+ draftID: draftResponse,
+ attachments: attachments.map((a) => a.file),
+ });
+
+ // Assign the attachment ids to attachments for later use
+ for (const attachment of uploaded.attachments) {
+ form().attachments.assignAttachmentID(
+ attachment.file,
+ attachment.attachmentID
+ );
+ }
+
setSavedDraftId(draftResponse);
+ refetchThreadMessages();
}
- refetchThreadMessages();
}
function scheduleDraftSave() {
@@ -359,28 +391,6 @@ export function BaseInput(props: {
untrack(scheduleDraftSave);
};
- function onAttach(items: Item[]) {
- const documentMentionItems = items.map((item) => ({
- documentId: item.id,
- documentName: item.name,
- blockName:
- item.type === 'document' ? (item.fileType as FileType) : item.type,
- }));
- appendItemsAsMacroMentions(editor(), documentMentionItems);
- items.forEach((item) => {
- makeAttachmentPublic(item.id);
- });
- scheduleDraftSave();
- }
-
- function onAttachDocuments(items: DocumentMentionInfo[]) {
- appendItemsAsMacroMentions(editor(), items);
- items.forEach((item) => {
- makeAttachmentPublic(item.documentId);
- });
- scheduleDraftSave();
- }
-
// Handles clicks outside of the expanded recipients area
const expandedPointerDownHandler = (e: PointerEvent) => {
if (showExpandedRecipients()) {
@@ -412,7 +422,7 @@ export function BaseInput(props: {
let composeContainerRef: HTMLDivElement | undefined;
const sendEmail = async (markDone = false) => {
- if (sendMutation.isPending || isPendingUpload()) return;
+ if (sendMutation.isPending || uploadAttachmentMutation.isPending) return;
const to = form().recipients.to.map(convertEmailRecipientToContactInfo);
const cc = form().recipients.cc.map(convertEmailRecipientToContactInfo);
@@ -483,8 +493,11 @@ export function BaseInput(props: {
const processedMacroBody = prepareMacroBody(bodyMacro());
+ const currentDraftID = savedDraftId();
+
sendMutation.mutate({
message: {
+ db_id: currentDraftID,
bcc,
body_html: prepared.bodyHtml,
body_macro: processedMacroBody,
@@ -635,20 +648,60 @@ export function BaseInput(props: {
}
});
- const ReplyIcon = createMemo(() => {
- let Icon =
- effectiveReplyType() === 'reply'
- ? Reply
- : effectiveReplyType() === 'reply-all'
- ? ReplyAll
- : Forward;
+ const handleAddAttachments = (files: File[]) => {
+ const currentAttachments = form().attachments.list();
- return (
- <Button showChevron>
- <Icon class="h-7 p-1" />
- </Button>
+ const attachmentsToAddByteSize = files.reduce((sum, f) => sum + f.size, 0);
+
+ if (attachmentsToAddByteSize >= MAX_ATTACHMENTS_BYTES_SIZE) {
+ toast.failure(`${plural('Attachment', files.length)} exceed 18MB`);
+ return;
+ }
+
+ const currentAttachmentsByteSize = currentAttachments.reduce(
+ (sum, a) => sum + (a.type === 'local' ? a.file.size : a.fileSize),
+ 0
);
- });
+
+ if (
+ currentAttachmentsByteSize + attachmentsToAddByteSize >=
+ MAX_ATTACHMENTS_BYTES_SIZE
+ ) {
+ toast.failure(
+ "Can't add more attachments",
+ 'Total attachments exceed 18MB limit'
+ );
+ return;
+ }
+
+ for (const file of files) {
+ form().attachments.add({
+ type: 'local',
+ file,
+ });
+ }
+
+ scheduleDraftSave();
+ };
+
+ const removeAttachmentMutation = useRemoveDraftAttachmentMutation();
+
+ const handleRemoveAttachment = (attachment: DraftFormAttachment) => {
+ if (attachment.type === 'local') {
+ form().attachments.removeByFile(attachment.file);
+ } else {
+ form().attachments.removeByID(attachment.attachmentID);
+ }
+
+ const currentDraftID = savedDraftId();
+
+ if (!currentDraftID || !attachment.attachmentID) return;
+
+ removeAttachmentMutation.mutate({
+ draftID: currentDraftID,
+ attachmentID: attachment.attachmentID,
+ });
+ };
return (
<div
@@ -662,7 +715,22 @@ export function BaseInput(props: {
<div class="flex items-start gap-2 p-2">
<DropdownMenu>
<DropdownMenu.Trigger>
- <div class="px-1">{ReplyIcon()}</div>
+ <div class="px-1">
+ <Button showChevron>
+ <Switch>
+ <Match when={effectiveReplyType() === 'reply'}>
+ <Reply class="h-7 p-1" />
+ </Match>
+
+ <Match when={effectiveReplyType() === 'reply-all'}>
+ <ReplyAll class="h-7 p-1" />
+ </Match>
+ <Match when={effectiveReplyType() === 'forward'}>
+ <Forward class="h-7 p-1" />
+ </Match>
+ </Switch>
+ </Button>
+ </div>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenuContent>
@@ -841,8 +909,7 @@ export function BaseInput(props: {
/>
</Show>
<div
- class="max-h-80 overflow-y-scroll w-full flex flex-col cursor-text placeholder:text-ink-placeholder placeholder:opacity-50 px-3"
- ref={bodyDiv}
+ class="max-h-80 overflow-y-scroll w-full flex flex-col placeholder:text-ink-placeholder placeholder:opacity-50 px-3"
onclick={() => {
editor()?.focus();
}}
@@ -883,7 +950,7 @@ export function BaseInput(props: {
setEditor(editor);
form().setCapturedEditor(editor);
}}
- class={`text-sm break-words text-ink ${isDragging() && 'blur'}`}
+ class={`cursor-text text-sm break-words text-ink ${isDragging() && 'blur'}`}
editable={() => !sendMutation.isPending}
initialValue={props.preloadedBody}
initialHtml={props.preloadedHtml}
@@ -921,27 +988,54 @@ export function BaseInput(props: {
);
}}
/>
+ <div class="flex gap-1 flex-wrap w-full py-2">
+ <For each={form().attachments.list()}>
+ {(attachment) => (
+ <Switch>
+ <Match when={attachment.type === 'local' && attachment}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment().file.name,
+ mimeType: attachment().file.type,
+ }}
+ removable
+ onRemove={() => handleRemoveAttachment(attachment())}
+ />
+ )}
+ </Match>
+ <Match when={attachment.type === 'remote' && attachment}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment().fileName,
+ mimeType: attachment().contentType,
+ }}
+ removable
+ onRemove={() => handleRemoveAttachment(attachment())}
+ />
+ )}
+ </Match>
+ </Switch>
+ )}
+ </For>
+ </div>
</div>
<div class="flex flex-row w-full h-8 justify-between items-center py-2 px-2 mb-2 space-x-2 allow-css-brackets">
<div class="flex flex-row items-center gap-2">
- <div class="relative" ref={attachButtonRef}>
+ <div class="relative">
<Button
- onclick={() => setAttachMenuOpen(true)}
+ ref={(el) =>
+ fileSelector(el, () => ({
+ multiple: true,
+ onSelect: handleAddAttachments,
+ }))
+ }
tooltip="Attach"
- class="aspect-square *:h-5 p-1"
+ class="aspect-square p-1"
>
- <Plus />
+ <Plus class="h-5" />
</Button>
-
- <AttachMenu
- open={attachMenuOpen()}
- close={() => setAttachMenuOpen(false)}
- anchorRef={attachButtonRef}
- containerRef={bodyDiv}
- onAttach={onAttach}
- onAttachDocuments={onAttachDocuments}
- setIsPending={setIsPendingUpload}
- />
</div>
<Button
@@ -1002,12 +1096,14 @@ export function BaseInput(props: {
</div>
<Button
- disabled={isPendingUpload() || sendMutation.isPending}
+ disabled={
+ uploadAttachmentMutation.isPending || sendMutation.isPending
+ }
onClick={() => sendEmail()}
- class="text-ink-muted hover:scale-115 transition ease-in-out flex-col items-center rounded-full p-[0.25lh] hover:bg-transparent"
+ class="text-ink-muted hover:scale-115 transition ease-in-out flex-col items-center rounded-full p-[0.25lh] hover:bg-transparent disabled:opacity-30"
>
<Show
- when={!isPendingUpload() && !sendMutation.isPending}
+ when={!sendMutation.isPending}
fallback={<Spinner class="size-6 animate-spin cursor-disabled" />}
>
<div class="group hover:bg-accent transition ease-in-out size-6 border border-accent rounded-full flex items-center justify-center p-0">
diff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsx
index d886d0f442..1291094d76 100644
--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx
+++ b/js/app/packages/block-email/component/ComposeEmailInput.tsx
@@ -4,6 +4,7 @@ import { MacroSignatureButton } from '@block-email/component/MacroSignatureButto
import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';
import { useHasPaidAccess } from '@core/auth';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
+import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';
import {
@@ -13,6 +14,7 @@ import {
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { handleFileFolderDrop } from '@core/util/upload';
import TextAa from '@icon/regular/text-aa.svg';
+import XIcon from '@icon/regular/x.svg';
import {
$appendWatermarkNodeToLast,
type DocumentMentionInfo,
@@ -69,7 +71,6 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
const [isPendingUpload, setIsPendingUpload] = createSignal<boolean>(false);
const [showFormatRibbon, setShowFormatRibbon] = createSignal<boolean>(false);
- const [attachMenuOpen, setAttachMenuOpen] = createSignal(false);
const [content, setContent] = createSignal('');
@@ -159,6 +160,36 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
attachComposeHotkeys(container);
});
+ const onAddFilesAndDirs = (
+ files: FileSystemFileEntry[],
+ directories: FileSystemDirectoryEntry[],
+ dropEvent?: DragEvent
+ ) => {
+ const editor_ = editor();
+ if (!editor_) return;
+
+ const getPositionCallback = dropEvent
+ ? () => getDragDropPosition(editor_, dropEvent, true)
+ : undefined;
+
+ handleFileFolderDrop(
+ files,
+ directories,
+ createFilesReadyHandler(
+ editor_,
+ undefined,
+ undefined,
+ getPositionCallback,
+ (uploadedItemIds) => {
+ uploadedItemIds.forEach((itemId) => {
+ makeAttachmentPublic(itemId);
+ });
+ },
+ { width: 542, height: 542 }
+ )
+ );
+ };
+
registerHotkey({
hotkey: 'cmd+enter',
scopeId: composeHotkeyScope,
@@ -200,28 +231,7 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
use:fileFolderDrop={{
onDragStart: () => setIsDragging(true),
onDragEnd: () => setIsDragging(false),
- onDrop: (fileEntries, folderEntries, e) => {
- const editor_ = editor();
- if (!editor_ || !e) return;
- handleFileFolderDrop(
- fileEntries,
- folderEntries,
- createFilesReadyHandler(
- editor_,
- undefined,
- undefined,
- () => getDragDropPosition(editor_, e, true),
- (uploadedItemIds) => {
- setIsDragging(false);
- uploadedItemIds.forEach((itemId) => {
- makeAttachmentPublic(itemId);
- });
- // TODO: schedule draft save, when implemented
- },
- { width: 542, height: 542 }
- )
- );
- },
+ onDrop: onAddFilesAndDirs,
}}
>
<div class={`${!isDragging() && 'hidden'} absolute inset-0`}>
@@ -244,44 +254,34 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
focusSibling('next');
}}
portalScope="local"
- onPasteFilesAndDirs={(files, directories) => {
- const editor_ = editor();
- if (!editor_) return;
- handleFileFolderDrop(
- files,
- directories,
- createFilesReadyHandler(
- editor_,
- undefined,
- undefined,
- undefined,
- (uploadedItemIds) => {
- uploadedItemIds.forEach((itemId) => {
- makeAttachmentPublic(itemId);
- });
- },
- { width: 542, height: 542 }
- )
- );
- }}
+ onPasteFilesAndDirs={onAddFilesAndDirs}
/>
</div>
+ <div class="flex flex-wrap items-center gap-2">
+ <DeprecatedTextButton
+ class="w-fit"
+ icon={PaperclipIcon}
+ secondaryIcon={XIcon}
+ secondaryTooltip={{ label: 'Remove attachment' }}
+ onOptionClick={() => {}}
+ theme="base"
+ >
+ Test attachment.pdf
+ </DeprecatedTextButton>
+ </div>
</div>
<div class="flex flex-row w-full h-8 justify-between items-center space-x-2 allow-css-brackets mt-2">
<div class="flex flex-row items-center gap-2">
<div class="relative" ref={attachButtonRef}>
- <DeprecatedIconButton
- theme="base"
- icon={PaperclipIcon}
- tooltip={{ label: 'Attach' }}
- disabled={props.disabled}
- onClick={() => setAttachMenuOpen(true)}
- />
<AttachMenu
- open={attachMenuOpen()}
- close={() => setAttachMenuOpen(false)}
- anchorRef={attachButtonRef}
- containerRef={bodyDiv}
+ trigger={
+ <DeprecatedIconButton
+ theme="base"
+ icon={PaperclipIcon}
+ tooltip={{ label: 'Attach' }}
+ disabled={props.disabled}
+ />
+ }
onAttach={onAttach}
onAttachDocuments={onAttachDocuments}
setIsPending={setIsPendingUpload}
diff --git a/js/app/packages/block-email/component/MessageContainer.tsx b/js/app/packages/block-email/component/MessageContainer.tsx
index 7ad6dfa59d..e8d76d9a79 100644
--- a/js/app/packages/block-email/component/MessageContainer.tsx
+++ b/js/app/packages/block-email/component/MessageContainer.tsx
@@ -307,8 +307,13 @@ export function MessageContainer(props: MessageContainerProps) {
<For each={otherAttachments()}>
{(attachment) => (
<EmailAttachmentPill
- attachment={attachment}
- onClick={onClickAttachment}
+ attachment={{
+ fileName: attachment.filename ?? '',
+ mimeType: attachment.mime_type ?? undefined,
+ }}
+ onClick={(fileType) =>
+ onClickAttachment(attachment, fileType)
+ }
/>
)}
</For>
diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.ts
index 001ee0771a..920753444a 100644
--- a/js/app/packages/block-email/component/createEmailFormState.ts
+++ b/js/app/packages/block-email/component/createEmailFormState.ts
@@ -19,6 +19,21 @@ export type EmailFormRecipients = {
bcc: EmailRecipient[];
};
+export type DraftFormAttachment =
+ | {
+ type: 'local';
+ file: File;
+ attachmentID?: string;
+ }
+ | {
+ type: 'remote';
+ url: string;
+ fileName: string;
+ contentType: string;
+ attachmentID: string;
+ fileSize: number;
+ };
+
/**
* Creates a state object for the email form.
* @param key - The db_id of the email being replied to.
@@ -61,6 +76,19 @@ export function createEmailFormState(key: string) {
const [shouldFocusInput, setShouldFocusInput] = createSignal(false);
+ // TODO: Replace this signal with a memo deriving the attachments from the draft data
+ // and a temporary queue to track attachments to be uploaded on draft save
+ const [attachments, setAttachments] = createSignal<DraftFormAttachment[]>(
+ draft?.attachments_draft.map((a) => ({
+ type: 'remote',
+ attachmentID: a.id,
+ contentType: a.content_type,
+ fileName: a.file_name,
+ url: a.s3_key,
+ fileSize: a.size,
+ })) ?? []
+ );
+
const initialReplyType: ReplyType | undefined = replyingTo
? (replyingTo.to.length ?? 0) + (replyingTo.cc.length ?? 0) > 1
? 'reply-all'
@@ -183,6 +211,8 @@ export function createEmailFormState(key: string) {
setSubjectInner(initialSubject);
setShouldFocusInput(false);
+ setAttachments([]);
+
// Mark as dirty to propagate change
callDirty();
};
@@ -211,6 +241,31 @@ export function createEmailFormState(key: string) {
setCapturedEditor: (editor: LexicalEditor) => {
setCapturedEditor(editor);
},
+ attachments: {
+ list: attachments,
+ add: (attachment: DraftFormAttachment) => {
+ setAttachments((p) => [...p, attachment]);
+ },
+ assignAttachmentID: (file: File, attachmentID: string) => {
+ setAttachments((p) =>
+ p.map((a) =>
+ a.type === 'local' && a.file === file ? { ...a, attachmentID } : a
+ )
+ );
+ },
+ removeByFile: (file: File) => {
+ setAttachments((p) =>
+ p.filter((a) => a.type !== 'local' || a.file !== file)
+ );
+ },
+ removeByID: (attachmentID: string) => {
+ setAttachments((p) =>
+ p.filter(
+ (a) => a.type !== 'remote' || a.attachmentID !== attachmentID
+ )
+ );
+ },
+ },
};
return value;
diff --git a/js/app/packages/core/util/string.ts b/js/app/packages/core/util/string.ts
index ff97c52396..bcd861edba 100644
--- a/js/app/packages/core/util/string.ts
+++ b/js/app/packages/core/util/string.ts
@@ -31,3 +31,14 @@ export function bufToString(buf: ArrayBuffer) {
if (!decoder) decoder = new TextDecoder();
return decoder.decode(buf);
}
+
+/**
+ * Pluralize a string if the `length` is great than 1
+ */
+export function plural(singular: string, length: number, suffix = 's') {
+ if (!singular.length) return singular;
+
+ if (length === 1) return singular;
+
+ return `${singular}${suffix}`;
+}
diff --git a/js/app/packages/queries/email/attachment.ts b/js/app/packages/queries/email/attachment.ts
new file mode 100644
index 0000000000..f82a524c42
--- /dev/null
+++ b/js/app/packages/queries/email/attachment.ts
@@ -0,0 +1,134 @@
+import { toast } from '@core/component/Toast/Toast';
+import { contentHash } from '@core/util/hash';
+import { isErr, throwOnErr, toHybridError } from '@core/util/maybeResult';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import { emailClient } from '@service-email/client';
+import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';
+import { useMutation } from '@tanstack/solid-query';
+
+type UploadDraftAttachmentsParams = {
+ draftID: string;
+ attachments: File[];
+};
+
+type UploadDraftAttachmentsReturn = {
+ attachments: { file: File; attachmentID: string }[];
+};
+
+class UploadDraftAttachmentError extends Error {
+ constructor(
+ message: string,
+ opts: { cause?: unknown },
+ public context: { attachmentID: string; file: File }
+ ) {
+ super(message, { cause: opts.cause });
+ }
+}
+
+export const useUploadDraftAttachmentsMutation = (
+ callbacks?: MutationCallbacks<
+ UploadDraftAttachmentsReturn,
+ Error,
+ UploadDraftAttachmentsParams
+ >
+) => {
+ return useMutation(() => ({
+ mutationFn: async (params: UploadDraftAttachmentsParams) => {
+ const uploadedAttachments = [];
+
+ for (const attachment of params.attachments) {
+ const arrayBuffer = await attachment.arrayBuffer();
+ const sha = await contentHash(arrayBuffer);
+
+ const result = await throwOnErr(
+ async () =>
+ await emailClient.addDraftAttachment({
+ draftID: params.draftID,
+ attachment: {
+ file_name: attachment.name,
+ size: attachment.size,
+ sha,
+ },
+ })
+ );
+
+ uploadedAttachments.push({
+ file: attachment,
+ attachmentID: result.attachment_id,
+ });
+
+ const uploadedResponse = await uploadToPresignedUrl({
+ presignedUrl: result.upload_url,
+ sha,
+ buffer: arrayBuffer,
+ type: result.content_type,
+ });
+
+ if (isErr(uploadedResponse)) {
+ const err = toHybridError(uploadedResponse);
+ throw new UploadDraftAttachmentError(
+ err.message,
+ { cause: err.code },
+ {
+ attachmentID: result.attachment_id,
+ file: attachment,
+ }
+ );
+ }
+ }
+
+ return { attachments: uploadedAttachments };
+ },
+ ...withCallbacks<
+ UploadDraftAttachmentsReturn,
+ Error,
+ UploadDraftAttachmentsParams
+ >(
+ {
+ async onError(error, variables) {
+ if (error instanceof UploadDraftAttachmentError) {
+ try {
+ await emailClient.removeDraftAttachment({
+ draftID: variables.draftID,
+ attachmentID: error.context.attachmentID,
+ });
+ } catch {
+ console.error('Unable to remove draft attachment after failure');
+ }
+ }
+ toast.failure('Failed to save attachments');
+ },
+ },
+ callbacks
+ ),
+ }));
+};
+
+type RemoveDraftAttachmentParams = {
+ draftID: string;
+ attachmentID: string;
+};
+
+export const useRemoveDraftAttachmentMutation = (
+ callbacks?: MutationCallbacks<void, Error, RemoveDraftAttachmentParams>
+) => {
+ return useMutation(() => ({
+ mutationFn: async (params: RemoveDraftAttachmentParams) => {
+ await throwOnErr(
+ async () =>
+ await emailClient.removeDraftAttachment({
+ draftID: params.draftID,
+ attachmentID: params.attachmentID,
+ })
+ );
+ },
+ ...withCallbacks<void, Error, RemoveDraftAttachmentParams>(
+ {
+ onError() {
+ toast.failure('Failed to remove draft attachment');
+ },
+ },
+ callbacks
+ ),
+ }));
+};
diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.ts
index 8f526f06d2..a6d5a02e83 100644
--- a/js/app/packages/service-clients/service-email/client.ts
+++ b/js/app/packages/service-clients/service-email/client.ts
@@ -11,6 +11,8 @@ import {
} from '@core/util/maybeResult';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type {
+ AddDraftAttachmentRequest,
+ AddDraftAttachmentResponse,
ApiPaginatedThreadCursor,
CreateDraftRequest,
CreateDraftResponse,
@@ -204,6 +206,32 @@ export const emailClient = {
(result) => result
);
},
+ async addDraftAttachment(args: {
+ draftID: string;
+ attachment: AddDraftAttachmentRequest;
+ }) {
+ return mapOk(
+ await emailFetch<AddDraftAttachmentResponse>(
+ `/email/drafts/${args.draftID}/attachments`,
+ {
+ method: 'POST',
+ body: JSON.stringify(args.attachment),
+ }
+ ),
+ (result) => result
+ );
+ },
+ async removeDraftAttachment(args: { draftID: string; attachmentID: string }) {
+ return mapOk(
+ await emailFetch<EmptyResponse>(
+ `/email/drafts/${args.draftID}/attachments/${args.attachmentID}`,
+ {
+ method: 'DELETE',
+ }
+ ),
+ (result) => result
+ );
+ },
async markThreadAsSeen(args: { thread_id: string }) {
const { thread_id } = args;
return mapOk(